text:
package io.getquill.context.finagle.mysql

import java.time.{ LocalDate, LocalDateTime, ZoneId }
import java.util.{ Date, TimeZone }

import com.twitter.util.Await
import io.getquill.context.sql.EncodingSpec
import io.getquill.util.LoadConfig
import io.getquill.{ FinagleMysqlContext, FinagleMysqlContextConfig, Literal }

import scala.concurrent.duration._

class FinagleMysqlEncodingSpec extends EncodingSpec {

  val context = testContext
  import testContext._

  "encodes and decodes types" in {
    val r =
      for {
        _ <- testContext.run(delete)
        _ <- testContext.run(liftQuery(insertValues).foreach(e => insert(e)))
        result <- testContext.run(query[EncodingTestEntity])
      } yield result

    verify(Await.result(r).toList)
  }

  "fails if the column has the wrong type" in {
    Await.result(testContext.run(liftQuery(insertValues).foreach(e => insert(e))))
    case class EncodingTestEntity(v1: Int)
    val e = intercept[IllegalStateException] {
      Await.result(testContext.run(query[EncodingTestEntity]))
    }
  }

  "encodes sets" in {
    val q = quote {
      (set: Query[Int]) =>
        query[EncodingTestEntity].filter(t => set.contains(t.v6))
    }
    Await.result {
      for {
        _ <- testContext.run(query[EncodingTestEntity].delete)
        _ <- testContext.run(liftQuery(insertValues).foreach(e => query[EncodingTestEntity].insert(e)))
        r <- testContext.run(q(liftQuery(insertValues.map(_.v6))))
      } yield {
        verify(r)
      }
    }
  }

  "Integer type with Long" in {
    case class IntLong(o6: Long)
    val entity = quote { querySchema[IntLong]("EncodingTestEntity") }
    val insert = quote {
      entity.insert(_.o6 -> 5589)
    }
    val q = quote {
      entity.filter(_.o6 == 5589)
    }
    Await.result(testContext.run(insert))
    Await.result(testContext.run(q)).nonEmpty mustEqual true
  }

  "decode boolean types" - {
    case class BooleanEncodingTestEntity(
      v1: Boolean,
      v2: Boolean,
      v3: Boolean,
      v4: Boolean,
      v5: Boolean,
      v6: Boolean,
      v7: Boolean
    )
    val decodeBoolean = (entity: BooleanEncodingTestEntity) => {
      val r = for {
        _ <- testContext.run(query[BooleanEncodingTestEntity].delete)
        _ <- testContext.run(query[BooleanEncodingTestEntity].insert(lift(entity)))
        result <- testContext.run(query[BooleanEncodingTestEntity])
      } yield result
      Await.result(r).head
    }
    "true" in {
      val entity = BooleanEncodingTestEntity(true, true, true, true, true, true, true)
      val r = decodeBoolean(entity)
      r.v1 mustEqual true
      r.v2 mustEqual true
      r.v3 mustEqual true
      r.v4 mustEqual true
      r.v5 mustEqual true
      r.v6 mustEqual true
      r.v7 mustEqual true
    }

    "false" in {
      val entity = BooleanEncodingTestEntity(false, false, false, false, false, false, false)
      val r = decodeBoolean(entity)
      r.v1 mustEqual false
      r.v2 mustEqual false
      r.v3 mustEqual false
      r.v4 mustEqual false
      r.v5 mustEqual false
      r.v6 mustEqual false
      r.v7 mustEqual false
    }
  }

  "decode date types" - {
    case class DateEncodingTestEntity(
      v1: Date,
      v2: Date,
      v3: Date
    )

    val date = new Date
    val entity = DateEncodingTestEntity(date, date, date)

    def round(milliseconds: Long, duration: Duration): Long = Math.round(milliseconds / duration.toMillis.toDouble) * duration.toMillis

    def verify(result: DateEncodingTestEntity) = {
      round(result.v1.getTime, 24.hours) mustEqual round(entity.v1.getTime, 24.hours)
      result.v2.getTime mustEqual entity.v2.getTime
      result.v3.getTime mustEqual entity.v3.getTime
    }

    "default timezone" in {
      val r = for {
        _ <- testContext.run(query[DateEncodingTestEntity].delete)
        _ <- testContext.run(query[DateEncodingTestEntity].insert(lift(entity)))
        result <- testContext.run(query[DateEncodingTestEntity])
      } yield result

      verify(Await.result(r).head)
    }

    "different timezone" in {
      val config = FinagleMysqlContextConfig(LoadConfig("testDB"))
      val testTimezoneContext = new FinagleMysqlContext(Literal, config.client, TimeZone.getTimeZone("KST"), TimeZone.getTimeZone("UTC"))
      import testTimezoneContext._

      val r = for {
        _ <- testTimezoneContext.run(query[DateEncodingTestEntity].delete)
        _ <- testTimezoneContext.run(query[DateEncodingTestEntity].insert(lift(entity)))
        result <- testTimezoneContext.run(query[DateEncodingTestEntity])
      } yield result

      //verify(Await.result(r).head)
    }
  }

  "decode LocalDateTime types" - {
    case class LocalDateTimeEncodingTestEntity(
      v1: LocalDateTime,
      v2: LocalDateTime
    )

    val dt = LocalDateTime.parse("2017-01-01T00:00:00")
    val entity = LocalDateTimeEncodingTestEntity(dt, dt)

    def verify(result: LocalDateTimeEncodingTestEntity) = {
      result.v1 mustEqual entity.v1
      result.v2 mustEqual entity.v2
    }

    "TimeZone.setDefault() to different timezone than that of FinagleMysqlContext" in {
      val config = FinagleMysqlContextConfig(LoadConfig("testDB"))
      val testTimezoneContext = new FinagleMysqlContext(Literal, config.client, TimeZone.getTimeZone(ZoneId.of("Asia/Tokyo")), TimeZone.getTimeZone(ZoneId.of("Asia/Tokyo")))
      import testTimezoneContext._

      val zone = TimeZone.getDefault
      TimeZone.setDefault(TimeZone.getTimeZone("UTC"))

      val r = for {
        _ <- testTimezoneContext.run(query[LocalDateTimeEncodingTestEntity].delete)
        _ <- testTimezoneContext.run(query[LocalDateTimeEncodingTestEntity].insert(lift(entity)))
        result <- testTimezoneContext.run(query[LocalDateTimeEncodingTestEntity])
      } yield result

      TimeZone.setDefault(zone)

      verify(Await.result(r).head)
    }
  }

  "timestamp as localdate" in {
    case class LocalDateTimeEncodingTestEntity(v2: LocalDate)
    val e = LocalDateTimeEncodingTestEntity(LocalDate.now())

    val r = for {
      _ <- testContext.run(query[LocalDateTimeEncodingTestEntity].delete)
      _ <- testContext.run(query[LocalDateTimeEncodingTestEntity].insert(lift(e)))
      result <- testContext.run(query[LocalDateTimeEncodingTestEntity])
    } yield result

    Await.result(r).headOption.map(_.v2) mustBe Some(e.v2)
  }
}


text:
task :default => [:build]

desc "Packages Kings code and content files into a Python egg"
task :build do
	sh "python setup.py egg_info -b _#{build_number} bdist_egg"
	egg_file = egg_file("kings")
	puts "Built #{egg_file}"
end

desc "Clears .pyc files, and the build and dist directories"
task :clean => "clean:all"
namespace :clean do
	task :all => [:pyc, :dist, :build]

	task :pyc do
		rm(FileList.new(File.join("**", "*.pyc")))
	end
	task :dist do
		rm_rf("dist")
	end
	task :build do
		rm_rf("build")
	end
end

# Helpers

