text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'Event.chapter_id'
        db.add_column(u'events_event', 'chapter_id',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
                      keep_default=False)

        # Adding field 'Event.chapter_title'
        db.add_column(u'events_event', 'chapter_title',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
                      keep_default=False)

        # Adding field 'Event.fraternity_title'
        db.add_column(u'events_event', 'fraternity_title',
                      self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'Event.chapter_id'
        db.delete_column(u'events_event', 'chapter_id')

        # Deleting field 'Event.chapter_title'
        db.delete_column(u'events_event', 'chapter_title')

        # Deleting field 'Event.fraternity_title'
        db.delete_column(u'events_event', 'fraternity_title')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'chapters.chapter': {
            'Meta': {'object_name': 'Chapter'},
            u'_awards_excerpt': ('django.db.models.fields.TextField', [], {}),
            u'_description_excerpt': ('django.db.models.fields.TextField', [], {}),
            u'_philanthropy_excerpt': ('django.db.models.fields.TextField', [], {}),
            u'_potential_new_members_excerpt': ('django.db.models.fields.TextField', [], {}),
            'awards': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True', 'blank': 'True'}),
            'chapter_address': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'chapter_website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'cost': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'description': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True', 'blank': 'True'}),
            'facebook': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'fb_status': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'founding_year': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'fraternity': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['fraternities.Fraternity']", 'null': 'True', 'blank': 'True'}),
            'fraternity_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'gpa': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'linked_active_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_active'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_admin_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_admin'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_call_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_call'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_pending_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_pending'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_pledge_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_pledge'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'linked_rush_group': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'linked_chapter_rush'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.Group']"}),
            'location': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'philanthropy': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True', 'blank': 'True'}),
            'potential_new_members': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True', 'blank': 'True'}),
            'rush_form': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'chapter'", 'unique': 'True', 'null': 'True', 'to': u"orm['rush_forms.Form']"}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'status': ('model_utils.fields.StatusField', [], {'default': "'excellence'", 'max_length': '100', u'no_check_for_status': 'True'}),
            'status_changed': ('model_utils.fields.MonitorField', [], {'default': 'datetime.datetime.now', u'monitor': "u'status'"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
            'university': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['universities.University']", 'null': 'True', 'blank': 'True'}),
            'university_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
        },
        u'chapters.position': {
            'Meta': {'object_name': 'Position'},
            'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['chapters.Chapter']"}),
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'events.attendees': {
            'Meta': {'object_name': 'Attendees'},
            'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'attendees': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'attending'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['users.User']"}),
            'event': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['events.Event']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'rsvps': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'rsvps'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['users.User']"}),
            'rsvps_copy': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'rsvps_copy'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['users.User']"})
        },
        u'events.event': {
            'Meta': {'object_name': 'Event'},
            u'_description_excerpt': ('django.db.models.fields.TextField', [], {}),
            'all_day': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'chapter_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'chapter_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'description': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True'}),
            'enable_comments': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'fraternity_title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'events'", 'null': 'True', 'to': u"orm['users.User']"}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'status': ('model_utils.fields.StatusField', [], {'default': "'rush'", 'max_length': '100', u'no_check_for_status': 'True'}),
            'status_changed': ('model_utils.fields.MonitorField', [], {'default': 'datetime.datetime.now', u'monitor': "u'status'"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        u'fraternities.fraternity': {
            'Meta': {'object_name': 'Fraternity'},
            u'_description_excerpt': ('django.db.models.fields.TextField', [], {}),
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'description': ('model_utils.fields.SplitField', [], {u'no_excerpt_field': 'True', 'blank': 'True'}),
            'facebook': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
            'fb_status': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'gpa': ('django.db.models.fields.FloatField', [], {'default': '0'}),
            'group': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.Group']", 'unique': 'True', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        u'rush_forms.form': {
            'Meta': {'object_name': 'Form'},
            'button_text': ('django.db.models.fields.CharField', [], {'default': "u'Submit'", 'max_length': '50'}),
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'email_copies': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'email_from': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'email_message': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'email_subject': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'response': ('django.db.models.fields.TextField', [], {}),
            'send_email': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'status': ('model_utils.fields.StatusField', [], {'default': "u'draft'", 'max_length': '100', u'no_check_for_status': 'True'}),
            'status_changed': ('model_utils.fields.MonitorField', [], {'default': 'datetime.datetime.now', u'monitor': "u'status'"}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        u'universities.university': {
            'Meta': {'object_name': 'University'},
            'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),
            'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),
            'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        u'users.user': {
            'Meta': {'object_name': 'User'},
            'chapter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['chapters.Chapter']", 'null': 'True', 'blank': 'True'}),
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'fraternity': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['fraternities.Fraternity']", 'null': 'True', 'blank': 'True'}),
            'gpa': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            'highschool_gpa': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
            'hometown': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'major': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'phone': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
            'position': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['chapters.Position']", 'null': 'True', 'blank': 'True'}),
            'profile_img_id': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
            'profile_img_pic': ('django.db.models.fields.URLField', [], {'max_length': '500', 'blank': 'True'}),
            'profile_img_select': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
            'profile_img_src': ('django.db.models.fields.URLField', [], {'max_length': '500', 'blank': 'True'}),
            'status': ('model_utils.fields.StatusField', [], {'default': "'Rushing'", 'max_length': '100', u'no_check_for_status': 'True'}),
            'status_changed': ('model_utils.fields.MonitorField', [], {'default': 'datetime.datetime.now', u'monitor': "u'status'"}),
            'university': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['universities.University']", 'null': 'True', 'blank': 'True'}),
            'university_email': ('django.db.models.fields.EmailField', [], {'max_length': '255', 'blank': 'True'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
            'year': ('django.db.models.fields.IntegerField', [], {'default': '0'})
        }
    }

    complete_apps = ['events']


text:
package cn.felord.wepay.ali.sdk.api.domain;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;

/**
 * 电子发票抬头添加
 *
 * @author auto create
 * @version $Id: $Id
 */
public class AlipayEbppInvoiceTitleSyncModel extends AlipayObject {

	private static final long serialVersionUID = 4152542299616638376L;

	/**
	 * 开户银行账号
	 */
	@ApiField("open_bank_account")
	private String openBankAccount;

	/**
	 * 开户银行
	 */
	@ApiField("open_bank_name")
	private String openBankName;

	/**
	 * 税号
	 */
	@ApiField("tax_register_no")
	private String taxRegisterNo;

	/**
	 * 抬头名称
	 */
	@ApiField("title_name")
	private String titleName;

	/**
	 * 地址
	 */
	@ApiField("user_address")
	private String userAddress;

	/**
	 * 支付宝用户id
	 */
	@ApiField("user_id")
	private String userId;

	/**
	 * 电话
	 */
	@ApiField("user_mobile")
	private String userMobile;

	/**
	 *
Getter for the field openBankAccount.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOpenBankAccount() {
		return this.openBankAccount;
	}
	/**
	 *
Setter for the field openBankAccount.

	 *
	 * @param openBankAccount a {@link java.lang.String} object.
	 */
	public void setOpenBankAccount(String openBankAccount) {
		this.openBankAccount = openBankAccount;
	}

	/**
	 *
Getter for the field openBankName.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOpenBankName() {
		return this.openBankName;
	}
	/**
	 *
Setter for the field openBankName.

	 *
	 * @param openBankName a {@link java.lang.String} object.
	 */
	public void setOpenBankName(String openBankName) {
		this.openBankName = openBankName;
	}

	/**
	 *
Getter for the field taxRegisterNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTaxRegisterNo() {
		return this.taxRegisterNo;
	}
	/**
	 *
Setter for the field taxRegisterNo.

	 *
	 * @param taxRegisterNo a {@link java.lang.String} object.
	 */
	public void setTaxRegisterNo(String taxRegisterNo) {
		this.taxRegisterNo = taxRegisterNo;
	}

	/**
	 *
Getter for the field titleName.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTitleName() {
		return this.titleName;
	}
	/**
	 *
Setter for the field titleName.

	 *
	 * @param titleName a {@link java.lang.String} object.
	 */
	public void setTitleName(String titleName) {
		this.titleName = titleName;
	}

	/**
	 *
Getter for the field userAddress.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getUserAddress() {
		return this.userAddress;
	}
	/**
	 *
Setter for the field userAddress.

	 *
	 * @param userAddress a {@link java.lang.String} object.
	 */
	public void setUserAddress(String userAddress) {
		this.userAddress = userAddress;
	}

	/**
	 *
Getter for the field userId.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getUserId() {
		return this.userId;
	}
	/**
	 *
Setter for the field userId.

	 *
	 * @param userId a {@link java.lang.String} object.
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 *
Getter for the field userMobile.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getUserMobile() {
		return this.userMobile;
	}
	/**
	 *
Setter for the field userMobile.

	 *
	 * @param userMobile a {@link java.lang.String} object.
	 */
	public void setUserMobile(String userMobile) {
		this.userMobile = userMobile;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package datastore

import (
	"encoding/gob"
	"net/http"
	"reflect"
	"testing"

	"github.com/janelia-flyem/dvid/dvid"
)

func init() {
	gob.Register(&TestType{})
	gob.Register(&TestData{})
}

type TestType struct {
	Type
}

func (t *TestType) Help() string {
	return "no help here!"
}

func (t *TestType) NewDataService(uuid dvid.UUID, id dvid.InstanceID, name dvid.InstanceName, c dvid.Config) (DataService, error) {
	basedata, err := NewDataService(t, uuid, id, name, c)
	if err != nil {
		return nil, err
	}
	return &TestData{basedata}, nil
}

type TestData struct {
	*Data
}

func (d *TestData) DoRPC(request Request, reply *Response) error {
	return nil
}

func (d *TestData) ServeHTTP(uuid dvid.UUID, ctx *VersionedCtx, w http.ResponseWriter, r *http.Request) {
}

func (d *TestData) Help() string {
	return "no help here!"
}

func TestDataGobEncoding(t *testing.T) {
	compression, _ := dvid.NewCompression(dvid.LZ4, dvid.DefaultCompression)
	data := &TestData{&Data{
		typename:    "testtype",
		typeurl:     "foo.bar.baz/testtype",
		typeversion: "1.0",
		id:          dvid.InstanceID(13),
		name:        "my fabulous data",
		rootUUID:    dvid.UUID("42"),
		dataUUID:    dvid.NewUUID(),
		compression: compression,
		checksum:    dvid.DefaultChecksum,
		syncData:    dvid.UUIDSet{"moo": struct{}{}, "bar": struct{}{}, "baz": struct{}{}},
	}}

	encoding, err := data.GobEncode()
	if err != nil {
		t.Fatalf("Couldn't Gob encode test data: %v\n", err)
	}
	data2 := &TestData{new(Data)}
	if err = data2.GobDecode(encoding); err != nil {
		t.Fatalf("Couldn't Gob decode test data: %v\n", err)
	}
	if !reflect.DeepEqual(data, data2) {
		t.Errorf("Bad Gob roundtrip:\nOriginal: %v\nReturned: %v\n", data, data2)
	}
}


text:
class FbRootWindow: public FbTk::FbWindow {
public:
    explicit FbRootWindow(int screen_num);
    // disable functions that we can't do on root window
    void move(int x, int y) { }
    void resize(unsigned int width, unsigned int height) { }
    void moveResize(int x, int y, unsigned int width, unsigned int height) { }
    void show() { }
    void hide() { }
    // we should not assign a new window to this
    FbTk::FbWindow &operator = (Window win) { return *this; }
    Visual *visual() const { return m_visual; }
    Colormap colormap() const { return m_colormap; }

private:
    Visual *m_visual;
    Colormap m_colormap;
};

#endif // FBROOTWINDOW_HH


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

<title>Uses of Class org.springframework.jdbc.support.SQLErrorCodes (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.springframework.jdbc.support.SQLErrorCodes

Packages that use SQLErrorCodes

Package
Description

org.springframework.jdbc.support

Support classes for the JDBC framework, used by the classes in the
 jdbc.core and jdbc.object packages.

Uses of SQLErrorCodes in org.springframework.jdbc.support

Methods in org.springframework.jdbc.support that return SQLErrorCodes

Modifier and Type
Method and Description

SQLErrorCodes
SQLErrorCodesFactory.getErrorCodes(DataSource dataSource)

Return SQLErrorCodes for the given DataSource,
 evaluating "databaseProductName" from the
 DatabaseMetaData, or an empty error codes
 instance if no SQLErrorCodes were found.

SQLErrorCodes
SQLErrorCodesFactory.getErrorCodes(String databaseName)

Return the SQLErrorCodes instance for the given database.

SQLErrorCodes
SQLErrorCodeSQLExceptionTranslator.getSqlErrorCodes()

Return the error codes used by this translator.

SQLErrorCodes
SQLErrorCodesFactory.registerDatabase(DataSource dataSource,
                String databaseName)

Associate the specified database name with the given DataSource.

SQLErrorCodes
SQLErrorCodesFactory.unregisterDatabase(DataSource dataSource)

Clear the cache for the specified DataSource, if registered.

Methods in org.springframework.jdbc.support with parameters of type SQLErrorCodes

Modifier and Type
Method and Description

void
SQLErrorCodeSQLExceptionTranslator.setSqlErrorCodes(SQLErrorCodes sec)

Set custom error codes to be used for translation.

Constructors in org.springframework.jdbc.support with parameters of type SQLErrorCodes

Constructor and Description

SQLErrorCodeSQLExceptionTranslator(SQLErrorCodes sec)

Create an SQLErrorCode translator given these error codes.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
package mcjty.rftools.blocks.teleporter;

import mcjty.lib.container.EmptyContainer;
import mcjty.lib.container.GenericGuiContainer;
import mcjty.lib.gui.Window;
import mcjty.lib.gui.events.ButtonEvent;
import mcjty.lib.gui.events.ChoiceEvent;
import mcjty.lib.gui.events.TextEvent;
import mcjty.lib.gui.layout.HorizontalAlignment;
import mcjty.lib.gui.layout.HorizontalLayout;
import mcjty.lib.gui.layout.VerticalLayout;
import mcjty.lib.gui.widgets.Button;
import mcjty.lib.gui.widgets.*;
import mcjty.lib.gui.widgets.Label;
import mcjty.lib.gui.widgets.Panel;
import mcjty.lib.gui.widgets.TextField;
import mcjty.lib.network.Argument;
import mcjty.rftools.RFTools;
import mcjty.rftools.network.RFToolsMessages;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.input.Keyboard;

import java.awt.*;
import java.util.*;
import java.util.List;

public class GuiMatterReceiver extends GenericGuiContainer<MatterReceiverTileEntity> {
    public static final int MATTER_WIDTH = 180;
    public static final int MATTER_HEIGHT = 160;
    public static final String ACCESS_PRIVATE = "Private";
    public static final String ACCESS_PUBLIC = "Public";

    private EnergyBar energyBar;
    private ChoiceLabel privateSetting;
    private WidgetList allowedPlayers;
    private Button addButton;
    private Button delButton;
    private TextField nameField;

    // A copy of the players we're currently showing.
    private java.util.List<String> players = null;
    private int listDirty = 0;

    private static Set<String> fromServer_allowedPlayers = new HashSet<String>();
    public static void storeAllowedPlayersForClient(List<PlayerName> players) {
        Set<String> p = new HashSet<String>();
        for (PlayerName n : players) {
            p.add(n.getName());
        }
        fromServer_allowedPlayers = p;
    }

    public GuiMatterReceiver(MatterReceiverTileEntity matterReceiverTileEntity, EmptyContainer container) {
        super(RFTools.instance, RFToolsMessages.INSTANCE, matterReceiverTileEntity, container, RFTools.GUI_MANUAL_MAIN, "tpreceiver");
        matterReceiverTileEntity.setCurrentRF(matterReceiverTileEntity.getEnergyStored(ForgeDirection.DOWN));

        xSize = MATTER_WIDTH;
        ySize = MATTER_HEIGHT;
    }

    @Override
    public void initGui() {
        super.initGui();

        int maxEnergyStored = tileEntity.getMaxEnergyStored(ForgeDirection.DOWN);
        energyBar = new EnergyBar(mc, this).setFilledRectThickness(1).setHorizontal().setDesiredHeight(12).setDesiredWidth(MATTER_WIDTH-10).setMaxValue(maxEnergyStored).setShowText(true);
        energyBar.setValue(tileEntity.getCurrentRF());

        TextField textField = new TextField(mc, this).setTooltips("Use this name to", "identify this receiver", "in the dialer").addTextEvent(new TextEvent() {
            @Override
            public void textChanged(Widget parent, String newText) {
                setReceiverName(newText);
            }
        });
        textField.setText(tileEntity.getName());
        Panel namePanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(new Label(mc, this).setText("Name:")).addChild(textField).setDesiredHeight(16);

        privateSetting = new ChoiceLabel(mc, this).addChoices(ACCESS_PUBLIC, ACCESS_PRIVATE).setDesiredHeight(13).setDesiredWidth(60).
                setChoiceTooltip(ACCESS_PUBLIC, "Everyone can dial to this receiver").
                setChoiceTooltip(ACCESS_PRIVATE, "Only people in the access list below", "can dial to this receiver").
                addChoiceEvent(new ChoiceEvent() {
                    @Override
                    public void choiceChanged(Widget parent, String newChoice) {
                        changeAccessMode(newChoice);
                    }
                });
        if (tileEntity.isPrivateAccess()) {
            privateSetting.setChoice(ACCESS_PRIVATE);
        } else {
            privateSetting.setChoice(ACCESS_PUBLIC);
        }
        Panel privatePanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(new Label(mc, this).setText("Access:")).addChild(privateSetting).setDesiredHeight(16);

        allowedPlayers = createStyledList();
        Slider allowedPlayerSlider = new Slider(mc, this).setDesiredWidth(10).setVertical().setScrollable(allowedPlayers);
        Panel allowedPlayersPanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(allowedPlayers).addChild(allowedPlayerSlider);

        nameField = new TextField(mc, this);
        addButton = new Button(mc, this).setText("Add").setDesiredHeight(13).setDesiredWidth(34).setTooltips("Add a player to the access list").
                addButtonEvent(new ButtonEvent() {
                    @Override
                    public void buttonClicked(Widget parent) {
                        addPlayer();
                    }
                });
        delButton = new Button(mc, this).setText("Del").setDesiredHeight(13).setDesiredWidth(34).setTooltips("Remove the selected player", "from the access list").
                addButtonEvent(new ButtonEvent() {
                    @Override
                    public void buttonClicked(Widget parent) {
                        delPlayer();
                    }
                });
        Panel buttonPanel = new Panel(mc, this).setLayout(new HorizontalLayout()).addChild(nameField).addChild(addButton).addChild(delButton).setDesiredHeight(16);

        Widget toplevel = new Panel(mc, this).setFilledRectThickness(2).setLayout(new VerticalLayout().setHorizontalMargin(3).setVerticalMargin(3).setSpacing(1)).
                addChild(energyBar).addChild(namePanel).addChild(privatePanel).addChild(allowedPlayersPanel).addChild(buttonPanel);
        toplevel.setBounds(new Rectangle(guiLeft, guiTop, MATTER_WIDTH, MATTER_HEIGHT));
        window = new Window(this, toplevel);
        Keyboard.enableRepeatEvents(true);

        listDirty = 0;
        requestPlayers();
        tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE);
    }

    private void setReceiverName(String text) {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterReceiverTileEntity.CMD_SETNAME, new Argument("name", text));
    }

    private void changeAccessMode(String newAccess) {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterReceiverTileEntity.CMD_SETPRIVATE, new Argument("private", ACCESS_PRIVATE.equals(newAccess)));
    }

    private void addPlayer() {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterReceiverTileEntity.CMD_ADDPLAYER, new Argument("player", nameField.getText()));
        listDirty = 0;
    }

    private void delPlayer() {
        sendServerCommand(RFToolsMessages.INSTANCE, MatterReceiverTileEntity.CMD_DELPLAYER, new Argument("player", players.get(allowedPlayers.getSelected())));
        listDirty = 0;
    }

    private void requestPlayers() {
        RFToolsMessages.INSTANCE.sendToServer(new PacketGetPlayers(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, MatterReceiverTileEntity.CMD_GETPLAYERS, MatterReceiverTileEntity.CLIENTCMD_GETPLAYERS));
    }

    private void populatePlayers() {
        List<String> newPlayers = new ArrayList<String>(fromServer_allowedPlayers);
        Collections.sort(newPlayers);
        if (newPlayers.equals(players)) {
            return;
        }

        players = new ArrayList<String>(newPlayers);
        allowedPlayers.removeChildren();
        for (String player : players) {
            allowedPlayers.addChild(new Label(mc, this).setText(player).setHorizontalAlignment(HorizontalAlignment.ALIGH_LEFT));
        }
    }

    private void requestListsIfNeeded() {
        listDirty--;
        if (listDirty <= 0) {
            requestPlayers();
            listDirty = 20;
        }
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) {
        requestListsIfNeeded();
        populatePlayers();
        enableButtons();

        drawWindow();
        int currentRF = tileEntity.getCurrentRF();
        energyBar.setValue(currentRF);
        tileEntity.requestRfFromServer(RFToolsMessages.INSTANCE);
    }

    private void enableButtons() {
        boolean isPrivate = ACCESS_PRIVATE.equals(privateSetting.getCurrentChoice());
        allowedPlayers.setEnabled(isPrivate);
        nameField.setEnabled(isPrivate);

        int isPlayerSelected = allowedPlayers.getSelected();
        delButton.setEnabled(isPrivate && (isPlayerSelected != -1));
        String name = nameField.getText();
        addButton.setEnabled(isPrivate && name != null && !name.isEmpty());
    }
}


text:
"""DNS TTL conversion."""

import dns.exception

class BadTTL(dns.exception.SyntaxError):
    pass

def from_text(text):
    """Convert the text form of a TTL to an integer.

    The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.

    @param text: the textual TTL
    @type text: string
    @raises dns.ttl.BadTTL: the TTL is not well-formed
    @rtype: int
    """

    if text.isdigit():
        total = long(text)
    else:
        if not text[0].isdigit():
            raise BadTTL
        total = 0L
        current = 0L
        for c in text:
            if c.isdigit():
                current *= 10
                current += long(c)
            else:
                c = c.lower()
                if c == 'w':
                    total += current * 604800L
                elif c == 'd':
                    total += current * 86400L
                elif c == 'h':
                    total += current * 3600L
                elif c == 'm':
                    total += current * 60L
                elif c == 's':
                    total += current
                else:
                    raise BadTTL("unknown unit '%s'" % c)
                current = 0
        if not current == 0:
            raise BadTTL("trailing integer")
    if total < 0L or total > 2147483647L:
        raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
    return total


text:
/*jslint plusplus: true, indent: 2, maxerr: 500 */
/*global setTimeout, importScripts, require, sudoku_solver, addEventListener, postMessage */

importScripts("../lib/requirejs/require.js");
require.config({
  paths: {
    "angular": "../lib/angular/angular",
    "ngroute": "../lib/angular-route/angular-route",
    "ngtouch": "../lib/angular-touch/angular-touch.min",
    "ngbootstrap": "../lib/angular-bootstrap/ui-bootstrap.min",
    "ngbootstrap-tpls": "../lib/angular-bootstrap/ui-bootstrap-tpls.min",
    "jquery": "../lib/jquery/jquery",
    "bootstrap.modal": "../lib/bootstrap/js/modal",
    "bootstrap.collapse": "../lib/bootstrap/js/collapse",
    "kudoku": "../lib/kudoku",
    "sheetrock": "../lib/jquery-sheetrock/src/jquery.sheetrock",
    "underscore": "../lib/underscore/underscore-min"
  },

  shim: {
    "angular": {
      exports: "angular"
    },
    "ngtouch": ['angular'],
    "ngbootstrap": ['angular'],
    "ngbootstrap-tpls": ['angular'],
    "ngroute": ['angular'],
    "bootstrap.modal": ['jquery'],
    "bootstrap.collapse": ['jquery'],
    "sudokuUtils": {
      exports: "sudoku"
    },
    "underscore": {
      exports: "_"
    }
  }
});

require(
  {baseUrl: "./"},
  ["require", "../lib/kudoku", "sudokuUtils", "sudokuSolver"],
  function (require, kudoku, sudoku, Solver) {
    "use strict";
    var self = this || {};
    self.solver = sudoku_solver();
    self.utils = sudoku.utils;
    self.running = true;

    self.correct = function (board) {
      return self.utils.correct(board);
    };

    self.fillRestOfBoard = function (board) {
      var solstr, solarr, row, column,
        array = [],
        tempBoard = [];

      for (row = 0; row < 9; row++) {
        array = array.concat(board[row].slice(0));
      }

      array = array.toString().replace(/,/g, "").replace(/0/g, ".");
      solarr = self.solver(array, 1);

      if(solarr.length === 0){
        return board;
      }

      for (row = 0; row < 9; row++) {
        for (column = 0; column < 9; column++) {
          board[row][column] = solarr[0][row * 9 + column];
        }
      }

      return board;
    };

    self.numberOfSolutionsMaxTwo = function (board) {
      var solstr, solarr, row, column,
        array = [],
        tempBoard = [];

      for (row = 0; row < 9; row++) {
        array = array.concat(board[row].slice(0));
      }

      array = array.toString().replace(/,/g, "").replace(/0/g, ".");
      solarr = self.solver(array, 2);

      return solarr.length;
    };

    self.digHoles = function (board, number, x, y, mult) {
      var nextmult, oldVal = board[x][y],
        nexty = y,
        nextx = x,
        nextnum = number - 1;

      nexty = mult ? nexty - 1 : nexty + 1;

      if (number < 1) {
        return true;
      }

      if (nexty > 8) {
        nexty = mult ? 8 : 0;
        nextmult = !mult;
        nextx++;
        if (nextx > 8) {
          return true;
        }
      }

      board[x][y] = 0;
      if (self.numberOfSolutionsMaxTwo(board) !== 1) {
        board[x][y] = oldVal;
        return false;
      }
      while (self.digHoles(board, nextnum, nextx, nexty, mult) === false) {
        nexty++;
        if (nexty > 8) {
          nexty = 0;
          nextx++;
          if (nextx > 8) {
            return true;
          }
        }
      }
      return true;
    };

    self.generate = function (numberToRemove) {
      var row, col, cell,
        correctBoard = [],
        board = [[], [], [], [], [], [], [], [], []],
        difficulty = 10;

      for (row = 0; row < 9; row++) {
        for (col = 0; col < 9; col++) {
          board[row][col] = 0;
        }
      }

      for (cell = 0; cell < 12; cell++) {
        row = Math.floor((Math.random() * 9));
        col = Math.floor((Math.random() * 9));
        board[row][col] = Math.floor((Math.random() * 9) + 1);
        if (!self.correct(board) || self.numberOfSolutionsMaxTwo(board) < 1) {
          board[row][col] = 0;
          cell--;
        }
      }
      self.fillRestOfBoard(board);

      for (row = 0; row < 9; row++) {
        correctBoard[row] = board[row].slice(0);
      }

      self.digHoles(board, 81, 0, 0, false);

      return {"board": board, "correctBoard": correctBoard};
    };

    self.rate = function (board, original) {
      var solver = new Solver(board, original);
      return solver.rate(board, original);
    };

    self.humanSolve = function (board, original, messages) {
      var solver = new Solver(board, original);
      return solver.humanSolve({
        board: board,
        correct: original,
        rate: false,
        messageCallback: function (message) {
          messages.push(message);
        }
      });
    };

    self.generateLots = function () {
      while (true) {
        var message = self.generate(10),
            rateBoard = [];
        for (var i = 0; i < 9; i++) {
          rateBoard[i] = message.board[i].slice();
        }
        message.rating = self.rate(rateBoard, message.correctBoard);
        postMessage(message);
      }
    };

    self.generatePencils = function (board) {
      return this.utils.generatePencils(board);
    };

    addEventListener("message", function (event) {
      var board, pencils;
      switch (event.data.command) {
      case "generate":
        board = self.generate(10);
        postMessage(board);
        break;
      case "possibilities":
        pencils = self.generatePencils(event.data.board);
        postMessage(pencils);
        break;
      case "correct":
        postMessage(self.correct(event.data.board));
        break;
      case "humanSolve":
        var messages = [],
            finalBoard = self.humanSolve(event.data.board, event.data.original, messages);
        postMessage({message: "finished", board: finalBoard, messages: messages});
        break;
      case "solve":
        postMessage(self.fillRestOfBoard(event.data.board));
        break;
      case "rate":
        postMessage(self.rate(event.data.board, event.data.original));
        break;
      case "generateLots":
        self.generateLots();
        break;
      }
    });

    postMessage("Ready");
  }
);


text:
package io.github.ageofwar.telejam.users;

import com.google.gson.annotations.SerializedName;
import io.github.ageofwar.telejam.TelegramObject;
import io.github.ageofwar.telejam.media.PhotoSize;

import java.util.Arrays;
import java.util.Objects;

/**
 * This object represent a user's profile pictures.
 *
 * @author Michi Palazzo
 */
public class UserProfilePhotos implements TelegramObject {

  static final String TOTAL_COUNT_FIELD = "total_count";
  static final String PHOTOS_FIELD = "photos";

  /**
   * Total number of profile pictures the target user has.
   */
  @SerializedName(TOTAL_COUNT_FIELD)
  private final int totalCount;

  /**
   * Requested profile pictures (in up to 4 sizes each).
   */
  @SerializedName(PHOTOS_FIELD)
  private final PhotoSize[][] photos;

  public UserProfilePhotos(int totalCount, PhotoSize[][] photos) {
    this.totalCount = totalCount;
    this.photos = Objects.requireNonNull(photos);
  }

  /**
   * Getter for property {@link #totalCount}.
   *
   * @return value for property {@link #totalCount}
   */
  public int getTotalCount() {
    return totalCount;
  }

  /**
   * Getter for property {@link #photos}.
   *
   * @return value for property {@link #photos}
   */
  public PhotoSize[][] getPhotos() {
    return photos;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (!(obj instanceof UserProfilePhotos)) {
      return false;
    }

    UserProfilePhotos userProfilePhotos = (UserProfilePhotos) obj;
    return totalCount == userProfilePhotos.totalCount &&
        Arrays.deepEquals(photos, userProfilePhotos.getPhotos());
  }

  @Override
  public int hashCode() {
    return 31 * totalCount + Arrays.deepHashCode(photos);
  }

}


text:
package dummyentities;

/**
 * @author hsommer Apr 7, 2003 11:05:04 AM
 */
public class ObsProposal
{

	/**
	 *
	 */
	public ObsProposal()
	{
		super();
		// TODO Auto-generated constructor stub
	}

}


text:
"""
law workflow mechanism.
"""


text:
import conf
import g

import copy
import os
import sys

from item.util.item_type import Item_Type

__all__ = ['Job_Base',]

log = g.log.getLogger('job_base')

class Job_Base(object):

   # NOTE: Skipping __slots__, other cPickle will complain,
   # TypeError: a class that defines __slots__ without defining
   #            __getstate__ cannot be pickled.
   # But if you define __getstate__, you have to do the pickling yourself,
   # which seems like it defeats the purpose of using cPickle.

   # Base class overrides

   item_type_id = Item_Type.JOB_BASE
   item_type_table = 'job_base'
   #item_gwis_abbrev = 'jbas'
   child_item_types = None

   #
   def __init__(self, viewport, filters):
      log.debug('job_base: __init__')

      # We want to pickle the viewport and filters, but we cannot pickle a
      # class that defines __slots__ (that is, unless we also define
      # __getstate__, but I haven't got that to work). Neither viewport nor
      # filters define slots, but they do maintain a reference to the request
      # object, which does define slots, and also which we don't need to ref.
      #
      # FIXME: 2012.03.23: I don't think we should attach viewport and filters
      # to job, but should just make what we care about attributes of the job.
      self.viewport = copy.copy(viewport)
      self.viewport.req = None
      self.filters = copy.copy(filters)
      self.filters.req = None

   #
   def re_init(self):
      # NOTE: Nothing to do currently. If the job def changes, this fcn. should
      # make sure that what is stored in the database gets hydrated correctly
      # into the new job def.
      # NOTE: See Query_Filters.fix_missing() for an example.
      self.filters.fix_missing()
      pass

   #
   def __eq__(self, other):
      log.verbose('job_base: checking __eq__...')
      log.verbose('  id(self): %d' % (id(self),))
      log.verbose('  id(other): %d' % (id(other),))
      log.verbose('  self.viewport: %s' % (self.viewport,))
      log.verbose('  other.viewport: %s' % (other.viewport,))
      log.verbose('  self.filters: %s' % (self.filters,))
      log.verbose('  other.filters: %s' % (other.filters,))
      return (   (self.viewport == other.viewport)
              and (self.filters == other.filters))

   #
   def __ne__(self, other):
      return not self.__eq__(other)

   # ***

# ***

class Callback_Def_Base(object):

   # NOTE: Skipping __slots__, other cPickle will complain,
   # TypeError: a class that defines __slots__ without defining
   #            __getstate__ cannot be pickled.
   # But if you define __getstate__, you have to do the pickling yourself,
   # which seems like it defeats the purpose of using cPickle.

   #
   def __init__(self):
      log.debug('callback_def_base: __init__')

   #
   def re_init(self):
      # NOTE: Nothing to do currently. If the callback def changes, this fcn.
      # should make sure that what is stored in the database gets hydrated
      # correctly into the new callback def.
      # NOTE: See Query_Filters.fix_missing() for an example.
      pass

   #
   def __eq__(self, other):
      log.verbose('callback_def_base: checking __eq__...')
      log.verbose('  id(self): %d' % (id(self),))
      log.verbose('  id(other): %d' % (id(other),))
      return (id(self) == id(other))

   #
   def __ne__(self, other):
      return not self.__eq__(other)

   # ***

# ***


text:
Spillman/Ctree SQL Examples
===========================

Query Date Range
---------------

```sql
select "number",securid FROM lwmain where dtrepor BETWEEN '2016-01-30 00:00:00' and '2016-01-31 00:00:00';
```

Timestamp to Date Casting
-------------------------

```sql
select count(*),cast(towdate as date) as tow_on from vimain group by cast(towdate as date) order by tow_on desc;
```

Evidence with Float Quantity
----------------------------

```sql
select
"number", lctn, incino, item, pmodel, serial,meas,CAST(quant AS CHAR(10)) as qty
FROM evmain
WHERE addwhen > '1/1/2016'
AND status = 'ACT'
AND lctn in ('GB','G01','G02','G03','GS','SAFEA','SAFEB','NARC');
```

Hierarchy of Offense/Charge
---------------------------

Goal: Find highest offense.

```sql
select distinct
l."number",
o.offcode,
t.action
FROM lwmain l
JOIN lwoffs o ON o."number" = l."number"
JOIN tboff t ON o.offcode = t.abbr
WHERE l."number" like ' 160002%'
AND NOT EXISTS (SELECT 1 FROM lwoffs o1
  JOIN tboff t1 ON o1.offcode = t1.abbr
  WHERE o1."number" = l."number"
  AND t1.action > t.action
);
```

Goal: list offenses by rank.

```sql
select distinct
l."number",
s.statute,
t.action
FROM lwmain l
JOIN lwstatut s ON s."number" = l."number"
JOIN tblaw c ON c.abbr = s.statute
JOIN tboff t ON t.abbr = c.offense
WHERE l."number" = ' 16024520'
ORDER BY t.action DESC;

NUMBER       STATUTE                        ACTION
------       -------                        ------
 16024520    470 (D) PC FEL                     29
 16024520    484 I(C) PC FEL                    29
 16024520    11357 (A) HS MIS                   20
 16024520    11364 (A) HS                       16
 16024520    11350 (A) HS MIS                   14
 16024520    11377 (A) HS MIS                   14
 16024520    475 (A) PC FEL                      0
 16024520    529 (A)(3) PC FEL                   0
8 records selected
```

Goal: list charge codes by rank

```sql
select distinct
l."number",
o.offcode,
t.action
FROM lwmain l
JOIN lwoffs o ON o."number" = l."number"
JOIN tboff t ON o.offcode = t.abbr
WHERE l."number" = ' 16024520'
ORDER BY t.action DESC
;
```

List Arrests with name record
-----------------------------

Link by syinvolv

```sql
SELECT lawnum,
inmate,n."number" as name,counts,statute
FROM jloffens j
JOIN syinvolv i ON i.rec = j.num
JOIN nmmain n ON i.relrec = n."number"
WHERE i.typ = 750 and reltyp = 900
AND lawnum = ' 15091929'
;
```

Link by jlinmate

```sql
SELECT lawnum,
inmate,n."number" as name,counts,statute
FROM jloffens j
JOIN jlinmate i ON i."num" = j.inmate
JOIN nmmain n ON i.namenum = n."number"
AND lawnum = ' 15091929'
;
```
Last 8 days of Deleted lwsupl's
-------------------------------

```sql
SELECT usrid,"date",misc
FROM sylog
WHERE tablnam = 'lwsupl'
AND "mode" = 'D'
AND "date" > TIMESTAMPADD(SQL_TSI_DAY,-8,systime)
ORDER BY "date" desc;
```

Activity for a Month
--------------------

```sql
SELECT
l."number" as dr,
s.statute,
z."desc" as beat,
locatn,
address,
dtrepor,
ocurdt1,
ocurdt2,
ccode
FROM lwmain l
JOIN lwstatut s ON l."number" = s."number"
JOIN tbzones z ON l.locatn = z.abbr
WHERE dtrepor BETWEEN '2016-03-01 00:00:00' AND '2016-04-01 00:00:00'
AND ccode IN ('6X','7X','8X')
ORDER BY statute,dr desc
;
```

Count of Statutes in 16-17 Law Incidents
----------------------------------------

```sql
SELECT * from (SELECT count(1) as cnt,o.statute
FROM lwmain l
JOIN lwstatut o ON o."number" = l."number"
WHERE l."number" LIKE ' 16%' OR l."number" LIKE ' 16%'
GROUP BY o.statute
ORDER BY count(1) DESC
) s WHERE cnt > 20
;
```

Juvie Arrests
-------------

```sql
SELECT j.lawnum,
         n.birthd, CONVERT(SQL_DATE,j."date") as chg_date,
         (CONVERT(SQL_DATE,j."date") - n.birthd)/365.25 as age
         FROM jloffens j
         JOIN syinvolv i ON i.rec = j.num
         JOIN nmmain n ON i.relrec = n."number"
         WHERE i.typ = 750
         AND reltyp = 900
         AND (CONVERT(SQL_DATE,j."date") - n.birthd)/365.25 < 18

```

Injunction Offenders with Involvements in last 90 days
-----------------------------------------------------

```sql
select rec,relship,"date",(TRIM(n.last)||', '||TRIM(n.first)) as name
FROM syinvolv i
JOIN nmmain n ON i.relrec = n."number"
AND i.reltyp = 900
AND i."date" > CURRENT_DATE - 90
WHERE n."number" IN (SELECT namenum FROM somain WHERE type = 'INJ')
;
```

Names with Gang Alerts with Involvements in last 90 days
--------------------------------------------------------

```sql
SELECT TRIM(rec) as rec_num,
  TRIM(relship) as relship,
  TRIM(TO_CHAR(i."date",'DD/MM/YY') as "date",
  TRIM(TRIM(n.last)||', '||TRIM(n.first)) as name,
  TRIM(TO_CHAR(n.birthd,'DD/MM/YY')) as dob
FROM syinvolv i
JOIN nmmain n ON i.relrec = n."number"
AND i.reltyp = 900
AND i."date" > CURRENT_DATE - 90
WHERE n."number" IN (SELECT "number" FROM nmalert WHERE code = 'GANG')
ORDER BY i."date" DESC
;
```

Counts of partitions, not complete
----------------------------------

```sql
SELECT
COUNT(*) as cnt,
TRIM(securid) as securid
from lwmain
WHERE securid like '"%'
AND LOWER(securid) NOT like '"cmplt'
GROUP BY TRIM(securid)
ORDER BY securid
```

Clean workflow for no report dispos
-----------------------------------

```sql
SELECT "number"
        FROM lwmain
        WHERE ccode = '2X'
        AND dispos <> '2X'
        AND NOT EXISTS (SELECT 1 FROM lwsupl WHERE "number" = lwmain."number")
        AND modwhen < TIMESTAMPADD(SQL_TSI_HOUR,-2,systime);
-- remove status lines
DELETE  FROM wfstat WHERE "number" IN (SELECT "number" FROM wfmain WHERE rkeyval in (SELECT "number" FROM lwmain  WHERE ccode = '2X'
        AND dispos <> '2X'
        AND NOT EXISTS (SELECT 1 FROM lwsupl WHERE "number" = lwmain."number")
        AND modwhen < TIMESTAMPADD(SQL_TSI_HOUR,-2,systime)
        ));
-- remove wfmain
DELETE FROM wfmain WHERE rkeyval IN (SELECT "number" FROM lwmain  WHERE ccode = '2X'
        AND dispos <> '2X'
        AND NOT EXISTS (SELECT 1 FROM lwsupl WHERE "number" = lwmain."number")
        AND modwhen < TIMESTAMPADD(SQL_TSI_HOUR,-2,systime)
        );
-- set 2x dispos to '2x' for '2x' ccodes
UPDATE lwmain SET dispos = '2X' WHERE ccode = '2X' AND dispos <> '2X'
AND NOT EXISTS (SELECT 1 FROM lwsupl WHERE "number" = lwmain."number")
AND modwhen < TIMESTAMPADD(SQL_TSI_HOUR,-2,systime);
COMMIT;
```


text:
import React from 'react';
import cn from 'classnames';

import Paragraph from './components/Paragraph';
import MusicTrigger from './components/MusicTrigger';

import part1 from './content/1-1';

const Chapter1 = () => {
  const insideClass = cn(
    'col-xs',
    'col-sm',
    'col-md',
    'col-lg',
  );
  return (

        <Paragraph
          text={"第一章"}
          textAlign="center"
          verticalAlign="middle"
          height="100vh"
          fontSize="3em"
        />
        <Paragraph
          text={"(滾到這裡開始有音效)"}
          textAlign="center"
          fontSize="1em"
        />
        <MusicTrigger
          musicSrc="https://s3-ap-southeast-1.amazonaws.com/novel-videos/wave.mp3"
          volume={0.5}
          playing={true}
          fadeInDUration={10000}
          soundRemainPx="-200px"
        />
        <Paragraph
          text={part1}
          fontSize="1em"
        />

  );
};

export default Chapter1;


text:
TextureVault::TextureVault(SDL_Renderer *p_Renderer, unsigned long p_ulExpirationTime, unsigned long p_ulAutoFreeTime)
    :m_vTextures(), m_pRenderer(p_Renderer), m_ulExpirationTime(p_ulExpirationTime) {

    if (p_ulAutoFreeTime > 0) SetAutoFree(p_ulAutoFreeTime);
}

TextureVault::~TextureVault() {
    StopAutoFree();
    for (auto t_Entry : m_vTextures)
        SDL_DestroyTexture( *(t_Entry.m_pData) );
}

std::shared_ptr<SDL_Texture*> TextureVault::GetTexture(std::string p_sPath) {
    if (!m_pRenderer) return std::shared_ptr<SDL_Texture*>();

    for (auto t_Entry : m_vTextures)
        if (t_Entry.m_sPath == p_sPath) {
            t_Entry.m_ulExpiring = 0;
            return std::shared_ptr<SDL_Texture*>(t_Entry.m_pData);
        }

    //Reaching here means the texture was not previously loaded.

    //Loads the Texture using the LoadTexture helper function.
    SDL_Texture* t_pTexture = LoadTexture(p_sPath.c_str());
    //If LoadTexture returns NULL, we couldn't load the Texture.
    //An invalid entry is then returned.
    if (t_pTexture  == NULL) return std::shared_ptr<SDL_Texture*>();
    //Otherwise, it was successfully loaded.

    //Returns the entry, with the strong reference.
    return PushNewTexture(t_pTexture, p_sPath);
}

std::shared_ptr<SDL_Texture*> TextureVault::PushNewTexture(SDL_Texture* p_pTexture, std::string p_sPath) {
    //Sets the path into our texture entry.
    TEntry t_TextureEntry(p_sPath);
    //Sets the strong reference (shared_ptr).
    t_TextureEntry.m_pData = std::make_shared<SDL_Texture*>(p_pTexture);

    //Pushes it into the vector.
    m_vTextures.push_back(t_TextureEntry);

    //Returns the entry, with the strong reference.
    return std::shared_ptr<SDL_Texture*>(t_TextureEntry.m_pData);
}

SDL_Texture* TextureVault::CheckTexture(std::string p_sPath) {
    for (auto t_Entry : m_vTextures)
        if (t_Entry.m_sPath == p_sPath)
            return *(t_Entry.m_pData);
    return NULL; //Not Found.
    //This function won't load the texture if it was not found.
}

bool TextureVault::FreeUnused() {
    bool t_bFreedSomething = false;

    for (auto t_Entry = m_vTextures.begin(); t_Entry < m_vTextures.end(); ++t_Entry) {
        if ( t_Entry->m_pData.unique() ) {
            if (t_Entry->m_ulExpiring == 0)
                t_Entry->m_ulExpiring = SDL_GetTicks();
            if (SDL_GetTicks()-t_Entry->m_ulExpiring >= m_ulExpirationTime) {
                FreeTexture( &*t_Entry );
                m_vTextures.erase(t_Entry);
                t_bFreedSomething = true;
            }
        }
    }

    return t_bFreedSomething;
}

void TextureVault::Purge() {
    for (auto t_Entry : m_vTextures)
        SDL_DestroyTexture( *(t_Entry.m_pData) );
    m_vTextures.clear();
}

SDL_Texture* TextureVault::LoadTexture (const char* p_pcPath) {
    //Load the texture
    SDL_Surface* t_pSurface = IMG_Load(p_pcPath);
    if (t_pSurface == NULL) return NULL;

    SDL_Texture* t_pRetTexture = SDL_CreateTextureFromSurface(m_pRenderer, t_pSurface);

    SDL_FreeSurface(t_pSurface);

    return t_pRetTexture;
}

unsigned int TextureVault::TimedFreeUnused(unsigned int, void* p_TexVault) {
    ((TextureVault*)p_TexVault)->FreeUnused();
    return 0;
}

void TextureVault::SetAutoFree(unsigned long p_ulTimeMS) {
    if(m_TimerID != 0) StopAutoFree();
    if (p_ulTimeMS == 0) return;
    m_TimerID = SDL_AddTimer(p_ulTimeMS, TextureVault::TimedFreeUnused, this);
}

void TextureVault::StopAutoFree() {
    if (m_TimerID != 0){
        SDL_RemoveTimer(m_TimerID);
        m_TimerID = 0;
    }
}


text:
package uk.gov.gds.ier.validation

object TelephoneValidator {

  val telephoneRegex = "^[0-9]{5,30}$"

  def isValid(telephone: String) = {
    telephone.replaceAll("[\\s\\+\\-\\_\\(\\)\\[A-Za-z]", "").matches(telephoneRegex)
  }
}


text:
class PledgeSurveyResponse < ApplicationRecord
  belongs_to :person
  belongs_to :reward
  has_one :fundraiser, through: :reward

  validates :person, presence: true
  validates :reward, presence: true

end


text:
package discovery

import (
	"encoding/json"
	"fmt"
	"mime"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"
	"time"

	"github.com/gogo/protobuf/proto"
	openapi_v2 "github.com/google/gnostic/openapiv2"
	openapi_v3 "github.com/google/gnostic/openapiv3"
	"github.com/stretchr/testify/assert"
	golangproto "google.golang.org/protobuf/proto"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/diff"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/version"
	restclient "k8s.io/client-go/rest"
	testutil "k8s.io/client-go/util/testing"
)

func TestGetServerVersion(t *testing.T) {
	expect := version.Info{
		Major:     "foo",
		Minor:     "bar",
		GitCommit: "baz",
	}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		output, err := json.Marshal(expect)
		if err != nil {
			t.Errorf("unexpected encoding error: %v", err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))
	defer server.Close()
	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})

	got, err := client.ServerVersion()
	if err != nil {
		t.Fatalf("unexpected encoding error: %v", err)
	}
	if e, a := expect, *got; !reflect.DeepEqual(e, a) {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestGetServerGroupsWithV1Server(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var obj interface{}
		switch req.URL.Path {
		case "/api":
			obj = &metav1.APIVersions{
				Versions: []string{
					"v1",
				},
			}
		case "/apis":
			obj = &metav1.APIGroupList{
				Groups: []metav1.APIGroup{
					{
						Name: "extensions",
						Versions: []metav1.GroupVersionForDiscovery{
							{GroupVersion: "extensions/v1beta1"},
						},
					},
				},
			}
		default:
			w.WriteHeader(http.StatusNotFound)
			return
		}
		output, err := json.Marshal(obj)
		if err != nil {
			t.Fatalf("unexpected encoding error: %v", err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))
	defer server.Close()
	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	// ServerGroups should not return an error even if server returns error at /api and /apis
	apiGroupList, err := client.ServerGroups()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	groupVersions := metav1.ExtractGroupVersions(apiGroupList)
	if !reflect.DeepEqual(groupVersions, []string{"v1", "extensions/v1beta1"}) {
		t.Errorf("expected: %q, got: %q", []string{"v1", "extensions/v1beta1"}, groupVersions)
	}
}

func TestGetServerGroupsWithBrokenServer(t *testing.T) {
	for _, statusCode := range []int{http.StatusNotFound, http.StatusForbidden} {
		server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			w.WriteHeader(statusCode)
		}))
		defer server.Close()
		client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
		// ServerGroups should not return an error even if server returns Not Found or Forbidden error at all end points
		apiGroupList, err := client.ServerGroups()
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		groupVersions := metav1.ExtractGroupVersions(apiGroupList)
		if len(groupVersions) != 0 {
			t.Errorf("expected empty list, got: %q", groupVersions)
		}
	}
}

func TestTimeoutIsSet(t *testing.T) {
	cfg := &restclient.Config{}
	setDiscoveryDefaults(cfg)
	assert.Equal(t, defaultTimeout, cfg.Timeout)
}

func TestGetServerResourcesWithV1Server(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var obj interface{}
		switch req.URL.Path {
		case "/api":
			obj = &metav1.APIVersions{
				Versions: []string{
					"v1",
				},
			}
		default:
			w.WriteHeader(http.StatusNotFound)
			return
		}
		output, err := json.Marshal(obj)
		if err != nil {
			t.Errorf("unexpected encoding error: %v", err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))
	defer server.Close()
	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	// ServerResources should not return an error even if server returns error at /api/v1.
	_, serverResources, err := client.ServerGroupsAndResources()
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	gvs := groupVersions(serverResources)
	if !sets.NewString(gvs...).Has("v1") {
		t.Errorf("missing v1 in resource list: %v", serverResources)
	}
}

func TestGetServerResourcesForGroupVersion(t *testing.T) {
	stable := metav1.APIResourceList{
		GroupVersion: "v1",
		APIResources: []metav1.APIResource{
			{Name: "pods", Namespaced: true, Kind: "Pod"},
			{Name: "services", Namespaced: true, Kind: "Service"},
			{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
		},
	}
	beta := metav1.APIResourceList{
		GroupVersion: "extensions/v1beta1",
		APIResources: []metav1.APIResource{
			{Name: "deployments", Namespaced: true, Kind: "Deployment"},
			{Name: "ingresses", Namespaced: true, Kind: "Ingress"},
			{Name: "jobs", Namespaced: true, Kind: "Job"},
		},
	}
	beta2 := metav1.APIResourceList{
		GroupVersion: "extensions/v1beta2",
		APIResources: []metav1.APIResource{
			{Name: "deployments", Namespaced: true, Kind: "Deployment"},
			{Name: "ingresses", Namespaced: true, Kind: "Ingress"},
			{Name: "jobs", Namespaced: true, Kind: "Job"},
		},
	}
	extensionsbeta3 := metav1.APIResourceList{GroupVersion: "extensions/v1beta3", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta4 := metav1.APIResourceList{GroupVersion: "extensions/v1beta4", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta5 := metav1.APIResourceList{GroupVersion: "extensions/v1beta5", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta6 := metav1.APIResourceList{GroupVersion: "extensions/v1beta6", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta7 := metav1.APIResourceList{GroupVersion: "extensions/v1beta7", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta8 := metav1.APIResourceList{GroupVersion: "extensions/v1beta8", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta9 := metav1.APIResourceList{GroupVersion: "extensions/v1beta9", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	extensionsbeta10 := metav1.APIResourceList{GroupVersion: "extensions/v1beta10", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}

	appsbeta1 := metav1.APIResourceList{GroupVersion: "apps/v1beta1", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta2 := metav1.APIResourceList{GroupVersion: "apps/v1beta2", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta3 := metav1.APIResourceList{GroupVersion: "apps/v1beta3", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta4 := metav1.APIResourceList{GroupVersion: "apps/v1beta4", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta5 := metav1.APIResourceList{GroupVersion: "apps/v1beta5", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta6 := metav1.APIResourceList{GroupVersion: "apps/v1beta6", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta7 := metav1.APIResourceList{GroupVersion: "apps/v1beta7", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta8 := metav1.APIResourceList{GroupVersion: "apps/v1beta8", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta9 := metav1.APIResourceList{GroupVersion: "apps/v1beta9", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}
	appsbeta10 := metav1.APIResourceList{GroupVersion: "apps/v1beta10", APIResources: []metav1.APIResource{{Name: "deployments", Namespaced: true, Kind: "Deployment"}}}

	tests := []struct {
		resourcesList *metav1.APIResourceList
		path          string
		request       string
		expectErr     bool
	}{
		{
			resourcesList: &stable,
			path:          "/api/v1",
			request:       "v1",
			expectErr:     false,
		},
		{
			resourcesList: &beta,
			path:          "/apis/extensions/v1beta1",
			request:       "extensions/v1beta1",
			expectErr:     false,
		},
		{
			resourcesList: &stable,
			path:          "/api/v1",
			request:       "foobar",
			expectErr:     true,
		},
	}
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var list interface{}
		switch req.URL.Path {
		case "/api/v1":
			list = &stable
		case "/apis/extensions/v1beta1":
			list = &beta
		case "/apis/extensions/v1beta2":
			list = &beta2
		case "/apis/extensions/v1beta3":
			list = &extensionsbeta3
		case "/apis/extensions/v1beta4":
			list = &extensionsbeta4
		case "/apis/extensions/v1beta5":
			list = &extensionsbeta5
		case "/apis/extensions/v1beta6":
			list = &extensionsbeta6
		case "/apis/extensions/v1beta7":
			list = &extensionsbeta7
		case "/apis/extensions/v1beta8":
			list = &extensionsbeta8
		case "/apis/extensions/v1beta9":
			list = &extensionsbeta9
		case "/apis/extensions/v1beta10":
			list = &extensionsbeta10
		case "/apis/apps/v1beta1":
			list = &appsbeta1
		case "/apis/apps/v1beta2":
			list = &appsbeta2
		case "/apis/apps/v1beta3":
			list = &appsbeta3
		case "/apis/apps/v1beta4":
			list = &appsbeta4
		case "/apis/apps/v1beta5":
			list = &appsbeta5
		case "/apis/apps/v1beta6":
			list = &appsbeta6
		case "/apis/apps/v1beta7":
			list = &appsbeta7
		case "/apis/apps/v1beta8":
			list = &appsbeta8
		case "/apis/apps/v1beta9":
			list = &appsbeta9
		case "/apis/apps/v1beta10":
			list = &appsbeta10
		case "/api":
			list = &metav1.APIVersions{
				Versions: []string{
					"v1",
				},
			}
		case "/apis":
			list = &metav1.APIGroupList{
				Groups: []metav1.APIGroup{
					{
						Name: "apps",
						Versions: []metav1.GroupVersionForDiscovery{
							{GroupVersion: "apps/v1beta1", Version: "v1beta1"},
							{GroupVersion: "apps/v1beta2", Version: "v1beta2"},
							{GroupVersion: "apps/v1beta3", Version: "v1beta3"},
							{GroupVersion: "apps/v1beta4", Version: "v1beta4"},
							{GroupVersion: "apps/v1beta5", Version: "v1beta5"},
							{GroupVersion: "apps/v1beta6", Version: "v1beta6"},
							{GroupVersion: "apps/v1beta7", Version: "v1beta7"},
							{GroupVersion: "apps/v1beta8", Version: "v1beta8"},
							{GroupVersion: "apps/v1beta9", Version: "v1beta9"},
							{GroupVersion: "apps/v1beta10", Version: "v1beta10"},
						},
					},
					{
						Name: "extensions",
						Versions: []metav1.GroupVersionForDiscovery{
							{GroupVersion: "extensions/v1beta1", Version: "v1beta1"},
							{GroupVersion: "extensions/v1beta2", Version: "v1beta2"},
							{GroupVersion: "extensions/v1beta3", Version: "v1beta3"},
							{GroupVersion: "extensions/v1beta4", Version: "v1beta4"},
							{GroupVersion: "extensions/v1beta5", Version: "v1beta5"},
							{GroupVersion: "extensions/v1beta6", Version: "v1beta6"},
							{GroupVersion: "extensions/v1beta7", Version: "v1beta7"},
							{GroupVersion: "extensions/v1beta8", Version: "v1beta8"},
							{GroupVersion: "extensions/v1beta9", Version: "v1beta9"},
							{GroupVersion: "extensions/v1beta10", Version: "v1beta10"},
						},
					},
				},
			}
		default:
			t.Logf("unexpected request: %s", req.URL.Path)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		output, err := json.Marshal(list)
		if err != nil {
			t.Errorf("unexpected encoding error: %v", err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))
	defer server.Close()
	for _, test := range tests {
		client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
		got, err := client.ServerResourcesForGroupVersion(test.request)
		if test.expectErr {
			if err == nil {
				t.Error("unexpected non-error")
			}
			continue
		}
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		if !reflect.DeepEqual(got, test.resourcesList) {
			t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got)
		}
	}

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	start := time.Now()
	_, serverResources, err := client.ServerGroupsAndResources()
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	end := time.Now()
	if d := end.Sub(start); d > time.Second {
		t.Errorf("took too long to perform discovery: %s", d)
	}
	serverGroupVersions := groupVersions(serverResources)
	expectedGroupVersions := []string{
		"v1",
		"apps/v1beta1",
		"apps/v1beta2",
		"apps/v1beta3",
		"apps/v1beta4",
		"apps/v1beta5",
		"apps/v1beta6",
		"apps/v1beta7",
		"apps/v1beta8",
		"apps/v1beta9",
		"apps/v1beta10",
		"extensions/v1beta1",
		"extensions/v1beta2",
		"extensions/v1beta3",
		"extensions/v1beta4",
		"extensions/v1beta5",
		"extensions/v1beta6",
		"extensions/v1beta7",
		"extensions/v1beta8",
		"extensions/v1beta9",
		"extensions/v1beta10",
	}
	if !reflect.DeepEqual(expectedGroupVersions, serverGroupVersions) {
		t.Errorf("unexpected group versions: %v", diff.ObjectReflectDiff(expectedGroupVersions, serverGroupVersions))
	}
}

func returnedOpenAPI() *openapi_v2.Document {
	return &openapi_v2.Document{
		Definitions: &openapi_v2.Definitions{
			AdditionalProperties: []*openapi_v2.NamedSchema{
				{
					Name: "fake.type.1",
					Value: &openapi_v2.Schema{
						Properties: &openapi_v2.Properties{
							AdditionalProperties: []*openapi_v2.NamedSchema{
								{
									Name: "count",
									Value: &openapi_v2.Schema{
										Type: &openapi_v2.TypeItem{
											Value: []string{"integer"},
										},
									},
								},
							},
						},
					},
				},
				{
					Name: "fake.type.2",
					Value: &openapi_v2.Schema{
						Properties: &openapi_v2.Properties{
							AdditionalProperties: []*openapi_v2.NamedSchema{
								{
									Name: "count",
									Value: &openapi_v2.Schema{
										Type: &openapi_v2.TypeItem{
											Value: []string{"array"},
										},
										Items: &openapi_v2.ItemsItem{
											Schema: []*openapi_v2.Schema{
												{
													Type: &openapi_v2.TypeItem{
														Value: []string{"string"},
													},
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func openapiSchemaDeprecatedFakeServer(status int, t *testing.T) (*httptest.Server, error) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/openapi/v2" {
			// write the error status for the new endpoint request
			w.WriteHeader(status)
			return
		}
		if req.URL.Path != "/swagger-2.0.0.pb-v1" {
			errMsg := fmt.Sprintf("Unexpected url %v", req.URL)
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}
		if req.Method != "GET" {
			errMsg := fmt.Sprintf("Unexpected method %v", req.Method)
			w.WriteHeader(http.StatusMethodNotAllowed)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}

		mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf")

		output, err := proto.Marshal(returnedOpenAPI())
		if err != nil {
			errMsg := fmt.Sprintf("Unexpected marshal error: %v", err)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))

	return server, nil
}

func openapiSchemaFakeServer(t *testing.T) (*httptest.Server, error) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/openapi/v2" {
			errMsg := fmt.Sprintf("Unexpected url %v", req.URL)
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}
		if req.Method != "GET" {
			errMsg := fmt.Sprintf("Unexpected method %v", req.Method)
			w.WriteHeader(http.StatusMethodNotAllowed)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}
		decipherableFormat := req.Header.Get("Accept")
		if decipherableFormat != "application/com.github.proto-openapi.spec.v2@v1.0+protobuf" {
			errMsg := fmt.Sprintf("Unexpected accept mime type %v", decipherableFormat)
			w.WriteHeader(http.StatusUnsupportedMediaType)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}

		mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf")

		output, err := proto.Marshal(returnedOpenAPI())
		if err != nil {
			errMsg := fmt.Sprintf("Unexpected marshal error: %v", err)
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(errMsg))
			t.Errorf("testing should fail as %s", errMsg)
			return
		}
		w.WriteHeader(http.StatusOK)
		w.Write(output)
	}))

	return server, nil
}

func openapiV3SchemaFakeServer(t *testing.T) (*httptest.Server, map[string]*openapi_v3.Document, error) {
	res, err := testutil.NewFakeOpenAPIV3Server("testdata")
	if err != nil {
		return nil, nil, err
	}
	return res.HttpServer, res.ServedDocuments, nil
}

func TestGetOpenAPISchema(t *testing.T) {
	server, err := openapiSchemaFakeServer(t)
	if err != nil {
		t.Errorf("unexpected error starting fake server: %v", err)
	}
	defer server.Close()

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	got, err := client.OpenAPISchema()
	if err != nil {
		t.Fatalf("unexpected error getting openapi: %v", err)
	}
	if e, a := returnedOpenAPI(), got; !golangproto.Equal(e, a) {
		t.Errorf("expected \n%v, got \n%v", e, a)
	}
}

func TestGetOpenAPISchemaV3(t *testing.T) {
	server, testV3Specs, err := openapiV3SchemaFakeServer(t)
	if err != nil {
		t.Errorf("unexpected error starting fake server: %v", err)
	}
	defer server.Close()

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	openapiClient := client.OpenAPIV3()
	paths, err := openapiClient.Paths()
	if err != nil {
		t.Fatalf("unexpected error getting openapi: %v", err)
	}

	for k, v := range paths {
		actual, err := v.Schema()
		if err != nil {
			t.Fatal(err)
		}

		expected := testV3Specs[k]
		if !golangproto.Equal(expected, actual) {
			t.Fatalf("expected \n%v\n\ngot:\n%v", expected, actual)
		}

		// Ensure that fetching schema once again does not return same instance
		actualAgain, err := v.Schema()
		if err != nil {
			t.Fatal(err)
		}

		if reflect.ValueOf(actual).Pointer() == reflect.ValueOf(actualAgain).Pointer() {
			t.Fatal("expected schema not to be cached")
		} else if !golangproto.Equal(actual, actualAgain) {
			t.Fatal("expected schema values to be equal")
		}
	}
}

func TestGetOpenAPISchemaForbiddenFallback(t *testing.T) {
	server, err := openapiSchemaDeprecatedFakeServer(http.StatusForbidden, t)
	if err != nil {
		t.Errorf("unexpected error starting fake server: %v", err)
	}
	defer server.Close()

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	got, err := client.OpenAPISchema()
	if err != nil {
		t.Fatalf("unexpected error getting openapi: %v", err)
	}
	if e, a := returnedOpenAPI(), got; !golangproto.Equal(e, a) {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestGetOpenAPISchemaNotFoundFallback(t *testing.T) {
	server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotFound, t)
	if err != nil {
		t.Errorf("unexpected error starting fake server: %v", err)
	}
	defer server.Close()

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	got, err := client.OpenAPISchema()
	if err != nil {
		t.Fatalf("unexpected error getting openapi: %v", err)
	}
	if e, a := returnedOpenAPI(), got; !golangproto.Equal(e, a) {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestGetOpenAPISchemaNotAcceptableFallback(t *testing.T) {
	server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotAcceptable, t)
	if err != nil {
		t.Errorf("unexpected error starting fake server: %v", err)
	}
	defer server.Close()

	client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
	got, err := client.OpenAPISchema()
	if err != nil {
		t.Fatalf("unexpected error getting openapi: %v", err)
	}
	if e, a := returnedOpenAPI(), got; !golangproto.Equal(e, a) {
		t.Errorf("expected %v, got %v", e, a)
	}
}

func TestServerPreferredResources(t *testing.T) {
	stable := metav1.APIResourceList{
		GroupVersion: "v1",
		APIResources: []metav1.APIResource{
			{Name: "pods", Namespaced: true, Kind: "Pod"},
			{Name: "services", Namespaced: true, Kind: "Service"},
			{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
		},
	}
	tests := []struct {
		resourcesList []*metav1.APIResourceList
		response      func(w http.ResponseWriter, req *http.Request)
		expectErr     func(err error) bool
	}{
		{
			resourcesList: []*metav1.APIResourceList{&stable},
			expectErr:     IsGroupDiscoveryFailedError,
			response: func(w http.ResponseWriter, req *http.Request) {
				var list interface{}
				switch req.URL.Path {
				case "/apis/extensions/v1beta1":
					w.WriteHeader(http.StatusInternalServerError)
					return
				case "/api/v1":
					list = &stable
				case "/api":
					list = &metav1.APIVersions{
						Versions: []string{
							"v1",
						},
					}
				case "/apis":
					list = &metav1.APIGroupList{
						Groups: []metav1.APIGroup{
							{
								Versions: []metav1.GroupVersionForDiscovery{
									{GroupVersion: "extensions/v1beta1"},
								},
							},
						},
					}
				default:
					t.Logf("unexpected request: %s", req.URL.Path)
					w.WriteHeader(http.StatusNotFound)
					return
				}
				output, err := json.Marshal(list)
				if err != nil {
					t.Errorf("unexpected encoding error: %v", err)
					return
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusOK)
				w.Write(output)
			},
		},
		{
			resourcesList: nil,
			expectErr:     IsGroupDiscoveryFailedError,
			response: func(w http.ResponseWriter, req *http.Request) {
				var list interface{}
				switch req.URL.Path {
				case "/apis/extensions/v1beta1":
					w.WriteHeader(http.StatusInternalServerError)
					return
				case "/api/v1":
					w.WriteHeader(http.StatusInternalServerError)
				case "/api":
					list = &metav1.APIVersions{
						Versions: []string{
							"v1",
						},
					}
				case "/apis":
					list = &metav1.APIGroupList{
						Groups: []metav1.APIGroup{
							{
								Versions: []metav1.GroupVersionForDiscovery{
									{GroupVersion: "extensions/v1beta1"},
								},
							},
						},
					}
				default:
					t.Logf("unexpected request: %s", req.URL.Path)
					w.WriteHeader(http.StatusNotFound)
					return
				}
				output, err := json.Marshal(list)
				if err != nil {
					t.Errorf("unexpected encoding error: %v", err)
					return
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusOK)
				w.Write(output)
			},
		},
	}
	for _, test := range tests {
		server := httptest.NewServer(http.HandlerFunc(test.response))
		defer server.Close()

		client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
		resources, err := client.ServerPreferredResources()
		if test.expectErr != nil {
			if err == nil {
				t.Error("unexpected non-error")
			}

			continue
		}
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		got, err := GroupVersionResources(resources)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		expected, _ := GroupVersionResources(test.resourcesList)
		if !reflect.DeepEqual(got, expected) {
			t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got)
		}
		server.Close()
	}
}

func TestServerPreferredResourcesRetries(t *testing.T) {
	stable := metav1.APIResourceList{
		GroupVersion: "v1",
		APIResources: []metav1.APIResource{
			{Name: "pods", Namespaced: true, Kind: "Pod"},
		},
	}
	beta := metav1.APIResourceList{
		GroupVersion: "extensions/v1",
		APIResources: []metav1.APIResource{
			{Name: "deployments", Namespaced: true, Kind: "Deployment"},
		},
	}

	response := func(numErrors int) http.HandlerFunc {
		var i = 0
		return func(w http.ResponseWriter, req *http.Request) {
			var list interface{}
			switch req.URL.Path {
			case "/apis/extensions/v1beta1":
				if i < numErrors {
					i++
					w.WriteHeader(http.StatusInternalServerError)
					return
				}
				list = &beta
			case "/api/v1":
				list = &stable
			case "/api":
				list = &metav1.APIVersions{
					Versions: []string{
						"v1",
					},
				}
			case "/apis":
				list = &metav1.APIGroupList{
					Groups: []metav1.APIGroup{
						{
							Name: "extensions",
							Versions: []metav1.GroupVersionForDiscovery{
								{GroupVersion: "extensions/v1beta1", Version: "v1beta1"},
							},
							PreferredVersion: metav1.GroupVersionForDiscovery{
								GroupVersion: "extensions/v1beta1",
								Version:      "v1beta1",
							},
						},
					},
				}
			default:
				t.Logf("unexpected request: %s", req.URL.Path)
				w.WriteHeader(http.StatusNotFound)
				return
			}
			output, err := json.Marshal(list)
			if err != nil {
				t.Errorf("unexpected encoding error: %v", err)
				return
			}
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			w.Write(output)
		}
	}
	tests := []struct {
		responseErrors  int
		expectResources int
		expectedError   func(err error) bool
	}{
		{
			responseErrors:  1,
			expectResources: 2,
			expectedError: func(err error) bool {
				return err == nil
			},
		},
		{
			responseErrors:  2,
			expectResources: 1,
			expectedError:   IsGroupDiscoveryFailedError,
		},
	}

	for i, tc := range tests {
		server := httptest.NewServer(http.HandlerFunc(response(tc.responseErrors)))
		defer server.Close()

		client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
		resources, err := client.ServerPreferredResources()
		if !tc.expectedError(err) {
			t.Errorf("case %d: unexpected error: %v", i, err)
		}
		got, err := GroupVersionResources(resources)
		if err != nil {
			t.Errorf("case %d: unexpected error: %v", i, err)
		}
		if len(got) != tc.expectResources {
			t.Errorf("case %d: expect %d resources, got %#v", i, tc.expectResources, got)
		}
		server.Close()
	}
}

func TestServerPreferredNamespacedResources(t *testing.T) {
	stable := metav1.APIResourceList{
		GroupVersion: "v1",
		APIResources: []metav1.APIResource{
			{Name: "pods", Namespaced: true, Kind: "Pod"},
			{Name: "services", Namespaced: true, Kind: "Service"},
			{Name: "namespaces", Namespaced: false, Kind: "Namespace"},
		},
	}
	batchv1 := metav1.APIResourceList{
		GroupVersion: "batch/v1",
		APIResources: []metav1.APIResource{
			{Name: "jobs", Namespaced: true, Kind: "Job"},
		},
	}
	batchv2alpha1 := metav1.APIResourceList{
		GroupVersion: "batch/v2alpha1",
		APIResources: []metav1.APIResource{
			{Name: "jobs", Namespaced: true, Kind: "Job"},
			{Name: "cronjobs", Namespaced: true, Kind: "CronJob"},
		},
	}
	batchv3alpha1 := metav1.APIResourceList{
		GroupVersion: "batch/v3alpha1",
		APIResources: []metav1.APIResource{
			{Name: "jobs", Namespaced: true, Kind: "Job"},
			{Name: "cronjobs", Namespaced: true, Kind: "CronJob"},
		},
	}
	tests := []struct {
		response func(w http.ResponseWriter, req *http.Request)
		expected map[schema.GroupVersionResource]struct{}
	}{
		{
			response: func(w http.ResponseWriter, req *http.Request) {
				var list interface{}
				switch req.URL.Path {
				case "/api/v1":
					list = &stable
				case "/api":
					list = &metav1.APIVersions{
						Versions: []string{
							"v1",
						},
					}
				default:
					t.Logf("unexpected request: %s", req.URL.Path)
					w.WriteHeader(http.StatusNotFound)
					return
				}
				output, err := json.Marshal(list)
				if err != nil {
					t.Errorf("unexpected encoding error: %v", err)
					return
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusOK)
				w.Write(output)
			},
			expected: map[schema.GroupVersionResource]struct{}{
				{Group: "", Version: "v1", Resource: "pods"}:     {},
				{Group: "", Version: "v1", Resource: "services"}: {},
			},
		},
		{
			response: func(w http.ResponseWriter, req *http.Request) {
				var list interface{}
				switch req.URL.Path {
				case "/apis":
					list = &metav1.APIGroupList{
						Groups: []metav1.APIGroup{
							{
								Name: "batch",
								Versions: []metav1.GroupVersionForDiscovery{
									{GroupVersion: "batch/v1", Version: "v1"},
									{GroupVersion: "batch/v2alpha1", Version: "v2alpha1"},
									{GroupVersion: "batch/v3alpha1", Version: "v3alpha1"},
								},
								PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v1", Version: "v1"},
							},
						},
					}
				case "/apis/batch/v1":
					list = &batchv1
				case "/apis/batch/v2alpha1":
					list = &batchv2alpha1
				case "/apis/batch/v3alpha1":
					list = &batchv3alpha1
				default:
					t.Logf("unexpected request: %s", req.URL.Path)
					w.WriteHeader(http.StatusNotFound)
					return
				}
				output, err := json.Marshal(list)
				if err != nil {
					t.Errorf("unexpected encoding error: %v", err)
					return
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusOK)
				w.Write(output)
			},
			expected: map[schema.GroupVersionResource]struct{}{
				{Group: "batch", Version: "v1", Resource: "jobs"}:           {},
				{Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {},
			},
		},
		{
			response: func(w http.ResponseWriter, req *http.Request) {
				var list interface{}
				switch req.URL.Path {
				case "/apis":
					list = &metav1.APIGroupList{
						Groups: []metav1.APIGroup{
							{
								Name: "batch",
								Versions: []metav1.GroupVersionForDiscovery{
									{GroupVersion: "batch/v1", Version: "v1"},
									{GroupVersion: "batch/v2alpha1", Version: "v2alpha1"},
									{GroupVersion: "batch/v3alpha1", Version: "v3alpha1"},
								},
								PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v2alpha", Version: "v2alpha1"},
							},
						},
					}
				case "/apis/batch/v1":
					list = &batchv1
				case "/apis/batch/v2alpha1":
					list = &batchv2alpha1
				case "/apis/batch/v3alpha1":
					list = &batchv3alpha1
				default:
					t.Logf("unexpected request: %s", req.URL.Path)
					w.WriteHeader(http.StatusNotFound)
					return
				}
				output, err := json.Marshal(list)
				if err != nil {
					t.Errorf("unexpected encoding error: %v", err)
					return
				}
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusOK)
				w.Write(output)
			},
			expected: map[schema.GroupVersionResource]struct{}{
				{Group: "batch", Version: "v2alpha1", Resource: "jobs"}:     {},
				{Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {},
			},
		},
	}
	for i, test := range tests {
		server := httptest.NewServer(http.HandlerFunc(test.response))
		defer server.Close()

		client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL})
		resources, err := client.ServerPreferredNamespacedResources()
		if err != nil {
			t.Errorf("[%d] unexpected error: %v", i, err)
			continue
		}
		got, err := GroupVersionResources(resources)
		if err != nil {
			t.Errorf("[%d] unexpected error: %v", i, err)
			continue
		}

		if !reflect.DeepEqual(got, test.expected) {
			t.Errorf("[%d] expected:\n%v\ngot:\n%v\n", i, test.expected, got)
		}
		server.Close()
	}
}

func groupVersions(resources []*metav1.APIResourceList) []string {
	result := []string{}
	for _, resourceList := range resources {
		result = append(result, resourceList.GroupVersion)
	}
	return result
}


text:
package x.flyspace.gradle.plugin.enumgenerator.runtime.converter;

/**
 * Created by sky91 on 2/3/15.
 */
public class WithPrefixPackageNameAndTypeConverter implements PackageNameAndTypeConverter {
	private String basePackageName;
	private String basePrefix;

	public WithPrefixPackageNameAndTypeConverter(String basePackageName, String basePrefix) {
		this.basePackageName = basePackageName;
		this.basePrefix = basePrefix;
	}

	@Override
	public String packageNameToType(String packageName) {
		return replacePrefix(packageName, basePackageName, basePrefix);
	}

	@Override
	public String typeToPackageName(String type) {
		return replacePrefix(type, basePrefix, basePackageName);
	}

	private String replacePrefix(String s, String origin, String replace) {
		if(!s.startsWith(origin)) {
			throw new RuntimeException(s + " not starts with " + origin);
		}
		String pre = replace == null ? "" : replace;
		while(pre.endsWith(".")) {
			pre = pre.substring(0, pre.length() - 1);
		}
		String post = s.substring(origin.length());
		while(post.startsWith(".")) {
			post = post.substring(1);
		}
		return pre + "." + post;
	}
}