text:
@extends('_layouts.base')

@section('head')

    <link href="/css/login.css" rel="stylesheet">
@endsection

@section('body')

            Dienstplan
            Online

                @if (session('status'))

                        {{ session('status') }}

                @endif
                <form id="forgot_password" method="POST" action="{{ route('password.request') }}">
                    {{ csrf_field() }}

                    <input type="hidden" name="token" value="{{ $token }}">

                        Passwort neu setzen

has('email') ? ' has-error' : '' }}">

                            email

                            <input type="email" class="form-control" name="email" placeholder="Email" value="{{ $email or old('email') }}" required autofocus>

                            @if ($errors->has('email'))

                                        {{ $errors->first('email') }}

                            @endif

has('password') ? ' has-error' : '' }}">

                            lock

                            <input type="password" id="password" class="form-control" name="password" minlength="6" placeholder="Passwort" required>
                            @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                            @endif

                            lock

                            <input type="password" id="password-confirm" class="form-control" name="password_confirmation" minlength="6" placeholder="Passwort wiederholen" required>
                            @if ($errors->has('password_confirmation'))

                                    {{ $errors->first('password_confirmation') }}

                            @endif

                    <button class="btn btn-block btn-lg btn-nicered waves-effect" type="submit">Passwort setzen</button>
                </form>

        Impressum |
        Datenschutz

@endsection


text:
package org.thingsboard.server.common.data.query;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ComparisonTsValue {

    private TsValue current;
    private TsValue previous;
}

redpajama_set_name: RedPajamaGithub


text:
#include "behavior.h"
#include <vector>
#include <string>
#include <math.h>
#include <r-tech1/input/input-map.h>
#include <r-tech1/input/input-source.h>
#include <r-tech1/debug.h>
#include <r-tech1/funcs.h>
// #include "command.h"
#include "constraint.h"
#include "random.h"
#include "character.h"
#include "stage.h"

using namespace std;

namespace Mugen{

namespace PaintownUtil = ::Util;

Behavior::Behavior(){
}

Behavior::~Behavior(){
}

void Behavior::hit(Object * enemy){
}

DummyBehavior::DummyBehavior(){
}

void DummyBehavior::flip(){
}

vector<string> DummyBehavior::currentCommands(const Mugen::Stage & stage, Character * owner, const std::vector<Command2*> & commands, bool reversed){
    vector<string> out;
    return out;
}

DummyBehavior::~DummyBehavior(){
}

static void debugit(const string & what, const InputMap<Mugen::Keys> & right){
    Global::debug(0) << "Debug input map " << what << std::endl;
    const std::map<Keyboard::KeyType, PaintownUtil::ReferenceCount<KeyState<Mugen::Keys> > > & keys = right.getKeyStates();
    for (std::map<Keyboard::KeyType, PaintownUtil::ReferenceCount<KeyState<Mugen::Keys> > >::const_iterator it = keys.begin(); it != keys.end(); it++){
        Keyboard::KeyType key = it->first;
        const PaintownUtil::ReferenceCount<KeyState<Mugen::Keys> > & state = it->second;
        if (state != NULL){
            Global::debug(0) << "Mapped " << key << " to " << state->out << std::endl;
        }
    }
}

HumanBehavior::HumanBehavior(const InputMap<Mugen::Keys> & right, const InputMap<Mugen::Keys> & left):
right(right),
left(left){
}

InputMap<Keys> & HumanBehavior::getInput(bool facingRight){
    if (facingRight){
        return right;
    }
    return left;
}

/* turned around so we have to swap forward/backward */
void HumanBehavior::flip(){
    bool forward = input.pressed.forward;
    input.pressed.forward = input.pressed.back;
    input.pressed.back = forward;
}

Mugen::Input HumanBehavior::updateInput(InputMap<Keys> & keys, Mugen::Input old){
    /* Reset released events */
    old.released = Input::Key();

    vector<InputMap<Keys>::InputEvent> eventsHold = InputManager::getEvents(keys, InputSource(true));
    for (vector<InputMap<Keys>::InputEvent>::iterator it = eventsHold.begin(); it != eventsHold.end(); it++){
        InputMap<Keys>::InputEvent event = *it;

        /* Release event if the key was pressed but now its not */
#define DoKey(Name, accessor) case Mugen::Name: \
                                old.released.accessor = old.pressed.accessor && !event.enabled; \
                                old.pressed.accessor = event.enabled; break;

        switch (event.out){
            DoKey(Right, forward)
            DoKey(Left, back)
            DoKey(Up, up)
            DoKey(Down, down)
            DoKey(A, a)
            DoKey(B, b)
            DoKey(C, c)
            DoKey(X, x)
            DoKey(Y, y)
            DoKey(Z, z)
            DoKey(Start, start)
            default: break;
            /* the keys map already sets up left/right to be forward/backward */

            /*
            case Mugen::Right: {
                old.released.forward = old.pressed.forward && !event.enabled;
                old.pressed.forward = event.enabled;
                break;
            }
            case Mugen::Left: old.pressed.back = event.enabled; break;
            case Mugen::Up: old.pressed.up = event.enabled; break;
            case Mugen::Down: old.pressed.down = event.enabled; break;
            case Mugen::A: old.pressed.a = event.enabled; break;
            case Mugen::B: old.pressed.b = event.enabled; break;
            case Mugen::C: old.pressed.c = event.enabled; break;
            case Mugen::X: old.pressed.x = event.enabled; break;
            case Mugen::Y: old.pressed.y = event.enabled; break;
            case Mugen::Z: old.pressed.z = event.enabled; break;
            case Mugen::Start: old.pressed.start = event.enabled; break;
            default: break;
            */
        }
    }

#undef DoKey

    return old;
}

vector<string> HumanBehavior::currentCommands(const Mugen::Stage & stage, Character * owner, const vector<Command2*> & commands, bool reversed){
    vector<string> out;

    // InputMap<Mugen::Keys>::Output output = InputManager::getMap(getInput(reversed));
    input = updateInput(getInput(reversed), input);

    for (vector<Command2*>::const_iterator it = commands.begin(); it != commands.end(); it++){
        Command2 * command = *it;
        if (command->handle(input, stage.getTicks())){
            Global::debug(1) << "command: " << command->getName() << endl;
            out.push_back(command->getName());
        }
    }

    return out;
}

const Mugen::Input & HumanBehavior::getInput() const {
    return input;
}

HumanBehavior::~HumanBehavior(){
}

void HumanBehavior::updateKeys(const InputMap<Keys> & right, const InputMap<Keys> & left){
    this->right = right;
    this->left = left;
}

RandomAIBehavior::RandomAIBehavior(){
}

void RandomAIBehavior::flip(){
}

static string randomCommand(const vector<Command2*> & commands){
    if (commands.size() == 0){
        return "";
    }

    int choice = Mugen::random(commands.size());
    return commands[choice]->getName();
}

vector<string> RandomAIBehavior::currentCommands(const Mugen::Stage & stage, Character * owner, const vector<Command2*> & commands, bool reversed){
    vector<string> out;
    if (Mugen::random(100) > 90){
        out.push_back(randomCommand(commands));
    }
    return out;
}

RandomAIBehavior::~RandomAIBehavior(){
}

LearningAIBehavior::LearningAIBehavior(int difficulty):
direction(Forward),
difficulty(difficulty),
dontMove(0){
    /* make walking more likely to begin with */
    /*
    moves["holdfwd"].points -= 10;
    moves["holdfwd"].minimumDistance = 999999;
    moves["holdfwd"].maximumDistance = 0;
    moves["holdback"].points -= 10;
    moves["holdback"].minimumDistance = 999999;
    moves["holdback"].maximumDistance = 0;
    */

    /* this is just to give the AI a starting move that does nothing, this is
     * basically a noop. eventualy the AI will learn other moves to do.
     *
     * the name is something that the user can't write for a command (hopefully)
     */
    moves["not-possible+#$*(@#$"].points = 5;
}

/* the command with the most points will be chosen. points are tallied by
 * adding all the quantities associated with that move thus far. right now they are:
 *  - starting points is the number of times the move hit successfully
 *  - add points if the move is within range, where range is determined by the last
 *     successful hit for that command
 *  - add a random number of points to shake things up
 *  - subtract points if the move is out of range
 *  - subtract points based on the number of times the move has been tried
 *  - subtract points if the move has been done recently
 */
string LearningAIBehavior::selectBestCommand(int distance, const vector<Command2*> & commands){
    Move * currentMove = NULL;
    string what = "";
    double points = 0;

    for (vector<Command2*>::const_iterator it = commands.begin(); it != commands.end(); it++){
        string name = (*it)->getName();

        /* Skip movement keys */
        if (name == "holdfwd" ||
            name == "holdback" ||
            name == "holddown" ||
            name == "holdup"){
            continue;
        }

        Move & move = moves[name];
        double morePoints = move.points + Mugen::random(10);
        if (move.minimumDistance != -1){
            if (distance < move.maximumDistance + 10 && distance > move.minimumDistance - 10){
                morePoints += 2;
            } else if (distance > move.maximumDistance + 10){
                morePoints -= 3;
            }
        }

        morePoints -= log((double) move.attempts * 3);
        morePoints -= move.consecutive * 2;

        if (currentMove == NULL){
            currentMove = &move;
            what = name;
            points = morePoints;
        } else if (morePoints > points){
            currentMove = &move;
            what = name;
            points = morePoints;
        }
    }

    for (map<string, Move>::iterator it = moves.begin(); it != moves.end(); it++){
        Move & move = (*it).second;
        if (currentMove != &move){
            move.consecutive /= 2;
        }
    }

    currentMove->attempts += 1;
    currentMove->consecutive += 1;

    return what;
}

void LearningAIBehavior::flip(){
}

static LearningAIBehavior::Direction randomDirection(){
    int what = Mugen::random(100);
    if (what > 70){
        return LearningAIBehavior::Forward;
    } else if (what > 40){
        return LearningAIBehavior::Backward;
    } else if (what > 20){
        return LearningAIBehavior::Stopped;
    } else {
        return LearningAIBehavior::Crouch;
    }
}

vector<string> LearningAIBehavior::currentCommands(const Mugen::Stage & stage, Character * owner, const vector<Command2*> & commands, bool reversed){

    vector<string> out;

    /* maybe attack */
    if ((int) Mugen::random(200) < difficulty * 2){
        const Character * enemy = stage.getEnemy(owner);
        int xDistance = (int) fabs(owner->getX() - enemy->getX());
        string command = selectBestCommand(xDistance, commands);
        out.push_back(command);
        lastCommand = command;
        lastDistance = xDistance;
    } else {
        /* otherwise move around */
        dontMove += 1;
        if (direction == Forward){
            out.push_back("holdfwd");
        } else if (direction == Backward){
            out.push_back("holdback");
        } else if (direction == Crouch){
            out.push_back("holddown");
        } else if (direction == Stopped){
        }

        /* after keeping a direction for 40 ticks, maybe change directions */
        if (dontMove > 40 && Mugen::random(10) > 8){
            direction = randomDirection();
            dontMove = 0;
        }

        /* make the AI jump sometimes */
        if (Mugen::random(100) == 0){
            out.push_back("holdup");
        }
    }

    return out;
}

/* hit succeeded, reinforce learning behavior for that move */
void LearningAIBehavior::hit(Object * enemy){
    Move & move = moves[lastCommand];
    move.points += 1;
    if (move.points > 5){
        move.points = 5;
    }

    if (move.maximumDistance == -1 || lastDistance > move.maximumDistance){
        move.maximumDistance = lastDistance;
    }

    if (move.minimumDistance == -1 || lastDistance < move.minimumDistance){
        move.minimumDistance = lastDistance;
    }
}

LearningAIBehavior::~LearningAIBehavior(){
}

/* crummy regex parsing */
static vector<string> parseCommands(string stuff){
    vector<string> out;

    while (PaintownUtil::matchRegex(stuff, PaintownUtil::Regex("\\s*(\\w+)"))){
        string get;
        get = PaintownUtil::captureRegex(stuff, PaintownUtil::Regex("\\s*(\\w+)"),0);
        out.push_back(get);
        stuff = PaintownUtil::captureRegex(stuff, PaintownUtil::Regex("\\s*\\w+,?\\s*(.*)"), 0);
    }

    return out;
}

ScriptedBehavior::ScriptedBehavior(const Filesystem::AbsolutePath & path){
    if (!Storage::instance().exists(path)){
        ostringstream out;
        out << "Could not load script file '" << path.path() << "'";
        throw MugenException(out.str(), __FILE__, __LINE__);
    }

    ifstream file(path.path().c_str());
    while (file.good() && !file.eof()){

        char line[1024];
        file.getline(line, sizeof(line) - 1);
        line[sizeof(line) - 1] = '\0';
        string whole(line);

        if (PaintownUtil::matchRegex(whole, PaintownUtil::Regex("\\d+\\s*$"))){
            int ticks = atoi(PaintownUtil::captureRegex(whole, PaintownUtil::Regex("(\\d+)"), 0).c_str());
            actions.push_back(Action(ticks, vector<string>()));
        } else if (PaintownUtil::matchRegex(whole, PaintownUtil::Regex("\\d+\\s+"))){
            int ticks = atoi(PaintownUtil::captureRegex(whole, PaintownUtil::Regex("(\\d+)"), 0).c_str());
            string command = PaintownUtil::captureRegex(whole, PaintownUtil::Regex("\\d+\\s+(.*)"), 0);
            vector<string> commands = parseCommands(command);
            actions.push_back(Action(ticks, commands));
            // Global::debug(0) << "Added action " << PaintownUtil::join(commands, ", ") << " for " << ticks << std::endl;
            // Global::debug(1) << "Added no action for " << ticks << std::endl;
        } else {
            string command = PaintownUtil::captureRegex(whole, PaintownUtil::Regex("(\\w+)\\s*"), 0);
            vector<string> commands = parseCommands(command);
            if (commands.size() > 0){
                actions.push_back(Action(1, commands));
            }
            // Global::debug(1) << "Added action " << command << " for 1" << std::endl;
        }
    }

    currentAction = actions.begin();
}

std::vector<std::string> ScriptedBehavior::currentCommands(const Stage & stage, Character * owner, const std::vector<Command2*> & commands, bool reversed){
    vector<string> out;

    if (currentAction != actions.end()){
        Action & action = *currentAction;

        action.ticks -= 1;
        out = action.commands;

        if (action.ticks == 0){
            currentAction++;

            // Global::debug(0) << "Next action " << PaintownUtil::join(action.commands, ", ") << std::endl;
        }
    }

    return out;
}

void ScriptedBehavior::flip(){
}

ScriptedBehavior::~ScriptedBehavior(){
}

}