def egg_file(package)
	filename = File.join("dist", [package, egg_version, "*.egg"].join("-"))
  %x[ls #{filename} | sort | tail -n 1].strip
end

def egg_version
	%x[python setup.py --version].strip + "_" + build_number
end

def build_number
  b_num = ENV["BUILD_NUMBER"] || "dev"
  git_hash = short_git_hash || "unknown"

  b_num + "_" + git_hash
end

def short_git_hash
  %x[git log --pretty=format:'%h' -n 1].strip
end

redpajama_set_name: RedPajamaGithub


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):
        # Deleting field 'Hotel.nights'
        db.delete_column(u'rsvp_hotel', 'nights')

    def backwards(self, orm):
        # Adding field 'Hotel.nights'
        db.add_column(u'rsvp_hotel', 'nights',
                      self.gf('django.db.models.fields.IntegerField')(default=0, max_length=1),
                      keep_default=False)

    models = {
        u'rsvp.event': {
            'Meta': {'object_name': 'Event'},
            'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Location']", 'null': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        },
        u'rsvp.guest': {
            'Meta': {'ordering': "['-last_name', '-first_name']", 'object_name': 'Guest'},
            'attending': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'city': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'display_as': ('django.db.models.fields.CharField', [], {'max_length': '91', 'null': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '45'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '45'}),
            'max_guests': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
            'prefix': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}),
            'primary': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'primary_email': ('django.db.models.fields.EmailField', [], {'max_length': '254'}),
            'relation': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}),
            'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
            'street_addr': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'zip_code': ('django.db.models.fields.IntegerField', [], {'max_length': '5'})
        },
        u'rsvp.hotel': {
            'Meta': {'object_name': 'Hotel'},
            'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}),
            'hotel_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'notes': ('django.db.models.fields.TextField', [], {}),
            'total_guest_count': ('django.db.models.fields.IntegerField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'})
        },
        u'rsvp.location': {
            'Meta': {'object_name': 'Location'},
            'distance': ('django.db.models.fields.DecimalField', [], {'max_digits': '3', 'decimal_places': '2'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        },
        u'rsvp.room': {
            'Meta': {'object_name': 'Room'},
            'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}),
            'hotel': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Hotel']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'max_occupancy': ('django.db.models.fields.IntegerField', [], {}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'room_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['rsvp.Roomtype']", 'null': 'True', 'blank': 'True'})
        },
        u'rsvp.roomtype': {
            'Meta': {'object_name': 'Roomtype'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        },
        u'rsvp.table': {
            'Meta': {'object_name': 'Table'},
            'guests': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['rsvp.Guest']", 'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
        }
    }

    complete_apps = ['rsvp']


text:
import {
  AfterViewInit,
  Component,
  ElementRef,
  Input,
  OnInit,
  OnDestroy,
  ViewChild,
  ViewChildren,
  QueryList,
  TemplateRef,
  DoCheck,
  ViewEncapsulation
} from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';
import { cloneDeep, trimEnd } from 'lodash';

import { IterationService } from './../../iteration/iteration.service';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import { Broadcaster } from 'ngx-base';
import { Space, Spaces } from 'ngx-fabric8-wit';
import { AuthenticationService, User, UserService } from 'ngx-login-client';
import { ArrayCount } from 'ngx-widgets';
import { DragulaService } from 'ng2-dragula';

import { IterationModel } from './../../models/iteration.model';
import { WorkItem } from '../../models/work-item';
import { WorkItemType } from '../../models/work-item-type';
import { WorkItemService } from '../work-item.service';

@Component({
  // tslint:disable-next-line:use-host-property-decorator
  host: {
     'class': 'app-component height-100 flex-container in-column-direction flex-grow-1'
  },
  selector: 'alm-board',
  templateUrl: './work-item-board.component.html',
  styleUrls: ['./work-item-board.component.scss']
})

export class WorkItemBoardComponent implements OnInit, OnDestroy {

  @ViewChildren('activeFilters', {read: ElementRef}) activeFiltersRef: QueryList<ElementRef>;
  @ViewChild('activeFiltersDiv') activeFiltersDiv: any;

  workItem: WorkItem;
  filters: any[] = [];
  lanes: Array<any> = [];
  pageSize: number = 20;
  loggedIn: Boolean = false;
  spaceSubscription: Subscription;
  contentItemHeight: number = 85;
  boardContextSubscription: Subscription;
  private allUsers: User[] = [];
  private iterations: IterationModel[] = [];
  private workItemTypes: WorkItemType[] = [];
  private readyToInit = false;
  eventListeners: any[] = [];

  constructor(
    private auth: AuthenticationService,
    private broadcaster: Broadcaster,
    private router: Router,
    private workItemService: WorkItemService,
    private dragulaService: DragulaService,
    private iterationService: IterationService,
    private userService: UserService,
    private spaces: Spaces) {
      this.dragulaService.drag.subscribe((value) => {
        this.onDrag(value.slice(1));
      });

      this.dragulaService.drop.subscribe((value) => {
        this.onDrop(value.slice(1));
      });

      this.dragulaService.over.subscribe((value) => {
        this.onOver(value.slice(1));
      });

      this.dragulaService.out.subscribe((value) => {
        this.onOut(value.slice(1));
      });
    }

  ngOnInit() {
    this.listenToEvents();
    this.loggedIn = this.auth.isLoggedIn();
    this.spaceSubscription = this.spaces.current.subscribe(space => {
      if (space) {
        console.log('[WorkItemBoardComponent] New Space selected: ' + space.attributes.name);
        this.getDefaultWorkItemTypeStates();
      } else {
        console.log('[WorkItemBoardComponent] Space deselected');
        this.lanes = [];
        this.workItemTypes = [];
      }
    });
    this.boardContextSubscription = this.broadcaster.on<WorkItemType>('board_type_context').subscribe(workItemType => {
      if (workItemType) {
        console.log('[WorkItemBoardComponent] New type context selected: ' + workItemType.attributes.name);
        this.lanes = [];
        this.getDefaultWorkItemTypeStates(workItemType.id);
      }
    });
    this.initStuff();
  }

  ngOnDestroy() {
    console.log('Destroying all the listeners in board component');
    this.eventListeners.forEach(subscriber => subscriber.unsubscribe());
  }

  initStuff() {
    Observable.combineLatest(
      this.iterationService.getIterations(),
      this.userService.getAllUsers(),
      this.workItemService.getWorkItemTypes()
    ).map((items) => {
      return items;
    })
    .subscribe(([iterations, users, wiTypes]) => {
      this.allUsers = users;
      this.iterations = iterations;
      this.workItemTypes = wiTypes;
      this.readyToInit = true;

      // Set lanes
      this.getDefaultWorkItemTypeStates();
    });
  }

  getWorkItems(pageSize, lane) {
    this.workItemService.getWorkItems(pageSize, [{
        active: true,
        paramKey: 'filter[workitemstate]',
        value: lane.option
      }, ...this.filters])
    .subscribe(workItemResp => {
      const workItems = workItemResp.workItems;
      lane.workItems = this.workItemService.resolveWorkItems(
        workItems,
        this.iterations,
        this.allUsers,
        this.workItemTypes
      );
      lane.nextLink = workItemResp.nextLink;
    });
  }

  getDefaultWorkItemTypeStates(workItemTypeId?: string) {
    this.lanes = [];
    if (!workItemTypeId) {
        if (this.workItemTypes.length) {
          let lanes = this.workItemTypes[0].attributes.fields['system.state'].type.values;
          lanes.forEach((value, index) => {
            this.lanes.push({
              option: value,
              workItems: [] as WorkItem[],
              nextLink: null
            });
          });
          this.filters = [ {
            active: true,
            paramKey: 'filter[workitemtype]',
            value: this.workItemTypes[0].id
          } ];
        }
    } else {
      // we have a type id, we just fetch the states from it.
      let witype = this.workItemTypes.find(type => type.id === workItemTypeId);
      if (witype) {
        let lanes = witype.attributes.fields['system.state'].type.values;
        lanes.forEach((value, index) => {
          this.lanes.push({
            option: value,
            workItems: [] as WorkItem[],
            nextLink: null
          });
        });
      } else {
        this.getDefaultWorkItemTypeStates();
      }
    }
  }

  initWiItems($event, lane) {
    this.getWorkItems($event.pageSize, lane);
  }

  fetchMoreWiItems(lane) {
    console.log('More for ' + lane.option);
    if (lane.nextLink) {
      this.workItemService.getMoreWorkItems(lane.nextLink)
        .subscribe((workItemResp) => {
          lane.workItems = [
            ...lane.workItems,
            ...this.workItemService.resolveWorkItems(
              workItemResp.workItems,
              this.iterations,
              this.allUsers,
              this.workItemTypes
          )];
          lane.nextLink = workItemResp.nextLink;
        });
    } else {
      console.log('No More for ' + lane.option);
    }
  }

  gotoDetail(workItem: WorkItem) {
    let link = trimEnd(this.router.url.split('detail')[0], '/') + '/detail/' + workItem.id;
    this.router.navigateByUrl(link);
  }

  onDrag(args: any) {
    let [el, source] = args;
  }

  getWI(workItem: WorkItem) {
    let lane = this.lanes.find((lane) => lane.option === workItem.attributes['system.state']);
    let _workItem = lane.workItems.find((item) => item.id === workItem.id);
    this.workItem = _workItem;
  }

  onDrop(args) {
    let [el, target, source, sibling] = args;
    target.parentElement.parentElement.classList.remove('active-lane');
    let state = target.parentElement.parentElement.getAttribute('data-state');
    let adjElm = null;

    let prevElId = '0';
    try {
      prevElId = el.previousElementSibling.getAttribute('data-id');
    } catch (e) {}

    this.changeLane(this.workItem.attributes['system.state'], state, this.workItem, prevElId);

    if (el.previousElementSibling) {
      adjElm = el.previousElementSibling;
      this.changeState(state, el.getAttribute('data-id'), adjElm.getAttribute('data-id'), 'below');
    }
    else if(el.nextElementSibling) {
      adjElm = el.nextElementSibling;
      this.changeState(state, el.getAttribute('data-id'), adjElm.getAttribute('data-id'), 'above');
    }
    else {
      this.changeState(state, el.getAttribute('data-id'), null, 'above');
    }
  }

  onOver(args) {
    let [el, container, source] = args;
    let containerClassList = container.parentElement.parentElement.classList;
    let laneSection = document.getElementsByClassName('board-lane-column');
    for(let i=0; i<laneSection.length; i++) {
      laneSection[i].classList.remove('active-lane');
    }
    containerClassList.add('active-lane');
  }

  onOut(args) {
    let [el, container, source] = args;
    source.parentElement.parentElement.classList.remove('active-lane');
  }

  activeOnList(timeOut: number = 0) {
    setTimeout(() => {
      this.broadcaster.broadcast('activeWorkItem', this.workItem.id);
    }, timeOut);
  }

  changeState(option: any, elId: string, adjElmId: string | null = null, direction: string): void {
    this.workItem.attributes['system.state'] = option;
    let lane = this.lanes.find((lane) => lane.option === this.workItem.attributes['system.state']);
    if (this.workItem.id) {
      this.workItemService
        .update(this.workItem)
        .subscribe((workItem) => {
          let wItem = lane.workItems.find((item) => item.id === workItem.id);
          wItem.attributes['version'] = workItem.attributes['version'];
          this.activeOnList();
          if (adjElmId !== null) {
            this.workItemService.reOrderWorkItem(wItem, adjElmId, direction)
                .subscribe((workitem) => {
                  lane.workItems.find((item) => item.id === workItem.id).attributes['version'] = workitem.attributes['version'];
                  lane.workItems.find((item) => item.id === workItem.id).attributes['system.order'] = workitem.attributes['system.order'];
                });
          }
      });
    }
  }

  changeLane(oldState, newState, workItem, prevIdEl: string | null = null) {
    let oldLane = this.lanes.find((lane) => lane.option === oldState);
    let newLane = this.lanes.find((lane) => lane.option === newState);
    let index = oldLane.workItems.findIndex((item) => item.id === workItem.id);

    oldLane.workItems.splice(index, 1);

    if (prevIdEl !== null) {
      let newIndex = newLane.workItems.findIndex((item) => item.id === prevIdEl);
      if (newIndex > -1) {
        newIndex += 1;
        newLane.workItems.splice(newIndex, 0, workItem);
      } else {
        newLane.workItems.splice(0, 0, workItem);
      }
    } else {
      newLane.workItems.push(workItem);
    }
  }

  listenToEvents() {
    // filters like assign to me should stack with the current filters
    this.eventListeners.push(
      this.broadcaster.on<string>('item_filter')
        .subscribe((filters: any) => {
          this.filters = filters;
          // this reloads the states for the lanes, and then the wis inside the lanes.
          filters.forEach((filter) => {
            if (filter.paramKey === 'filter[workitemtype]')
              this.getDefaultWorkItemTypeStates(filter.value);
          });
      })
    );

    this.eventListeners.push(
      this.broadcaster.on<string>('wi_change_state')
          .subscribe((data: any) => {
            this.changeLane(data[0].oldState, data[0].newState, data[0].workItem);
      })
    );
  }

}


text:
In the spirit of [free software][free-sw], **everyone** is encouraged to help
improve this project.

[free-sw]: http://www.fsf.org/licensing/essays/free-sw.html

Here are some ways *you* can contribute:

* by using alpha, beta, and prerelease versions
* by triaging bug reports
* by writing or editing documentation
* by writing specifications
* by writing code (**no patch is too small**: fix typos, add comments, clean up
  inconsistent whitespace)
* by refactoring code
* by fixing [issues][]
* by reviewing patches
* by suggesting new features
* [financially][gittip]

[issues]: https://github.com/sferik/rails_admin/issues
[gittip]: https://www.gittip.com/sferik/

## Development

### Running tests locally

To run the test suite, you need PhantomJS and ImageMagick (or GraphicsMagick).

Example on macOS using Homebrew:

    brew cask install phantomjs
    brew install imagemagick
    bundle exec rspec

### Tests run against multiple versions of Rails

In CI, we use [appraisal] to run tests against multiple versions of Rails.
The [gemfiles/ directory] contains the Gemfiles used to create the CI build
matrix. See [the Travis CI configuration] for more details on what Ruby versions
run what Rails versions.

[appraisal]: https://github.com/thoughtbot/appraisal
[gemfiles/ directory]: ./gemfiles
[the Travis CI configuration]: ./.travis.yml

## Getting Help

We use a [mailing list][list] for user support. If you've got a "how do
I do this?" or "this doesn't seem to work the way I expect" type of
issue or just want some help, please post a message to the [mailing
list][list].

## Submitting an Issue

If you're confident that you've found a bug in
rails_admin, please [open an issue][issues], but check to make sure it hasn't
already been submitted. When submitting a bug report, please include a
[Gist][] that includes a stack trace and any details that may be
necessary to reproduce the bug, including your gem version, Ruby
version, and operating system.  Ideally, a bug report should include a
pull request with failing specs.

[gist]: https://gist.github.com/
[list]: http://groups.google.com/group/rails_admin

## Submitting a Pull Request
1. [Fork the repository.][fork]
2. Create a branch.
3. Add specs for your unimplemented feature or bug fix.
4. Run `bundle exec rake spec`. If your specs pass, return to step 3.
5. Implement your feature or bug fix.
6. Run `bundle exec rake default`. If your specs fail, return to step 5.
7. Run `open coverage/index.html`. If your changes are not completely covered
   by your tests, return to step 3.
8. Add, commit, and push your changes.
9. [Submit a pull request.][pr]

[fork]: http://help.github.com/fork-a-repo/
[pr]: http://help.github.com/send-pull-requests/


text:
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 * @version $Id: Sort.php 6353 2012-05-28 17:29:23Z SteveG $
 *
 * @category Piwik
 * @package Piwik
 */

/**
 * Sort the DataTable based on the value of column $columnToSort ordered by $order.
 * Possible to specify a natural sorting (see php.net/natsort for details)
 *
 * @package Piwik
 * @subpackage Piwik_DataTable
 */
class Piwik_DataTable_Filter_Sort extends Piwik_DataTable_Filter
{
	protected $columnToSort;
	protected $order;

	/**
	 * @param Piwik_DataTable  $table
	 * @param string           $columnToSort   name of the column to sort by
	 * @param string           $order          order (asc|desc)
	 * @param bool             $naturalSort    use natural sort?
	 * @param bool             $recursiveSort  sort recursively?
	 */
	public function __construct( $table, $columnToSort, $order = 'desc', $naturalSort = true, $recursiveSort = false )
	{
		parent::__construct($table);
		if($recursiveSort)
		{
			$table->enableRecursiveSort();
		}
		$this->columnToSort = $columnToSort;
		$this->naturalSort = $naturalSort;
		$this->setOrder($order);
	}

	/**
	 * Updates the order
	 *
	 * @param string  $order  asc|desc
	 */
	public function setOrder($order)
	{
		if($order == 'asc')
		{
			$this->order = 'asc';
			$this->sign = 1;
		}
		else
		{
			$this->order = 'desc';
			$this->sign = -1;
		}
	}

	/**
	 * Sorting method used for sorting numbers
	 *
	 * @param number  $a
	 * @param number  $b
	 * @return int
	 */
	public function sort($a, $b)
	{
		return !isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
						&&  !isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])

					? 0
					: (
						!isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
						? 1
						: (
							!isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
							? -1
							: ( ($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort] != $b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort]
								|| !isset($a->c[Piwik_DataTable_Row::COLUMNS]['label']))
								? ( $this->sign * (
										$a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort]
											< $b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort]
										? -1
										: 1)
								)
								: -1 * $this->sign * strnatcasecmp(
										$a->c[Piwik_DataTable_Row::COLUMNS]['label'],
										$b->c[Piwik_DataTable_Row::COLUMNS]['label'])
							)
						)
					)
			;
	}

	/**
	 * Sorting method used for sorting values natural
	 *
	 * @param mixed  $a
	 * @param mixed  $b
	 * @return int
	 */
	function naturalSort($a, $b)
	{
		return !isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
				&& !isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort] )
				? 0
				: (!isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
					? 1
					: (!isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort] )
						? -1
						: $this->sign * strnatcasecmp(
								$a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort],
								$b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort]
							)
						)
					)
				;
	}

	/**
	 * Sorting method used for sorting values
	 *
	 * @param mixed  $a
	 * @param mixed  $b
	 * @return int
	 */
	function sortString($a, $b)
	{
		return !isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
				&& !isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort] )
				? 0
				: (!isset($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort])
					? 1
					: (!isset($b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort] )
						? -1
						: $this->sign *
							strcasecmp($a->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort],
								$b->c[Piwik_DataTable_Row::COLUMNS][$this->columnToSort]
							)
						)
					)
				;
	}

	/**
	 * Sets the column to be used for sorting
	 *
	 * @param Piwik_DataTable_Row  $row
	 * @return int
	 */
	protected function selectColumnToSort($row)
	{
		$value = $row->getColumn($this->columnToSort);
		if($value !== false)
		{
			return $this->columnToSort;
		}

		// sorting by "nb_visits" but the index is Piwik_Archive::INDEX_NB_VISITS in the table
		if(isset(Piwik_Archive::$mappingFromNameToId[$this->columnToSort]))
		{
			$column = Piwik_Archive::$mappingFromNameToId[$this->columnToSort];
			$value = $row->getColumn($column);

			if($value !== false)
			{
				return $column;
			}
		}

		// eg. was previously sorted by revenue_per_visit, but this table
		// doesn't have this column; defaults with nb_visits
		$column = Piwik_Archive::INDEX_NB_VISITS;
		$value = $row->getColumn($column);
		if($value !== false)
		{
			return $column;
		}

		// even though this column is not set properly in the table,
		// we select it for the sort, so that the table's internal state is set properly
		return $this->columnToSort;
	}

	/**
	 * Sorts the given data table by defined column and sorting method
	 *
	 * @param Piwik_DataTable  $table
	 * @return mixed
	 */
	public function filter($table)
	{
		if($table instanceof Piwik_DataTable_Simple)
		{
			return;
		}
		if(empty($this->columnToSort))
		{
			return;
		}
		$rows = $table->getRows();
		if(count($rows) == 0)
		{
			return;
		}
		$row = current($rows);
		if($row === false)
		{
			return;
		}
		$this->columnToSort = $this->selectColumnToSort($row);

		$value = $row->getColumn($this->columnToSort);
		if( is_numeric($value))
		{
			$methodToUse = "sort";
		}
		else
		{
			if($this->naturalSort)
			{
				$methodToUse = "naturalSort";
			}
			else
			{
				$methodToUse = "sortString";
			}
		}
		$table->sort( array($this,$methodToUse), $this->columnToSort );
	}
}


text:
<?php

namespace Drupal\import_publication\PublicationParser;

/**
 * Parses the Publication and returns corresponding values
 */
class PublicationParser {

	protected $publication;
	protected $remainingData;
	protected $logger;

	public function __construct($publication) {
		$this->publication = $this->convert_smart_quotes($publication);
		$this->remainingData = $this->publication;
		$this->logger = \Drupal::logger('import_publication');
		//$this->logger->notice(t("New Publication String:" . $this->publication));

	}

	/*
		* Finds the year and returns it
	*/
	public function getYear() {
		//finds the date wrapped in ()
		preg_match("/\(.*\d{4}.*\)/", $this->publication, $matches);

		//$this->logger->notice(t("REGEX:
" . print_r($matches, true)) . "
");

		if (!empty($matches)) {
			$wrappedYear = $matches[0];
			preg_match("/\d{4}/", $wrappedYear, $year);

			//$this->logger->notice(t("REGEX year:
" . print_r($year, true)) . "
");

			$this->shortenRemainingData($year[0]);
			return $year[0];
		}

		//else the date is not wrapped in ().
		preg_match("/\d{4}/", $this->publication, $year);
		//$this->logger->notice(t("REGEX year not wrapped:
" . print_r($year, true)) . "
");

		$this->shortenRemainingData($year[0]);
		return $year[0];

	}

	/*
		* Returns the title wrapped in  tags
	*/
	public function getTitle() {
		preg_match("/(.*?)<\/em>/", $this->publication, $matches);

		if (!empty($matches)) {
			$title = $matches[0];
			$this->shortenRemainingData($title);

			$title = substr($title, 4, -5);

			$title = $this->limit255($title);

			return $title;

		}

		$this->logger->warning(t("Could not find Title in " . $this->publication));

		return "";

	}

	/*
		    * Returns the periodical wrapped in quotes
	*/
	public function getPeriodical() {
		preg_match("/\".*\"/", $this->publication, $matches);

		if (!empty($matches)) {
			$periodicalData = $matches[0];

			$this->shortenRemainingData($periodicalData);
			$periodicalData = str_replace("\"", "", $periodicalData);

			$periodicalData = $this->limit255($periodicalData);

			return $periodicalData;
		}
		$this->logger->warning(t("Could not find periodical in " . $this->publication));

		return "";
	}

	/*
		* Returns the author(s)
	*/
	public function getAuthors() {

		//first start with data using "(with <author name>, yyyy)"
		preg_match("/\(?with (.*), \d{4}\)/", $this->publication, $matches);
		if (!empty($matches)) {
			//$this->logger->notice(t("authors:
" . print_r($matches, true)) . "
");
			$authors = $matches[0];
			$authors = trim(substr($authors, 5, -7));
			$this->shortenRemainingData($authors);

			if (stripos(strrev($authors), ".") === 0) {
				$authors = trim(substr($authors, 0, -1));
			}
			return $authors;
		}

		//or it could simply be (with <author names>)
		preg_match("/\(with (.*)\)/", $this->publication, $matches);
		if (!empty($matches)) {
			//$this->logger->notice(t("authors:
" . print_r($matches, true)) . "
");
			$authors = $matches[0];

			$this->shortenRemainingData($authors);

			$authors = trim(substr($authors, 5, -1));

			if (stripos(strrev($authors), ".") === 0) {
				$authors = trim(substr($authors, 0, -1));
			}

			return $authors;
		}

		//Not found yet, so its probably at the start. remove strong tags
		$publication = strip_tags($this->publication, "");
		$this->remainingData = strip_tags($this->remainingData, "");

		//not found, so strip the first part of the string, up to a (, ", or , or YYYY characters
		preg_match("/^([A-Za-z].*?) (\(|\"||\(?\d{4}\)?)/", $publication, $matches);
		if (!empty($matches)) {
			//$this->logger->notice(t("authors (at start) :
" . print_r($matches, true)) . "
");
			$authors = $matches[0];

			//check if authors ends with a quote or bracket. If yes, then remove.
			if (stripos(strrev($authors), "\"") === 0 || stripos(strrev($authors), "(") === 0) {
				$authors = trim(substr($authors, 0, -1));
			}

			if (stripos(strrev($authors), strrev("")) === 0) {
				$authors = trim(substr($authors, 0, -4));
			}

			//some author data ends with the year, so strip out the last 4 digits.
			if (preg_match("/^([A-Za-z].*?)\d{4}/", $authors, $newmatches)) {
				$authors = trim(substr($authors, 0, -4));
			}

			if (stripos(strrev($authors), ",") === 0 || stripos(strrev($authors), ".") === 0) {
				$authors = trim(substr($authors, 0, -1));
			}

			$this->shortenRemainingData($authors);
			return $authors;
		}

		$this->logger->warning(t("Could not find author in " . $publication));
		return "";

	}