text:
HiiGUID - Time based byte GUID
===============================

Creates a GUID based on a float so you can sort it by the GUID and maintain its order

* packed: String representing the packed struct value of the GUID.
* base36: String representing the base36 encoded value of the GUID.
* float: Float representing the non-fractional portion of the GUID's initial timestamp.

Note: Timestamps are to the nearest second.

Installation and Setup
----------------------

Installation is as easy as installing with easy_install or pip.

    >>> from hiiguid import HiiGUID
    >>> timestamp = 1315490012.0
    >>> guid = HiiGUID(timestamp).packed
    >>> unpacked_timestamp = HiiGUID(guid).timestamp
    >>> print (guid, len(guid), timestamp, unpacked_timestamp)
    ('Nh\xc8\xdc\xac\xb6\x19g\x19\xe8O)\x9a\xd9\xe9thb\xcbu', 20, 1315490012.0, 1315490012.0)


text:
"use strict";

var request = require("request");

function forwardClientRequestToApi(apiHost){
    return function(req,res){
        var options = {
            url: apiHost + req.url
        };

        req.pipe(forwardClientRequestToApi.request(options)).pipe(res);
    };
}

forwardClientRequestToApi.request = request;

module.exports = forwardClientRequestToApi;

// ----------------------------------------------------------------------------
// Copyright (C) 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------- END-OF-FILE ----------------------------------


text:
package opendsd_test

import (
	"bytes"
	"log"
	"testing"

	"github.com/scoutred/opendsd"
)

var applicationTestData = `
<?xml version="1.0" encoding="UTF-8"?>
<extract_results>
  <!--City of San Diego Development Services Department-->
  <!--Please see dtd for extract explanation-->
  <metadata>
    <jurisdiction>City of San Diego</jurisdiction>
    <agency>Development Services Department</agency>
    <agency_address>APPLICATION_PARM</agency_address>
    <agency_website>APPLICATION_PARM</agency_website>
    <data_extract>
      <extract_system>PTSxml Report Id:  47</extract_system>
      <query>VWXML_WEEKLYPERMITSAPPLRECV</query>
      <extract_date>10/23/2016 21:23</extract_date>
      <start_date>10/17/2016</start_date>
      <end_date>10/23/2016</end_date>
      <report_title>Weekly_PermitsApplRecv</report_title>
      <request_id/>
    </data_extract>
  </metadata>
  <approvals>
    <approval approval_id="1795317">
      <approval_type>Map Waiver</approval_type>
      <approval_type_id>244</approval_type_id>
      <project_id>447621</project_id>
      <map_reference>XXXX-XX</map_reference>
      <latitude>32.746437</latitude>
      <longitude>-117.139728</longitude>
      <application_date>10/21/2016 11:05</application_date>
    </approval>
  </approvals>
</extract_results>
`

func TestDecodApplications(t *testing.T) {
	var err error

	buf := bytes.NewBufferString(applicationTestData)

	applications, err := opendsd.DecodeApplication(buf)
	if err != nil {
		t.Errorf("error parsing: %v", err)
	}

	log.Printf("%+v", applications)
}


text:
package com.skellix.editor.js;

import java.nio.ByteBuffer;

public interface ContextSearchCallback {

	public void onMatchFound(ByteBuffer buffer, int start, int end);

}


text:
package com.epam.dlab.dto.azure.edge;

import com.epam.dlab.dto.ResourceSysBaseDTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;