	/*
		* Location has the rest of the data
	*/
	public function getLocation() {
		$this->remainingData = str_replace("(with , )", "", $this->remainingData);
		$this->remainingData = str_replace("()", "", $this->remainingData);
		$this->remainingData = str_replace(",", "", $this->remainingData);
		$this->remainingData = str_replace(".", "", $this->remainingData);

		return $this->limit255(trim(strip_tags($this->remainingData)));
	}

	/*
		 * takes the RemainingData string, and cuts out the $piece from it.
	*/
	private function shortenRemainingData($piece) {
		$start = strpos($this->remainingData, $piece);

		if ($start === false) {
			//not found
		} else {
			$end = strpos($this->remainingData, $piece) + strlen($piece);
			$this->remainingData = substr($this->remainingData, 0, $start) . substr($this->remainingData, $end);
		}

		//$this->logger->notice(t("Remaining String: " . $this->remainingData));

	}

	private function convert_smart_quotes($string) {
		$search = array(
			"'",
			"'",
			""",
			""",
		);

		$replace = array(
			"'",
			"'",
			'"',
			'"',
		);

		return str_replace($search, $replace, $string);
	}

	private function limit255($str) {
		if (strlen($str) > 255) {
			$str = substr($str, 0, 255);
		}
		return $str;
	}

}


text:
# Introduction

zend-inputfilter can be used to filter and validate generic sets of input data.
For instance, you could use it to filter `$_GET` or `$_POST` values, CLI
arguments, etc.

To pass input data to the `InputFilter`, use the `setData()` method; the data
must be specified using an associative array. Below is an example on how to
validate the data coming from a form using the POST method.

```php
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Input;
use Zend\Validator;

$email = new Input('email');
$email->getValidatorChain()
      ->attach(new Validator\EmailAddress());

$password = new Input('password');
$password->getValidatorChain()
         ->attach(new Validator\StringLength(8));

$inputFilter = new InputFilter();
$inputFilter->add($email);
$inputFilter->add($password);
$inputFilter->setData($_POST);

if ($inputFilter->isValid()) {
    echo "The form is valid\n";
} else {
    echo "The form is not valid\n";
    foreach ($inputFilter->getInvalidInput() as $error) {
        print_r($error->getMessages());
    }
}
```

In this example, we validated the email and password values. The email must be a
valid address and the password must be composed of at least 8 characters. If the
input data are not valid, we report the list of invalid input using the
`getInvalidInput()` method.

You can add validators to each input using the `attach()` method for each
validator chain. It is also possible to specify a "validation group", a subset
of the data to be validated; this may be done using the `setValidationGroup()`
method. You can specify the list of the input names as an array or as individual
parameters.

```php
// As individual parameters
$inputFilter->setValidationGroup('email', 'password');

// or as an array of names
$inputFilter->setValidationGroup(['email', 'password']);
```

You can validate and/or filter the data using the `InputFilter`. To filter data,
use the `getFilterChain()` method of individual `Input` instances, and attach
filters to the returned filter chain. Below is an example that uses filtering
without validation.

```php
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;

$input = new Input('foo');
$input->getFilterChain()
      ->attachByName('stringtrim')
      ->attachByName('alpha');

$inputFilter = new InputFilter();
$inputFilter->add($input)
$inputFilter->setData([
    'foo' => ' Bar3 ',
]);

echo "Before:\n";
echo $inputFilter->getRawValue('foo') . "\n"; // the output is ' Bar3 '
echo "After:\n";
echo $inputFilter->getValue('foo') . "\n";    // the output is 'Bar'
```

The `getValue()` method returns the filtered value of the 'foo' input, while
`getRawValue()` returns the original value of the input.

We also provide `Zend\InputFilter\Factory` to allow initialization of the
`InputFilter` based on a configuration array or `Traversable` object. Below is
an example where we create a password input value with the same constraints
proposed before (a string with at least 8 characters):

```php
use Zend\InputFilter\Factory;

$factory = new Factory();
$inputFilter = $factory->createInputFilter([
    'password' => [
        'name'       => 'password',
        'required'   => true,
        'validators' => [
            [
                'name' => 'not_empty',
            ],
            [
                'name' => 'string_length',
                'options' => [
                    'min' => 8
                ],
            ],
        ],
    ],
]);

$inputFilter->setData($_POST);
echo $inputFilter->isValid() ? 'Valid form' : 'Invalid form';
```

The factory may be used to create not only `Input` instances, but also nested
`InputFilter`s, allowing you to create validation and filtering rules for
hierarchical data sets.

Finally, the default `InputFilter` implementation is backed by a `Factory`. This
means that when calling `add()`, you can provide a specification that the
`Factory` understands, and it will create the appropriate object. You may
create either `Input` or `InputFilter` objects in this fashion.

```php
use Zend\InputFilter\InputFilter;

$filter = new InputFilter();

// Adding a single input
$filter->add([
    'name' => 'username',
    'required' => true,
    'validators' => [
        [
            'name' => 'not_empty',
        ],
        [
            'name' => 'string_length',
            'options' => [
                'min' => 5
            ],
        ],
    ],
]);

// Adding another input filter what also contains a single input. Merging both.
$filter->add([
    'type' => 'Zend\InputFilter\InputFilter',
    'password' => [
        'name' => 'password',
        'required' => true,
        'validators' => [
            [
                'name' => 'not_empty',
            ],
            [
                'name' => 'string_length',
                'options' => [
                    'min' => 8
                ],
            ],
        ],
    ],
]);
```

The `merge()` method may be used on an `InputFilterInterface` instance in order
to add two or more filters to each other, effectively allowing you to create
chains of filters. This is especially useful in object hierarchies that define a
generic set of validation rules on the base object and build on these to create
more specific rules.

In the example below, an `InputFilter` is built creating name and email
properties, allowing them to be re-used elsewhere. When the `isValid()` method
is called on the object, all of the merged filters are run against the calling
object in order to validate the internal properties based on our compound set of
filters.

```php
use Zend\InputFilter\InputFilter;

/**
 * Filter to ensure a name property is set and > 8 characters
 */
class NameInputFilter extends InputFilter
{
    /** Filter body goes here **/
}

/**
 * Filter to ensure an email property is set and > 8 characters and is valid
 */
class EmailInputFilter extends InputFilter
{
    /** Filter body goes here **/
}

class SimplePerson
{
    /** Member variables ommitted for berevity **/

    /** @var InputFilter */
    protected $inputFilter;

    /**
     * Retrieve input filter
     *
     * @return InputFilter
     */
    public function getInputFilter()
    {
        if (! $this->inputFilter) {
            // Create a new input filter
            $this->inputFilter = new InputFilter();

            // Merge our inputFilter in for the email property
            $this->inputFilter->merge(new EmailInputFilter());

            // Merge our inputFilter in for the name property
            $this->inputFilter->merge(new NameInputFilter());
        }

        return $this->inputFilter;
    }

    /**
     * Set input filter
     *
     * @param  InputFilterInterface $inputFilter
     * @return SimplePerson
     */
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        $this->inputFilter = $inputFilter;

        return $this;
    }
}
```

Also see