public class EdgeCreateAzure extends ResourceSysBaseDTO<EdgeCreateAzure> {
    @JsonProperty("azure_datalake_enable")
    private String azureDataLakeEnable;

    public EdgeCreateAzure withAzureDataLakeEnable(String azureDataLakeEnable) {
        this.azureDataLakeEnable = azureDataLakeEnable;
        return this;
    }

    public String getAzureDataLakeEnable() {
        return azureDataLakeEnable;
    }

    public void setAzureDataLakeEnable(String azureDataLakeEnable) {
        this.azureDataLakeEnable = azureDataLakeEnable;
    }

    @Override
    public MoreObjects.ToStringHelper toStringHelper(Object self) {
        return super.toStringHelper(this)
                .add("azureDataLakeEnable", azureDataLakeEnable);
    }

    @Override
    public String toString() {
        return toStringHelper(this).toString();
    }
}


text:
@extends('layouts.default')

@section('content')
{{ $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] }}

GET /config: shows the high/low values for front end sliders

GET /start: starts an experiment - returns default values for experiment to be run

POST /run/{id}: runs an experiment with posted data - returns the location of the results or errors and where they exist

GET /results/{id}: displays the results of the experiment indicated

@stop


text:
package cn.xishan.oftenporter.porter.core.base;

/**
 * Created by https://github.com/CLovinr on 2017/8/8.
 */
public interface DefaultReturnFactory {
    Object getVoidReturn(WObject wObject, Object finalPorterObject, Object handleObject, Object handleMethod);

    Object getNullReturn(WObject wObject, Object finalPorterObject, Object handleObject, Object handleMethod);
}


text:
import React, { Component } from 'react';

import { Link } from 'react-router';

import AppContainer from '../../container/appContainer';
import Section from '../../component/ui/section';

import __ from '../../lang';

export default class NewDevice extends Component {
  render() {
    return (
      <AppContainer title={__('NewDeviceTitle')}>

{__('NewDeviceSelectTypeDesc')}

              {/* Hard-coded device types... Hmm. */}

                  {__('DeviceTypePc')}

                  <Link to='/new/device/webRemote'>
                    {__('DeviceTypeWebRemote')}
                  </Link>

      </AppContainer>
    );
  }
}


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

<TITLE>
CommerceMessage (ATG Java API)
</TITLE>

<META NAME="keywords" CONTENT="atg.commerce.messaging.CommerceMessage interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.commerce.messaging

Interface CommerceMessage

All Superinterfaces:
java.io.Serializable

All Known Subinterfaces:
UpdateInventory

All Known Implementing Classes:
CommerceMessageImpl, UpdateInventoryImpl

public interface CommerceMessage
extends java.io.Serializable

 This is the base interface for all the messages used in this system. Messages are the
 primary method of communication between the disparate fulfillment systems that might take
 part in the fulfillment process.  Third party systems that will be sending messages into our
 fulfillment system need to implement this interface.

Field Summary

static java.lang.String
CLASS_VERSION

          Class version string

Method Summary

 java.lang.String
getId()

          This method returns the id of this message in an unspecified format.

 java.lang.String
getOriginalId()

          Get the original message id as it came from the orignal source described above.

 java.lang.String
getOriginalSource()

          This is the orignal source of data for this message.

 java.lang.String
getOriginalUserId()

          This method returns the id of the end user whose action initiated this request.

 java.lang.String
getParentSessionId()

          Returns the parent session id.

 java.lang.String
getSessionId()

          Returns the current session id associated with the request when
 this message is sent in the context of an HTTP request.

 java.lang.String
getSource()

          This method returns an arbitrary string that identifies the source of the the message.

 java.lang.String
getType()

          returns the type of the message.

 java.lang.String
getUserId()

          This method returns the id of the most recent end user who acted on this message, if there
 was one.

 void
setId(java.lang.String pId)

          Set the id of this message.

 void
setParentSessionId(java.lang.String pParentSessionId)

          Sets the parent session id.

 void
setSessionId(java.lang.String pSessionId)

 void
setSource(java.lang.String pSource)

          Set the source of this message.

 void
setUserId(java.lang.String pUserId)

          Set the user id.

Field Detail

CLASS_VERSION

public static final java.lang.String CLASS_VERSION

Class version string

See Also:
Constant Field Values

Method Detail

getSource

public java.lang.String getSource()

This method returns an arbitrary string that identifies the source of the the message. The
 source combined with the message id must uniquely identify a message. An example of a
 meaningfull source would be 'CSRUI@host.domain', this tells what software system issued
 the message and the host it was running on. A message with a null value for it's source is
 considered invalid. If the recipient of this message passes it on it must set the source
 to a string identifying itself and generate an Id that keeps this combination unique. This
 is particularly important when a message is fragmented. The user id should be either set
 to null or set to the id of the user that is associated with the action performed by the
 recipient.

setSource

public void setSource(java.lang.String pSource)

Set the source of this message.

getId

public java.lang.String getId()

This method returns the id of this message in an unspecified format. The combination of
 this id and the source of this messages must be unique. A message with a null value for
 it's id is considered invalid.

setId

public void setId(java.lang.String pId)

Set the id of this message.

getUserId

public java.lang.String getUserId()

This method returns the id of the most recent end user who acted on this message, if there
 was one.  This field can be null and the message will still be considered valid.

setUserId

public void setUserId(java.lang.String pUserId)

Set the user id.

getOriginalSource

public java.lang.String getOriginalSource()

This is the orignal source of data for this message. It is important to keep the original
 source and id so that later references to this request can be identified. For example, it
 is necessary to identify the original requester of a ModifyOrder message so it can be set
 in a ModifyOrderNotification message. Keep in mind that the combination of original source
 and original id may not be unique if the message has been fragmented. This field is not
 used to identify what message this message is a response to, but to identify what message
 this message is a fragment of or a routed copy of.

getOriginalId

public java.lang.String getOriginalId()

Get the original message id as it came from the orignal source described above.

getOriginalUserId

public java.lang.String getOriginalUserId()

This method returns the id of the end user whose action initiated this request. This field
 can be null and the message will still be considered valid.

getType

public java.lang.String getType()

returns the type of the message.

getSessionId

public java.lang.String getSessionId()

Returns the current session id associated with the request when
 this message is sent in the context of an HTTP request. This field
 can be null and the message will still be considered valid.

setSessionId

public void setSessionId(java.lang.String pSessionId)

getParentSessionId

public java.lang.String getParentSessionId()

Returns the parent session id.  This may be different than the request's
 current session id on app servers which use a separate session id for
 each web application. This field can be null and the message will still
  be considered valid.

setParentSessionId

public void setParentSessionId(java.lang.String pParentSessionId)

Sets the parent session id.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
game.gui.BottomMenuBar = game.gui.MenuBar.extend({
    init: function(){
        this.parent(5, 5, 545, 70);

        this._addMenuItems();
    },
    _addMenuItems: function(){
        this._addItem('inventory', 'Inventory', game.inventoryWindow);
        this._addItem('equipment', 'Equipment', game.equipmentWindow);
    },
    _addItem: function(id, title, closableWindow){
        var item = this.addMenuItem({title: title, image: 'data/img/gui/icon/'+id+'.png'}, function(){
            closableWindow.toggle();
        });

        closableWindow.visibilityChanged.addHandler(function(e){
            e.visible ? item.addClass('active') : item.removeClass('active');
        });

        return item;
    }
})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 41: 130 (1943)

#### Original name
Gymnopus tenuifolius Murrill

### Remarks
null


text:
package alexp.blog.model;

import org.hibernate.validator.constraints.NotBlank;

import javax.validation.constraints.Size;

public class PostEditDto {

    private Long Id = null;

    // haven't figured out how to specify messages for Size.List in the messages file
    @Size.List({
            @Size(min = 3, message = "Title too short"),
            @Size(max = 250, message = "Title too long")
    })
    @NotBlank
    private String title;

    @NotBlank
    @Size(min = 50)
    private String text;

    @NotBlank
    private String tags = "";

    public Long getId() {
        return Id;
    }

    public void setId(Long id) {
        Id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }
}


text:
gradle-is-gr8
=============

GDG-TC Presentation On Using Gradle. Directed for Android Dev but will cover the basics.


text:
from setuptools import setup

setup(name='genesisclient',
      version='0.0.8',
      description='Genesis (DeStatis et. al.) client for Python',
      author='Marian Steinbach',
      author_email='marian@sendung.de',
      url='https://github.com/marians/genesisclient',
      license="MIT",
      packages=['genesisclient'],
      install_requires=[
        'lxml',
        'suds-py3'],
      entry_points={
        'console_scripts': [
            'genesiscl = genesisclient:main'
        ]
      }
)


text:
namespace TFSAdvanced.Updater.Models.Builds
{
    public class RequestedFor
    {
        public string id { get; set; }

        public string displayName { get; set; }

        public string imageUrl { get; set; }
    }
}


text:
using Atomiv.Core.Application;

namespace Generator.Core.Application.Customers.Responses
{
    public class DeleteCustomerResponse : IResponse
    {
    }
}


text:
A dynamic data context driver for querying JSON data with LINQPad. See [here](http://ryandavis.io/a-json-data-context-driver-for-linqpad/) for an overview, and check the [releases](https://github.com/rdavisau/jsondatacontext-linqpad/releases) for binaries.

This driver allows you to select a set of JSON inputs from which a LINQPad data context will be generated for strongly typed access. A context can currently be built from any combination of:

- plain text inputs (for example, pasted in or typed by hand)
- individual file paths
- directories to search, with a filemask (e.g. \*.json, \*.\*) and the option for recursive enumeration
- GET calls to urls that return json, exposed either as properties on the context, or methods with parameters mapped to querystring components in the url

####Screenshots

![](http://ryandavis.io/content/images/2015/06/json_connection_dialog_updated.png)
![](http://ryandavis.io/content/images/2015/06/json_query-1.png)

####Planned Features:

* enhanced support for grabbing JSON from the world wide web (basic GET with headers is currently supported, support for POST planned)
* support for caching of deserialised data, as well as programmatic invalidation of cached data
* support for persisting new data to the context (for example, written to path in the context's search definitions), allowing you to build out your context as you go
* better support wrapped JSON
* fixes for JSON data that it chokes on
* better error handling and no modal error dialogs (please forgive me, gods of UX).

####Considerations:
#####Errors:

Errors encountered when processing individual sources will not typically prevent the construction of a full context; that is, 'bad' inputs will be ignored and the context is generated with 'good' ones. If the driver fails on inputs that you are able to share, please include them when [filing an issue](https://github.com/rdavisau/jsondatacontext-linqpad/issues).

####Contributing:

Very welcome - fork, branch, PR :star2:

####Attributions:
* JSON-to-CSharp provided by the [jsonclassgenerator project](http://jsonclassgenerator.codeplex.com/).
* Dropdown button from [Extended WPF Toolkit](http://wpftoolkit.codeplex.com/)
* JSON.NET


text:
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;

namespace EdiEngine.Standards.X12_004010.Maps
{
	public class M_805 : MapLoop
	{
		public M_805() : base(null)
		{
			Content.AddRange(new MapBaseEntity[] {
				new BCP() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new SPI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_CBS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_CB1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_REF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new PL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_HL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_PD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
			});
		}

		//1000
		public class L_N1 : MapLoop
		{
			public L_N1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
				});
			}
		}

		//2000
		public class L_CBS : MapLoop
		{
			public L_CBS(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new CBS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new JIL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3000
		public class L_CB1 : MapLoop
		{
			public L_CB1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new CB1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3100
		public class L_N1_1 : MapLoop
		{
			public L_N1_1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				});
			}
		}

		//4000
		public class L_REF : MapLoop
		{
			public L_REF(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//5000
		public class L_HL : MapLoop
		{
			public L_HL(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				});
			}
		}

		//6000
		public class L_PD : MapLoop
		{
			public L_PD(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
					new PDD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//6100
		public class L_N1_2 : MapLoop
		{
			public L_N1_2(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//7000
		public class L_LX : MapLoop
		{
			public L_LX(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 4 },
				});
			}
		}

	}
 }


text:
Set New Admin Password

The admin password must be changed after installation of Aggie. Please do so before continuing.

Remember that the password has to be at least 8 characters long.

By default there is no email address associated with your admin
    account. If you forget your password, you may be unable to recover your
    account. Please add an email under Settings > Users > admin.

  <form novalidate name="form" class="form-horizontal" ng-submit="newPwd(form)">
    <fieldset>

        Password
        <input type="password" ng-model="user.password" class="form-control" id="password" />

        Password Confirmation

          <input type="password" ng-model="user.passwordConfirmation" class="form-control"
                 id="password_confirmation" />

          <button type="submit" class="btn btn-primary" translate>Confirm</button>

    </fieldset>
  </form>


text:
module Streamlined::Helpers::BreadcrumbHelper
  include Streamlined::Breadcrumb
  DELIMITER = "<"
  attr_with_default(:streamlined_breadcrumb) {false}

  def render_breadcrumb
    html = Builder::XmlMarkup.new
    html.div(:id => "streamlined_breadcrumb") do
      html << trail.join(ERB::Util.h(" #{DELIMITER} "))
    end
    html.target!
  end

  private
  def default_trail
    trail = [Nodes::HOME]
    if crud_context == :list
      trail << Nodes::LIST_UNLINKED
    else
      trail << Nodes::LIST_LINKED << Nodes::CRUD_CONTEXT
    end
  end

  def trail
    parts = breadcrumb_trail.empty? ? default_trail : breadcrumb_trail
    parts.collect { |e| e.is_a?(Proc) ? self.instance_eval(&e) : e }
  end
end


text:
import PythonQt
from PythonQt import QtCore, QtGui, QtUiTools
from director import lcmUtils
from director import applogic as app
from director.utime import getUtime
from director.timercallback import TimerCallback
from director import visualization as vis
from director.debugVis import DebugData
from director.wristforcetorquevisualizer import WristForceTorqueVisualizer

import numpy as np
import math
from time import time
from time import sleep

def addWidgetsToDict(widgets, d):

    for widget in widgets:
        if widget.objectName:
            d[str(widget.objectName)] = widget
        addWidgetsToDict(widget.children(), d)

class WidgetDict(object):

    def __init__(self, widgets):
        addWidgetsToDict(widgets, self.__dict__)

class HandControlPanel(object):

    def __init__(self, lDriver, rDriver, robotStateModel, robotStateJointController, view):

        self.robotStateModel = robotStateModel
        self.robotStateJointController = robotStateJointController
        self.drivers = {}
        self.drivers['left'] = lDriver
        self.drivers['right'] = rDriver

        self.storedCommand = {'left': None, 'right': None}

        loader = QtUiTools.QUiLoader()
        uifile = QtCore.QFile(':/ui/ddHandControl.ui')
        assert uifile.open(uifile.ReadOnly)

        self.widget = loader.load(uifile)

        self.ui = WidgetDict(self.widget.children())
        self._updateBlocked = True

        self.widget.advanced.sendButton.setEnabled(True)

        # Store calibration for wrist f/t sensors
        self.wristftvis = WristForceTorqueVisualizer(robotStateModel, robotStateJointController, view)

        # connect the callbacks
        self.widget.basic.openButton.clicked.connect(self.openClicked)
        self.widget.basic.closeButton.clicked.connect(self.closeClicked)
        self.widget.basic.waitOpenButton.clicked.connect(self.waitOpenClicked)
        self.widget.basic.waitCloseButton.clicked.connect(self.waitCloseClicked)
        self.widget.advanced.sendButton.clicked.connect(self.sendClicked)
        self.widget.advanced.calibrateButton.clicked.connect(self.calibrateClicked)
        self.widget.advanced.setModeButton.clicked.connect(self.setModeClicked)
        self.widget.advanced.regraspButton.clicked.connect(self.regraspClicked)
        self.widget.advanced.dropButton.clicked.connect(self.dropClicked)
        self.widget.advanced.repeatRateSpinner.valueChanged.connect(self.rateSpinnerChanged)
        self.ui.fingerControlButton.clicked.connect(self.fingerControlButton)

        self.widget.sensors.rightTareButton.clicked.connect(self.wristftvis.tareRightFT)
        self.widget.sensors.leftTareButton.clicked.connect(self.wristftvis.tareLeftFT)
        self.widget.sensors.rightCalibButton.clicked.connect(self.wristftvis.calibRightFT)
        self.widget.sensors.leftCalibButton.clicked.connect(self.wristftvis.calibLeftFT)
        self.widget.sensors.rightCalibClearButton.clicked.connect(self.wristftvis.calibRightClearFT)
        self.widget.sensors.leftCalibClearButton.clicked.connect(self.wristftvis.calibLeftClearFT)
        self.widget.sensors.rightVisCheck.clicked.connect(self.updateWristFTVis)
        self.widget.sensors.leftVisCheck.clicked.connect(self.updateWristFTVis)
        self.widget.sensors.torqueVisCheck.clicked.connect(self.updateWristFTVis)

        PythonQt.dd.ddGroupBoxHider(self.ui.sensors)
        PythonQt.dd.ddGroupBoxHider(self.ui.fingerControl)

        # Bug fix... for some reason one slider is set as disabled
        self.ui.fingerASlider.setEnabled(True)

        # create a timer to repeat commands
        self.updateTimer = TimerCallback()
        self.updateTimer.callback = self.updatePanel
        self.updateTimer.targetFps = 3
        self.updateTimer.start()

    def getModeInt(self, inputStr):
        if inputStr == 'Basic':
            return 0
        if inputStr == 'Pinch':
            return 1
        if inputStr == 'Wide':
            return 2
        if inputStr == 'Scissor':
            return 3
        return 0

    def openClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        self.widget.advanced.closePercentSpinner.setValue(0.0)

        position = 0.0
        force = float(self.widget.advanced.forcePercentSpinner.value)
        velocity = float(self.widget.advanced.velocityPercentSpinner.value)

        mode = self.getModeInt(self.widget.advanced.modeBox.currentText)

        self.drivers[side].sendCustom(position, force, velocity, mode)
        self.storedCommand[side] = (position, force, velocity, mode)

    def closeClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        self.widget.advanced.closePercentSpinner.setValue(100.0)

        position = 100.0
        force = float(self.widget.advanced.forcePercentSpinner.value)
        velocity = float(self.widget.advanced.velocityPercentSpinner.value)

        mode = self.getModeInt(self.widget.advanced.modeBox.currentText)

        self.drivers[side].sendCustom(position, force, velocity, mode)
        self.storedCommand[side] = (position, force, velocity, mode)

    def waitOpenClicked(self):
        sleep(10)
        self.openClicked()

    def waitCloseClicked(self):
        sleep(10)
        self.closeClicked()

    def sendClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        position = float(self.widget.advanced.closePercentSpinner.value)
        force = float(self.widget.advanced.forcePercentSpinner.value)
        velocity = float(self.widget.advanced.velocityPercentSpinner.value)

        mode = self.getModeInt(self.widget.advanced.modeBox.currentText)

        self.drivers[side].sendCustom(position, force, velocity, mode)
        self.storedCommand[side] = (position, force, velocity, mode)

    def setModeClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        mode = self.getModeInt(self.widget.advanced.modeBox.currentText)

        self.drivers[side].setMode(mode)
        self.storedCommand[side] = None

    def calibrateClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        self.drivers[side].sendCalibrate()
        self.storedCommand[side] = None

    def dropClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        self.drivers[side].sendDrop()
        self.storedCommand[side] = None

    def regraspClicked(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        position = float(self.widget.advanced.closePercentSpinner.value)
        force = float(self.widget.advanced.forcePercentSpinner.value)
        velocity = float(self.widget.advanced.velocityPercentSpinner.value)

        mode = self.getModeInt(self.widget.advanced.modeBox.currentText)

        self.drivers[side].sendRegrasp(position, force, velocity, mode)
        self.storedCommand[side] = (position, force, velocity, mode)

    def rateSpinnerChanged(self):
        self.updateTimer.targetFps = self.ui.repeatRateSpinner.value

    def fingerControlButton(self):
        if self.widget.handSelect.leftButton.checked:
            side = 'left'
        else:
            side = 'right'

        if not self.ui.scissorControl.isChecked():
            self.drivers[side].sendFingerControl(int(self.ui.fingerAValue.text),
                                                 int(self.ui.fingerBValue.text),
                                                 int(self.ui.fingerCValue.text),
                                                 float(self.widget.advanced.forcePercentSpinner.value),
                                                 float(self.widget.advanced.velocityPercentSpinner.value),
                                                 None,
                                                 self.getModeInt(self.widget.advanced.modeBox.currentText))
        else:
            self.drivers[side].sendFingerControl(int(self.ui.fingerAValue.text),
                                                 int(self.ui.fingerBValue.text),
                                                 int(self.ui.fingerCValue.text),
                                                 float(self.widget.advanced.forcePercentSpinner.value),
                                                 float(self.widget.advanced.velocityPercentSpinner.value),
                                                 int(self.ui.scissorValue.text),
                                                 0)  # can ignore mode because scissor will override
        self.storedCommand[side] = None

    def updateWristFTVis(self):
        self.wristftvis.updateDrawSettings(self.ui.leftVisCheck.checked, self.ui.rightVisCheck.checked, self.ui.torqueVisCheck.checked);

    def updatePanel(self):
        if self.ui.repeaterCheckBox.checked and self.storedCommand['left']:
            position, force, velocity, mode = self.storedCommand['left']
            self.drivers['left'].sendCustom(position, force, velocity, mode)
        if self.ui.repeaterCheckBox.checked and self.storedCommand['right']:
            position, force, velocity, mode = self.storedCommand['right']
            self.drivers['right'].sendCustom(position, force, velocity, mode)

def _getAction():
    return app.getToolBarActions()['ActionHandControlPanel']

def init(driverL, driverR, model, jc, view):

    global panel
    global dock

    panel = HandControlPanel(driverL, driverR, model, jc, view)
    dock = app.addWidgetToDock(panel.widget, action=_getAction())
    dock.hide()

    return panel


text:
package registry

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/apigee/registry/rpc"
	"github.com/apigee/registry/server/registry/test/seeder"
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/testing/protocmp"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

func TestCreateApiVersion(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.Api
		req  *rpc.CreateApiVersionRequest
		want *rpc.ApiVersion
	}{
		{
			desc: "fully populated resource",
			seed: &rpc.Api{
				Name: "projects/my-project/locations/global/apis/my-api",
			},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "v1",
				ApiVersion: &rpc.ApiVersion{
					DisplayName: "My Display Name",
					Description: "My Description",
					State:       "My State",
					PrimarySpec: "specs/my spec",
					Labels: map[string]string{
						"label-key": "label-value",
					},
					Annotations: map[string]string{
						"annotation-key": "annotation-value",
					},
				},
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "My Display Name",
				Description: "My Description",
				State:       "My State",
				PrimarySpec: "specs/my spec",
				Labels: map[string]string{
					"label-key": "label-value",
				},
				Annotations: map[string]string{
					"annotation-key": "annotation-value",
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedApis(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			created, err := server.CreateApiVersion(ctx, test.req)
			if err != nil {
				t.Fatalf("CreateApiVersion(%+v) returned error: %s", test.req, err)
			}

			opts := cmp.Options{
				protocmp.Transform(),
				protocmp.IgnoreFields(new(rpc.ApiVersion), "create_time", "update_time"),
			}

			if !cmp.Equal(test.want, created, opts) {
				t.Errorf("CreateApiVersion(%+v) returned unexpected diff (-want +got):\n%s", test.req, cmp.Diff(test.want, created, opts))
			}

			if created.CreateTime == nil || created.UpdateTime == nil {
				t.Errorf("CreateApiVersion(%+v) returned unset create_time (%v) or update_time (%v)", test.req, created.CreateTime, created.UpdateTime)
			} else if !created.CreateTime.AsTime().Equal(created.UpdateTime.AsTime()) {
				t.Errorf("CreateApiVersion(%+v) returned unexpected timestamps: create_time %v != update_time %v", test.req, created.CreateTime, created.UpdateTime)
			}

			t.Run("GetApiVersion", func(t *testing.T) {
				req := &rpc.GetApiVersionRequest{
					Name: created.GetName(),
				}

				got, err := server.GetApiVersion(ctx, req)
				if err != nil {
					t.Fatalf("GetApiVersion(%+v) returned error: %s", req, err)
				}

				opts := protocmp.Transform()
				if !cmp.Equal(created, got, opts) {
					t.Errorf("GetApiVersion(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(created, got, opts))
				}
			})
		})
	}
}

func TestCreateApiVersionResponseCodes(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.Api
		req  *rpc.CreateApiVersionRequest
		want codes.Code
	}{
		{
			desc: "parent not found",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/other-api",
				ApiVersionId: "valid-id",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.NotFound,
		},
		{
			desc: "missing resource body",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "valid-id",
				ApiVersion:   nil,
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "missing custom identifier",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "long custom identifier",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "this-identifier-is-invalid-because-it-exceeds-the-eighty-character-maximum-length",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "custom identifier underscores",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "underscore_identifier",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "custom identifier hyphen prefix",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "-identifier",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "custom identifier hyphen suffix",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "identifier-",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "customer identifier uuid format",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "072d2288-c685-42d8-9df0-5edbb2a809ea",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "custom identifier mixed case",
			seed: &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"},
			req: &rpc.CreateApiVersionRequest{
				Parent:       "projects/my-project/locations/global/apis/my-api",
				ApiVersionId: "IDentifier",
				ApiVersion:   &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedApis(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.CreateApiVersion(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("CreateApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
		})
	}
}

func TestCreateApiVersionDuplicates(t *testing.T) {
	test := struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.CreateApiVersionRequest
		want codes.Code
	}{
		desc: "case sensitive",
		seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
		req: &rpc.CreateApiVersionRequest{
			Parent:       "projects/my-project/locations/global/apis/my-api",
			ApiVersionId: "v1",
			ApiVersion:   &rpc.ApiVersion{},
		},
		want: codes.AlreadyExists,
	}
	t.Run(test.desc, func(t *testing.T) {
		ctx := context.Background()
		server := defaultTestServer(t)
		if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
			t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
		}

		if _, err := server.CreateApiVersion(ctx, test.req); status.Code(err) != test.want {
			t.Errorf("CreateApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
		}
	})
}

func TestGetApiVersion(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.GetApiVersionRequest
		want *rpc.ApiVersion
	}{
		{
			desc: "fully populated resource",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/my-version",
				DisplayName: "My Display Name",
				Description: "My Description",
				State:       "My State",
				Labels: map[string]string{
					"label-key": "label-value",
				},
				Annotations: map[string]string{
					"annotation-key": "annotation-value",
				},
			},
			req: &rpc.GetApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/my-version",
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/my-version",
				DisplayName: "My Display Name",
				Description: "My Description",
				State:       "My State",
				Labels: map[string]string{
					"label-key": "label-value",
				},
				Annotations: map[string]string{
					"annotation-key": "annotation-value",
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			got, err := server.GetApiVersion(ctx, test.req)
			if err != nil {
				t.Fatalf("GetApiVersion(%+v) returned error: %s", test.req, err)
			}

			opts := cmp.Options{
				protocmp.Transform(),
				protocmp.IgnoreFields(new(rpc.ApiVersion), "create_time", "update_time"),
			}

			if !cmp.Equal(test.want, got, opts) {
				t.Errorf("GetApiVersion(%+v) returned unexpected diff (-want +got):\n%s", test.req, cmp.Diff(test.want, got, opts))
			}
		})
	}
}

func TestGetApiVersionResponseCodes(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.GetApiVersionRequest
		want codes.Code
	}{
		{
			desc: "resource not found",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.GetApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/doesnt-exist",
			},
			want: codes.NotFound,
		},
		{
			desc: "case insensitive name",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.GetApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/V1",
			},
			want: codes.OK,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.GetApiVersion(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("GetApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
		})
	}
}

func TestListApiVersions(t *testing.T) {
	tests := []struct {
		admin     bool
		desc      string
		seed      []*rpc.ApiVersion
		req       *rpc.ListApiVersionsRequest
		want      *rpc.ListApiVersionsResponse
		wantToken bool
		extraOpts cmp.Option
	}{
		{
			desc: "default parameters",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
				{Name: "projects/my-project/locations/global/apis/other-api/versions/v1"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/my-api",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
				},
			},
		},
		{
			admin: true,
			desc:  "across all apis in a specific project",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/my-project/locations/global/apis/other-api/versions/v1"},
				{Name: "projects/other-project/locations/global/apis/my-api/versions/v1"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/-",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
					{Name: "projects/my-project/locations/global/apis/other-api/versions/v1"},
				},
			},
		},
		{
			admin: true,
			desc:  "across all projects and apis",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/other-project/locations/global/apis/other-api/versions/v1"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/-/locations/global/apis/-",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
					{Name: "projects/other-project/locations/global/apis/other-api/versions/v1"},
				},
			},
		},
		{
			admin: true,
			desc:  "in a specific api across all projects",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/other-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/my-project/locations/global/apis/other-api/versions/v1"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/-/locations/global/apis/my-api",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
					{Name: "projects/other-project/locations/global/apis/my-api/versions/v1"},
				},
			},
		},
		{
			desc: "custom page size",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent:   "projects/my-project/locations/global/apis/my-api",
				PageSize: 1,
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{},
				},
			},
			wantToken: true,
			// Ordering is not guaranteed by API, so any resource may be returned.
			extraOpts: protocmp.IgnoreFields(new(rpc.ApiVersion), "name"),
		},
		{
			desc: "name equality filtering",
			seed: []*rpc.ApiVersion{
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/my-api",
				Filter: "name == 'projects/my-project/locations/global/apis/my-api/versions/v2'",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
				},
			},
		},
		{
			desc: "description inequality filtering",
			seed: []*rpc.ApiVersion{
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "First ApiVersion",
				},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
				{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/my-api",
				Filter: "description != ''",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
						Description: "First ApiVersion",
					},
				},
			},
		},
		{
			desc: "ordered by description",
			seed: []*rpc.ApiVersion{
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "111: this should be returned first",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
					Description: "333: this should be returned third",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
					Description: "222: this should be returned second",
				},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "description",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
						Description: "111: this should be returned first",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
						Description: "222: this should be returned second",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
						Description: "333: this should be returned third",
					},
				},
			},
		},
		{
			desc: "ordered by description descending",
			seed: []*rpc.ApiVersion{
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "111: this should be returned third",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
					Description: "333: this should be returned first",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
					Description: "222: this should be returned second",
				},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "description desc",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
						Description: "333: this should be returned first",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
						Description: "222: this should be returned second",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
						Description: "111: this should be returned third",
					},
				},
			},
		},
		{
			desc: "ordered by description then by name",
			seed: []*rpc.ApiVersion{
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "222: this should be returned second or third (the name is the tie-breaker)",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
					Description: "111: this should be returned first",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
					Description: "222: this should be returned second or third (the name is the tie-breaker)",
				},
			},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "description,name",
			},
			want: &rpc.ListApiVersionsResponse{
				ApiVersions: []*rpc.ApiVersion{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v3",
						Description: "111: this should be returned first",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
						Description: "222: this should be returned second or third (the name is the tie-breaker)",
					},
					{
						Name:        "projects/my-project/locations/global/apis/my-api/versions/v2",
						Description: "222: this should be returned second or third (the name is the tie-breaker)",
					},
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			if test.admin && adminServiceUnavailable() {
				t.Skip(testRequiresAdminService)
			}
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed...); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			got, err := server.ListApiVersions(ctx, test.req)
			if err != nil {
				t.Fatalf("ListApiVersions(%+v) returned error: %s", test.req, err)
			}

			opts := cmp.Options{
				protocmp.Transform(),
				protocmp.IgnoreFields(new(rpc.ListApiVersionsResponse), "next_page_token"),
				protocmp.IgnoreFields(new(rpc.ApiVersion), "create_time", "update_time"),
				test.extraOpts,
			}

			if !cmp.Equal(test.want, got, opts) {
				t.Errorf("ListApiVersions(%+v) returned unexpected diff (-want +got):\n%s", test.req, cmp.Diff(test.want, got, opts))
			}

			if test.wantToken && got.NextPageToken == "" {
				t.Errorf("ListApiVersions(%+v) returned empty next_page_token, expected non-empty next_page_token", test.req)
			} else if !test.wantToken && got.NextPageToken != "" {
				t.Errorf("ListApiVersions(%+v) returned non-empty next_page_token, expected empty next_page_token: %s", test.req, got.GetNextPageToken())
			}
		})
	}
}