- [zend-filter](https://zendframework.github.io/zend-filter/)
- [zend-validator](https://github.com/zendframework/zend-validator/)


text:
use x86_64::structures::idt::ExceptionStackFrame;

use device::local_apic::LOCAL_APIC;

/// Handler for a Inter-Process Interrupt (IPI)
pub extern "x86-interrupt" fn ipi(stack_frame: &mut ExceptionStackFrame) {
    unsafe { LOCAL_APIC.end_of_interrupt(); }
}


text:
#include "ble_dtm.h"
#include <stdbool.h>
#include <string.h>
#include "nrf.h"

#define DTM_HEADER_OFFSET        0                                         /**< Index where the header of the pdu is located. */
#define DTM_HEADER_SIZE          2                                         /**< Size of PDU header. */
#define DTM_PAYLOAD_MAX_SIZE     37                                        /**< Maximum payload size allowed during dtm execution. */
#define DTM_LENGTH_OFFSET        (DTM_HEADER_OFFSET + 1)                   /**< Index where the length of the payload is encoded. */
#define DTM_PDU_MAX_MEMORY_SIZE  (DTM_HEADER_SIZE + DTM_PAYLOAD_MAX_SIZE)  /**< Maximum PDU size allowed during dtm execution. */

/**@details The UART poll cycle in micro seconds.
 *          Baud rate of 19200 bits / second, and 8 data bits, 1 start/stop bit, no flow control,
 *          give the time to transmit a byte: 10 bits * 1/19200 = approx: 520 us.
 *
 *          To ensure no loss of bytes, the UART should be polled every 260 us.
 *
 * @note If UART bit rate is changed, this value should be recalculated as well.
 */
#define UART_POLL_CYCLE  260

#define RX_MODE          true   /**< Constant defining RX mode for radio during dtm test. */
#define TX_MODE          false  /**< Constant defining TX mode for radio during dtm test. */

#define PHYS_CH_MAX      39     /**< Maximum number of valid channels in BLE. */

// Values that for now are "constants" - they could be configured by a function setting them,
// but most of these are set by the BLE DTM standard, so changing them is not relevant.
#define RFPHY_TEST_0X0F_REF_PATTERN  0x0f  /**<  RF-PHY test packet patterns, for the repeated octet packets. */
#define RFPHY_TEST_0X55_REF_PATTERN  0x55  /**<  RF-PHY test packet patterns, for the repeated octet packets. */

#define PRBS9_CONTENT {0xff, 0xc1, 0xfb, 0xe8, 0x4c, 0x90, 0x72, 0x8b,  \
                       0xe7, 0xb3, 0x51, 0x89, 0x63, 0xab, 0x23, 0x23,  \
                       0x2,  0x84, 0x18, 0x72, 0xaa, 0x61, 0x2f, 0x3b,  \
                       0x51, 0xa8, 0xe5, 0x37, 0x49, 0xfb, 0xc9, 0xca,  \
                       0xc,  0x18, 0x53, 0x2c, 0xfd}                         /**< The PRBS9 sequence used as packet payload. */

/**@brief Structure holding the PDU used for transmitting/receiving a PDU.
 */
typedef struct
{
    uint8_t content[DTM_HEADER_SIZE + DTM_PAYLOAD_MAX_SIZE];                 /**< PDU packet content. */
} pdu_type_t;

/**@brief States used for the DTM test implementation.
 */
typedef enum
{
    STATE_UNINITIALIZED,                                                     /**< The DTM is uninitialized. */
    STATE_IDLE,                                                              /**< State when system has just initialized, or current test has completed. */
    STATE_TRANSMITTER_TEST,                                                  /**< State used when a DTM Transmission test is running. */
    STATE_CARRIER_TEST,                                                      /**< State used when a DTM Carrier test is running (Vendor specific test). */
    STATE_RECEIVER_TEST                                                      /**< State used when a DTM Receive test is running. */
} state_t;

// Internal variables set as side effects of commands or events.
static state_t           m_state = STATE_UNINITIALIZED;                      /**< Current machine state. */
static uint16_t          m_rx_pkt_count;                                     /**< Number of valid packets received. */
static pdu_type_t        m_pdu;                                              /**< PDU to be sent. */
static uint16_t          m_event;                                            /**< current command status - initially "ok", may be set if error detected, or to packet count. */
static bool              m_new_event;                                        /**< Command has been processed - number of not yet reported event bytes. */
static uint8_t           m_packet_length;                                    /**< Payload length of transmitted PDU, bits 2:7 of 16-bit dtm command. */
static dtm_pkt_type_t    m_packet_type;                                      /**< Bits 0..1 of 16-bit transmit command, or 0xFFFFFFFF. */
static dtm_freq_t        m_phys_ch;                                          /**< 0..39 physical channel number (base 2402 MHz, Interval 2 MHz), bits 8:13 of 16-bit dtm command. */
static uint32_t          m_current_time = 0;                                 /**< Counter for interrupts from timer to ensure that the 2 bytes forming a DTM command are received within the time window. */

// Nordic specific configuration values (not defined by BLE standard).
// Definition of initial values found in ble_dtm.h
static int32_t           m_tx_power          = DEFAULT_TX_POWER;             /**< TX power for transmission test, default to maximum value (+4 dBm). */
static NRF_TIMER_Type *  mp_timer            = DEFAULT_TIMER;                /**< Timer to be used. */
static IRQn_Type         m_timer_irq         = DEFAULT_TIMER_IRQn;           /**< which interrupt line to clear on every timeout */

static uint8_t const     m_prbs_content[]    = PRBS9_CONTENT;                /**< Pseudo-random bit sequence defined by the BLE standard. */
static uint8_t           m_packetHeaderLFlen = 8;                            /**< Length of length field in packet Header (in bits). */
static uint8_t           m_packetHeaderS0len = 1;                            /**< Length of S0 field in packet Header (in bytes). */
static uint8_t           m_packetHeaderS1len = 0;                            /**< Length of S1 field in packet Header (in bits). */
static uint8_t           m_crcConfSkipAddr   = 1;                            /**< Leave packet address field out of CRC calculation. */
static uint8_t           m_static_length     = 0;                            /**< Number of bytes sent in addition to the var.length payload. */
static uint32_t          m_balen             = 3;                            /**< Base address length in bytes. */
static uint32_t          m_endian            = RADIO_PCNF1_ENDIAN_Little;    /**< On air endianess of packet, this applies to the S0, LENGTH, S1 and the PAYLOAD fields. */
static uint32_t          m_whitening         = RADIO_PCNF1_WHITEEN_Disabled; /**< Whitening disabled. */
static uint8_t           m_crcLength         = RADIO_CRCCNF_LEN_Three;       /**< CRC Length (in bytes). */
static uint32_t          m_address           = 0x71764129;                   /**< Address. */
static uint32_t          m_crc_poly          = 0x0000065B;                   /**< CRC polynomial. */
static uint32_t          m_crc_init          = 0x00555555;                   /**< Initial value for CRC calculation. */
static uint8_t           m_radio_mode        = RADIO_MODE_MODE_Ble_1Mbit;    /**< nRF51 specific radio mode vale. */
static uint32_t          m_txIntervaluS      = 625;                          /**< Time between start of Tx packets (in uS). */

/**@brief Function for verifying that a received PDU has the expected structure and content.
 */
static bool check_pdu(void)
{
    uint8_t        k;                // Byte pointer for running through PDU payload
    uint8_t        pattern;          // Repeating octet value in payload
    dtm_pkt_type_t pdu_packet_type;  // Note: PDU packet type is a 4-bit field in HCI, but 2 bits in BLE DTM
    uint8_t        length;

    pdu_packet_type = (dtm_pkt_type_t)(m_pdu.content[DTM_HEADER_OFFSET] & 0x0F);
    length          = m_pdu.content[DTM_LENGTH_OFFSET];

    if ((pdu_packet_type > (dtm_pkt_type_t)PACKET_TYPE_MAX) || (length > DTM_PAYLOAD_MAX_SIZE))
    {
        return false;
    }

    if (pdu_packet_type == DTM_PKT_PRBS9)
    {
        // Payload does not consist of one repeated octet; must compare ir with entire block into
        return (memcmp(m_pdu.content+DTM_HEADER_SIZE, m_prbs_content, length) == 0);
    }

    if (pdu_packet_type == DTM_PKT_0X0F)
    {
        pattern = RFPHY_TEST_0X0F_REF_PATTERN;
    }
    else
    {
        pattern = RFPHY_TEST_0X55_REF_PATTERN;
    }

    for (k = 0; k < length; k++)
    {
        // Check repeated pattern filling the PDU payload
        if (m_pdu.content[k + 2] != pattern)
        {
            return false;
        }
    }
    return true;
}

/**@brief Function for turning off the radio after a test.
 *        Also called after test done, to be ready for next test.
 */
static void radio_reset(void)
{
    NRF_PPI->CHENCLR = PPI_CHENCLR_CH0_Msk | PPI_CHENCLR_CH1_Msk;

    NRF_RADIO->SHORTS          = 0;
    NRF_RADIO->EVENTS_DISABLED = 0;
    NRF_RADIO->TASKS_DISABLE   = 1;

    while (NRF_RADIO->EVENTS_DISABLED == 0)
    {
        // Do nothing
    }

    NRF_RADIO->EVENTS_DISABLED = 0;
    NRF_RADIO->TASKS_RXEN      = 0;
    NRF_RADIO->TASKS_TXEN      = 0;

    m_rx_pkt_count = 0;
}

/**@brief Function for initializing the radio for DTM.
 */
static uint32_t radio_init(void)
{
#ifdef NRF51
    // Handle BLE Radio tuning parameters from production for DTM if required.
    // Only needed for DTM without SoftDevice, as the SoftDevice normally handles this.
    // PCN-083.
    if ( ((NRF_FICR->OVERRIDEEN) & FICR_OVERRIDEEN_BLE_1MBIT_Msk) == FICR_OVERRIDEEN_BLE_1MBIT_Override)
    {
        NRF_RADIO->OVERRIDE0 = NRF_FICR->BLE_1MBIT[0];
        NRF_RADIO->OVERRIDE1 = NRF_FICR->BLE_1MBIT[1];
        NRF_RADIO->OVERRIDE2 = NRF_FICR->BLE_1MBIT[2];
        NRF_RADIO->OVERRIDE3 = NRF_FICR->BLE_1MBIT[3];
        NRF_RADIO->OVERRIDE4 = NRF_FICR->BLE_1MBIT[4];
    }
#endif // NRF51

    // Initializing code below is quite generic - for BLE, the values are fixed, and expressions
    // are constant. Non-constant values are essentially set in radio_prepare().
    if (((m_tx_power & 0x03) != 0)           ||      // tx_power should be a multiple of 4
         ((m_tx_power & 0xffffff00) != 0)    ||      // Upper 24 bits are required to be zeroed
         ((int8_t)m_tx_power > 4)            ||      // Max tx_power is +4 dBm
         ((int8_t)(m_tx_power & 0xff) < -40) ||      // Min tx_power is -40 dBm
         (m_radio_mode > RADIO_MODE_MODE_Ble_1Mbit)  // Values 0-2: Proprietary mode, 3 (last valid): BLE
       )
    {
        return DTM_ERROR_ILLEGAL_CONFIGURATION;
    }

    // Turn off radio before configuring it
    radio_reset();

    NRF_RADIO->TXPOWER = m_tx_power;
    NRF_RADIO->MODE    = m_radio_mode << RADIO_MODE_MODE_Pos;

    // Set the access address, address0/prefix0 used for both Rx and Tx address
    NRF_RADIO->PREFIX0    &= ~RADIO_PREFIX0_AP0_Msk;
    NRF_RADIO->PREFIX0    |= (m_address >> 24) & RADIO_PREFIX0_AP0_Msk;
    NRF_RADIO->BASE0       = m_address << 8;
    NRF_RADIO->RXADDRESSES = RADIO_RXADDRESSES_ADDR0_Enabled << RADIO_RXADDRESSES_ADDR0_Pos;
    NRF_RADIO->TXADDRESS   = (0x00 << RADIO_TXADDRESS_TXADDRESS_Pos) & RADIO_TXADDRESS_TXADDRESS_Msk;

    // Configure CRC calculation
    NRF_RADIO->CRCCNF = (m_crcConfSkipAddr << RADIO_CRCCNF_SKIP_ADDR_Pos) |
                        (m_crcLength << RADIO_CRCCNF_LEN_Pos);

    NRF_RADIO->PCNF0 = (m_packetHeaderS1len << RADIO_PCNF0_S1LEN_Pos) |
                       (m_packetHeaderS0len << RADIO_PCNF0_S0LEN_Pos) |
                       (m_packetHeaderLFlen << RADIO_PCNF0_LFLEN_Pos);

    NRF_RADIO->PCNF1 = (m_whitening          << RADIO_PCNF1_WHITEEN_Pos) |
                       (m_endian             << RADIO_PCNF1_ENDIAN_Pos)  |
                       (m_balen              << RADIO_PCNF1_BALEN_Pos)   |
                       (m_static_length      << RADIO_PCNF1_STATLEN_Pos) |
                       (DTM_PAYLOAD_MAX_SIZE << RADIO_PCNF1_MAXLEN_Pos);

    return DTM_SUCCESS;
}

/**@brief Function for preparing the radio. At start of each test: Turn off RF, clear interrupt flags of RF, initialize the radio
 *        at given RF channel.
 *
 *@param[in] rx     boolean indicating if radio should be prepared in rx mode (true) or tx mode.
 */
static void radio_prepare(bool rx)
{
#ifdef NRF51
    NRF_RADIO->TEST         = 0;
#elif defined(NRF52)
    NRF_RADIO->MODECNF0     = (RADIO_MODECNF0_RU_Default << RADIO_MODECNF0_RU_Pos) |
                              (RADIO_MODECNF0_DTX_B1 << RADIO_MODECNF0_DTX_Pos);
#endif // NRF51 / NRF52
    NRF_RADIO->CRCPOLY      = m_crc_poly;
    NRF_RADIO->CRCINIT      = m_crc_init;
    NRF_RADIO->FREQUENCY    = (m_phys_ch << 1) + 2;                  // Actual frequency (MHz): 2400 + register value
    NRF_RADIO->PACKETPTR    = (uint32_t)&m_pdu;                      // Setting packet pointer will start the radio
    NRF_RADIO->EVENTS_READY = 0;
    NRF_RADIO->SHORTS       = (1 << RADIO_SHORTS_READY_START_Pos) |  // Shortcut between READY event and START task
                              (1 << RADIO_SHORTS_END_DISABLE_Pos);   // Shortcut between END event and DISABLE task

    if (rx)
    {
        NRF_RADIO->EVENTS_END = 0;
        NRF_RADIO->TASKS_RXEN = 1;  // shorts will start radio in RX mode when it is ready
    }
    else // tx
    {
        NRF_RADIO->TXPOWER = m_tx_power;
    }
}

/**@brief Function for terminating the ongoing test (if any) and closing down the radio.
 */
static void dtm_test_done(void)
{
#ifdef NRF51
    NRF_RADIO->TEST = 0;
#elif defined(NRF52)
    NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_RU_Default << RADIO_MODECNF0_RU_Pos) |
                          (RADIO_MODECNF0_DTX_B1 << RADIO_MODECNF0_DTX_Pos);
#endif // NRF51 / NRF52
    NRF_PPI->CHENCLR = 0x01;
    NRF_PPI->CH[0].EEP = 0;     // Break connection from timer to radio to stop transmit loop
    NRF_PPI->CH[0].TEP = 0;

    radio_reset();
    m_state = STATE_IDLE;
}