func TestListApiVersionsResponseCodes(t *testing.T) {
	tests := []struct {
		admin bool
		desc  string
		seed  *rpc.ApiVersion
		req   *rpc.ListApiVersionsRequest
		want  codes.Code
	}{
		{
			desc: "parent api not found",
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/my-api",
			},
			want: codes.NotFound,
		},
		{
			admin: true,
			desc:  "parent project not found",
			req: &rpc.ListApiVersionsRequest{
				Parent: "projects/my-project/locations/global/apis/-",
			},
			want: codes.NotFound,
		},
		{
			desc: "negative page size",
			req: &rpc.ListApiVersionsRequest{
				PageSize: -1,
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid filter",
			req: &rpc.ListApiVersionsRequest{
				Filter: "this filter is not valid",
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid page token",
			req: &rpc.ListApiVersionsRequest{
				PageToken: "this token is not valid",
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid ordering by unknown field",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "something",
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid ordering by private field",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "key",
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid ordering direction",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "description asc",
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "invalid ordering format",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.ListApiVersionsRequest{
				Parent:  "projects/my-project/locations/global/apis/my-api",
				OrderBy: "description,",
			},
			want: codes.InvalidArgument,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			if test.admin && adminServiceUnavailable() {
				t.Skip(testRequiresAdminService)
			}
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.ListApiVersions(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("ListApiVersions(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
		})
	}
}

func TestListApiVersionsSequence(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	seed := []*rpc.ApiVersion{
		{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
		{Name: "projects/my-project/locations/global/apis/my-api/versions/v2"},
		{Name: "projects/my-project/locations/global/apis/my-api/versions/v3"},
	}
	if err := seeder.SeedVersions(ctx, server, seed...); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	listed := make([]*rpc.ApiVersion, 0, 3)

	var nextToken string
	t.Run("first page", func(t *testing.T) {
		req := &rpc.ListApiVersionsRequest{
			Parent:   "projects/my-project/locations/global/apis/my-api",
			PageSize: 1,
		}

		got, err := server.ListApiVersions(ctx, req)
		if err != nil {
			t.Fatalf("ListApiVersions(%+v) returned error: %s", req, err)
		}

		if count := len(got.GetApiVersions()); count != 1 {
			t.Errorf("ListApiVersions(%+v) returned %d versions, expected exactly one", req, count)
		}

		if got.GetNextPageToken() == "" {
			t.Errorf("ListApiVersions(%+v) returned empty next_page_token, expected another page", req)
		}

		listed = append(listed, got.ApiVersions...)
		nextToken = got.GetNextPageToken()
	})

	if t.Failed() {
		t.Fatal("Cannot test intermediate page after failure on first page")
	}

	t.Run("intermediate page", func(t *testing.T) {
		req := &rpc.ListApiVersionsRequest{
			Parent:    "projects/my-project/locations/global/apis/my-api",
			PageSize:  1,
			PageToken: nextToken,
		}

		got, err := server.ListApiVersions(ctx, req)
		if err != nil {
			t.Fatalf("ListApiVersions(%+v) returned error: %s", req, err)
		}

		if count := len(got.GetApiVersions()); count != 1 {
			t.Errorf("ListApiVersions(%+v) returned %d versions, expected exactly one", req, count)
		}

		if got.GetNextPageToken() == "" {
			t.Errorf("ListApiVersions(%+v) returned empty next_page_token, expected another page", req)
		}

		listed = append(listed, got.ApiVersions...)
		nextToken = got.GetNextPageToken()
	})

	if t.Failed() {
		t.Fatal("Cannot test final page after failure on intermediate page")
	}

	t.Run("final page", func(t *testing.T) {
		req := &rpc.ListApiVersionsRequest{
			Parent:    "projects/my-project/locations/global/apis/my-api",
			PageSize:  1,
			PageToken: nextToken,
		}

		got, err := server.ListApiVersions(ctx, req)
		if err != nil {
			t.Fatalf("ListApiVersions(%+v) returned error: %s", req, err)
		}

		if count := len(got.GetApiVersions()); count != 1 {
			t.Errorf("ListApiVersions(%+v) returned %d versions, expected exactly one", req, count)
		}

		if got.GetNextPageToken() != "" {
			t.Errorf("ListApiVersions(%+v) returned next_page_token, expected no next page", req)
		}

		listed = append(listed, got.ApiVersions...)
	})

	if t.Failed() {
		t.Fatal("Cannot test sequence result after failure on final page")
	}

	opts := cmp.Options{
		protocmp.Transform(),
		protocmp.IgnoreFields(new(rpc.ApiVersion), "create_time", "update_time"),
		cmpopts.SortSlices(func(a, b *rpc.ApiVersion) bool {
			return a.GetName() < b.GetName()
		}),
	}

	if !cmp.Equal(seed, listed, opts) {
		t.Errorf("List sequence returned unexpected diff (-want +got):\n%s", cmp.Diff(seed, listed, opts))
	}
}

// This test prevents the list sequence from ending before a known filter match is listed.
// For simplicity, it does not guarantee the resource is returned on a later page.
func TestListApiVersionsLargeCollectionFiltering(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	seed := make([]*rpc.ApiVersion, 0, 100)
	for i := 1; i <= cap(seed); i++ {
		seed = append(seed, &rpc.ApiVersion{
			Name: fmt.Sprintf("projects/my-project/locations/global/apis/my-api/versions/v%03d", i),
		})
	}

	if err := seeder.SeedVersions(ctx, server, seed...); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	req := &rpc.ListApiVersionsRequest{
		Parent:   "projects/my-project/locations/global/apis/my-api",
		PageSize: 1,
		Filter:   "name == 'projects/my-project/locations/global/apis/my-api/versions/v099'",
	}

	got, err := server.ListApiVersions(ctx, req)
	if err != nil {
		t.Fatalf("ListApiVersions(%+v) returned error: %s", req, err)
	}

	if len(got.GetApiVersions()) == 1 && got.GetNextPageToken() != "" {
		t.Errorf("ListApiVersions(%+v) returned a page token when the only matching resource has been listed: %+v", req, got)
	} else if len(got.GetApiVersions()) == 0 && got.GetNextPageToken() == "" {
		t.Errorf("ListApiVersions(%+v) returned an empty next page token before listing the only matching resource", req)
	} else if count := len(got.GetApiVersions()); count > 1 {
		t.Errorf("ListApiVersions(%+v) returned %d projects, expected at most one: %+v", req, count, got.GetApiVersions())
	}
}

func TestUpdateApiVersion(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.UpdateApiVersionRequest
		want *rpc.ApiVersion
	}{
		{
			desc: "allow missing updates existing resources",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/a/versions/v",
				Description: "My ApiVersion",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name:        "projects/my-project/locations/global/apis/a/versions/v",
					Description: "My Updated ApiVersion",
				},
				UpdateMask:   &fieldmaskpb.FieldMask{Paths: []string{"description"}},
				AllowMissing: true,
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/a/versions/v",
				Description: "My Updated ApiVersion",
			},
		},
		{
			desc: "allow missing creates missing resources",
			seed: &rpc.ApiVersion{
				Name: "projects/my-project/locations/global/apis/a/versions/v-sibling",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/a/versions/v",
				},
				AllowMissing: true,
			},
			want: &rpc.ApiVersion{
				Name: "projects/my-project/locations/global/apis/a/versions/v",
			},
		},
		{
			desc: "implicit nil mask",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My ApiVersion",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "My Updated ApiVersion",
				},
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My Updated ApiVersion",
			},
		},
		{
			desc: "implicit empty mask",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My ApiVersion",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "My Updated ApiVersion",
				},
				UpdateMask: &fieldmaskpb.FieldMask{},
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My Updated ApiVersion",
			},
		},
		{
			desc: "field specific mask",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My ApiVersion",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					DisplayName: "Ignored",
					Description: "My Updated ApiVersion",
				},
				UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"description"}},
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My Updated ApiVersion",
			},
		},
		{
			desc: "full replacement wildcard mask",
			seed: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "Version One",
				Description: "My ApiVersion",
			},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
					Description: "My Updated ApiVersion",
				},
				UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"*"}},
			},
			want: &rpc.ApiVersion{
				Name:        "projects/my-project/locations/global/apis/my-api/versions/v1",
				DisplayName: "",
				Description: "My Updated ApiVersion",
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			updated, err := server.UpdateApiVersion(ctx, test.req)
			if err != nil {
				t.Fatalf("UpdateApiVersion(%+v) returned error: %s", test.req, err)
			}

			opts := cmp.Options{
				protocmp.Transform(),
				protocmp.IgnoreFields(new(rpc.ApiVersion), "create_time", "update_time"),
			}

			if !cmp.Equal(test.want, updated, opts) {
				t.Errorf("UpdateApiVersion(%+v) returned unexpected diff (-want +got):\n%s", test.req, cmp.Diff(test.want, updated, opts))
			}

			t.Run("GetApiVersion", func(t *testing.T) {
				req := &rpc.GetApiVersionRequest{
					Name: updated.GetName(),
				}

				got, err := server.GetApiVersion(ctx, req)
				if err != nil {
					t.Fatalf("GetApiVersion(%+v) returned error: %s", req, err)
				}

				opts := protocmp.Transform()
				if !cmp.Equal(updated, got, opts) {
					t.Errorf("GetApiVersion(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(updated, got, opts))
				}
			})
		})
	}
}

func TestUpdateApiVersionResponseCodes(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.UpdateApiVersionRequest
		want codes.Code
	}{
		{
			desc: "resource not found",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/my-api/versions/doesnt-exist",
				},
			},
			want: codes.NotFound,
		},
		{
			desc: "missing resource body",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req:  &rpc.UpdateApiVersionRequest{},
			want: codes.InvalidArgument,
		},
		{
			desc: "missing resource name",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{},
			},
			want: codes.InvalidArgument,
		},
		{
			desc: "nonexistent field in mask",
			seed: &rpc.ApiVersion{Name: "projects/my-project/locations/global/apis/my-api/versions/v1"},
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/my-api/versions/v1",
				},
				UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"this field does not exist"}},
			},
			want: codes.InvalidArgument,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.UpdateApiVersion(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("UpdateApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
		})
	}
}

func TestUpdateApiVersionSequence(t *testing.T) {
	tests := []struct {
		desc string
		req  *rpc.UpdateApiVersionRequest
		want codes.Code
	}{
		{
			desc: "create using update with allow_missing=false",
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/a/versions/v",
				},
				AllowMissing: false,
			},
			want: codes.NotFound,
		},
		{
			desc: "create using update with allow_missing=true",
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/a/versions/v",
				},
				AllowMissing: true,
			},
			want: codes.OK,
		},
		{
			desc: "update existing resource with allow_missing=true",
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/a/versions/v",
				},
				AllowMissing: true,
			},
			want: codes.OK,
		},
		{
			desc: "update existing resource with allow_missing=false",
			req: &rpc.UpdateApiVersionRequest{
				ApiVersion: &rpc.ApiVersion{
					Name: "projects/my-project/locations/global/apis/a/versions/v",
				},
				AllowMissing: false,
			},
			want: codes.OK,
		},
	}
	ctx := context.Background()
	server := defaultTestServer(t)
	seed := &rpc.Api{Name: "projects/my-project/locations/global/apis/a"}
	if err := seeder.SeedApis(ctx, server, seed); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}
	var createTime time.Time
	var updateTime time.Time
	// NOTE: in the following sequence of tests, each test depends on its predecessor.
	// Resources are successively created and updated using the "Update" RPC and the
	// tests verify that CreateTime/UpdateTime fields are modified appropriately.
	for i, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			var result *rpc.ApiVersion
			var err error
			if result, err = server.UpdateApiVersion(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("UpdateApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
			if result != nil {
				if i == 1 {
					createTime = result.CreateTime.AsTime()
					updateTime = result.UpdateTime.AsTime()
				} else {
					if !createTime.Equal(result.CreateTime.AsTime()) {
						t.Errorf("UpdateApiVersion create time changed after update (%v %v)", createTime, result.CreateTime.AsTime())
					}
					if !updateTime.Before(result.UpdateTime.AsTime()) {
						t.Errorf("UpdateApiVersion update time did not increase after update (%v %v)", updateTime, result.UpdateTime.AsTime())
					}
					updateTime = result.UpdateTime.AsTime()
				}
			}
		})
	}
}