/**@brief Function for configuring the timer for 625us cycle time.
 */
static uint32_t timer_init(void)
{
    // Use 16MHz from external crystal
    // This could be customized for RC/Xtal, or even to use a 32 kHz crystal
    NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;
    NRF_CLOCK->TASKS_HFCLKSTART    = 1;

    while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0)
    {
        // Do nothing while waiting for the clock to start
    }

    mp_timer->TASKS_STOP        = 1;                      // Stop timer, if it was running
    mp_timer->TASKS_CLEAR       = 1;
    mp_timer->MODE              = TIMER_MODE_MODE_Timer;  // Timer mode (not counter)
    mp_timer->EVENTS_COMPARE[0] = 0;                      // clean up possible old events
    mp_timer->EVENTS_COMPARE[1] = 0;
    mp_timer->EVENTS_COMPARE[2] = 0;
    mp_timer->EVENTS_COMPARE[3] = 0;

    // Timer is polled, but enable the compare0 interrupt in order to wakeup from CPU sleep
    mp_timer->INTENSET    = TIMER_INTENSET_COMPARE0_Msk;
    mp_timer->SHORTS      = 1 << TIMER_SHORTS_COMPARE0_CLEAR_Pos;  // Clear the count every time timer reaches the CCREG0 count
    mp_timer->PRESCALER   = 4;                                     // Input clock is 16MHz, timer clock = 2 ^ prescale -> interval 1us
    mp_timer->CC[0]       = m_txIntervaluS;                        // 625uS with 1MHz clock to the timer
    mp_timer->CC[1]       = UART_POLL_CYCLE;                       // 260uS with 1MHz clock to the timer
    mp_timer->TASKS_START = 1;                                     // Start the timer - it will be running continuously
    m_current_time        = 0;
    return DTM_SUCCESS;
}

/**@brief Function for handling vendor specific commands.
 *        Used when packet type is set to Vendor specific.
 *        The length field is used for encoding vendor specific command.
 *        The frequency field is used for encoding vendor specific options to the command.
 *
 * @param[in]   vendor_cmd      Vendor specific command to be executed.
 * @param[in]   vendor_option   Vendor specific option to the vendor command.
 *
 * @return      DTM_SUCCESS or one of the DTM_ERROR_ values
 */
static uint32_t dtm_vendor_specific_pkt(uint32_t vendor_cmd, dtm_freq_t vendor_option)
{
    switch (vendor_cmd)
    {
        // nRFgo Studio uses CARRIER_TEST_STUDIO to indicate a continuous carrier without
        // a modulated signal.
        case CARRIER_TEST:
        case CARRIER_TEST_STUDIO:
            // Not a packet type, but used to indicate that a continuous carrier signal
            // should be transmitted by the radio.
            radio_prepare(TX_MODE);
#ifdef NRF51
            NRF_RADIO->TEST = (RADIO_TEST_PLL_LOCK_Enabled << RADIO_TEST_PLL_LOCK_Pos) |
                              (RADIO_TEST_CONST_CARRIER_Enabled << RADIO_TEST_CONST_CARRIER_Pos);
#elif defined(NRF52)
            NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_RU_Default << RADIO_MODECNF0_RU_Pos) |
                                  (RADIO_MODECNF0_DTX_B1 << RADIO_MODECNF0_DTX_Pos);
#endif // NRF51 / NRF52

            // Shortcut between READY event and START task
            NRF_RADIO->SHORTS = 1 << RADIO_SHORTS_READY_START_Pos;

            // Shortcut will start radio in Tx mode when it is ready
            NRF_RADIO->TASKS_TXEN = 1;
            m_state               = STATE_CARRIER_TEST;
            break;

        case SET_TX_POWER:
            if (!dtm_set_txpower(vendor_option))
            {
                return DTM_ERROR_ILLEGAL_CONFIGURATION;
            }
            break;

        case SELECT_TIMER:
            if (!dtm_set_timer(vendor_option))
            {
                return DTM_ERROR_ILLEGAL_CONFIGURATION;
            }
            break;
    }
    // Event code is unchanged, successful
    return DTM_SUCCESS;
}

uint32_t dtm_init(void)
{
    if ((timer_init() != DTM_SUCCESS) || (radio_init() != DTM_SUCCESS))
    {
        return DTM_ERROR_ILLEGAL_CONFIGURATION;
    }
    m_new_event = false;
    m_state     = STATE_IDLE;

    // Enable wake-up on event
    SCB->SCR |= SCB_SCR_SEVONPEND_Msk;

    return DTM_SUCCESS;
}

uint32_t dtm_wait(void)
{
    // Enable wake-up on event
    SCB->SCR |= SCB_SCR_SEVONPEND_Msk;

    for (;;)
    {
        // Event may be the reception of a packet -
        // handle radio first, to give it highest priority:
        if (NRF_RADIO->EVENTS_END != 0)
        {
            NRF_RADIO->EVENTS_END = 0;
            NVIC_ClearPendingIRQ(RADIO_IRQn);

            if (m_state == STATE_RECEIVER_TEST)
            {
                NRF_RADIO->TASKS_RXEN = 1;
                if ((NRF_RADIO->CRCSTATUS == 1) && check_pdu())
                {
                    // Count the number of successfully received packets
                    m_rx_pkt_count++;
                }
                // Note that failing packets are simply ignored (CRC or contents error).

                // Zero fill all pdu fields to avoid stray data
                memset(&m_pdu, 0, DTM_PDU_MAX_MEMORY_SIZE);
            }
            // If no RECEIVER_TEST is running, ignore incoming packets (but do clear IRQ!)
        }

        // Check for timeouts:
        if (mp_timer->EVENTS_COMPARE[0] != 0)
        {
            mp_timer->EVENTS_COMPARE[0] = 0;
        }
        else if (mp_timer->EVENTS_COMPARE[1] != 0)
        {
            // Reset timeout event flag for next iteration.
            mp_timer->EVENTS_COMPARE[1] = 0;
            NVIC_ClearPendingIRQ(m_timer_irq);
            return ++m_current_time;
        }

        // Other events: No processing
    }
}

uint32_t dtm_cmd(dtm_cmd_t cmd, dtm_freq_t freq, uint32_t length, dtm_pkt_type_t payload)
{
    // Save specified packet in static variable for tx/rx functions to use.
    // Note that BLE conformance testers always use full length packets.
    m_packet_length = ((uint8_t)length & 0xFF);
    m_packet_type   = payload;
    m_phys_ch       = freq;

    // Clean out any non-retrieved event that might linger from an earlier test
    m_new_event     = true;

    // Set default event; any error will set it to LE_TEST_STATUS_EVENT_ERROR
    m_event         = LE_TEST_STATUS_EVENT_SUCCESS;

    if (m_state == STATE_UNINITIALIZED)
    {
        // Application has not explicitly initialized DTM,
        return DTM_ERROR_UNINITIALIZED;
    }

    if (cmd == LE_RESET)
    {
        // Note that timer will continue running after a reset
        dtm_test_done();
        return DTM_SUCCESS;
    }

    if (cmd == LE_TEST_END)
    {
        if (m_state == STATE_IDLE)
        {
            // Sequencing error - only rx or tx test may be ended!
            m_event = LE_TEST_STATUS_EVENT_ERROR;
            return DTM_ERROR_INVALID_STATE;
        }
        m_event = LE_PACKET_REPORTING_EVENT | m_rx_pkt_count;
        dtm_test_done();
        return DTM_SUCCESS;
    }

    if (m_state != STATE_IDLE)
    {
        // Sequencing error - only TEST_END/RESET are legal while test is running
        // Note: State is unchanged; ongoing test not affected
        m_event = LE_TEST_STATUS_EVENT_ERROR;
        return DTM_ERROR_INVALID_STATE;
    }

    if (m_phys_ch > PHYS_CH_MAX)
    {
        // Parameter error
        // Note: State is unchanged; ongoing test not affected
        m_event = LE_TEST_STATUS_EVENT_ERROR;
        return DTM_ERROR_ILLEGAL_CHANNEL;
    }

    m_rx_pkt_count = 0;

    if (cmd == LE_RECEIVER_TEST)
    {
        // Zero fill all pdu fields to avoid stray data from earlier test run
        memset(&m_pdu, 0, DTM_PDU_MAX_MEMORY_SIZE);
        radio_prepare(RX_MODE);                      // Reinitialize "everything"; RF interrupts OFF
        m_state = STATE_RECEIVER_TEST;
        return DTM_SUCCESS;
    }

    if (cmd == LE_TRANSMITTER_TEST)
    {
        if (m_packet_length > DTM_PAYLOAD_MAX_SIZE)
        {
            // Parameter error
            m_event = LE_TEST_STATUS_EVENT_ERROR;
            return DTM_ERROR_ILLEGAL_LENGTH;
        }

        // Note that PDU uses 4 bits even though BLE DTM uses only 2 (the HCI SDU uses all 4)
        m_pdu.content[DTM_HEADER_OFFSET] = ((uint8_t)m_packet_type & 0x0F);
        m_pdu.content[DTM_LENGTH_OFFSET] = m_packet_length;

        switch (m_packet_type)
        {
            case DTM_PKT_PRBS9:
                // Non-repeated, must copy entire pattern to PDU
                memcpy(m_pdu.content + DTM_HEADER_SIZE, m_prbs_content, length);
                break;

            case DTM_PKT_0X0F:
                // Bit pattern 00001111 repeated
                memset(m_pdu.content + DTM_HEADER_SIZE, RFPHY_TEST_0X0F_REF_PATTERN, length);
                break;

            case DTM_PKT_0X55:
                // Bit pattern 01010101 repeated
                memset(m_pdu.content + DTM_HEADER_SIZE, RFPHY_TEST_0X55_REF_PATTERN, length);
                break;

            case DTM_PKT_VENDORSPECIFIC:
                // The length field is for indicating the vendor specific command to execute.
                // The frequency field is used for vendor specific options to the command.
                return dtm_vendor_specific_pkt(length, freq);

            default:
                // Parameter error
                m_event = LE_TEST_STATUS_EVENT_ERROR;
                return DTM_ERROR_ILLEGAL_CONFIGURATION;
        }

        // Initialize CRC value, set channel:
        radio_prepare(TX_MODE);
        // Configure PPI so that timer will activate radio every 625 us
        NRF_PPI->CH[0].EEP = (uint32_t)&mp_timer->EVENTS_COMPARE[0];
        NRF_PPI->CH[0].TEP = (uint32_t)&NRF_RADIO->TASKS_TXEN;
        NRF_PPI->CHENSET   = 0x01;
        m_state            = STATE_TRANSMITTER_TEST;
    }
    return DTM_SUCCESS;
}