func TestDeleteApiVersion(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.ApiVersion
		req  *rpc.DeleteApiVersionRequest
	}{
		{
			desc: "existing resource",
			seed: &rpc.ApiVersion{
				Name: "projects/my-project/locations/global/apis/my-api/versions/v1",
			},
			req: &rpc.DeleteApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/v1",
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedVersions(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.DeleteApiVersion(ctx, test.req); err != nil {
				t.Fatalf("DeleteApiVersion(%+v) returned error: %s", test.req, err)
			}

			t.Run("GetApiVersion", func(t *testing.T) {
				req := &rpc.GetApiVersionRequest{
					Name: test.req.GetName(),
				}

				if _, err := server.GetApiVersion(ctx, req); status.Code(err) != codes.NotFound {
					t.Fatalf("GetApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), codes.NotFound, err)
				}
			})
		})
	}
}

func TestDeleteApiVersionResponseCodes(t *testing.T) {
	tests := []struct {
		desc string
		seed *rpc.Artifact
		req  *rpc.DeleteApiVersionRequest
		want codes.Code
	}{
		{
			desc: "resource not found",
			req: &rpc.DeleteApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/doesnt-exist",
			},
			want: codes.NotFound,
		},
		{
			desc: "resource has children",
			seed: &rpc.Artifact{
				Name: "projects/my-project/locations/global/apis/my-api/versions/my-version/artifacts/my-artifact",
			},
			req: &rpc.DeleteApiVersionRequest{
				Name: "projects/my-project/locations/global/apis/my-api/versions/my-version",
			},
			want: codes.FailedPrecondition,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedArtifacts(ctx, server, test.seed); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			if _, err := server.DeleteApiVersion(ctx, test.req); status.Code(err) != test.want {
				t.Errorf("DeleteApiVersion(%+v) returned status code %q, want %q: %v", test.req, status.Code(err), test.want, err)
			}
		})
	}
}

func TestDeleteApiVersionCascading(t *testing.T) {
	var (
		ctx    = context.Background()
		server = defaultTestServer(t)
		spec   = &rpc.ApiSpec{
			Name: "projects/my-project/locations/global/apis/my-api/versions/my-version/specs/my-spec",
		}
		artifact = &rpc.Artifact{
			Name: "projects/my-project/locations/global/apis/my-api/versions/my-version/artifacts/my-artifact",
		}
	)

	if err := seeder.SeedRegistry(ctx, server, spec, artifact); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	req := &rpc.DeleteApiVersionRequest{
		Name:  "projects/my-project/locations/global/apis/my-api/versions/my-version",
		Force: true,
	}

	if _, err := server.DeleteApiVersion(ctx, req); err != nil {
		t.Errorf("DeleteApiVersion(%+v) returned error: %s", req, err)
	}

	if _, err := server.GetApiVersion(ctx, &rpc.GetApiVersionRequest{Name: req.GetName()}); status.Code(err) != codes.NotFound {
		t.Errorf("GetApiVersion(%q) returned status code %q, want %q: %s", req.GetName(), status.Code(err), codes.NotFound, err)
	}

	if _, err := server.GetApiSpec(ctx, &rpc.GetApiSpecRequest{Name: spec.GetName()}); status.Code(err) != codes.NotFound {
		t.Errorf("GetApiSpec(%q) returned status code %q, want %q: %s", spec.GetName(), status.Code(err), codes.NotFound, err)
	}

	if _, err := server.GetArtifact(ctx, &rpc.GetArtifactRequest{Name: artifact.GetName()}); status.Code(err) != codes.NotFound {
		t.Errorf("GetArtifact(%q) returned status code %q, want %q: %s", artifact.GetName(), status.Code(err), codes.NotFound, err)
	}
}


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

using Microsoft.Languages.Editor.Text;

namespace Microsoft.Languages.Editor {
    public static class EditorViewExtensions {
        /// <summary>
        /// Retrieves service from the service container attached to the view
        /// </summary>
        public static T GetService<T>(this IEditorView editorView) where T : class => editorView.Services.GetService<T>();

        /// <summary>
        /// Adds service to this instance of the view
        /// </summary>
        public static void AddService<T>(this IEditorView editorView, object service) => editorView.Services.AddService(service);

        /// <summary>
        /// Removes service from the instance of the view
        /// </summary>
        public static void RemoveService(this IEditorView editorView, object service) => editorView.Services.RemoveService(service);
    }
}


text:
import sys, time
from file_check import *

check_data_files()

from print_trade_info import set_low_balance_msg, print_trade, reset_print_info
from db_access import db_connect, db_exists, output_records_exist, output_init_record, get_last_output_record
from balances import *
from analyst import *
from trader import *
from info_track import *

nonce_file = 'auth/nonce.sqlite'
output_file = parent_dir + 'build/data/output.sqlite'

bal = Balance(0, 0)
timer = Timer()
info = Trade_Counter()

initial_order = True

while not db_exists(output_file):
    timer.track()
    sys.stdout.write('\rWaiting for output.sqlite, execute neural network...%i:%i:%i' % (timer.hour, timer.min, timer.sec))
    sys.stdout.flush()
    time.sleep(1)
timer.reset()

db_connect(nonce_file, output_file)

while not output_records_exist():
    timer.track()
    sys.stdout.write('\rWaiting for first prediction from neural network %i:%i:%i' % (timer.hour, timer.min, timer.sec))
    sys.stdout.flush()
    time.sleep(1)
timer.reset()

balance_response = make_request('getInfo', 0, 0, 0)
bal.set_initial_balances(balance_response['return']['funds']['btc'], balance_response['return']['funds']['usd'])
bal.set_balances(balance_response['return']['funds']['btc'], balance_response['return']['funds']['usd'])

last_order_entry = output_init_record()

while True:
    output_data = get_last_output_record()
    current_row = output_data[0]
    current_price = output_data[1]
    predicted_price = output_data[2]
    order_type = output_data[3]
    err_rate = output_data[4]

    # A new output.sqlite record is present if this evaluates to true or the first record was inserted
    if current_row != last_order_entry or initial_order:
        last_order_entry = current_row
        initial_order = False

        balance_response = make_request('getInfo', 0, 0, 0)
        bal.set_balances(balance_response['return']['funds']['btc'], balance_response['return']['funds']['usd'])

        if order_type == 'buy':
            if bal.balance_check(order_type):
                usd_to_btc_qty = get_order_size(err_rate) * bal.usd_bal()
                if profit_check(order_type, usd_to_btc_qty, current_price, predicted_price):

                    if exceeds_threshold(usd_to_btc_qty / current_price):

                        prediction_buy_response = make_request(order_type, usd_to_btc_qty / current_price, current_price, 0)
                        bal.set_balances(prediction_buy_response['return']['funds']['btc'], prediction_buy_response['return']['funds']['usd'])
                        info.prediction_trade_complete()

                        cs_args = post_trade_check(bal.btc_bal(), 'COUNTER_SELL', usd_to_btc_qty, predicted_price)

                        counter_sell_response = make_request(cs_args[0], cs_args[1], cs_args[2], cs_args[3])
                        info.counter_trade_complete()
                        timer.reset()
            else:
                set_low_balance_msg(str(order_type + ' order aborted - Inadequate USD balance ($' + str(bal.btc_bal()) + ')'))

        elif order_type == 'sell':
            if bal.balance_check(order_type):
                btc_to_usd_qty = get_order_size(err_rate) * bal.btc_bal()
                if profit_check(order_type, btc_to_usd_qty, current_price, predicted_price):
                    if exceeds_threshold(btc_to_usd_qty):

                        prediction_sell_response = make_request(order_type, btc_to_usd_qty, current_price, 0)
                        bal.set_balances(prediction_sell_response['return']['funds']['btc'], prediction_sell_response['return']['funds']['usd'])
                        info.prediction_trade_complete()

                        cb_args = post_trade_check(bal.usd_bal(), 'COUNTER_BUY', btc_to_usd_qty, predicted_price)

                        counter_buy_response = make_request(cb_args[0], cb_args[1], cb_args[2], cb_args[3])
                        info.counter_trade_complete()
                        timer.reset()
            else:
                set_low_balance_msg(str(order_type + ' order aborted - Inadequate BTC balance (B' + str(bal.btc_bal()) + ')'))

        else:
            print('UNKNOWN ORDER TYPE')

        active_order_response = make_request('active', 0, 0, 0)
        open_btc_order_value = active_order_value(active_order_response)

        print('\r/---------------------------------------------------------------------------\\')
        print_trade()
        bal.print_bal(open_btc_order_value, current_price)
        reset_print_info()
        print('\r\---------------------------------------------------------------------------/')
    else:
        timer.track()
        sys.stdout.write('\rPrimary Trades: %i // Counter Trades: %i // Last Trade %i:%i:%i ' % (info.prediction_trades, info.counter_trades, timer.hour, timer.min, timer.sec))
        sys.stdout.flush()
        time.sleep(1)