bool dtm_event_get(dtm_event_t *p_dtm_event)
{
    bool was_new = m_new_event;
    // mark the current event as retrieved
    m_new_event  = false;
    *p_dtm_event = m_event;
    // return value indicates whether this value was already retrieved.
    return was_new;
}

// =================================================================================================
// Configuration functions (only for parameters not definitely determined by the BLE DTM standard).
// These functions return true if successful, false if value could not be set

/**@brief Function for configuring the output power for transmitter test.
          This function may be called directly, or through dtm_cmd() specifying
          DTM_PKT_VENDORSPECIFIC as payload, SET_TX_POWER as length, and the dBm value as frequency.
 */
bool dtm_set_txpower(uint32_t new_tx_power)
{
    // radio->TXPOWER register is 32 bits, low octet a signed value, upper 24 bits zeroed
    int8_t new_power8 = (int8_t)(new_tx_power & 0xFF);

    if (m_state > STATE_IDLE)
    {
        // radio must be idle to change the tx power
        return false;
    }

    if ((new_power8 > 4) || (new_power8 < -40))
    {
        // Parameter outside valid range: nRF radio is restricted to the range -40 dBm to +4 dBm
        return false;
    }

    if (new_tx_power & 0x03)
    {
        // Parameter error: The nRF51 radio requires settings that are a multiple of 4.
        return false;
    }
    m_tx_power = new_tx_power;

    return true;
}

/**@brief Function for selecting a timer resource.
 *        This function may be called directly, or through dtm_cmd() specifying
 *        DTM_PKT_VENDORSPECIFIC as payload, SELECT_TIMER as length, and the timer as freq
 *
 * @param[in] new_timer     Timer id for the timer to use: 0, 1, or 2.
 *
 * @return true if the timer was successfully changed, false otherwise.
 */
bool dtm_set_timer(uint32_t new_timer)
{
    if (m_state > STATE_IDLE)
    {
        return false;
    }
    if (new_timer == 0)
    {
        mp_timer    = NRF_TIMER0;
        m_timer_irq = TIMER0_IRQn;
    }
    else if (new_timer == 1)
    {
        mp_timer    = NRF_TIMER1;
        m_timer_irq = TIMER1_IRQn;
    }
    else if (new_timer == 2)
    {
        mp_timer    = NRF_TIMER2;
        m_timer_irq = TIMER2_IRQn;
    }
    else
    {
        // Parameter error: Only TIMER 0, 1, 2 provided by nRF51
        return false;
    }
    // New timer has been selected:
    return true;
}

/// @}


text:
SCRIPT_DIR=$(dirname $0)
ADDED_DIR=${SCRIPT_DIR}/added

# Make sure the owner of added files is the 'jboss' user
chown -R jboss:jboss ${SCRIPT_DIR}

# Necessary to permit running with a randomised UID
chmod -R a+rwX ${SCRIPT_DIR}

# Move the parent EAP S2I assemble script and install child S2I scripts
mv /usr/local/s2i/assemble /usr/local/s2i/assemble_eap
cp -r ${ADDED_DIR}/s2i/* /usr/local/s2i/
chmod 755 /usr/local/s2i/*


text:
package org.protempa.proposition;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * A unique identifier for a data source backend.
 *
 * @author Himanshu Rathod
 */
public final class DataSourceBackendId extends SourceId {

    private static Map<String, DataSourceBackendId> cache =
            new HashMap<>();

    private final String id;
    private transient volatile int hashCode;

    /**
     * Creates a data source backend id.
     *
     * @param id the id {@link String}. Cannot be null.
     * @return a {@link DataSourceBackendId}.
     */
    public static DataSourceBackendId getInstance(String id) {
        DataSourceBackendId result = cache.get(id);
        if (result == null) {
            id = id.intern();
            result = new DataSourceBackendId(id);
            cache.put(id, result);
        }
        return result;
    }

    @Override
    String getId() {
        return this.id;
    }

    /**
     * Creates a new data source backend id. Only used by
     * {@link #getInstance(java.lang.String)}.
     *
     * @param newId the id {@link String}. Cannot be null.
     */
    private DataSourceBackendId(String newId) {
        if (newId == null) {
            throw new IllegalArgumentException("newId cannot be null");
        }
        this.id = newId;
    }

    @Override
    public int hashCode() {
        if (this.hashCode == 0) {
            int result = 17;
            result = 37 * result + id.hashCode();
            this.hashCode = result;
        }
        return this.hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final DataSourceBackendId other = (DataSourceBackendId) obj;
        return this.id.equals(other.id);
    }

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


text:
using System;
using System.Collections.Generic;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAdmin.Diagnostics.Checks;
using XenAdmin.Diagnostics.Hotfixing;
using XenAdmin.Wizards.PatchingWizard;
using XenAPI;
using System.Linq;
using CheckGroup = System.Collections.Generic.KeyValuePair<string, System.Collections.Generic.List<XenAdmin.Diagnostics.Checks.Check>>;

namespace XenAdmin.Wizards.RollingUpgradeWizard
{
    public partial class RollingUpgradeWizardPrecheckPage : PatchingWizard_PrecheckPage
    {
        public RollingUpgradeWizardPrecheckPage()
        {
            InitializeComponent();
            ManualUpgrade = true;
        }

        private void AddEventHandlersToMasters()
        {
            foreach (Host master in SelectedMasters)
            {
                master.Connection.ConnectionStateChanged += connection_ConnectionChanged;
                master.Connection.CachePopulated += connection_ConnectionChanged;
            }
        }

        private void RemoveEventHandlersToMasters()
        {
            foreach (Host master in SelectedMasters)
            {
                master.Connection.ConnectionStateChanged -= connection_ConnectionChanged;
                master.Connection.CachePopulated -= connection_ConnectionChanged;
            }
        }

        private void connection_ConnectionChanged(object sender, EventArgs eventArgs)
        {
            Program.Invoke(this, RefreshRechecks);
        }

        protected override void PageLoadedCore(PageLoadedDirection direction)
        {
            if (direction == PageLoadedDirection.Back)
            {
                RefreshRechecks();
                return;
            }
            var selectedMasters = new List<Host>(SelectedMasters);
            RemoveEventHandlersToMasters();
            SelectedServers.Clear();
            foreach (Host selectedMaster in selectedMasters)
            {
                Host master = selectedMaster;
                if (master != null)
                {
                    Pool pool = Helpers.GetPoolOfOne(master.Connection);
                    if (pool != null)
                        SelectedServers.AddRange(pool.HostsToUpgrade());
                    else
                        SelectedServers.Add(master);
                }
            }
            AddEventHandlersToMasters();
            labelPrechecksFirstLine.Text = Messages.ROLLINGUPGRADE_PRECHECKS;
            RefreshRechecks();
        }

        protected override void PageLeaveCore(PageLoadedDirection direction, ref bool cancel)
        {
            RemoveEventHandlersToMasters();
        }

        public override void PageCancelled(ref bool cancel)
        {
            base.PageCancelled(ref cancel);
            if (cancel)
                return;
            RemoveEventHandlersToMasters();
        }

        public override string PageTitle
        {
            get
            {
                return Messages.UPGRADE_PRECHECKS_TITLE;
            }
        }

        public override string Text
        {
            get
            {
                return Messages.UPGRADE_PRECHECKS_TEXT;
            }
        }

        public override string HelpID
        {
            get { return "Upgradeprechecks"; }
        }

        public override string NextText(bool isLastPage)
        {
            return Messages.START_UPGRADE;
        }

        protected override List<CheckGroup> GenerateChecks(Pool_patch patch)
        {
            var groups = new List<CheckGroup>();

            List<Host> hostsToUpgrade = new List<Host>();
            List<Host> hostsToUpgradeOrUpdate = new List<Host>();
            foreach (var pool in SelectedPools)
            {
                var poolHostsToUpgrade = pool.HostsToUpgrade();
                hostsToUpgrade.AddRange(poolHostsToUpgrade);
                hostsToUpgradeOrUpdate.AddRange(ApplyUpdatesToNewVersion
                    ? HostsToUpgradeOrUpdate(pool)
                    : poolHostsToUpgrade);
            }

            //XenCenter version check (if any of the selected server version is not the latest)
            var latestCrVersion = Updates.XenServerVersions.FindAll(item => item.LatestCr).OrderByDescending(v => v.Version).FirstOrDefault();
            if (latestCrVersion != null &&
                hostsToUpgradeOrUpdate.Any(host => new Version(Helpers.HostProductVersion(host)) < latestCrVersion.Version))
            {
                groups.Add(new CheckGroup(Messages.CHECKING_XENCENTER_VERSION, new List<Check> {new XenCenterVersionCheck(null)}));
            }

            //HostMaintenanceModeCheck checks - for hosts that will be upgraded or updated
            var livenessChecks = new List<Check>();
            foreach (Host host in hostsToUpgradeOrUpdate)
                livenessChecks.Add(new HostLivenessCheck(host, hostsToUpgrade.Contains(host)));
            groups.Add(new CheckGroup(Messages.CHECKING_HOST_LIVENESS_STATUS, livenessChecks));

            //HotfixesCheck - for hosts that will be upgraded
            var hotfixChecks = new List<Check>();
            foreach (var host in hostsToUpgrade)
            {
                if (new HotfixFactory().IsHotfixRequired(host) && !ManualUpgrade)
                    hotfixChecks.Add(new HostHasHotfixCheck(host));
            }
            if (hotfixChecks.Count > 0)
                groups.Add(new CheckGroup(Messages.CHECKING_UPGRADE_HOTFIX_STATUS, hotfixChecks));

            //SafeToUpgrade- and PrepareToUpgrade- checks - in automatic mode only, for hosts that will be upgraded
            if (!ManualUpgrade)
            {
                var prepareToUpgradeChecks = new List<Check>();
                foreach (var host in hostsToUpgrade)
                    prepareToUpgradeChecks.Add(new PrepareToUpgradeCheck(host, InstallMethodConfig));
                groups.Add(new CheckGroup(Messages.CHECKING_PREPARE_TO_UPGRADE, prepareToUpgradeChecks));

                var safeToUpgradeChecks = new List<Check>();
                foreach (var host in hostsToUpgrade)
                    safeToUpgradeChecks.Add(new SafeToUpgradeCheck(host));
                groups.Add(new CheckGroup(Messages.CHECKING_SAFE_TO_UPGRADE, safeToUpgradeChecks));
            }

            //HA checks - for each pool
            var haChecks = (from Host server in SelectedMasters
                select new HAOffCheck(server) as Check).ToList();
            groups.Add(new CheckGroup(Messages.CHECKING_HA_STATUS, haChecks));

            //Checking can evacuate host - for hosts that will be upgraded or updated
            var evacuateChecks = new List<Check>();
            foreach (Host host in hostsToUpgradeOrUpdate)
                evacuateChecks.Add(new AssertCanEvacuateUpgradeCheck(host));
            groups.Add(new CheckGroup(Messages.CHECKING_CANEVACUATE_STATUS, evacuateChecks));

            //PBDsPluggedCheck -  for hosts that will be upgraded or updated
            var pbdChecks = new List<Check>();
            foreach (Host host in hostsToUpgradeOrUpdate)
                pbdChecks.Add(new PBDsPluggedCheck(host));
            groups.Add(new CheckGroup(Messages.CHECKING_STORAGE_CONNECTIONS_STATUS, pbdChecks));

            //HostMemoryPostUpgradeCheck - for hosts that will be upgraded
            var mostMemoryPostUpgradeChecks = new List<Check>();
            foreach (var host in hostsToUpgrade)
            {
                mostMemoryPostUpgradeChecks.Add(new HostMemoryPostUpgradeCheck(host, InstallMethodConfig));
            }
            if (mostMemoryPostUpgradeChecks.Count > 0)
                groups.Add(new CheckGroup(Messages.CHECKING_HOST_MEMORY_POST_UPGRADE, mostMemoryPostUpgradeChecks));

            var gfs2Checks = new List<Check>();
            foreach (Pool pool in SelectedPools.Where(p =>
                Helpers.KolkataOrGreater(p.Connection) && !Helpers.LimaOrGreater(p.Connection)))
            {
                Host host = pool.Connection.Resolve(pool.master);
                gfs2Checks.Add(new PoolHasGFS2SR(host));
            }

            if (gfs2Checks.Count > 0)
            {
                groups.Add(new CheckGroup(Messages.CHECKING_CLUSTERING_STATUS, gfs2Checks));
            }

            //Checking PV guests - for hosts that have any PV guests and warn the user before the upgrade.
            var pvChecks = new List<Check>();
            foreach (Pool pool in SelectedPools.Where(p => !Helpers.QuebecOrGreater(p.Connection)))
            {
                if (pool.Connection.Resolve(pool.master) != null)
                    pvChecks.Add(new PVGuestsCheck(pool, true, InstallMethodConfig, ManualUpgrade));
            }
            if (pvChecks.Count > 0)
                groups.Add(new CheckGroup(Messages.CHECKING_PV_GUESTS, pvChecks));

            //Checking automated updates are possible if apply updates checkbox is ticked
            if (ApplyUpdatesToNewVersion)
            {
                var automatedUpdateChecks = (from Host server in SelectedMasters
                    select new AutomatedUpdatesLicenseCheck(server) as Check).ToList();

                automatedUpdateChecks.Add(new CfuAvailabilityCheck());

                groups.Add(new CheckGroup(Messages.CHECKING_AUTOMATED_UPDATES_POSSIBLE,
                    automatedUpdateChecks));
            }

            return groups;
        }

        public IEnumerable<Host> SelectedMasters { private get; set; }
        public bool ManualUpgrade { set; private get; }

        public Dictionary<string, string> InstallMethodConfig { private get; set; }

        #region private methods
        public static List<Host> HostsToUpgradeOrUpdate(Pool pool)
        {
            var result = new List<Host>();

            if (pool == null)
                return result;

            var master = Helpers.GetMaster(pool);
            if (master == null)
                return result;

            if (pool.IsMasterUpgraded())
            {
                foreach (var h in pool.Connection.Cache.Hosts)
                {
                    if (h.LongProductVersion() != master.LongProductVersion()) // host needs to be upgraded
                        result.Add(h); // host
                    else
                    {
                        //check update sequence for already-upgraded hosts
                        var us = Updates.GetPatchSequenceForHost(h, Updates.GetMinimalPatches(master));
                        if (us != null && us.Count > 0)
                        {
                            result.Add(h);
                        }
                    }
                }
            }
            else
                result.AddRange(pool.Connection.Cache.Hosts);

            result.Sort();

            return result;
        }
        #endregion

    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width user-scalable=no">
    <title>PointerEvent scrolling sample</title>

    <button onclick="x()">Pan-X</button>
    <button onclick="y()">Pan-Y</button>
    <button onclick="scroll()">Scroll</button>
    <button onclick="none()">None</button>


text:
from flask import current_app as app

@app.route('/')
def index():
	return 'Hello from %s' % app.config.SERVICE_NAME


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `EnumeratedItems` struct in crate `rustc_lint`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, EnumeratedItems">

    <title>rustc_lint::middle::subst::EnumeratedItems - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc_lint::<wbr>middle::<wbr>subst

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct rustc_lint::<wbr>middle::<wbr>subst::<wbr>EnumeratedItems<wbr>Unstable
            [-] [+]
        [src]

pub struct EnumeratedItems<'a, T> where T: 'a {
    // some fields omitted
}

Trait Implementations

impl<'a, T> Iterator for EnumeratedItems<'a, T>

type Item = (ParamSpace, usize, &'a T)

fn next(&mut self) -> Option<(ParamSpace, usize, &'a T)>

Derived Implementations

impl<'a, T> Clone for EnumeratedItems<'a, T> where T: 'a, T: Clone

fn clone(&self) -> EnumeratedItems<'a, T>

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
using io.rong.models;
using io.rong.models.response;
using System;
using System.Collections.Generic;
using System.Text;
using io.rong.models.message;
using io.rong.exception;
using io.rong.util;
using System.Web;
using io.rong.util;

namespace io.rong.methods.messages.history
{
    /**
     * 消息历史记录服务
     *
     * docs : http://www.rongcloud.cn/docs/server.html#history_message
     * @author RongCloud
     *
     */
    public class History

    {
        private static readonly Encoding UTF8 = Encoding.UTF8;
        private static readonly String PATH = "message/history";
        private String appKey;
        private String appSecret;
        private RongCloud rongCloud;

        public History(String appKey, String appSecret)
        {
            this.appKey = appKey;
            this.appSecret = appSecret;

        }

        public string AppKey { get => appKey; set => appKey = value; }
        public string AppSecret { get => appSecret; set => appSecret = value; }
        internal RongCloud RongCloud { get => rongCloud; set => rongCloud = value; }

        /**
* 消息历史记录下载地址获取 方法消息历史记录下载地址获取方法。获取 APP 内指定某天某小时内的所有会话消息记录的下载地址。(目前支持二人会话、讨论组、群组、聊天室、客服、系统通知消息历史记录下载)
*
* @param  date:指定北京时间某天某小时,格式为2014010101,表示:2014年1月1日凌晨1点。(必传)
*
* @return HistoryMessageResult
* @throws Exception
**/
        public HistoryMessageResult Get(String date)
        {
            if (date == null)
            {
                return new HistoryMessageResult(1002, "", "", "Paramer 'date' is required");
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("&date=").Append(HttpUtility.UrlEncode(date.ToString(), UTF8));
            String body = sb.ToString();
            if (body.IndexOf("&") == 0)
            {
                body = body.Substring(1, body.Length - 1);
            }
            String result = RongHttpClient.ExecutePost(appKey, appSecret, body,
                                          rongCloud.ApiHostType.Type + "/message/history.json", "application/x-www-form-urlencoded");

            return (HistoryMessageResult)RongJsonUtil.JsonStringToObj<HistoryMessageResult>(CommonUtil.GetResponseByCode(PATH, CheckMethod.GET, result));
        }

        /**
         * 消息历史记录删除方法(删除 APP 内指定某天某小时内的所有会话消息记录。调用该接口返回成功后,date参数指定的某小时的消息记录文件将在随后的5-10分钟内被永久删除。)
         *
         * @param  date:指定北京时间某天某小时,格式为2014010101,表示:2014年1月1日凌晨1点。(必传)
         *
         * @return ResponseResult
         * @throws Exception
         **/
        public ResponseResult Remove(String date)
        {
            if (date == null)
            {
                return new ResponseResult(1002, "Paramer 'date' is required");
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("&date=").Append(HttpUtility.UrlEncode(date.ToString(), UTF8));
            String body = sb.ToString();
            if (body.IndexOf("&") == 0)
            {
                body = body.Substring(1, body.Length - 1);
            }
            String result = RongHttpClient.ExecutePost(appKey, appSecret, body,
                                              rongCloud.ApiHostType.Type + "/message/history/delete.json", "application/x-www-form-urlencoded");

            return (ResponseResult)RongJsonUtil.JsonStringToObj<ResponseResult>(CommonUtil.GetResponseByCode(PATH, CheckMethod.REMOVE, result));

        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface org.avaje.metric.MetricNameCache (avaje-metric-api 3.5.0 API)</title>
<meta name="date" content="2014-08-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.avaje.metric.MetricNameCache

Packages that use MetricNameCache

Package
Description

org.avaje.metric

The main public API for Avaje Metrics.

org.avaje.metric.spi

The service provider API that needs to be implemented by implementors.

Uses of MetricNameCache in org.avaje.metric

Methods in org.avaje.metric that return MetricNameCache

Modifier and Type
Method and Description

static MetricNameCache
MetricManager.getMetricNameCache(Class<?> cls)

Return a MetricNameCache for the given class.

static MetricNameCache
MetricManager.getMetricNameCache(MetricName baseName)

Return a MetricNameCache for a given base metric name.

Uses of MetricNameCache in org.avaje.metric.spi

Methods in org.avaje.metric.spi that return MetricNameCache

Modifier and Type
Method and Description

MetricNameCache
PluginMetricManager.getMetricNameCache(Class<?> cls)

Return the MetricNameCache using the class as a base name.

MetricNameCache
PluginMetricManager.getMetricNameCache(MetricName baseName)

Return the MetricNameCache using a MetricName as a base name.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014. All Rights Reserved.


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta http-equiv="Access-Control-Allow-Origin" content="http://localhost:8080"/>
    <title>测试编译表达式</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">

测试编译表达式

    <input type="text" name="exp" id="input_exp" value="{user.username}">
    <button id="btn_exp">运行</button>

运行结果


text:
package org.openkilda.testing.service.traffexam.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.InputMismatchException;

public final class EndpointAddress implements Serializable {
    public final Inet4Address address;
    public final int port;

    public EndpointAddress(Inet4Address address, int port) {
        this.address = address;
        this.port = port;
    }

    @JsonCreator
    public EndpointAddress(
            @JsonProperty("address") String address,
            @JsonProperty("port") int port) {
        try {
            this.address = (Inet4Address) Inet4Address.getByName(address);
        } catch (UnknownHostException e) {
            throw new InputMismatchException(String.format("Invalid value for \"address\" property: %s", address));
        }
        this.port = port;
    }
}


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

<title>Uses of Class org.security.crypt.AbstractEncryptionCli</title>
<meta name="date" content="2014-09-01">
<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

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.security.crypt.AbstractEncryptionCli

Packages that use AbstractEncryptionCli

Package
Description

org.security.crypt.asymmetric

This package contains classes to implement asymmetric algorithms viz, RSA.

org.security.crypt.symmetric

This package contains classes to implement symmetric algorithms viz, AES, DES, DESede, RC, CAST, Rijndael Twofish, etc.

Uses of AbstractEncryptionCli in org.security.crypt.asymmetric

Subclasses of AbstractEncryptionCli in org.security.crypt.asymmetric

Modifier and Type
Class and Description

class
AsymmetricCli

Command line interface for asymmetric encryption operations.

Uses of AbstractEncryptionCli in org.security.crypt.symmetric

Subclasses of AbstractEncryptionCli in org.security.crypt.symmetric

Modifier and Type
Class and Description

class
SymmetricCli

Command line interface for symmetric encryption operations.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes