repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
UITools/saleor
saleor/order/__init__.py
8246
from enum import Enum from django.conf import settings from django.utils.translation import npgettext_lazy, pgettext_lazy from django_prices.templatetags import prices_i18n from prices import Money class OrderStatus: DRAFT = 'draft' UNFULFILLED = 'unfulfilled' PARTIALLY_FULFILLED = 'partially fulfilled' FULFILLED = 'fulfilled' CANCELED = 'canceled' CHOICES = [ (DRAFT, pgettext_lazy( 'Status for a fully editable, not confirmed order created by ' 'staff users', 'Draft')), (UNFULFILLED, pgettext_lazy( 'Status for an order with no items marked as fulfilled', 'Unfulfilled')), (PARTIALLY_FULFILLED, pgettext_lazy( 'Status for an order with some items marked as fulfilled', 'Partially fulfilled')), (FULFILLED, pgettext_lazy( 'Status for an order with all items marked as fulfilled', 'Fulfilled')), (CANCELED, pgettext_lazy( 'Status for a permanently canceled order', 'Canceled'))] class FulfillmentStatus: FULFILLED = 'fulfilled' CANCELED = 'canceled' CHOICES = [ (FULFILLED, pgettext_lazy( 'Status for a group of products in an order marked as fulfilled', 'Fulfilled')), (CANCELED, pgettext_lazy( 'Status for a fulfilled group of products in an order marked ' 'as canceled', 'Canceled'))] class OrderEvents(Enum): PLACED = 'placed' PLACED_FROM_DRAFT = 'draft_placed' OVERSOLD_ITEMS = 'oversold_items' ORDER_MARKED_AS_PAID = 'marked_as_paid' CANCELED = 'canceled' ORDER_FULLY_PAID = 'order_paid' UPDATED = 'updated' EMAIL_SENT = 'email_sent' PAYMENT_CAPTURED = 'captured' PAYMENT_REFUNDED = 'refunded' PAYMENT_VOIDED = 'voided' FULFILLMENT_CANCELED = 'fulfillment_canceled' FULFILLMENT_RESTOCKED_ITEMS = 'restocked_items' FULFILLMENT_FULFILLED_ITEMS = 'fulfilled_items' TRACKING_UPDATED = 'tracking_updated' NOTE_ADDED = 'note_added' # Used mostly for importing legacy data from before Enum-based events OTHER = 'other' class OrderEventsEmails(Enum): PAYMENT = 'payment_confirmation' SHIPPING = 'shipping_confirmation' ORDER = 'order_confirmation' FULFILLMENT = 'fulfillment_confirmation' EMAIL_CHOICES = { OrderEventsEmails.PAYMENT.value: pgettext_lazy( 'Email type', 'Payment confirmation'), OrderEventsEmails.SHIPPING.value: pgettext_lazy( 'Email type', 'Shipping confirmation'), OrderEventsEmails.FULFILLMENT.value: pgettext_lazy( 'Email type', 'Fulfillment confirmation'), OrderEventsEmails.ORDER.value: pgettext_lazy( 'Email type', 'Order confirmation')} def get_money_from_params(amount): """Money serialization changed at one point, as for now it's serialized as a dict. But we keep those settings for the legacy data. Can be safely removed after migrating to Dashboard 2.0 """ if isinstance(amount, Money): return amount if isinstance(amount, dict): return Money(amount=amount['amount'], currency=amount['currency']) return Money(amount, settings.DEFAULT_CURRENCY) def display_order_event(order_event): """This function is used to keep the backwards compatibility with the old dashboard and new type of order events (storing enums instead of messages) """ event_type = order_event.type params = order_event.parameters if event_type == OrderEvents.PLACED_FROM_DRAFT.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order created from draft order by %(user_name)s' % { 'user_name': order_event.user}) if event_type == OrderEvents.PAYMENT_VOIDED.value: return pgettext_lazy( 'Dashboard message related to an order', 'Payment was voided by %(user_name)s' % { 'user_name': order_event.user}) if event_type == OrderEvents.PAYMENT_REFUNDED.value: amount = get_money_from_params(params['amount']) return pgettext_lazy( 'Dashboard message related to an order', 'Successfully refunded: %(amount)s' % { 'amount': prices_i18n.amount(amount)}) if event_type == OrderEvents.PAYMENT_CAPTURED.value: amount = get_money_from_params(params['amount']) return pgettext_lazy( 'Dashboard message related to an order', 'Successfully captured: %(amount)s' % { 'amount': prices_i18n.amount(amount)}) if event_type == OrderEvents.ORDER_MARKED_AS_PAID.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order manually marked as paid by %(user_name)s' % { 'user_name': order_event.user}) if event_type == OrderEvents.CANCELED.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order was canceled by %(user_name)s' % { 'user_name': order_event.user}) if event_type == OrderEvents.FULFILLMENT_RESTOCKED_ITEMS.value: return npgettext_lazy( 'Dashboard message related to an order', 'We restocked %(quantity)d item', 'We restocked %(quantity)d items', number='quantity') % {'quantity': params['quantity']} if event_type == OrderEvents.NOTE_ADDED.value: return pgettext_lazy( 'Dashboard message related to an order', '%(user_name)s added note: %(note)s' % { 'note': params['message'], 'user_name': order_event.user}) if event_type == OrderEvents.FULFILLMENT_CANCELED.value: return pgettext_lazy( 'Dashboard message', 'Fulfillment #%(fulfillment)s canceled by %(user_name)s') % { 'fulfillment': params['composed_id'], 'user_name': order_event.user} if event_type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS.value: return npgettext_lazy( 'Dashboard message related to an order', 'Fulfilled %(quantity_fulfilled)d item', 'Fulfilled %(quantity_fulfilled)d items', number='quantity_fulfilled') % { 'quantity_fulfilled': params['quantity']} if event_type == OrderEvents.PLACED.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order was placed') if event_type == OrderEvents.ORDER_FULLY_PAID.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order was fully paid') if event_type == OrderEvents.EMAIL_SENT.value: return pgettext_lazy( 'Dashboard message related to an order', '%(email_type)s email was sent to the customer ' '(%(email)s)') % { 'email_type': EMAIL_CHOICES[params['email_type']], 'email': params['email']} if event_type == OrderEvents.UPDATED.value: return pgettext_lazy( 'Dashboard message related to an order', 'Order details were updated by %(user_name)s' % { 'user_name': order_event.user}) if event_type == OrderEvents.TRACKING_UPDATED.value: return pgettext_lazy( 'Dashboard message related to an order', 'Fulfillment #%(fulfillment)s tracking was updated to' ' %(tracking_number)s by %(user_name)s') % { 'fulfillment': params['composed_id'], 'tracking_number': params['tracking_number'], 'user_name': order_event.user} if event_type == OrderEvents.OVERSOLD_ITEMS.value: return npgettext_lazy( 'Dashboard message related to an order', '%(quantity)d line item oversold on this order.', '%(quantity)d line items oversold on this order.', number='quantity') % { 'quantity': len(params['oversold_items'])} if event_type == OrderEvents.OTHER.value: return order_event.parameters['message'] raise ValueError('Not supported event type: %s' % (event_type))
bsd-3-clause
tsl143/addons-server
src/olympia/devhub/templates/devhub/base_impala.html
1015
{% extends "impala/base.html" %} {% if addon %} {% set editable_body_class = "no-edit" if not check_addon_ownership(request, addon, dev=True) %} {% endif %} {% block bodyclass %}developer-hub gutter {{ editable_body_class }}{% endblock %} {% block bodyattrs %} {% if addon %}data-default-locale="{{ addon.default_locale|lower }}"{% endif %} {% endblock %} {% block title %}{{ dev_page_title() }}{% endblock %} {% block extrahead %} {{ css('zamboni/devhub_impala') }} {% endblock %} {% block aux_nav %} <li class="nomenu"> <a class="return" href="{{ url('home') }}">{{ _('Back to Add-ons') }}</a> </li> {% endblock %} {% block site_header_title %} {% include "devhub/nav.html" %} {% endblock %} {% block search_form %} {% include "devhub/search.html" %} {% endblock %} {% block js %} {{ js('zamboni/devhub') }} {% endblock %} {% set hide_mobile_link=True %} {% block footer_extras %} <img class="footerlogo" src="{{ static('img/developers/hub-logo-footer.png') }}" alt=""> {% endblock %}
bsd-3-clause
rescrv/Replicant
replicant-benchmark.cc
7712
// Copyright (c) 2015, Robert Escriva // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Replicant nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #define __STDC_LIMIT_MACROS // Google SparseHash #include <google/dense_hash_map> // po6 #include <po6/errno.h> #include <po6/threads/mutex.h> #include <po6/threads/thread.h> #include <po6/time.h> // e #include <e/atomic.h> // Ygor #include <ygor.h> // Replicant #include <replicant.h> #include "tools/common.h" #define MICROS 1000ULL #define MILLIS (1000ULL * MICROS) #define SECONDS (1000ULL * MILLIS) struct benchmark { benchmark(); ~benchmark() throw (); void producer(); void consumer(); const char* output; const char* object; const char* function; long target; long length; ygor_data_logger* dl; uint32_t done; po6::threads::mutex mtx; replicant_client* client; google::dense_hash_map<int64_t, uint64_t> times; replicant_returncode rr; private: benchmark(const benchmark&); benchmark& operator = (const benchmark&); }; benchmark :: benchmark() : output("benchmark.dat.bz2") , object("echo") , function("echo") , target(100) , length(60) , dl(NULL) , done(0) , mtx() , client(NULL) , times() , rr() { times.set_empty_key(INT64_MAX); times.set_deleted_key(INT64_MAX - 1); } benchmark :: ~benchmark() throw () { } void benchmark :: producer() { const uint64_t start = po6::wallclock_time(); const uint64_t end = start + length * SECONDS; uint64_t now = start; uint64_t issued = 0; while (now < end) { double elapsed = double(now - start) / SECONDS; uint64_t expected = elapsed * target; for (uint64_t i = issued; i < expected; ++i) { po6::threads::mutex::hold hold(&mtx); now = po6::wallclock_time(); int64_t id = replicant_client_call(client, object, function, "", 0, 0, &rr, NULL, 0); if (id < 0) { std::cerr << "call failed: " << replicant_client_error_message(client) << " @ " << replicant_client_error_location(client) << std::endl; abort(); } times.insert(std::make_pair(id, now)); } issued = expected; timespec ts; ts.tv_sec = 0; ts.tv_nsec = 1 * MILLIS; nanosleep(&ts, NULL); now = po6::wallclock_time(); } e::atomic::store_32_release(&done, 1); } void benchmark :: consumer() { while (true) { replicant_client_block(client, 250); po6::threads::mutex::hold hold(&mtx); replicant_returncode lr; int64_t id = replicant_client_loop(client, 0, &lr); if (id < 0 && lr == REPLICANT_NONE_PENDING && e::atomic::load_32_acquire(&done) != 0) { break; } else if (id < 0 && (lr == REPLICANT_TIMEOUT || lr == REPLICANT_NONE_PENDING)) { continue; } else if (id < 0) { std::cerr << "loop failed: " << replicant_client_error_message(client) << " @ " << replicant_client_error_location(client) << std::endl; abort(); } if (rr != REPLICANT_SUCCESS) { std::cerr << "call failed: " << replicant_client_error_message(client) << " @ " << replicant_client_error_location(client) << std::endl; abort(); } const uint64_t end = po6::wallclock_time(); google::dense_hash_map<int64_t, uint64_t>::iterator it = times.find(id); if (it == times.end()) { std::cerr << "bad map handling code" << std::endl; abort(); } const uint64_t start = it->second; times.erase(it); ygor_data_record dr; dr.series = 1; dr.when = start; dr.data = end - start; if (ygor_data_logger_record(dl, &dr) < 0) { std::cerr << "could not record data point: " << po6::strerror(errno) << std::endl; abort(); } } } int main(int argc, const char* argv[]) { benchmark b; connect_opts conn; e::argparser ap; ap.autohelp(); ap.arg().name('o', "output") .description("where to save the recorded benchmark stats (default: benchmark.dat.bz2)") .as_string(&b.output); ap.arg().long_name("object") .description("object to call (default: echo)") .as_string(&b.object); ap.arg().long_name("function") .description("function to call (default: echo)") .as_string(&b.function); ap.arg().name('t', "throughput") .description("target throughput (default: 100 ops/s)") .as_long(&b.target); ap.arg().name('r', "runtime") .description("total test runtime length in seconds (default: 60)") .as_long(&b.length); ap.add("Connect to a cluster:", conn.parser()); if (!ap.parse(argc, argv)) { return EXIT_FAILURE; } if (ap.args_sz() != 0) { std::cerr << "command requires no positional arguments\n" << std::endl; ap.usage(); return EXIT_FAILURE; } if (!conn.validate()) { std::cerr << "invalid host:port specification\n" << std::endl; ap.usage(); return EXIT_FAILURE; } ygor_data_logger* dl = ygor_data_logger_create(b.output, 1000000, 1000); if (!dl) { std::cerr << "could not open output: " << po6::strerror(errno) << std::endl; return EXIT_FAILURE; } b.client = replicant_client_create(conn.host(), conn.port()); b.dl = dl; po6::threads::thread prod(po6::threads::make_thread_wrapper(&benchmark::producer, &b)); po6::threads::thread cons(po6::threads::make_thread_wrapper(&benchmark::consumer, &b)); prod.start(); cons.start(); prod.join(); cons.join(); if (ygor_data_logger_flush_and_destroy(dl) < 0) { std::cerr << "could not close output: " << po6::strerror(errno) << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
bsd-3-clause
Clinical-Genomics/scout
tests/load/test_load_transcripts.py
707
from pprint import pprint as pp from scout.load.transcript import load_transcripts def test_load_transcripts(adapter, gene_bulk, transcripts_handle): # GIVEN a empty database assert sum(1 for i in adapter.all_genes()) == 0 assert sum(1 for i in adapter.transcripts()) == 0 # WHEN inserting a number of genes and some transcripts adapter.load_hgnc_bulk(gene_bulk) load_transcripts(adapter, transcripts_lines=transcripts_handle, build="37") # THEN assert all genes have been added to the database assert sum(1 for i in adapter.all_genes()) == len(gene_bulk) # THEN assert that the transcripts where loaded loaded assert sum(1 for i in adapter.transcripts()) > 0
bsd-3-clause
praekelt/helpdesk
casepro/orgs_ext/tests.py
382
from __future__ import absolute_import, unicode_literals from django.core.urlresolvers import reverse from casepro.test import BaseCasesTest class OrgExtCRUDLTest(BaseCasesTest): def test_home(self): url = reverse('orgs_ext.org_home') self.login(self.admin) response = self.url_get('unicef', url) self.assertEqual(response.status_code, 200)
bsd-3-clause
jeking3/web-interface
public/uts/shaketable/shaketable.js
37584
/** * Shake Table web interface. * * @author Michael Diponio <[email protected]> * @author Jesse Charlton <[email protected]> * @date 1/6/2013 */ /* ============================================================================ * == Shake Table. == * ============================================================================ */ function ShakeTable(is3DOF) { new WebUIApp(is3DOF ? Config3DOF() : Config2DOF()).setup().run(); } /** * 2 degree of freedom (2DOF) Shake Table interface. */ function Config2DOF() { return { anchor: "#shake-table-anchor", controller: "ShakeTableController", dataAction: "dataAndGraph", dataDuration: 30, dataPeriod: 10, pollPeriod: 1000, windowToggle: true, theme: Globals.THEMES.flat, cookie: "shaketable2dof", widgets: [ new MimicWidget(false), new Container("graphs-container", { title: "Graphs", reizable: true, left: -191, top: 540, widgets: [ new Graph("graph-displacement", { title: "Displacements", resizable: true, fields: { 'disp-graph-1': 'Base', 'disp-graph-2': 'Level 1', 'disp-graph-3': 'Level 2' }, minValue: -60, maxValue: 60, duration: 10, durationCtl: true, yLabel: "Displacement (mm)", fieldCtl: true, autoCtl: true, traceLabels: true, width: 832, height: 325, }), new Container("graphs-lissajous-container", { title: "Lissajous", widgets: [ new ScatterPlot("graph-lissajous-l0l1", { title: "L0 vs L1", xLabel: "L0 (mm)", yLabel: "L1 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-1': 'disp-graph-2' }, labels: { 'disp-graph-1': "L0 vs L1", }, traceLabels: false, }), new ScatterPlot("graph-lissajous-l0l2", { title: "L0 vs L2", xLabel: "L0 (mm)", yLabel: "L2 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-1': 'disp-graph-3' }, labels: { 'disp-graph-1': "L0 vs L2", }, traceLabels: false }), new ScatterPlot("graph-lissajous-l1l2", { title: "L1 vs L2", xLabel: "L1 (mm)", yLabel: "L2 (mm)", autoScale: true, vertScales: 5, horizScales: 5, sampleSize: 125, fields: { 'disp-graph-2': 'disp-graph-3' }, labels: { 'disp-graph-2': "L1 vs L2", }, traceLabels: false }), ], layout: new TabLayout({ position: TabLayout.POSITION.left, border: 0, }) }), new Container("fft-container", { title: "FFT", widgets: [ new FFTGraph("graph-fft", { title: "FFT", resizable: true, fields: { 'disp-graph-1': 'Base', 'disp-graph-2': 'Level 1', 'disp-graph-3': 'Level 2' }, xLabel: "Frequency (Hz)", yLabel: "Amplitude (mm)", horizScales: 10, maxValue: 30, period: 10, duration: 10, fieldCtl: true, autoScale: true, }), new Button("button-fft-export", { label: "Export FFT", link: "/primitive/file/pc/ShakeTableController/pa/exportFFT/fn/fft.txt", target: "_blank", width: 80, height: 20, resizable: false }) ], layout: new AbsoluteLayout({ coords: { "graph-fft": { x: 0, y: 0 }, "button-fft-export": { x: 20, y: -1 } } }) }), ], layout: new TabLayout({ position: TabLayout.POSITION.top, border: 10, }) }), new CameraStream("camera-stream", { resizable: true, left: -2, top: 5, videoWidth: 320, videoHeight: 240, swfParam: 'camera-swf', mjpegParam: 'camera-mjpeg', title: "Camera" }), new Container("controls-container", { title: "Controls", resizable: false, left: -2, top: 335, widgets: [ new Slider("slider-motor-speed", { field: "motor-speed", action: "setMotor", max: 8, precision: 2, label: "Motor Frequency", units: "Hz", vertical: false, }), new Slider("slider-coil-1", { length: 75, action: "setCoil", field: "coils-1-power", label: "Coil 1", vertical: true, scales: 2, units: "%" }), new Slider("slider-coil-2", { length: 75, action: "setCoil", field: "coils-2-power", label: "Coil 2", vertical: true, scales: 2, units: "%" }), new Container("container-control-buttons", { width: 200, widgets: [ new Switch("switch-motor-on", { field: "motor-on", action: "setMotor", label: "Motor", width: 96, }), new Switch("switch-coils-on", { field: "coils-on", action: "setCoils", label: "Coils", width: 92, }), new Switch("switch-coupling", { field: "motor-coil-couple", action: "setCouple", label: "Couple", width: 107, }), new Image("couple-to-motor" , { image: "/uts/shaketable/images/arrow-couple-left.png", }), new Image("couple-to-coils" , { image: "/uts/shaketable/images/arrow-couple-right.png", }), ], layout: new AbsoluteLayout({ border: 10, coords: { "switch-motor-on": { x: -5, y: 20 }, "switch-coils-on": { x: 100, y: 20 }, "switch-coupling": { x: 40, y: 80 }, "couple-to-motor": { x: 0, y: 55 }, "couple-to-coils": { x: 154, y: 55 }, } }) }), ], layout: new GridLayout({ padding: 5, columns: [ [ "container-control-buttons" ], [ "slider-motor-speed" ], [ "slider-coil-1" ], [ "slider-coil-2" ] ] }) }), new DataLogging("data-logger", { left: -193, top: 142, width: 183, height: 388, }) ] }; } /* * 3 degree of freedom (3DOF) Shake Table interface. */ function Config3DOF() { return { anchor: "#shake-table-anchor", controller: "ShakeTableController", dataAction: "dataAndGraph", dataDuration: 10, dataPeriod: 100, pollPeriod: 1000, windowToggle: true, theme: Globals.THEMES.flat, cookie: "shaketable", widgets: [ new Graph("graph-displacement", { title: "Graphs", resizable: true, width: 418, height: 328, left: 351, top: 423, fields: { 'disp-graph-1': 'Level 1', 'disp-graph-2': 'Level 2', 'disp-graph-3': 'Level 3' }, minValue: -60, maxValue: 60, duration: 10, yLabel: "Displacement (mm)", fieldCtl: false, autoCtl: false, durationCtl: false, traceLabels: false, }), new MimicWidget(true), new CameraStream("camera-stream", { resizable: true, left: 2, top: 45, videoWidth: 320, videoHeight: 240, swfParam: 'camera-swf', mjpegParam: 'camera-mjpeg', title: "Camera" }), new Container("controls-container", { title: "Controls", resizable: false, left: 2, top: 375, widgets: [ new Switch("switch-motor-on", { field: "motor-on", action: "setMotor", label: "Motor", }), new Switch("switch-coils-on", { field: "coils-on", action: "setCoils", label: "Dampening", }), new Slider("slider-motor-speed", { field: "motor-speed", action: "setMotor", max: 8, precision: 2, label: "Motor Frequency", units: "Hz", vertical: false, }) ], layout: new FlowLayout({ padding: 5, size: 320, vertical: false, center: true, }) }) ] }; } /* ============================================================================ * == Mimic Widget. == * ============================================================================ */ /** * Mimic Widget. This widget creates and controls the Shake Table Mimic. * * @param {boolean} is3DOF whether to display 2DOF or 3DOF configuration */ function MimicWidget(is3DOF) { Widget.call(this, "shaker-mimic", { title: "Model", windowed: true, resizable: true, preserveAspectRatio: true, minWidth: 320, minHeight: 410, closeable: true, shadeable: true, expandable: true, draggable: true, left: 338, top: 5, width: 334 }); /** Model dimensions in mm. */ this.model = { levelWidth: 200, // Width of the model armWidth: 70, // Width of the stroke arm connecting the motor to the model motorRadius: 10, // Radius of the motor wallHeight: 120, // Height of the walls levelHeight: 30, // Height of the levels trackHeight: 20, // Height of the track trackWidth: 300, // Width of track carHeight: 10, // Height of carriage carWidth: 120, // Width of carriage maxDisp: 60, // Maximum displacement of the diagram baseDisp: 0.7 // Displacement of the base when the motor is on }; /** Whether this mimic represents a 2DOF or a 3DOF widget. */ this.is3DOF = is3DOF; /** Number of levels in the model. */ this.numberLevels = this.is3DOF ? 4 : 3; /** Millimeters per pixel. */ this.mmPerPx = 1.475; /** The width of the diagram in pixels. */ this.width = undefined; /** The height of the diagram in pixels. */ this.height = undefined; /** The period in milliseconds. */ this.period = 10; /** Canvas context. */ this.ctx = null; /** Amplitude of displacement in mm. */ this.amp = [ 0, 0, 0, 0 ]; /** Angular frequency r/s. */ this.w = 0; /** Offsets of levels. */ this.o = [ 0, 0, 0, 0 ]; /** Frame count. */ this.fr = 0; /** Motor frequency. */ this.motor = 0; /** Coil power percentages. */ this.coils = [ undefined, undefined, undefined ]; /** Center line. */ this.cx = undefined; /** Animation interval. */ this.animateInterval = undefined; } MimicWidget.prototype = new Widget; MimicWidget.ANIMATE_PERIOD = 50; MimicWidget.prototype.init = function($container) { var canvas, thiz = this; this.mmPerPx = 1.475; if (this.window.width) { this.mmPerPx = 320 / this.window.width * 1.475; } /* The width of the canvas diagram is the width of the building model plus * the maximum possible displacement. */ this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100); this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) + this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight); this.cx = this.width / 2; /* Box. */ this.$widget = this._generate($container, "<div class='mimic'></div>"); this.$widget.css("height", "auto"); /* Canvas to draw display. */ canvas = Util.getCanvas(this.id + "-canvas", this.width, this.height); this.$widget.find(".mimic").append(canvas); this.ctx = canvas.getContext("2d"); this.ctx.translate(0.5, 0.5); /* Draw initial frame of zero position. */ this.drawFrame([0, 0, 0, 0]); this.boxWidth = this.$widget.width(); /* Start animation. */ this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD); }; MimicWidget.prototype.consume = function(data) { var i, l, peaks = [], level, range, topLevel = this.numberLevels - 1; /* We need to find a list of peaks for each of the levels. */ for (l = 1; l <= this.numberLevels; l++) { if (!$.isArray(data["disp-graph-" + l])) continue; /* To find peaks we are searching for the values where the preceding value is * not larger than the subsequent value. */ level = [ ]; for (i = data["disp-graph-" + l].length - 2; i > 1; i--) { if (data["disp-graph-" + l][i] > data["disp-graph-" + l][i + 1] && data["disp-graph-" + l][i] >= data["disp-graph-" + l][i - 1]) { level.push(i); /* We only require a maximum of 5 peaks. */ if (level.length == 5) break; } } /* If we don't have the requiste number of peaks, don't update data. */ while (level.length < 5) return; peaks.push(level); /* Amplitude is a peak value. The amplitude we are using will the median * of the last 3 peaks. */ this.amp[l] = this.medianFilter([ data["disp-graph-" + l][level[0]], data["disp-graph-" + l][level[1]], data["disp-graph-" + l][level[2]] ]); /* Without a distinct signal, the model has an unrepresentative wiggle, * so we small amplitudes will be thresholded to 0. */ if (this.amp[l] < 2) this.amp[l] = 0; } /* Amplitude for the base is fixed at 0.7 mm but only applies if the motor * is active. */ this.amp[0] = data['motor-on'] ? this.model.baseDisp : 0; /* Angular frequency is derived by the periodicity of peaks. */ range = this.medianFilter([ peaks[topLevel][0] - peaks[topLevel][1], peaks[topLevel][1] - peaks[topLevel][2], peaks[topLevel][2] - peaks[topLevel][3], peaks[topLevel][3] - peaks[topLevel][4] ]); this.w = isFinite(i = 2 * Math.PI * 1 / (this.period / 1000 * range)) != Number.Infinity ? i : 0; /* Phase if determined based on the difference in peaks between the top * level and lower levels. */ for (l = 2; l < this.numberLevels - 1; l++) { this.o[l] = 2 * Math.PI * this.medianFilter([ peaks[l - 1][0] - peaks[topLevel][0], peaks[l - 1][1] - peaks[topLevel][1], peaks[l - 1][2] - peaks[topLevel][2], peaks[l - 1][3] - peaks[topLevel][3] ]) / range; } /** Coil states. */ if (this.is3DOF) { /* The 3DOF is either on or off. */ for (i = 0; i < this.coils.length; i++) this.coils[i] = data['coils-on'] ? 100 : 0; } else { this.coils[0] = data['coils-1-on'] ? data['coils-1-power'] : 0; this.coils[1] = data['coils-2-on'] ? data['coils-2-power'] : 0; } /* Motor details. */ this.motor = data['motor-on'] ? data['motor-speed'] : 0; }; /** * Runs a median filter on the algorithm. */ MimicWidget.prototype.medianFilter = function(data) { data = data.sort(function(a, b) { return a - b; }); return data[Math.round(data.length / 2)]; }; MimicWidget.prototype.animationFrame = function() { var disp = [], i; this.fr++; for (i = 1; i <= this.numberLevels; i++) { disp[i - 1] = this.amp[i] * Math.sin(this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr + this.o[i]); } this.drawFrame(disp, this.motor > 0 ? (this.w * MimicWidget.ANIMATE_PERIOD / 1000 * this.fr) : 0); }; /** * Animates the mimic. * * @param disp displacements of each level in mm * @param motor motor rotation */ MimicWidget.prototype.drawFrame = function(disp, motor) { /* Store the current transformation matrix. */ this.ctx.save(); /* Use the identity matrix while clearing the canvas to fix I.E not clearing. */ this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.clearRect(0, 0, this.width, this.height); /* Restore the transform. */ this.ctx.restore(); this.drawTrackCarriageMotor(disp[0], motor); var l, xVert = [], yVert = []; /* Levels. */ for (l = 0; l < this.numberLevels; l++) { xVert.push(this.cx - this.px(this.model.levelWidth / 2 + disp[l])); yVert.push(this.height - this.px(this.model.trackHeight + this.model.carHeight) - this.px(this.model.levelHeight * (l + 1)) - this.px(this.model.wallHeight * l)); /* Coil. */ if (l > 0) this.drawCoil(yVert[l] + this.px(this.model.levelHeight / 2), this.coils[l - 1]); /* Mass. */ this.drawLevel(xVert[l], yVert[l], l); } /* Arm vertices. */ for (l = 0; l < xVert.length - 1; l++) { this.drawVertex(xVert[l], yVert[l], xVert[l + 1], yVert[l + 1] + this.px(this.model.levelHeight)); this.drawVertex(xVert[l] + this.px(this.model.levelWidth), yVert[l], xVert[l + 1] + this.px(this.model.levelWidth), yVert[l + 1] + this.px(this.model.levelHeight)); } this.drawGrid(); }; /** The widget of the coil box in mm. */ MimicWidget.COIL_BOX_WIDTH = 26; /** * Draws a coil. * * @param y the vertical position of coil * @param pw coil power */ MimicWidget.prototype.drawCoil = function(y, pw) { var gx = this.width - this.px(20), gy; this.ctx.strokeStyle = "#888888"; this.ctx.lineWidth = 1; this.ctx.beginPath(); this.ctx.moveTo(this.cx, y); this.ctx.lineTo(gx, y); this.ctx.moveTo(gx, y - this.px(this.model.levelHeight) / 2); this.ctx.lineTo(gx, y + this.px(this.model.levelHeight / 2)); for (gy = y - this.px(this.model.levelHeight) / 2; gy <= y + this.px(this.model.levelHeight) / 2; gy += this.px(this.model.levelHeight) / 4) { this.ctx.moveTo(gx, gy); this.ctx.lineTo(this.width, gy + this.px(5)); } this.ctx.stroke(); this.ctx.fillStyle = pw === undefined ? "#CCCCCC" : pw > 0 ? "#50C878" : "#ED2939"; this.ctx.fillRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2), this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH)); this.ctx.strokeRect(this.width - this.px(55), y - this.px(MimicWidget.COIL_BOX_WIDTH / 2), this.px(MimicWidget.COIL_BOX_WIDTH), this.px(MimicWidget.COIL_BOX_WIDTH)); this.ctx.fillStyle = "#000000"; this.ctx.font = this.px(13) + "px sans-serif"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "middle"; this.ctx.fillText("C", this.width - this.px(30) - this.px(MimicWidget.COIL_BOX_WIDTH / 2), y); }; MimicWidget.prototype.drawVertex = function(x0, y0, x1, y1) { this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 2; this.ctx.beginPath(); this.ctx.moveTo(x0, y0); this.ctx.lineTo(x1, y1); this.ctx.stroke(); }; /** * Draws a level box from the top left position. * * @param x x coordinate * @param y y coordinate * @param l level number */ MimicWidget.prototype.drawLevel = function(x, y, l) { this.ctx.fillStyle = "#548DD4"; this.ctx.fillRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight)); this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 1.5; this.ctx.strokeRect(x, y, this.px(this.model.levelWidth), this.px(this.model.levelHeight)); if (l > 0) { this.ctx.fillStyle = "#000000"; this.ctx.font = this.px(13) + "px sans-serif"; this.ctx.textAlign = "center"; this.ctx.textBaseline = "middle"; this.ctx.fillText("M" + l, x + this.px(this.model.levelWidth) / 2, y + this.px(this.model.levelHeight / 2)); } }; /** * Draws the track, carriage and motor. * * @param d0 displacement of base level * @param motor motor rotation */ MimicWidget.prototype.drawTrackCarriageMotor = function(d0, motor) { var tx = this.cx - this.px(this.model.trackWidth / 2), ty = this.height - this.px(this.model.trackHeight), mx, my, mr; /* Track. */ this.ctx.fillStyle = "#AAAAAA"; this.ctx.fillRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight)); this.ctx.strokeStyle = "#333333"; this.ctx.lineWidth = 1; this.ctx.strokeRect(tx, ty, this.px(this.model.trackWidth), this.px(this.model.trackHeight)); this.ctx.beginPath(); this.ctx.moveTo(tx, ty + this.px(this.model.trackHeight) / 2 - 1); this.ctx.lineTo(tx + this.px(this.model.trackWidth), ty + this.px(this.model.trackHeight) / 2 - 1); this.ctx.lineWidth = 2; this.ctx.stroke(); /* Carriage. */ this.ctx.fillStyle = "#666666"; this.ctx.fillRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.fillRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.strokeStyle = "#222222"; this.ctx.strokeRect(this.cx - this.px(this.model.levelWidth / 4 + 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); this.ctx.strokeRect(this.cx + this.px(this.model.levelWidth / 4 - 10) - this.px(d0), ty - this.px(10), this.px(20), this.px(20)); mx = this.px(40); my = this.height - this.px(44); mr = this.px(20); /* Arm. */ this.ctx.beginPath(); this.ctx.moveTo(mx - this.px(8 + d0), my - this.px(15)); this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(15)); this.ctx.lineTo(mx + this.px(8 - d0), my - this.px(5)); this.ctx.lineTo(this.cx, my - this.px(5)); this.ctx.lineTo(this.cx, my + this.px(5)); this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(5)); this.ctx.lineTo(mx + this.px(8 - d0), my + this.px(15)); this.ctx.lineTo(mx - this.px(8 + d0), my + this.px(15)); this.ctx.closePath(); this.ctx.fillStyle = "#AAAAAA"; this.ctx.fill(); this.ctx.clearRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18)); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.strokeRect(mx - this.px(2.5 + d0), my - this.px(9), this.px(5), this.px(18)); /* Motor. */ this.ctx.save(); this.ctx.globalCompositeOperation = "destination-over"; /* Couple between the motor and the arm. */ this.ctx.beginPath(); this.ctx.arc(mx, my - this.px(d0), this.px(4), 0, 2 * Math.PI); this.ctx.fillStyle = "#222222"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.arc(mx, my, mr, -Math.PI / 18 + motor, Math.PI / 18 + motor, false); this.ctx.arc(mx, my, mr, Math.PI - Math.PI / 18 + motor, Math.PI + Math.PI / 18 + motor, false); this.ctx.closePath(); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.fillStyle = "#999999"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.arc(mx, my, mr, 0, 2 * Math.PI); this.ctx.fillStyle = "#666666"; this.ctx.fill(); this.ctx.strokeStyle = "#333333"; this.ctx.stroke(); this.ctx.restore(); }; MimicWidget.GRID_WIDTH = 50; /** * Draws a grid. */ MimicWidget.prototype.drawGrid = function() { var d, dt = this.px(MimicWidget.GRID_WIDTH); this.ctx.save(); this.ctx.globalCompositeOperation = "destination-over"; /* Grid lines. */ this.ctx.beginPath(); for (d = this.cx - dt; d > 0; d -= dt) this.stippleLine(d, 0, d, this.height); for (d = this.cx + dt; d < this.width - dt; d+= dt) this.stippleLine(d, 0, d, this.height); for (d = dt; d < this.height; d += dt) this.stippleLine(0, d, this.width, d); this.ctx.strokeStyle = "#AAAAAA"; this.ctx.lineWidth = 1; this.ctx.stroke(); /* Units. */ this.ctx.beginPath(); this.ctx.moveTo(this.px(22), 0); this.ctx.lineTo(this.px(22), dt); this.ctx.moveTo(this.px(10), this.px(10)); this.ctx.lineTo(dt + this.px(10), this.px(10)); this.ctx.strokeStyle = "#555555"; this.ctx.stroke(); this.ctx.beginPath(); this.ctx.moveTo(this.px(22), 0); this.ctx.lineTo(this.px(22 + 2.5), this.px(5)); this.ctx.lineTo(this.px(22 - 2.5), this.px(5)); this.ctx.closePath(); this.ctx.fillStyle = "#555555"; this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(22), dt); this.ctx.lineTo(this.px(22 + 2.5), dt - this.px(5)); this.ctx.lineTo(this.px(22 - 2.5), dt - this.px(5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(10), this.px(10)); this.ctx.lineTo(this.px(15), this.px(7.5)); this.ctx.lineTo(this.px(15), this.px(12.5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.beginPath(); this.ctx.moveTo(this.px(10) + dt, this.px(10)); this.ctx.lineTo(this.px(5) + dt, this.px(7.5)); this.ctx.lineTo(this.px(5) + dt, this.px(12.5)); this.ctx.closePath(); this.ctx.fill(); this.ctx.font = this.px(10) + "px sans-serif"; this.ctx.fillText(MimicWidget.GRID_WIDTH + "mm", this.px(40), this.px(20)); /* Center line. */ this.ctx.beginPath(); this.ctx.moveTo(this.cx, 0); this.ctx.lineTo(this.cx, this.height); this.ctx.moveTo(0, this.height / 2); this.ctx.strokeStyle = "#555555"; this.ctx.lineWidth = 1.5; this.ctx.stroke(); this.ctx.restore(); }; MimicWidget.STIPPLE_WIDTH = 10; /** * Draws a stippled line. * * @param x0 begin x coordinate * @param y0 begin y coordinate * @param x1 end x coordinate * @param y1 end y coordinate */ MimicWidget.prototype.stippleLine = function(x0, y0, x1, y1) { var p; if (x0 == x1) // Horizontal line { p = y0 - MimicWidget.STIPPLE_WIDTH; while (p < y1) { this.ctx.moveTo(x0, p += MimicWidget.STIPPLE_WIDTH); this.ctx.lineTo(x0, p += MimicWidget.STIPPLE_WIDTH); } } else if (y0 == y1) // Vertical line { p = x0 - MimicWidget.STIPPLE_WIDTH; while (p < x1) { this.ctx.moveTo(p += MimicWidget.STIPPLE_WIDTH, y0); this.ctx.lineTo(p += MimicWidget.STIPPLE_WIDTH, y0); } } else // Diagonal { throw "Diagonal lines not implemented."; } }; /** * Converts a pixel dimension to a millimetre dimension. * * @param px pixel dimension * @return millimetre dimension */ MimicWidget.prototype.mm = function(px) { return px * this.mmPerPx; }; /** * Converts a millimetre dimension to a pixel dimension. * * @param mm millimetre dimension * @return pixel dimension */ MimicWidget.prototype.px = function(mm) { return mm / this.mmPerPx; }; MimicWidget.prototype.resized = function(width, height) { if (this.animateInterval) { clearInterval(this.animateInterval); this.animateInterval = undefined; } height -= 63; this.$widget.find("canvas").attr({ width: width, height: height }); this.ctx.fillStyle = "#FAFAFA"; this.ctx.fillRect(0, 0, width, height); }; MimicWidget.prototype.resizeStopped = function(width, height) { this.mmPerPx *= this.boxWidth / width; this.width = this.px(this.model.levelWidth + this.model.maxDisp * 2) + this.px(100); this.cx = this.width / 2; this.height = this.px(this.model.levelHeight * (this.is3DOF ? 4 : 3) + this.model.wallHeight * (this.is3DOF ? 3: 2) + this.model.trackHeight + this.model.carHeight); this.boxWidth = width; this.$widget.find("canvas").attr({ width: this.width, height: this.height }); this.$widget.css("height", "auto"); if (!this.animateInterval) { var thiz = this; this.animateInterval = setInterval(function() { thiz.animationFrame(); }, MimicWidget.ANIMATE_PERIOD); } }; MimicWidget.prototype.destroy = function() { clearInterval(this.animateInterval); this.animateInterval = undefined; Widget.prototype.destroy.call(this); }; /** * Displays an FFT of one or more signals. * * @constructor * @param {string} id graph identifier * @param {object} config configuration object * @config {object} [fields] map of graphed data fields with field => label * @config {object} [colors] map of graph trace colors with field => color (optional) * @config {boolean} [autoScale] whether to autoscale the graph dependant (default off) * @config {integer} [minValue] minimum value that is graphed, implies not autoscaling (default 0) * @config {integer} [maxValue] maximum value that is graphed, implies not autoscaling (default 100) * @config {integer} [duration] number of seconds this graph displays (default 60) * @config {integer} [period] period betweeen samples in milliseconds (default 100) * @config {string} [xLabel] X axis label (default (Time (s)) * @config {String} [yLabel] Y axis label (optional) * @config {boolean} [traceLabels] whether to show trace labels (default true) * @config {boolean} [fieldCtl] whether data field displays can be toggled (default false) * @config {boolean} [autoCtl] whether autoscaling enable control is shown (default false) * @config {boolean} [durationCtl] whether duration control slider is displayed * @config {integer} [vertScales] number of vertical scales (default 5) * @config {integer} [horizScales] number of horizontal scales (default 8) */ function FFTGraph(id, config) { Graph.call(this, id, config); } FFTGraph.prototype = new Graph; FFTGraph.prototype.consume = function(data) { /* Not stopping updates when controls are showing , causes ugly blinking. */ if (this.showingControls) return; var i = 0; if (this.startTime == undefined) { this.startTime = data.start; this._updateIndependentScale(); } this.latestTime = data.time; for (i in this.dataFields) { if (data[i] === undefined) continue; this.dataFields[i].values = this.fftTransform( this._pruneSample(data[i], this.config.duration * 1000 / this.config.period)); this.dataFields[i].seconds = this.dataFields[i].values.length * this.config.period / 1000; this.displayedDuration = data.duration; } if (this.config.autoScale) { /* Determine graph scaling for this frame and label it. */ this._adjustScaling(); this._updateDependantScale(); } this._drawFrame(); }; FFTGraph.prototype._updateIndependentScale = function() { var i, $d = this.$widget.find(".graph-bottom-scale-0"), t; for (i = 0; i <= this.config.horizScales; i++) { t = 1000 * i / this.config.period / this.config.horizScales / 20; $d.html(Util.zeroPad(t, 1)); $d = $d.next(); } }; /** * Pads the length of the array with 0 until its length is a multiple of 2. * * @param {Array} arr array to pad * @return {Array} padded arary (same as input) */ FFTGraph.prototype.fftTransform = function(sample) { var i, n = sample.length, vals = new Array(n); /* The FFT is computed on complex numbers. */ for (i = 0; i < n; i++) { vals[i] = new Complex(sample[i], 0); } /* The Cooley-Turkey algorithm operates on samples whose length is a * multiple of 2. */ while (((n = vals.length) & (n - 1)) != 0) { vals.push(new Complex(0, 0)); } /** Apply the FFT transform. */ vals = fft(vals); /* We only care about the first 10 Hz. */ vals.splice(n / 20 - 1, n - n / 20); /* The plot is of the absolute values of the sample, then scaled . */ for (i = 0; i < vals.length; i++) { vals[i] = vals[i].abs() * 2 / n; } return vals; };
bsd-3-clause
VulcanRobotics/Vector
doc/edu/wpi/first/wpilibj/class-use/Servo.html
6455
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Wed Jan 01 17:07:30 EST 2014 --> <TITLE> Uses of Class edu.wpi.first.wpilibj.Servo (2013 FRC Java API) </TITLE> <META NAME="date" CONTENT="2014-01-01"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class edu.wpi.first.wpilibj.Servo (2013 FRC Java API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../edu/wpi/first/wpilibj/Servo.html" title="class in edu.wpi.first.wpilibj"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> "<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?edu/wpi/first/wpilibj/\class-useServo.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Servo.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>edu.wpi.first.wpilibj.Servo</B></H2> </CENTER> No usage of edu.wpi.first.wpilibj.Servo <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../edu/wpi/first/wpilibj/Servo.html" title="class in edu.wpi.first.wpilibj"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> "<p style=\"background-color:${javadoc.bgcolor}; color:${javadoc.fgcolor}; padding:4px 5px 2px 3px; margin-top:-1px\"><b>2013 FRC Java API</b></p>"</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?edu/wpi/first/wpilibj/\class-useServo.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Servo.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> "<center><i><font size=\"-1\">For updated information see the <a href=\"http://www.usfirst.org/roboticsprograms/frc/\">Java FRC site</a></font></i></center>" </BODY> </HTML>
bsd-3-clause
Aerotenna/Firmware
src/lib/FlightTasks/tasks/Failsafe/FlightTaskFailsafe.hpp
2259
/**************************************************************************** * * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file FlightTaskFailsafe.hpp * */ #pragma once #include "FlightTask.hpp" class FlightTaskFailsafe : public FlightTask { public: FlightTaskFailsafe() = default; virtual ~FlightTaskFailsafe() = default; bool update() override; bool activate() override; private: DEFINE_PARAMETERS_CUSTOM_PARENT(FlightTask, (ParamFloat<px4::params::MPC_LAND_SPEED>) MPC_LAND_SPEED, (ParamFloat<px4::params::MPC_THR_HOVER>) MPC_THR_HOVER /**< throttle value at which vehicle is at hover equilibrium */ ) };
bsd-3-clause
cjh1/Xdmf2
vtk/vtkSILBuilder.h
2271
/*========================================================================= Program: Visualization Toolkit Module: vtkSILBuilder.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkSILBuilder - helper class to build a SIL i.e. a directed graph used // by reader producing composite datasets to describes the relationships among // the blocks. // .SECTION Description // vtkSILBuilder is a helper class to build a SIL i.e. a directed graph used // by reader producing composite datasets to describes the relationships among // the blocks. // Refer to http://www.paraview.org/Wiki/Block_Hierarchy_Meta_Data for details. #ifndef __vtkSILBuilder_h #define __vtkSILBuilder_h #include "vtkObject.h" class vtkUnsignedCharArray; class vtkStringArray; class vtkMutableDirectedGraph; class VTK_EXPORT vtkSILBuilder : public vtkObject { public: static vtkSILBuilder* New(); vtkTypeMacro(vtkSILBuilder, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description // Get/Set the graph to populate. void SetSIL(vtkMutableDirectedGraph*); vtkGetObjectMacro(SIL, vtkMutableDirectedGraph); // Description: // Initializes the data-structures. void Initialize(); // Description: // Add vertex, child-edge or cross-edge to the graph. vtkIdType AddVertex(const char* name); vtkIdType AddChildEdge(vtkIdType parent, vtkIdType child); vtkIdType AddCrossEdge(vtkIdType src, vtkIdType dst); // Description: // Returns the vertex id for the root vertex. vtkGetMacro(RootVertex, vtkIdType); //BTX protected: vtkSILBuilder(); ~vtkSILBuilder(); vtkStringArray* NamesArray; vtkUnsignedCharArray* CrossEdgesArray; vtkMutableDirectedGraph* SIL; vtkIdType RootVertex; private: vtkSILBuilder(const vtkSILBuilder&); // Not implemented. void operator=(const vtkSILBuilder&); // Not implemented. //ETX }; #endif
bsd-3-clause
Jakegogo/concurrent
concur/src-transfer/transfer/test/TestType.java
867
package transfer.test; import transfer.TypeReference; import java.util.Map; /** * Created by Jake on 2015/3/7. */ public class TestType { public static void main(String[] args) { System.out.println(new TypeReference<Entity>(){}.getType() == new TypeReference<Entity>(){}.getType()); System.out.println(new TypeReference<Map<String,Entity>>(){}.getType() == new TypeReference<Map<String,Entity>>(){}.getType()); System.out.println(new TypeReference<Map<String,Entity>>(){}.getType().hashCode()); System.out.println(new TypeReference<Map<String,Entity>>(){}.getType().hashCode()); System.out.println(System.identityHashCode(new TypeReference<Map<String,Entity>>(){}.getType())); System.out.println(System.identityHashCode(new TypeReference<Map<String,Entity>>(){}.getType())); } }
bsd-3-clause
forste/haReFork
tools/base/AST/HsTypePretty.hs
1125
--- Pretty printing for the T functor ------------------------------------------ module HsTypePretty where import HsTypeStruct --import HsIdent import PrettySymbols(rarrow,forall') import PrettyPrint import PrettyUtil instance (Printable i,Printable t,PrintableApp t t) => Printable (TI i t) where ppi (HsTyFun a b) = sep [ wrap a <+> rarrow, ppi b ] ppi (HsTyApp f x) = ppiApp f [x] ppi (HsTyForall xs ts t) = forall' <+> hsep (map ppi xs) <> kw '.' <+> ppContext ts <+> t ppi t = wrap t -- wrap (HsTyTuple ts) = ppiTuple ts wrap (HsTyApp f x) = wrapApp f [x] wrap (HsTyVar v) = wrap v wrap (HsTyCon c) = tcon (wrap c) wrap t = parens $ ppi t instance (PrintableApp i t,PrintableApp t t) => PrintableApp (TI i t) t where ppiApp (HsTyApp tf ta) ts = ppiApp tf (ta:ts) ppiApp (HsTyCon c) ts = ppiApp c ts ppiApp t ts = wrap t<+>fsep (map wrap ts) wrapApp (HsTyApp tf ta) ts = wrapApp tf (ta:ts) wrapApp (HsTyCon c) ts = wrapApp c ts wrapApp t ts = parens (wrap t<+>fsep (map wrap ts))
bsd-3-clause
Crystalnix/house-of-life-chromium
printing/printing_context_mac.h
2849
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef PRINTING_PRINTING_CONTEXT_MAC_H_ #define PRINTING_PRINTING_CONTEXT_MAC_H_ #include <string> #include "base/memory/scoped_nsobject.h" #include "printing/printing_context.h" #include "printing/print_job_constants.h" #ifdef __OBJC__ @class NSPrintInfo; #else class NSPrintInfo; #endif // __OBJC__ namespace printing { class PrintingContextMac : public PrintingContext { public: explicit PrintingContextMac(const std::string& app_locale); ~PrintingContextMac(); // PrintingContext implementation. virtual void AskUserForSettings(gfx::NativeView parent_view, int max_pages, bool has_selection, PrintSettingsCallback* callback); virtual Result UseDefaultSettings(); virtual Result UpdatePrintSettings(const DictionaryValue& job_settings, const PageRanges& ranges); virtual Result InitWithSettings(const PrintSettings& settings); virtual Result NewDocument(const string16& document_name); virtual Result NewPage(); virtual Result PageDone(); virtual Result DocumentDone(); virtual void Cancel(); virtual void ReleaseContext(); virtual gfx::NativeDrawingContext context() const; private: // Read the settings from the given NSPrintInfo (and cache it for later use). void ParsePrintInfo(NSPrintInfo* print_info); // Initializes PrintSettings from native print info object. void InitPrintSettingsFromPrintInfo(const PageRanges& ranges); // Updates |print_info_| to use the given printer. // Returns true if the printer was set else returns false. bool SetPrinter(const std::string& device_name); // Sets |copies| in PMPrintSettings. // Returns true if the number of copies is set. bool SetCopiesInPrintSettings(int copies); // Sets |collate| in PMPrintSettings. // Returns true if |collate| is set. bool SetCollateInPrintSettings(bool collate); // Sets orientation in native print info object. // Returns true if the orientation was set. bool SetOrientationIsLandscape(bool landscape); // Sets duplex mode in PMPrintSettings. // Returns true if duplex mode is set. bool SetDuplexModeInPrintSettings(DuplexMode mode); // Sets output color mode in PMPrintSettings. // Returns true if color mode is set. bool SetOutputIsColor(bool color); // The native print info object. scoped_nsobject<NSPrintInfo> print_info_; // The current page's context; only valid between NewPage and PageDone call // pairs. CGContext* context_; DISALLOW_COPY_AND_ASSIGN(PrintingContextMac); }; } // namespace printing #endif // PRINTING_PRINTING_CONTEXT_MAC_H_
bsd-3-clause
benkaraban/anima-games-engine
Sources/Modules/Renderer/SM2/FreeFormRenderer.cpp
13312
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Core/Logger.h> #include <Renderer/Common/Texture.h> #include <Renderer/Common/Tools.h> #include <Renderer/SM2/FreeFormRenderer.h> #include <algorithm> namespace Renderer { //----------------------------------------------------------------------------- FreeFormRenderer::FreeFormRenderer(const Ptr<Gfx::IDevice> & pDevice, const Ptr<ShaderLib> & pShaderLib, const Ptr<GPUResourceLib> & pResLib, const Ptr<TextureMap> & pDefaultTex, const RendererSettings & settings) : _pDevice(pDevice), _pShaderLib(pShaderLib), _pResLib(pResLib), _pDefaultTex(pDefaultTex), _settings(settings) { _pResLib->registerResource(this); } //----------------------------------------------------------------------------- FreeFormRenderer::~FreeFormRenderer() { _pResLib->unregisterResource(this); } //----------------------------------------------------------------------------- bool FreeFormRenderer::initialise() { bool result = true; int32 iMode = 0; int32 iFlag = 0; try { for(iMode=0; iMode < EFreeFormMode_COUNT; iMode++) for(iFlag=0; iFlag < FLAG_COUNT; iFlag++) initialise(_params[iMode][iFlag], EFreeFormMode(iMode), iFlag); } catch(Core::Exception & exception) { ERR << L"Error initializing FreeFormRenderer : '" << exception.getMessage() << L"' (" << Renderer::toString(EFreeFormMode(iMode)) << L" 0x" << Core::toStringHex(iFlag) << L")\n"; result = false; } return result; } //----------------------------------------------------------------------------- void FreeFormRenderer::onDeviceLost() { } //----------------------------------------------------------------------------- void FreeFormRenderer::onDeviceReset() { } //----------------------------------------------------------------------------- void FreeFormRenderer::initialise(ShaderParams & params, EFreeFormMode mode, int32 flags) { // Shaders Core::List<Gfx::ShaderMacro> macros; if(mode == FREE_FORM_REFRAC) macros.push_back(Gfx::ShaderMacro(L"REFRACTION_FLAG", L"1")); if(flags & NORMAL_MAP_DXT5_FLAG) macros.push_back(Gfx::ShaderMacro(L"NORMAL_MAP_DXT5_FLAG", L"1")); if(flags & GLOW_FLAG) macros.push_back(Gfx::ShaderMacro(L"GLOW_FLAG", L"1")); if(flags & LIGHT_FLAG) macros.push_back(Gfx::ShaderMacro(L"LIGHT_FLAG", L"1")); if(flags & WORLD_SPACE_FLAG) macros.push_back(Gfx::ShaderMacro(L"WORLD_SPACE_FLAG", L"1")); params.pVShader = _pShaderLib->getVShader(L"FreeForm.vsh", Gfx::VS_V1_1, L"vs_main", macros); params.pPShader = _pShaderLib->getPShader(L"FreeForm.psh", Gfx::PS_V2_0, L"ps_main", macros); params.pVConst = params.pVShader->getConstantTable(); params.pPConst = params.pPShader->getConstantTable(); params.idWorldViewProj = params.pVConst->getConstantIndexIfExists(L"WorldViewProj"); params.idWorldView = params.pVConst->getConstantIndexIfExists(L"WorldView"); params.idEyePos = params.pVConst->getConstantIndexIfExists(L"EyePos"); params.idFogRange = params.pVConst->getConstantIndexIfExists(L"FogRange"); params.idMainLightDir = params.pVConst->getConstantIndexIfExists(L"MainLightDir"); params.idSamplerColor = params.pPConst->getConstantIndexIfExists(L"SamplerColor"); params.idSamplerNormal = params.pPConst->getConstantIndexIfExists(L"SamplerNormal"); params.idSamplerRefraction = params.pPConst->getConstantIndexIfExists(L"SamplerRefraction"); params.idRefrScale = params.pPConst->getConstantIndexIfExists(L"RefrScale"); // Format Gfx::VertexFormatDesc formatDesc; formatDesc.addAttribut(0, Gfx::VAT_FLOAT3, Gfx::VAU_POSITION); formatDesc.addAttribut(0, Gfx::VAT_COLOR, Gfx::VAU_COLOR); formatDesc.addAttribut(0, Gfx::VAT_FLOAT3, Gfx::VAU_TEXTURE_COORD, 0); // texcoord formatDesc.addAttribut(0, Gfx::VAT_COLOR, Gfx::VAU_TEXTURE_COORD, 1); // glow params.pFormat = _pDevice->createVertexFormat(formatDesc, params.pVShader); // State Gfx::RSRasterizerDesc raster(Gfx::CM_NOCM, true, Gfx::FM_SOLID); Gfx::RSRasterizerDesc rasterLIGHT(Gfx::CM_BACK, true, Gfx::FM_SOLID); Gfx::RSDepthStencilDesc depthLIGHT(true, true, Gfx::COMPARISON_LESS_EQUAL); Gfx::RSDepthStencilDesc depth(true, false, Gfx::COMPARISON_LESS_EQUAL); Gfx::RSBlendDesc blendADD(Gfx::BM_SRC_ALPHA, Gfx::BO_ADD, Gfx::BM_ONE); Gfx::RSBlendDesc blendLERP(Gfx::BM_SRC_ALPHA, Gfx::BO_ADD, Gfx::BM_INVERT_SRC_ALPHA); Gfx::RSBlendDesc blendREFRAC; Gfx::RSBlendDesc blendLIGHT; Gfx::RSSamplerDesc samplerColor(Gfx::TEXTURE_ADDRESS_WRAP); Gfx::RSSamplerDesc samplerNormal(Gfx::TEXTURE_ADDRESS_CLAMP); setSampler(samplerColor, _settings.filterLevel); setSampler(samplerNormal, _settings.filterLevel); blendADD.sRGBWriteEnabled = true; blendLERP.sRGBWriteEnabled = true; blendREFRAC.sRGBWriteEnabled = true; blendLIGHT.sRGBWriteEnabled = true; samplerColor.isSRGB = true; switch(mode) { case FREE_FORM_ADD: LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST); params.state = _pDevice->createState(raster, depth, blendADD); params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor); break; case FREE_FORM_LERP: LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST); params.state = _pDevice->createState(raster, depth, blendLERP); params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor); break; case FREE_FORM_REFRAC: LM_ASSERT(params.idSamplerNormal != Gfx::UNDEFINED_SHADER_CONST); LM_ASSERT(params.idSamplerRefraction != Gfx::UNDEFINED_SHADER_CONST); params.state = _pDevice->createState(raster, depth, blendREFRAC); params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerNormal)] = _pDevice->createState(samplerNormal); params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerRefraction)] = _pDevice->createState(samplerColor); break; case FREE_FORM_LIGHT_MESH: LM_ASSERT(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST); params.state = _pDevice->createState(rasterLIGHT, depthLIGHT, blendLIGHT); params.state.ptSampler[params.pPConst->getSamplerId(params.idSamplerColor)] = _pDevice->createState(samplerColor); break; } } //----------------------------------------------------------------------------- void FreeFormRenderer::bind(const ShaderParams & params, const FreeForm & freeForm) { _pDevice->setState(params.state); _pDevice->setVertexFormat(params.pFormat); _pDevice->setVertexShader(params.pVShader); _pDevice->setPixelShader(params.pPShader); Core::Matrix4f world; freeForm.getWorldMatrix(world); Core::Matrix4f worldView(_view * world); Core::Matrix4f worldViewProj(_viewProj * world); Core::Vector3f fogRange(_fogSettings.getStart(), _fogSettings.getInvRange(), _fogSettings.getColor().a); if(freeForm.isWorldSpaceCoords()) fogRange.x = _fogSettings.getEnd() + _eye.z; params.pVConst->setConstantSafe(params.idFogRange, fogRange); params.pVConst->setConstantSafe(params.idEyePos, _eye); params.pVConst->setConstantSafe(params.idWorldViewProj, worldViewProj); params.pVConst->setConstantSafe(params.idWorldView, worldView); params.pVConst->setConstantSafe(params.idMainLightDir, -_lightSettings.getDirection()); if(params.idSamplerColor != Gfx::UNDEFINED_SHADER_CONST) { if(freeForm.getTexture() != null) params.pPConst->setSampler2D(params.idSamplerColor, LM_DEBUG_PTR_CAST<TextureMap>(freeForm.getTexture())->getResource()); else params.pPConst->setSampler2D(params.idSamplerColor, _pDefaultTex->getResource()); } if(params.idSamplerNormal != Gfx::UNDEFINED_SHADER_CONST) { params.pPConst->setSampler2D(params.idSamplerNormal, LM_DEBUG_PTR_CAST<TextureMap>(freeForm.getTexture())->getResource()); } if(params.idSamplerRefraction != Gfx::UNDEFINED_SHADER_CONST) { params.pPConst->setSampler2D(params.idSamplerRefraction, _pRenderTarget->getShaderTextureView(RT_REFRACTION_BUFFER)); } } //----------------------------------------------------------------------------- void FreeFormRenderer::startContext(const RenderContext & context, ERenderPass pass) { _pass = pass; _eye = context.getEye(); _view = context.getView(); _proj = context.getProj(); _viewProj = context.getViewProj(); _fogSettings = context.getFog(); _lightSettings = context.getLight(); _pRenderTarget = context.getRenderTarget(); _commands.clear(); const Core::List<FreeForm *> & fforms = context.getFreeForms(); if(pass == PASS_GLOW || pass == PASS_LIGHTING || pass == PASS_REFLECTION) { Command command; command.pass = pass; command.pExecuter = this; command.flags = 0; for(int32 ii=0; ii < fforms.size(); ii++) { const FreeForm & fform = *fforms[ii]; if(pass != PASS_GLOW || fform.getGlowFlag()) { command.mode = (fform.getMode() == FREE_FORM_LIGHT_MESH) ? CMD_SOLID : CMD_TRANS; command.camDist = Core::dot(fform.getBoundingBox().getCenter() - context.getEye(), context.getEyeDir()); command.pExecData = (void*)&fform; _commands.push_back(command); } } } } //----------------------------------------------------------------------------- int32 FreeFormRenderer::getFlags(const FreeForm & freeForm) const { int32 flags = 0; if(freeForm.getMode() == FREE_FORM_LIGHT_MESH) flags |= LIGHT_FLAG; if(freeForm.getTexture() != null && freeForm.getTexture()->getSourceTexture()->getFormat() == Assets::TEX_FORMAT_DXTC5) flags |= NORMAL_MAP_DXT5_FLAG; if(freeForm.isWorldSpaceCoords()) flags |= WORLD_SPACE_FLAG; return flags; } //----------------------------------------------------------------------------- void FreeFormRenderer::endContext() { } //----------------------------------------------------------------------------- void FreeFormRenderer::enqueueCommands(Core::List<Command> & commands) { commands.insert(commands.end(), _commands.begin(), _commands.end()); } //----------------------------------------------------------------------------- void FreeFormRenderer::exec(Command * pStart, Command * pEnd) { while(pStart != pEnd) { const FreeForm & freeForm = *(FreeForm*)pStart->pExecData; switch(_pass) { case PASS_LIGHTING: case PASS_REFLECTION: { bind(_params[int32(freeForm.getMode())][getFlags(freeForm)], freeForm); break; } case PASS_GLOW: { bind(_params[int32(FREE_FORM_ADD)][getFlags(freeForm) + GLOW_FLAG], freeForm); break; } } freeForm.sendData(); pStart++; } } //----------------------------------------------------------------------------- }
bsd-3-clause
OpenChemistry/mongochem
mongochem/gui/quickquerywidget.h
1312
/****************************************************************************** This source file is part of the MongoChem project. Copyright 2011 Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #ifndef QUICKQUERYWIDGET_H #define QUICKQUERYWIDGET_H #include <QWidget> namespace mongo { class Query; } namespace Ui { class QuickQueryWidget; } namespace MongoChem { class QuickQueryWidget : public QWidget { Q_OBJECT public: explicit QuickQueryWidget(QWidget *parent = 0); ~QuickQueryWidget(); QString field() const; QString value() const; mongo::Query query() const; signals: void queryClicked(); void resetQueryClicked(); private slots: void updateModeComboBox(const QString &field_); void updatePlaceholderText(const QString &field_); private: Ui::QuickQueryWidget *ui; }; } // end MongoChem namespace #endif // QUICKQUERYWIDGET_H
bsd-3-clause
ResearchSoftwareInstitute/MyHPOM
myhpom/views/verification.py
2927
from smtplib import SMTPException from django.conf import settings from django.core.mail import send_mail from django.views.decorators.http import require_GET from django.shortcuts import redirect from django.template.loader import render_to_string from django.contrib.auth.decorators import login_required from django.contrib import messages from django.utils import timezone @login_required def send_account_verification(request): """ * if already verified => returns message: info: verification already completed * if unverified => * if no verification code: set it and save UserDetails * send the verification email and returns message: info: email sent, please check """ userdetails = request.user.userdetails if userdetails.verification_completed: messages.info(request, "Your email address is already verified.") else: userdetails.reset_verification() code = userdetails.verification_code subject = 'Mind My Health Email Verification' domain = request.get_host() try: send_mail( subject, render_to_string( 'myhpom/accounts/verification_email.txt', context={ 'code': code, 'domain': domain }, request=request, ), settings.DEFAULT_FROM_EMAIL, [request.user.email], fail_silently=False, ) messages.info(request, "Please check your email to verify your address.") except SMTPException: messages.error( request, "The verification email could not be sent. Please try again later." ) userdetails.save() return redirect('myhpom:dashboard') @require_GET @login_required def verify_account(request, code): """This URL is usually accessed from an email. Login will redirect here if needed. * if already verified => returns message: success: verification already completed * if not verified: Check the given code against the user's verification code * if match: * set verification_completed as now and save UserDetails * message: success: email verified * if not match: * message: invalid: the verification code is invalid. """ userdetails = request.user.userdetails if userdetails.verification_completed: messages.info(request, "Your email address is already verified.") else: if code == userdetails.verification_code: userdetails.verification_completed = timezone.now() userdetails.save() messages.success(request, "Your email address is now verified.") else: messages.error(request, "The verification code is invalid.") return redirect('myhpom:dashboard')
bsd-3-clause
nonego/ldb
qq/testwrite.cpp
761
#include <leveldb/db.h> #include <string> #include <iostream> using namespace std; using namespace leveldb; int main( int argc, char* argv[]) { DB* db; Options options; options.create_if_missing = true; if( argc < 2 ) return 0; char delim; if( argc == 3 ) delim = argv[2][0]; else delim = '\t'; leveldb::Status status = leveldb::DB::Open(options, argv[1], &db); string line; int n=0; while( getline(cin, line)) { size_t i=line.find(delim); if( i == string::npos ) continue; db->Put(leveldb::WriteOptions(), line.substr(0, i), line.substr(i+1)); ++n; if( ( n & 0xFFFF ) == 0 ) cout << n << endl; } return 0; }
bsd-3-clause
czpython/django-cms
docs/conf.py
8185
# -*- coding: utf-8 -*- # # django cms documentation build configuration file, created by # sphinx-quickstart on Tue Sep 15 10:47:03 2009. # # This file is execfile()d with the current directory set to its containing # dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out serve # to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it absolute, # like shown here. sys.path.append(os.path.abspath('.')) sys.path.append(os.path.abspath('..')) sys.path.append(os.path.join(os.path.abspath('.'), '_ext')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. #extensions = ['sphinx.ext.autodoc'] extensions = ['djangocms', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.autodoc'] intersphinx_mapping = { 'python': ('http://docs.python.org/3/', None), 'django': ('https://docs.djangoproject.com/en/1.10/', 'https://docs.djangoproject.com/en/1.10/_objects/'), 'classytags': ('http://readthedocs.org/docs/django-classy-tags/en/latest/', None), 'sekizai': ('http://readthedocs.org/docs/django-sekizai/en/latest/', None), 'treebeard': ('http://django-treebeard.readthedocs.io/en/latest/', None), } # Add any paths that contain templates here, relative to this directory. # templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django cms' copyright = u'2009-2017, Divio AG and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. path = os.path.split(os.path.dirname(__file__))[0] path = os.path.split(path)[0] sys.path.insert(0, path) import cms version = cms.__version__ # The full version, including alpha/beta/rc tags. release = cms.__version__ # The language for content autogenerated by Sphinx. Refer to documentation for # a list of supported languages. language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['build', 'env'] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be # searched for source files. exclude_trees = ['build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description unit # titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] todo_include_todos = True # -- Options for HTML output --------------------------------------------------- # on_rtd is whether we are on readthedocs.org on_rtd = os.environ.get('READTHEDOCS', None) == 'True' try: import divio_docs_theme html_theme = 'divio_docs_theme' html_theme_path = [divio_docs_theme.get_html_theme_path()] except: html_theme = 'default' show_cloud_banner = True # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'djangocmsdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). latex_paper_size = 'a4' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'djangocms.tex', u'django cms Documentation', u'Divio AG and contributors', 'manual'), ] # The name of an image file (relative to this directory) to place at the top # of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True # -- Options for LaTeX output -------------------------------------------------- # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. # temporarily disabled because of an issue on RTD. see docs/requirements.txt # if 'spelling' in sys.argv: # extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = 'en_GB' # Location of word list. spelling_word_list_filename = 'spelling_wordlist' spelling_ignore_pypi_package_names = True
bsd-3-clause
micktaiwan/scpm
app/controllers/workloads_controller.rb
41083
require 'rubygems' require 'google_chart' # http://badpopcorn.com/blog/2008/09/08/rails-google-charts-gchartrb/ class WorkloadsController < ApplicationController layout 'pdc' def index person_id = params[:person_id] project_ids = params[:project_ids] iterations_ids = params[:iterations_ids] tags_ids = params[:person_tags_ids] session['workload_person_id'] = person_id if person_id session['workload_person_id'] = current_user.id if not session['workload_person_id'] session['workload_person_id'] = params[:wl_person] if params[:wl_person] if project_ids if project_ids.class==Array session['workload_person_project_ids'] = project_ids # array of strings else session['workload_person_project_ids'] = [project_ids] # array with one string end else session['workload_person_project_ids'] = [] end session['workload_persons_iterations'] = [] if iterations_ids iterations_ids.each do |i| iteration = Iteration.find(i) iteration_name = iteration.name project_code = iteration.project_code project_id = iteration.project.id session['workload_persons_iterations'] << {:name=>iteration_name, :project_code=>project_code, :project_id=>project_id} end end session['workload_person_tags'] = [] if tags_ids if tags_ids.class==Array session['workload_person_tags'] = tags_ids # array of strings else session['workload_person_tags'] = [tags_ids] # array with one string end end @people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]} @projects = Project.find(:all).map {|p| ["#{p.name} (#{p.wl_lines.size} persons)", p.id]} change_workload(session['workload_person_id']) end def change_workload(person_id=nil) person_id = params[:person_id] if !person_id session['workload_person_id'] = person_id @workload = Workload.new(person_id,session['workload_person_project_ids'], session['workload_persons_iterations'],session['workload_person_tags'], {:hide_lines_with_no_workload => session['workload_hide_lines_with_no_workload'].to_s=='true', :include_forecast=>true}) @person = @workload.person get_last_sdp_update get_suggested_requests(@workload) get_sdp_tasks(@workload) get_chart get_sdp_gain(@workload.person) get_backup_warnings(@workload.person) get_holiday_warning(@workload.person) get_unlinked_sdp_tasks(@workload) end def get_last_sdp_update @last_sdp_phase = SDPPhase.find(:first, :order=>'updated_at desc') if @last_sdp_phase != nil @last_sdp_update = @last_sdp_phase.updated_at else @last_sdp_update = nil end end def get_chart chart = GoogleChart::LineChart.new('1000x300', "#{@workload.person.name} workload", false) serie = @workload.percents.map{ |p| p[:value] } return if serie.size == 0 realmax = serie.max high_limit = 150.0 max = realmax > high_limit ? high_limit : realmax high_limit = high_limit > max ? max : high_limit chart.data "non capped", serie, '0000ff' chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center chart.axis :x, :labels => @workload.months, :font_size => 10, :alignment => :center chart.shape_marker :circle, :color=>'3333ff', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>7 serie.each_with_index do |p,index| if p > high_limit chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>index, :pixel_size=>8 end end chart.range_marker :horizontal, :color=>'DDDDDD', :start_point=>97.0/max, :end_point=>103.0/max chart.show_legend = false @chart_url = chart.to_url({:chd=>"t:#{serie.join(',')}", :chds=>"0,#{high_limit}"}) end def get_suggested_requests(wl) if !wl or !wl.person or wl.person.rmt_user == "" @suggested_requests = [] return end request_ids = wl.wl_lines.select {|l| l.request_id != nil}.map { |l| filled_number(l.request_id,7)} cond = "" cond = " and request_id not in (#{request_ids.join(',')})" if request_ids.size > 0 @suggested_requests = Request.find(:all, :conditions => "assigned_to='#{wl.person.rmt_user}' and status!='closed' and status!='performed' and status!='cancelled' and status!='removed' and resolution!='ended' #{cond}", :order=>"project_name, summary") @suggested_requests = @suggested_requests.select { |r| r.sdp_tasks_remaining_sum > 0 } end def get_backup_warnings(person_id) currentWeek = wlweek(Date.today) nextWeek = wlweek(Date.today+7.days) backups = WlBackup.find(:all, :conditions=>["backup_person_id = ? and (week = ? or week = ?)", person_id, currentWeek, nextWeek]) @backup_holidays = [] backups.each do |b| # Load for holyday and concerned user (for the 14 next days) person_holiday_load = WlLoad.find(:all, :joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id', :conditions=>["wl_lines.person_id = ? and wl_lines.wl_type = ? and (wl_loads.week = ? or wl_loads.week = ?)", b.person.id.to_s, WL_LINE_HOLIDAYS, currentWeek, nextWeek]) if person_holiday_load.count > 0 load_total = 0 # Calcul the number of day of holiday. If it's over the threshold, display the warning person_holiday_load.map { |wload| load_total += wload.wlload } if (load_total > APP_CONFIG['workload_holiday_threshold_before_backup']) @backup_holidays << b.person.name if !@backup_holidays.include?(b.person.name) end end end end def do_get_sdp_tasks() person_id = session['workload_person_id'] p = Person.find(person_id) @sdp_tasks = SDPTask.find(:all, :conditions=>["collab=?", p.trigram], :order=>"title").map{|t| ["[#{t.project_name}] #{ActionController::Base.helpers.sanitize(t.title)} (#{t.remaining})", t.sdp_id]} render(:partial=>'sdp_task_options') end def get_sdp_tasks(wl,options = {}) # if wl.nil? if wl.person.trigram == "" @sdp_tasks = [] return end task_ids = wl.wl_lines.map{|l| l.sdp_tasks.map{|l| l.sdp_id}}.select{|l| (l != [])}#wl.wl_lines.select {|l| l.sdp_task_id != nil}.map { |l| l.sdp_task_id} cond = "" cond = " and sdp_id not in (#{task_ids.join(',')})" if task_ids.size > 0 @sdp_tasks = SDPTask.find(:all, :conditions=>["collab=? and request_id is null #{cond} and remaining > 0", wl.person.trigram], :order=>"title").map{|t| ["[#{t.project_name}] #{ActionController::Base.helpers.sanitize(t.title)} (#{t.assigned})", t.sdp_id]} # end end def get_unlinked_sdp_tasks(wl) # Directly linked wl<=> sdp task_ids = wl.wl_lines.map{|l| l.sdp_tasks.map{|l| l.sdp_id}}.select{|l| (l != [])} cond = " and sdp_id not in (#{task_ids.join(',')})" if task_ids.size > 0 @sdp_tasks_unlinked = SDPTask.find(:all, :conditions => ["collab = ? AND request_id IS NULL #{cond} and remaining > 0", wl.person.trigram]) # By requests wl_lines_id = wl.wl_lines.map{ |l| l.request_id} @sdp_tasks_unlinked_req = SDPTask.find(:all, :conditions => ["collab = ? AND request_id IS NOT NULL AND request_id NOT IN (?) and remaining > 0", wl.person.trigram, wl_lines_id]) # Requests not linked and with no remaining person = Person.find(session['workload_person_id'].to_i) @requests_to_close = Array.new reqs = Request.find(:all, :conditions=>["status='assigned' and resolution!='ended' and resolution!='aborted' and assigned_to = ?", person.rmt_user]) reqs.each { |r| total_remaining = 0 sdpTaskTemp = SDPTask.find(:all, :conditions=>"request_id='#{r.request_id}'") sdpTaskTemp.each do |tmp_sdp| total_remaining += tmp_sdp.remaining end if sdpTaskTemp.size > 0 and total_remaining == 0 @requests_to_close << r end } # render :layout => false end # Return an array of hash # Hash : {"holidayObject" => HolidayModel, "needBackup" => BOOL, "hasBackup" => BOOL, "backup_people" => [STRING], "backup_comments" => [STIRNG]} def get_holiday_warning_detailed(person, dateMax) holiday_array = Array.new index = 0 # Get holidays person_holiday_load = WlLoad.find(:all, :joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id', :conditions=>["wl_lines.person_id = ? and wl_lines.wl_type = ? and week >= ? and week < ?", person.id.to_s, WL_LINE_HOLIDAYS, wlweek(Date.today), wlweek(dateMax)], :order=>"week") # Each holiday person_holiday_load.each do |holiday| backups = WlBackup.find(:all, :conditions=>["person_id = ? and week = ?",person.id.to_s, holiday.week]) # Create hash object holiday_hash = {"holidayObject" => holiday, "needBackup" => false, "hasBackup" => false, "backup_people" => [], "backup_comments" => []} # Need backup by week load ? if holiday.wlload >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i holiday_hash["needBackup"] = true end # Have backups ? if backups != nil and backups.size > 0 holiday_hash["hasBackup"] = true backups.each do |b| holiday_hash["backup_people"] << b.backup.name if b.comment != nil and b.comment.length > 0 holiday_hash["backup_comments"] << b.comment else holiday_hash["backup_comments"] << "" end end end # Add hash holiday_array << holiday_hash # Check previous and update needBackup if necessary if (index > 0) previous_holiday_hash = holiday_array[index-1] if (wlweek_reverse(previous_holiday_hash["holidayObject"].week) + 1.week) == wlweek_reverse(holiday_hash["holidayObject"].week) if ((previous_holiday_hash["holidayObject"].wlload.to_i + holiday_hash["holidayObject"].wlload.to_i) >= 4) if (previous_holiday_hash["holidayObject"].wlload.to_i >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i) or (holiday_hash["holidayObject"].wlload.to_i >= APP_CONFIG['workload_holiday_threshold_before_backup'].to_i) previous_holiday_hash["needBackup"] = true holiday_hash["needBackup"] = true end end end end index += 1 end return holiday_array end def get_holiday_warning(person) @holiday_without_backup = false # Backup button in red if holiday without backup @holiday_backup_warning = Hash.new # WLload in red if holiday without backup while it should holiday_array = get_holiday_warning_detailed(person, Date.today+8.weeks) # Analyze the array of hash - Set holiday_array.each do |hash| if hash["needBackup"] == true and hash["hasBackup"] == false @holiday_without_backup = true @holiday_backup_warning[hash["holidayObject"].week] = true else @holiday_backup_warning[hash["holidayObject"].week] = false end end end def get_sdp_gain(person) @balance = person.sdp_balance @sdp_logs = SdpLog.find(:all, :conditions=>["person_id=?", person.id], :order=>"`date` desc", :limit=>3).reverse end def consolidation @companies = Company.all.map {|p| ["#{p.name}", p.id]} @projects = Project.all.map {|p| ["#{p.name}", p.id]} end def get_people @company_ids = params['company'] @company_ids = @company_ids['company_ids'] if @company_ids # FIXME: pass only a simple field.... @project_ids = params['project'] @project_ids = @project_ids['project_ids'] if @project_ids # FIXME: pass only a simple field.... if @project_ids and @project_ids != '' @project_ids = [@project_ids] else @project_ids = [] end cond = "" cond += " and company_id in (#{@company_ids})" if @company_ids and @company_ids!='' @people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0 and is_transverse=0" + cond, :order=>"name") end def refresh_conso @start_time = Time.now # find "to be validated" requests not in the workload already_in_the_workload = WlLine.all.select{|l| l.request and (l.request.status=='to be validated' or (l.request.status=='assigned' and l.request.resolution!='ended' and l.request.resolution!='aborted'))}.map{|l| l.request} @not_in_workload = (Request.find(:all,:conditions=>"status='to be validated' or (status='assigned' and resolution!='ended' and resolution!='aborted')") - already_in_the_workload).sort_by{|r| (r.project ? r.project.full_name : "")} # find the corresponding production days (minus 20% of gain) @not_in_workload_days = @not_in_workload.inject(0) { |sum, r| sum += r.workload2} * 0.80 get_people @transverse_people = Person.find(:all, :conditions=>"has_left=0 and is_transverse=1", :order=>"name").map{|p| p.name.split(" ")[0]}.join(", ") @workloads = [] @total_days = 0 @total_planned_days = 0 @to_be_validated_in_wl_remaining_total = 0 for p in @people next if not p.has_workload_for_projects?(@project_ids) w = Workload.new(p.id,[],'','', {:add_holidays=>true}) next if w.wl_lines.select{|l| l.wl_type != WL_LINE_HOLIDAYS}.size == 0 # do not display people with no lines at all @workloads << w @total_days += w.line_sums.inject(0) { |sum, (k,v)| sum += v[:remaining] == '' ? 0 : v[:remaining] } @total_planned_days += w.planned_total @to_be_validated_in_wl_remaining_total += w.to_be_validated_in_wl_remaining_total #break end @workloads = @workloads.sort_by {|w| [-w.person.is_virtual, w.next_month_percents, w.three_next_months_percents, w.person.name]} @totals = [] @cap_totals = [] @chart_totals = [] @chart_cap_totals = [] @avail_totals = [] size = @workloads.size if size == 0 render :layout => false return end chart_size = @workloads.select{|w| w.person.is_virtual==0}.size # to plan @totals << (@workloads.inject(0) { |sum,w| sum += w.remain_to_plan_days }) @cap_totals << '' @avail_totals << '' # next 5 weeks @totals << (@workloads.inject(0) { |sum,w| sum += w.next_month_percents} / size).round @cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.next_month_percents)} / size).round @avail_totals << '' # next 3 months @totals << (@workloads.inject(0) { |sum,w| sum += w.three_next_months_percents} / size).round @cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.three_next_months_percents)} / size).round @avail_totals << '' # availability 2 mths @totals << '' @cap_totals << '' @avail_totals << (@workloads.inject(0) { |sum,w| sum += w.sum_availability }) # per weeks @workloads.first.weeks.each_with_index do |tmp,i| @totals << (@workloads.inject(0) { |sum,w| sum += w.percents[i][:value]} / size).round @chart_totals << (@workloads.inject(0) { |sum,w| w.person.is_virtual==1 ? 0.0 : sum += w.percents[i][:value]} / chart_size).round @cap_totals << (@workloads.inject(0) { |sum,w| sum += cap(w.percents[i][:value])} / size).round @chart_cap_totals << (@workloads.inject(0) { |sum,w| w.person.is_virtual==1 ? 0.0 : sum += cap(w.percents[i][:value])} / chart_size).round @avail_totals << (@workloads.inject(0) { |sum,w| sum += w.availability[i][:value]}) end # workload chart chart = GoogleChart::LineChart.new('1000x300', "Workload (without virtual people)", false) realmax = [@chart_totals.max, @chart_cap_totals.max].max high_limit = 150.0 max = realmax > high_limit ? high_limit : realmax high_limit = high_limit > max ? max : high_limit cap_serie = @chart_cap_totals.map { |p| p <= max ? p : max} noncap_serie = @chart_totals.map { |p| p <= max ? p : max} chart.data "capped", cap_serie, 'ff0000' chart.data "non capped", noncap_serie, '0000ff' #chart.add_labels @chart_cap_totals chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center chart.axis :x, :labels => @workloads.first.months, :font_size => 10, :alignment => :center chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>8 chart.shape_marker :circle, :color=>'3333ff', :data_set_index=>1, :data_point_index=>-1, :pixel_size=>8 @chart_cap_totals.each_with_index do |p,index| if p > high_limit chart.shape_marker :circle, :color=>'333333', :data_set_index=>0, :data_point_index=>index, :pixel_size=>8 end end @chart_totals.each_with_index do |p,index| if p > high_limit chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>1, :data_point_index=>index, :pixel_size=>8 end end chart.range_marker :horizontal, :color=>'EEEEEE', :start_point=>95.0/max, :end_point=>105.0/max chart.show_legend = true #chart.enable_interactivity = true #chart.params[:chm] = "h,FF0000,0,-1,1" @chart_url = chart.to_url #({:chm=>"r,DDDDDD,0,#{100.0/max-0.01},#{100.0/max}"}) #({:enableInteractivity=>true}) if APP_CONFIG['use_virtual_people'] # staffing chart serie = [] @workloads.first.weeks.each_with_index do |tmp,i| serie << @workloads.inject(0) { |sum,w| sum += w.staffing[i]} end chart = GoogleChart::LineChart.new('1000x300', "Staffing", false) max = serie.max chart.data "nb person", serie, 'ff0000' chart.axis :y, :range => [0,max], :font_size => 10, :alignment => :center chart.axis :x, :labels => @workloads.first.months, :font_size => 10, :alignment => :center chart.shape_marker :circle, :color=>'ff3333', :data_set_index=>0, :data_point_index=>-1, :pixel_size=>8 chart.show_legend = true @staffing_chart_url = chart.to_url #({:chm=>"r,DDDDDD,0,#{100.0/max-0.01},#{100.0/max}"}) #({:enableInteractivity=>true}) end render :layout => false end def cap(nb) nb > 100 ? 100 : nb end def refresh_holidays @people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name") @workloads = [] @resfresh_holidays_backup_warnings = {} #resfresh_holidays_backup_warnings[person.id] = Hash from get_holiday_warning for p in @people # Person Workload @workloads << Workload.new(p.id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags'], {:only_holidays=>true}) # Person Holiday Warning @resfresh_holidays_backup_warnings[p.id] = get_holiday_warning_detailed(p, Date.today+27.weeks) end @workloads = @workloads.sort_by {|w| [w.person.name]} render :layout => false end # Find all lines without tasks def refresh_missing_tasks @lines = WlLine.find(:all, :conditions=>"wl_lines.id not in (select wl_line_id from wl_line_tasks) and wl_lines.wl_type=200", :order=>"project_id, person_id") render :layout => false end # find all SDP tasks not associated to workload lines def refresh_missing_wl_lines task_ids = WlLineTask.find(:all, :select=>"sdp_task_id").map{ |t| t.sdp_task_id}.uniq @tasks = SDPTask.find(:all, :conditions=>"remaining > 0 and sdp_id not in (#{task_ids.join(',')})", :order=>"project_code, remaining desc") render :layout => false end # find all sdp tasks affected to wrong workload def refresh_errors_in_affectations @associations = WlLineTask.find(:all).select{|a| !a.sdp_task or a.sdp_task.collab != a.wl_line.person.trigram}.sort_by { |a| [a.wl_line.project_name, a.wl_line.name]} render :layout => false end def refresh_requests_to_validate @requests = Request.find(:all, :conditions=>"status='to be validated'", :order=>"summary") @week1 = wlweek(Date.today) @week2 = wlweek(Date.today+7.days) @requests = @requests.select {|r| wl = r.wl_line; wl and (wl.get_load_by_week(@week1) > 0 or wl.get_load_by_week(@week2) > 0)} render :layout => false end def refresh_tbp get_people @workloads = [] for p in @people w = Workload.new(p.id, @project_ids, '', '', {:include_forecast=>true, :add_holidays=>false, :weeks_to_display=>12}) next if w.wl_lines.select{|l| l.wl_type != WL_LINE_HOLIDAYS}.size == 0 # do not display people with no lines at all @workloads << w end render :layout => false end def add_by_request request_id = params[:request_id] if !request_id or request_id.empty? @error = "Please provide a request number" return end request_id.strip! person_id = session['workload_person_id'].to_i # person_id = params[:wl_person].to_i session['workload_person_id'] = person_id.to_s filled = filled_number(request_id,7) request = Request.find_by_request_id(filled) if not request @error = "Can not find request with number #{request_id}" return end project = request.project name = request.workload_name found = WlLine.find_by_person_id_and_request_id(person_id, request_id) if not found @line = WlLine.create(:name=>name, :request_id=>request_id, :person_id=>person_id, :wl_type=>WL_LINE_REQUEST) get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) else @error = "This line already exists: #{request_id}" end end def add_by_name name = params[:name].strip if name.empty? @error = "Please provide a name." return end person_id = session['workload_person_id'].to_i # person_id = params[:wl_person].to_i session['workload_person_id'] = person_id.to_s found = WlLine.find_by_person_id_and_name(person_id, name) if not found @line = WlLine.create(:name=>name, :request_id=>nil, :person_id=>person_id, :wl_type=>WL_LINE_OTHER) get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) else @error = "This line already exists: #{name}" end end def add_by_sdp_task sdp_task_id = params[:sdp_task_id].to_i person_id = params[:wl_person].to_i session['workload_person_id'] = person_id.to_s sdp_task = SDPTask.find_by_sdp_id(sdp_task_id) if not sdp_task @error = "Can not find SDP Task with id #{sdp_task_id}" return end found = WlLineTask.find(:first, :conditions=>["sdp_task_id=?",sdp_task_id]) if not found @line = WlLine.create(:name=>sdp_task.title, :person_id=>person_id, :wl_type=>WL_LINE_OTHER) WlLineTask.create(:wl_line_id=>@line.id, :sdp_task_id=>sdp_task_id) if(APP_CONFIG['auto_link_task_to_project']) and sdp_task.project @line.project_id = sdp_task.project.id @line.save end else @error = "Task '#{found.sdp_task.title}' is already linked to workload line '#{found.wl_line.name}'" end get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def add_by_project project_id = params[:project_id].to_i person_id = session['workload_person_id'].to_i # person_id = params[:wl_person].to_i session['workload_person_id'] = person_id.to_s project = Project.find(project_id) if not project @error = "Can not find project with id #{project_id}" return end found = WlLine.find_by_project_id_and_person_id(project_id, person_id) # allow to add several lines by projet #if not found @line = WlLine.create(:name=>project.name, :project_id=>project_id, :person_id=>person_id, :wl_type=>WL_LINE_OTHER) #else # @error = "This line already exists: #{found.name}" #end get_workload_data(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def display_edit_line line_id = params[:l].to_i @wl_line = WlLine.find(line_id) @workload = Workload.new(session['workload_person_id'],session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) if APP_CONFIG['workloads_add_by_project'] @projects = Project.all.map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]} end if @workload.person.trigram == "" @sdp_tasks = [] else get_sdp_tasks(@workload) end end def edit_line @wl_line = WlLine.find(params[:id]) @wl_line.update_attributes(params[:wl_line]) @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def destroy_line @wl_line_id = params[:id] wl_line = WlLine.find(@wl_line_id) person_id = wl_line.person_id wl_line.destroy WlLineTask.find(:all, :conditions=>["wl_line_id=?",@wl_line_id]).each do |l| l.destroy end line_tags = LineTag.find(:all, :conditions=>["line_id=#{@wl_line_id}"]) tags = [] line_tags.each do |l| tag = Tag.find(l.tag_id) tags << tag if !tags.include?(tag) end line_tags.each do |l| l.destroy end tags.each do |t| t.destroy if LineTag.find(:all, :conditions=>["tag_id=#{t.id}"]).size == 0 end @workload = Workload.new(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) get_sdp_tasks(@workload) end def link_to_request request_id = params[:request_id].strip line_id = params[:id] if request_id.empty? @error = "Please provide a request number." return end person_id = session['workload_person_id'].to_i # person_id = params[:wl_person].to_i session['workload_person_id'] = person_id.to_s filled = filled_number(request_id,7) request = Request.find_by_request_id(filled) if not request @error = "Can not find request with number #{request_id}" return end project = request.project name = request.workload_name found = WlLine.find_by_person_id_and_request_id(person_id, request_id) if not found @wl_line = WlLine.find(line_id) @wl_line.name = name @wl_line.request_id = request_id @wl_line.wl_type = WL_LINE_REQUEST @wl_line.save @workload = Workload.new(person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) else @error = "This line already exists: #{request_id}" end end def unlink_request line_id = params[:id] @wl_line = WlLine.find(line_id) @wl_line.request_id = nil @wl_line.wl_type = WL_LINE_OTHER @wl_line.save @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def update_settings_name update_status = params[:on] if update_status=='true' current_user.settings.wl_line_change_name = 1 else current_user.settings.wl_line_change_name = 0 end current_user.save render(:nothing=>true) end def link_to_sdp sdp_task_id = params[:sdp_task_id].to_i line_id = params[:id] task = SDPTask.find_by_sdp_id(sdp_task_id) @wl_line = WlLine.find(line_id) @wl_line.add_sdp_task_by_id(sdp_task_id) if not @wl_line.sdp_tasks.include?(task) update_line_name(@wl_line) if ( current_user.settings.wl_line_change_name == 1 ) @wl_line.wl_type = WL_LINE_OTHER @wl_line.save @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) get_sdp_tasks(@workload) end def unlink_sdp_task sdp_task_id = params[:sdp_task_id].to_i line_id = params[:id] @wl_line = WlLine.find(line_id) person = Person.find(session['workload_person_id'].to_i) @wl_line.delete_sdp(sdp_task_id) update_line_name(@wl_line) if ( current_user.settings.wl_line_change_name == 1 ) @wl_line.save @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) get_sdp_tasks(@workload) end def link_to_project project_id = params[:project_id].to_i line_id = params[:id] @wl_line = WlLine.find(line_id) @wl_line.project_id = project_id @wl_line.wl_type = WL_LINE_OTHER @wl_line.save @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def unlink_project line_id = params[:id] @wl_line = WlLine.find(line_id) @wl_line.project_id = nil @wl_line.wl_type = WL_LINE_OTHER @wl_line.save @workload = Workload.new(@wl_line.person_id,session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def edit_load view_by = (params['view_by']=='1' ? :project : :person) @line_id = params[:l].to_i @wlweek = params[:w].to_i value = round_to_hour(params[:v].to_f) value = 0 if value < 0 line = WlLine.find(@line_id) id = view_by==:person ? line.person_id : line.project_id if value == 0.0 if (line.wl_type == WL_LINE_HOLIDAYS) backup = WlBackup.find(:all, :conditions=>["person_id = ? and week = ?", line.person.id.to_s, @wlweek]) # Send email backup.each do |b| Mailer::deliver_backup_delete(b) end backup.each(&:destroy) end WlLoad.delete_all(["wl_line_id=? and week=?",@line_id, @wlweek]) @value = "" else wl_load = WlLoad.find_by_wl_line_id_and_week(@line_id, @wlweek) wl_load = WlLoad.create(:wl_line_id=>@line_id, :week=>@wlweek) if not wl_load wl_load.wlload = value wl_load.save @value = value end @lsum, @plsum, @csum, @cpercent, @case_percent, @total, @planned_total, @avail, @diff_planned_remaining_line, @diff_planned_remaining = get_sums(line, @wlweek, id, view_by) end # type is :person or :projet and indicates what is the id (person or projet) def get_sums(line, week, id, type=:person) @type = type today_week = wlweek(Date.today) plsum = line.wl_loads.map{|l| (l.week < today_week ? 0 : l.wlload)}.inject(:+) || 0 lsum = line.wl_loads.map{|l| l.wlload}.inject(:+) if(type==:project) wl_lines = WlLine.find(:all, :conditions=>["project_id in (#{session['workload_project_ids'].join(',')})"]) person_wl_lines = WlLine.find(:all, :conditions=>["person_id=?", line.person.id]) case_sum = person_wl_lines.map{|l| l.get_load_by_week(week)}.inject(:+) case_sum = 0 if !case_sum nb_days_per_weeks = 5 * wl_lines.map{|l| l.person_id}.uniq.size else wl_lines = WlLine.find(:all, :conditions=>["person_id=?", id]) nb_days_per_weeks = 5 end csum = wl_lines.map{|l| l.get_load_by_week(week)}.inject(:+) csum = 0 if !csum case_sum = csum if type==:person open = nb_days_per_weeks wl_lines.map{|l| l.person}.uniq.each do |p| company = Company.find_by_id(p.company_id) open = open - WlHoliday.get_from_week_and_company(week,company) end company = Company.find_by_id(line.person.company_id) person_open = 5 - WlHoliday.get_from_week_and_company(week,company) # cpercent is the percent of occupation for a week. It depends of the view (person or project) cpercent = open > 0 ? (csum / open*100).round : 0 # case_percent is the percent of occupation for a week for a person. It does not depend of the view (person or project) case_percent = open > 0 ? (case_sum / person_open*100).round : 0 if APP_CONFIG['workload_show_overload_availability'] avail = open-csum else avail = [0,(open-csum)].max end planned_total = 0 total = 0 total_remaining = 0 for l in wl_lines next if l.wl_type > 200 l.wl_loads.each { |load| total += load.wlload planned_total += (load.week < today_week ? 0 : load.wlload) } total_remaining += l.sdp_tasks_remaining end diff_planned_remaining_line = plsum - line.sdp_tasks_remaining diff_planned_remaining = planned_total - total_remaining [lsum, plsum, csum, cpercent, case_percent, total, planned_total, avail, diff_planned_remaining_line, diff_planned_remaining] end def transfert @people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]} # WL Lines without project @lines = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NULL", session['workload_person_id']], :include=>["request","wl_line_task","person"], :order=>"wl_type, name") # WL lines by project temp_lines_qr_qwr = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NOT NULL", session['workload_person_id']], :include=>["request","wl_line_task","person"], :order=>"wl_type, name") @lines_qr_qwr = Hash.new temp_lines_qr_qwr.each do |wl| @lines_qr_qwr[wl.project_id] = [wl] end @owner_id = session['workload_person_id'] # all lines @all_lines = WlLine.find(:all, :conditions=>["person_id=?", session['workload_person_id']], :include=>["project"], :order=>"wl_type, name") end def do_transfert # Params lines = params['lines'] # array of ids (as strings) lines_qr_qwr = params['lines_qr_qwr'] # array of ids of wl lines qr qwr (as strings) p_id = params['person_id'] owner_id = params['owner_id'] # Lines to transfert if lines lines.each { |l_id| l = WlLine.find(l_id.to_i) l.person_id = p_id.to_i l.save } end # Lines of qr_qwr to transfert if lines_qr_qwr lines_qr_qwr.each { |l_id| # Find all lines (two line by project qr_qwr) l = WlLine.find(l_id.to_i) WlLine.find(:all,:conditions=>["person_id = ? and project_id = ?",owner_id.to_s, l.project_id.to_s]).each { |line_by_project| line_by_project.person_id = p_id.to_i line_by_project.project.qr_qwr_id = p_id.to_i line_by_project.save line_by_project.project.save } } end redirect_to(:action=>"transfert") end def duplicate @months = [] @weeks = [] @wl_weeks = [] @months = params[:months] @weeks = params[:weeks] @wl_weeks = params[:wl_weeks] @people = Person.find(:all, :conditions=>"has_left=0 and is_supervisor=0", :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]} # WL lines without project_id @lines = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NULL", session['workload_person_id']], :include=>["request","wl_line_task","person"], :order=>"wl_type, name") # WL lines by project @lines_qr_qwr = WlLine.find(:all, :conditions=>["person_id=? and project_id IS NOT NULL", session['workload_person_id']], :include=>["request","wl_line_task","person"], :order=>"project_id,wl_type,name") end def do_duplication lines_loads = params['lines_loads'] # array of lineId_loadId p_id = params['person_id'] lines_loads.each { |l_l| # Wl_line and Wl_load selected l_l_splited = l_l.split("_") line_id = l_l_splited[0] load_id = l_l_splited[1] line = WlLine.find(line_id.to_i) load = WlLoad.find(load_id.to_i) # Check if the line to duplicate isn't already duplicated from another line # If Line to duplicate is already duplicate, so we take the first line as parent_id parent_id = line.id if line.parent_line parent = WlLine.find(line.parent_line) parent_id = parent.id end # Check if the person selected has not already a duplicate duplicate = 0 # Id of the Wl_line duplicated and managed by the person selected (0 if null) if line.duplicates != nil line.duplicates.each { |l| if l.person_id.to_s == p_id duplicate = l.id end } end # If the person selected has not already a duplicate, we create it if duplicate == 0 new_line = line.clone new_line.parent_line = parent_id new_line.person_id = p_id new_line.save duplicate = new_line.id end # Change wl_line of load selected load.wl_line_id = duplicate load.save # Project request = Request.first(:conditions=>["request_id = ?",line.request_id]) if line.request_id if request != nil project_id = request.project_id project_person = ProjectPerson.first(:conditions => ["project_id = ? and person_id = ?", project_id, p_id]) if project_id if project_person == nil project_person = ProjectPerson.new project_person.project_id = project_id project_person.person_id = p_id project_person.save end end } redirect_to(:action=>"index") end def hide_lines_with_no_workload on = (params[:on].to_s != 'false') session['workload_hide_lines_with_no_workload'] = on get_workload_data(session['workload_person_id'],session['workload_person_project_ids'],session['workload_persons_iterations'],session['workload_person_tags']) end def hide_wmenu session['wmenu_hidden'] = params[:on] render(:nothing=>true) end def backup @people = Person.find(:all, :conditions=>["has_left=0 and is_supervisor=0 and id != ?", session['workload_person_id']], :order=>"name").map {|p| ["#{p.name} (#{p.wl_lines.size} lines)", p.id]} @backups = WlBackup.find(:all, :conditions=>["person_id=?", session['workload_person_id']]); @self_backups = WlBackup.find(:all, :conditions=>["backup_person_id=?", session['workload_person_id']]); backup_weeks = Array.new @backups.each do |b| backup_weeks << b.week end # Get holidays week conditions = "wl_lines.person_id = #{session['workload_person_id'].to_s} and wl_lines.wl_type = #{WL_LINE_HOLIDAYS} and wlload > 0 and week >= #{wlweek(Date.today)}" person_holiday_load = WlLoad.find(:all, :joins => 'JOIN wl_lines ON wl_lines.id = wl_loads.wl_line_id', :conditions=>conditions, :order=>"week") @holiday_dates = person_holiday_load.map { |h| year = h.week.to_s[0..-3] week = h.week.to_s[4..6] ["#{week}-#{year}","#{h.week}"] } end def create_backup b_id = params['backup_person_id'] p_id = params['person_id'] week = params['week'] backups = WlBackup.first(:conditions=>["backup_person_id = ? and person_id = ? and week = ?", b_id, p_id, week]); if (backups == nil) backup = WlBackup.new backup.backup_person_id = b_id backup.person_id = p_id backup.week = week backup.save render :text=>backup.week.to_s+"_"+backup.backup.name else render(:nothing=>true) end end def delete_backup backup_id = params['backup_id'] backup = WlBackup.first(:conditions=>["id = ?", backup_id]); backup.destroy render(:nothing=>true) end def update_backup_comment backup_id = params['backup_id'] backup_comment = params['backup_comment'] backup = WlBackup.first(:conditions=>["id = ?", backup_id]); if backup != nil backup.comment = backup_comment backup.save end render :text=>backup.comment, :layout => false end private def get_workload_data(person_id, projects_ids, person_iterations, tags_ids) @workload = Workload.new(person_id,projects_ids,person_iterations, tags_ids, {:hide_lines_with_no_workload => session['workload_hide_lines_with_no_workload'].to_s=='true'}) @person = @workload.person get_last_sdp_update get_suggested_requests(@workload) get_chart get_sdp_gain(@workload.person) get_sdp_tasks(@workload) get_backup_warnings(@workload.person) get_unlinked_sdp_tasks(@workload) get_holiday_warning(@workload.person) end def update_line_name(line) line.name = line.sdp_tasks.map{|p| p.title}.sort.join(', ') line.name = "No line name" if line.name == "" end end
bsd-3-clause
danielbarter/personal_website_code
CALGO/sorting/sort_test.c
3896
/* system includes */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <limits.h> /* source includes */ #include "insertion_merge_sort_unboxed.c" #include "insertion_merge_sort.c" void test_sort ( void (*sort_pointer) (list *l), int array_test_size, int max_size); void test_sort_unboxed ( void (*sort_pointer) (int *array, int length), int array_test_size, int max_size ); void print_array(int * array, int length); int int_compare_32bit(void *ptr1, void *ptr2); void print_list_32bit(list *l); int main(void) { srand(time(NULL)); /* initialize the seed for the pseudorandom generator */ printf("testing insertion sort unboxed: \n\n"); test_sort_unboxed(&insertion_sort_unboxed,0,100); test_sort_unboxed(&insertion_sort_unboxed,1,100); test_sort_unboxed(&insertion_sort_unboxed,10,100); test_sort_unboxed(&insertion_sort_unboxed,50,10); printf("\n"); printf("testing merge sort unboxed: \n\n"); test_sort_unboxed(&merge_sort_unboxed,0,100); test_sort_unboxed(&merge_sort_unboxed,1,100); test_sort_unboxed(&merge_sort_unboxed,10,100); test_sort_unboxed(&merge_sort_unboxed,50,10); printf("\n"); printf("testing insertion sort: \n\n"); test_sort(&insertion_sort,10,100); test_sort(&insertion_sort,0,100); test_sort(&insertion_sort,1,100); test_sort(&insertion_sort,10,100); test_sort(&insertion_sort,50,10); printf("\n"); printf("testing merge sort: \n\n"); test_sort(&merge_sort,0,100); test_sort(&merge_sort,1,100); test_sort(&merge_sort,2,100); test_sort(&merge_sort,10,100); test_sort(&merge_sort,50,10); printf("\n"); return 0; } void test_sort_unboxed ( void (*sort_pointer) (int *array, int length), int array_test_size, int max_size ) /* http://fuckingfunctionpointers.com/ sort_pointer is a pointer to the sorting procedure array_test_size is the size of the array to test with the entries of the test array are reduced modulo max_size */ { int test[array_test_size]; /* dynamically allocated arrays yew */ int i; /* index for initializing the test arrays */ /* initializing the test array with random data */ for (i = 0; i < array_test_size; i++) { test[i] = rand() % max_size; } /* printing the test array */ printf("test array with %d elements in range [0,%d]: ",array_test_size,max_size); print_array(test, array_test_size); printf("\n"); printf("applying procedure....... \n"); (*sort_pointer)(test,array_test_size); /* printing the sorted array */ printf("sorted array: "); print_array(test,array_test_size); printf("\n\n"); } void test_sort ( void (*sort_pointer) (list *l), int array_test_size, int max_size) { int test_array[array_test_size]; int i; /* index for initializing the test arrays */ /* initializing the test array with random data */ for (i = 0; i < array_test_size; i++) { test_array[i] = rand() % max_size; } void *test_pointers[array_test_size]; for (i = 0; i < array_test_size; i++) test_pointers[i] = test_array + i; list l = { .ptr = test_pointers , .length = array_test_size , .compare = &int_compare_32bit}; printf("test array with %d elements in range [0,%d]: ",array_test_size,max_size); print_list_32bit(&l); printf("\n"); printf("applying procedure....... \n"); (*sort_pointer)(&l); printf("sorted array: "); print_list_32bit(&l); printf("\n\n"); } /* misc procedures */ int int_compare_32bit(void *ptr1, void *ptr2) { return *((int *) ptr1) < *((int *) ptr2); } void print_array(int *array, int length) { int i; for (i = 0; i < length; i++) { printf("%d ",array[i]); } } /* procedure for printing a list of 32 bit integers */ void print_list_32bit(list *l) { int i; for (i = 0; i < l->length; i++) printf("%d ", *((int *) l->ptr[i])); }
bsd-3-clause
ovh-ux/ovh-ui-kit
packages/apps/workshop/stories/design-system/components/button-native-primary.stories.js
3190
import { select } from '@storybook/addon-knobs'; import readme from '@ovh-ux/ui-kit.button/README.md'; const state = { label: 'State', options: { Normal: '', Disabled: 'disabled', }, default: '', }; export default { title: 'Design System/Components/Buttons/Native/Primary', parameters: { notes: readme, options: { showPanel: true, }, }, }; export const Default = () => ` <button class="oui-button oui-button_primary" ${select(state.label, state.options, state.default)}> Call to action </button> <button class="oui-button oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> Call to action </button> <button class="oui-button oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> </button>`; export const Large = () => ` <button class="oui-button oui-button_l oui-button_primary" ${select( state.label, state.options, state.default, )}> Call to action </button> <button class="oui-button oui-button_l oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> Call to action </button> <button class="oui-button oui-button_l oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder" aria-hidden="true"></span> </button>`; export const Small = () => ` <button class="oui-button oui-button_s oui-button_primary" ${select( state.label, state.options, state.default, )}> OK </button> <button class="oui-button oui-button_s oui-button_primary" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder"></span> </button>`; export const Block = () => ` <button class="oui-button oui-button_block oui-button_primary" ${select( state.label, state.options, state.default, )}> Call to action </button> <button class="oui-button oui-button_block oui-button_primary oui-button_icon-left" ${select( state.label, state.options, state.default, )}> <span class="oui-icon oui-icon-folder"></span> Call to action </button> <button class="oui-button oui-button_block oui-button_primary oui-button_icon-right" ${select( state.label, state.options, state.default, )}> Call to action <span class="oui-icon oui-icon-folder"></span> </button>`; export const Group = () => ` <div class="oui-button-group"> <button class="oui-button oui-button_primary">Lorem</button> <button class="oui-button oui-button_primary">Ipsum</button> <button class="oui-button oui-button_primary">Dolor</button> <button class="oui-button oui-button_primary">Sit</button> <button class="oui-button oui-button_primary">Amet</button> </div>`;
bsd-3-clause
stormi/tsunami
src/secondaires/magie/sorts.py
3125
# -*-coding:Utf-8 -* # Copyright (c) 2010 DAVY Guillaume # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Fichier contenant la classe Sorts, détaillée plus bas.""" from abstraits.obase import BaseObj from .sort import Sort class Sorts(BaseObj): """Classe-conteneur des sorts. Cette classe contient tous les sortilèges et autres maléfices de l'univers, éditables et utilisables, et offre quelques méthodes de manipulation. Voir : ./sort.py """ enregistrer = True def __init__(self): """Constructeur du conteneur""" BaseObj.__init__(self) self.__sorts = {} def __getnewargs__(self): return () def __contains__(self, cle): """Renvoie True si le sort existe, False sinon""" return cle in self.__sorts def __len__(self): return len(self.__sorts) def __getitem__(self, cle): """Renvoie un sort à partir de sa clé""" return self.__sorts[cle] def __setitem__(self, cle, sort): """Ajoute un sort à la liste""" self.__sorts[cle] = sort def __delitem__(self, cle): """Détruit le sort spécifié""" del self.__sorts[cle] def values(self): return self.__sorts.values() def ajouter_ou_modifier(self, cle): """Ajoute un sort ou le renvoie si existant""" if cle in self.__sorts: return self.__sorts[cle] else: sort = Sort(cle, self) self.__sorts[cle] = sort return sort def get(self, cle, valeur=None): """Retourne le sort ou valeur si non présent.""" return self.__sorts.get(cle, valeur)
bsd-3-clause
NovaeWorkshop/Nova
app/templates/server/config/environment/production.js
465
/// <reference path="../../server.d.ts" /> 'use strict'; module.exports = { ip: process.env.IP || undefined, server: { url: 'http://www.<%= appname %>.com' }<% if (filters.backend === 'mongo') { %>, mongo: { uri: 'mongodb://localhost/<%= slugName %>' }<% } %>, facebook: { clientID: '975041909195011', clientSecret: '6bcf8b64f80546cfd799a4f467cd1a20', callbackURL: '/auth/facebook/callback' } };
bsd-3-clause
nikolasco/project_euler
023.cpp
793
#include <iostream> #include <vector> using namespace std; typedef unsigned long long int ull; int main() { static const ull MAX = 28123; ull sum = 0; vector<ull> abu; vector<bool> is_abu(MAX+1); for(ull i = 1; i <= MAX; i++) { ull sum_d = 0; for(ull j = 1; j < i; j++) { if(0 == i%j) sum_d += j; } if(sum_d > i) { abu.push_back(i); is_abu[i] = true; } } for(ull i = 1; i < MAX; i++) { bool add = true; for(vector<ull>::const_iterator it = abu.begin(); it != abu.end(); it++) { if(*it <= i && is_abu[i-*it]) { add = false; break; } } if(add) sum += i; } cout << sum << endl; return 0; }
bsd-3-clause
VitaliyProdan/hr
backend/views/site/index.php
7390
<?php /* @var $this yii\web\View */ /* @var $lastPosts */ /* @var $featured */ /* @var $drafts */ use yii\helpers\Url; use yii\helpers\Html; $this->title = 'Головна'; ?> <div class="site-index"> <h1 class="by-center">Адмін панель</h1> <hr /> <div class="body-content"> <div class="row"> <div class="col-lg-3 col-md-6"> <div class="panel panel-primary"> <div class="panel-heading"> <div class="row row-panel"> <div class="col-xs-3"> <i class="glyphicon glyphicon-list-alt dashboard-glyp"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?= $postsCount ?></div> <div>Всього вакансій</div> </div> </div> </div> <a href="<?= Url::toRoute('post/index') ?>"> <div class="panel-footer"> <span class="pull-left">Переглянути</span> <span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> <div class="col-lg-3 col-md-6"> <div class="panel panel-green"> <div class="panel-green panel-heading"> <div class="row row-panel"> <div class="col-xs-3"> <i class="glyphicon glyphicon-bookmark dashboard-glyp"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?= $categoryCount ?></div> <div>Всього напрямків</div> </div> </div> </div> <a href="<?= Url::toRoute('category/index') ?>"> <div class="panel-footer"> <span class="pull-left">Переглянути</span> <span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> <div class="col-lg-3 col-md-6"> <div class="panel panel-yellow"> <div class="panel-yellow panel-heading"> <div class="row row-panel"> <div class="col-xs-3"> <i class="glyphicon glyphicon-circle-arrow-up dashboard-glyp"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?= $mostPopularCategory->qty ?></div> <div> Топ напрямок: <b><?= $mostPopularCategory->title ?></b></div> </div> </div> </div> <a href="<?= Url::toRoute(['./../posts/category', 'id' => $mostPopularCategory->id]) ?>"> <div class="panel-footer"> <span class="pull-left">Переглянути</span> <span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> <div class="col-lg-3 col-md-6"> <div class="panel panel-red"> <div class="panel-red panel-heading"> <div class="row row-panel"> <div class="col-xs-3"> <i class="glyphicon glyphicon-tags dashboard-glyp"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?= $mostPopularTag->qty ?></div> <div> Навички: <b><?= $mostPopularTag->title ?></b></div> </div> </div> </div> <a href="<?= Url::toRoute(['./../posts/tag', 'ids' => $mostPopularTag->id]) ?>"> <div class="panel-footer"> <span class="pull-left">Переглянути</span> <span class="pull-right"><i class="glyphicon glyphicon-circle-arrow-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> </div> <hr /> <div class="row"> <div class="col-lg-4"> <div class="panel panel-default"> <div class="panel-heading"> <?= Html::a('<h4><i class="glyphicon glyphicon-list-alt"></i> Останні вакансії</h4>', ['/post/index'])?> </div> <ul class="list-group"> <?php foreach($lastPosts as $post): ?> <li class="list-group-item"> <?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?> </li> <?php endforeach ?> </ul> </div> </div> <div class="col-lg-4"> <div class="panel panel-default"> <div class="panel-heading"> <?= Html::a('<h4><i class="glyphicon glyphicon-thumbs-up"></i> Термінові вакансії</h4>', ['/post/index'])?> </div> <ul class="list-group"> <?php foreach($featured as $post): ?> <li class="list-group-item"> <?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?> </li> <?php endforeach ?> </ul> </div> </div> <div class="col-lg-4"> <div class="panel panel-default"> <div class="panel-heading"> <?= Html::a('<h4><i class="glyphicon glyphicon-file"></i> Чернетки</h4>', ['/post/index'])?> </div> <ul class="list-group"> <?php foreach($drafts as $post): ?> <li class="list-group-item"> <?= Html::a($post->title , ['./../posts/view', 'id' => $post->id], ['target'=>'_blank'])?> </li> <?php endforeach ?> </ul> </div> </div> </div> </div> </div>
bsd-3-clause
hpdcj/PCJ
src/main/java/org/pcj/internal/message/scatter/ScatterStates.java
8076
/* * Copyright (c) 2011-2021, PCJ Library, Marek Nowicki * All rights reserved. * * Licensed under New BSD License (3-clause license). * * See the file "LICENSE" for the full license governing this code. */ package org.pcj.internal.message.scatter; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.pcj.PcjFuture; import org.pcj.PcjRuntimeException; import org.pcj.internal.InternalCommonGroup; import org.pcj.internal.InternalPCJ; import org.pcj.internal.InternalStorages; import org.pcj.internal.Networker; import org.pcj.internal.NodeData; import org.pcj.internal.PcjThread; import org.pcj.internal.message.Message; /** * @author Marek Nowicki ([email protected]) */ public class ScatterStates { private final AtomicInteger counter; private final ConcurrentMap<List<Integer>, State> stateMap; public ScatterStates() { counter = new AtomicInteger(0); stateMap = new ConcurrentHashMap<>(); } public State create(int threadId, InternalCommonGroup commonGroup) { int requestNum = counter.incrementAndGet(); NodeData nodeData = InternalPCJ.getNodeData(); ScatterFuture future = new ScatterFuture(); State state = new State(requestNum, threadId, commonGroup.getCommunicationTree().getChildrenNodes(nodeData.getCurrentNodePhysicalId()).size(), future); stateMap.put(Arrays.asList(requestNum, threadId), state); return state; } public State getOrCreate(int requestNum, int requesterThreadId, InternalCommonGroup commonGroup) { NodeData nodeData = InternalPCJ.getNodeData(); int requesterPhysicalId = nodeData.getPhysicalId(commonGroup.getGlobalThreadId(requesterThreadId)); return stateMap.computeIfAbsent(Arrays.asList(requestNum, requesterThreadId), key -> new State(requestNum, requesterThreadId, commonGroup.getCommunicationTree().getChildrenNodes(requesterPhysicalId).size())); } public State remove(int requestNum, int threadId) { return stateMap.remove(Arrays.asList(requestNum, threadId)); } public class State { private final int requestNum; private final int requesterThreadId; private final AtomicInteger notificationCount; private final ScatterFuture future; private final Queue<Exception> exceptions; private State(int requestNum, int requesterThreadId, int childrenCount, ScatterFuture future) { this.requestNum = requestNum; this.requesterThreadId = requesterThreadId; this.future = future; // notification from children and from itself notificationCount = new AtomicInteger(childrenCount + 1); exceptions = new ConcurrentLinkedQueue<>(); } private State(int requestNum, int requesterThreadId, int childrenCount) { this(requestNum, requesterThreadId, childrenCount, null); } public int getRequestNum() { return requestNum; } public PcjFuture<Void> getFuture() { return future; } void downProcessNode(InternalCommonGroup group, String sharedEnumClassName, String name, int[] indices, Map<Integer, Object> newValueMap) { NodeData nodeData = InternalPCJ.getNodeData(); Set<Integer> threadsId = group.getLocalThreadsId(); for (int threadId : threadsId) { if (!newValueMap.containsKey(threadId)) { continue; } int globalThreadId = group.getGlobalThreadId(threadId); PcjThread pcjThread = nodeData.getPcjThread(globalThreadId); InternalStorages storage = pcjThread.getThreadData().getStorages(); try { Object newValue = newValueMap.remove(threadId); storage.put(newValue, sharedEnumClassName, name, indices); } catch (Exception ex) { exceptions.add(ex); } } Networker networker = InternalPCJ.getNetworker(); int requesterPhysicalId = nodeData.getPhysicalId(group.getGlobalThreadId(requesterThreadId)); Set<Integer> childrenNodes = group.getCommunicationTree().getChildrenNodes(requesterPhysicalId); Map<Integer, Integer> groupIdToGlobalIdMap = group.getThreadsMap(); for (int childrenNode : childrenNodes) { List<Integer> subTree = group.getCommunicationTree().getSubtree(requesterPhysicalId, childrenNode); Map<Integer, Object> subTreeNewValueMap = groupIdToGlobalIdMap.entrySet() .stream() .filter(entry -> subTree.contains(nodeData.getPhysicalId(entry.getValue()))) .map(Map.Entry::getKey) .filter(newValueMap::containsKey) .collect(HashMap::new, (map, key) -> map.put(key, newValueMap.get(key)), HashMap::putAll); ScatterRequestMessage message = new ScatterRequestMessage( group.getGroupId(), requestNum, requesterThreadId, sharedEnumClassName, name, indices, subTreeNewValueMap); SocketChannel socket = nodeData.getSocketChannelByPhysicalId(childrenNode); networker.send(socket, message); } nodeProcessed(group); } void upProcessNode(InternalCommonGroup group, Queue<Exception> messageExceptions) { if ((messageExceptions != null) && (!messageExceptions.isEmpty())) { exceptions.addAll(messageExceptions); } nodeProcessed(group); } private void nodeProcessed(InternalCommonGroup group) { int leftPhysical = notificationCount.decrementAndGet(); NodeData nodeData = InternalPCJ.getNodeData(); if (leftPhysical == 0) { int requesterPhysicalId = nodeData.getPhysicalId(group.getGlobalThreadId(requesterThreadId)); if (requesterPhysicalId != nodeData.getCurrentNodePhysicalId()) { // requester will receive response ScatterStates.this.remove(requestNum, requesterThreadId); } int parentId = group.getCommunicationTree().getParentNode(requesterPhysicalId); if (parentId >= 0) { Message message = new ScatterResponseMessage(group.getGroupId(), requestNum, requesterThreadId, exceptions); SocketChannel socket = nodeData.getSocketChannelByPhysicalId(parentId); InternalPCJ.getNetworker().send(socket, message); } else { ScatterStates.State state = ScatterStates.this.remove(requestNum, requesterThreadId); state.signal(exceptions); } } } public void signal(Queue<Exception> messageExceptions) { if ((messageExceptions != null) && (!messageExceptions.isEmpty())) { PcjRuntimeException ex = new PcjRuntimeException("Scatter value array failed", messageExceptions.poll()); messageExceptions.forEach(ex::addSuppressed); future.signalException(ex); } else { future.signalDone(); } } protected void addException(Exception ex) { exceptions.add(ex); } } }
bsd-3-clause
michaelbausor/gax-php
src/Page.php
9056
<?php /* * Copyright 2016 Google LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Google\ApiCore; use Generator; use Google\Protobuf\Internal\Message; use IteratorAggregate; /** * A Page object wraps an API list method response and provides methods * to retrieve additional pages using the page token. */ class Page implements IteratorAggregate { const FINAL_PAGE_TOKEN = ""; private $call; private $callable; private $options; private $pageStreamingDescriptor; private $pageToken; private $response; /** * Page constructor. * * @param Call $call * @param array $options * @param callable $callable * @param PageStreamingDescriptor $pageStreamingDescriptor * @param Message $response */ public function __construct( Call $call, array $options, callable $callable, PageStreamingDescriptor $pageStreamingDescriptor, Message $response ) { $this->call = $call; $this->options = $options; $this->callable = $callable; $this->pageStreamingDescriptor = $pageStreamingDescriptor; $this->response = $response; $requestPageTokenGetMethod = $this->pageStreamingDescriptor->getRequestPageTokenGetMethod(); $this->pageToken = $this->call->getMessage()->$requestPageTokenGetMethod(); } /** * Returns true if there are more pages that can be retrieved from the * API. * * @return bool */ public function hasNextPage() { return strcmp($this->getNextPageToken(), Page::FINAL_PAGE_TOKEN) != 0; } /** * Returns the next page token from the response. * * @return string */ public function getNextPageToken() { $responsePageTokenGetMethod = $this->pageStreamingDescriptor->getResponsePageTokenGetMethod(); return $this->getResponseObject()->$responsePageTokenGetMethod(); } /** * Retrieves the next Page object using the next page token. * * @param int|null $pageSize * @throws ValidationException if there are no pages remaining, or if pageSize is supplied but * is not supported by the API * @throws ApiException if the call to fetch the next page fails. * @return Page */ public function getNextPage($pageSize = null) { if (!$this->hasNextPage()) { throw new ValidationException( 'Could not complete getNextPage operation: ' . 'there are no more pages to retrieve.' ); } $newRequest = clone $this->getRequestObject(); $requestPageTokenSetMethod = $this->pageStreamingDescriptor->getRequestPageTokenSetMethod(); $newRequest->$requestPageTokenSetMethod($this->getNextPageToken()); if (isset($pageSize)) { if (!$this->pageStreamingDescriptor->requestHasPageSizeField()) { throw new ValidationException( 'pageSize argument was defined, but the method does not ' . 'support a page size parameter in the optional array argument' ); } $requestPageSizeSetMethod = $this->pageStreamingDescriptor->getRequestPageSizeSetMethod(); $newRequest->$requestPageSizeSetMethod($pageSize); } $this->call = $this->call->withMessage($newRequest); $callable = $this->callable; $response = $callable( $this->call, $this->options )->wait(); return new Page( $this->call, $this->options, $this->callable, $this->pageStreamingDescriptor, $response ); } /** * Return the number of elements in the response. * * @return int */ public function getPageElementCount() { $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod(); return count($this->getResponseObject()->$resourcesGetMethod()); } /** * Return an iterator over the elements in the response. * * @return Generator */ public function getIterator() { $resourcesGetMethod = $this->pageStreamingDescriptor->getResourcesGetMethod(); foreach ($this->getResponseObject()->$resourcesGetMethod() as $element) { yield $element; } } /** * Return an iterator over Page objects, beginning with this object. * Additional Page objects are retrieved lazily via API calls until * all elements have been retrieved. * * @return Generator|Page[] * @throws ValidationException * @throws ApiException */ public function iteratePages() { $currentPage = $this; yield $this; while ($currentPage->hasNextPage()) { $currentPage = $currentPage->getNextPage(); yield $currentPage; } } /** * Gets the request object used to generate the Page. * * @return mixed|Message */ public function getRequestObject() { return $this->call->getMessage(); } /** * Gets the API response object. * * @return mixed|Message */ public function getResponseObject() { return $this->response; } /** * Returns a collection of elements with a fixed size set by * the collectionSize parameter. The collection will only contain * fewer than collectionSize elements if there are no more * pages to be retrieved from the server. * * NOTE: it is an error to call this method if an optional parameter * to set the page size is not supported or has not been set in the * API call that was used to create this page. It is also an error * if the collectionSize parameter is less than the page size that * has been set. * * @param $collectionSize int * @throws ValidationException if a FixedSizeCollection of the specified size cannot be constructed * @return FixedSizeCollection */ public function expandToFixedSizeCollection($collectionSize) { if (!$this->pageStreamingDescriptor->requestHasPageSizeField()) { throw new ValidationException( "FixedSizeCollection is not supported for this method, because " . "the method does not support an optional argument to set the " . "page size." ); } $request = $this->getRequestObject(); $pageSizeGetMethod = $this->pageStreamingDescriptor->getRequestPageSizeGetMethod(); $pageSize = $request->$pageSizeGetMethod(); if (is_null($pageSize)) { throw new ValidationException( "Error while expanding Page to FixedSizeCollection: No page size " . "parameter found. The page size parameter must be set in the API " . "optional arguments array, and must be less than the collectionSize " . "parameter, in order to create a FixedSizeCollection object." ); } if ($pageSize > $collectionSize) { throw new ValidationException( "Error while expanding Page to FixedSizeCollection: collectionSize " . "parameter is less than the page size optional argument specified in " . "the API call. collectionSize: $collectionSize, page size: $pageSize" ); } return new FixedSizeCollection($this, $collectionSize); } }
bsd-3-clause
aliclark/libquic
src/quux/server/chlo_extractor.cc
5344
// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quux/server/chlo_extractor.h" #include "net/quic/crypto/crypto_framer.h" #include "net/quic/crypto/crypto_handshake_message.h" #include "net/quic/crypto/crypto_protocol.h" #include "net/quic/crypto/quic_decrypter.h" #include "net/quic/crypto/quic_encrypter.h" #include "net/quic/quic_framer.h" using base::StringPiece; namespace net { namespace { class ChloFramerVisitor : public QuicFramerVisitorInterface, public CryptoFramerVisitorInterface { public: ChloFramerVisitor(QuicFramer* framer, ChloExtractor::Delegate* delegate); ~ChloFramerVisitor() override {} // QuicFramerVisitorInterface implementation void OnError(QuicFramer* framer) override {} bool OnProtocolVersionMismatch(QuicVersion version) override; void OnPacket() override {} void OnPublicResetPacket(const QuicPublicResetPacket& packet) override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) override {} bool OnUnauthenticatedPublicHeader( const QuicPacketPublicHeader& header) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; void OnDecryptedPacket(EncryptionLevel level) override {} bool OnPacketHeader(const QuicPacketHeader& header) override; bool OnStreamFrame(const QuicStreamFrame& frame) override; bool OnAckFrame(const QuicAckFrame& frame) override; bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; bool OnPingFrame(const QuicPingFrame& frame) override; bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; bool OnBlockedFrame(const QuicBlockedFrame& frame) override; bool OnPathCloseFrame(const QuicPathCloseFrame& frame) override; bool OnPaddingFrame(const QuicPaddingFrame& frame) override; void OnPacketComplete() override {} // CryptoFramerVisitorInterface implementation. void OnError(CryptoFramer* framer) override; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override; bool found_chlo() { return found_chlo_; } private: QuicFramer* framer_; ChloExtractor::Delegate* delegate_; bool found_chlo_; QuicConnectionId connection_id_; }; ChloFramerVisitor::ChloFramerVisitor(QuicFramer* framer, ChloExtractor::Delegate* delegate) : framer_(framer), delegate_(delegate), found_chlo_(false), connection_id_(0) {} bool ChloFramerVisitor::OnProtocolVersionMismatch(QuicVersion version) { if (!framer_->IsSupportedVersion(version)) { return false; } framer_->set_version(version); return true; } bool ChloFramerVisitor::OnUnauthenticatedPublicHeader( const QuicPacketPublicHeader& header) { connection_id_ = header.connection_id; return true; } bool ChloFramerVisitor::OnUnauthenticatedHeader( const QuicPacketHeader& header) { return true; } bool ChloFramerVisitor::OnPacketHeader(const QuicPacketHeader& header) { return true; } bool ChloFramerVisitor::OnStreamFrame(const QuicStreamFrame& frame) { StringPiece data(frame.data_buffer, frame.data_length); if (frame.stream_id == kCryptoStreamId && frame.offset == 0 && data.starts_with("CHLO")) { CryptoFramer crypto_framer; crypto_framer.set_visitor(this); if (!crypto_framer.ProcessInput(data)) { return false; } } return true; } bool ChloFramerVisitor::OnAckFrame(const QuicAckFrame& frame) { return true; } bool ChloFramerVisitor::OnStopWaitingFrame(const QuicStopWaitingFrame& frame) { return true; } bool ChloFramerVisitor::OnPingFrame(const QuicPingFrame& frame) { return true; } bool ChloFramerVisitor::OnRstStreamFrame(const QuicRstStreamFrame& frame) { return true; } bool ChloFramerVisitor::OnConnectionCloseFrame( const QuicConnectionCloseFrame& frame) { return true; } bool ChloFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& frame) { return true; } bool ChloFramerVisitor::OnWindowUpdateFrame( const QuicWindowUpdateFrame& frame) { return true; } bool ChloFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& frame) { return true; } bool ChloFramerVisitor::OnPathCloseFrame(const QuicPathCloseFrame& frame) { return true; } bool ChloFramerVisitor::OnPaddingFrame(const QuicPaddingFrame& frame) { return true; } void ChloFramerVisitor::OnError(CryptoFramer* framer) {} void ChloFramerVisitor::OnHandshakeMessage( const CryptoHandshakeMessage& message) { delegate_->OnChlo(framer_->version(), connection_id_, message); found_chlo_ = true; } } // namespace // static bool ChloExtractor::Extract(const QuicEncryptedPacket& packet, const QuicVersionVector& versions, Delegate* delegate) { QuicFramer framer(versions, QuicTime::Zero(), Perspective::IS_SERVER); ChloFramerVisitor visitor(&framer, delegate); framer.set_visitor(&visitor); if (!framer.ProcessPacket(packet)) { return false; } return visitor.found_chlo(); } } // namespace net
bsd-3-clause
cezarsa/tsuru
provision/pool/pool_test.go
19932
// Copyright 2015 tsuru authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pool import ( "sort" "testing" "github.com/tsuru/config" "github.com/tsuru/tsuru/auth" "github.com/tsuru/tsuru/db" "github.com/tsuru/tsuru/db/dbtest" tsuruErrors "github.com/tsuru/tsuru/errors" "github.com/tsuru/tsuru/router" "github.com/tsuru/tsuru/service" _ "github.com/tsuru/tsuru/storage/mongodb" "gopkg.in/check.v1" "gopkg.in/mgo.v2/bson" ) func Test(t *testing.T) { check.TestingT(t) } type S struct { storage *db.Storage } var _ = check.Suite(&S{}) func (s *S) SetUpSuite(c *check.C) { config.Set("log:disable-syslog", true) config.Set("database:driver", "mongodb") config.Set("database:url", "127.0.0.1:27017") config.Set("database:name", "pool_tests_s") var err error s.storage, err = db.Conn() c.Assert(err, check.IsNil) } func (s *S) TearDownSuite(c *check.C) { s.storage.Apps().Database.DropDatabase() s.storage.Close() } func (s *S) SetUpTest(c *check.C) { err := dbtest.ClearAllCollections(s.storage.Apps().Database) c.Assert(err, check.IsNil) err = auth.CreateTeam("ateam", &auth.User{}) c.Assert(err, check.IsNil) err = auth.CreateTeam("test", &auth.User{}) c.Assert(err, check.IsNil) err = auth.CreateTeam("pteam", &auth.User{}) c.Assert(err, check.IsNil) } func (s *S) TestAddPool(c *check.C) { msg := "Invalid pool name, pool name should have at most 63 " + "characters, containing only lower case letters, numbers or dashes, " + "starting with a letter." vErr := &tsuruErrors.ValidationError{Message: msg} tt := []struct { name string expectedErr error }{ {"pool1", nil}, {"myPool", vErr}, {"my pool", vErr}, {"123mypool", vErr}, {"", ErrPoolNameIsRequired}, {"p", nil}, } for _, t := range tt { err := AddPool(AddPoolOptions{Name: t.name}) c.Assert(err, check.DeepEquals, t.expectedErr, check.Commentf("%s", t.name)) if t.expectedErr == nil { pool, err := GetPoolByName(t.name) c.Assert(err, check.IsNil, check.Commentf("%s", t.name)) c.Assert(pool, check.DeepEquals, &Pool{Name: t.name}, check.Commentf("%s", t.name)) } } } func (s *S) TestAddNonPublicPool(c *check.C) { coll := s.storage.Pools() opts := AddPoolOptions{ Name: "pool1", Public: false, Default: false, } err := AddPool(opts) c.Assert(err, check.IsNil) var p Pool err = coll.Find(bson.M{"_id": "pool1"}).One(&p) c.Assert(err, check.IsNil) constraints, err := getConstraintsForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraints["team"].AllowsAll(), check.Equals, false) } func (s *S) TestAddPublicPool(c *check.C) { coll := s.storage.Pools() opts := AddPoolOptions{ Name: "pool1", Public: true, Default: false, } err := AddPool(opts) c.Assert(err, check.IsNil) var p Pool err = coll.Find(bson.M{"_id": "pool1"}).One(&p) c.Assert(err, check.IsNil) constraints, err := getConstraintsForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraints["team"].AllowsAll(), check.Equals, true) } func (s *S) TestAddPoolWithoutNameShouldBreak(c *check.C) { opts := AddPoolOptions{ Name: "", Public: false, Default: false, } err := AddPool(opts) c.Assert(err, check.NotNil) c.Assert(err.Error(), check.Equals, "Pool name is required.") } func (s *S) TestAddDefaultPool(c *check.C) { opts := AddPoolOptions{ Name: "pool1", Public: false, Default: true, } err := AddPool(opts) c.Assert(err, check.IsNil) } func (s *S) TestAddTeamToPoolNotFound(c *check.C) { err := AddTeamsToPool("notfound", []string{"ateam"}) c.Assert(err, check.Equals, ErrPoolNotFound) } func (s *S) TestDefaultPoolCantHaveTeam(c *check.C) { err := AddPool(AddPoolOptions{Name: "nonteams", Public: false, Default: true}) c.Assert(err, check.IsNil) err = AddTeamsToPool("nonteams", []string{"ateam"}) c.Assert(err, check.NotNil) c.Assert(err, check.Equals, ErrPublicDefaultPoolCantHaveTeams) } func (s *S) TestDefaultPoolShouldBeUnique(c *check.C) { err := AddPool(AddPoolOptions{Name: "nonteams", Public: false, Default: true}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true}) c.Assert(err, check.NotNil) } func (s *S) TestAddPoolNameShouldBeUnique(c *check.C) { err := AddPool(AddPoolOptions{Name: "mypool"}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "mypool"}) c.Assert(err, check.DeepEquals, ErrPoolAlreadyExists) } func (s *S) TestForceAddDefaultPool(c *check.C) { coll := s.storage.Pools() opts := AddPoolOptions{ Name: "pool1", Public: false, Default: true, } err := AddPool(opts) c.Assert(err, check.IsNil) opts = AddPoolOptions{ Name: "pool2", Public: false, Default: true, Force: true, } err = AddPool(opts) c.Assert(err, check.IsNil) var p Pool err = coll.Find(bson.M{"_id": "pool1"}).One(&p) c.Assert(err, check.IsNil) c.Assert(p.Default, check.Equals, false) err = coll.Find(bson.M{"_id": "pool2"}).One(&p) c.Assert(err, check.IsNil) c.Assert(p.Default, check.Equals, true) } func (s *S) TestRemovePoolNotFound(c *check.C) { err := RemovePool("notfound") c.Assert(err, check.Equals, ErrPoolNotFound) } func (s *S) TestRemovePool(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = RemovePool("pool1") c.Assert(err, check.IsNil) p, err := coll.FindId("pool1").Count() c.Assert(err, check.IsNil) c.Assert(p, check.Equals, 0) } func (s *S) TestAddTeamToPool(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = AddTeamsToPool("pool1", []string{"ateam", "test"}) c.Assert(err, check.IsNil) var p Pool err = coll.FindId(pool.Name).One(&p) c.Assert(err, check.IsNil) teams, err := p.GetTeams() c.Assert(err, check.IsNil) sort.Strings(teams) c.Assert(teams, check.DeepEquals, []string{"ateam", "test"}) } func (s *S) TestAddTeamToPoolWithTeams(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = AddTeamsToPool(pool.Name, []string{"test", "ateam"}) c.Assert(err, check.IsNil) err = AddTeamsToPool(pool.Name, []string{"pteam"}) c.Assert(err, check.IsNil) teams, err := pool.GetTeams() c.Assert(err, check.IsNil) sort.Strings(teams) c.Assert(teams, check.DeepEquals, []string{"ateam", "pteam", "test"}) } func (s *S) TestAddTeamToPollShouldNotAcceptDuplicatedTeam(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = AddTeamsToPool(pool.Name, []string{"test", "ateam"}) c.Assert(err, check.IsNil) err = AddTeamsToPool(pool.Name, []string{"ateam"}) c.Assert(err, check.NotNil) teams, err := pool.GetTeams() c.Assert(err, check.IsNil) sort.Strings(teams) c.Assert(teams, check.DeepEquals, []string{"ateam", "test"}) } func (s *S) TestAddTeamsToAPublicPool(c *check.C) { err := AddPool(AddPoolOptions{Name: "nonteams", Public: true}) c.Assert(err, check.IsNil) err = AddTeamsToPool("nonteams", []string{"ateam"}) c.Assert(err, check.NotNil) c.Assert(err, check.Equals, ErrPublicDefaultPoolCantHaveTeams) } func (s *S) TestAddTeamsToPoolWithBlacklistShouldFail(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"myteam"}, Blacklist: true}) c.Assert(err, check.IsNil) err = AddTeamsToPool("pool1", []string{"otherteam"}) c.Assert(err, check.NotNil) constraint, err := getExactConstraintForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraint.Blacklist, check.Equals, true) c.Assert(constraint.Values, check.DeepEquals, []string{"myteam"}) } func (s *S) TestRemoveTeamsFromPoolNotFound(c *check.C) { err := RemoveTeamsFromPool("notfound", []string{"test"}) c.Assert(err, check.Equals, ErrPoolNotFound) } func (s *S) TestRemoveTeamsFromPool(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = AddTeamsToPool(pool.Name, []string{"test", "ateam"}) c.Assert(err, check.IsNil) teams, err := pool.GetTeams() c.Assert(err, check.IsNil) sort.Strings(teams) c.Assert(teams, check.DeepEquals, []string{"ateam", "test"}) err = RemoveTeamsFromPool(pool.Name, []string{"test"}) c.Assert(err, check.IsNil) teams, err = pool.GetTeams() c.Assert(err, check.IsNil) c.Assert(teams, check.DeepEquals, []string{"ateam"}) } func (s *S) TestRemoveTeamsFromPoolWithBlacklistShouldFail(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1"} err := coll.Insert(pool) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"myteam"}, Blacklist: true}) c.Assert(err, check.IsNil) err = RemoveTeamsFromPool("pool1", []string{"myteam"}) c.Assert(err, check.NotNil) constraint, err := getExactConstraintForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraint.Blacklist, check.Equals, true) c.Assert(constraint.Values, check.DeepEquals, []string{"myteam"}) } func boolPtr(v bool) *bool { return &v } func (s *S) TestPoolUpdateNotFound(c *check.C) { err := PoolUpdate("notfound", UpdatePoolOptions{Public: boolPtr(true)}) c.Assert(err, check.Equals, ErrPoolNotFound) } func (s *S) TestPoolUpdate(c *check.C) { opts := AddPoolOptions{ Name: "pool1", Public: false, } err := AddPool(opts) c.Assert(err, check.IsNil) err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true)}) c.Assert(err, check.IsNil) constraint, err := getExactConstraintForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraint.AllowsAll(), check.Equals, true) } func (s *S) TestPoolUpdateToDefault(c *check.C) { opts := AddPoolOptions{ Name: "pool1", Public: false, Default: false, } err := AddPool(opts) c.Assert(err, check.IsNil) err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true)}) c.Assert(err, check.IsNil) p, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) c.Assert(p.Default, check.Equals, true) } func (s *S) TestPoolUpdateForceToDefault(c *check.C) { err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool2", Public: false, Default: false}) c.Assert(err, check.IsNil) err = PoolUpdate("pool2", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true), Force: true}) c.Assert(err, check.IsNil) p, err := GetPoolByName("pool2") c.Assert(err, check.IsNil) c.Assert(p.Default, check.Equals, true) } func (s *S) TestPoolUpdateDefaultAttrFailIfDefaultPoolAlreadyExists(c *check.C) { err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool2", Public: false, Default: false}) c.Assert(err, check.IsNil) err = PoolUpdate("pool2", UpdatePoolOptions{Public: boolPtr(true), Default: boolPtr(true)}) c.Assert(err, check.NotNil) c.Assert(err, check.Equals, ErrDefaultPoolAlreadyExists) } func (s *S) TestPoolUpdateDontHaveSideEffects(c *check.C) { err := AddPool(AddPoolOptions{Name: "pool1", Public: false, Default: true}) c.Assert(err, check.IsNil) err = PoolUpdate("pool1", UpdatePoolOptions{Public: boolPtr(true)}) c.Assert(err, check.IsNil) p, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) c.Assert(p.Default, check.Equals, true) constraint, err := getExactConstraintForPool("pool1", "team") c.Assert(err, check.IsNil) c.Assert(constraint.AllowsAll(), check.Equals, true) } func (s *S) TestListPool(c *check.C) { err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool2", Default: true}) c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool3"}) c.Assert(err, check.IsNil) pools, err := ListPools("pool1", "pool3") c.Assert(err, check.IsNil) c.Assert(len(pools), check.Equals, 2) c.Assert(pools[0].Name, check.Equals, "pool1") c.Assert(pools[1].Name, check.Equals, "pool3") } func (s *S) TestListPossiblePoolsAll(c *check.C) { err := AddPool(AddPoolOptions{Name: "pool1", Default: true}) c.Assert(err, check.IsNil) pools, err := ListPossiblePools(nil) c.Assert(err, check.IsNil) c.Assert(pools, check.HasLen, 1) } func (s *S) TestListPoolByQuery(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1", Default: true} err := coll.Insert(pool) c.Assert(err, check.IsNil) pool2 := Pool{Name: "pool2", Default: true} err = coll.Insert(pool2) c.Assert(err, check.IsNil) pools, err := listPools(bson.M{"_id": "pool2"}) c.Assert(err, check.IsNil) c.Assert(pools, check.HasLen, 1) c.Assert(pools[0].Name, check.Equals, "pool2") } func (s *S) TestListPoolEmpty(c *check.C) { pools, err := ListPossiblePools(nil) c.Assert(err, check.IsNil) c.Assert(pools, check.HasLen, 0) } func (s *S) TestGetPoolByName(c *check.C) { coll := s.storage.Pools() pool := Pool{Name: "pool1", Default: true} err := coll.Insert(pool) c.Assert(err, check.IsNil) p, err := GetPoolByName(pool.Name) c.Assert(err, check.IsNil) c.Assert(p.Name, check.Equals, pool.Name) p, err = GetPoolByName("not found") c.Assert(p, check.IsNil) c.Assert(err, check.NotNil) } func (s *S) TestGetRouters(c *check.C) { config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: true}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) routers, err := pool.GetRouters() c.Assert(err, check.IsNil) c.Assert(routers, check.DeepEquals, []string{"router1"}) pool.Name = "other" routers, err = pool.GetRouters() c.Assert(err, check.IsNil) c.Assert(routers, check.DeepEquals, []string{"router1", "router2"}) } func (s *S) TestGetServices(c *check.C) { serv := service.Service{Name: "demacia", Password: "pentakill", Endpoint: map[string]string{"production": "http://localhost:1234"}, OwnerTeams: []string{"ateam"}} err := serv.Create() c.Assert(err, check.IsNil) err = AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) services, err := pool.GetServices() c.Assert(err, check.IsNil) c.Assert(services, check.DeepEquals, []string{"demacia"}) } func (s *S) TestGetDefaultRouterFromConstraint(c *check.C) { config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: false}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) r, err := pool.GetDefaultRouter() c.Assert(err, check.IsNil) c.Assert(r, check.Equals, "router2") } func (s *S) TestGetDefaultRouterNoDefault(c *check.C) { config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"*"}, Blacklist: false}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) r, err := pool.GetDefaultRouter() c.Assert(err, check.Equals, router.ErrDefaultRouterNotFound) c.Assert(r, check.Equals, "") } func (s *S) TestGetDefaultFallbackFromConfig(c *check.C) { config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") config.Set("routers:router2:default", true) defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) r, err := pool.GetDefaultRouter() c.Assert(err, check.Equals, nil) c.Assert(r, check.Equals, "router2") } func (s *S) TestGetDefaultAllowAllSingleAllowedValue(c *check.C) { config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router*"}, Blacklist: false}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) r, err := pool.GetDefaultRouter() c.Assert(err, check.IsNil) c.Assert(r, check.Equals, "router2") } func (s *S) TestGetDefaultBlacklistSingleAllowedValue(c *check.C) { config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := AddPool(AddPoolOptions{Name: "pool1"}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router2"}, Blacklist: true}) c.Assert(err, check.IsNil) pool, err := GetPoolByName("pool1") c.Assert(err, check.IsNil) r, err := pool.GetDefaultRouter() c.Assert(err, check.IsNil) c.Assert(r, check.Equals, "router1") } func (s *S) TestPoolAllowedValues(c *check.C) { config.Set("routers:router:type", "hipache") config.Set("routers:router1:type", "hipache") config.Set("routers:router2:type", "hipache") defer config.Unset("routers") err := auth.CreateTeam("pubteam", &auth.User{}) c.Assert(err, check.IsNil) err = auth.CreateTeam("team1", &auth.User{}) c.Assert(err, check.IsNil) coll := s.storage.Pools() pool := Pool{Name: "pool1"} err = coll.Insert(pool) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "team", Values: []string{"pubteam"}}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool*", Field: "router", Values: []string{"router"}, Blacklist: true}) c.Assert(err, check.IsNil) err = SetPoolConstraint(&PoolConstraint{PoolExpr: "pool1", Field: "team", Values: []string{"team1"}}) c.Assert(err, check.IsNil) constraints, err := pool.allowedValues() c.Assert(err, check.IsNil) c.Assert(constraints, check.DeepEquals, map[string][]string{ "team": {"team1"}, "router": {"router1", "router2"}, "service": nil, }) pool.Name = "other" constraints, err = pool.allowedValues() c.Assert(err, check.IsNil) c.Assert(constraints, check.HasLen, 3) sort.Strings(constraints["team"]) c.Assert(constraints["team"], check.DeepEquals, []string{ "ateam", "pteam", "pubteam", "team1", "test", }) sort.Strings(constraints["router"]) c.Assert(constraints["router"], check.DeepEquals, []string{ "router", "router1", "router2", }) } func (s *S) TestRenamePoolTeam(c *check.C) { coll := s.storage.PoolsConstraints() constraints := []PoolConstraint{ {PoolExpr: "e1", Field: "router", Values: []string{"t1", "t2"}}, {PoolExpr: "e2", Field: "team", Values: []string{"t1", "t2"}}, {PoolExpr: "e3", Field: "team", Values: []string{"t2", "t3"}}, } for _, constraint := range constraints { err := SetPoolConstraint(&constraint) c.Assert(err, check.IsNil) } err := RenamePoolTeam("t2", "t9000") c.Assert(err, check.IsNil) var cs []PoolConstraint err = coll.Find(nil).Sort("poolexpr").All(&cs) c.Assert(err, check.IsNil) c.Assert(cs, check.DeepEquals, []PoolConstraint{ {PoolExpr: "e1", Field: "router", Values: []string{"t1", "t2"}}, {PoolExpr: "e2", Field: "team", Values: []string{"t1", "t9000"}}, {PoolExpr: "e3", Field: "team", Values: []string{"t3", "t9000"}}, }) }
bsd-3-clause
mtitinger/phabos
apps/svc/tsb_switch_es1.c
16306
/* * Copyright (c) 2015 Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author: Perry Hung */ #define DBG_COMP DBG_SWITCH #include <phabos/i2c.h> #include <asm/byteordering.h> #include <errno.h> #include <string.h> #include <sys/ioctl.h> #include "up_debug.h" #include "tsb_switch.h" #include "tsb_switch_driver_es1.h" #define ES1_I2C_ADDR (0x44) #define ES1_I2C_FREQUENCY (400000) #define CHECK_VALID_ENTRY(entry) \ (valid_bitmask[15 - ((entry) / 8)] & (1 << ((entry)) % 8)) static int es1_transfer(struct tsb_switch *sw, uint8_t *tx_buf, size_t tx_size, uint8_t *rx_buf, size_t rx_size) { int i2c_fd = (int) sw->priv; int rc; dbg_insane("\t%s(): TX buffer:\n", __func__); dbg_print_buf(DBG_INSANE, tx_buf, tx_size); struct i2c_msg msgs[] = { { .addr = ES1_I2C_ADDR, .flags = 0, .buffer = tx_buf, .length = tx_size, }, { .addr = ES1_I2C_ADDR, .flags = I2C_M_READ, .buffer = rx_buf, .length = rx_size, } }; rc = ioctl(i2c_fd, I2C_TRANSFER, msgs, 2); dbg_insane("\t%s(): RX buffer:\n", __func__); dbg_print_buf(DBG_INSANE, rx_buf, rx_size); if (rc < 0) { dbg_error("%s(): error %d\n", __func__, rc); return rc; } return 0; } static int es1_dev_id_mask_get(struct tsb_switch *sw, uint8_t unipro_portid, uint8_t *dst) { int rc; uint8_t getreq[] = { SWITCH_DEVICE_ID, NCP_RESERVED, NCP_GETDEVICEIDMASKREQ }; struct __attribute__ ((__packed__)) getcnf { uint8_t rc; uint8_t fid; uint8_t mask[16]; } getcnf; rc = es1_transfer(sw, getreq, sizeof(getreq), (uint8_t*)&getcnf, sizeof(getcnf)); if (rc) { return rc; } if (getcnf.fid != NCP_GETDEVICEIDMASKCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return getcnf.rc; } memcpy(dst, &getcnf.mask, sizeof(getcnf.mask)); dbg_verbose("%s(): device_id_mask[]:\n", __func__); dbg_print_buf(DBG_VERBOSE, dst, sizeof(getcnf.mask)); return 0; } static int es1_set(struct tsb_switch *sw, uint8_t portid, uint16_t attrid, uint16_t select_index, uint32_t attr_value) { uint8_t setreq[] = { SWITCH_DEVICE_ID, portid, NCP_SETREQ, (attrid >> 8), (attrid & 0xff), (select_index >> 8), (select_index & 0xff), ((attr_value >> 24) & 0xff), ((attr_value >> 16) & 0xff), ((attr_value >> 8) & 0xff), (attr_value & 0xff) }; struct __attribute__ ((__packed__)) setcnf { uint8_t portid; uint8_t fid; uint8_t reserved; uint8_t rc; } setcnf; int rc; rc = es1_transfer(sw, setreq, sizeof(setreq), (uint8_t*)&setcnf, sizeof(setcnf)); if (rc) { return rc; } if (setcnf.fid != NCP_SETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return setcnf.rc; } dbg_verbose("%s(): portid=%u, (attr,sel)=(0x%04x,%d)=0x%04x, ret=0x%02x\n", __func__, portid, attrid, select_index, attr_value, setcnf.rc); return setcnf.rc; } static int es1_get(struct tsb_switch *sw, uint8_t portid, uint16_t attrid, uint16_t select_index, uint32_t *attr_value) { int rc; uint8_t getreq[] = { SWITCH_DEVICE_ID, portid, NCP_GETREQ, (attrid >> 8), (attrid & 0xff), (select_index >> 8), (select_index & 0xff), }; struct __attribute__ ((__packed__)) getcnf { uint8_t portid; uint8_t fid; uint8_t reserved; uint8_t rc; uint32_t attr_val; } getcnf; rc = es1_transfer(sw, getreq, sizeof(getreq), (uint8_t*)&getcnf, sizeof(getcnf)); if (rc) { return rc; } if (getcnf.fid != NCP_GETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return getcnf.rc; } *attr_value = be32_to_cpu(getcnf.attr_val); dbg_verbose("%s(): portid=%u, (attr,sel)=(0x%04x,%d)=0x%04x, ret=0x%02x\n", __func__, portid, attrid, select_index, *attr_value, getcnf.rc); return getcnf.rc; } static int es1_peer_set(struct tsb_switch *sw, uint8_t portid, uint16_t attrid, uint16_t select_index, uint32_t attr_value) { uint8_t setreq[] = { SWITCH_DEVICE_ID, portid, NCP_PEERSETREQ, (attrid >> 8), (attrid & 0xff), (select_index >> 8), (select_index & 0xff), ((attr_value >> 24) & 0xff), ((attr_value >> 16) & 0xff), ((attr_value >> 8) & 0xff), (attr_value & 0xff) }; struct __attribute__ ((__packed__)) peer_setcnf { uint8_t portid; uint8_t fid; uint8_t reserved; uint8_t rc; } setcnf; int rc; rc = es1_transfer(sw, setreq, sizeof(setreq), (uint8_t*)&setcnf, sizeof(setcnf)); if (rc) { return rc; } if (setcnf.fid != NCP_PEERSETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return setcnf.rc; } dbg_verbose("%s(): portid=%u, (attr,sel)=(0x%04x,%d)=0x%04x, ret=0x%02x\n", __func__, portid, attrid, select_index, attr_value, setcnf.rc); return setcnf.rc; } static int es1_peer_get(struct tsb_switch *sw, uint8_t portid, uint16_t attrid, uint16_t select_index, uint32_t *attr_value) { int rc; uint8_t getreq[] = { SWITCH_DEVICE_ID, portid, NCP_PEERGETREQ, (attrid >> 8), (attrid & 0xff), (select_index >> 8), (select_index & 0xff), }; struct __attribute__ ((__packed__)) getcnf { uint8_t portid; uint8_t fid; uint8_t reserved; uint8_t rc; uint32_t attr_val; } getcnf; rc = es1_transfer(sw, getreq, sizeof(getreq), (uint8_t*)&getcnf, sizeof(getcnf)); if (rc) { return rc; } if (getcnf.fid != NCP_PEERGETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return getcnf.rc; } *attr_value = be32_to_cpu(getcnf.attr_val); dbg_verbose("%s(): portid=%u, (attr,sel)=(0x%04x,%d)=0x%04x, ret=0x%02x\n", __func__, portid, attrid, select_index, *attr_value, getcnf.rc); return getcnf.rc; } static int es1_switch_attr_get(struct tsb_switch *sw, uint16_t attrid, uint32_t *val) { uint8_t getreq[] = { SWITCH_DEVICE_ID, NCP_RESERVED, NCP_SWITCHATTRGETREQ, (attrid >> 8), (attrid & 0xFF), }; struct __attribute__ ((__packed__)) switch_attr_cnf { uint8_t rc; uint8_t functionid; uint32_t attr_val; } getcnf; int rc; rc = es1_transfer(sw, getreq, sizeof(getreq), (uint8_t*)&getcnf, sizeof(getcnf)); if (rc) { return rc; } if (getcnf.functionid != NCP_SWITCHATTRGETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return getcnf.rc; } if (val) { *val = be32_to_cpu(getcnf.attr_val); } dbg_verbose("%s(): attr(0x%04x)=0x%08x, ret=0x%02x\n", __func__, attrid, *val, getcnf.rc); return getcnf.rc; } static int es1_lut_get(struct tsb_switch *sw, uint8_t unipro_portid, uint8_t addr, uint8_t *dst_portid) { int rc; uint8_t getreq[] = { SWITCH_DEVICE_ID, addr, NCP_LUTGETREQ, }; struct __attribute__ ((__packed__)) getcnf { uint8_t rc; uint8_t fid; uint8_t reserved; uint8_t dst_portid; } getcnf; rc = es1_transfer(sw, getreq, sizeof(getreq), (uint8_t*)&getcnf, sizeof(getcnf)); if (rc) { return rc; } if (getcnf.fid != NCP_LUTGETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return getcnf.rc; } *dst_portid = getcnf.dst_portid; dbg_verbose("%s(): addr=%u, dst_portid=%u\n", __func__, addr, *dst_portid); return getcnf.rc; } static int es1_lut_set(struct tsb_switch *sw, uint8_t unipro_portid, uint8_t addr, uint8_t dst_portid) { int rc; uint8_t setreq[] = { SWITCH_DEVICE_ID, addr, NCP_LUTSETREQ, NCP_RESERVED, dst_portid }; struct __attribute__ ((__packed__)) switch_id_setcnf { uint8_t rc; uint8_t fid; } setcnf; rc = es1_transfer(sw, setreq, sizeof(setreq), (uint8_t*)&setcnf, sizeof(setcnf)); if (rc) { return rc; } if (setcnf.fid != NCP_LUTSETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); } dbg_verbose("%s(): addr=%u, dst_portid=%u, ret=0x%02x\n", __func__, addr, dst_portid, setcnf.rc); return setcnf.rc; } static int es1_switch_id_set(struct tsb_switch *sw, uint8_t cportid, uint8_t peer_cportid, uint8_t dis, uint8_t irt) { uint8_t setreq[] = { SWITCH_DEVICE_ID, (dis << 2) | (irt << 0), NCP_SWITCHIDSETREQ, SWITCH_DEVICE_ID, cportid, // L4 CPortID SWITCH_DEVICE_ID, peer_cportid, NCP_RESERVED, SWITCH_PORT_ID // Source portID }; struct __attribute__ ((__packed__)) switch_id_setcnf { uint8_t rc; uint8_t fid; } setcnf; int rc; dbg_insane("%s(): cportid: %u peer_cportid: %u dis: %u irt: %u\n", __func__, cportid, peer_cportid, dis, irt); rc = es1_transfer(sw, setreq, sizeof(setreq), (uint8_t*)&setcnf, sizeof(setcnf)); if (rc) { return rc; } if (setcnf.fid != NCP_SWITCHIDSETCNF) { dbg_error("%s(): unexpected CNF\n", __func__); return setcnf.rc; } dbg_verbose("%s(): switchDeviceId=0x%01x, cPortId=0x%01x -> peerCPortId=0x%01x, ret=0x%02x\n", __func__, SWITCH_DEVICE_ID, cportid, peer_cportid, setcnf.rc); return setcnf.rc; } /** * @brief Dump routing table to low level console */ static int es1_dump_routing_table(struct tsb_switch *sw) { int i, j, idx, rc; uint8_t p = 0, valid_bitmask[16]; char msg[64]; rc = switch_dev_id_mask_get(sw, SWITCH_PORT_ID, valid_bitmask); if (rc) { dbg_error("%s() Failed to retrieve routing table.\n", __func__); return rc; } dbg_info("%s(): Routing table\n", __func__); dbg_info("======================================================\n"); /* Replace invalid entries with 'XX' */ for (i = 0; i < 8; i++) { /* Build a line with the offset, 8 entries, a '|' then 8 entries */ idx = 0; rc = sprintf(msg, "%3d: ", i * 16); if (rc <= 0) goto out; else idx += rc; for (j = 0; j < 16; j++) { if (CHECK_VALID_ENTRY(i * 16 + j)) { switch_lut_get(sw, SWITCH_PORT_ID, i * 16 + j, &p); rc = sprintf(msg + idx, "%2u ", p); if (rc <= 0) goto out; else idx += rc; } else { rc = sprintf(msg + idx, "XX "); if (rc <= 0) goto out; else idx += rc; } if (j == 7) { rc = sprintf(msg + idx, "| "); if (rc <= 0) goto out; else idx += rc; } } rc = sprintf(msg + idx, "\n"); if (rc <= 0) goto out; else idx += rc; msg[idx] = 0; /* Output the line */ dbg_info("%s", msg); } out: dbg_info("======================================================\n"); return 0; } static struct tsb_switch_ops es1_ops = { .set = es1_set, .get = es1_get, .peer_set = es1_peer_set, .peer_get = es1_peer_get, .lut_set = es1_lut_set, .lut_get = es1_lut_get, .dump_routing_table = es1_dump_routing_table, .dev_id_mask_get = es1_dev_id_mask_get, .switch_attr_get = es1_switch_attr_get, .switch_id_set = es1_switch_id_set, }; /* * FIXME fix all i2c usage */ int tsb_switch_es1_init(struct tsb_switch *sw, unsigned int i2c_bus) { int i2c_dev; dbg_info("Initializing ES1 switch...\n"); i2c_dev = open("/dev/i2c-0", 0); if (i2c_dev < 0) { return -ENODEV; } ioctl(i2c_dev, I2C_SET_FREQUENCY, ES1_I2C_FREQUENCY); sw->priv = (void*) i2c_dev; sw->ops = &es1_ops; dbg_info("... Done!\n"); return 0; } void tsb_switch_es1_exit(struct tsb_switch *sw) { close((int) sw->priv); sw->priv = NULL; sw->ops = NULL; }
bsd-3-clause
rust-lang/rust-bindgen
tests/expectations/tests/issue-662-cannot-find-T-in-this-scope.rs
1396
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RefPtr<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for RefPtr<T> { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHolder<T> { pub a: T, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHolder<T> { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct nsMainThreadPtrHandle<T> { pub mPtr: RefPtr<nsMainThreadPtrHolder<T>>, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>, } impl<T> Default for nsMainThreadPtrHandle<T> { fn default() -> Self { let mut s = ::std::mem::MaybeUninit::<Self>::uninit(); unsafe { ::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } }
bsd-3-clause
babelsberg/babelsberg-r
tests/modules/ffi/test_ffi.py
2305
from tests.modules.ffi.base import BaseFFITest from rpython.rtyper.lltypesystem import rffi # Most of the stuff is still very vague. # This is because lots of the constants had to be set to something in order to # run some specs but the specs weren't about them. class TestTypeDefs(BaseFFITest): def test_it_is_kind_of_a_Hash(self, space): assert self.ask(space, 'FFI::TypeDefs.kind_of? Hash') class TestTypes(BaseFFITest): def test_it_is_kind_of_a_Hash(self, space): assert self.ask(space, 'FFI::Types.kind_of? Hash') class TestPlatform(BaseFFITest): def test_it_is_a_Module(self, space): assert self.ask(space, "FFI::Platform.is_a? Module") def test_it_offers_some_SIZE_constants(self, space): w_res = space.execute('FFI::Platform::INT8_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.CHAR) w_res = space.execute('FFI::Platform::INT16_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.SHORT) w_res = space.execute('FFI::Platform::INT32_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.INT) w_res = space.execute('FFI::Platform::INT64_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.LONGLONG) w_res = space.execute('FFI::Platform::LONG_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.LONG) w_res = space.execute('FFI::Platform::FLOAT_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.FLOAT) w_res = space.execute('FFI::Platform::DOUBLE_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.DOUBLE) w_res = space.execute('FFI::Platform::ADDRESS_SIZE') assert space.int_w(w_res) == rffi.sizeof(rffi.VOIDP) class TestStructLayout(BaseFFITest): def test_it_is_a_class(self, space): assert self.ask(space, "FFI::StructLayout.is_a? Class") def test_its_Field_constant_is_nil(self, space): assert self.ask(space, "FFI::StructLayout::Field.nil?") class TestStructByReference(BaseFFITest): def test_it_is_a_class(self, space): assert self.ask(space, "FFI::StructByReference.is_a? Class") class TestNullPointerError(BaseFFITest): def test_it_inherits_from_Exception(self, space): assert self.ask(space, "FFI::NullPointerError.ancestors.include? Exception")
bsd-3-clause
jonathanihm/freeCodeCamp
curriculum/challenges/english/03-front-end-libraries/redux/use-middleware-to-handle-asynchronous-actions.english.md
5673
--- id: 5a24c314108439a4d4036156 title: Use Middleware to Handle Asynchronous Actions challengeType: 6 isHidden: false isRequired: false forumTopicId: 301451 --- ## Description <section id='description'> So far these challenges have avoided discussing asynchronous actions, but they are an unavoidable part of web development. At some point you'll need to call asynchronous endpoints in your Redux app, so how do you handle these types of requests? Redux provides middleware designed specifically for this purpose, called Redux Thunk middleware. Here's a brief description how to use this with Redux. To include Redux Thunk middleware, you pass it as an argument to <code>Redux.applyMiddleware()</code>. This statement is then provided as a second optional parameter to the <code>createStore()</code> function. Take a look at the code at the bottom of the editor to see this. Then, to create an asynchronous action, you return a function in the action creator that takes <code>dispatch</code> as an argument. Within this function, you can dispatch actions and perform asynchronous requests. In this example, an asynchronous request is simulated with a <code>setTimeout()</code> call. It's common to dispatch an action before initiating any asynchronous behavior so that your application state knows that some data is being requested (this state could display a loading icon, for instance). Then, once you receive the data, you dispatch another action which carries the data as a payload along with information that the action is completed. Remember that you're passing <code>dispatch</code> as a parameter to this special action creator. This is what you'll use to dispatch your actions, you simply pass the action directly to dispatch and the middleware takes care of the rest. </section> ## Instructions <section id='instructions'> Write both dispatches in the <code>handleAsync()</code> action creator. Dispatch <code>requestingData()</code> before the <code>setTimeout()</code> (the simulated API call). Then, after you receive the (pretend) data, dispatch the <code>receivedData()</code> action, passing in this data. Now you know how to handle asynchronous actions in Redux. Everything else continues to behave as before. </section> ## Tests <section id='tests'> ```yml tests: - text: The <code>requestingData</code> action creator should return an object of type equal to the value of <code>REQUESTING_DATA</code>. testString: assert(requestingData().type === REQUESTING_DATA); - text: The <code>receivedData</code> action creator should return an object of type equal to the value of <code>RECEIVED_DATA</code>. testString: assert(receivedData('data').type === RECEIVED_DATA); - text: <code>asyncDataReducer</code> should be a function. testString: assert(typeof asyncDataReducer === 'function'); - text: Dispatching the requestingData action creator should update the store <code>state</code> property of fetching to <code>true</code>. testString: assert((function() { const initialState = store.getState(); store.dispatch(requestingData()); const reqState = store.getState(); return initialState.fetching === false && reqState.fetching === true })()); - text: Dispatching <code>handleAsync</code> should dispatch the data request action and then dispatch the received data action after a delay. testString: assert((function() { const noWhiteSpace = handleAsync.toString().replace(/\s/g,''); return noWhiteSpace.includes('dispatch(requestingData())') === true && noWhiteSpace.includes('dispatch(receivedData(data))') === true })()); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='jsx-seed'> ```jsx const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { // dispatch request action here setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } // dispatch received data action here }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) ); ``` </div> </section> ## Solution <section id='solution'> ```js const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { dispatch(requestingData()); setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } dispatch(receivedData(data)); }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) ); ``` </section>
bsd-3-clause
datasift/storyplayer
src/php/Storyplayer/SPv3/Modules/Types/FromArray.php
3138
<?php /** * Copyright (c) 2011-present Mediasift Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the names of the copyright holders nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Libraries * @package Storyplayer/Modules/Types * @author Thomas Shipley <[email protected]> * @copyright 2011-present Mediasift Ltd www.datasift.com * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://datasift.github.io/storyplayer */ namespace Storyplayer\SPv3\Modules\Types; use Storyplayer\SPv3\Modules\Types; /** * A collection of functions for manipulating arrays * * Great for testing APIs * * @category Libraries * @package Storyplayer/Modules/Types * @author Thomas Shipley <[email protected]> * @copyright 2011-present Mediasift Ltd www.datasift.com * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @link http://datasift.github.io/storyplayer */ class FromArray extends Prose { /** * Sets a value in an array for a . delimited path * if the path does not exist it will be added to the array * @param $array - array to add the value to * @param $path - the . delimited path to the key of the value to add - * if path not found key at that path will be created * @param $val - the value to add */ public function setValueInArray(&$array, $path, $val) { $pathAsArray = Types::fromString()->splitDotSeparatedPath($path); for ($i=&$array; $key=array_shift($pathAsArray); $i=&$i[$key]) { if (!isset($i[$key])) { $i[$key] = []; } } $i = $val; } }
bsd-3-clause
Codewaves/Highlight.java
src/main/java/com/codewaves/codehighlight/languages/BashLanguage.java
3376
package com.codewaves.codehighlight.languages; import com.codewaves.codehighlight.core.Keyword; import com.codewaves.codehighlight.core.Language; import com.codewaves.codehighlight.core.Mode; /** * Created by Sergej Kravcenko on 5/17/2017. * Copyright (c) 2017 Sergej Kravcenko */ public class BashLanguage implements LanguageBuilder { private static String[] ALIASES = { "sh", "zsh" }; private static String KEYWORDS = "if then else elif fi for while in do done case esac function"; private static String KEYWORDS_LITERAL = "true false"; private static String KEYWORDS_BUILTIN = "break cd continue eval exec exit export getopts hash pwd readonly return shift test times " + "trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf " + "read readarray source type typeset ulimit unalias set shopt " + "autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles " + "compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate " + "fc fg float functions getcap getln history integer jobs kill limit log noglob popd print " + "pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit " + "unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof " + "zpty zregexparse zsocket zstyle ztcp"; private static String KEYWORDS_REL = "-ne -eq -lt -gt -f -d -e -s -l -a"; @Override public Language build() { final Mode VAR = new Mode() .className("variable") .variants(new Mode[] { new Mode().begin("\\$[\\w\\d#@][\\w\\d_]*"), new Mode().begin("\\$\\{(.*?)\\}") }); final Mode QUOTE_STRING = new Mode() .className("string") .begin("\"") .end("\"") .contains(new Mode[] { Mode.BACKSLASH_ESCAPE, VAR, new Mode().className("variable") .begin("\\$\\(") .end("\\)") .contains(new Mode[] { Mode.BACKSLASH_ESCAPE }) }); final Mode APOS_STRING = new Mode() .className("string") .begin("'") .end("'"); return (Language) new Language() .aliases(ALIASES) .lexemes("\\b-?[a-z\\._]+\\b") .keywords(new Keyword[] { new Keyword("keyword", KEYWORDS), new Keyword("literal", KEYWORDS_LITERAL), new Keyword("built_in", KEYWORDS_BUILTIN), new Keyword("_", KEYWORDS_REL) }) .contains(new Mode[] { new Mode().className("meta").begin("^#![^\\n]+sh\\s*$").relevance(10), new Mode() .className("function") .begin("\\w[\\w\\d_]*\\s*\\(\\s*\\)\\s*\\{") .returnBegin() .contains(new Mode[] { Mode.inherit(Mode.TITLE_MODE, new Mode().begin("\\w[\\w\\d_]*")) }) .relevance(0), Mode.HASH_COMMENT_MODE, QUOTE_STRING, APOS_STRING, VAR }); } }
bsd-3-clause
419989658/conciseCMS
backend/models/ImageUpload.php
1127
<?php /** * User: sometimes * Date: 2016/10/1 * Time: 23:47 */ namespace backend\models; use yii\base\Model; use yii\helpers\FileHelper; class ImageUpload extends Model { //private $imageFile; public $imageFile; public function rules() { return [ [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png,jpg'], ]; } /** * 用于上传图片 * @param string $filePath 指定图片存放在何处,such as: path/to/image/,Note that:最后需要加上一个 /符号,表示存放目录 * @return bool 上传成功返回 true,上传失败返回false */ public function upload($filePath) { if(!file_exists($filePath)){ FileHelper::createDirectory($filePath); } $fileName = date('YmdHis') . '_' . rand(111, 999) . '_' . md5($this->imageFile->baseName) . '.' . $this->imageFile->extension; if ($this->validate()) { $this->imageFile->saveAs($filePath.$fileName); return $filePath.$fileName; } else { return false; } } }
bsd-3-clause
verzeilberg/boodschappen
module/Grocery/src/Grocery/Service/productImageServiceInterface.php
673
<?php namespace Grocery\Service; interface productImageServiceInterface { /** * Should return a set of all blog posts that we can iterate over. Single entries of the array are supposed to be * implementing \Blog\Model\PostInterface * * @return array|PostInterface[] */ public function deleteProductImages($productImages, $product); /** * Should return a set of all blog posts that we can iterate over. Single entries of the array are supposed to be * implementing \Blog\Model\PostInterface * * @return array|PostInterface[] */ public function deleteImageFile($productImageType); }
bsd-3-clause
krytarowski/lumina
src-qt5/core/lumina-desktop/desktop-plugins/desktopview/DesktopViewPlugin.cpp
8788
#include "DesktopViewPlugin.h" #include <QFileInfo> #include <QDir> #include <QClipboard> #include <QMimeData> #include <QImageReader> #include <LuminaXDG.h> #include "LSession.h" DesktopViewPlugin::DesktopViewPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){ this->setLayout( new QVBoxLayout()); this->layout()->setContentsMargins(0,0,0,0); list = new QListWidget(this); list->setViewMode(QListView::IconMode); list->setFlow(QListWidget::TopToBottom); //Qt bug workaround - need the opposite flow in the widget constructor list->setWrapping(true); list->setSpacing(4); list->setSelectionBehavior(QAbstractItemView::SelectItems); list->setSelectionMode(QAbstractItemView::ExtendedSelection); list->setContextMenuPolicy(Qt::CustomContextMenu); list->setMovement(QListView::Snap); //make sure items are "stuck" in the grid menu = new QMenu(this); menu->addAction( LXDG::findIcon("run-build-file",""), tr("Open"), this, SLOT(runItems()) ); menu->addSeparator(); menu->addAction( LXDG::findIcon("edit-cut",""), tr("Cut"), this, SLOT(cutItems()) ); menu->addAction( LXDG::findIcon("edit-copy",""), tr("Copy"), this, SLOT(copyItems()) ); menu->addSeparator(); menu->addAction( LXDG::findIcon("zoom-in",""), tr("Increase Icons"), this, SLOT(increaseIconSize()) ); menu->addAction( LXDG::findIcon("zoom-out",""), tr("Decrease Icons"), this, SLOT(decreaseIconSize()) ); menu->addSeparator(); menu->addAction( LXDG::findIcon("edit-delete",""), tr("Delete"), this, SLOT(deleteItems()) ); menu->addSeparator(); if(LUtils::isValidBinary("lumina-fileinfo")){ menu->addAction( LXDG::findIcon("system-search",""), tr("Properties"), this, SLOT(displayProperties()) ); } this->layout()->addWidget(list); connect(QApplication::instance(), SIGNAL(DesktopFilesChanged()), this, SLOT(updateContents()) ); connect(list, SIGNAL(itemActivated(QListWidgetItem*)), this, SLOT(runItems()) ); connect(list, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showMenu(const QPoint&)) ); QTimer::singleShot(1000,this, SLOT(updateContents()) ); //wait a second before loading contents } DesktopViewPlugin::~DesktopViewPlugin(){ } void DesktopViewPlugin::runItems(){ QList<QListWidgetItem*> sel = list->selectedItems(); for(int i=0; i<sel.length(); i++){ LSession::LaunchApplication("lumina-open \""+sel[i]->whatsThis()+"\""); } } void DesktopViewPlugin::copyItems(){ QList<QListWidgetItem*> sel = list->selectedItems(); if(sel.isEmpty()){ return; } //nothing selected QStringList items; //Format the data string for(int i=0; i<sel.length(); i++){ items << "copy::::"+sel[i]->whatsThis(); } //Now save that data to the global clipboard QMimeData *dat = new QMimeData; dat->clear(); dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit()); QApplication::clipboard()->clear(); QApplication::clipboard()->setMimeData(dat); } void DesktopViewPlugin::cutItems(){ QList<QListWidgetItem*> sel = list->selectedItems(); if(sel.isEmpty()){ return; } //nothing selected QStringList items; //Format the data string for(int i=0; i<sel.length(); i++){ items << "cut::::"+sel[i]->whatsThis(); } //Now save that data to the global clipboard QMimeData *dat = new QMimeData; dat->clear(); dat->setData("x-special/lumina-copied-files", items.join("\n").toLocal8Bit()); QApplication::clipboard()->clear(); QApplication::clipboard()->setMimeData(dat); } void DesktopViewPlugin::deleteItems(){ QList<QListWidgetItem*> sel = list->selectedItems(); for(int i=0; i<sel.length(); i++){ if(QFileInfo(sel[i]->whatsThis()).isDir()){ QProcess::startDetached("rm -r \""+sel[i]->whatsThis()+"\""); }else{ QFile::remove(sel[i]->whatsThis()); } } } void DesktopViewPlugin::showMenu(const QPoint &pos){ //Make sure there is an item underneath the mouse first if(list->itemAt(pos)!=0){ menu->popup(this->mapToGlobal(pos)); }else{ //Pass the context menu request on to the desktop (emit it from the plugin) this->showPluginMenu(); //emit OpenDesktopMenu(); } } void DesktopViewPlugin::increaseIconSize(){ int icosize = this->readSetting("IconSize",64).toInt(); icosize+=16; //go in orders of 16 pixels //list->setIconSize(QSize(icosize,icosize)); this->saveSetting("IconSize",icosize); QTimer::singleShot(10, this, SLOT(updateContents())); } void DesktopViewPlugin::decreaseIconSize(){ int icosize = this->readSetting("IconSize",64).toInt(); if(icosize < 20){ return; } //too small to decrease more icosize-=16; //go in orders of 16 pixels //list->setIconSize(QSize(icosize,icosize)); this->saveSetting("IconSize",icosize); QTimer::singleShot(10,this, SLOT(updateContents())); } void DesktopViewPlugin::updateContents(){ list->clear(); int icosize = this->readSetting("IconSize",64).toInt(); QSize gridSZ = QSize(qRound(1.8*icosize),icosize+4+(2*this->fontMetrics().height()) ); //qDebug() << "Icon Size:" << icosize <<"Grid Size:" << gridSZ.width() << gridSZ.height(); list->setGridSize(gridSZ); list->setIconSize(QSize(icosize,icosize)); QDir dir(QDir::homePath()+"/Desktop"); QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name | QDir::Type | QDir::DirsFirst); for(int i=0; i<files.length(); i++){ QListWidgetItem *it = new QListWidgetItem; it->setSizeHint(gridSZ); //ensure uniform item sizes //it->setForeground(QBrush(Qt::black, Qt::Dense2Pattern)); //Try to use a font color which will always be visible it->setTextAlignment(Qt::AlignCenter); it->setWhatsThis(files[i].absoluteFilePath()); QString txt; if(files[i].isDir()){ it->setIcon( LXDG::findIcon("folder","") ); txt = files[i].fileName(); }else if(files[i].suffix() == "desktop" ){ bool ok = false; XDGDesktop desk = LXDG::loadDesktopFile(files[i].absoluteFilePath(), ok); if(ok){ it->setIcon( LXDG::findIcon(desk.icon,"unknown") ); if(desk.name.isEmpty()){ txt = files[i].fileName(); }else{ txt = desk.name; } }else{ //Revert back to a standard file handling it->setIcon( LXDG::findMimeIcon(files[i].fileName()) ); txt = files[i].fileName(); } }else if(LUtils::imageExtensions().contains(files[i].suffix().toLower()) ){ it->setIcon( QIcon( QPixmap(files[i].absoluteFilePath()).scaled(icosize,icosize,Qt::IgnoreAspectRatio, Qt::SmoothTransformation) ) ); txt = files[i].fileName(); }else{ it->setIcon( LXDG::findMimeIcon( files[i].fileName() ) ); txt = files[i].fileName(); } //Add the sym-link overlay to the icon as necessary if(files[i].isSymLink()){ QImage img = it->icon().pixmap(QSize(icosize,icosize)).toImage(); int oSize = icosize/2; //overlay size QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPainter painter(&img); painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner it->setIcon( QIcon(QPixmap::fromImage(img)) ); } //Now adjust the visible text as necessary based on font/grid sizing it->setToolTip(txt); if(this->fontMetrics().width(txt) > (gridSZ.width()-4) ){ //int dash = this->fontMetrics().width("-"); //Text too long, try to show it on two lines txt = txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks if(txt.contains("\n")){ //need to check each line QStringList txtL = txt.split("\n"); for(int i=0; i<txtL.length(); i++){ txtL[i] = this->fontMetrics().elidedText(txtL[i], Qt::ElideRight, gridSZ.width()-4); } txt = txtL.join("\n"); if(txtL.length()>2){ txt = txt.section("\n",0,1); } //only keep the first two lines }else{ txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(gridSZ.width()-4)); //Now split the line in half for the two lines txt.insert( (txt.count()/2), "\n"); } }else{ txt.append("\n "); //ensure two lines (2nd one invisible) - keeps formatting sane } it->setText(txt); list->addItem(it); if( (i%10) == 0){ QApplication::processEvents(); }//keep the UI snappy, every 10 items } list->setFlow(QListWidget::TopToBottom); //To ensure this is consistent - issues with putting it in the constructor list->update(); //Re-paint the widget after all items are added } void DesktopViewPlugin::displayProperties(){ QList<QListWidgetItem*> sel = list->selectedItems(); for(int i=0; i<sel.length(); i++){ LSession::LaunchApplication("lumina-fileinfo \""+sel[i]->whatsThis()); } }
bsd-3-clause
zepheira/exhibit
src/webapp/examples/italian-soccer/tutorial.html
10880
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns:css="http://macVmlSchemaUri" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta name=Title content=""> <meta name=Keywords content=""> <meta http-equiv=Content-Type content="text/html; charset=macintosh"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 2008"> <meta name=Originator content="Microsoft Word 2008"> <link rel=File-List href="tsv_csv_tutorial_files/filelist.xml"> <!--[if gte mso 9]><xml> <o:DocumentProperties> <o:Author>Gaia Carini</o:Author> <o:Template>Normal.dotm</o:Template> <o:LastAuthor>Gaia Carini</o:LastAuthor> <o:Revision>2</o:Revision> <o:TotalTime>38</o:TotalTime> <o:Created>2009-07-22T19:22:00Z</o:Created> <o:LastSaved>2009-07-22T19:22:00Z</o:LastSaved> <o:Pages>1</o:Pages> <o:Company>MIT</o:Company> <o:Lines>1</o:Lines> <o:Paragraphs>1</o:Paragraphs> <o:Version>12.0</o:Version> </o:DocumentProperties> <o:OfficeDocumentSettings> <o:AllowPNG/> </o:OfficeDocumentSettings> </xml><![endif]--><!--[if gte mso 9]><xml> <w:WordDocument> <w:TrackMoves>false</w:TrackMoves> <w:TrackFormatting/> <w:PunctuationKerning/> <w:DrawingGridHorizontalSpacing>18 pt</w:DrawingGridHorizontalSpacing> <w:DrawingGridVerticalSpacing>18 pt</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>0</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:BreakWrappedTables/> <w:DontGrowAutofit/> <w:DontAutofitConstrainedTables/> <w:DontVertAlignInTxbx/> </w:Compatibility> </w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="276"> </w:LatentStyles> </xml><![endif]--> <style> <!-- /* Font Definitions */ @font-face {font-family:Cambria; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:0; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 0 0 0 1 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin-top:0in; margin-right:0in; margin-bottom:10.0pt; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:Cambria; mso-fareast-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} a:link, span.MsoHyperlink {mso-style-noshow:yes; color:blue; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {mso-style-noshow:yes; color:purple; text-decoration:underline; text-underline:single;} pre {mso-style-link:"HTML Preformatted Char"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:Courier; mso-fareast-font-family:Cambria; mso-fareast-theme-font:minor-latin; mso-bidi-font-family:Courier;} span.HTMLPreformattedChar {mso-style-name:"HTML Preformatted Char"; mso-style-locked:yes; mso-style-link:"HTML Preformatted"; mso-ansi-font-size:10.0pt; mso-bidi-font-size:10.0pt; font-family:Courier; mso-ascii-font-family:Courier; mso-hansi-font-family:Courier; mso-bidi-font-family:Courier;} @page Section1 {size:8.5in 11.0in; margin:1.0in 67.5pt 1.0in 1.0in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style> <!--[if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-ascii-font-family:Cambria; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Cambria; mso-hansi-theme-font:minor-latin;} </style> <![endif]--><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026"/> </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif]--> </head> <body lang=EN-US link=blue vlink=purple style='tab-interval:.5in'> <div class=Section1> <p class=MsoNormal align=center style='text-align:center'><b style='mso-bidi-font-weight: normal'><u><span style='font-size:16.0pt;mso-bidi-font-size:12.0pt'>How to make an Exhibit from a tsv or csv file<o:p></o:p></span></u></b></p> <p class=MsoNormal style='text-align:justify'>This tutorial walks you through the steps of setting up an Exhibit from a tsv or csv file. Here are the <a href="http://mit.edu/carinig/Public/tsv-csv-importerDocumentation/italianSoccer.html">example exhibit</a> and the data files in both formats: <a href="http://mit.edu/carinig/Public/tsv-csv-importerDocumentation/italianSoccer.csv">csv</a> and <a href="http://mit.edu/carinig/Public/tsv-csv-importerDocumentation/italianSoccer.txt">tsv</a>.</p> <p class=MsoNormal style='text-align:justify'><o:p>&nbsp;</o:p></p> <p class=MsoNormal style='text-align:justify'><b style='mso-bidi-font-weight: normal'><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt'>Setting up the Exhibit<o:p></o:p></span></b></p> <p class=MsoNormal style='text-align:justify'>To make your TSV/CSV Exhibit, you should first follow the <a href="http://simile.mit.edu/wiki/Exhibit/Getting_Started_Tutorial">Getting Started Tutorial</a><a href="#"></a><a href="http://simile.mit.edu/wiki/Exhibit/Getting_Started_Tutorial"></a> to set up the initial html page. The link to the data however should be similar to the following, depending on the fileÕs format:</p> <p class=MsoNormal align=center style='text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;font-family:Courier'>&lt;link href=&quot;italianSoccer.csv&quot; type=&quot;text/csv&quot; rel=&quot;exhibit/data&quot;/&gt;<o:p></o:p></span></p> <p class=MsoNormal align=center style='text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;font-family:Courier'> <o:p></o:p></span><span class="MsoNormal" style="text-align:center">or</span></p> <p class=MsoNormal align=center style='text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;font-family:Courier'>&lt;link href=&quot;italianSoccer.txt&quot; type=&quot;text/tsv&quot; rel=&quot;exhibit/data&quot;/&gt;<o:p></o:p></span></p> <p class=MsoNormal><span style='font-size:8.0pt;mso-bidi-font-size:12.0pt; font-family:Courier'><o:p>&nbsp;</o:p></span></p> <p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt'>Formatting the Data<o:p></o:p></span></b></p> <p class=MsoNormal style='text-align:justify'>If you are creating the tsv/csv file yourself , the first line should provide the names of the properties along with their value types as shown below. In the case that the value type is ÒtextÓ, then you do not have to specify it as it is the default type.</p> <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt; text-align:center;tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt'><span style='font-size:10.0pt;font-family:Courier;mso-bidi-font-family:Courier'>label,url:url,image:url,City,Region,Winners,Runner-up,Championship Seasons<o:p></o:p></span></p> <p class=MsoNormal style='margin-bottom:0in;margin-bottom:.0001pt;tab-stops: 45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt'><span style='font-size:10.0pt;font-family:Courier;mso-bidi-font-family:Courier'><o:p>&nbsp;</o:p></span></p> <p class=MsoNormal align=center style='text-align:center'>or</p> <pre style='text-align:center'>label<span style='mso-tab-count:1'>&nbsp;&nbsp; </span>url:url<span style='mso-tab-count:1'> </span>image:url<span style='mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>City<span style='mso-tab-count:1'>&nbsp;&nbsp;&nbsp; </span>Region<span style='mso-tab-count: 1'>&nbsp; </span>Winners<span style='mso-tab-count:1'> </span>Runner-up<span style='mso-tab-count:1'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>Championship Seasons</pre> <p class=MsoNormal><o:p>&nbsp;</o:p></p> <p class=MsoNormal><b style='mso-bidi-font-weight:normal'><span style='font-size:14.0pt;mso-bidi-font-size:12.0pt'>Adding the Property Names and Value Types<o:p></o:p></span></b></p> <p class=MsoNormal style='text-align:justify'>If instead the data is taken from another website and you would like to add or replace the existing property names to match the Exhibit format, you must change the link so that it follows the structure below:</p> <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt; text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt; font-family:Courier'><o:p>&nbsp;</o:p></span></p> <p class=MsoNormal align=center style='text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt;font-family:Courier'>&lt;link href=&quot;italianSoccer.txt&quot; type=&quot;text/tsv&quot; rel=&quot;exhibit/data&quot; ex:properties=&quot;label,url:url,image:url,City,Region,latlng,Winners:number,Runner-up:number,ChampionshipSeasons&quot; ex:hasColumnTitles=&quot;true&quot;/&gt; <o:p></o:p></span></p> <p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt; text-align:center'><span style='font-size:10.0pt;mso-bidi-font-size:12.0pt; font-family:Courier'><o:p>&nbsp;</o:p></span></p> <p class=MsoNormal style='text-align:justify'>The Ò<span style='font-family: Courier'>ex:properties</span>Ó attribute allows you to specify a comma-separated list of names and types for the properties. The Ò<span style='font-family: Courier'>ex:hasColumnTitles</span>Ó attribute, which is set to true by default, lets you specify whether the data file already contains a header row. If a list of properties is specified in <span style="font-family: Courier">ex:properties</span> and <span style="font-family: Courier">ex:hasColumnTitles</span> is set to true, the property list will override the existing header row. Note, you will get an error if you set <span style="font-family: Courier">ex:hasColumnTitles</span> to false and do not provide a list of property names. </p> <p class=MsoNormal style='text-align:justify'><o:p>&nbsp;</o:p></p> </div> </body> </html>
bsd-3-clause
programacionav/Proyecto2015
modules/admcapacitaciones/admcapacitacionesModule.php
300
<?php namespace app\modules\admcapacitaciones; class admcapacitacionesModule extends \yii\base\Module { public $controllerNamespace = 'app\modules\admcapacitaciones\controllers'; public function init() { parent::init(); // custom initialization code goes here } }
bsd-3-clause
smartdevicelink/sdl_core
src/components/transport_manager/test/include/transport_manager/bt/mock_bluetooth_transport_adapter.h
2405
/* * Copyright (c) 2019, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_BT_MOCK_BLUETOOTH_TRANSPORT_ADAPTER_H_ #define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_BT_MOCK_BLUETOOTH_TRANSPORT_ADAPTER_H_ #include "transport_manager/transport_adapter/mock_transport_adapter.h" namespace test { namespace components { namespace transport_manager_test { using namespace ::transport_manager::transport_adapter; class MockBluetoothTransportAdapter : public MockTransportAdapter { public: MOCK_CONST_METHOD0(GetDeviceType, DeviceType()); MOCK_CONST_METHOD0(Store, void()); MOCK_METHOD0(Restore, bool()); }; } // namespace transport_manager_test } // namespace components } // namespace test #endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_BT_MOCK_BLUETOOTH_TRANSPORT_ADAPTER_H_
bsd-3-clause
FernandoMauricio/portal-senac
modules/aux_planejamento/views/cadastros/materialconsumo/view.php
1077
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\modules\aux_planejamento\models\cadastros\Materialconsumo */ $this->title = $model->matcon_cod; $this->params['breadcrumbs'][] = ['label' => 'Materialconsumos', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="materialconsumo-view"> <h1><?= Html::encode($this->title) ?></h1> <p> <?= Html::a('Update', ['update', 'id' => $model->matcon_cod], ['class' => 'btn btn-primary']) ?> <?= Html::a('Delete', ['delete', 'id' => $model->matcon_cod], [ 'class' => 'btn btn-danger', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', 'method' => 'post', ], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'matcon_cod', 'matcon_descricao', 'matcon_tipo', 'matcon_valor', 'matcon_status', ], ]) ?> </div>
bsd-3-clause
lz1988/stourwebcms
questions/ask.php
2695
<?php require_once(dirname(__FILE__)."/../include/common.inc.php"); function GetChannel() { global $dsql; $str = "分类:<select name=\"typeid\"><option value=''>--请选择--</option>"; $sql = "select * from #@__nav where pid='0' and isopen='1' and webid='0' and typeid != '10'"; $row = $dsql->getAll($sql); foreach($row AS $res) { $str .= "<option value='" . $res['typeid'] . "'>" . $res['shortname'] . "</option>"; } $str .= "</select>"; return $str; } $select=GetChannel(); ?> <div id="QS"> <form action="<?php echo $GLOBALS['cfg_cmsurl']; ?>/public/question.php" method="post" onSubmit="return SubmitQ();"> <div id="Submit"> <p><span>温馨提示:</span>请把你要问的问题按以下信息进行描述,我们将以最快的速度回复您</p> <ul class="Submit_bt"> <li style=" height:30px; line-height:30px"> <b class="fl">问题标题:</b> <input class="text fl" type="text" name="title" id="qtitle" /> <span class="color_f60 hf fl"><?php echo $select; ?></span> <span class="color_f60 hf fl">*需要及时回复<input name="musttime" type="checkbox" value="1" /></span> </li> <li><textarea name="content" cols="" rows="" id="qcontent"></textarea></li> <li style=" height:30px; line-height:30px" class="fl"> <span class="fl">联系人:</span> <input class="text1 fl" type="text" name="leavename" id="qusername" /> <span class="fl">匿名:<input class="nimi" name="noname" type="checkbox" id="noname" value="0" /></span> <span class="yzm fl">验证码:<img src= "<?php echo $GLOBALS['cfg_cmsurl']; ?>/include/vdimgck.php" style="cursor:pointer" onclick="this.src=this.src+'?'" title="点击我更换图片" alt="点击我更换图片" /></span> <input class="text2 fl" type="text" name="validate" id="validate" /><span class="color_46 fl">请输入图片上的预算结果</span> </li> </ul> <ul class="contact"> <li class="lx"><b>您的联系方式:</b>(方便客服人员及时联系为您解答疑问)</li> <li class="fl fs"><span>电话:</span><input class="text" type="text" name="telephone" id="telephone" /></li> <li class="fl fs"><span>邮箱:</span><input class="text" type="text" name="email" id="email" /></li> <li class="fl fs"><span>Q Q:</span><input class="text" type="text" name="qq" id="qq" /></li> <li class="fl fs"><span>MSN:</span><input class="text" type="text" name="msn" id="msn" /></li> <li class="fl fs"><input class="button_2" type="submit" name="anniu" value="提交问题" /></li> </ul> </div> </form> </div>
bsd-3-clause
brosner/django-sqlalchemy
tests/query/test_contains.py
1486
from django_sqlalchemy.test import * from apps.blog.models import Category class TestContains(object): def setup(self): Category.__table__.insert().execute({'name': 'Python'}, {'name': 'PHP'}, {'name': 'Ruby'}, {'name': 'Smalltalk'}, {'name': 'CSharp'}, {'name': 'Modula'}, {'name': 'Algol'}, {'name': 'Forth'}, {'name': 'Pascal'}) @fails_on('sqlite') def test_should_contain_string_in_name(self): assert 4 == Category.objects.filter(name__contains='a').count() assert 1 == Category.objects.filter(name__contains='A').count() @fails_on_everything_except('sqlite') def test_should_contain_string_in_name_on_sqlite(self): assert 5 == Category.objects.filter(name__contains='a').count() assert 5 == Category.objects.filter(name__contains='A').count() def test_should_contain_string_in_name_regardless_of_case(self): assert 5 == Category.objects.filter(name__icontains='a').count() assert 5 == Category.objects.filter(name__icontains='A').count() def test_should_contain_string_at_beginning(self): category = Category.objects.filter(name__contains='Sma') assert 1 == category.count() assert_equal(u'Smalltalk', category[0].name) def test_should_contain_string_at_end(self): category = Category.objects.filter(name__contains='arp') assert 1 == category.count() assert_equal(u'CSharp', category[0].name)
bsd-3-clause
syrexby/repostni
frontend/views/layouts/_advert.php
1439
<?php if (!isset($border)) { $border = false; } if (!isset($button)) { $button = false; } ?> <div class="container best-projects"> <div class="row"> <a href="/advert/create" class="create-best-project"> Реклама по<br/> доступной цене </a> </div> <div id="carousel-prev" class="carousel-btn"></div> <div id="carousel-next" class="carousel-btn"></div> <div id="owl-best-projects" class="row owl-carousel owl-theme<?= $border ? " border" : "" ?>"> <?php foreach (\common\models\Post::find()->where(["active" => true, "status_id" => \common\models\AdvertStatus::STATUS_ACTIVE])->orderBy("date DESC")->limit(20)->all() as $post) { ?> <div class="item" data-id="<?= $post->id ?>"> <a href="<?= $post->url ?>" target="_blank"><div class="post-img"><?= $post->photoFile ? '<img src="'. $post->photoFile->getUrl(178, 103, true) .'" />' : '' ?></div> <h4><?= \yii\bootstrap\Html::encode($post->name) ?></h4> <p><?= \yii\bootstrap\Html::encode($post->description) ?></p></a> </div> <?php } ?> </div> <?php /*if ($button) : */?><!-- <div class="row" style="text-align: center;"> <a href="/competition/create" class="btn btn-success btn-lg">Создать конкурс бесплатно</a> </div> --><?php /*endif; */?> </div>
bsd-3-clause
Andabekov/TheSuitProject
sql/clothstatustable.sql
1089
CREATE TABLE clothstatustable ( id INT PRIMARY KEY NOT NULL, status_name VARCHAR(200) NOT NULL ); CREATE UNIQUE INDEX unique_id ON clothstatustable (id); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (1, 'В обработке'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (2, 'На сверке кодов системы'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (3, 'Проверка продавцом'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (4, 'В ожидании производства'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (5, 'Готово к отправке'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (6, 'В пути до Астаны'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (7, 'В офисе'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (8, 'Пригласили на примерку'); INSERT INTO pidzhak.clothstatustable (id, status_name) VALUES (9, 'Изделие выдано');
bsd-3-clause
esgiprojetninja/ninjaPokedex
public/js/lib/pokedex/actions/pokeSearchTypes.js
374
export const SET_SEARCHED_POKEMONS = "SET_SEARCHED_POKEMONS"; export const SET_SEARCHED_QUERY = "SET_SEARCHED_QUERY"; export const SET_SEARCHED_TYPE = "SET_SEARCHED_TYPE"; export const RESET_SEARCHED_PARAMS = "RESET_SEARCHED_PARAMS"; export const RESET_SEARCHED_POKEMONS = "RESET_SEARCHED_POKEMONS"; export const REMOVE_SEARCHED_PARAMS_TYPE = "REMOVE_SEARCHED_PARAMS_TYPE";
bsd-3-clause
Gaia-Interactive/gaia_core_php
lib/gaia/shortcircuit/resolver.php
4536
<?php namespace Gaia\ShortCircuit; /** * A utility class designed to convert names into file paths for actions and views. */ class Resolver implements Iface\Resolver { protected $appdir = ''; const param_match = '#\\\\\(([a-z0-9_\-]+)\\\\\)#iu'; protected $urls = array(); public function __construct( $dir = '', array $urls = null ){ $this->appdir = $dir; if( $urls ) $this->setUrls( $urls ); } /** * convert a URI string into an action. */ public function match( $uri, & $args ){ $args = array(); if( $this->urls ){ $buildRegex = function ( $pattern ){ $params = array(); $regex = preg_replace_callback(Resolver::param_match, function($match) use ( &$params ) { $params[] = $match[1]; // only exclude line breaks from my match. this will let utf-8 sequences through. // older patterns below. // turns out I don't need to be super strict on my pattern matching. // php sapi does most of the work for me in giving me the url. return '([^\n]+)'; //return '([[:graph:][:space:]]+)'; //return '([a-z0-9\.+\,\;\'\\\&%\$\#\=~_\-%\s\"\{\}/\:\(\)\[\]]+)'; }, preg_quote($pattern, '#')); return array('#^' . $regex . '$#i', $params ); }; foreach( $this->urls as $pattern => $action ){ list( $regex, $params ) = $buildRegex( $pattern ); if( ! preg_match( $regex, $uri, $matches ) ) continue; $a = array_slice($matches, 1); foreach( $a as $i=>$v ){ $args[ $params[$i] ] = $v; } return $action; } } $uri = strtolower(trim( $uri, '/')); if( ! $uri ) $uri = 'index'; $res = $this->get( $uri, 'action', TRUE); if( $res ) return $uri; return ''; } public function link( $name, array $params = array() ){ $s = new \Gaia\Serialize\QueryString; $args = array(); if( $this->urls ){ $createLink = function( $pattern, array & $params ) use( $s ) { $url = preg_replace_callback(Resolver::param_match, function($match) use ( & $params, $s ) { if( ! array_key_exists( $match[1], $params ) ) return ''; $ret = $s->serialize($params[ $match[1] ]); unset( $params[ $match[1] ] ); return $ret; }, preg_quote($pattern, '#')); return $url; }; $match = FALSE; foreach( $this->urls as $pattern => $a ){ if( $a == $name ){ $match = TRUE; break; } } if( $match ) { $url = $createLink( $pattern, $params ); $qs = $s->serialize($params); if( $qs ) $qs = '?' . $qs; return $url . $qs; } } $p = array(); foreach( $params as $k => $v ){ if( is_int( $k ) ){ $args[ $k ] = $s->serialize($v); } else { $p[ $k ] = $v; } } $params = $s->serialize($p); if( $params ) $params = '?' . $params; return '/' . $name . '/' . implode('/', $args ) . $params; } /** * convert a name into a file path. */ public function get($name, $type, $skip_lower = FALSE ) { if( ! $skip_lower ) $name = strtolower($name); if( strlen( $name ) < 1 ) $name = 'index'; $path = $this->appdir . $name . '.' . $type . '.php'; if( ! file_exists( $path ) ) return ''; return $path; } public function appdir(){ return $this->appdir; } public function setAppDir( $dir ){ return $this->appdir = $dir; } public function addURL( $pattern, $action ){ $this->urls[ '/' . trim($pattern, '/') ] = $action; } public function setURLS( array $urls ){ $this->urls = array(); foreach( $urls as $pattern => $action ) { $this->addURL( $pattern, $action ); } } public function urls(){ return $this->urls; } } // EOF
bsd-3-clause
mandrewcito/EOpenCV
scriptExamples/gaussianFilter.py
826
''' script @ mandrewcito ''' import cv2 import numpy as np import sys def callback(x): x = cv2.getTrackbarPos('Kernel X','image') y = cv2.getTrackbarPos('Kernel Y','image') sigma = cv2.getTrackbarPos('sigma/100','image') img =cv2.GaussianBlur(imgOrig,(x,y),sigma/100.0) cv2.imshow('image',img) # Get the total number of args passed to the demo.py total = len(sys.argv) # Get the arguments list cmdargs = str(sys.argv) cv2.namedWindow('image',cv2.CV_WINDOW_AUTOSIZE) # create trackbars for color change cv2.createTrackbar('Kernel X','image',1,100,callback) cv2.createTrackbar('Kernel Y','image',1,100,callback) cv2.createTrackbar('sigma/100','image',0,1000,callback) imgOrig = cv2.imread(sys.argv[1]) img=imgOrig cv2.startWindowThread() cv2.imshow('image',img) cv2.waitKey(0) & 0xFF cv2.destroyAllWindows()
bsd-3-clause
eandbsoftware/phpbms
modules/bms/report/lineitems_totals.php
18530
<?php /* $Rev: 373 $ | $LastChangedBy: nate $ $LastChangedDate: 2008-01-04 12:54:39 -0700 (Fri, 04 Jan 2008) $ +-------------------------------------------------------------------------+ | Copyright (c) 2004 - 2007, Kreotek LLC | | All rights reserved. | +-------------------------------------------------------------------------+ | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are | | met: | | | | - Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | | | - Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | | | - Neither the name of Kreotek LLC nor the names of its contributore may | | be used to endorse or promote products derived from this software | | without specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A | | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | | | +-------------------------------------------------------------------------+ */ require("../../../include/session.php"); class totalReport{ var $selectcolumns; var $selecttable; var $whereclause=""; var $group=""; var $showinvoices=false; var $showlineitems=false; var $padamount=20; function totalReport($db,$variables = NULL){ $this->db = $db; // first we define the available groups $this->addGroup("Invoice ID","invoices.id"); //0 $this->addGroup("Product","concat(products.partnumber,' - ',products.partname)"); //1 $this->addGroup("Product Category","concat(productcategories.id,' - ',productcategories.name)",NULL,"INNER JOIN productcategories ON products.categoryid=productcategories.id"); //2 $this->addGroup("Invoice Date - Year","YEAR(invoices.invoicedate)"); //3 $this->addGroup("Invoice Date - Quarter","QUARTER(invoices.invoicedate)"); //4 $this->addGroup("Invoice Date - Month","MONTH(invoices.invoicedate)"); //5 $this->addGroup("Invoice Date","invoices.invoicedate","date"); //6 $this->addGroup("Order Date - Year","YEAR(invoices.orderdate)"); //7 $this->addGroup("Order Date - Quarter","QUARTER(invoices.orderdate)");//8 $this->addGroup("Order Date - Month","MONTH(invoices.orderdate)");//9 $this->addGroup("Order Date","invoices.orderdate","date");//10 $this->addGroup("Client","if(clients.lastname!='',concat(clients.lastname,', ',clients.firstname,if(clients.company!='',concat(' (',clients.company,')'),'')),clients.company)");//11 $this->addGroup("Client Sales Person","concat(salesPerson.firstname,' ',salesPerson.lastname)",NULL, "LEFT JOIN users AS salesPerson ON clients.salesmanagerid = salesPerson.id");//12 $this->addGroup("Client Lead Source","clients.leadsource");//13 $this->addGroup("Invoice Lead Source","invoices.leadsource");//14 $this->addGroup("Payment Method","paymentmethods.name");//15 $this->addGroup("Shipping Method","shippingmethods.name");//16 $this->addGroup("Invoice Shipping Country","invoices.country");//17 $this->addGroup("Invoice Shipping State / Province","invoices.state");//18 $this->addGroup("Invoice Shipping Postal Code","invoices.postalcode");//19 $this->addGroup("Invoice Shipping City","invoices.city");//20 $this->addGroup("Web Order","invoices.weborder","boolean");//21 //next we do the columns $this->addColumn("Record Count","count(lineitems.id)");//0 $this->addColumn("Extended Price","sum(lineitems.unitprice*lineitems.quantity)","currency");//1 $this->addColumn("Average Extended Price","avg(lineitems.unitprice*lineitems.quantity)","currency");//2 $this->addColumn("Unit Price","sum(lineitems.unitprice)","currency");//3 $this->addColumn("Average Unit Price","avg(lineitems.unitprice)","currency");//4 $this->addColumn("Quantity","sum(lineitems.quantity)","real");//5 $this->addColumn("Average Quantity","avg(lineitems.quantity)","real");//6 $this->addColumn("Unit Cost","sum(lineitems.unitcost)","currency");//7 $this->addColumn("Average Unit Cost","avg(lineitems.unitcost)","currency");//8 $this->addColumn("Extended Cost","sum(lineitems.unitcost*lineitems.quantity)","currency");//9 $this->addColumn("Average Extended Cost","avg(lineitems.unitcost*lineitems.quantity)","currency");//10 $this->addColumn("Unit Weight","sum(lineitems.unitweight)","real");//11 $this->addColumn("Average Unit Weight","avg(lineitems.unitweight)","real");//12 $this->addColumn("Extended Unit Weight","sum(lineitems.unitweight*lineitems.quantity)","real");//13 $this->addColumn("Extended Average Unit Weight","avg(lineitems.unitweight*lineitems.quantity)","real");//14 if($variables){ $tempArray = explode("::", $variables["columns"]); foreach($tempArray as $id) $this->selectcolumns[] = $this->columns[$id]; $this->selectcolumns = array_reverse($this->selectcolumns); //change $this->selecttable="(((((lineitems left join products on lineitems.productid=products.id) inner join invoices on lineitems.invoiceid=invoices.id) inner join clients on invoices.clientid=clients.id) LEFT JOIN shippingmethods ON shippingmethods.name=invoices.shippingmethodid) LEFT JOIN paymentmethods ON paymentmethods.name=invoices.paymentmethodid) "; if($variables["groupings"] !== ""){ $this->group = explode("::",$variables["groupings"]); $this->group = array_reverse($this->group); } else $this->group = array(); foreach($this->group as $grp){ if($this->groupings[$grp]["table"]) $this->selecttable="(".$this->selecttable." ".$this->groupings[$grp]["table"].")"; } $this->whereclause=$_SESSION["printing"]["whereclause"]; if($this->whereclause=="") $this->whereclause="WHERE invoices.id!=-1"; switch($variables["showwhat"]){ case "invoices": $this->showinvoices = true; $this->showlineitems = false; break; case "lineitems": $this->showinvoices = true; $this->showlineitems = true; break; default: $this->showinvoices = false; $this->showlineitems = false; }// endswitch if($this->whereclause!="") $this->whereclause=" WHERE (".substr($this->whereclause,6).") "; }// endif }//end method function addGroup($name, $field, $format = NULL, $tableAddition = NULL){ $temp = array(); $temp["name"] = $name; $temp["field"] = $field; $temp["format"] = $format; $temp["table"] = $tableAddition; $this->groupings[] = $temp; }//end method function addColumn($name, $field, $format = NULL){ $temp = array(); $temp["name"] = $name; $temp["field"] = $field; $temp["format"] = $format; $this->columns[] = $temp; }//end method function showReportTable(){ ?><table border="0" cellspacing="0" cellpadding="0"> <tr> <th>&nbsp;</th> <?php foreach($this->selectcolumns as $thecolumn){ ?><th align="right"><?php echo $thecolumn["name"]?></th><?php }//end foreach ?> </tr> <?php $this->showGroup($this->group,"",10);?> <?php $this->showGrandTotals();?> </table> <?php } function showGrandTotals(){ $querystatement="SELECT "; foreach($this->selectcolumns as $thecolumn) $querystatement.=$thecolumn["field"]." AS `".$thecolumn["name"]."`,"; $querystatement.=" count(lineitems.id) as thecount "; $querystatement.=" FROM ".$this->selecttable.$this->whereclause; $queryresult=$this->db->query($querystatement); $therecord=$this->db->fetchArray($queryresult); ?> <tr> <td class="grandtotals" align="right">Totals: (<?php echo $therecord["thecount"]?>)</td> <?php foreach($this->selectcolumns as $thecolumn){ ?><td align="right" class="grandtotals"><?php echo formatVariable($therecord[$thecolumn["name"]],$thecolumn["format"])?></td><?php }//end foreach ?> </tr> <?php } function showGroup($group,$where,$indent){ if(!$group){ if($this->showlineitems) $this->showLineItems($where,$indent+$this->padamount); } else { $groupby = array_pop($group); $querystatement="SELECT "; foreach($this->selectcolumns as $thecolumn) $querystatement.=$thecolumn["field"]." AS `".$thecolumn["name"]."`,"; $querystatement .= $this->groupings[$groupby]["field"]." AS thegroup, count(lineitems.id) as thecount "; $querystatement .= " FROM ".$this->selecttable.$this->whereclause.$where." GROUP BY ".$this->groupings[$groupby]["field"]; $queryresult=$this->db->query($querystatement); while($therecord=$this->db->fetchArray($queryresult)){ $showbottom=true; if($group or $this->showinvoices) { $showbottom=false; ?> <tr><td colspan="<?php echo (count($this->selectcolumns)+1)?>" class="group" style="padding-left:<?php echo ($indent+2)?>px;"><?php echo $this->groupings[$groupby]["name"].": <strong>".formatVariable($therecord["thegroup"],$this->groupings[$groupby]["format"])."</strong>"?>&nbsp;</td></tr> <?php }//endif if($group) { $whereadd = $where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\""; if(!$therecord["thegroup"]) $whereadd .= " OR ISNULL(".$this->groupings[$groupby]["field"].")"; $whereadd .= ")"; $this->showGroup($group,$whereadd,$indent+$this->padamount); } elseif($this->showlineitems) { if($therecord["thegroup"]) $this->showLineItems($where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\")",$indent+$this->padamount); else $this->showLineItems($where." AND (".$this->groupings[$groupby]["field"]."= \"".$therecord["thegroup"]."\" or isnull(".$this->groupings[$groupby]["field"].") )",$indent+$this->padamount); }//endif ?> <tr> <td width="100%" style=" <?php echo "padding-left:".($indent+2)."px"; ?>" class="groupFooter"> <?php echo $this->groupings[$groupby]["name"].": <strong>".formatVariable($therecord["thegroup"],$this->groupings[$groupby]["format"])."</strong>&nbsp;";?> </td> <?php foreach($this->selectcolumns as $thecolumn){ ?><td align="right" class="groupFooter"><?php echo formatVariable($therecord[$thecolumn["name"]],$thecolumn["format"])?></td><?php }//end foreach ?> </tr> <?php }//end while }//endif }//end function function showLineItems($where,$indent){ $querystatement="SELECT lineitems.invoiceid, if(clients.lastname!=\"\",concat(clients.lastname,\", \",clients.firstname,if(clients.company!=\"\",concat(\" (\",clients.company,\")\"),\"\")),clients.company) as thename, invoices.invoicedate, invoices.orderdate, lineitems.id,products.partnumber,products.partname,quantity,lineitems.unitprice,quantity*lineitems.unitprice as extended FROM ".$this->selecttable.$this->whereclause.$where." GROUP BY lineitems.id "; $queryresult=$this->db->query($querystatement); if($this->db->numRows($queryresult)){ ?> <tr><td class="invoices" style="padding-left:<?php echo ($indent+2)?>px;"> <table border="0" cellspacing="0" cellpadding="0" id="lineitems"> <tr> <th align="left">id</th> <th align="left">date</th> <th width="20%" align="left" >client</th> <th width="60%" align="left">product</th> <th width="9%" align="right" nowrap="nowrap">price</th> <th width="8%" align="right" nowrap="nowrap">qty.</th> <th width="7%" align="right" nowrap="nowrap">ext.</th> </tr> <?php while($therecord=$this->db->fetchArray($queryresult)){ ?> <tr> <td nowrap="nowrap"><?php echo $therecord["invoiceid"]?></td> <td nowrap="nowrap"><?php if($therecord["invoicedate"]) echo formatFromSQLDate($therecord["invoicedate"]); else echo "<strong>".formatFromSQLDate($therecord["orderdate"])."</strong>";?></td> <td><?php echo $therecord["thename"]?></td> <td width="60%" nowrap="nowrap"><?php echo $therecord["partnumber"]?>&nbsp;&nbsp;<?php echo $therecord["partname"]?></td> <td width="9%" align="right" nowrap="nowrap"><?php echo numberToCurrency($therecord["unitprice"])?></td> <td width="8%" align="center" nowrap="nowrap"><?php echo formatVariable($therecord["quantity"],"real")?></td> <td width="7%" align="right" nowrap="nowrap"><?php echo numberToCurrency($therecord["extended"])?></td> </tr> <?php }// endwhile ?></table></td> <?php for($i=1;$i < count($this->selectcolumns); $i++) echo "<td>&nbsp;</td>" ?> </tr><?php }// endif }//end method function showReport(){ if($_POST["reporttitle"]) $pageTitle = $_POST["reporttitle"]; else $pageTitle = "Line Item Totals"; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="<?php echo APP_PATH ?>common/stylesheet/<?php echo STYLESHEET ?>/pages/totalreports.css" rel="stylesheet" type="text/css" /> <title><?php echo $pageTitle?></title> </head> <body> <div id="toprint"> <h1><span><?php echo $pageTitle?></span></h1> <h2>Source: <?php echo $_SESSION["printing"]["dataprint"]?></h2> <h2>Date: <?php echo dateToString(mktime())." ".timeToString(mktime())?></h2> <?php $this->showReportTable();?> </div> </body> </html><?php }// end method function showOptions($what){ ?><option value="0">----- Choose One -----</option> <?php $i=0; foreach($this->$what as $value){ ?><option value="<?php echo $i+1; ?>"><?php echo $value["name"];?></option> <?php $i++; }// endforeach }//end mothd function showSelectScreen(){ global $phpbms; $pageTitle="Line Items Total"; $phpbms->showMenu = false; $phpbms->cssIncludes[] = "pages/totalreports.css"; $phpbms->jsIncludes[] = "modules/bms/javascript/totalreports.js"; include("header.php"); ?> <div class="bodyline"> <h1>Line Items Total Options</h1> <form id="GroupForm" action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" name="GroupForm"> <fieldset> <legend>report</legend> <p> <label for="reporttitle">report title</label><br /> <input type="text" name="reporttitle" id="reporttitle" size="45"/> </p> </fieldset> <fieldset> <legend>groupings</legend> <input id="groupings" type="hidden" name="groupings"/> <div id="theGroups"> <div id="Group1"> <select id="Group1Field"> <?php $this->showOptions("groupings")?> </select> <button type="button" id="Group1Minus" class="graphicButtons buttonMinusDisabled"><span>-</span></button> <button type="button" id="Group1Plus" class="graphicButtons buttonPlus"><span>+</span></button> </div> </div> </fieldset> <fieldset> <legend>columns</legend> <input id="columns" type="hidden" name="columns"/> <div id="theColumns"> <div id="Column1"> <select id="Column1Field"> <?php $this->showOptions("columns")?> </select> <button type="button" id="Column1Minus" class="graphicButtons buttonMinusDisabled"><span>-</span></button> <button type="button" id="Column1Plus" class="graphicButtons buttonPlus"><span>+</span></button> </div> </div> </fieldset> <fieldset> <legend>Options</legend> <p> <label for="showwhat">information shown</label><br /> <select name="showwhat" id="showwhat"> <option selected="selected" value="totals">Totals Only</option> <option value="invoices">Invoices</option> <option value="lineitems">Invoices &amp; Line Items</option> </select> </p> </fieldset> <p align="right"> <button id="print" type="button" class="Buttons">Print</button> <button id="cancel" type="button" class="Buttons">Cancel</button> </p> </form> </div> <?php include("footer.php"); }//end method }//end class // Processing =================================================================================================================== if(!isset($dontProcess)){ if(isset($_POST["columns"])){ $myreport= new totalReport($db,$_POST); $myreport->showReport(); } else { $myreport = new totalReport($db); $myreport->showSelectScreen(); } }?>
bsd-3-clause
wukchung/Home-development
documentation/api/core/db_Test_PHPUnit_ControllerTestCase.html
204934
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script><script type="text/javascript" src="js/jquery.cookie.js"></script><script type="text/javascript" src="js/jquery.treeview.js"></script><script type="text/javascript"> $(document).ready(function() { $(".filetree").treeview({ collapsed: true, persist: "cookie" }); $("#accordion").accordion({ collapsible: true, autoHeight: false, fillSpace: true }); $(".tabs").tabs(); }); </script></head><body><div xmlns="" class="content"> <div class="sub-page-main-header-api-documentation"><h2>API Documentation</h2></div> <div class="dotted-line"></div> </div> <div xmlns="" id="content"> <script type="text/javascript" src="js/menu.js"></script><script> $(document).ready(function() { $('a.gripper').click(function() { $(this).nextAll('div.code-tabs').slideToggle(); $(this).children('img').toggle(); return false; }); $('div.code-tabs').hide(); $('a.gripper').show(); $('div.file-nav').show(); }); </script><h1 class="file">Test/PHPUnit/ControllerTestCase.php</h1> <div class="file-nav"><ul id="file-nav"> <li><a href="#top">Global</a></li> <li> <a href="#classes"><img src="images/icons/class.png" height="14"> Classes </a><ul><li><a href="#%5CZend_Test_PHPUnit_ControllerTestCase">\Zend_Test_PHPUnit_ControllerTestCase</a></li></ul> </li> </ul></div> <a name="top"></a><div id="file-description"> <p class="short-description">Zend Framework</p> <div class="long-description"><p>LICENSE</p> <p>This source file is subject to the new BSD license that is bundled with this package in the file LICENSE.txt. It is also available through the world-wide-web at this URL: http://framework.zend.com/license/new-bsd If you did not receive a copy of the license and are unable to obtain it through the world-wide-web, please send an email to [email protected] so we can send you a copy immediately.</p> </div> </div> <dl class="file-info"> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Test   </dd> <dt>version</dt> <dd>$Id: ControllerTestCase.php 24213 2011-07-08 21:16:45Z rdohms $   </dd> </dl> <a name="classes"></a><a id="\Zend_Test_PHPUnit_ControllerTestCase"></a><h2 class="class">\Zend_Test_PHPUnit_ControllerTestCase<div class="to-top"><a href="#top">jump to top</a></div> </h2> <div class="class"> <p class="short-description">Functional testing scaffold for MVC applications</p> <div class="long-description"> </div> <dl class="class-info"> <dt>Extends from</dt> <dd>\PHPUnit_Framework_TestCase</dd> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Test   </dd> <dt>subpackage</dt> <dd>PHPUnit   </dd> <dt>uses</dt> <dd>\PHPUnit_Framework_TestCase   </dd> </dl> <h3>Properties</h3> <div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$_frontController"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">\Zend_Controller_Front  <span class="highlight">$_frontController</span>= '' </code><div class="description"> <p class="short-description"></p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd><a href="db_Controller_Front.html#%5CZend_Controller_Front">\Zend_Controller_Front</a></dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$_query"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">\Zend_Dom_Query  <span class="highlight">$_query</span>= '' </code><div class="description"> <p class="short-description"></p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd><a href="db_Dom_Query.html#%5CZend_Dom_Query">\Zend_Dom_Query</a></dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$_request"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">\Zend_Controller_Request_Abstract  <span class="highlight">$_request</span>= '' </code><div class="description"> <p class="short-description"></p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd><a href="db_Controller_Request_Abstract.html#%5CZend_Controller_Request_Abstract">\Zend_Controller_Request_Abstract</a></dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$_response"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">\Zend_Controller_Response_Abstract  <span class="highlight">$_response</span>= '' </code><div class="description"> <p class="short-description"></p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd><a href="db_Controller_Response_Abstract.html#%5CZend_Controller_Response_Abstract">\Zend_Controller_Response_Abstract</a></dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$_xpathNamespaces"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">array  <span class="highlight">$_xpathNamespaces</span>= 'array' </code><div class="description"> <p class="short-description">XPath namespaces</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Default value</strong><code>array</code><strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>array</dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::$bootstrap"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public">mixed  <span class="highlight">$bootstrap</span>= '' </code><div class="description"> <p class="short-description"></p>Bootstrap file path or callback</div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>mixed</dd> </dl> </div> <div class="clear"></div> </div> </div> <h3>Methods</h3> <div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::__construct()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__construct</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::__get()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__get</span><span class="nb-faded-text">( mixed $name ) </span> : void</code><div class="description"><p class="short_description">Overloading for common properties</p></div> <div class="code-tabs"> <div class="long-description"><p>Provides overloading for request, response, and frontController objects.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$name</th> <td>mixed</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::__set()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__set</span><span class="nb-faded-text">( string $name, mixed $value ) </span> : void</code><div class="description"><p class="short_description">Overloading: prevent overloading to special properties</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$name</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$value</th> <td>mixed</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::_incrementAssertionCount()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_incrementAssertionCount</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"><p class="short_description">Increment assertion count</p></div> <div class="code-tabs"><div class="long-description"> </div></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::_resetPlaceholders()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">_resetPlaceholders</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"><p class="short_description">Rest all view placeholders</p></div> <div class="code-tabs"><div class="long-description"> </div></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::addToAssertionCount()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">addToAssertionCount</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::any()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">any</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::anything()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">anything</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::arrayHasKey()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">arrayHasKey</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAction()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAction</span><span class="nb-faded-text">( string $action, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request used the given action</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$action</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertArrayHasKey()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertArrayHasKey</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertArrayNotHasKey()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertArrayNotHasKey</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeContains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeContains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeContainsOnly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeContainsOnly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeEmpty()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeEmpty</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeGreaterThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeGreaterThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeGreaterThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeGreaterThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeInstanceOf()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeInstanceOf</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeInternalType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeInternalType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeLessThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeLessThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeLessThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeLessThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotContains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotContains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotContainsOnly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotContainsOnly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotEmpty()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotEmpty</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotInstanceOf()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotInstanceOf</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotInternalType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotInternalType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotSame()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotSame</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeNotType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeNotType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeSame()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeSame</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertAttributeType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertAttributeType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertClassHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertClassHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertClassHasStaticAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertClassHasStaticAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertClassNotHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertClassNotHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertClassNotHasStaticAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertClassNotHasStaticAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertContains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertContains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertContainsOnly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertContainsOnly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertController()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertController</span><span class="nb-faded-text">( string $controller, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request used the given controller</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$controller</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertEmpty()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertEmpty</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertEqualXMLStructure()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertEqualXMLStructure</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertFalse()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertFalse</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertFileEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertFileEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertFileExists()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertFileExists</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertFileNotEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertFileNotEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertFileNotExists()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertFileNotExists</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertGreaterThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertGreaterThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertGreaterThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertGreaterThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertHeader()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertHeader</span><span class="nb-faded-text">( string $header, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header exists</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertHeaderContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertHeaderContains</span><span class="nb-faded-text">( string $header, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header exists and contains the given string</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertHeaderRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertHeaderRegex</span><span class="nb-faded-text">( string $header, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header exists and matches the given pattern</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertInstanceOf()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertInstanceOf</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertInternalType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertInternalType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertLessThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertLessThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertLessThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertLessThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertModule()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertModule</span><span class="nb-faded-text">( string $module, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request used the given module</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$module</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotAction()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotAction</span><span class="nb-faded-text">( string $action, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request did NOT use the given action</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$action</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotContains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotContains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotContainsOnly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotContainsOnly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotController()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotController</span><span class="nb-faded-text">( string $controller, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request did NOT use the given controller</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$controller</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotEmpty()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotEmpty</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotHeader()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotHeader</span><span class="nb-faded-text">( string $header, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header does not exist</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotHeaderContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotHeaderContains</span><span class="nb-faded-text">( string $header, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header does not exist and/or does not contain the given string</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotHeaderRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotHeaderRegex</span><span class="nb-faded-text">( string $header, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response header does not exist and/or does not match the given regex</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$header</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotInstanceOf()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotInstanceOf</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotInternalType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotInternalType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotModule()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotModule</span><span class="nb-faded-text">( string $module, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the last handled request did NOT use the given module</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$module</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotNull()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotNull</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotQuery()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotQuery</span><span class="nb-faded-text">( string $path, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotQueryContentContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotQueryContentContains</span><span class="nb-faded-text">( string $path, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; node should NOT contain content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em>content that should NOT be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotQueryContentRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotQueryContentRegex</span><span class="nb-faded-text">( string $path, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; node should NOT match content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em>pattern that should NOT be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotQueryCount()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotQueryCount</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; should NOT contain exact number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Number of nodes that should NOT match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotRedirect()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotRedirect</span><span class="nb-faded-text">( string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that response is NOT a redirect</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotRedirectRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotRedirectRegex</span><span class="nb-faded-text">( string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that redirect location does not match pattern</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$pattern</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotRedirectTo()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotRedirectTo</span><span class="nb-faded-text">( string $url, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that response does not redirect to given URL</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$url</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotRegExp()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotRegExp</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotResponseCode()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotResponseCode</span><span class="nb-faded-text">( int $code, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response code</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$code</th> <td>int</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotRoute()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotRoute</span><span class="nb-faded-text">( string $route, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the route matched is NOT as specified</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$route</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotSame()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotSame</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotTag()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotTag</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotXpath()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotXpath</span><span class="nb-faded-text">( string $path, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotXpathContentContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotXpathContentContains</span><span class="nb-faded-text">( string $path, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; node should NOT contain content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em>content that should NOT be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotXpathContentRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotXpathContentRegex</span><span class="nb-faded-text">( string $path, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; node should NOT match content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em>pattern that should NOT be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNotXpathCount()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNotXpathCount</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; should NOT contain exact number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Number of nodes that should NOT match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertNull()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertNull</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertObjectHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertObjectHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertObjectNotHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertObjectNotHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertPostConditions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">assertPostConditions</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertPreConditions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">assertPreConditions</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQuery()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQuery</span><span class="nb-faded-text">( string $path, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQueryContentContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQueryContentContains</span><span class="nb-faded-text">( string $path, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; node should contain content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em>content that should be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQueryContentRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQueryContentRegex</span><span class="nb-faded-text">( string $path, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; node should match content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em>Pattern that should be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQueryCount()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQueryCount</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; should contain exact number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQueryCountMax()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQueryCountMax</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; should contain no more than this number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Maximum number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertQueryCountMin()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertQueryCountMin</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against DOM selection; should contain at least this number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>CSS selector path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Minimum number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertRedirect()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertRedirect</span><span class="nb-faded-text">( string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that response is a redirect</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertRedirectRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertRedirectRegex</span><span class="nb-faded-text">( string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that redirect location matches pattern</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$pattern</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertRedirectTo()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertRedirectTo</span><span class="nb-faded-text">( string $url, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that response redirects to given URL</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$url</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertRegExp()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertRegExp</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertResponseCode()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertResponseCode</span><span class="nb-faded-text">( int $code, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert response code</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$code</th> <td>int</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertRoute()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertRoute</span><span class="nb-faded-text">( string $route, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert that the specified route was used</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$route</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertSame()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertSame</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertSelectCount()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertSelectCount</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertSelectEquals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertSelectEquals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertSelectRegExp()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertSelectRegExp</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringEndsNotWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringEndsNotWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringEndsWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringEndsWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringEqualsFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringEqualsFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringMatchesFormat()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringMatchesFormat</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringMatchesFormatFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringMatchesFormatFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringNotEqualsFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringNotEqualsFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringNotMatchesFormat()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringNotMatchesFormat</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringNotMatchesFormatFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringNotMatchesFormatFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringStartsNotWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringStartsNotWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertStringStartsWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertStringStartsWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertTag()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertTag</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertThat()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertThat</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertTrue()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertTrue</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlFileEqualsXmlFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlFileEqualsXmlFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlFileNotEqualsXmlFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlFileNotEqualsXmlFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlStringEqualsXmlFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlStringEqualsXmlFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlStringEqualsXmlString()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlStringEqualsXmlString</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlStringNotEqualsXmlFile()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlStringNotEqualsXmlFile</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXmlStringNotEqualsXmlString()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXmlStringNotEqualsXmlString</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpath()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpath</span><span class="nb-faded-text">( string $path, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpathContentContains()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpathContentContains</span><span class="nb-faded-text">( string $path, string $match, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; node should contain content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$match</th> <td>string</td> <td><em>content that should be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpathContentRegex()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpathContentRegex</span><span class="nb-faded-text">( string $path, string $pattern, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; node should match content</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$pattern</th> <td>string</td> <td><em>Pattern that should be contained in matched nodes</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpathCount()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpathCount</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; should contain exact number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpathCountMax()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpathCountMax</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; should contain no more than this number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Maximum number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::assertXpathCountMin()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">assertXpathCountMin</span><span class="nb-faded-text">( string $path, string $count, string $message ) </span> : void</code><div class="description"><p class="short_description">Assert against XPath selection; should contain at least this number of nodes</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$path</th> <td>string</td> <td><em>XPath path</em></td> </tr> <tr> <th>$count</th> <td>string</td> <td><em>Minimum number of nodes that should match</em></td> </tr> <tr> <th>$message</th> <td>string</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::at()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">at</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::atLeastOnce()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">atLeastOnce</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::attribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">attribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::attributeEqualTo()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">attributeEqualTo</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::bootstrap()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">bootstrap</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">final</span><p class="short_description">Bootstrap the front controller</p> </div> <div class="code-tabs"><div class="long-description"><p>Resets the front controller, and then bootstraps it.</p> <p>If {@link $bootstrap} is a callback, executes it; if it is a file, it include's it. When done, sets the test case request and response objects into the front controller.</p> </div></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::classHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">classHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::classHasStaticAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">classHasStaticAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::contains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">contains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::containsOnly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">containsOnly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::count()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">count</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::createResult()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">createResult</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::dataToString()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">dataToString</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::dispatch()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">dispatch</span><span class="nb-faded-text">( string|null $url = null ) </span> : void</code><div class="description"><p class="short_description">Dispatch the MVC</p></div> <div class="code-tabs"> <div class="long-description"><p>If a URL is provided, sets it as the request URI in the request object. Then sets test case request and response objects in front controller, disables throwing exceptions, and disables returning the response. Finally, dispatches the front controller.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$url</th> <td>string|null</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::equalTo()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">equalTo</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::exactly()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">exactly</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::fail()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">fail</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::fileExists()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">fileExists</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getAnnotations()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getAnnotations</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getCount()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getCount</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getDataSetAsString()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">getDataSetAsString</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getExpectedException()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getExpectedException</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getFrontController()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getFrontController</span><span class="nb-faded-text">( ) </span> : <a href="db_Controller_Front.html#%5CZend_Controller_Front">\Zend_Controller_Front</a></code><div class="description"><p class="short_description">Retrieve front controller instance</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Controller_Front.html#%5CZend_Controller_Front">\Zend_Controller_Front</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getMock()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getMock</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getMockBuilder()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getMockBuilder</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getMockClass()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">getMockClass</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getMockForAbstractClass()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getMockForAbstractClass</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getMockFromWsdl()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">getMockFromWsdl</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getName()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getName</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getNumAssertions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getNumAssertions</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getQuery()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getQuery</span><span class="nb-faded-text">( ) </span> : <a href="db_Dom_Query.html#%5CZend_Dom_Query">\Zend_Dom_Query</a></code><div class="description"><p class="short_description">Retrieve DOM query object</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Dom_Query.html#%5CZend_Dom_Query">\Zend_Dom_Query</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getRequest()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getRequest</span><span class="nb-faded-text">( ) </span> : <a href="db_Controller_Request_HttpTestCase.html#%5CZend_Controller_Request_HttpTestCase">\Zend_Controller_Request_HttpTestCase</a></code><div class="description"><p class="short_description">Retrieve test case request object</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Controller_Request_HttpTestCase.html#%5CZend_Controller_Request_HttpTestCase">\Zend_Controller_Request_HttpTestCase</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getResponse()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getResponse</span><span class="nb-faded-text">( ) </span> : <a href="db_Controller_Response_HttpTestCase.html#%5CZend_Controller_Response_HttpTestCase">\Zend_Controller_Response_HttpTestCase</a></code><div class="description"><p class="short_description">Retrieve test case response object</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Controller_Response_HttpTestCase.html#%5CZend_Controller_Response_HttpTestCase">\Zend_Controller_Response_HttpTestCase</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getResult()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getResult</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getStatus()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getStatus</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getStatusMessage()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getStatusMessage</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::getTestResultObject()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getTestResultObject</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::greaterThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">greaterThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::greaterThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">greaterThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::handleDependencies()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">handleDependencies</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::hasFailed()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">hasFailed</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::identicalTo()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">identicalTo</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::iniSet()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">iniSet</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isEmpty()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isEmpty</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isFalse()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isFalse</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isInstanceOf()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isInstanceOf</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isNull()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isNull</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isTrue()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isTrue</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::isType()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">isType</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::lessThan()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">lessThan</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::lessThanOrEqual()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">lessThanOrEqual</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::logicalAnd()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">logicalAnd</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::logicalNot()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">logicalNot</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::logicalOr()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">logicalOr</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::logicalXor()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">logicalXor</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::markTestIncomplete()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">markTestIncomplete</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::markTestSkipped()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">markTestSkipped</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::matches()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">matches</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::matchesRegularExpression()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">matchesRegularExpression</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::never()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">never</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::objectHasAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">objectHasAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::onConsecutiveCalls()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">onConsecutiveCalls</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::onNotSuccessfulTest()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">onNotSuccessfulTest</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::once()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">once</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::prepareTemplate()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">prepareTemplate</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::readAttribute()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">readAttribute</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::registerXpathNamespaces()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">registerXpathNamespaces</span><span class="nb-faded-text">( array $xpathNamespaces ) </span> : void</code><div class="description"><p class="short_description">Register XPath namespaces</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$xpathNamespaces</th> <td>array</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::reset()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">reset</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"><p class="short_description">Reset MVC state</p></div> <div class="code-tabs"> <div class="long-description"><p>Creates new request/response objects, resets the front controller instance, and resets the action helper broker.</p> </div> <strong>Details</strong><dl class="function-info"> <dt>todo</dt> <dd>Need to update Zend_Layout to add a resetInstance() method   </dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::resetCount()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">resetCount</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::resetRequest()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">resetRequest</span><span class="nb-faded-text">( ) </span> : <a href="db_Test_PHPUnit_ControllerTestCase.html#%5CZend_Test_PHPUnit_ControllerTestCase">\Zend_Test_PHPUnit_ControllerTestCase</a></code><div class="description"><p class="short_description">Reset the request object</p></div> <div class="code-tabs"> <div class="long-description"><p>Useful for test cases that need to test multiple trips to the server.</p> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Test_PHPUnit_ControllerTestCase.html#%5CZend_Test_PHPUnit_ControllerTestCase">\Zend_Test_PHPUnit_ControllerTestCase</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::resetResponse()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">resetResponse</span><span class="nb-faded-text">( ) </span> : <a href="db_Test_PHPUnit_ControllerTestCase.html#%5CZend_Test_PHPUnit_ControllerTestCase">\Zend_Test_PHPUnit_ControllerTestCase</a></code><div class="description"><p class="short_description">Reset the response object</p></div> <div class="code-tabs"> <div class="long-description"><p>Useful for test cases that need to test multiple trips to the server.</p> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Test_PHPUnit_ControllerTestCase.html#%5CZend_Test_PHPUnit_ControllerTestCase">\Zend_Test_PHPUnit_ControllerTestCase</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::returnArgument()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">returnArgument</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::returnCallback()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">returnCallback</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::returnValue()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">returnValue</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::run()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">run</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::runBare()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">runBare</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::runTest()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">runTest</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setBackupGlobals()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setBackupGlobals</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setBackupStaticAttributes()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setBackupStaticAttributes</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setDependencies()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setDependencies</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setDependencyInput()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setDependencyInput</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setExpectedException()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setExpectedException</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setExpectedExceptionFromAnnotation()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">setExpectedExceptionFromAnnotation</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setInIsolation()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setInIsolation</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setLocale()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">setLocale</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setName()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setName</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setPreserveGlobalState()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setPreserveGlobalState</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setResult()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setResult</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setRunTestInSeparateProcess()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setRunTestInSeparateProcess</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUp()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">setUp</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"><p class="short_description">Set up MVC app</p></div> <div class="code-tabs"><div class="long-description"><p>Calls {@link bootstrap()} by default</p> </div></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUpBeforeClass()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setUpBeforeClass</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUseErrorHandler()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setUseErrorHandler</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUseErrorHandlerFromAnnotation()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">setUseErrorHandlerFromAnnotation</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUseOutputBuffering()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setUseOutputBuffering</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::setUseOutputBufferingFromAnnotation()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">setUseOutputBufferingFromAnnotation</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::stringContains()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">stringContains</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::stringEndsWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">stringEndsWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::stringStartsWith()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">stringStartsWith</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::syntheticFail()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">syntheticFail</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::tearDown()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">tearDown</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::tearDownAfterClass()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">tearDownAfterClass</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::throwException()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">throwException</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <span class="attribute">static</span><p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::toString()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">toString</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::url()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">url</span><span class="nb-faded-text">( array $urlOptions = array, string $name = null, bool $reset = false, bool $encode = true ) </span> : void</code><div class="description"><p class="short_description">URL Helper</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$urlOptions</th> <td>array</td> <td><em></em></td> </tr> <tr> <th>$name</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$reset</th> <td>bool</td> <td><em></em></td> </tr> <tr> <th>$encode</th> <td>bool</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::urlizeOptions()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">urlizeOptions</span><span class="nb-faded-text">(  $urlOptions,  $actionControllerModuleOnly = true ) </span> : void</code><div class="description"><p class="short_description"></p></div> <div class="code-tabs"> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$urlOptions</th> <td></td> <td><em></em></td> </tr> <tr> <th>$actionControllerModuleOnly</th> <td></td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Test_PHPUnit_ControllerTestCase::verifyMockObjects()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected"><span class="highlight">verifyMockObjects</span><span class="nb-faded-text">( ) </span> : void</code><div class="description"> <p class="short_description"></p> <small>Inherited from: </small> </div> <div class="code-tabs"></div> <div class="clear"></div> </div> </div> </div> </div> <small xmlns="" class="footer">Documentation was generated by <a href="http://docblox-project.org">DocBlox 0.13.3</a>. </small></body></html>
bsd-3-clause
praekelt/vumi-go
go/base/static/js/test/components/actions.test.js
6932
describe("go.components.actions", function() { var actions = go.components.actions; var Model = go.components.models.Model; var testHelpers = go.testHelpers, assertRequest = testHelpers.rpc.assertRequest, response = testHelpers.rpc.response, noElExists = testHelpers.noElExists, oneElExists = testHelpers.oneElExists; describe("PopoverNotifierView", function() { var ActionView = actions.ActionView, PopoverNotifierView = actions.PopoverNotifierView; var action, notifier; beforeEach(function() { action = new ActionView({name: 'Crimp'}); action.$el.appendTo($('body')); notifier = new PopoverNotifierView({ delay: 0, busyWait: 0, action: action, bootstrap: { container: 'body', animation: false } }); sinon.stub( JST, 'components_notifiers_popover_busy', function() { return 'busy'; }); }); afterEach(function() { JST.components_notifiers_popover_busy.restore(); action.remove(); notifier.remove(); }); describe("when the action is invoked", function() { it("should show a notification", function() { assert(noElExists('.popover')); assert.equal(notifier.$el.text(), ''); action.trigger('invoke'); assert(oneElExists('.popover')); assert.equal(notifier.$el.text(), 'busy'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('notifier')); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert(!$popover.hasClass('info')); action.trigger('invoke'); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); }); }); describe("when the action is successful", function() { beforeEach(function() { action.trigger('invoke'); }); it("should show a notification", function() { action.trigger('success'); assert.include(notifier.$el.text(), 'Crimp successful.'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); action.trigger('success'); assert(!$popover.hasClass('error')); assert(!$popover.hasClass('info')); assert($popover.hasClass('notifier')); assert($popover.hasClass('success')); }); }); describe("when the action is unsuccessful", function() { beforeEach(function() { action.trigger('invoke'); }); it("should show a notification", function() { action.trigger('error'); assert.include(notifier.$el.text(), 'Crimp failed.'); }); it("set the appropriate class name on the popover element", function() { var $popover = notifier.popover.tip(); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('error')); assert($popover.hasClass('notifier')); assert($popover.hasClass('info')); action.trigger('error'); assert(!$popover.hasClass('success')); assert(!$popover.hasClass('info')); assert($popover.hasClass('notifier')); assert($popover.hasClass('error')); }); }); describe("when '.close' is clicked", function() { beforeEach(function() { action.trigger('success'); }); it("should close the popover", function() { assert(oneElExists('.popover')); notifier.$('.close').click(); assert(noElExists('.popover')); }); }); }); describe("ActionView", function() { var ActionView = actions.ActionView; var ToyActionView = ActionView.extend({ invoke: function() { this.trigger('invoke'); } }); var action; beforeEach(function() { action = new ToyActionView(); }); describe("when it is clicked", function() { it("should invoke its own action", function(done) { action.on('invoke', function() { done(); }); action.$el.click(); }); }); }); describe("SaveActionView", function() { var SaveActionView = actions.SaveActionView; var ToyModel = Model.extend({ url: '/test', methods: { create: {method: 's', params: ['a', 'b']} } }); var action; beforeEach(function() { action = new SaveActionView({ model: new ToyModel({a: 'foo', b: 'bar'}) }); }); describe(".invoke", function() { var server; beforeEach(function() { server = sinon.fakeServer.create(); }); afterEach(function() { server.restore(); }); it("should emit an 'invoke' event", function(done) { action.on('invoke', function() { done(); }); action.invoke(); }); it("should send its model's data to the server", function(done) { server.respondWith(function(req) { assertRequest(req, '/test', 's', ['foo', 'bar']); done(); }); action.invoke(); server.respond(); }); describe("when the request is successful", function() { it("should emit a 'success' event", function(done) { action.on('success', function() { done(); }); server.respondWith(response()); action.invoke(); server.respond(); }); }); describe("when the request is not successful", function() { it("should emit a 'failure' event", function(done) { action.on('error', function() { done(); }); server.respondWith([400, {}, '']); action.invoke(); server.respond(); }); }); }); }); describe("ResetActionView", function() { var ResetActionView = actions.ResetActionView; var action; beforeEach(function() { action = new ResetActionView({ model: new Model({a: 'foo', b: 'bar'}) }); }); describe(".invoke", function() { it("should emit an 'invoke' event", function(done) { action.on('invoke', function() { done(); }); action.invoke(); }); it("should reset its model to its initial state", function(done) { action.model.set('a', 'larp'); assert.deepEqual(action.model.toJSON(), {a: 'larp', b: 'bar'}); action.invoke(); action.once('success', function() { assert.deepEqual(action.model.toJSON(), {a: 'foo', b: 'bar'}); done(); }); }); }); }); });
bsd-3-clause
ekoontz/pgjdbc
org/postgresql/jdbc2/AbstractJdbc2Statement.java
126655
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2014, PostgreSQL Global Development Group * * *------------------------------------------------------------------------- */ package org.postgresql.jdbc2; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.*; import java.nio.charset.Charset; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TimerTask; import java.util.TimeZone; import java.util.Calendar; import org.postgresql.Driver; import org.postgresql.largeobject.*; import org.postgresql.core.*; import org.postgresql.core.types.*; import org.postgresql.util.ByteConverter; import org.postgresql.util.HStoreConverter; import org.postgresql.util.PGBinaryObject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.util.PGobject; import org.postgresql.util.GT; /** * This class defines methods of the jdbc2 specification. * The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Statement */ public abstract class AbstractJdbc2Statement implements BaseStatement { // only for testing purposes. even single shot statements will use binary transfers private boolean forceBinaryTransfers = Boolean.getBoolean("org.postgresql.forceBinary"); protected ArrayList batchStatements = null; protected ArrayList batchParameters = null; protected final int resultsettype; // the resultset type to return (ResultSet.TYPE_xxx) protected final int concurrency; // is it updateable or not? (ResultSet.CONCUR_xxx) protected int fetchdirection = ResultSet.FETCH_FORWARD; // fetch direction hint (currently ignored) private volatile TimerTask cancelTimerTask = null; /** * Does the caller of execute/executeUpdate want generated keys for this * execution? This is set by Statement methods that have generated keys * arguments and cleared after execution is complete. */ protected boolean wantsGeneratedKeysOnce = false; /** * Was this PreparedStatement created to return generated keys for every * execution? This is set at creation time and never cleared by * execution. */ public boolean wantsGeneratedKeysAlways = false; // The connection who created us protected BaseConnection connection; /** The warnings chain. */ protected SQLWarning warnings = null; /** The last warning of the warning chain. */ protected SQLWarning lastWarning = null; /** Maximum number of rows to return, 0 = unlimited */ protected int maxrows = 0; /** Number of rows to get in a batch. */ protected int fetchSize = 0; /** Timeout (in seconds) for a query */ protected int timeout = 0; protected boolean replaceProcessingEnabled = true; /** The current results. */ protected ResultWrapper result = null; /** The first unclosed result. */ protected ResultWrapper firstUnclosedResult = null; /** Results returned by a statement that wants generated keys. */ protected ResultWrapper generatedKeys = null; /** used to differentiate between new function call * logic and old function call logic * will be set to true if the server is < 8.1 or * if we are using v2 protocol * There is an exception to this where we are using v3, and the * call does not have an out parameter before the call */ protected boolean adjustIndex = false; /* * Used to set adjustIndex above */ protected boolean outParmBeforeFunc=false; // Static variables for parsing SQL when replaceProcessing is true. private static final short IN_SQLCODE = 0; private static final short IN_STRING = 1; private static final short IN_IDENTIFIER = 6; private static final short BACKSLASH = 2; private static final short ESC_TIMEDATE = 3; private static final short ESC_FUNCTION = 4; private static final short ESC_OUTERJOIN = 5; private static final short ESC_ESCAPECHAR = 7; protected final Query preparedQuery; // Query fragments for prepared statement. protected final ParameterList preparedParameters; // Parameter values for prepared statement. protected Query lastSimpleQuery; protected int m_prepareThreshold; // Reuse threshold to enable use of PREPARE protected int m_useCount = 0; // Number of times this statement has been used //Used by the callablestatement style methods private boolean isFunction; // functionReturnType contains the user supplied value to check // testReturn contains a modified version to make it easier to // check the getXXX methods.. private int []functionReturnType; private int []testReturn; // returnTypeSet is true when a proper call to registerOutParameter has been made private boolean returnTypeSet; protected Object []callResult; protected int maxfieldSize = 0; public ResultSet createDriverResultSet(Field[] fields, List tuples) throws SQLException { return createResultSet(null, fields, tuples, null); } public AbstractJdbc2Statement (AbstractJdbc2Connection c, int rsType, int rsConcurrency) throws SQLException { this.connection = c; this.preparedQuery = null; this.preparedParameters = null; this.lastSimpleQuery = null; forceBinaryTransfers |= c.getForceBinary(); resultsettype = rsType; concurrency = rsConcurrency; } public AbstractJdbc2Statement(AbstractJdbc2Connection connection, String sql, boolean isCallable, int rsType, int rsConcurrency) throws SQLException { this.connection = connection; this.lastSimpleQuery = null; String parsed_sql = replaceProcessing(sql); if (isCallable) parsed_sql = modifyJdbcCall(parsed_sql); this.preparedQuery = connection.getQueryExecutor().createParameterizedQuery(parsed_sql); this.preparedParameters = preparedQuery.createParameterList(); int inParamCount = preparedParameters.getInParameterCount() + 1; this.testReturn = new int[inParamCount]; this.functionReturnType = new int[inParamCount]; forceBinaryTransfers |= connection.getForceBinary(); resultsettype = rsType; concurrency = rsConcurrency; } public abstract ResultSet createResultSet(Query originalQuery, Field[] fields, List tuples, ResultCursor cursor) throws SQLException; public BaseConnection getPGConnection() { return connection; } public String getFetchingCursorName() { return null; } public int getFetchSize() { return fetchSize; } protected boolean wantsScrollableResultSet() { return resultsettype != ResultSet.TYPE_FORWARD_ONLY; } protected boolean wantsHoldableResultSet() { return false; } // // ResultHandler implementations for updates, queries, and either-or. // public class StatementResultHandler implements ResultHandler { private SQLException error; private ResultWrapper results; ResultWrapper getResults() { return results; } private void append(ResultWrapper newResult) { if (results == null) results = newResult; else results.append(newResult); } public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) { try { ResultSet rs = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor); append(new ResultWrapper(rs)); } catch (SQLException e) { handleError(e); } } public void handleCommandStatus(String status, int updateCount, long insertOID) { append(new ResultWrapper(updateCount, insertOID)); } public void handleWarning(SQLWarning warning) { AbstractJdbc2Statement.this.addWarning(warning); } public void handleError(SQLException newError) { if (error == null) error = newError; else error.setNextException(newError); } public void handleCompletion() throws SQLException { if (error != null) throw error; } } /* * Execute a SQL statement that retruns a single ResultSet * * @param sql typically a static SQL SELECT statement * @return a ResulSet that contains the data produced by the query * @exception SQLException if a database access error occurs */ public java.sql.ResultSet executeQuery(String p_sql) throws SQLException { if (preparedQuery != null) throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."), PSQLState.WRONG_OBJECT_TYPE); if (forceBinaryTransfers) { clearWarnings(); // Close any existing resultsets associated with this statement. while (firstUnclosedResult != null) { if (firstUnclosedResult.getResultSet() != null) firstUnclosedResult.getResultSet().close(); firstUnclosedResult = firstUnclosedResult.getNext(); } PreparedStatement ps = connection.prepareStatement(p_sql, resultsettype, concurrency, getResultSetHoldability()); ps.setMaxFieldSize(getMaxFieldSize()); ps.setFetchSize(getFetchSize()); ps.setFetchDirection(getFetchDirection()); AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) ps.executeQuery(); rs.registerRealStatement(this); result = firstUnclosedResult = new ResultWrapper(rs); return rs; } if (!executeWithFlags(p_sql, 0)) throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); if (result.getNext() != null) throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."), PSQLState.TOO_MANY_RESULTS); return (ResultSet)result.getResultSet(); } /* * A Prepared SQL query is executed and its ResultSet is returned * * @return a ResultSet that contains the data produced by the * * query - never null * @exception SQLException if a database access error occurs */ public java.sql.ResultSet executeQuery() throws SQLException { if (!executeWithFlags(0)) throw new PSQLException(GT.tr("No results were returned by the query."), PSQLState.NO_DATA); if (result.getNext() != null) throw new PSQLException(GT.tr("Multiple ResultSets were returned by the query."), PSQLState.TOO_MANY_RESULTS); return (ResultSet) result.getResultSet(); } /* * Execute a SQL INSERT, UPDATE or DELETE statement. In addition * SQL statements that return nothing such as SQL DDL statements * can be executed * * @param sql a SQL statement * @return either a row count, or 0 for SQL commands * @exception SQLException if a database access error occurs */ public int executeUpdate(String p_sql) throws SQLException { if (preparedQuery != null) throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."), PSQLState.WRONG_OBJECT_TYPE); if( isFunction ) { executeWithFlags(p_sql, 0); return 0; } executeWithFlags(p_sql, QueryExecutor.QUERY_NO_RESULTS); ResultWrapper iter = result; while (iter != null) { if (iter.getResultSet() != null) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } iter = iter.getNext(); } return getUpdateCount(); } /* * Execute a SQL INSERT, UPDATE or DELETE statement. In addition, * SQL statements that return nothing such as SQL DDL statements can * be executed. * * @return either the row count for INSERT, UPDATE or DELETE; or * * 0 for SQL statements that return nothing. * @exception SQLException if a database access error occurs */ public int executeUpdate() throws SQLException { if( isFunction ) { executeWithFlags(0); return 0; } executeWithFlags(QueryExecutor.QUERY_NO_RESULTS); ResultWrapper iter = result; while (iter != null) { if (iter.getResultSet() != null) { throw new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS); } iter = iter.getNext(); } return getUpdateCount(); } /* * Execute a SQL statement that may return multiple results. We * don't have to worry about this since we do not support multiple * ResultSets. You can use getResultSet or getUpdateCount to * retrieve the result. * * @param sql any SQL statement * @return true if the next result is a ResulSet, false if it is * an update count or there are no more results * @exception SQLException if a database access error occurs */ public boolean execute(String p_sql) throws SQLException { if (preparedQuery != null) throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."), PSQLState.WRONG_OBJECT_TYPE); return executeWithFlags(p_sql, 0); } public boolean executeWithFlags(String p_sql, int flags) throws SQLException { checkClosed(); p_sql = replaceProcessing(p_sql); Query simpleQuery = connection.getQueryExecutor().createSimpleQuery(p_sql); execute(simpleQuery, null, QueryExecutor.QUERY_ONESHOT | flags); this.lastSimpleQuery = simpleQuery; return (result != null && result.getResultSet() != null); } public boolean execute() throws SQLException { return executeWithFlags(0); } public boolean executeWithFlags(int flags) throws SQLException { checkClosed(); execute(preparedQuery, preparedParameters, flags); // If we are executing and there are out parameters // callable statement function set the return data if (isFunction && returnTypeSet ) { if (result == null || result.getResultSet() == null) throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA); ResultSet rs = result.getResultSet(); if (!rs.next()) throw new PSQLException(GT.tr("A CallableStatement was executed with nothing returned."), PSQLState.NO_DATA); // figure out how many columns int cols = rs.getMetaData().getColumnCount(); int outParameterCount = preparedParameters.getOutParameterCount() ; if ( cols != outParameterCount ) throw new PSQLException(GT.tr("A CallableStatement was executed with an invalid number of parameters"),PSQLState.SYNTAX_ERROR); // reset last result fetched (for wasNull) lastIndex = 0; // allocate enough space for all possible parameters without regard to in/out callResult = new Object[preparedParameters.getParameterCount()+1]; // move them into the result set for ( int i=0,j=0; i < cols; i++,j++) { // find the next out parameter, the assumption is that the functionReturnType // array will be initialized with 0 and only out parameters will have values // other than 0. 0 is the value for java.sql.Types.NULL, which should not // conflict while( j< functionReturnType.length && functionReturnType[j]==0) j++; callResult[j] = rs.getObject(i+1); int columnType = rs.getMetaData().getColumnType(i+1); if (columnType != functionReturnType[j]) { // this is here for the sole purpose of passing the cts if ( columnType == Types.DOUBLE && functionReturnType[j] == Types.REAL ) { // return it as a float if ( callResult[j] != null) callResult[j] = new Float(((Double)callResult[j]).floatValue()); } else { throw new PSQLException (GT.tr("A CallableStatement function was executed and the out parameter {0} was of type {1} however type {2} was registered.", new Object[]{new Integer(i+1), "java.sql.Types=" + columnType, "java.sql.Types=" + functionReturnType[j] }), PSQLState.DATA_TYPE_MISMATCH); } } } rs.close(); result = null; return false; } return (result != null && result.getResultSet() != null); } protected void closeForNextExecution() throws SQLException { // Every statement execution clears any previous warnings. clearWarnings(); // Close any existing resultsets associated with this statement. while (firstUnclosedResult != null) { ResultSet rs = firstUnclosedResult.getResultSet(); if (rs != null) { rs.close(); } firstUnclosedResult = firstUnclosedResult.getNext(); } result = null; if (lastSimpleQuery != null) { lastSimpleQuery.close(); lastSimpleQuery = null; } if (generatedKeys != null) { if (generatedKeys.getResultSet() != null) { generatedKeys.getResultSet().close(); } generatedKeys = null; } } protected void execute(Query queryToExecute, ParameterList queryParameters, int flags) throws SQLException { closeForNextExecution(); // Enable cursor-based resultset if possible. if (fetchSize > 0 && !wantsScrollableResultSet() && !connection.getAutoCommit() && !wantsHoldableResultSet()) flags |= QueryExecutor.QUERY_FORWARD_CURSOR; if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways) { flags |= QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS; // If the no results flag is set (from executeUpdate) // clear it so we get the generated keys results. // if ((flags & QueryExecutor.QUERY_NO_RESULTS) != 0) flags &= ~(QueryExecutor.QUERY_NO_RESULTS); } // Only use named statements after we hit the threshold. Note that only // named statements can be transferred in binary format. if (preparedQuery != null) { ++m_useCount; // We used this statement once more. if ((m_prepareThreshold == 0 || m_useCount < m_prepareThreshold) && !forceBinaryTransfers) flags |= QueryExecutor.QUERY_ONESHOT; } if (connection.getAutoCommit()) flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN; // updateable result sets do not yet support binary updates if (concurrency != ResultSet.CONCUR_READ_ONLY) flags |= QueryExecutor.QUERY_NO_BINARY_TRANSFER; if (queryToExecute.isEmpty()) { flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN; } if (!queryToExecute.isStatementDescribed() && forceBinaryTransfers) { int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY; StatementResultHandler handler2 = new StatementResultHandler(); connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler2, 0, 0, flags2); ResultWrapper result2 = handler2.getResults(); if (result2 != null) { result2.getResultSet().close(); } } StatementResultHandler handler = new StatementResultHandler(); result = null; try { startTimer(); connection.getQueryExecutor().execute(queryToExecute, queryParameters, handler, maxrows, fetchSize, flags); } finally { killTimerTask(); } result = firstUnclosedResult = handler.getResults(); if (wantsGeneratedKeysOnce || wantsGeneratedKeysAlways) { generatedKeys = result; result = result.getNext(); if (wantsGeneratedKeysOnce) wantsGeneratedKeysOnce = false; } } /* * setCursorName defines the SQL cursor name that will be used by * subsequent execute methods. This name can then be used in SQL * positioned update/delete statements to identify the current row * in the ResultSet generated by this statement. If a database * doesn't support positioned update/delete, this method is a * no-op. * * <p><B>Note:</B> By definition, positioned update/delete execution * must be done by a different Statement than the one which * generated the ResultSet being used for positioning. Also, cursor * names must be unique within a Connection. * * @param name the new cursor name * @exception SQLException if a database access error occurs */ public void setCursorName(String name) throws SQLException { checkClosed(); // No-op. } protected boolean isClosed = false; private int lastIndex = 0; /* * getUpdateCount returns the current result as an update count, * if the result is a ResultSet or there are no more results, -1 * is returned. It should only be called once per result. * * @return the current result as an update count. * @exception SQLException if a database access error occurs */ public int getUpdateCount() throws SQLException { checkClosed(); if (result == null || result.getResultSet() != null) return -1; return result.getUpdateCount(); } /* * getMoreResults moves to a Statement's next result. If it returns * true, this result is a ResulSet. * * @return true if the next ResultSet is valid * @exception SQLException if a database access error occurs */ public boolean getMoreResults() throws SQLException { if (result == null) return false; result = result.getNext(); // Close preceding resultsets. while (firstUnclosedResult != result) { if (firstUnclosedResult.getResultSet() != null) firstUnclosedResult.getResultSet().close(); firstUnclosedResult = firstUnclosedResult.getNext(); } return (result != null && result.getResultSet() != null); } /* * The maxRows limit is set to limit the number of rows that * any ResultSet can contain. If the limit is exceeded, the * excess rows are silently dropped. * * @return the current maximum row limit; zero means unlimited * @exception SQLException if a database access error occurs */ public int getMaxRows() throws SQLException { checkClosed(); return maxrows; } /* * Set the maximum number of rows * * @param max the new max rows limit; zero means unlimited * @exception SQLException if a database access error occurs * @see getMaxRows */ public void setMaxRows(int max) throws SQLException { checkClosed(); if (max < 0) throw new PSQLException(GT.tr("Maximum number of rows must be a value grater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); maxrows = max; } /* * If escape scanning is on (the default), the driver will do escape * substitution before sending the SQL to the database. * * @param enable true to enable; false to disable * @exception SQLException if a database access error occurs */ public void setEscapeProcessing(boolean enable) throws SQLException { checkClosed(); replaceProcessingEnabled = enable; } /* * The queryTimeout limit is the number of seconds the driver * will wait for a Statement to execute. If the limit is * exceeded, a SQLException is thrown. * * @return the current query timeout limit in seconds; 0 = unlimited * @exception SQLException if a database access error occurs */ public int getQueryTimeout() throws SQLException { checkClosed(); return timeout; } /* * Sets the queryTimeout limit * * @param seconds - the new query timeout limit in seconds * @exception SQLException if a database access error occurs */ public void setQueryTimeout(int seconds) throws SQLException { checkClosed(); if (seconds < 0) throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."), PSQLState.INVALID_PARAMETER_VALUE); timeout = seconds; } /** * This adds a warning to the warning chain. We track the * tail of the warning chain as well to avoid O(N) behavior * for adding a new warning to an existing chain. Some * server functions which RAISE NOTICE (or equivalent) produce * a ton of warnings. * @param warn warning to add */ public void addWarning(SQLWarning warn) { if (warnings == null) { warnings = warn; lastWarning = warn; } else { lastWarning.setNextWarning(warn); lastWarning = warn; } } /* * The first warning reported by calls on this Statement is * returned. A Statement's execute methods clear its SQLWarning * chain. Subsequent Statement warnings will be chained to this * SQLWarning. * * <p>The Warning chain is automatically cleared each time a statement * is (re)executed. * * <p><B>Note:</B> If you are processing a ResultSet then any warnings * associated with ResultSet reads will be chained on the ResultSet * object. * * @return the first SQLWarning on null * @exception SQLException if a database access error occurs */ public SQLWarning getWarnings() throws SQLException { checkClosed(); return warnings; } /* * The maxFieldSize limit (in bytes) is the maximum amount of * data returned for any column value; it only applies to * BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR * columns. If the limit is exceeded, the excess data is silently * discarded. * * @return the current max column size limit; zero means unlimited * @exception SQLException if a database access error occurs */ public int getMaxFieldSize() throws SQLException { return maxfieldSize; } /* * Sets the maxFieldSize * * @param max the new max column size limit; zero means unlimited * @exception SQLException if a database access error occurs */ public void setMaxFieldSize(int max) throws SQLException { checkClosed(); if (max < 0) throw new PSQLException(GT.tr("The maximum field size must be a value greater than or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); maxfieldSize = max; } /* * After this call, getWarnings returns null until a new warning * is reported for this Statement. * * @exception SQLException if a database access error occurs */ public void clearWarnings() throws SQLException { warnings = null; lastWarning = null; } /* * getResultSet returns the current result as a ResultSet. It * should only be called once per result. * * @return the current result set; null if there are no more * @exception SQLException if a database access error occurs (why?) */ public java.sql.ResultSet getResultSet() throws SQLException { checkClosed(); if (result == null) return null; return (ResultSet) result.getResultSet(); } /* * In many cases, it is desirable to immediately release a * Statement's database and JDBC resources instead of waiting * for this to happen when it is automatically closed. The * close method provides this immediate release. * * <p><B>Note:</B> A Statement is automatically closed when it is * garbage collected. When a Statement is closed, its current * ResultSet, if one exists, is also closed. * * @exception SQLException if a database access error occurs (why?) */ public void close() throws SQLException { // closing an already closed Statement is a no-op. if (isClosed) return ; killTimerTask(); closeForNextExecution(); if (preparedQuery != null) preparedQuery.close(); isClosed = true; } /** * This finalizer ensures that statements that have allocated server-side * resources free them when they become unreferenced. */ protected void finalize() throws Throwable { try { close(); } catch (SQLException e) { } finally { super.finalize(); } } /* * Filter the SQL string of Java SQL Escape clauses. * * Currently implemented Escape clauses are those mentioned in 11.3 * in the specification. Basically we look through the sql string for * {d xxx}, {t xxx}, {ts xxx}, {oj xxx} or {fn xxx} in non-string sql * code. When we find them, we just strip the escape part leaving only * the xxx part. * So, something like "select * from x where d={d '2001-10-09'}" would * return "select * from x where d= '2001-10-09'". */ protected String replaceProcessing(String p_sql) throws SQLException { if (replaceProcessingEnabled) { // Since escape codes can only appear in SQL CODE, we keep track // of if we enter a string or not. int len = p_sql.length(); StringBuilder newsql = new StringBuilder(len); int i=0; while (i<len){ i=parseSql(p_sql,i,newsql,false,connection.getStandardConformingStrings()); // We need to loop here in case we encounter invalid // SQL, consider: SELECT a FROM t WHERE (1 > 0)) ORDER BY a // We can't ending replacing after the extra closing paren // because that changes a syntax error to a valid query // that isn't what the user specified. if (i < len) { newsql.append(p_sql.charAt(i)); i++; } } return newsql.toString(); } else { return p_sql; } } /** * parse the given sql from index i, appending it to the gven buffer * until we hit an unmatched right parentheses or end of string. When * the stopOnComma flag is set we also stop processing when a comma is * found in sql text that isn't inside nested parenthesis. * * @param p_sql the original query text * @param i starting position for replacing * @param newsql where to write the replaced output * @param stopOnComma should we stop after hitting the first comma in sql text? * @param stdStrings whether standard_conforming_strings is on * @return the position we stopped processing at */ protected static int parseSql(String p_sql,int i,StringBuilder newsql, boolean stopOnComma, boolean stdStrings)throws SQLException{ short state = IN_SQLCODE; int len = p_sql.length(); int nestedParenthesis=0; boolean endOfNested=false; // because of the ++i loop i--; while (!endOfNested && ++i < len) { char c = p_sql.charAt(i); switch (state) { case IN_SQLCODE: if (c == '\'') // start of a string? state = IN_STRING; else if (c == '"') // start of a identifer? state = IN_IDENTIFIER; else if (c=='(') { // begin nested sql nestedParenthesis++; } else if (c==')') { // end of nested sql nestedParenthesis--; if (nestedParenthesis<0){ endOfNested=true; break; } } else if (stopOnComma && c==',' && nestedParenthesis==0) { endOfNested=true; break; } else if (c == '{') { // start of an escape code? if (i + 1 < len) { char next = p_sql.charAt(i + 1); char nextnext = (i + 2 < len) ? p_sql.charAt(i + 2) : '\0'; if (next == 'd' || next == 'D') { state = ESC_TIMEDATE; i++; newsql.append("DATE "); break; } else if (next == 't' || next == 'T') { state = ESC_TIMEDATE; if (nextnext == 's' || nextnext == 'S'){ // timestamp constant i+=2; newsql.append("TIMESTAMP "); }else{ // time constant i++; newsql.append("TIME "); } break; } else if ( next == 'f' || next == 'F' ) { state = ESC_FUNCTION; i += (nextnext == 'n' || nextnext == 'N') ? 2 : 1; break; } else if ( next == 'o' || next == 'O' ) { state = ESC_OUTERJOIN; i += (nextnext == 'j' || nextnext == 'J') ? 2 : 1; break; } else if ( next == 'e' || next == 'E' ) { // we assume that escape is the only escape sequence beginning with e state = ESC_ESCAPECHAR; break; } } } newsql.append(c); break; case IN_STRING: if (c == '\'') // end of string? state = IN_SQLCODE; else if (c == '\\' && !stdStrings) // a backslash? state = BACKSLASH; newsql.append(c); break; case IN_IDENTIFIER: if (c == '"') // end of identifier state = IN_SQLCODE; newsql.append(c); break; case BACKSLASH: state = IN_STRING; newsql.append(c); break; case ESC_FUNCTION: // extract function name String functionName; int posArgs = p_sql.indexOf('(',i); if (posArgs!=-1){ functionName=p_sql.substring(i,posArgs).trim(); // extract arguments i= posArgs+1;// we start the scan after the first ( StringBuilder args=new StringBuilder(); i = parseSql(p_sql,i,args,false,stdStrings); // translate the function and parse arguments newsql.append(escapeFunction(functionName,args.toString(),stdStrings)); } // go to the end of the function copying anything found i++; while (i<len && p_sql.charAt(i)!='}') newsql.append(p_sql.charAt(i++)); state = IN_SQLCODE; // end of escaped function (or query) break; case ESC_TIMEDATE: case ESC_OUTERJOIN: case ESC_ESCAPECHAR: if (c == '}') state = IN_SQLCODE; // end of escape code. else newsql.append(c); break; } // end switch } return i; } /** * generate sql for escaped functions * @param functionName the escaped function name * @param args the arguments for this functin * @param stdStrings whether standard_conforming_strings is on * @return the right postgreSql sql */ protected static String escapeFunction(String functionName, String args, boolean stdStrings) throws SQLException{ // parse function arguments int len = args.length(); int i=0; ArrayList parsedArgs = new ArrayList(); while (i<len){ StringBuilder arg = new StringBuilder(); int lastPos=i; i=parseSql(args,i,arg,true,stdStrings); if (lastPos!=i){ parsedArgs.add(arg); } i++; } // we can now tranlate escape functions try{ Method escapeMethod = EscapedFunctions.getFunction(functionName); return (String) escapeMethod.invoke(null,new Object[] {parsedArgs}); }catch(InvocationTargetException e){ if (e.getTargetException() instanceof SQLException) throw (SQLException) e.getTargetException(); else throw new PSQLException(e.getTargetException().getMessage(), PSQLState.SYSTEM_ERROR); }catch (Exception e){ // by default the function name is kept unchanged StringBuilder buf = new StringBuilder(); buf.append(functionName).append('('); for (int iArg = 0;iArg<parsedArgs.size();iArg++){ buf.append(parsedArgs.get(iArg)); if (iArg!=(parsedArgs.size()-1)) buf.append(','); } buf.append(')'); return buf.toString(); } } /* * * The following methods are postgres extensions and are defined * in the interface BaseStatement * */ /* * Returns the Last inserted/updated oid. Deprecated in 7.2 because * range of OID values is greater than a java signed int. * @deprecated Replaced by getLastOID in 7.2 */ public int getInsertedOID() throws SQLException { checkClosed(); if (result == null) return 0; return (int) result.getInsertOID(); } /* * Returns the Last inserted/updated oid. * @return OID of last insert * @since 7.2 */ public long getLastOID() throws SQLException { checkClosed(); if (result == null) return 0; return result.getInsertOID(); } /* * Set a parameter to SQL NULL * * <p><B>Note:</B> You must specify the parameter's SQL type. * * @param parameterIndex the first parameter is 1, etc... * @param sqlType the SQL type code defined in java.sql.Types * @exception SQLException if a database access error occurs */ public void setNull(int parameterIndex, int sqlType) throws SQLException { checkClosed(); int oid; switch (sqlType) { case Types.INTEGER: oid = Oid.INT4; break; case Types.TINYINT: case Types.SMALLINT: oid = Oid.INT2; break; case Types.BIGINT: oid = Oid.INT8; break; case Types.REAL: oid = Oid.FLOAT4; break; case Types.DOUBLE: case Types.FLOAT: oid = Oid.FLOAT8; break; case Types.DECIMAL: case Types.NUMERIC: oid = Oid.NUMERIC; break; case Types.CHAR: oid = Oid.BPCHAR; break; case Types.VARCHAR: case Types.LONGVARCHAR: oid = connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED; break; case Types.DATE: oid = Oid.DATE; break; case Types.TIME: case Types.TIMESTAMP: oid = Oid.UNSPECIFIED; break; case Types.BIT: oid = Oid.BOOL; break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: if (connection.haveMinimumCompatibleVersion("7.2")) { oid = Oid.BYTEA; } else { oid = Oid.OID; } break; case Types.BLOB: case Types.CLOB: oid = Oid.OID; break; case Types.ARRAY: case Types.DISTINCT: case Types.STRUCT: case Types.NULL: case Types.OTHER: oid = Oid.UNSPECIFIED; break; default: // Bad Types value. throw new PSQLException(GT.tr("Unknown Types value."), PSQLState.INVALID_PARAMETER_TYPE); } if ( adjustIndex ) parameterIndex--; preparedParameters.setNull( parameterIndex, oid); } /* * Set a parameter to a Java boolean value. The driver converts this * to a SQL BIT value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setBoolean(int parameterIndex, boolean x) throws SQLException { checkClosed(); bindString(parameterIndex, x ? "1" : "0", Oid.BOOL); } /* * Set a parameter to a Java byte value. The driver converts this to * a SQL TINYINT value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setByte(int parameterIndex, byte x) throws SQLException { setShort(parameterIndex, x); } /* * Set a parameter to a Java short value. The driver converts this * to a SQL SMALLINT value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setShort(int parameterIndex, short x) throws SQLException { checkClosed(); if (connection.binaryTransferSend(Oid.INT2)) { byte[] val = new byte[2]; ByteConverter.int2(val, 0, x); bindBytes(parameterIndex, val, Oid.INT2); return; } bindLiteral(parameterIndex, Integer.toString(x), Oid.INT2); } /* * Set a parameter to a Java int value. The driver converts this to * a SQL INTEGER value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setInt(int parameterIndex, int x) throws SQLException { checkClosed(); if (connection.binaryTransferSend(Oid.INT4)) { byte[] val = new byte[4]; ByteConverter.int4(val, 0, x); bindBytes(parameterIndex, val, Oid.INT4); return; } bindLiteral(parameterIndex, Integer.toString(x), Oid.INT4); } /* * Set a parameter to a Java long value. The driver converts this to * a SQL BIGINT value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setLong(int parameterIndex, long x) throws SQLException { checkClosed(); if (connection.binaryTransferSend(Oid.INT8)) { byte[] val = new byte[8]; ByteConverter.int8(val, 0, x); bindBytes(parameterIndex, val, Oid.INT8); return; } bindLiteral(parameterIndex, Long.toString(x), Oid.INT8); } /* * Set a parameter to a Java float value. The driver converts this * to a SQL FLOAT value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setFloat(int parameterIndex, float x) throws SQLException { checkClosed(); if (connection.binaryTransferSend(Oid.FLOAT4)) { byte[] val = new byte[4]; ByteConverter.float4(val, 0, x); bindBytes(parameterIndex, val, Oid.FLOAT4); return; } bindLiteral(parameterIndex, Float.toString(x), Oid.FLOAT8); } /* * Set a parameter to a Java double value. The driver converts this * to a SQL DOUBLE value when it sends it to the database * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setDouble(int parameterIndex, double x) throws SQLException { checkClosed(); if (connection.binaryTransferSend(Oid.FLOAT8)) { byte[] val = new byte[8]; ByteConverter.float8(val, 0, x); bindBytes(parameterIndex, val, Oid.FLOAT8); return; } bindLiteral(parameterIndex, Double.toString(x), Oid.FLOAT8); } /* * Set a parameter to a java.lang.BigDecimal value. The driver * converts this to a SQL NUMERIC value when it sends it to the * database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { checkClosed(); if (x == null) setNull(parameterIndex, Types.DECIMAL); else bindLiteral(parameterIndex, x.toString(), Oid.NUMERIC); } /* * Set a parameter to a Java String value. The driver converts this * to a SQL VARCHAR or LONGVARCHAR value (depending on the arguments * size relative to the driver's limits on VARCHARs) when it sends it * to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setString(int parameterIndex, String x) throws SQLException { checkClosed(); setString(parameterIndex, x, getStringType()); } private int getStringType() { return (connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED); } protected void setString(int parameterIndex, String x, int oid) throws SQLException { // if the passed string is null, then set this column to null checkClosed(); if (x == null) { if ( adjustIndex ) parameterIndex--; preparedParameters.setNull( parameterIndex, oid); } else bindString(parameterIndex, x, oid); } /* * Set a parameter to a Java array of bytes. The driver converts this * to a SQL VARBINARY or LONGVARBINARY (depending on the argument's * size relative to the driver's limits on VARBINARYs) when it sends * it to the database. * * <p>Implementation note: * <br>With org.postgresql, this creates a large object, and stores the * objects oid in this column. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setBytes(int parameterIndex, byte[] x) throws SQLException { checkClosed(); if (null == x) { setNull(parameterIndex, Types.VARBINARY); return ; } if (connection.haveMinimumCompatibleVersion("7.2")) { //Version 7.2 supports the bytea datatype for byte arrays byte[] copy = new byte[x.length]; System.arraycopy(x, 0, copy, 0, x.length); preparedParameters.setBytea( parameterIndex, copy, 0, x.length); } else { //Version 7.1 and earlier support done as LargeObjects LargeObjectManager lom = connection.getLargeObjectAPI(); long oid = lom.createLO(); LargeObject lob = lom.open(oid); lob.write(x); lob.close(); setLong(parameterIndex, oid); } } /* * Set a parameter to a java.sql.Date value. The driver converts this * to a SQL DATE value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setDate(int parameterIndex, java.sql.Date x) throws SQLException { setDate(parameterIndex, x, null); } /* * Set a parameter to a java.sql.Time value. The driver converts * this to a SQL TIME value when it sends it to the database. * * @param parameterIndex the first parameter is 1...)); * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setTime(int parameterIndex, Time x) throws SQLException { setTime(parameterIndex, x, null); } /* * Set a parameter to a java.sql.Timestamp value. The driver converts * this to a SQL TIMESTAMP value when it sends it to the database. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { setTimestamp(parameterIndex, x, null); } private void setCharacterStreamPost71(int parameterIndex, InputStream x, int length, String encoding) throws SQLException { if (x == null) { setNull(parameterIndex, Types.VARCHAR); return ; } if (length < 0) throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)), PSQLState.INVALID_PARAMETER_VALUE); //Version 7.2 supports AsciiStream for all PG text types (char, varchar, text) //As the spec/javadoc for this method indicate this is to be used for //large String values (i.e. LONGVARCHAR) PG doesn't have a separate //long varchar datatype, but with toast all text datatypes are capable of //handling very large values. Thus the implementation ends up calling //setString() since there is no current way to stream the value to the server try { InputStreamReader l_inStream = new InputStreamReader(x, encoding); char[] l_chars = new char[length]; int l_charsRead = 0; while (true) { int n = l_inStream.read(l_chars, l_charsRead, length - l_charsRead); if (n == -1) break; l_charsRead += n; if (l_charsRead == length) break; } setString(parameterIndex, new String(l_chars, 0, l_charsRead), Oid.VARCHAR); } catch (UnsupportedEncodingException l_uee) { throw new PSQLException(GT.tr("The JVM claims not to support the {0} encoding.", encoding), PSQLState.UNEXPECTED_ERROR, l_uee); } catch (IOException l_ioe) { throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, l_ioe); } } /* * When a very large ASCII value is input to a LONGVARCHAR parameter, * it may be more practical to send it via a java.io.InputStream. * JDBC will read the data from the stream as needed, until it reaches * end-of-file. The JDBC driver will do any necessary conversion from * ASCII to the database char format. * * <P><B>Note:</B> This stream object can either be a standard Java * stream object or your own subclass that implements the standard * interface. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @param length the number of bytes in the stream * @exception SQLException if a database access error occurs */ public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); if (connection.haveMinimumCompatibleVersion("7.2")) { setCharacterStreamPost71(parameterIndex, x, length, "ASCII"); } else { //Version 7.1 supported only LargeObjects by treating everything //as binary data setBinaryStream(parameterIndex, x, length); } } /* * When a very large Unicode value is input to a LONGVARCHAR parameter, * it may be more practical to send it via a java.io.InputStream. * JDBC will read the data from the stream as needed, until it reaches * end-of-file. The JDBC driver will do any necessary conversion from * UNICODE to the database char format. * * <P><B>Note:</B> This stream object can either be a standard Java * stream object or your own subclass that implements the standard * interface. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); if (connection.haveMinimumCompatibleVersion("7.2")) { setCharacterStreamPost71(parameterIndex, x, length, "UTF-8"); } else { //Version 7.1 supported only LargeObjects by treating everything //as binary data setBinaryStream(parameterIndex, x, length); } } /* * When a very large binary value is input to a LONGVARBINARY parameter, * it may be more practical to send it via a java.io.InputStream. * JDBC will read the data from the stream as needed, until it reaches * end-of-file. * * <P><B>Note:</B> This stream object can either be a standard Java * stream object or your own subclass that implements the standard * interface. * * @param parameterIndex the first parameter is 1... * @param x the parameter value * @exception SQLException if a database access error occurs */ public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { checkClosed(); if (x == null) { setNull(parameterIndex, Types.VARBINARY); return ; } if (length < 0) throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)), PSQLState.INVALID_PARAMETER_VALUE); if (connection.haveMinimumCompatibleVersion("7.2")) { //Version 7.2 supports BinaryStream for for the PG bytea type //As the spec/javadoc for this method indicate this is to be used for //large binary values (i.e. LONGVARBINARY) PG doesn't have a separate //long binary datatype, but with toast the bytea datatype is capable of //handling very large values. preparedParameters.setBytea(parameterIndex, x, length); } else { //Version 7.1 only supported streams for LargeObjects //but the jdbc spec indicates that streams should be //available for LONGVARBINARY instead LargeObjectManager lom = connection.getLargeObjectAPI(); long oid = lom.createLO(); LargeObject lob = lom.open(oid); OutputStream los = lob.getOutputStream(); try { // could be buffered, but then the OutputStream returned by LargeObject // is buffered internally anyhow, so there would be no performance // boost gained, if anything it would be worse! int c = x.read(); int p = 0; while (c > -1 && p < length) { los.write(c); c = x.read(); p++; } los.close(); } catch (IOException se) { throw new PSQLException(GT.tr("Provided InputStream failed."), PSQLState.UNEXPECTED_ERROR, se); } // lob is closed by the stream so don't call lob.close() setLong(parameterIndex, oid); } } /* * In general, parameter values remain in force for repeated used of a * Statement. Setting a parameter value automatically clears its * previous value. However, in coms cases, it is useful to immediately * release the resources used by the current parameter values; this * can be done by calling clearParameters * * @exception SQLException if a database access error occurs */ public void clearParameters() throws SQLException { preparedParameters.clear(); } private PGType createInternalType( Object x, int targetType ) throws PSQLException { if ( x instanceof Byte ) return PGByte.castToServerType((Byte)x, targetType ); if ( x instanceof Short ) return PGShort.castToServerType((Short)x, targetType ); if ( x instanceof Integer ) return PGInteger.castToServerType((Integer)x, targetType ); if ( x instanceof Long ) return PGLong.castToServerType((Long)x, targetType ); if ( x instanceof Double ) return PGDouble.castToServerType((Double)x, targetType ); if ( x instanceof Float ) return PGFloat.castToServerType((Float)x, targetType ); if ( x instanceof BigDecimal) return PGBigDecimal.castToServerType((BigDecimal)x, targetType ); // since all of the above are instances of Number make sure this is after them if ( x instanceof Number ) return PGNumber.castToServerType((Number)x, targetType ); if ( x instanceof Boolean) return PGBoolean.castToServerType((Boolean)x, targetType ); return new PGUnknown(x); } // Helper method for setting parameters to PGobject subclasses. private void setPGobject(int parameterIndex, PGobject x) throws SQLException { String typename = x.getType(); int oid = connection.getTypeInfo().getPGType(typename); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE); if ((x instanceof PGBinaryObject) && connection.binaryTransferSend(oid)) { PGBinaryObject binObj = (PGBinaryObject) x; byte[] data = new byte[binObj.lengthInBytes()]; binObj.toBytes(data, 0); bindBytes(parameterIndex, data, oid); } else { setString(parameterIndex, x.getValue(), oid); } } private void setMap(int parameterIndex, Map x) throws SQLException { int oid = connection.getTypeInfo().getPGType("hstore"); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("No hstore extension installed."), PSQLState.INVALID_PARAMETER_TYPE); if (connection.binaryTransferSend(oid)) { byte[] data = HStoreConverter.toBytes(x, connection.getEncoding()); bindBytes(parameterIndex, data, oid); } else { setString(parameterIndex, HStoreConverter.toString(x), oid); } } /* * Set the value of a parameter using an object; use the java.lang * equivalent objects for integral values. * * <P>The given Java object will be converted to the targetSqlType before * being sent to the database. * * <P>note that this method may be used to pass database-specific * abstract data types. This is done by using a Driver-specific * Java type and using a targetSqlType of java.sql.Types.OTHER * * @param parameterIndex the first parameter is 1... * @param x the object containing the input parameter value * @param targetSqlType The SQL type to be send to the database * @param scale For java.sql.Types.DECIMAL or java.sql.Types.NUMERIC * * types this is the number of digits after the decimal. For * * all other types this value will be ignored. * @exception SQLException if a database access error occurs */ public void setObject(int parameterIndex, Object in, int targetSqlType, int scale) throws SQLException { checkClosed(); if (in == null) { setNull(parameterIndex, targetSqlType); return ; } Object pgType = createInternalType( in, targetSqlType ); switch (targetSqlType) { case Types.INTEGER: bindLiteral(parameterIndex, pgType.toString(), Oid.INT4); break; case Types.TINYINT: case Types.SMALLINT: bindLiteral(parameterIndex, pgType.toString(), Oid.INT2); break; case Types.BIGINT: bindLiteral(parameterIndex, pgType.toString(), Oid.INT8); break; case Types.REAL: //TODO: is this really necessary ? //bindLiteral(parameterIndex, new Float(pgType.toString()).toString(), Oid.FLOAT4); bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT4); break; case Types.DOUBLE: case Types.FLOAT: bindLiteral(parameterIndex, pgType.toString(), Oid.FLOAT8); break; case Types.DECIMAL: case Types.NUMERIC: bindLiteral(parameterIndex, pgType.toString(), Oid.NUMERIC); break; case Types.CHAR: setString(parameterIndex, pgType.toString(), Oid.BPCHAR); break; case Types.VARCHAR: case Types.LONGVARCHAR: setString(parameterIndex, pgType.toString(), getStringType()); break; case Types.DATE: if (in instanceof java.sql.Date) setDate(parameterIndex, (java.sql.Date)in); else { java.sql.Date tmpd; if (in instanceof java.util.Date) { tmpd = new java.sql.Date(((java.util.Date)in).getTime()); } else { tmpd = connection.getTimestampUtils().toDate(null, in.toString()); } setDate(parameterIndex, tmpd); } break; case Types.TIME: if (in instanceof java.sql.Time) setTime(parameterIndex, (java.sql.Time)in); else { java.sql.Time tmpt; if (in instanceof java.util.Date) { tmpt = new java.sql.Time(((java.util.Date)in).getTime()); } else { tmpt = connection.getTimestampUtils().toTime(null, in.toString()); } setTime(parameterIndex, tmpt); } break; case Types.TIMESTAMP: if (in instanceof java.sql.Timestamp) setTimestamp(parameterIndex , (java.sql.Timestamp)in); else { java.sql.Timestamp tmpts; if (in instanceof java.util.Date) { tmpts = new java.sql.Timestamp(((java.util.Date)in).getTime()); } else { tmpts = connection.getTimestampUtils().toTimestamp(null, in.toString()); } setTimestamp(parameterIndex, tmpts); } break; case Types.BIT: bindLiteral(parameterIndex, pgType.toString(), Oid.BOOL); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: setObject(parameterIndex, in); break; case Types.BLOB: if (in instanceof Blob) { setBlob(parameterIndex, (Blob)in); } else if (in instanceof InputStream) { long oid = createBlob(parameterIndex, (InputStream) in, -1); setLong(parameterIndex, oid); } else { throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.BLOB"}), PSQLState.INVALID_PARAMETER_TYPE); } break; case Types.CLOB: if (in instanceof Clob) setClob(parameterIndex, (Clob)in); else throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.CLOB"}), PSQLState.INVALID_PARAMETER_TYPE); break; case Types.ARRAY: if (in instanceof Array) setArray(parameterIndex, (Array)in); else throw new PSQLException(GT.tr("Cannot cast an instance of {0} to type {1}", new Object[]{in.getClass().getName(),"Types.ARRAY"}), PSQLState.INVALID_PARAMETER_TYPE); break; case Types.DISTINCT: bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED); break; case Types.OTHER: if (in instanceof PGobject) setPGobject(parameterIndex, (PGobject)in); else bindString(parameterIndex, in.toString(), Oid.UNSPECIFIED); break; default: throw new PSQLException(GT.tr("Unsupported Types value: {0}", new Integer(targetSqlType)), PSQLState.INVALID_PARAMETER_TYPE); } } public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { setObject(parameterIndex, x, targetSqlType, 0); } /* * This stores an Object into a parameter. */ public void setObject(int parameterIndex, Object x) throws SQLException { checkClosed(); if (x == null) setNull(parameterIndex, Types.OTHER); else if (x instanceof String) setString(parameterIndex, (String)x); else if (x instanceof BigDecimal) setBigDecimal(parameterIndex, (BigDecimal)x); else if (x instanceof Short) setShort(parameterIndex, ((Short)x).shortValue()); else if (x instanceof Integer) setInt(parameterIndex, ((Integer)x).intValue()); else if (x instanceof Long) setLong(parameterIndex, ((Long)x).longValue()); else if (x instanceof Float) setFloat(parameterIndex, ((Float)x).floatValue()); else if (x instanceof Double) setDouble(parameterIndex, ((Double)x).doubleValue()); else if (x instanceof byte[]) setBytes(parameterIndex, (byte[])x); else if (x instanceof java.sql.Date) setDate(parameterIndex, (java.sql.Date)x); else if (x instanceof Time) setTime(parameterIndex, (Time)x); else if (x instanceof Timestamp) setTimestamp(parameterIndex, (Timestamp)x); else if (x instanceof Boolean) setBoolean(parameterIndex, ((Boolean)x).booleanValue()); else if (x instanceof Byte) setByte(parameterIndex, ((Byte)x).byteValue()); else if (x instanceof Blob) setBlob(parameterIndex, (Blob)x); else if (x instanceof Clob) setClob(parameterIndex, (Clob)x); else if (x instanceof Array) setArray(parameterIndex, (Array)x); else if (x instanceof PGobject) setPGobject(parameterIndex, (PGobject)x); else if (x instanceof Character) setString(parameterIndex, ((Character)x).toString()); else if (x instanceof Map) setMap(parameterIndex, (Map)x); else { // Can't infer a type. throw new PSQLException(GT.tr("Can''t infer the SQL type to use for an instance of {0}. Use setObject() with an explicit Types value to specify the type to use.", x.getClass().getName()), PSQLState.INVALID_PARAMETER_TYPE); } } /* * Before executing a stored procedure call you must explicitly * call registerOutParameter to register the java.sql.Type of each * out parameter. * * <p>Note: When reading the value of an out parameter, you must use * the getXXX method whose Java type XXX corresponds to the * parameter's registered SQL type. * * ONLY 1 RETURN PARAMETER if {?= call ..} syntax is used * * @param parameterIndex the first parameter is 1, the second is 2,... * @param sqlType SQL type code defined by java.sql.Types; for * parameters of type Numeric or Decimal use the version of * registerOutParameter that accepts a scale value * @exception SQLException if a database-access error occurs. */ public void registerOutParameter(int parameterIndex, int sqlType, boolean setPreparedParameters) throws SQLException { checkClosed(); switch( sqlType ) { case Types.TINYINT: // we don't have a TINYINT type use SMALLINT sqlType = Types.SMALLINT; break; case Types.LONGVARCHAR: sqlType = Types.VARCHAR; break; case Types.DECIMAL: sqlType = Types.NUMERIC; break; case Types.FLOAT: // float is the same as double sqlType = Types.DOUBLE; break; case Types.VARBINARY: case Types.LONGVARBINARY: sqlType = Types.BINARY; break; default: break; } if (!isFunction) throw new PSQLException (GT.tr("This statement does not declare an OUT parameter. Use '{' ?= call ... '}' to declare one."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL); checkIndex(parameterIndex, false); if( setPreparedParameters ) preparedParameters.registerOutParameter( parameterIndex, sqlType ); // functionReturnType contains the user supplied value to check // testReturn contains a modified version to make it easier to // check the getXXX methods.. functionReturnType[parameterIndex-1] = sqlType; testReturn[parameterIndex-1] = sqlType; if (functionReturnType[parameterIndex-1] == Types.CHAR || functionReturnType[parameterIndex-1] == Types.LONGVARCHAR) testReturn[parameterIndex-1] = Types.VARCHAR; else if (functionReturnType[parameterIndex-1] == Types.FLOAT) testReturn[parameterIndex-1] = Types.REAL; // changes to streamline later error checking returnTypeSet = true; } /* * You must also specify the scale for numeric/decimal types: * * <p>Note: When reading the value of an out parameter, you must use * the getXXX method whose Java type XXX corresponds to the * parameter's registered SQL type. * * @param parameterIndex the first parameter is 1, the second is 2,... * @param sqlType use either java.sql.Type.NUMERIC or java.sql.Type.DECIMAL * @param scale a value greater than or equal to zero representing the * desired number of digits to the right of the decimal point * @exception SQLException if a database-access error occurs. */ public void registerOutParameter(int parameterIndex, int sqlType, int scale, boolean setPreparedParameters) throws SQLException { registerOutParameter (parameterIndex, sqlType, setPreparedParameters); // ignore for now.. } /* * An OUT parameter may have the value of SQL NULL; wasNull * reports whether the last value read has this special value. * * <p>Note: You must first call getXXX on a parameter to read its * value and then call wasNull() to see if the value was SQL NULL. * @return true if the last parameter read was SQL NULL * @exception SQLException if a database-access error occurs. */ public boolean wasNull() throws SQLException { if (lastIndex == 0) throw new PSQLException(GT.tr("wasNull cannot be call before fetching a result."), PSQLState.OBJECT_NOT_IN_STATE); // check to see if the last access threw an exception return (callResult[lastIndex-1] == null); } /* * Get the value of a CHAR, VARCHAR, or LONGVARCHAR parameter as a * Java String. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. */ public String getString(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.VARCHAR, "String"); return (String)callResult[parameterIndex-1]; } /* * Get the value of a BIT parameter as a Java boolean. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is false * @exception SQLException if a database-access error occurs. */ public boolean getBoolean(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.BIT, "Boolean"); if (callResult[parameterIndex-1] == null) return false; return ((Boolean)callResult[parameterIndex-1]).booleanValue (); } /* * Get the value of a TINYINT parameter as a Java byte. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public byte getByte(int parameterIndex) throws SQLException { checkClosed(); // fake tiny int with smallint checkIndex (parameterIndex, Types.SMALLINT, "Byte"); if (callResult[parameterIndex-1] == null) return 0; return ((Integer)callResult[parameterIndex-1]).byteValue(); } /* * Get the value of a SMALLINT parameter as a Java short. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public short getShort(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.SMALLINT, "Short"); if (callResult[parameterIndex-1] == null) return 0; return ((Integer)callResult[parameterIndex-1]).shortValue (); } /* * Get the value of an INTEGER parameter as a Java int. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public int getInt(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.INTEGER, "Int"); if (callResult[parameterIndex-1] == null) return 0; return ((Integer)callResult[parameterIndex-1]).intValue (); } /* * Get the value of a BIGINT parameter as a Java long. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public long getLong(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.BIGINT, "Long"); if (callResult[parameterIndex-1] == null) return 0; return ((Long)callResult[parameterIndex-1]).longValue (); } /* * Get the value of a FLOAT parameter as a Java float. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public float getFloat(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.REAL, "Float"); if (callResult[parameterIndex-1] == null) return 0; return ((Float)callResult[parameterIndex-1]).floatValue (); } /* * Get the value of a DOUBLE parameter as a Java double. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is 0 * @exception SQLException if a database-access error occurs. */ public double getDouble(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.DOUBLE, "Double"); if (callResult[parameterIndex-1] == null) return 0; return ((Double)callResult[parameterIndex-1]).doubleValue (); } /* * Get the value of a NUMERIC parameter as a java.math.BigDecimal * object. * * @param parameterIndex the first parameter is 1, the second is 2,... * @param scale a value greater than or equal to zero representing the * desired number of digits to the right of the decimal point * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. * @deprecated in Java2.0 */ public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal"); return ((BigDecimal)callResult[parameterIndex-1]); } /* * Get the value of a SQL BINARY or VARBINARY parameter as a Java * byte[] * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. */ public byte[] getBytes(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.VARBINARY, Types.BINARY, "Bytes"); return ((byte [])callResult[parameterIndex-1]); } /* * Get the value of a SQL DATE parameter as a java.sql.Date object * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. */ public java.sql.Date getDate(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.DATE, "Date"); return (java.sql.Date)callResult[parameterIndex-1]; } /* * Get the value of a SQL TIME parameter as a java.sql.Time object. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. */ public java.sql.Time getTime(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.TIME, "Time"); return (java.sql.Time)callResult[parameterIndex-1]; } /* * Get the value of a SQL TIMESTAMP parameter as a java.sql.Timestamp object. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return the parameter value; if the value is SQL NULL, the result is null * @exception SQLException if a database-access error occurs. */ public java.sql.Timestamp getTimestamp(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.TIMESTAMP, "Timestamp"); return (java.sql.Timestamp)callResult[parameterIndex-1]; } // getObject returns a Java object for the parameter. // See the JDBC spec's "Dynamic Programming" chapter for details. /* * Get the value of a parameter as a Java object. * * <p>This method returns a Java object whose type coresponds to the * SQL type that was registered for this parameter using * registerOutParameter. * * <P>Note that this method may be used to read datatabase-specific, * abstract data types. This is done by specifying a targetSqlType * of java.sql.types.OTHER, which allows the driver to return a * database-specific Java type. * * <p>See the JDBC spec's "Dynamic Programming" chapter for details. * * @param parameterIndex the first parameter is 1, the second is 2,... * @return A java.lang.Object holding the OUT parameter value. * @exception SQLException if a database-access error occurs. */ public Object getObject(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex); return callResult[parameterIndex-1]; } /* * Returns the SQL statement with the current template values * substituted. */ public String toString() { if (preparedQuery == null) return super.toString(); return preparedQuery.toString(preparedParameters); } /* * Note if s is a String it should be escaped by the caller to avoid SQL * injection attacks. It is not done here for efficency reasons as * most calls to this method do not require escaping as the source * of the string is known safe (i.e. Integer.toString()) */ protected void bindLiteral(int paramIndex, String s, int oid) throws SQLException { if(adjustIndex) paramIndex--; preparedParameters.setLiteralParameter(paramIndex, s, oid); } protected void bindBytes(int paramIndex, byte[] b, int oid) throws SQLException { if(adjustIndex) paramIndex--; preparedParameters.setBinaryParameter(paramIndex, b, oid); } /* * This version is for values that should turn into strings * e.g. setString directly calls bindString with no escaping; * the per-protocol ParameterList does escaping as needed. */ private void bindString(int paramIndex, String s, int oid) throws SQLException { if (adjustIndex) paramIndex--; preparedParameters.setStringParameter( paramIndex, s, oid); } /** * this method will turn a string of the form * { [? =] call <some_function> [(?, [?,..])] } * into the PostgreSQL format which is * select <some_function> (?, [?, ...]) as result * or select * from <some_function> (?, [?, ...]) as result (7.3) */ private String modifyJdbcCall(String p_sql) throws SQLException { checkClosed(); // Mini-parser for JDBC function-call syntax (only) // TODO: Merge with escape processing (and parameter parsing?) // so we only parse each query once. isFunction = false; boolean stdStrings = connection.getStandardConformingStrings(); int len = p_sql.length(); int state = 1; boolean inQuotes = false, inEscape = false; outParmBeforeFunc = false; int startIndex = -1, endIndex = -1; boolean syntaxError = false; int i = 0; while (i < len && !syntaxError) { char ch = p_sql.charAt(i); switch (state) { case 1: // Looking for { at start of query if (ch == '{') { ++i; ++state; } else if (Character.isWhitespace(ch)) { ++i; } else { // Not function-call syntax. Skip the rest of the string. i = len; } break; case 2: // After {, looking for ? or =, skipping whitespace if (ch == '?') { outParmBeforeFunc = isFunction = true; // { ? = call ... } -- function with one out parameter ++i; ++state; } else if (ch == 'c' || ch == 'C') { // { call ... } -- proc with no out parameters state += 3; // Don't increase 'i' } else if (Character.isWhitespace(ch)) { ++i; } else { // "{ foo ...", doesn't make sense, complain. syntaxError = true; } break; case 3: // Looking for = after ?, skipping whitespace if (ch == '=') { ++i; ++state; } else if (Character.isWhitespace(ch)) { ++i; } else { syntaxError = true; } break; case 4: // Looking for 'call' after '? =' skipping whitespace if (ch == 'c' || ch == 'C') { ++state; // Don't increase 'i'. } else if (Character.isWhitespace(ch)) { ++i; } else { syntaxError = true; } break; case 5: // Should be at 'call ' either at start of string or after ?= if ((ch == 'c' || ch == 'C') && i + 4 <= len && p_sql.substring(i, i + 4).equalsIgnoreCase("call")) { isFunction=true; i += 4; ++state; } else if (Character.isWhitespace(ch)) { ++i; } else { syntaxError = true; } break; case 6: // Looking for whitespace char after 'call' if (Character.isWhitespace(ch)) { // Ok, we found the start of the real call. ++i; ++state; startIndex = i; } else { syntaxError = true; } break; case 7: // In "body" of the query (after "{ [? =] call ") if (ch == '\'') { inQuotes = !inQuotes; ++i; } else if (inQuotes && ch == '\\' && !stdStrings) { // Backslash in string constant, skip next character. i += 2; } else if (!inQuotes && ch == '{') { inEscape = !inEscape; ++i; } else if (!inQuotes && ch == '}') { if (!inEscape) { // Should be end of string. endIndex = i; ++i; ++state; } else { inEscape = false; } } else if (!inQuotes && ch == ';') { syntaxError = true; } else { // Everything else is ok. ++i; } break; case 8: // At trailing end of query, eating whitespace if (Character.isWhitespace(ch)) { ++i; } else { syntaxError = true; } break; default: throw new IllegalStateException("somehow got into bad state " + state); } } // We can only legally end in a couple of states here. if (i == len && !syntaxError) { if (state == 1) return p_sql; // Not an escaped syntax. if (state != 8) syntaxError = true; // Ran out of query while still parsing } if (syntaxError) throw new PSQLException (GT.tr("Malformed function or procedure escape syntax at offset {0}.", new Integer(i)), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL); if (connection.haveMinimumServerVersion("8.1") && ((AbstractJdbc2Connection)connection).getProtocolVersion() == 3) { String s = p_sql.substring(startIndex, endIndex ); StringBuilder sb = new StringBuilder(s); if ( outParmBeforeFunc ) { // move the single out parameter into the function call // so that it can be treated like all other parameters boolean needComma=false; // have to use String.indexOf for java 2 int opening = s.indexOf('(')+1; int closing = s.indexOf(')'); for ( int j=opening; j< closing;j++ ) { if ( !Character.isWhitespace(sb.charAt(j)) ) { needComma = true; break; } } if ( needComma ) { sb.insert(opening, "?,"); } else { sb.insert(opening, "?"); } } return "select * from " + sb.toString() + " as result"; } else { return "select " + p_sql.substring(startIndex, endIndex) + " as result"; } } /** helperfunction for the getXXX calls to check isFunction and index == 1 * Compare BOTH type fields against the return type. */ protected void checkIndex (int parameterIndex, int type1, int type2, String getName) throws SQLException { checkIndex (parameterIndex); if (type1 != this.testReturn[parameterIndex-1] && type2 != this.testReturn[parameterIndex-1]) throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.", new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1], getName, "java.sql.Types=" + type1}), PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH); } /** helperfunction for the getXXX calls to check isFunction and index == 1 */ protected void checkIndex (int parameterIndex, int type, String getName) throws SQLException { checkIndex (parameterIndex); if (type != this.testReturn[parameterIndex-1]) throw new PSQLException(GT.tr("Parameter of type {0} was registered, but call to get{1} (sqltype={2}) was made.", new Object[]{"java.sql.Types=" + testReturn[parameterIndex-1], getName, "java.sql.Types=" + type}), PSQLState.MOST_SPECIFIC_TYPE_DOES_NOT_MATCH); } private void checkIndex (int parameterIndex) throws SQLException { checkIndex(parameterIndex, true); } /** helperfunction for the getXXX calls to check isFunction and index == 1 * @param parameterIndex index of getXXX (index) * check to make sure is a function and index == 1 */ private void checkIndex (int parameterIndex, boolean fetchingData) throws SQLException { if (!isFunction) throw new PSQLException(GT.tr("A CallableStatement was declared, but no call to registerOutParameter(1, <some type>) was made."), PSQLState.STATEMENT_NOT_ALLOWED_IN_FUNCTION_CALL); if (fetchingData) { if (!returnTypeSet) throw new PSQLException(GT.tr("No function outputs were registered."), PSQLState.OBJECT_NOT_IN_STATE); if (callResult == null) throw new PSQLException(GT.tr("Results cannot be retrieved from a CallableStatement before it is executed."), PSQLState.NO_DATA); lastIndex = parameterIndex; } } public void setPrepareThreshold(int newThreshold) throws SQLException { checkClosed(); if (newThreshold < 0) { forceBinaryTransfers = true; newThreshold = 1; } else forceBinaryTransfers = false; this.m_prepareThreshold = newThreshold; } public int getPrepareThreshold() { return m_prepareThreshold; } public void setUseServerPrepare(boolean flag) throws SQLException { setPrepareThreshold(flag ? 1 : 0); } public boolean isUseServerPrepare() { return (preparedQuery != null && m_prepareThreshold != 0 && m_useCount + 1 >= m_prepareThreshold); } protected void checkClosed() throws SQLException { if (isClosed) throw new PSQLException(GT.tr("This statement has been closed."), PSQLState.OBJECT_NOT_IN_STATE); } // ** JDBC 2 Extensions ** public void addBatch(String p_sql) throws SQLException { checkClosed(); if (preparedQuery != null) throw new PSQLException(GT.tr("Can''t use query methods that take a query string on a PreparedStatement."), PSQLState.WRONG_OBJECT_TYPE); if (batchStatements == null) { batchStatements = new ArrayList(); batchParameters = new ArrayList(); } p_sql = replaceProcessing(p_sql); batchStatements.add(connection.getQueryExecutor().createSimpleQuery(p_sql)); batchParameters.add(null); } public void clearBatch() throws SQLException { if (batchStatements != null) { batchStatements.clear(); batchParameters.clear(); } } // // ResultHandler for batch queries. // private class BatchResultHandler implements ResultHandler { private BatchUpdateException batchException = null; private int resultIndex = 0; private final Query[] queries; private final ParameterList[] parameterLists; private final int[] updateCounts; private final boolean expectGeneratedKeys; private ResultSet generatedKeys; BatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts, boolean expectGeneratedKeys) { this.queries = queries; this.parameterLists = parameterLists; this.updateCounts = updateCounts; this.expectGeneratedKeys = expectGeneratedKeys; } public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) { if (!expectGeneratedKeys) { handleError(new PSQLException(GT.tr("A result was returned when none was expected."), PSQLState.TOO_MANY_RESULTS)); } else { if (generatedKeys == null) { try { generatedKeys = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor); } catch (SQLException e) { handleError(e); } } else { ((AbstractJdbc2ResultSet)generatedKeys).addRows(tuples); } } } public void handleCommandStatus(String status, int updateCount, long insertOID) { if (resultIndex >= updateCounts.length) { handleError(new PSQLException(GT.tr("Too many update results were returned."), PSQLState.TOO_MANY_RESULTS)); return ; } updateCounts[resultIndex++] = updateCount; } public void handleWarning(SQLWarning warning) { AbstractJdbc2Statement.this.addWarning(warning); } public void handleError(SQLException newError) { if (batchException == null) { int[] successCounts; if (resultIndex >= updateCounts.length) successCounts = updateCounts; else { successCounts = new int[resultIndex]; System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex); } String queryString = "<unknown>"; if (resultIndex < queries.length) queryString = queries[resultIndex].toString(parameterLists[resultIndex]); batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.", new Object[]{ new Integer(resultIndex), queryString}), newError.getSQLState(), successCounts); } batchException.setNextException(newError); } public void handleCompletion() throws SQLException { if (batchException != null) throw batchException; } public ResultSet getGeneratedKeys() { return generatedKeys; } } private class CallableBatchResultHandler implements ResultHandler { private BatchUpdateException batchException = null; private int resultIndex = 0; private final Query[] queries; private final ParameterList[] parameterLists; private final int[] updateCounts; CallableBatchResultHandler(Query[] queries, ParameterList[] parameterLists, int[] updateCounts) { this.queries = queries; this.parameterLists = parameterLists; this.updateCounts = updateCounts; } public void handleResultRows(Query fromQuery, Field[] fields, List tuples, ResultCursor cursor) { } public void handleCommandStatus(String status, int updateCount, long insertOID) { if (resultIndex >= updateCounts.length) { handleError(new PSQLException(GT.tr("Too many update results were returned."), PSQLState.TOO_MANY_RESULTS)); return ; } updateCounts[resultIndex++] = updateCount; } public void handleWarning(SQLWarning warning) { AbstractJdbc2Statement.this.addWarning(warning); } public void handleError(SQLException newError) { if (batchException == null) { int[] successCounts; if (resultIndex >= updateCounts.length) successCounts = updateCounts; else { successCounts = new int[resultIndex]; System.arraycopy(updateCounts, 0, successCounts, 0, resultIndex); } String queryString = "<unknown>"; if (resultIndex < queries.length) queryString = queries[resultIndex].toString(parameterLists[resultIndex]); batchException = new BatchUpdateException(GT.tr("Batch entry {0} {1} was aborted. Call getNextException to see the cause.", new Object[]{ new Integer(resultIndex), queryString}), newError.getSQLState(), successCounts); } batchException.setNextException(newError); } public void handleCompletion() throws SQLException { if (batchException != null) throw batchException; } } public int[] executeBatch() throws SQLException { checkClosed(); closeForNextExecution(); if (batchStatements == null || batchStatements.isEmpty()) return new int[0]; int size = batchStatements.size(); int[] updateCounts = new int[size]; // Construct query/parameter arrays. Query[] queries = (Query[])batchStatements.toArray(new Query[batchStatements.size()]); ParameterList[] parameterLists = (ParameterList[])batchParameters.toArray(new ParameterList[batchParameters.size()]); batchStatements.clear(); batchParameters.clear(); int flags = 0; // Force a Describe before any execution? We need to do this if we're going // to send anything dependent on the Desribe results, e.g. binary parameters. boolean preDescribe = false; if (wantsGeneratedKeysAlways) { /* * This batch will return generated keys, tell the executor to * expect result rows. We also force a Describe later so we know * the size of the results to expect. * * If the parameter type(s) change between batch entries and the * default binary-mode changes we might get mixed binary and text * in a single result set column, which we cannot handle. To prevent * this, disable binary transfer mode in batches that return generated * keys. See GitHub issue #267 */ flags = QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS | QueryExecutor.QUERY_NO_BINARY_TRANSFER; } else { // If a batch hasn't specified that it wants generated keys, using the appropriate // Connection.createStatement(...) interfaces, disallow any result set. flags = QueryExecutor.QUERY_NO_RESULTS; } // Only use named statements after we hit the threshold if (preparedQuery != null) { m_useCount += queries.length; } if (m_prepareThreshold == 0 || m_useCount < m_prepareThreshold) { flags |= QueryExecutor.QUERY_ONESHOT; } else { // If a batch requests generated keys and isn't already described, // force a Describe of the query before proceeding. That way we can // determine the appropriate size of each batch by estimating the // maximum data returned. Without that, we don't know how many queries // we'll be able to queue up before we risk a deadlock. // (see v3.QueryExecutorImpl's MAX_BUFFERED_RECV_BYTES) preDescribe = wantsGeneratedKeysAlways && !queries[0].isStatementDescribed(); /* * It's also necessary to force a Describe on the first execution of the * new statement, even though we already described it, to work around * bug #267. */ flags |= QueryExecutor.QUERY_FORCE_DESCRIBE_PORTAL; } if (connection.getAutoCommit()) flags |= QueryExecutor.QUERY_SUPPRESS_BEGIN; if (preDescribe || forceBinaryTransfers) { // Do a client-server round trip, parsing and describing the query so we // can determine its result types for use in binary parameters, batch sizing, // etc. int flags2 = flags | QueryExecutor.QUERY_DESCRIBE_ONLY; StatementResultHandler handler2 = new StatementResultHandler(); connection.getQueryExecutor().execute(queries[0], parameterLists[0], handler2, 0, 0, flags2); ResultWrapper result2 = handler2.getResults(); if (result2 != null) { result2.getResultSet().close(); } } result = null; ResultHandler handler; if (isFunction) { handler = new CallableBatchResultHandler(queries, parameterLists, updateCounts ); } else { handler = new BatchResultHandler(queries, parameterLists, updateCounts, wantsGeneratedKeysAlways); } try { startTimer(); connection.getQueryExecutor().execute(queries, parameterLists, handler, maxrows, fetchSize, flags); } finally { killTimerTask(); } if (wantsGeneratedKeysAlways) { generatedKeys = new ResultWrapper(((BatchResultHandler)handler).getGeneratedKeys()); } return updateCounts; } /* * Cancel can be used by one thread to cancel a statement that * is being executed by another thread. * <p> * * @exception SQLException only because thats the spec. */ public void cancel() throws SQLException { connection.cancelQuery(); } public Connection getConnection() throws SQLException { return (Connection) connection; } public int getFetchDirection() { return fetchdirection; } public int getResultSetConcurrency() { return concurrency; } public int getResultSetType() { return resultsettype; } public void setFetchDirection(int direction) throws SQLException { switch (direction) { case ResultSet.FETCH_FORWARD: case ResultSet.FETCH_REVERSE: case ResultSet.FETCH_UNKNOWN: fetchdirection = direction; break; default: throw new PSQLException(GT.tr("Invalid fetch direction constant: {0}.", new Integer(direction)), PSQLState.INVALID_PARAMETER_VALUE); } } public void setFetchSize(int rows) throws SQLException { checkClosed(); if (rows < 0) throw new PSQLException(GT.tr("Fetch size must be a value greater to or equal to 0."), PSQLState.INVALID_PARAMETER_VALUE); fetchSize = rows; } public void addBatch() throws SQLException { checkClosed(); if (batchStatements == null) { batchStatements = new ArrayList(); batchParameters = new ArrayList(); } // we need to create copies of our parameters, otherwise the values can be changed batchStatements.add(preparedQuery); batchParameters.add(preparedParameters.copy()); } public ResultSetMetaData getMetaData() throws SQLException { checkClosed(); ResultSet rs = getResultSet(); if (rs == null || ((AbstractJdbc2ResultSet)rs).isResultSetClosed() ) { // OK, we haven't executed it yet, or it was closed // we've got to go to the backend // for more info. We send the full query, but just don't // execute it. int flags = QueryExecutor.QUERY_ONESHOT | QueryExecutor.QUERY_DESCRIBE_ONLY | QueryExecutor.QUERY_SUPPRESS_BEGIN; StatementResultHandler handler = new StatementResultHandler(); connection.getQueryExecutor().execute(preparedQuery, preparedParameters, handler, 0, 0, flags); ResultWrapper wrapper = handler.getResults(); if (wrapper != null) { rs = wrapper.getResultSet(); } } if (rs != null) return rs.getMetaData(); return null; } public void setArray(int i, java.sql.Array x) throws SQLException { checkClosed(); if (null == x) { setNull(i, Types.ARRAY); return; } // This only works for Array implementations that return a valid array // literal from Array.toString(), such as the implementation we return // from ResultSet.getArray(). Eventually we need a proper implementation // here that works for any Array implementation. // Use a typename that is "_" plus the base type; this matches how the // backend looks for array types. String typename = "_" + x.getBaseTypeName(); int oid = connection.getTypeInfo().getPGType(typename); if (oid == Oid.UNSPECIFIED) throw new PSQLException(GT.tr("Unknown type {0}.", typename), PSQLState.INVALID_PARAMETER_TYPE); if (x instanceof AbstractJdbc2Array) { AbstractJdbc2Array arr = (AbstractJdbc2Array) x; if (arr.isBinary()) { bindBytes(i, arr.toBytes(), oid); return; } } setString(i, x.toString(), oid); } protected long createBlob(int i, InputStream inputStream, long length) throws SQLException { LargeObjectManager lom = connection.getLargeObjectAPI(); long oid = lom.createLO(); LargeObject lob = lom.open(oid); OutputStream outputStream = lob.getOutputStream(); byte[] buf = new byte[4096]; try { long remaining; if (length > 0) { remaining = length; } else { remaining = Long.MAX_VALUE; } int numRead = inputStream.read(buf, 0, (length > 0 && remaining < buf.length ? (int)remaining : buf.length)); while (numRead != -1 && remaining > 0) { remaining -= numRead; outputStream.write(buf, 0, numRead); numRead = inputStream.read(buf, 0, (length > 0 && remaining < buf.length ? (int)remaining : buf.length)); } } catch (IOException se) { throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se); } finally { try { outputStream.close(); } catch ( Exception e ) { } } return oid; } public void setBlob(int i, Blob x) throws SQLException { checkClosed(); if (x == null) { setNull(i, Types.BLOB); return; } InputStream inStream = x.getBinaryStream(); try { long oid = createBlob(i, inStream, x.length()); setLong(i, oid); } finally { try { inStream.close(); } catch ( Exception e ) { } } } public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException { checkClosed(); if (x == null) { if (connection.haveMinimumServerVersion("7.2")) { setNull(i, Types.VARCHAR); } else { setNull(i, Types.CLOB); } return; } if (length < 0) throw new PSQLException(GT.tr("Invalid stream length {0}.", new Integer(length)), PSQLState.INVALID_PARAMETER_VALUE); if (connection.haveMinimumCompatibleVersion("7.2")) { //Version 7.2 supports CharacterStream for for the PG text types //As the spec/javadoc for this method indicate this is to be used for //large text values (i.e. LONGVARCHAR) PG doesn't have a separate //long varchar datatype, but with toast all the text datatypes are capable of //handling very large values. Thus the implementation ends up calling //setString() since there is no current way to stream the value to the server char[] l_chars = new char[length]; int l_charsRead = 0; try { while (true) { int n = x.read(l_chars, l_charsRead, length - l_charsRead); if (n == -1) break; l_charsRead += n; if (l_charsRead == length) break; } } catch (IOException l_ioe) { throw new PSQLException(GT.tr("Provided Reader failed."), PSQLState.UNEXPECTED_ERROR, l_ioe); } setString(i, new String(l_chars, 0, l_charsRead)); } else { //Version 7.1 only supported streams for LargeObjects //but the jdbc spec indicates that streams should be //available for LONGVARCHAR instead LargeObjectManager lom = connection.getLargeObjectAPI(); long oid = lom.createLO(); LargeObject lob = lom.open(oid); OutputStream los = lob.getOutputStream(); try { // could be buffered, but then the OutputStream returned by LargeObject // is buffered internally anyhow, so there would be no performance // boost gained, if anything it would be worse! int c = x.read(); int p = 0; while (c > -1 && p < length) { los.write(c); c = x.read(); p++; } los.close(); } catch (IOException se) { throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se); } // lob is closed by the stream so don't call lob.close() setLong(i, oid); } } public void setClob(int i, Clob x) throws SQLException { checkClosed(); if (x == null) { setNull(i, Types.CLOB); return; } Reader l_inStream = x.getCharacterStream(); int l_length = (int) x.length(); LargeObjectManager lom = connection.getLargeObjectAPI(); long oid = lom.createLO(); LargeObject lob = lom.open(oid); Charset connectionCharset = Charset.forName(connection.getEncoding().name()); OutputStream los = lob.getOutputStream(); Writer lw = new OutputStreamWriter(los, connectionCharset); try { // could be buffered, but then the OutputStream returned by LargeObject // is buffered internally anyhow, so there would be no performance // boost gained, if anything it would be worse! int c = l_inStream.read(); int p = 0; while (c > -1 && p < l_length) { lw.write(c); c = l_inStream.read(); p++; } lw.close(); } catch (IOException se) { throw new PSQLException(GT.tr("Unexpected error writing large object to database."), PSQLState.UNEXPECTED_ERROR, se); } // lob is closed by the stream so don't call lob.close() setLong(i, oid); } public void setNull(int i, int t, String s) throws SQLException { checkClosed(); setNull(i, t); } public void setRef(int i, Ref x) throws SQLException { throw Driver.notImplemented(this.getClass(), "setRef(int,Ref)"); } public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException { checkClosed(); if (d == null) { setNull(i, Types.DATE); return; } if (connection.binaryTransferSend(Oid.DATE)) { byte[] val = new byte[4]; TimeZone tz = cal != null ? cal.getTimeZone() : null; connection.getTimestampUtils().toBinDate(tz, val, d); preparedParameters.setBinaryParameter(i, val, Oid.DATE); return; } if (cal != null) cal = (Calendar)cal.clone(); // We must use UNSPECIFIED here, or inserting a Date-with-timezone into a // timestamptz field does an unexpected rotation by the server's TimeZone: // // We want to interpret 2005/01/01 with calendar +0100 as // "local midnight in +0100", but if we go via date it interprets it // as local midnight in the server's timezone: // template1=# select '2005-01-01+0100'::timestamptz; // timestamptz // ------------------------ // 2005-01-01 02:00:00+03 // (1 row) // template1=# select '2005-01-01+0100'::date::timestamptz; // timestamptz // ------------------------ // 2005-01-01 00:00:00+03 // (1 row) bindString(i, connection.getTimestampUtils().toString(cal, d), Oid.UNSPECIFIED); } public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException { checkClosed(); if (t == null) { setNull(i, Types.TIME); return; } if (cal != null) cal = (Calendar)cal.clone(); bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED); } public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException { checkClosed(); if (t == null) { setNull(i, Types.TIMESTAMP); return; } if (cal != null) cal = (Calendar)cal.clone(); // Use UNSPECIFIED as a compromise to get both TIMESTAMP and TIMESTAMPTZ working. // This is because you get this in a +1300 timezone: // // template1=# select '2005-01-01 15:00:00 +1000'::timestamptz; // timestamptz // ------------------------ // 2005-01-01 18:00:00+13 // (1 row) // template1=# select '2005-01-01 15:00:00 +1000'::timestamp; // timestamp // --------------------- // 2005-01-01 15:00:00 // (1 row) // template1=# select '2005-01-01 15:00:00 +1000'::timestamptz::timestamp; // timestamp // --------------------- // 2005-01-01 18:00:00 // (1 row) // So we want to avoid doing a timestamptz -> timestamp conversion, as that // will first convert the timestamptz to an equivalent time in the server's // timezone (+1300, above), then turn it into a timestamp with the "wrong" // time compared to the string we originally provided. But going straight // to timestamp is OK as the input parser for timestamp just throws away // the timezone part entirely. Since we don't know ahead of time what type // we're actually dealing with, UNSPECIFIED seems the lesser evil, even if it // does give more scope for type-mismatch errors being silently hidden. bindString(i, connection.getTimestampUtils().toString(cal, t), Oid.UNSPECIFIED); // Let the server infer the right type. } // ** JDBC 2 Extensions for CallableStatement** public java.sql.Array getArray(int i) throws SQLException { checkClosed(); checkIndex(i, Types.ARRAY, "Array"); return (Array)callResult[i-1]; } public java.math.BigDecimal getBigDecimal(int parameterIndex) throws SQLException { checkClosed(); checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal"); return ((BigDecimal)callResult[parameterIndex-1]); } public Blob getBlob(int i) throws SQLException { throw Driver.notImplemented(this.getClass(), "getBlob(int)"); } public Clob getClob(int i) throws SQLException { throw Driver.notImplemented(this.getClass(), "getClob(int)"); } public Object getObjectImpl(int i, java.util.Map map) throws SQLException { if (map == null || map.isEmpty()) { return getObject(i); } throw Driver.notImplemented(this.getClass(), "getObjectImpl(int,Map)"); } public Ref getRef(int i) throws SQLException { throw Driver.notImplemented(this.getClass(), "getRef(int)"); } public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException { checkClosed(); checkIndex(i, Types.DATE, "Date"); if (callResult[i-1] == null) return null; if (cal != null) cal = (Calendar)cal.clone(); String value = callResult[i-1].toString(); return connection.getTimestampUtils().toDate(cal, value); } public Time getTime(int i, java.util.Calendar cal) throws SQLException { checkClosed(); checkIndex(i, Types.TIME, "Time"); if (callResult[i-1] == null) return null; if (cal != null) cal = (Calendar)cal.clone(); String value = callResult[i-1].toString(); return connection.getTimestampUtils().toTime(cal, value); } public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException { checkClosed(); checkIndex(i, Types.TIMESTAMP, "Timestamp"); if (callResult[i-1] == null) return null; if (cal != null) cal = (Calendar)cal.clone(); String value = callResult[i-1].toString(); return connection.getTimestampUtils().toTimestamp(cal, value); } // no custom types allowed yet.. public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { throw Driver.notImplemented(this.getClass(), "registerOutParameter(int,int,String)"); } protected synchronized void startTimer() { if (timeout == 0) return; /* * there shouldn't be any previous timer active, but better safe than * sorry. */ killTimerTask(); cancelTimerTask = new TimerTask() { public void run() { try { AbstractJdbc2Statement.this.cancel(); } catch (SQLException e) { } } }; connection.addTimerTask(cancelTimerTask, timeout * 1000); } private synchronized void killTimerTask() { if (cancelTimerTask != null) { cancelTimerTask.cancel(); cancelTimerTask = null; connection.purgeTimerTasks(); } } protected boolean getForceBinaryTransfer() { return forceBinaryTransfers; } }
bsd-3-clause
maxsnew/TAPL
SimplyTyped/Lambda/Implementation/Grammar.hs
5507
module Grammar where import Control.Applicative ((<$>), (<*>)) import Control.Arrow ((***)) import Control.Monad.Reader (Reader, ask, local, runReader) import Data.List (elemIndex) import Data.Maybe (fromJust) import Data.Set as Set (Set, empty, singleton, toList, union, unions) import Test.QuickCheck (Arbitrary(..), elements, oneof, sized) -- | Simply Typed Lambda Calculus data Type = TyUnit | TyBool | TyNat | TyArr Type Type deriving (Show, Eq) data Term = TUnit | TTrue | TFalse | TNat Integer | TIf Term Term Term | TVar Int | TAbs Type Term | TApp Term Term deriving (Show, Eq) -- | Untyped Lambda Calculus using explicit variable names. data NamedTerm = NUnit | NTrue | NFalse | NNat Integer | NIf NamedTerm NamedTerm NamedTerm | NVar String | NAbs Type String NamedTerm | NApp NamedTerm NamedTerm deriving (Show, Eq) validIdentifiers :: [String] validIdentifiers = (flip (:)) <$> ("":validRest) <*> validStart where validStart = ['a'..'z'] ++ ['A'..'Z'] ++ "_" validRest = (flip (:)) <$> ("" : validRest) <*> (validStart ++ ['0'..'9'] ++ "'") -- | Convert back and forth between De Bruijn and explicit names -- | Returns the nameless term and a list representing the encodings of -- | the free variables (the naming context). removeNames :: NamedTerm -> (Term, [String]) removeNames t = withFree $ runReader (rec t) free where withFree x = (x, free) free = freeVars t rec nt = do ctx <- ask case nt of NUnit -> return TUnit NTrue -> return TTrue NFalse -> return TFalse NNat i -> return $ TNat i NIf t1 t2 t3 -> TIf <$> rec t1 <*> rec t2 <*> rec t3 (NVar s) -> let i = fromJust $ s `elemIndex` ctx in return $ TVar i (NAbs ty s bod) -> TAbs ty <$> (local (s:) $ rec bod) (NApp t1 t2) -> TApp <$> rec t1 <*> rec t2 freeVars :: NamedTerm -> [String] freeVars t = Set.toList $ runReader (go t) [] where go :: NamedTerm -> Reader [String] (Set String) go nt = do bound <- ask case nt of NUnit -> return Set.empty NTrue -> return Set.empty NFalse -> return Set.empty NNat{} -> return Set.empty NIf nt1 nt2 nt3 -> do free1 <- go nt1 free2 <- go nt2 free3 <- go nt3 return $ Set.unions $ [free1, free2, free3] NVar s -> return $ if s `elem` bound then Set.empty else Set.singleton s NAbs _ s bod -> local (s:) $ go bod NApp t1 t2 -> do free1 <- go t1 free2 <- go t2 return $ free1 `Set.union` free2 restoreNames :: Term -> [String] -> NamedTerm restoreNames t' ctx = runReader (rec t') (nameCtx) where rec :: Term -> Reader ([String], [String]) NamedTerm rec TUnit = return NUnit rec TTrue = return NTrue rec TFalse = return NFalse rec (TNat i) = return $ NNat i rec (TIf t1 t2 t3) = NIf <$> rec t1 <*> rec t2 <*> rec t3 rec (TVar i) = do (names, _) <- ask return $ NVar (names !! i) rec (TApp t1 t2) = NApp <$> rec t1 <*> rec t2 rec (TAbs ty t) = do (_, unused) <- ask let s = head unused in NAbs ty s <$> (local ((s:) *** tail) $ rec t) nameCtx = splitAt (length ctx) validIdentifiers -- | Testing instance Arbitrary Type where arbitrary = sized type' where type' 0 = elements [TyUnit, TyBool, TyNat] type' n = TyArr <$> halved <*> halved where halved = type' (n `div` 2) shrink (TyArr t1 t2) = [t1, t2] shrink _ = [] instance Arbitrary Term where arbitrary = sized term' where term' 0 = oneof $ (TVar . abs <$> arbitrary) : (TNat <$> arbitrary) : map return [TUnit, TTrue, TFalse] term' n = oneof [ TIf <$> thirded <*> thirded <*> thirded , TAbs <$> arbitrary <*> (term' (n-1)) , TApp <$> halved <*> halved ] where halved = term' (n `div` 2) thirded = term' (n `div` 3) shrink (TIf t1 t2 t3) = [t1, t2, t3] shrink (TApp t1 t2) = [t1, t2] shrink (TAbs ty t) = t : ((flip TAbs t) <$> shrink ty) shrink _ = [] instance Arbitrary NamedTerm where arbitrary = sized term' where term' 0 = oneof $ (NVar <$> vars) : map return [NTrue, NFalse] term' n = oneof [ NIf <$> thirded <*> thirded <*> thirded , NAbs <$> arbitrary <*> vars <*> (term' (n-1)) , NApp <$> halved <*> halved ] where halved = term' (n `div` 2) thirded = term' (n `div` 3) vars = elements . fmap (:[]) $ ['a'..'z'] shrink (NApp t1 t2) = [t1, t2] shrink (NAbs _ _ t) = [t] shrink _ = [] prop_idempotent_encoding :: NamedTerm -> Bool prop_idempotent_encoding nt = run nt == (run . run $ nt) where run = uncurry restoreNames . removeNames
bsd-3-clause
wirepair/netcode
client.go
11175
package netcode import ( "log" "net" "time" ) const CLIENT_MAX_RECEIVE_PACKETS = 64 const PACKET_SEND_RATE = 10.0 const NUM_DISCONNECT_PACKETS = 10 // number of disconnect packets the client/server should send when disconnecting type Context struct { WritePacketKey []byte ReadPacketKey []byte } type ClientState int8 const ( StateTokenExpired ClientState = -6 StateInvalidConnectToken = -5 StateConnectionTimedOut = -4 StateConnectionResponseTimedOut = -3 StateConnectionRequestTimedOut = -2 StateConnectionDenied = -1 StateDisconnected = 0 StateSendingConnectionRequest = 1 StateSendingConnectionResponse = 2 StateConnected = 3 ) var clientStateMap = map[ClientState]string{ StateTokenExpired: "connect token expired", StateInvalidConnectToken: "invalid connect token", StateConnectionTimedOut: "connection timed out", StateConnectionResponseTimedOut: "connection response timed out", StateConnectionRequestTimedOut: "connection request timed out", StateConnectionDenied: "connection denied", StateDisconnected: "disconnected", StateSendingConnectionRequest: "sending connection request", StateSendingConnectionResponse: "sending connection response", StateConnected: "connected", } type Client struct { id uint64 connectToken *ConnectToken time float64 startTime float64 lastPacketSendTime float64 lastPacketRecvTime float64 shouldDisconnect bool state ClientState shouldDisconnectState ClientState sequence uint64 challengeSequence uint64 clientIndex uint32 maxClients uint32 serverIndex int address *net.UDPAddr serverAddress *net.UDPAddr challengeData []byte context *Context replayProtection *ReplayProtection conn *NetcodeConn packetQueue *PacketQueue allowedPackets []byte packetCh chan *NetcodeData } func NewClient(connectToken *ConnectToken) *Client { c := &Client{connectToken: connectToken} c.lastPacketRecvTime = -1 c.lastPacketSendTime = -1 c.packetCh = make(chan *NetcodeData, PACKET_QUEUE_SIZE) c.setState(StateDisconnected) c.shouldDisconnect = false c.challengeData = make([]byte, CHALLENGE_TOKEN_BYTES) c.context = &Context{} c.packetQueue = NewPacketQueue(PACKET_QUEUE_SIZE) c.replayProtection = NewReplayProtection() c.allowedPackets = make([]byte, ConnectionNumPackets) c.allowedPackets[ConnectionDenied] = 1 c.allowedPackets[ConnectionChallenge] = 1 c.allowedPackets[ConnectionKeepAlive] = 1 c.allowedPackets[ConnectionPayload] = 1 c.allowedPackets[ConnectionDisconnect] = 1 return c } func (c *Client) GetState() ClientState { return c.state } func (c *Client) SetId(id uint64) { c.id = id } func (c *Client) setState(newState ClientState) { c.state = newState } func (c *Client) Connect() error { var err error c.startTime = 0 if c.serverIndex > len(c.connectToken.ServerAddrs) { return ErrExceededServerNumber } c.serverAddress = &c.connectToken.ServerAddrs[c.serverIndex] c.conn = NewNetcodeConn() c.conn.SetRecvHandler(c.handleNetcodeData) if err = c.conn.Dial(c.serverAddress); err != nil { return err } c.context.ReadPacketKey = c.connectToken.ServerKey c.context.WritePacketKey = c.connectToken.ClientKey c.setState(StateSendingConnectionRequest) return nil } func (c *Client) connectNextServer() bool { if c.serverIndex+1 >= len(c.connectToken.ServerAddrs) { return false } c.serverIndex++ c.serverAddress = &c.connectToken.ServerAddrs[c.serverIndex] c.Reset() log.Printf("client[%d] connecting to next server %s (%d/%d)\n", c.id, c.serverAddress.String(), c.serverIndex, len(c.connectToken.ServerAddrs)) if err := c.Connect(); err != nil { log.Printf("error connecting to next server: %s\n", err) return false } c.setState(StateSendingConnectionRequest) return true } func (c *Client) Close() error { return c.conn.Close() } func (c *Client) Reset() { c.lastPacketSendTime = c.time - 1 c.lastPacketRecvTime = c.time c.shouldDisconnect = false c.shouldDisconnectState = StateDisconnected c.challengeData = make([]byte, CHALLENGE_TOKEN_BYTES) c.challengeSequence = 0 c.replayProtection.Reset() } func (c *Client) resetConnectionData(newState ClientState) { c.sequence = 0 c.clientIndex = 0 c.maxClients = 0 c.startTime = 0 c.serverIndex = 0 c.serverAddress = nil c.connectToken = nil c.context = nil c.setState(newState) c.Reset() c.packetQueue.Clear() c.conn.Close() } func (c *Client) LocalAddr() net.Addr { return c.conn.LocalAddr() } func (c *Client) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } func (c *Client) Update(t float64) { c.time = t c.recv() if err := c.send(); err != nil { log.Printf("error sending packet: %s\n", err) } state := c.GetState() if state > StateDisconnected && state < StateConnected { expire := c.connectToken.ExpireTimestamp - c.connectToken.CreateTimestamp if c.startTime+float64(expire) <= c.time { log.Printf("client[%d] connect failed. connect token expired\n", c.id) c.Disconnect(StateTokenExpired, false) return } } if c.shouldDisconnect { log.Printf("client[%d] should disconnect -> %s\n", c.id, clientStateMap[c.shouldDisconnectState]) if c.connectNextServer() { return } c.Disconnect(c.shouldDisconnectState, false) return } switch c.GetState() { case StateSendingConnectionRequest: timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000) if timeout < c.time { log.Printf("client[%d] connection request timed out.\n", c.id) if c.connectNextServer() { return } c.Disconnect(StateConnectionRequestTimedOut, false) } case StateSendingConnectionResponse: timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000) if timeout < c.time { log.Printf("client[%d] connect failed. connection response timed out\n", c.id) if c.connectNextServer() { return } c.Disconnect(StateConnectionResponseTimedOut, false) } case StateConnected: timeout := c.lastPacketRecvTime + float64(c.connectToken.TimeoutSeconds*1000) if timeout < c.time { log.Printf("client[%d] connection timed out\n", c.id) c.Disconnect(StateConnectionTimedOut, false) } } } func (c *Client) recv() { // empty recv'd data from channel for { select { case recv := <-c.packetCh: c.OnPacketData(recv.data, recv.from) default: return } } } func (c *Client) Disconnect(reason ClientState, sendDisconnect bool) error { log.Printf("client[%d] disconnected: %s\n", c.id, clientStateMap[reason]) if c.GetState() <= StateDisconnected { log.Printf("state <= StateDisconnected") return nil } if sendDisconnect && c.GetState() > StateDisconnected { for i := 0; i < NUM_DISCONNECT_PACKETS; i += 1 { packet := &DisconnectPacket{} c.sendPacket(packet) } } c.resetConnectionData(reason) return nil } func (c *Client) SendData(payloadData []byte) error { if c.GetState() != StateConnected { return ErrClientNotConnected } p := NewPayloadPacket(payloadData) return c.sendPacket(p) } func (c *Client) send() error { // check our send rate prior to bother sending if c.lastPacketSendTime+float64(1.0/PACKET_SEND_RATE) >= c.time { return nil } switch c.GetState() { case StateSendingConnectionRequest: p := &RequestPacket{} p.VersionInfo = c.connectToken.VersionInfo p.ProtocolId = c.connectToken.ProtocolId p.ConnectTokenExpireTimestamp = c.connectToken.ExpireTimestamp p.ConnectTokenSequence = c.connectToken.Sequence p.ConnectTokenData = c.connectToken.PrivateData.Buffer() log.Printf("client[%d] sent connection request packet to server\n", c.id) return c.sendPacket(p) case StateSendingConnectionResponse: p := &ResponsePacket{} p.ChallengeTokenSequence = c.challengeSequence p.ChallengeTokenData = c.challengeData log.Printf("client[%d] sent connection response packet to server\n", c.id) return c.sendPacket(p) case StateConnected: p := &KeepAlivePacket{} p.ClientIndex = 0 p.MaxClients = 0 log.Printf("client[%d] sent connection keep-alive packet to server\n", c.id) return c.sendPacket(p) } return nil } func (c *Client) sendPacket(packet Packet) error { buffer := make([]byte, MAX_PACKET_BYTES) packet_bytes, err := packet.Write(buffer, c.connectToken.ProtocolId, c.sequence, c.context.WritePacketKey) if err != nil { return err } _, err = c.conn.Write(buffer[:packet_bytes]) if err != nil { log.Printf("error writing packet %s to server: %s\n", packetTypeMap[packet.GetType()], err) } c.lastPacketSendTime = c.time c.sequence++ return err } func (c *Client) RecvData() ([]byte, uint64) { packet := c.packetQueue.Pop() p, ok := packet.(*PayloadPacket) if !ok { return nil, 0 } return p.PayloadData, p.sequence } // write the netcodeData to our unbuffered packet channel. The NetcodeConn verifies // that the recv'd data is > 0 < maxBytes and is of a valid packet type before // this is even called. func (c *Client) handleNetcodeData(packetData *NetcodeData) { c.packetCh <- packetData } func (c *Client) OnPacketData(packetData []byte, from *net.UDPAddr) { var err error var size int var sequence uint64 if !addressEqual(c.serverAddress, from) { log.Printf("client[%d] unknown/old server address sent us data %s != %s\n", c.id, c.serverAddress.String(), from.String()) return } size = len(packetData) timestamp := uint64(time.Now().Unix()) packet := NewPacket(packetData) if err = packet.Read(packetData, size, c.connectToken.ProtocolId, timestamp, c.context.ReadPacketKey, nil, c.allowedPackets, c.replayProtection); err != nil { log.Printf("error reading packet: %s\n", err) } c.processPacket(packet, sequence) } func (c *Client) processPacket(packet Packet, sequence uint64) { state := c.GetState() switch packet.GetType() { case ConnectionDenied: if state == StateSendingConnectionRequest || state == StateSendingConnectionResponse { c.shouldDisconnect = true c.shouldDisconnectState = StateConnectionDenied } case ConnectionChallenge: if state != StateSendingConnectionRequest { return } p, ok := packet.(*ChallengePacket) if !ok { return } c.challengeData = p.ChallengeTokenData c.challengeSequence = p.ChallengeTokenSequence c.setState(StateSendingConnectionResponse) case ConnectionKeepAlive: p, ok := packet.(*KeepAlivePacket) if !ok { return } if state == StateSendingConnectionResponse { c.clientIndex = p.ClientIndex c.maxClients = p.MaxClients c.setState(StateConnected) } case ConnectionPayload: if state != StateConnected { return } c.packetQueue.Push(packet) case ConnectionDisconnect: if state != StateConnected { return } c.shouldDisconnect = true c.shouldDisconnectState = StateDisconnected default: return } // always update last packet recv time for valid packets. c.lastPacketRecvTime = c.time }
bsd-3-clause
ichuang/sympy
sympy/core/decorators.py
3543
""" SymPy core decorators. The purpose of this module is to expose decorators without any other dependencies, so that they can be easily imported anywhere in sympy/core. """ from functools import wraps from sympify import SympifyError, sympify def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" @wraps(func) def new_func(*args, **kwargs): from sympy.utilities.exceptions import SymPyDeprecationWarning SymPyDeprecationWarning( "Call to deprecated function.", feature=func.__name__ + "()" ).warn() return func(*args, **kwargs) return new_func def _sympifyit(arg, retval=None): """decorator to smartly _sympify function arguments @_sympifyit('other', NotImplemented) def add(self, other): ... In add, other can be thought of as already being a SymPy object. If it is not, the code is likely to catch an exception, then other will be explicitly _sympified, and the whole code restarted. if _sympify(arg) fails, NotImplemented will be returned see: __sympifyit """ def deco(func): return __sympifyit(func, arg, retval) return deco def __sympifyit(func, arg, retval=None): """decorator to _sympify `arg` argument for function `func` don't use directly -- use _sympifyit instead """ # we support f(a,b) only assert func.func_code.co_argcount # only b is _sympified assert func.func_code.co_varnames[1] == arg if retval is None: @wraps(func) def __sympifyit_wrapper(a, b): return func(a, sympify(b, strict=True)) else: @wraps(func) def __sympifyit_wrapper(a, b): try: return func(a, sympify(b, strict=True)) except SympifyError: return retval return __sympifyit_wrapper def call_highest_priority(method_name): """A decorator for binary special methods to handle _op_priority. Binary special methods in Expr and its subclasses use a special attribute '_op_priority' to determine whose special method will be called to handle the operation. In general, the object having the highest value of '_op_priority' will handle the operation. Expr and subclasses that define custom binary special methods (__mul__, etc.) should decorate those methods with this decorator to add the priority logic. The ``method_name`` argument is the name of the method of the other class that will be called. Use this decorator in the following manner:: # Call other.__rmul__ if other._op_priority > self._op_priority @call_highest_priority('__rmul__') def __mul__(self, other): ... # Call other.__mul__ if other._op_priority > self._op_priority @call_highest_priority('__mul__') def __rmul__(self, other): ... """ def priority_decorator(func): def binary_op_wrapper(self, other): if hasattr(other, '_op_priority'): if other._op_priority > self._op_priority: try: f = getattr(other, method_name) except AttributeError: pass else: return f(self) return func(self, other) return binary_op_wrapper return priority_decorator
bsd-3-clause
denisenkom/django
django/db/migrations/operations/__init__.py
170
from .models import CreateModel, DeleteModel, AlterModelTable, AlterUniqueTogether, AlterIndexTogether from .fields import AddField, RemoveField, AlterField, RenameField
bsd-3-clause
RuslanKozin/yii2-int.mag
controllers/AppController.php
472
<?php namespace app\controllers; use yii\web\Controller; class AppController extends Controller { protected function setMeta( $title = null, $keywords = null, $description = null ) { //Устанавливаем мета-теги $this->view->title = $title; $this->view->registerMetaTag(['name' => 'keywords', 'content' => "$keywords"]); $this->view->registerMetaTag(['name' => 'description', 'content' => "$description"]); } }
bsd-3-clause
candhill/scry
functions.php
10408
<?php // // Scry - Simple PHP Photo Album // Copyright 2004 James Byers <[email protected]> // http://scry.org // // Scry is distributed under a BSD License. See LICENSE for details. // // $Id: functions.php,v 1.18 2004/11/29 00:42:56 jbyers Exp $ // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !! !! // !! NOTE - this file does not need to be edited; see setup.php !! // !! !! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // ////////////////////////////////////////////////////////////////////////////// // Security // // Two functions contain filesystem calls (search for "FS" in this // file): // // directory_data() // cache_test() // // function path_security_check(string $victim, string $test) // // the resolved path of $victim must be below $test on the filesystem // check only if victim exists; otherwise realpath cannot resolve path // function path_security_check($victim, $test) { if (!realpath($victim) || //eregi("^" . rtrim($test, '/') . ".*", rtrim(realpath($victim), '/'))) { preg_match("/^" . rtrim('/', $test) . ".*/", rtrim('/', realpath($victim)))) { return true; } die("path security check failed: $victim - $test"); } // function path_security_check // function parse_resolution(string $res) // // converts a string dimension (800x600, 800X600, 800 x 600, 800 X 600) // to a two-element array // function parse_resolution($res) { //return(explode('x', ereg_replace('[^0-9x]', '', strtolower($res)))); return(explode('x', preg_replace('/[^0-9x]/', '', strtolower($res)))); } // function parse_resolution // function cache_test(string $url, int $x, int $y) { // // creates the file's cache path and tests for existance in the cache // returns: // array( // is_cached, // name, // path, // cache_url // ) // function cache_test($url, $x, $y) { global $CFG_cache_enable, $CFG_path_cache, $CFG_url_cache; // cache paths and URL references to images must be URL and filesystem safe // pure urlencoding would require double-urlencoding image URLs -- confusing // instead replace %2f (/) with ! and % with $ (!, $ are URL safe) for readability and consistency between two versions // //ereg("(.*)(\.[A-Za-z0-9]+)$", $url, $matches); preg_match("/(.*)(\.[A-Za-z0-9]+)$/", $url, $matches); $result = array(); $result['is_cached'] = false; $result['name'] = str_replace('%', '$', str_replace('%2F', '!', urlencode($matches[1]))) . '_' . $x . 'x' . $y . $matches[2]; $result['path'] = $CFG_path_cache . '/' . $result['name']; $result['cache_url'] = $CFG_url_cache . '/' . $result['name']; path_security_check($result['path'], $CFG_path_cache); if ($CFG_cache_enable && is_file($result['path']) && is_readable($result['path'])) { // FS READ $result['is_cached'] = true; } return $result; } // function cache_test // function directory_data(string $path, string $url_path) // // walks the specified directory and returns an array containing image file // and directory details: // // array( // files => array( // name, // index, // path, // thumb_url, // image_url, // view_url, // raw_url // ), // directories => array( // name, // index, // list_url // ) // ) // // note: only files with extensions matching $CFG_image_valid are included // '.' and '..' are not referenced in the directory array // function directory_data($path, $url_path) { global $CFG_image_valid, $CFG_url_album, $CFG_thumb_width, $CFG_thumb_height, $CFG_image_width, $CFG_image_height, $CFG_path_images, $CFG_cache_outside_docroot, $CFG_movies_enabled, $CFG_movie_valid; //compensate for switching away from eregi $CFG_image_valid_i = array(); foreach($CFG_image_valid as $e) { $CFG_image_valid_i[] = $e; $CFG_image_valid_i[] = strtoupper($e); } if ($CFG_movies_enabled) { $CFG_movie_valid_i = array(); foreach($CFG_movie_valid as $e) { $CFG_image_valid_i[] = $e; $CFG_image_valid_i[] = strtoupper($e); $CFG_movie_valid_i[] = $e; $CFG_movie_valid_i[] = strtoupper($e); } } // put CFG_image_valid array into eregi form // $valid_extensions = '(.' . implode('|.', $CFG_image_valid_i) . ')$'; if ($CFG_movies_enabled) { $valid_movie_extensions = '(.' . implode('|.', $CFG_movie_valid_i) . ')$'; } path_security_check($path, $CFG_path_images); // load raw directory first, sort, and reprocess // $files_raw = array(); $dirs_raw = array(); if ($h_dir = opendir($path)) { // FS READ while (false !== ($filename = readdir($h_dir))) { // FS READ if ($filename != '.' && $filename != '..') { // set complete url // if ($url_path == '') { $url = $filename; } else { $url = "$url_path/$filename"; } path_security_check("$path/$filename", $CFG_path_images); if (is_readable("$path/$filename") && // FS READ is_file("$path/$filename") && // FS READ //eregi($valid_extensions, $filename)) { preg_match("/{$valid_extensions}/", $filename)) { $files_raw[] = array('name' => $filename, 'url' => $url); } else if (is_readable("$path/$filename") && is_dir("$path/$filename") && substr($filename, 0, 1) != '_') { // FS READ $dirs_raw[] = array('name' => $filename, 'url' => $url); } // if ... else is_file or is_dir } // if } // while closedir($h_dir); // FS READ } // if opendir // sort directory arrays by filename // function cmp($a, $b) { global $CFG_sort_reversed; if (!$CFG_sort_reversed) { return strcasecmp($a['name'], $b['name']); } else { return strcasecmp($b['name'], $a['name']); } } // function cmp @usort($dirs_raw, 'cmp'); @usort($files_raw, 'cmp'); // reprocess arrays // $files = array(); $dirs = array(); $file_count = 0; $dir_count = 0; while (list($k, $v) = each($files_raw)) { // set thumbnail cached vs. not // $thumb = cache_test($v['url'], $CFG_thumb_width, $CFG_thumb_height); // FS FUNCTION $image = cache_test($v['url'], $CFG_view_width, $CFG_view_height); // FS FUNCTION if ($CFG_cache_outside_docroot || !$thumb['is_cached']) { $thumb_url = build_url('image', $CFG_thumb_width . 'x' . $CFG_thumb_height, $v['url']); } else { $thumb_url = $thumb['cache_url']; } if ($CFG_cache_outside_docroot || !$image['is_cached']) { $image_url = build_url('image', $CFG_image_width . 'x' . $CFG_image_height, $v['url']); } else { $image_url = $image['cache_url']; } path_security_check("$path/$v[name]", $CFG_path_images); if ($CFG_movies_enabled) { if (preg_match("/{$valid_movie_extensions}/", "$v[name]")) { $ismovie = true; } else { $ismovie = false; } } $files[] = array('name' => $v['name'], 'index' => $file_count, 'path' => "$path/$v[name]", 'thumb_url' => $thumb_url, 'image_url' => $image_url, 'view_url' => build_url('view', $file_count, $v['url']), 'raw_url' => build_url('image', '0', $v['url']), // 0 index for raw image 'is_movie' => $ismovie); $file_count++; } while (list($k, $v) = each($dirs_raw)) { $dirs[] = array('name' => $v['name'], 'index' => $dir_count, 'list_url' => build_url('list', '0', $v['url'])); $dir_count++; } return(array('files' => $files, 'directories' => $dirs)); } // function directory_data // function path_list(string $path) // // return list of path parts and URLs in an array: // // array( // url, // name // ) // function path_list($path) { global $CFG_url_album, $CFG_album_name; $image_subdir_parts = array(); if ($path != '') { $image_subdir_parts = explode('/', $path); } $path_list[] = array('url' => $CFG_url_album, 'name' => $CFG_album_name); for ($i = 0; $i < count($image_subdir_parts); $i++) { list($k, $v) = each($image_subdir_parts); $path_list[] = array('url' => build_url('list', '0', implode('/', array_slice($image_subdir_parts, 0, $i + 1))), 'name' => $image_subdir_parts[$i]); } // for return $path_list; } // function path_data // function debug(string $type[, string $message]) // // sets an entry in global DEBUG_MESSAGES // function debug($type, $message = '') { global $DEBUG_MESSAGES; if ($message == '') { $message = $type; $type = 'debug'; } // if if (is_array($message) || is_object($message)) { ob_start(); var_dump($message); $message = ob_get_contents(); ob_end_clean(); } // if $DEBUG_MESSAGES[] = "[$type]: $message"; } // function debug // return a URL string based on view, index, path components and CFG vars // function build_url($view, $index, $path) { global $CFG_variable_mode, $CFG_url_album; if ($CFG_variable_mode == 'path') { return("$CFG_url_album/$view/$index/" . str_replace('%2F', '/', urlencode($path))); } else { return("$CFG_url_album?v=$view&amp;i=$index&amp;p=" . str_replace('%2F', '/', urlencode($path))); } } // function build_url // function resize($x, $y) // calculates resized image based on image x1,y1 and bounding box x2,y2 // three modes: constant X, constant Y, full bounding box // returns array(x, y) // function calculate_resize($x1, $y1, $x2, $y2) { global $CFG_resize_mode; switch ($CFG_resize_mode) { case 'X': (int)$resize_x = $x2; if ( $x1 != "" ) { (int)$resize_y = round(($y1 * $x2)/$x1); } break; case 'Y': if ( $y1 != "" ) { (int)$resize_x = round(($x1 * $y2)/$y1); } (int)$resize_y = $y2; break; default: if ( $y1 != "" ) { (int)$resize_x = ($x1 <= $y1) ? round(($x1 * $y2)/$y1) : $x2; } if ( $x1 != "" ) { (int)$resize_y = ($x1 > $y1) ? round(($y1 * $x2)/$x1) : $y2; } break; } return array($resize_x, $resize_y); } // calculate_resize ?>
bsd-3-clause
brilliantorg/django-components
example/example/templates/example/step_1/attendance_page.html
598
{% extends "base.html" %} {% block content %} {% comment %} The surrounding div id follows a specific formula so it can be automatically updated on ajax requests: `cmp_<component_name>_id` {% endcomment %} <div class="cmp" id="cmp_step_1_attendance_entry_id"> {% comment %} Similarly, you can grab the rendered html from the component by asking for `component_name` from the dictionary of rendered html `components`: {% endcomment %} {{ components.step_1_attendance_entry }} </div> {% endblock content %}
bsd-3-clause
junsanity06/Sentinel
src/Roles/IlluminateRoleRepository.php
1637
<?php /** * Part of the Sentinel package. * * NOTICE OF LICENSE * * Licensed under the 3-clause BSD License. * * This source file is subject to the 3-clause BSD License that is * bundled with this package in the LICENSE file. * * @package Sentinel * @version 2.0.4 * @author Cartalyst LLC * @license BSD License (3-clause) * @copyright (c) 2011-2015, Cartalyst LLC * @link http://cartalyst.com */ namespace Cartalyst\Sentinel\Roles; use Cartalyst\Support\Traits\RepositoryTrait; class IlluminateRoleRepository implements RoleRepositoryInterface { use RepositoryTrait; /** * The Eloquent role model name. * * @var string */ protected $model = 'Cartalyst\Sentinel\Roles\EloquentRole'; /** * Create a new Illuminate role repository. * * @param string $model * @return void */ public function __construct($model = null) { if (isset($model)) { $this->model = $model; } } /** * {@inheritDoc} */ public function findById($id) { return $this ->createModel() ->newQuery() ->find($id); } /** * {@inheritDoc} */ public function findBySlug($slug) { return $this ->createModel() ->newQuery() ->where('slug', $slug) ->first(); } /** * {@inheritDoc} */ public function findByName($name) { return $this ->createModel() ->newQuery() ->where('name', $name) ->first(); } }
bsd-3-clause
liujiasheng/kuaidishu
public/js/adminCommon.js
1995
function showMessage(object, message){ if(message == null) message=""; object.text(message); } function getEmptyResultHtml(){ flushEmptyResultHtml(); var html = '<div class="emptyMsg text-center" class="text-center">列表为空</div>'; return html; } function flushEmptyResultHtml(){ $(".emptyMsg").remove(); } //一波分页搜索函数 function nextPage(){ var allPages = parseInt($("#allPages").text()); if(adminUserSelect["curPage"]+1 <= allPages){ adminUserSelect["curPage"]++; changeTable(); $("#curPage").text(adminUserSelect["curPage"]); } } function prevPage(){ if(adminUserSelect["curPage"]-1 >= 1){ adminUserSelect["curPage"]--; changeTable(); $("#curPage").text(adminUserSelect["curPage"]); } } function changeState(){ var state = parseInt($("#state-select").val()); adminUserSelect["state"] = state; adminUserSelect["curPage"] = 1; adminUserSelect["pageCount"] = 10; changeTable(); $("#curPage").text("1"); } function searchTextChange(){ var text = $("#searchText").val(); adminUserSelect["searchText"] = text; adminUserSelect["curPage"] = 1; adminUserSelect["pageCount"] = 10; changeTable(); $("#curPage").text("1"); } function displayLoading(switcher){ if(switcher==true){ $("#loading").show(); }else{ $("#loading").hide(); } } //操作checkbox函数 function checkAllBoxes(){ var grouper = $("#check-all")[0].checked; $("tbody :checkbox").each(function(){ $(this)[0].checked = grouper; }); } //清空checkbox function flushAllBoxes(checked){ $('tbody :checkbox').each(function(){ $(this)[0].checked = checked; }); } function getSelectedIdArray(){ var ids = new Array(0); $("tbody :checkbox").each(function(){ if($(this)[0].checked == true) ids.push(($(this)[0].id).split("-")[1]); }); return ids; } function getSellerLogoLink(){ }
bsd-3-clause
nocoolnicksleft/TurboControl
TurboControl/Win32.cs
2229
using System; using System.Drawing; using System.Runtime.InteropServices; namespace TurboControl { /// <summary> /// Summary description for Win32. /// </summary> public class Win32 { [DllImport("gdi32.dll", EntryPoint="BitBlt")] public static extern int BitBlt (IntPtr hDestC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); [DllImport("gdi32.dll", EntryPoint="CreateCompatibleDC")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [DllImport("gdi32.dll", EntryPoint="DeleteDC")] public static extern int DeleteDC(IntPtr hdc); [DllImport("gdi32.dll", EntryPoint="SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject); [DllImport("gdi32.dll", EntryPoint="DeleteObject")] public static extern int DeleteObject(IntPtr hdc); [DllImport("gdi32.dll", EntryPoint="SetBkColor")] public static extern int SetBkColor (IntPtr hdc, int crColor); public const int SRCCOPY = 0xCC0020; public const int SRCAND = 0x8800C6; public const int SRCERASE = 0x440328; public const int SRCINVERT = 0x660046; public const int SRCPAINT = 0xEE0086; public const int IMAGE_BITMAP = 0x0; public const int LR_LOADFROMFILE = 16; public const int WM_WINDOWPOSCHANGING = 0x46; public static void TurboBitmapCopy(Graphics g, Bitmap bmp, int targetX, int targetY) { IntPtr ptrTargetContext = g.GetHdc(); IntPtr ptrSourceContext = Win32.CreateCompatibleDC(ptrTargetContext); // Select the bitmap into the source context, keeping the original object IntPtr ptrOriginalObject; IntPtr ptrNewObject; ptrOriginalObject = Win32.SelectObject(ptrSourceContext, bmp.GetHbitmap()); // Copy the bitmap from the source to the target Win32.BitBlt(ptrTargetContext, targetX, targetY, bmp.Width, bmp.Height, ptrSourceContext, 0, 0, Win32.SRCCOPY); // 'Select our bitmap out of the dc and delete it ptrNewObject = Win32.SelectObject(ptrSourceContext, ptrOriginalObject); Win32.DeleteObject(ptrNewObject); Win32.DeleteDC(ptrSourceContext); g.ReleaseHdc(ptrTargetContext); } } public struct WM_PosChanging { public int hWnd, hWndInsertAfter, X, Y, cX, cY, Flags; } }
bsd-3-clause
Hgjj/CharViewer
js/src/main/scala/unof/cv/utils/Algebra.scala
2302
package unof.cv.utils import scala.scalajs.js import unof.cv.base.JSVec object Algebra { implicit def diVec(dd: (Double, Int)): DDVector = new DDVector(dd._1, dd._2) implicit def idVec(dd: (Int, Double)): DDVector = new DDVector(dd._1, dd._2) implicit def iiVec(dd: (Int, Int)): DDVector = new DDVector(dd._1, dd._2) implicit def ffVec(dd: (Float, Float)): DDVector = new DDVector(dd._1, dd._2) implicit def jsVec(jsv : JSVec) : DDVector = new DDVector(jsv.x.doubleValue(),jsv.y.doubleValue()) implicit def jsVecToDD(jsv : JSVec) : Vec = (jsv.x.doubleValue(),jsv.y.doubleValue()) type Vec = (Double, Double) implicit class DDVector(val t: (Double, Double)) extends AnyVal { def x = t._1.toInt def y = t._2.toInt def sqrNorm = t._1 * t._1 + t._2 * t._2 def norm = math.sqrt(sqrNorm) private def genZipOp(f: (Double, Double) => Double)(v: Vec): Vec = (f(t._1, v._1), f(t._2, v._2)) def + = genZipOp(_ + _)_ def - = genZipOp(_ - _)_ def * = genZipOp(_ * _)_ def *(d: Double): Vec = (t._1 * d, t._2 * d) def /(d: Double): Vec = (t._1 / d, t._2 / d) def min = genZipOp(_ min _)_ def max = genZipOp(_ max _)_ def / = genZipOp(_ / _)_ def unary_- : Vec = (-t._1, -t._2) def abs = (t._1.abs,t._2.abs) private def genCompOp(f: (Double, Double) => Boolean)(v: Vec): Boolean = f(t._1, v.t._1) && f(t._2, v.t._2) /** * @return true if the relation is true for the two t._1 and true for the two t._2 */ def < = genCompOp(_ < _)_ /** * @return true if the relation is true for the two t._1 and true for the two t._2 */ def <= = genCompOp(_ <= _)_ /** * @return true if the relation is true for the two t._1 and true for the two t._2 */ def > = genCompOp(_ > _)_ /** * @return true if the relation is true for the two t._1 and true for the two t._2 */ def >= = genCompOp(_ >= _)_ def dot(v: Vec) = t._1 * v._1 + t._2 * v._2 def direction = this / this.norm def halfPiRotate = (-t._2, t._1) def minusHalfPiRotate = (t._2, -t._1) def <-> (v :Vec) = { math.sqrt(this <<->> v) } def <<->> (v : Vec) = { val dif = this - v dif dot dif } implicit def toNN: (Number, Number) = (t._1, t._2) } }
bsd-3-clause
kfwalkow/sheetkram
src/main/scala/sheetkram/model/CellVector.scala
499
package sheetkram.model trait CellVector { def cells : IndexedSeq[ Cell ] protected def doEnsure( idx : Int ) : IndexedSeq[ Cell ] = { if ( idx >= cells.size ) cells ++ IndexedSeq.fill( idx - cells.size + 1 )( EmptyCell() ) else cells } protected def doUpdateCell( idx : Int, cell : Cell ) : IndexedSeq[ Cell ] = { if ( idx >= cells.size ) cells ++ IndexedSeq.fill( idx - cells.size )( EmptyCell() ) :+ cell else cells.updated( idx, cell ) } }
bsd-3-clause
nikai3d/ce-challenges
moderate/reverse_groups.lua
366
function div(a, b) return math.floor(a/b) end for line in io.lines(arg[1]) do local sep, a = line:find(";"), {} for i in line:sub(1, sep):gmatch("%d+") do a[#a + 1] = i end local l = tonumber(line:sub(sep+1)) for c = l, #a, l do for i = 1, div(l, 2) do a[c+1-i], a[c-l+i] = a[c-l+i], a[c+1-i] end end print(table.concat(a, ",")) end
bsd-3-clause
epri-dev/PT2
Documents/javadoc/org/epri/pt2/controller/ContentDataController.html
17904
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Sat Oct 20 16:08:43 CDT 2012 --> <TITLE> ContentDataController </TITLE> <META NAME="date" CONTENT="2012-10-20"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ContentDataController"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ContentDataController.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/epri/pt2/controller/AbstractProtocolController.html" title="class in org.epri.pt2.controller"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/epri/pt2/controller/DataTypeController.html" title="class in org.epri.pt2.controller"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/epri/pt2/controller/ContentDataController.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ContentDataController.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.epri.pt2.controller</FONT> <BR> Class ContentDataController</H2> <PRE> java.lang.Object <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../org/epri/pt2/listeners/ViewCallback.html" title="class in org.epri.pt2.listeners">org.epri.pt2.listeners.ViewCallback</A> <IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.epri.pt2.controller.ContentDataController</B> </PRE> <HR> <DL> <DT><PRE>public class <B>ContentDataController</B><DT>extends <A HREF="../../../../org/epri/pt2/listeners/ViewCallback.html" title="class in org.epri.pt2.listeners">ViewCallback</A></DL> </PRE> <P> <DL> <DT><B>Author:</B></DT> <DD>Southwest Research Institute</DD> </DL> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#addContentData(org.epri.pt2.DO.ContentDataDO)">addContentData</A></B>(<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add a content data to the database.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#addContentData(int, org.epri.pt2.DO.ContentDataDO)">addContentData</A></B>(int&nbsp;packetId, <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add a content data to the database.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#addContentData(org.epri.pt2.DO.PacketDO, org.epri.pt2.DO.ContentDataDO)">addContentData</A></B>(<A HREF="../../../../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>&nbsp;packet, <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Add content data.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#getContentData(int)">getContentData</A></B>(int&nbsp;id)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get content data with given id.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.util.List&lt;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#getContentDataList()">getContentDataList</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get all content data.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../org/epri/pt2/controller/ContentDataController.html" title="class in org.epri.pt2.controller">ContentDataController</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#getInstance()">getInstance</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Get an instance of the controller.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#removeContentData(int, int)">removeContentData</A></B>(int&nbsp;contentDataId, int&nbsp;packetId)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Remove content data.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/epri/pt2/controller/ContentDataController.html#updateContentData(org.epri.pt2.DO.ContentDataDO)">updateContentData</A></B>(<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Update a content data.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.epri.pt2.listeners.ViewCallback"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.epri.pt2.listeners.<A HREF="../../../../org/epri/pt2/listeners/ViewCallback.html" title="class in org.epri.pt2.listeners">ViewCallback</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../org/epri/pt2/listeners/ViewCallback.html#registerListener(org.epri.pt2.listeners.ViewCallbackInterface)">registerListener</A>, <A HREF="../../../../org/epri/pt2/listeners/ViewCallback.html#removeListener(org.epri.pt2.listeners.ViewCallbackInterface)">removeListener</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getInstance()"><!-- --></A><H3> getInstance</H3> <PRE> public static <A HREF="../../../../org/epri/pt2/controller/ContentDataController.html" title="class in org.epri.pt2.controller">ContentDataController</A> <B>getInstance</B>()</PRE> <DL> <DD>Get an instance of the controller. <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="addContentData(org.epri.pt2.DO.ContentDataDO)"><!-- --></A><H3> addContentData</H3> <PRE> public <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A> <B>addContentData</B>(<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</PRE> <DL> <DD>Add a content data to the database. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>contentData</CODE> - <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="addContentData(org.epri.pt2.DO.PacketDO, org.epri.pt2.DO.ContentDataDO)"><!-- --></A><H3> addContentData</H3> <PRE> public <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A> <B>addContentData</B>(<A HREF="../../../../org/epri/pt2/DO/PacketDO.html" title="class in org.epri.pt2.DO">PacketDO</A>&nbsp;packet, <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</PRE> <DL> <DD>Add content data. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>packet</CODE> - <DD><CODE>contentData</CODE> - <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="addContentData(int, org.epri.pt2.DO.ContentDataDO)"><!-- --></A><H3> addContentData</H3> <PRE> public <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A> <B>addContentData</B>(int&nbsp;packetId, <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</PRE> <DL> <DD>Add a content data to the database. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>contentData</CODE> - <DD><CODE>packetId</CODE> - <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="removeContentData(int, int)"><!-- --></A><H3> removeContentData</H3> <PRE> public void <B>removeContentData</B>(int&nbsp;contentDataId, int&nbsp;packetId)</PRE> <DL> <DD>Remove content data. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>contentDataId</CODE> - <DD><CODE>packetId</CODE> - </DL> </DD> </DL> <HR> <A NAME="updateContentData(org.epri.pt2.DO.ContentDataDO)"><!-- --></A><H3> updateContentData</H3> <PRE> public <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A> <B>updateContentData</B>(<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&nbsp;contentData)</PRE> <DL> <DD>Update a content data. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>contentData</CODE> - </DL> </DD> </DL> <HR> <A NAME="getContentData(int)"><!-- --></A><H3> getContentData</H3> <PRE> public <A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A> <B>getContentData</B>(int&nbsp;id)</PRE> <DL> <DD>Get content data with given id. <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>id</CODE> - <DT><B>Returns:</B><DD></DL> </DD> </DL> <HR> <A NAME="getContentDataList()"><!-- --></A><H3> getContentDataList</H3> <PRE> public java.util.List&lt;<A HREF="../../../../org/epri/pt2/DO/ContentDataDO.html" title="class in org.epri.pt2.DO">ContentDataDO</A>&gt; <B>getContentDataList</B>()</PRE> <DL> <DD>Get all content data. <P> <DD><DL> <DT><B>Returns:</B><DD></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ContentDataController.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/epri/pt2/controller/AbstractProtocolController.html" title="class in org.epri.pt2.controller"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../org/epri/pt2/controller/DataTypeController.html" title="class in org.epri.pt2.controller"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/epri/pt2/controller/ContentDataController.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ContentDataController.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
bsd-3-clause
keybase/client
go/service/gpg.go
1584
// Copyright 2015 Keybase, Inc. All rights reserved. Use of // this source code is governed by the included BSD license. package service import ( keybase1 "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/go-framed-msgpack-rpc/rpc" "golang.org/x/net/context" ) type RemoteGPGUI struct { sessionID int uicli keybase1.GpgUiClient } func NewRemoteGPGUI(sessionID int, c *rpc.Client) *RemoteGPGUI { return &RemoteGPGUI{ sessionID: sessionID, uicli: keybase1.GpgUiClient{Cli: c}, } } func (r *RemoteGPGUI) SelectKey(ctx context.Context, arg keybase1.SelectKeyArg) (string, error) { arg.SessionID = r.sessionID return r.uicli.SelectKey(ctx, arg) } func (r *RemoteGPGUI) SelectKeyAndPushOption(ctx context.Context, arg keybase1.SelectKeyAndPushOptionArg) (keybase1.SelectKeyRes, error) { arg.SessionID = r.sessionID return r.uicli.SelectKeyAndPushOption(ctx, arg) } func (r *RemoteGPGUI) WantToAddGPGKey(ctx context.Context, _ int) (bool, error) { return r.uicli.WantToAddGPGKey(ctx, r.sessionID) } func (r *RemoteGPGUI) ConfirmDuplicateKeyChosen(ctx context.Context, _ int) (bool, error) { return r.uicli.ConfirmDuplicateKeyChosen(ctx, r.sessionID) } func (r *RemoteGPGUI) ConfirmImportSecretToExistingKey(ctx context.Context, _ int) (bool, error) { return r.uicli.ConfirmImportSecretToExistingKey(ctx, r.sessionID) } func (r *RemoteGPGUI) Sign(ctx context.Context, arg keybase1.SignArg) (string, error) { return r.uicli.Sign(ctx, arg) } func (r *RemoteGPGUI) GetTTY(ctx context.Context) (string, error) { return r.uicli.GetTTY(ctx) }
bsd-3-clause
nwjs/chromium.src
chrome/android/junit/src/org/chromium/chrome/browser/browserservices/digitalgoods/DigitalGoodsConverterTest.java
13661
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.browserservices.digitalgoods; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.PARAM_ACKNOWLEDGE_MAKE_AVAILABLE_AGAIN; import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.PARAM_ACKNOWLEDGE_PURCHASE_TOKEN; import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.RESPONSE_ACKNOWLEDGE; import static org.chromium.chrome.browser.browserservices.digitalgoods.AcknowledgeConverter.RESPONSE_ACKNOWLEDGE_RESPONSE_CODE; import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_ALREADY_OWNED; import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_NOT_OWNED; import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_ITEM_UNAVAILABLE; import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.PLAY_BILLING_OK; import static org.chromium.chrome.browser.browserservices.digitalgoods.DigitalGoodsConverter.convertResponseCode; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.browser.trusted.TrustedWebActivityCallback; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.payments.mojom.BillingResponseCode; import org.chromium.payments.mojom.DigitalGoods.AcknowledgeResponse; import org.chromium.payments.mojom.DigitalGoods.GetDetailsResponse; import org.chromium.payments.mojom.DigitalGoods.ListPurchasesResponse; import org.chromium.payments.mojom.ItemDetails; import org.chromium.payments.mojom.PurchaseDetails; import java.util.concurrent.atomic.AtomicInteger; /** * Tests for {@link DigitalGoodsConverterTest}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class DigitalGoodsConverterTest { // TODO(peconn): Add tests for error cases as well. @Test public void convertGetDetailsParams() { String[] itemIds = { "id1", "id2" }; Bundle b = GetDetailsConverter.convertParams(itemIds); String[] out = b.getStringArray(GetDetailsConverter.PARAM_GET_DETAILS_ITEM_IDS); assertArrayEquals(itemIds, out); } @Test public void convertItemDetails() { String id = "id"; String title = "Item"; String desc = "An item."; String currency = "GBP"; String value = "10"; Bundle bundle = GetDetailsConverter.createItemDetailsBundle(id, title, desc, currency, value); ItemDetails item = GetDetailsConverter.convertItemDetails(bundle); assertItemDetails(item, id, title, desc, currency, value); assertSubsItemDetails(item, null, null, null, null, null); } @Test public void convertItemDetails_subscriptions() { String subsPeriod = "2 weeks"; String freeTrialPeriod = "1 week"; String introPriceCurrency = "GBP"; String introPriceValue = "3.0"; String introPricePeriod = "1 month"; Bundle bundle = GetDetailsConverter.createItemDetailsBundle("id", "Title", "desc", "GBP", "10.0", subsPeriod, freeTrialPeriod, introPriceCurrency, introPriceValue, introPricePeriod); ItemDetails item = GetDetailsConverter.convertItemDetails(bundle); assertSubsItemDetails(item, subsPeriod, freeTrialPeriod, introPriceCurrency, introPriceValue, introPricePeriod); } /** * A class to allow passing values out of callbacks. */ private static class TestState<T> { public int responseCode; public T[] results; } @Test public void convertGetDetailsCallback() { TestState<ItemDetails> state = new TestState<>(); GetDetailsResponse callback = (responseCode, itemDetails) -> { state.responseCode = responseCode; state.results = itemDetails; }; TrustedWebActivityCallback convertedCallback = GetDetailsConverter.convertCallback(callback); int responseCode = 0; Bundle args = GetDetailsConverter.createResponseBundle(responseCode, GetDetailsConverter.createItemDetailsBundle("1", "t1", "d1", "c1", "v1"), GetDetailsConverter.createItemDetailsBundle( "2", "t2", "d2", "c2", "v2", "sp2", "ftp2", "ipc2", "ipv2", "ipp2")); convertedCallback.onExtraCallback(GetDetailsConverter.RESPONSE_COMMAND, args); assertEquals(DigitalGoodsConverter.convertResponseCode(responseCode, Bundle.EMPTY), state.responseCode); assertItemDetails(state.results[0], "1", "t1", "d1", "c1", "v1"); assertSubsItemDetails(state.results[0], null, null, null, null, null); assertItemDetails(state.results[1], "2", "t2", "d2", "c2", "v2"); assertSubsItemDetails(state.results[1], "sp2", "ftp2", "ipc2", "ipv2", "ipp2"); } private static void assertItemDetails(ItemDetails item, String id, String title, String desc, String currency, String value) { assertEquals(id, item.itemId); assertEquals(title, item.title); assertEquals(desc, item.description); assertEquals(currency, item.price.currency); assertEquals(value, item.price.value); } private static void assertSubsItemDetails(ItemDetails item, @Nullable String subsPeriod, @Nullable String freeTrialPeriod, @Nullable String introPriceCurrency, @Nullable String introPriceValue, @Nullable String intoPricePeriod) { assertEquals(subsPeriod, item.subscriptionPeriod); assertEquals(freeTrialPeriod, item.freeTrialPeriod); if (introPriceCurrency == null || introPriceValue == null) { assertNull(item.introductoryPrice); } else { assertEquals(introPriceCurrency, item.introductoryPrice.currency); assertEquals(introPriceValue, item.introductoryPrice.value); } assertEquals(intoPricePeriod, item.introductoryPricePeriod); } @Test public void convertAcknowledgeParams() { String token = "abcdef"; boolean makeAvailableAgain = true; Bundle b = AcknowledgeConverter.convertParams(token, makeAvailableAgain); String outToken = b.getString(PARAM_ACKNOWLEDGE_PURCHASE_TOKEN); boolean outMakeAvailableAgain = b.getBoolean(PARAM_ACKNOWLEDGE_MAKE_AVAILABLE_AGAIN); assertEquals(token, outToken); assertEquals(makeAvailableAgain, outMakeAvailableAgain); } @Test public void convertAcknowledgeCallback() { // Since there's only one value we want to get out of the callback, we can use Atomic* // instead of creating a new class. AtomicInteger state = new AtomicInteger(); AcknowledgeResponse callback = (responseCode) -> state.set(responseCode); TrustedWebActivityCallback convertedCallback = AcknowledgeConverter.convertCallback(callback); Bundle args = new Bundle(); int responseCode = 0; args.putInt(RESPONSE_ACKNOWLEDGE_RESPONSE_CODE, responseCode); convertedCallback.onExtraCallback(RESPONSE_ACKNOWLEDGE, args); assertEquals(responseCode, state.get()); } @Test public void convertListPurchases() { String id = "id"; String token = "token"; boolean acknowledged = true; int state = 2; long time = 1234L; boolean autoRenew = true; Bundle bundle = ListPurchasesConverter.createPurchaseDetailsBundle( id, token, acknowledged, state, time, autoRenew); PurchaseDetails details = ListPurchasesConverter.convertPurchaseDetails(bundle); assertPurchaseDetails(details, id, token, acknowledged, state, time, autoRenew); } private static void assertPurchaseDetails(PurchaseDetails details, String itemId, String purchaseToken, boolean acknowledged, int purchaseState, long purchaseTime, boolean willAutoRenew) { assertEquals(details.itemId, itemId); assertEquals(details.purchaseToken, purchaseToken); assertEquals(details.acknowledged, acknowledged); assertEquals(details.purchaseState, purchaseState); assertEquals(details.purchaseTime.microseconds, purchaseTime); assertEquals(details.willAutoRenew, willAutoRenew); } @Test public void convertListPurchases_wrongTypes() { Bundle validBundle = ListPurchasesConverter.createPurchaseDetailsBundle( "id", "token", true, 1, 2L, true); assertNotNull(ListPurchasesConverter.convertPurchaseDetails(validBundle)); { Bundle bundle = validBundle.deepCopy(); bundle.putInt(ListPurchasesConverter.KEY_ITEM_ID, 5); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } { Bundle bundle = validBundle.deepCopy(); bundle.putInt(ListPurchasesConverter.KEY_PURCHASE_TOKEN, 5); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } { Bundle bundle = validBundle.deepCopy(); bundle.putInt(ListPurchasesConverter.KEY_ACKNOWLEDGED, 5); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } { Bundle bundle = validBundle.deepCopy(); bundle.putBoolean(ListPurchasesConverter.KEY_PURCHASE_STATE, true); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } { Bundle bundle = validBundle.deepCopy(); bundle.putInt(ListPurchasesConverter.KEY_PURCHASE_TIME_MICROSECONDS_PAST_UNIX_EPOCH, 5); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } { Bundle bundle = validBundle.deepCopy(); bundle.putInt(ListPurchasesConverter.KEY_WILL_AUTO_RENEW, 5); assertNull(ListPurchasesConverter.convertPurchaseDetails(bundle)); } } @Test public void convertListPurchasesCallback() { TestState<PurchaseDetails> state = new TestState<>(); ListPurchasesResponse callback = (responseCode, purchaseDetails) -> { state.responseCode = responseCode; state.results = purchaseDetails; }; TrustedWebActivityCallback convertedCallback = ListPurchasesConverter.convertCallback(callback); int responseCode = 0; Bundle args = ListPurchasesConverter.createResponseBundle(responseCode, ListPurchasesConverter.createPurchaseDetailsBundle("1", "t1", true, 1, 1L, true), ListPurchasesConverter.createPurchaseDetailsBundle("2", "t2", false, 2, 2L, false)); convertedCallback.onExtraCallback(ListPurchasesConverter.RESPONSE_COMMAND, args); assertEquals(DigitalGoodsConverter.convertResponseCode(responseCode, Bundle.EMPTY), state.responseCode); assertPurchaseDetails(state.results[0], "1", "t1", true, 1, 1L, true); assertPurchaseDetails(state.results[1], "2", "t2", false, 2, 2L, false); } @Test public void convertResponseCodes_v0() { Bundle args = Bundle.EMPTY; assertEquals(BillingResponseCode.OK, DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_OK, args)); assertEquals(BillingResponseCode.ITEM_ALREADY_OWNED, DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_ALREADY_OWNED, args)); assertEquals(BillingResponseCode.ITEM_NOT_OWNED, DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_NOT_OWNED, args)); assertEquals(BillingResponseCode.ITEM_UNAVAILABLE, DigitalGoodsConverter.convertResponseCode(PLAY_BILLING_ITEM_UNAVAILABLE, args)); // Check that other numbers get set to ERROR. assertEquals(BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(2, args)); assertEquals( BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(-1, args)); assertEquals( BillingResponseCode.ERROR, DigitalGoodsConverter.convertResponseCode(10, args)); } @Test public void convertResponseCodes_v1() { Bundle args = new Bundle(); args.putInt(DigitalGoodsConverter.KEY_VERSION, 1); assertEquals(BillingResponseCode.OK, convertResponseCode(BillingResponseCode.OK, args)); assertEquals(BillingResponseCode.ITEM_ALREADY_OWNED, convertResponseCode(BillingResponseCode.ITEM_ALREADY_OWNED, args)); assertEquals(BillingResponseCode.ITEM_NOT_OWNED, convertResponseCode(BillingResponseCode.ITEM_NOT_OWNED, args)); assertEquals(BillingResponseCode.ITEM_UNAVAILABLE, convertResponseCode(BillingResponseCode.ITEM_UNAVAILABLE, args)); assertEquals(BillingResponseCode.ERROR, convertResponseCode(123, args)); assertEquals(BillingResponseCode.ERROR, convertResponseCode(-12, args)); } }
bsd-3-clause
NifTK/MITK
Modules/Core/src/Rendering/mitkOverlay.cpp
9744
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkOverlay.h" mitk::Overlay::Overlay() : m_LayoutedBy(NULL) { m_PropertyList = mitk::PropertyList::New(); } mitk::Overlay::~Overlay() { } void mitk::Overlay::SetProperty(const std::string& propertyKey, const BaseProperty::Pointer& propertyValue, const mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue); this->Modified(); } void mitk::Overlay::ReplaceProperty(const std::string& propertyKey, const BaseProperty::Pointer& propertyValue, const mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->ReplaceProperty(propertyKey, propertyValue); } void mitk::Overlay::AddProperty(const std::string& propertyKey, const BaseProperty::Pointer& propertyValue, const mitk::BaseRenderer* renderer, bool overwrite) { if ((overwrite) || (GetProperty(propertyKey, renderer) == NULL)) { SetProperty(propertyKey, propertyValue, renderer); } } void mitk::Overlay::ConcatenatePropertyList(PropertyList *pList, bool replace) { m_PropertyList->ConcatenatePropertyList(pList, replace); } mitk::BaseProperty* mitk::Overlay::GetProperty(const std::string& propertyKey, const mitk::BaseRenderer* renderer) const { //renderer specified? if (renderer) { std::map<const mitk::BaseRenderer*, mitk::PropertyList::Pointer>::const_iterator it; //check for the renderer specific property it = m_MapOfPropertyLists.find(renderer); if (it != m_MapOfPropertyLists.cend()) //found { mitk::BaseProperty::Pointer property = it->second->GetProperty(propertyKey); if (property.IsNotNull())//found an enabled property in the render specific list return property; else //found a renderer specific list, but not the desired property return m_PropertyList->GetProperty(propertyKey); //return renderer unspecific property } else //didn't find the property list of the given renderer { //return the renderer unspecific property if there is one return m_PropertyList->GetProperty(propertyKey); } } else //no specific renderer given; use the renderer independent one { mitk::BaseProperty::Pointer property = m_PropertyList->GetProperty(propertyKey); if (property.IsNotNull()) return property; } //only to satisfy compiler! return NULL; } bool mitk::Overlay::GetBoolProperty(const std::string& propertyKey, bool& boolValue, mitk::BaseRenderer* renderer) const { mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(propertyKey, renderer)); if (boolprop.IsNull()) return false; boolValue = boolprop->GetValue(); return true; } bool mitk::Overlay::GetIntProperty(const std::string& propertyKey, int &intValue, mitk::BaseRenderer* renderer) const { mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer)); if (intprop.IsNull()) return false; intValue = intprop->GetValue(); return true; } bool mitk::Overlay::GetFloatProperty(const std::string& propertyKey, float &floatValue, mitk::BaseRenderer* renderer) const { mitk::FloatProperty::Pointer floatprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer)); if (floatprop.IsNull()) return false; floatValue = floatprop->GetValue(); return true; } bool mitk::Overlay::GetStringProperty(const std::string& propertyKey, std::string& string, mitk::BaseRenderer* renderer) const { mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty*>(GetProperty(propertyKey, renderer)); if (stringProp.IsNull()) { return false; } else { //memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous string = stringProp->GetValue(); return true; } } void mitk::Overlay::SetIntProperty(const std::string& propertyKey, int intValue, mitk::BaseRenderer* renderer) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::IntProperty::New(intValue)); Modified(); } void mitk::Overlay::SetBoolProperty(const std::string& propertyKey, bool boolValue, mitk::BaseRenderer* renderer/*=NULL*/) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue)); Modified(); } void mitk::Overlay::SetFloatProperty(const std::string& propertyKey, float floatValue, mitk::BaseRenderer* renderer/*=NULL*/) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue)); Modified(); } void mitk::Overlay::SetStringProperty(const std::string& propertyKey, const std::string& stringValue, mitk::BaseRenderer* renderer/*=NULL*/) { GetPropertyList(renderer)->SetProperty(propertyKey, mitk::StringProperty::New(stringValue)); Modified(); } std::string mitk::Overlay::GetName() const { mitk::StringProperty* sp = dynamic_cast<mitk::StringProperty*>(this->GetProperty("name")); if (sp == NULL) return ""; return sp->GetValue(); } void mitk::Overlay::SetName(const std::string& name) { this->SetStringProperty("name", name); } bool mitk::Overlay::GetName(std::string& nodeName, mitk::BaseRenderer* renderer, const std::string& propertyKey) const { return GetStringProperty(propertyKey, nodeName, renderer); } void mitk::Overlay::SetText(std::string text) { SetStringProperty("Overlay.Text", text.c_str()); } std::string mitk::Overlay::GetText() const { std::string text; GetPropertyList()->GetStringProperty("Overlay.Text", text); return text; } void mitk::Overlay::SetFontSize(int fontSize) { SetIntProperty("Overlay.FontSize", fontSize); } int mitk::Overlay::GetFontSize() const { int fontSize = 1; GetPropertyList()->GetIntProperty("Overlay.FontSize", fontSize); return fontSize; } bool mitk::Overlay::GetVisibility(bool& visible, mitk::BaseRenderer* renderer, const std::string& propertyKey) const { return GetBoolProperty(propertyKey, visible, renderer); } bool mitk::Overlay::IsVisible(mitk::BaseRenderer* renderer, const std::string& propertyKey, bool defaultIsOn) const { return IsOn(propertyKey, renderer, defaultIsOn); } bool mitk::Overlay::GetColor(float rgb[], mitk::BaseRenderer* renderer, const std::string& propertyKey) const { mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(propertyKey, renderer)); if (colorprop.IsNull()) return false; memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); return true; } void mitk::Overlay::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const std::string& propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(color); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::Overlay::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const std::string& propertyKey) { float color[3]; color[0] = red; color[1] = green; color[2] = blue; SetColor(color, renderer, propertyKey); } void mitk::Overlay::SetColor(const float rgb[], mitk::BaseRenderer* renderer, const std::string& propertyKey) { mitk::ColorProperty::Pointer prop; prop = mitk::ColorProperty::New(rgb); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } bool mitk::Overlay::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const std::string& propertyKey) const { mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer)); if (opacityprop.IsNull()) return false; opacity = opacityprop->GetValue(); return true; } void mitk::Overlay::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const std::string& propertyKey) { mitk::FloatProperty::Pointer prop; prop = mitk::FloatProperty::New(opacity); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } void mitk::Overlay::SetVisibility(bool visible, mitk::BaseRenderer *renderer, const std::string& propertyKey) { mitk::BoolProperty::Pointer prop; prop = mitk::BoolProperty::New(visible); GetPropertyList(renderer)->SetProperty(propertyKey, prop); } mitk::PropertyList* mitk::Overlay::GetPropertyList(const mitk::BaseRenderer* renderer) const { if (renderer == NULL) return m_PropertyList; mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer]; if (propertyList.IsNull()) propertyList = mitk::PropertyList::New(); assert(m_MapOfPropertyLists[renderer].IsNotNull()); return propertyList; } bool mitk::Overlay::BaseLocalStorage::IsGenerateDataRequired(mitk::BaseRenderer *renderer, mitk::Overlay *overlay) { if (m_LastGenerateDataTime < overlay->GetMTime()) return true; if (renderer && m_LastGenerateDataTime < renderer->GetTimeStepUpdateTime()) return true; return false; } mitk::Overlay::Bounds mitk::Overlay::GetBoundsOnDisplay(mitk::BaseRenderer*) const { mitk::Overlay::Bounds bounds; bounds.Position[0] = bounds.Position[1] = bounds.Size[0] = bounds.Size[1] = 0; return bounds; } void mitk::Overlay::SetBoundsOnDisplay(mitk::BaseRenderer*, const mitk::Overlay::Bounds&) { } void mitk::Overlay::SetForceInForeground(bool forceForeground) { m_ForceInForeground = forceForeground; } bool mitk::Overlay::IsForceInForeground() const { return m_ForceInForeground; }
bsd-3-clause
cpmech/gosl
ode/methods.go
1549
// Copyright 2016 The Gosl Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ode import ( "github.com/cpmech/gosl/chk" "github.com/cpmech/gosl/la" ) // rkmethod defines the required functions of Runge-Kutta method type rkmethod interface { Free() // free memory Info() (fixedOnly, implicit bool, nstages int) // information Init(ndim int, conf *Config, work *rkwork, stat *Stat, fcn Func, jac JacF, M *la.Triplet) // initialize Accept(y0 la.Vector, x0 float64) (dxnew float64) // accept update (must compute rerr) Reject() (dxnew float64) // process step rejection (must compute rerr) DenseOut(yout la.Vector, h, x float64, y la.Vector, xout float64) // dense output (after Accept) Step(x0 float64, y0 la.Vector) // step update } // rkmMaker defines a function that makes rkmethods type rkmMaker func() rkmethod // rkmDB implements a database of rkmethod makers var rkmDB = make(map[string]rkmMaker) // newRKmethod finds a rkmethod in database or panic func newRKmethod(kind string) rkmethod { if maker, ok := rkmDB[kind]; ok { return maker() } chk.Panic("cannot find rkmethod named %q in database\n", kind) return nil }
bsd-3-clause
blockoperation/boxnope
src/utils.hpp
308
// Copyright (c) 2016-2017, blockoperation. All rights reserved. // boxnope is distributed under the terms of the BSD license. // See LICENSE for details. #ifndef BOXNOPE_UTILS_HPP #define BOXNOPE_UTILS_HPP #define QS(s) QString(s) #define QSL(s) QStringLiteral(s) #define QL1S(s) QLatin1String(s) #endif
bsd-3-clause
flipactual/react
src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
37790
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var PropTypes; var checkPropTypes; var React; var ReactDOM; var Component; var MyComponent; function resetWarningCache() { jest.resetModules(); checkPropTypes = require('prop-types/checkPropTypes'); PropTypes = require('ReactPropTypes'); } function getPropTypeWarningMessage(propTypes, object, componentName) { if (!console.error.calls) { spyOn(console, 'error'); } else { console.error.calls.reset(); } resetWarningCache(); checkPropTypes(propTypes, object, 'prop', 'testComponent'); const callCount = console.error.calls.count(); if (callCount > 1) { throw new Error('Too many warnings.'); } const message = console.error.calls.argsFor(0)[0] || null; console.error.calls.reset(); return message; } function typeCheckFail(declaration, value, expectedMessage) { const propTypes = { testProp: declaration, }; const props = { testProp: value, }; const message = getPropTypeWarningMessage(propTypes, props, 'testComponent'); expect(message).toContain(expectedMessage); } function typeCheckFailRequiredValues(declaration) { var specifiedButIsNullMsg = 'The prop `testProp` is marked as required in ' + '`testComponent`, but its value is `null`.'; var unspecifiedMsg = 'The prop `testProp` is marked as required in ' + '`testComponent`, but its value is \`undefined\`.'; var propTypes = {testProp: declaration}; // Required prop is null var message1 = getPropTypeWarningMessage( propTypes, {testProp: null}, 'testComponent', ); expect(message1).toContain(specifiedButIsNullMsg); // Required prop is undefined var message2 = getPropTypeWarningMessage( propTypes, {testProp: undefined}, 'testComponent', ); expect(message2).toContain(unspecifiedMsg); // Required prop is not a member of props object var message3 = getPropTypeWarningMessage(propTypes, {}, 'testComponent'); expect(message3).toContain(unspecifiedMsg); } function typeCheckPass(declaration, value) { const propTypes = { testProp: declaration, }; const props = { testProp: value, }; const message = getPropTypeWarningMessage(propTypes, props, 'testComponent'); expect(message).toBe(null); } function expectThrowInDevelopment(declaration, value) { var props = {testProp: value}; var propName = 'testProp' + Math.random().toString(); var componentName = 'testComponent' + Math.random().toString(); var message; try { declaration(props, propName, componentName, 'prop'); } catch (e) { message = e.message; } expect(message).toContain( 'Calling PropTypes validators directly is not supported', ); console.error.calls.reset(); } describe('ReactPropTypes', () => { beforeEach(() => { React = require('react'); ReactDOM = require('react-dom'); resetWarningCache(); }); describe('checkPropTypes', () => { it('does not return a value from a validator', () => { spyOn(console, 'error'); const propTypes = { foo(props, propName, componentName) { return new Error('some error'); }, }; const props = {foo: 'foo'}; const returnValue = checkPropTypes( propTypes, props, 'prop', 'testComponent', null, ); expect(console.error.calls.argsFor(0)[0]).toContain('some error'); expect(returnValue).toBe(undefined); }); it('does not throw if validator throws', () => { spyOn(console, 'error'); const propTypes = { foo(props, propName, componentName) { throw new Error('some error'); }, }; const props = {foo: 'foo'}; const returnValue = checkPropTypes( propTypes, props, 'prop', 'testComponent', null, ); expect(console.error.calls.argsFor(0)[0]).toContain('some error'); expect(returnValue).toBe(undefined); }); }); describe('Primitive Types', () => { it('should warn for invalid strings', () => { typeCheckFail( PropTypes.string, [], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, false, 'Invalid prop `testProp` of type `boolean` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, 0, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, {}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, Symbol(), 'Invalid prop `testProp` of type `symbol` supplied to ' + '`testComponent`, expected `string`.', ); }); it('should fail date and regexp correctly', () => { typeCheckFail( PropTypes.string, new Date(), 'Invalid prop `testProp` of type `date` supplied to ' + '`testComponent`, expected `string`.', ); typeCheckFail( PropTypes.string, /please/, 'Invalid prop `testProp` of type `regexp` supplied to ' + '`testComponent`, expected `string`.', ); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.array, []); typeCheckPass(PropTypes.bool, false); typeCheckPass(PropTypes.func, function() {}); typeCheckPass(PropTypes.number, 0); typeCheckPass(PropTypes.string, ''); typeCheckPass(PropTypes.object, {}); typeCheckPass(PropTypes.object, new Date()); typeCheckPass(PropTypes.object, /please/); typeCheckPass(PropTypes.symbol, Symbol()); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.string, null); typeCheckPass(PropTypes.string, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.string.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.array, /please/); expectThrowInDevelopment(PropTypes.array, []); expectThrowInDevelopment(PropTypes.array.isRequired, /please/); expectThrowInDevelopment(PropTypes.array.isRequired, []); expectThrowInDevelopment(PropTypes.array.isRequired, null); expectThrowInDevelopment(PropTypes.array.isRequired, undefined); expectThrowInDevelopment(PropTypes.bool, []); expectThrowInDevelopment(PropTypes.bool, true); expectThrowInDevelopment(PropTypes.bool.isRequired, []); expectThrowInDevelopment(PropTypes.bool.isRequired, true); expectThrowInDevelopment(PropTypes.bool.isRequired, null); expectThrowInDevelopment(PropTypes.bool.isRequired, undefined); expectThrowInDevelopment(PropTypes.func, false); expectThrowInDevelopment(PropTypes.func, function() {}); expectThrowInDevelopment(PropTypes.func.isRequired, false); expectThrowInDevelopment(PropTypes.func.isRequired, function() {}); expectThrowInDevelopment(PropTypes.func.isRequired, null); expectThrowInDevelopment(PropTypes.func.isRequired, undefined); expectThrowInDevelopment(PropTypes.number, function() {}); expectThrowInDevelopment(PropTypes.number, 42); expectThrowInDevelopment(PropTypes.number.isRequired, function() {}); expectThrowInDevelopment(PropTypes.number.isRequired, 42); expectThrowInDevelopment(PropTypes.number.isRequired, null); expectThrowInDevelopment(PropTypes.number.isRequired, undefined); expectThrowInDevelopment(PropTypes.string, 0); expectThrowInDevelopment(PropTypes.string, 'foo'); expectThrowInDevelopment(PropTypes.string.isRequired, 0); expectThrowInDevelopment(PropTypes.string.isRequired, 'foo'); expectThrowInDevelopment(PropTypes.string.isRequired, null); expectThrowInDevelopment(PropTypes.string.isRequired, undefined); expectThrowInDevelopment(PropTypes.symbol, 0); expectThrowInDevelopment(PropTypes.symbol, Symbol('Foo')); expectThrowInDevelopment(PropTypes.symbol.isRequired, 0); expectThrowInDevelopment(PropTypes.symbol.isRequired, Symbol('Foo')); expectThrowInDevelopment(PropTypes.symbol.isRequired, null); expectThrowInDevelopment(PropTypes.symbol.isRequired, undefined); expectThrowInDevelopment(PropTypes.object, ''); expectThrowInDevelopment(PropTypes.object, {foo: 'bar'}); expectThrowInDevelopment(PropTypes.object.isRequired, ''); expectThrowInDevelopment(PropTypes.object.isRequired, {foo: 'bar'}); expectThrowInDevelopment(PropTypes.object.isRequired, null); expectThrowInDevelopment(PropTypes.object.isRequired, undefined); }); }); describe('Any type', () => { it('should should accept any value', () => { typeCheckPass(PropTypes.any, 0); typeCheckPass(PropTypes.any, 'str'); typeCheckPass(PropTypes.any, []); typeCheckPass(PropTypes.any, Symbol()); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.any, null); typeCheckPass(PropTypes.any, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.any.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.any, null); expectThrowInDevelopment(PropTypes.any.isRequired, null); expectThrowInDevelopment(PropTypes.any.isRequired, undefined); }); }); describe('ArrayOf Type', () => { it('should fail for invalid argument', () => { typeCheckFail( PropTypes.arrayOf({foo: PropTypes.string}), {foo: 'bar'}, 'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.', ); }); it('should support the arrayOf propTypes', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]); typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']); typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']); typeCheckPass(PropTypes.arrayOf(PropTypes.symbol), [Symbol(), Symbol()]); }); it('should support arrayOf with complex types', () => { typeCheckPass( PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})), [{a: 1}, {a: 2}], ); function Thing() {} typeCheckPass(PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [ new Thing(), new Thing(), ]); }); it('should warn with invalid items in the array', () => { typeCheckFail( PropTypes.arrayOf(PropTypes.number), [1, 2, 'b'], 'Invalid prop `testProp[2]` of type `string` supplied to ' + '`testComponent`, expected `number`.', ); }); it('should warn with invalid complex types', () => { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), 'xyz'], 'Invalid prop `testProp[1]` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.', ); }); it('should warn when passed something other than an array', () => { typeCheckFail( PropTypes.arrayOf(PropTypes.number), {'0': 'maybe-array', length: 1}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected an array.', ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an array.', ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an array.', ); }); it('should not warn when passing an empty array', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), []); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.arrayOf(PropTypes.number), null); typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.arrayOf(PropTypes.number).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.arrayOf({foo: PropTypes.string}), { foo: 'bar', }); expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), [ 1, 2, 'b', ]); expectThrowInDevelopment(PropTypes.arrayOf(PropTypes.number), { '0': 'maybe-array', length: 1, }); expectThrowInDevelopment( PropTypes.arrayOf(PropTypes.number).isRequired, null, ); expectThrowInDevelopment( PropTypes.arrayOf(PropTypes.number).isRequired, undefined, ); }); }); describe('Component Type', () => { beforeEach(() => { Component = class extends React.Component { static propTypes = { label: PropTypes.element.isRequired, }; render() { return <div>{this.props.label}</div>; } }; }); it('should support components', () => { typeCheckPass(PropTypes.element, <div />); }); it('should not support multiple components or scalar values', () => { typeCheckFail( PropTypes.element, [<div />, <div />], 'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, 123, 'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, 'foo', 'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); typeCheckFail( PropTypes.element, false, 'Invalid prop `testProp` of type `boolean` supplied to `testComponent`, ' + 'expected a single ReactElement.', ); }); it('should be able to define a single child as label', () => { spyOn(console, 'error'); var container = document.createElement('div'); ReactDOM.render(<Component label={<div />} />, container); expectDev(console.error.calls.count()).toBe(0); }); it('should warn when passing no label and isRequired is set', () => { spyOn(console, 'error'); var container = document.createElement('div'); ReactDOM.render(<Component />, container); expectDev(console.error.calls.count()).toBe(1); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.element, null); typeCheckPass(PropTypes.element, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.element.isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.element, [<div />, <div />]); expectThrowInDevelopment(PropTypes.element, <div />); expectThrowInDevelopment(PropTypes.element, 123); expectThrowInDevelopment(PropTypes.element, 'foo'); expectThrowInDevelopment(PropTypes.element, false); expectThrowInDevelopment(PropTypes.element.isRequired, null); expectThrowInDevelopment(PropTypes.element.isRequired, undefined); }); }); describe('Instance Types', () => { it('should warn for invalid instances', () => { function Person() {} function Cat() {} var personName = Person.name || '<<anonymous>>'; var dateName = Date.name || '<<anonymous>>'; var regExpName = RegExp.name || '<<anonymous>>'; typeCheckFail( PropTypes.instanceOf(Person), false, 'Invalid prop `testProp` of type `Boolean` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), '', 'Invalid prop `testProp` of type `String` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Date), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + dateName + '`.', ); typeCheckFail( PropTypes.instanceOf(RegExp), {}, 'Invalid prop `testProp` of type `Object` supplied to ' + '`testComponent`, expected instance of `' + regExpName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), new Cat(), 'Invalid prop `testProp` of type `Cat` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); typeCheckFail( PropTypes.instanceOf(Person), Object.create(null), 'Invalid prop `testProp` of type `<<anonymous>>` supplied to ' + '`testComponent`, expected instance of `' + personName + '`.', ); }); it('should not warn for valid values', () => { function Person() {} function Engineer() {} Engineer.prototype = new Person(); typeCheckPass(PropTypes.instanceOf(Person), new Person()); typeCheckPass(PropTypes.instanceOf(Person), new Engineer()); typeCheckPass(PropTypes.instanceOf(Date), new Date()); typeCheckPass(PropTypes.instanceOf(RegExp), /please/); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.instanceOf(String), null); typeCheckPass(PropTypes.instanceOf(String), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.instanceOf(String).isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.instanceOf(Date), {}); expectThrowInDevelopment(PropTypes.instanceOf(Date), new Date()); expectThrowInDevelopment(PropTypes.instanceOf(Date).isRequired, {}); expectThrowInDevelopment( PropTypes.instanceOf(Date).isRequired, new Date(), ); }); }); describe('React Component Types', () => { beforeEach(() => { MyComponent = class extends React.Component { render() { return <div />; } }; }); it('should warn for invalid values', () => { var failMessage = 'Invalid prop `testProp` supplied to ' + '`testComponent`, expected a ReactNode.'; typeCheckFail(PropTypes.node, true, failMessage); typeCheckFail(PropTypes.node, function() {}, failMessage); typeCheckFail(PropTypes.node, {key: function() {}}, failMessage); typeCheckFail(PropTypes.node, {key: <div />}, failMessage); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.node, <div />); typeCheckPass(PropTypes.node, false); typeCheckPass(PropTypes.node, <MyComponent />); typeCheckPass(PropTypes.node, 'Some string'); typeCheckPass(PropTypes.node, []); typeCheckPass(PropTypes.node, [ 123, 'Some string', <div />, ['Another string', [456], <span />, <MyComponent />], <MyComponent />, null, undefined, ]); }); it('should not warn for iterables', () => { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return {value: done ? undefined : <MyComponent />, done: done}; }, }; }, }; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for entry iterables', () => { var iterable = { '@@iterator': function() { var i = 0; return { next: function() { var done = ++i > 2; return { value: done ? undefined : ['#' + i, <MyComponent />], done: done, }; }, }; }, }; iterable.entries = iterable['@@iterator']; typeCheckPass(PropTypes.node, iterable); }); it('should not warn for null/undefined if not required', () => { typeCheckPass(PropTypes.node, null); typeCheckPass(PropTypes.node, undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.node.isRequired); }); it('should accept empty array for required props', () => { typeCheckPass(PropTypes.node.isRequired, []); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.node, 'node'); expectThrowInDevelopment(PropTypes.node, {}); expectThrowInDevelopment(PropTypes.node.isRequired, 'node'); expectThrowInDevelopment(PropTypes.node.isRequired, undefined); expectThrowInDevelopment(PropTypes.node.isRequired, undefined); }); }); describe('ObjectOf Type', () => { it('should fail for invalid argument', () => { typeCheckFail( PropTypes.objectOf({foo: PropTypes.string}), {foo: 'bar'}, 'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.', ); }); it('should support the objectOf propTypes', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3}); typeCheckPass(PropTypes.objectOf(PropTypes.string), { a: 'a', b: 'b', c: 'c', }); typeCheckPass(PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), { a: 'a', b: 'b', }); typeCheckPass(PropTypes.objectOf(PropTypes.symbol), { a: Symbol(), b: Symbol(), c: Symbol(), }); }); it('should support objectOf with complex types', () => { typeCheckPass( PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})), {a: {a: 1}, b: {a: 2}}, ); function Thing() {} typeCheckPass(PropTypes.objectOf(PropTypes.instanceOf(Thing)), { a: new Thing(), b: new Thing(), }); }); it('should warn with invalid items in the object', () => { typeCheckFail( PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 'b'}, 'Invalid prop `testProp.c` of type `string` supplied to `testComponent`, ' + 'expected `number`.', ); }); it('should warn with invalid complex types', () => { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: 'xyz'}, 'Invalid prop `testProp.b` of type `String` supplied to ' + '`testComponent`, expected instance of `' + name + '`.', ); }); it('should warn when passed something other than an object', () => { typeCheckFail( PropTypes.objectOf(PropTypes.number), [1, 2], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an object.', ); typeCheckFail( PropTypes.objectOf(PropTypes.symbol), Symbol(), 'Invalid prop `testProp` of type `symbol` supplied to ' + '`testComponent`, expected an object.', ); }); it('should not warn when passing an empty object', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), {}); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.objectOf(PropTypes.number), null); typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.objectOf(PropTypes.number).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.objectOf({foo: PropTypes.string}), { foo: 'bar', }); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), { a: 1, b: 2, c: 'b', }); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), [1, 2]); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), null); expectThrowInDevelopment(PropTypes.objectOf(PropTypes.number), undefined); }); }); describe('OneOf Types', () => { it('should warn but not error for invalid argument', () => { spyOn(console, 'error'); PropTypes.oneOf('red', 'blue'); expectDev(console.error).toHaveBeenCalled(); expectDev(console.error.calls.argsFor(0)[0]).toContain( 'Invalid argument supplied to oneOf, expected an instance of array.', ); typeCheckPass(PropTypes.oneOf('red', 'blue'), 'red'); }); it('should warn for invalid values', () => { typeCheckFail( PropTypes.oneOf(['red', 'blue']), true, 'Invalid prop `testProp` of value `true` supplied to ' + '`testComponent`, expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), [], 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), '', 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].', ); typeCheckFail( PropTypes.oneOf([0, 'false']), false, 'Invalid prop `testProp` of value `false` supplied to ' + '`testComponent`, expected one of [0,"false"].', ); }); it('should not warn for valid values', () => { typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red'); typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue'); typeCheckPass(PropTypes.oneOf(['red', 'blue', NaN]), NaN); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass(PropTypes.oneOf(['red', 'blue']), null); typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues(PropTypes.oneOf(['red', 'blue']).isRequired); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), true); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), null); expectThrowInDevelopment(PropTypes.oneOf(['red', 'blue']), undefined); }); }); describe('Union Types', () => { it('should warn but not error for invalid argument', () => { spyOn(console, 'error'); PropTypes.oneOfType(PropTypes.string, PropTypes.number); expectDev(console.error).toHaveBeenCalled(); expectDev(console.error.calls.argsFor(0)[0]).toContain( 'Invalid argument supplied to oneOfType, expected an instance of array.', ); typeCheckPass(PropTypes.oneOf(PropTypes.string, PropTypes.number), []); }); it('should warn if none of the types are valid', () => { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], 'Invalid prop `testProp` supplied to `testComponent`.', ); var checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckFail( checker, {c: 1}, 'Invalid prop `testProp` supplied to `testComponent`.', ); }); it('should not warn if one of the types are valid', () => { var checker = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); typeCheckPass(checker, null); typeCheckPass(checker, 'foo'); typeCheckPass(checker, 123); checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}), ]); typeCheckPass(checker, {a: 1}); typeCheckPass(checker, {b: 1}); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null, ); typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined, ); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], ); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null, ); expectThrowInDevelopment( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined, ); }); }); describe('Shape Types', () => { it('should warn for non objects', () => { typeCheckFail( PropTypes.shape({}), 'some string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `object`.', ); typeCheckFail( PropTypes.shape({}), ['array'], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `object`.', ); }); it('should not warn for empty values', () => { typeCheckPass(PropTypes.shape({}), undefined); typeCheckPass(PropTypes.shape({}), null); typeCheckPass(PropTypes.shape({}), {}); }); it('should not warn for an empty object', () => { typeCheckPass(PropTypes.shape({}).isRequired, {}); }); it('should not warn for non specified types', () => { typeCheckPass(PropTypes.shape({}), {key: 1}); }); it('should not warn for valid types', () => { typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1}); }); it('should warn for required valid types', () => { typeCheckFail( PropTypes.shape({key: PropTypes.number.isRequired}), {}, 'The prop `testProp.key` is marked as required in `testComponent`, ' + 'but its value is `undefined`.', ); }); it('should warn for the first required type', () => { typeCheckFail( PropTypes.shape({ key: PropTypes.number.isRequired, secondKey: PropTypes.number.isRequired, }), {}, 'The prop `testProp.key` is marked as required in `testComponent`, ' + 'but its value is `undefined`.', ); }); it('should warn for invalid key types', () => { typeCheckFail( PropTypes.shape({key: PropTypes.number}), {key: 'abc'}, 'Invalid prop `testProp.key` of type `string` supplied to `testComponent`, ' + 'expected `number`.', ); }); it('should be implicitly optional and not warn without values', () => { typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null, ); typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined, ); }); it('should warn for missing required values', () => { typeCheckFailRequiredValues( PropTypes.shape({key: PropTypes.number}).isRequired, ); }); it('should throw if called manually in development', () => { spyOn(console, 'error'); expectThrowInDevelopment(PropTypes.shape({}), 'some string'); expectThrowInDevelopment(PropTypes.shape({foo: PropTypes.number}), { foo: 42, }); expectThrowInDevelopment( PropTypes.shape({key: PropTypes.number}).isRequired, null, ); expectThrowInDevelopment( PropTypes.shape({key: PropTypes.number}).isRequired, undefined, ); expectThrowInDevelopment(PropTypes.element, <div />); }); }); describe('Symbol Type', () => { it('should warn for non-symbol', () => { typeCheckFail( PropTypes.symbol, 'hello', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `symbol`.', ); typeCheckFail( PropTypes.symbol, function() {}, 'Invalid prop `testProp` of type `function` supplied to ' + '`testComponent`, expected `symbol`.', ); typeCheckFail( PropTypes.symbol, { '@@toStringTag': 'Katana', }, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `symbol`.', ); }); it('should not warn for a polyfilled Symbol', () => { var CoreSymbol = require('core-js/library/es6/symbol'); typeCheckPass(PropTypes.symbol, CoreSymbol('core-js')); }); }); describe('Custom validator', () => { beforeEach(() => { jest.resetModules(); }); it('should have been called with the right params', () => { var spy = jasmine.createSpy(); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={5} />, container); expect(spy.calls.count()).toBe(1); expect(spy.calls.argsFor(0)[1]).toBe('num'); }); it('should have been called even if the prop is not present', () => { var spy = jasmine.createSpy(); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component bla={5} />, container); expect(spy.calls.count()).toBe(1); expect(spy.calls.argsFor(0)[1]).toBe('num'); }); it("should have received the validator's return value", () => { spyOn(console, 'error'); var spy = jasmine .createSpy() .and.callFake(function(props, propName, componentName) { if (props[propName] !== 5) { return new Error('num must be 5!'); } }); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={6} />, container); expectDev(console.error.calls.count()).toBe(1); expect( console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)'), ).toBe( 'Warning: Failed prop type: num must be 5!\n' + ' in Component (at **)', ); }); it('should not warn if the validator returned null', () => { spyOn(console, 'error'); var spy = jasmine .createSpy() .and.callFake(function(props, propName, componentName) { return null; }); Component = class extends React.Component { static propTypes = {num: spy}; render() { return <div />; } }; var container = document.createElement('div'); ReactDOM.render(<Component num={5} />, container); expectDev(console.error.calls.count()).toBe(0); }); }); });
bsd-3-clause
mrapitis/sdl_android
sdl_android_lib/src/com/smartdevicelink/protocol/ProtocolFrameHeader.java
4083
package com.smartdevicelink.protocol; import com.smartdevicelink.protocol.enums.FrameType; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.util.BitConverter; public class ProtocolFrameHeader { private byte version = 1; private boolean compressed = false; private FrameType frameType = FrameType.Control; private SessionType sessionType = SessionType.RPC; private byte frameData = 0; private byte sessionID; private int dataSize; private int messageID; public static final byte FrameDataSingleFrame = 0x00; public static final byte FrameDataFirstFrame = 0x00; public static final byte FrameDataFinalConsecutiveFrame = 0x00; public ProtocolFrameHeader() {} public static ProtocolFrameHeader parseWiProHeader(byte[] header) { ProtocolFrameHeader msg = new ProtocolFrameHeader(); byte version = (byte) (header[0] >>> 4); msg.setVersion(version); boolean compressed = 1 == ((header[0] & 0x08) >>> 3); msg.setCompressed(compressed); byte frameType = (byte) (header[0] & 0x07); msg.setFrameType(FrameType.valueOf(frameType)); byte serviceType = header[1]; msg.setSessionType(SessionType.valueOf(serviceType)); byte frameData = header[2]; msg.setFrameData(frameData); byte sessionID = header[3]; msg.setSessionID(sessionID); int dataSize = BitConverter.intFromByteArray(header, 4); msg.setDataSize(dataSize); if (version > 1) { int messageID = BitConverter.intFromByteArray(header, 8); msg.setMessageID(messageID); } else msg.setMessageID(0); return msg; } protected byte[] assembleHeaderBytes() { int header = 0; header |= (version & 0x0F); header <<= 1; header |= (compressed ? 1 : 0); header <<= 3; header |= (frameType.value() & 0x07); header <<= 8; header |= (sessionType.value() & 0xFF); header <<= 8; header |= (frameData & 0xFF); header <<= 8; header |= (sessionID & 0xFF); if (version == 1) { byte[] ret = new byte[8]; System.arraycopy(BitConverter.intToByteArray(header), 0, ret, 0, 4); System.arraycopy(BitConverter.intToByteArray(dataSize), 0, ret, 4, 4); return ret; } else if (version > 1) { byte[] ret = new byte[12]; System.arraycopy(BitConverter.intToByteArray(header), 0, ret, 0, 4); System.arraycopy(BitConverter.intToByteArray(dataSize), 0, ret, 4, 4); System.arraycopy(BitConverter.intToByteArray(messageID), 0, ret, 8, 4); return ret; } else return null; } public String toString() { String ret = ""; ret += "version " + version + ", " + (compressed ? "compressed" : "uncompressed") + "\n"; ret += "frameType " + frameType + ", serviceType " + sessionType; ret += "\nframeData " + frameData; ret += ", sessionID " + sessionID; ret += ", dataSize " + dataSize; ret += ", messageID " + messageID; return ret; } public byte getVersion() { return version; } public void setVersion(byte version) { this.version = version; } public boolean isCompressed() { return compressed; } public void setCompressed(boolean compressed) { this.compressed = compressed; } public byte getFrameData() { return frameData; } public void setFrameData(byte frameData) { this.frameData = frameData; } public byte getSessionID() { return sessionID; } public void setSessionID(byte sessionID) { this.sessionID = sessionID; } public int getDataSize() { return dataSize; } public void setDataSize(int dataSize) { this.dataSize = dataSize; } public int getMessageID() { return messageID; } public void setMessageID(int messageID) { this.messageID = messageID; } public FrameType getFrameType() { return frameType; } public void setFrameType(FrameType frameType) { this.frameType = frameType; } public SessionType getSessionType() { return sessionType; } public void setSessionType(SessionType sessionType) { this.sessionType = sessionType; } }
bsd-3-clause
timcera/tsgettoolbox
src/tsgettoolbox/ulmo/ncdc/ghcn_daily/core.py
9898
# -*- coding: utf-8 -*- """ ulmo.ncdc.ghcn_daily.core ~~~~~~~~~~~~~~~~~~~~~~~~~ This module provides direct access to `National Climatic Data Center`_ `Global Historical Climate Network - Daily`_ dataset. .. _National Climatic Data Center: http://www.ncdc.noaa.gov .. _Global Historical Climate Network - Daily: http://www.ncdc.noaa.gov/oa/climate/ghcn-daily/ """ import itertools import os import numpy as np import pandas from tsgettoolbox.ulmo import util GHCN_DAILY_DIR = os.path.join(util.get_ulmo_dir(), "ncdc/ghcn_daily") def get_data(station_id, elements=None, update=True, as_dataframe=False): """Retrieves data for a given station. Parameters ---------- station_id : str Station ID to retrieve data for. elements : ``None``, str, or list of str If specified, limits the query to given element code(s). update : bool If ``True`` (default), new data files will be downloaded if they are newer than any previously cached files. If ``False``, then previously downloaded files will be used and new files will only be downloaded if there is not a previously downloaded file for a given station. as_dataframe : bool If ``False`` (default), a dict with element codes mapped to value dicts is returned. If ``True``, a dict with element codes mapped to equivalent pandas.DataFrame objects will be returned. The pandas dataframe is used internally, so setting this to ``True`` is a little bit faster as it skips a serialization step. Returns ------- site_dict : dict A dict with element codes as keys, mapped to collections of values. See the ``as_dataframe`` parameter for more. """ if isinstance(elements, str): elements = [elements] start_columns = [ ("year", 11, 15, int), ("month", 15, 17, int), ("element", 17, 21, str), ] value_columns = [ ("value", 0, 5, float), ("mflag", 5, 6, str), ("qflag", 6, 7, str), ("sflag", 7, 8, str), ] columns = list( itertools.chain( start_columns, *[ [ (name + str(n), start + 13 + (8 * n), end + 13 + (8 * n), converter) for name, start, end, converter in value_columns ] for n in range(1, 32) ] ) ) station_file_path = _get_ghcn_file(station_id + ".dly", check_modified=update) station_data = util.parse_fwf(station_file_path, columns, na_values=[-9999]) dataframes = {} for element_name, element_df in station_data.groupby("element"): if not elements is None and element_name not in elements: continue element_df["month_period"] = element_df.apply( lambda x: pandas.Period("{}-{}".format(x["year"], x["month"])), axis=1 ) element_df = element_df.set_index("month_period") monthly_index = element_df.index # here we're just using pandas' builtin resample logic to construct a daily # index for the timespan # 2018/11/27 johanneshorak: hotfix to get ncdc ghcn_daily working again # new resample syntax requires resample method to generate resampled index. daily_index = element_df.resample("D").sum().index.copy() # XXX: hackish; pandas support for this sort of thing will probably be # added soon month_starts = (monthly_index - 1).asfreq("D") + 1 dataframe = pandas.DataFrame( columns=["value", "mflag", "qflag", "sflag"], index=daily_index ) for day_of_month in range(1, 32): dates = [ date for date in (month_starts + day_of_month - 1) if date.day == day_of_month ] if not dates: continue months = pandas.PeriodIndex([pandas.Period(date, "M") for date in dates]) for column_name in dataframe.columns: col = column_name + str(day_of_month) dataframe[column_name][dates] = element_df[col][months] dataframes[element_name] = dataframe if as_dataframe: return dataframes return { key: util.dict_from_dataframe(dataframe) for key, dataframe in dataframes.items() } def get_stations( country=None, state=None, elements=None, start_year=None, end_year=None, update=True, as_dataframe=False, ): """Retrieves station information, optionally limited to specific parameters. Parameters ---------- country : str The country code to use to limit station results. If set to ``None`` (default), then stations from all countries are returned. state : str The state code to use to limit station results. If set to ``None`` (default), then stations from all states are returned. elements : ``None``, str, or list of str If specified, station results will be limited to the given element codes and only stations that have data for any these elements will be returned. start_year : int If specified, station results will be limited to contain only stations that have data after this year. Can be combined with the ``end_year`` argument to get stations with data within a range of years. end_year : int If specified, station results will be limited to contain only stations that have data before this year. Can be combined with the ``start_year`` argument to get stations with data within a range of years. update : bool If ``True`` (default), new data files will be downloaded if they are newer than any previously cached files. If ``False``, then previously downloaded files will be used and new files will only be downloaded if there is not a previously downloaded file for a given station. as_dataframe : bool If ``False`` (default), a dict with station IDs keyed to station dicts is returned. If ``True``, a single pandas.DataFrame object will be returned. The pandas dataframe is used internally, so setting this to ``True`` is a little bit faster as it skips a serialization step. Returns ------- stations_dict : dict or pandas.DataFrame A dict or pandas.DataFrame representing station information for stations matching the arguments. See the ``as_dataframe`` parameter for more. """ columns = [ ("country", 0, 2, None), ("network", 2, 3, None), ("network_id", 3, 11, None), ("latitude", 12, 20, None), ("longitude", 21, 30, None), ("elevation", 31, 37, None), ("state", 38, 40, None), ("name", 41, 71, None), ("gsn_flag", 72, 75, None), ("hcn_flag", 76, 79, None), ("wm_oid", 80, 85, None), ] stations_file = _get_ghcn_file("ghcnd-stations.txt", check_modified=update) stations = util.parse_fwf(stations_file, columns) if not country is None: stations = stations[stations["country"] == country] if not state is None: stations = stations[stations["state"] == state] # set station id and index by it stations["id"] = stations[["country", "network", "network_id"]].T.apply("".join) if not elements is None or not start_year is None or not end_year is None: inventory = _get_inventory(update=update) if not elements is None: if isinstance(elements, str): elements = [elements] mask = np.zeros(len(inventory), dtype=bool) for element in elements: mask += inventory["element"] == element inventory = inventory[mask] if not start_year is None: inventory = inventory[inventory["last_year"] >= start_year] if not end_year is None: inventory = inventory[inventory["first_year"] <= end_year] uniques = inventory["id"].unique() ids = pandas.DataFrame(uniques, index=uniques, columns=["id"]) stations = pandas.merge(stations, ids).set_index("id", drop=False) stations = stations.set_index("id", drop=False) # wm_oid gets convertidsed as a float, so cast it to str manually # pandas versions prior to 0.13.0 could use numpy's fix-width string type # to do this but that stopped working in pandas 0.13.0 - fortunately a # regex-based helper method was added then, too if pandas.__version__ < "0.13.0": stations["wm_oid"] = stations["wm_oid"].astype("|U5") stations["wm_oid"][stations["wm_oid"] == "nan"] = np.nan else: stations["wm_oid"] = stations["wm_oid"].astype("|U5").map(lambda x: x[:-2]) is_nan = stations["wm_oid"] == "n" is_empty = stations["wm_oid"] == "" is_invalid = is_nan | is_empty stations.loc[is_invalid, "wm_oid"] = np.nan if as_dataframe: return stations return util.dict_from_dataframe(stations) def _get_ghcn_file(filename, check_modified=True): base_url = "http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/" if "ghcnd-" in filename: url = base_url + filename else: url = base_url + "all/" + filename path = os.path.join(GHCN_DAILY_DIR, url.split("/")[-1]) util.download_if_new(url, path, check_modified=check_modified) return path def _get_inventory(update=True): columns = [ ("id", 0, 11, None), ("latitude", 12, 20, None), ("longitude", 21, 30, None), ("element", 31, 35, None), ("first_year", 36, 40, None), ("last_year", 41, 45, None), ] inventory_file = _get_ghcn_file("ghcnd-inventory.txt", check_modified=update) return util.parse_fwf(inventory_file, columns)
bsd-3-clause
FatturaElettronicaPA/FatturaElettronicaPA
Test/Ordinaria/FatturaElettronicaBodyValidator.cs
4718
using System.Linq; using FatturaElettronica.Ordinaria.FatturaElettronicaBody; using FatturaElettronica.Ordinaria.FatturaElettronicaBody.DatiBeniServizi; using FatturaElettronica.Ordinaria.FatturaElettronicaBody.DatiGenerali; using FatturaElettronica.Common; using FluentValidation.TestHelper; using Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ordinaria.Tests { [TestClass] public class FatturaElettronicaBodyValidator : BaseClass<FatturaElettronicaBody, FatturaElettronica.Validators.FatturaElettronicaBodyValidator> { [TestMethod] public void DatiGeneraliHasChildValidator() { validator.ShouldHaveChildValidator( x => x.DatiGenerali, typeof(FatturaElettronica.Validators.DatiGeneraliValidator)); } [TestMethod] public void DatiBeniServiziHasChildValidator() { validator.ShouldHaveChildValidator( x => x.DatiBeniServizi, typeof(FatturaElettronica.Validators.DatiBeniServiziValidator)); } [TestMethod] public void DatiBeniServiziCannotBeEmpty() { var r = validator.Validate(challenge); Assert.AreEqual("DatiBeniServizi è obbligatorio", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi").ErrorMessage); } [TestMethod] public void DatiRitenutaValidateAgainstError00411() { challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { Ritenuta = "SI" }); var r = validator.Validate(challenge); Assert.AreEqual("00411", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiGenerali.DatiGeneraliDocumento.DatiRitenuta").ErrorCode); challenge.DatiBeniServizi.DettaglioLinee[0].Ritenuta = null; r = validator.Validate(challenge); Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiGenerali.DatiGeneraliDocumento.DatiRitenuta")); } [TestMethod] public void DatiRitenutaValidateAgainstError00422() { challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 10m, PrezzoTotale = 100m }); challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 10m, ImponibileImporto = 101m }); var r = validator.Validate(challenge); Assert.AreEqual("00422", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo").ErrorCode); challenge.DatiBeniServizi.DatiRiepilogo[0].ImponibileImporto = 100m; r = validator.Validate(challenge); Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo")); } [TestMethod] public void DatiRitenutaValidateAgainstError00419() { challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 1 }); challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 2 }); challenge.DatiBeniServizi.DettaglioLinee.Add(new DettaglioLinee { AliquotaIVA = 3 }); challenge.DatiGenerali.DatiGeneraliDocumento.DatiCassaPrevidenziale.Add(new DatiCassaPrevidenziale { AliquotaIVA = 4 }); challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 1 }); challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 2 }); challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 3 }); var r = validator.Validate(challenge); Assert.AreEqual("00419", r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo").ErrorCode); challenge.DatiBeniServizi.DatiRiepilogo.Add(new DatiRiepilogo { AliquotaIVA = 4 }); r = validator.Validate(challenge); Assert.IsNull(r.Errors.FirstOrDefault(x => x.PropertyName == "DatiBeniServizi.DatiRiepilogo")); } [TestMethod] public void DatiVeicoliHasChildValidator() { validator.ShouldHaveChildValidator( x => x.DatiGenerali, typeof(FatturaElettronica.Validators.DatiGeneraliValidator)); } [TestMethod] public void DatiPagamentoHasChildValidator() { validator.ShouldHaveChildValidator( x => x.DatiPagamento, typeof(FatturaElettronica.Validators.DatiPagamentoValidator)); } [TestMethod] public void AllegatiHasChildValidator() { validator.ShouldHaveChildValidator( x => x.Allegati, typeof(FatturaElettronica.Validators.AllegatiValidator)); } } }
bsd-3-clause
GaloisInc/hacrypto
src/C/FELICS/common/msp/src/printf.c
15191
/****************************************************************************** * * msp430 printf function compatible with mspdebug simulator * Originally for mspgcc libc, only modificatin was to inline vuprintf * inside printf * ******************************************************************************/ #include <msp430.h> extern int putchar(int c) __attribute__((weak)); #undef __MSP430LIBC_PRINTF_INT32__ #undef __MSP430LIBC_PRINTF_INT64__ #undef __MSP430LIBC_PRINTF_INT20__ #include <stdlib.h> #include <stdbool.h> #include <stdarg.h> #include <string.h> #include <stdint.h> /** Format modifier indicating following int should be treated as a * 20-bit value */ #define A20_MODIFIER '\x8a' /** * Internal state tracking. * Saves memory and parameters when compacted in a bit field. */ typedef struct { #if __MSP430X__ uint8_t is_long20:1; ///< process a 20-bit integer #endif /* __MSP430X__ */ #if __MSP430LIBC_PRINTF_INT32__ || __MSP430LIBC_PRINTF_INT64__ uint8_t is_long32:1; ///< process a 32-bit integer #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT64__ uint8_t is_long64:1; ///< process a 64-bit integer #endif /* __MSP430LIBC_PRINTF_INT64__ */ uint8_t is_signed:1; ///< process a signed number uint8_t is_alternate_form:1; ///< alternate output uint8_t left_align:1; ///< if != 0 pad on right side, else on left side uint8_t emit_octal_prefix:1; ///< emit a prefix 0 uint8_t emit_hex_prefix:1; ///< emit a prefix 0x uint8_t fill_zero:1; ///< pad left with zero instead of space uint8_t uppercase:1; ///< print hex digits in upper case uint8_t zero_pad_precision:1; ///< add precision zeros before text uint8_t truncate_precision:1; ///< limit text to precision characters char sign_char; ///< character to emit as sign (NUL no emit) uint8_t precision; ///< value related to format precision specifier } flags_t; /** Maximum number of characters in any (numeric) prefix. The only * prefix at the moment is "0x". */ #define MAX_PREFIX_CHARS 2 #ifndef __MSP430LIBC_PRINTF_INT20__ #define __MSP430LIBC_PRINTF_INT20__ __MSP430X__ - 0 #endif /* __MSP430LIBC_PRINTF_INT20__ */ /** Maximum number of characters for formatted numbers, including sign * and EOS but excluding prefix. The longest representation will be * in octal, so assume one char for every three bits in the * representation. */ #if __MSP430LIBC_PRINTF_INT64__ #define MAX_FORMAT_LENGTH (((64 + 2) / 3) + 1 + 1) #elif __MSP430LIBC_PRINTF_INT32__ #define MAX_FORMAT_LENGTH (((32 + 2) / 3) + 1 + 1) #elif __MSP430_LIBC_PRINTF_INT20__ #define MAX_FORMAT_LENGTH (((20 + 2) / 3) + 1 + 1) #else /* __MSP430LIBC_PRINTF_INT*__ */ #define MAX_FORMAT_LENGTH (((16 + 2) / 3) + 1 + 1) #endif /* __MSP430LIBC_PRINTF_INT*__ */ /** * Helper function to generate anything that precedes leading zeros. * * @param write_char [in] function used to write characters * @param flags [in] flags that specify how the field is aligned * @return the number of characters that were written */ static int build_numeric_prefix (char *prefix_buffer, flags_t flags) { char *p = prefix_buffer; if (flags.emit_hex_prefix) { *p++ = '0'; *p++ = (flags.uppercase ? 'X' : 'x'); } else if (flags.emit_octal_prefix) { *p++ = '0'; } else if (flags.sign_char) { *p++ = flags.sign_char; } return (p - prefix_buffer); } /** * Helper function to print strings and fill to the defined width, with the * given fill character. * * @param write_char [in] function used to write characters * @param char_p [in] the string that is written * @param width [in] field width. 0 is without limitation of width. * @param flags [in] flags that specify how the field is aligned * @return the number of characters that were written */ static int print_field (int (*write_char) (int), const char *char_p, unsigned int width, flags_t flags) { int character_count = 0; char prefix_buffer[MAX_PREFIX_CHARS]; int prefix_idx = 0; unsigned int truncate_precision = flags.precision; int prefix_len = build_numeric_prefix (prefix_buffer, flags); if (!flags.truncate_precision) { truncate_precision = UINT16_MAX; } // if right aligned, pad if (!flags.left_align) { char leading_fill = ' '; unsigned int len = strlen (char_p); // Account for the prefix we'll write if (prefix_len <= width) { width -= prefix_len; } else { width = 0; } // Account for leading zeros required by a numeric precision specifier if (flags.zero_pad_precision) { if (flags.precision <= width) { width -= flags.precision; } else { width = 0; } } // Account for short writes of strings due to precision specifier if (truncate_precision < len) { len = truncate_precision; } // emit numeric prefix prior to padded zeros if (flags.fill_zero) { leading_fill = '0'; character_count += prefix_len; while (prefix_idx < prefix_len) { write_char(prefix_buffer[prefix_idx++]); } } while (len < width) { write_char(leading_fill); character_count++; len++; } } // emit any unemitted prefix while (prefix_idx < prefix_len) { character_count++; write_char(prefix_buffer[prefix_idx++]); } // emit zeros to meet precision requirements if (flags.zero_pad_precision) { while (flags.precision--) { write_char ('0'); character_count++; } } // output the buffer contents up to the maximum length while (*char_p && truncate_precision--) { write_char(*char_p); char_p++; character_count++; } // if left aligned, pad while (character_count < width) { write_char(' '); character_count++; } // return how many characters have been output return character_count; } int printf (const char *format, ...) { va_list args; va_start (args, format); int (*write_char)(int) = putchar; int character_count = 0x00; enum { DIRECT, FORMATING } mode = DIRECT; unsigned int wp_value = 0x34; unsigned int width = 0; flags_t flags; const char* specifier = format; char *char_p; char character; int radix; bool have_wp_value = false; bool have_precision = false; bool is_zero = false; bool is_negative = false; union { int16_t i16; intptr_t ptr; #if __MSP430LIBC_PRINTF_INT20__ int20_t i20; #endif /* __MSP430X__ */ #if __MSP430LIBC_PRINTF_INT32__ int32_t i32; #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT64__ int64_t i64; #endif /* __MSP430LIBC_PRINTF_INT64__ */ } number; char buffer[MAX_FORMAT_LENGTH]; // used to print numbers while ((character = *format++)) { // test and save character if (mode == DIRECT) { // output characters from the format string directly, except the // '%' sign which changes the mode if (character == '%') { width = wp_value = 0; memset (&flags, 0, sizeof (flags)); have_wp_value = have_precision = is_zero = is_negative = false; specifier = format - 1; mode = FORMATING; } else { write_character: write_char(character); character_count++; mode = DIRECT; } } else { //FORMATING // process format characters switch (character) { // output '%' itself case '%': goto write_character; // character is already the % // alternate form flag case '#': flags.is_alternate_form = true; break; #if __MSP430LIBC_PRINTF_INT20__ // 20-bit integer follows case A20_MODIFIER: flags.is_long20 = true; break; #endif // interpret next number as long integer case 'l': #if __MSP430LIBC_PRINTF_INT64__ if (flags.is_long32) { flags.is_long32 = false; flags.is_long64 = true; } else { #endif /* __MSP430LIBC_PRINTF_INT64__ */ #if __MSP430LIBC_PRINTF_INT32__ if (flags.is_long32) { goto bad_format; } flags.is_long32 = true; #else /* __MSP430LIBC_PRINTF_INT32__ */ goto bad_format; #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT64__ } #endif /* __MSP430LIBC_PRINTF_INT64__ */ break; // left align instead of right align case '-': flags.left_align = true; break; // emit a + before a positive number case '+': flags.sign_char = '+'; break; // emit a space before a positive number case ' ': // + overrides space as a flag character if ('+' != flags.sign_char) { flags.sign_char = ' '; } break; case '.': // explicit precision is present if (have_wp_value) { width = wp_value; wp_value = 0; have_wp_value = false; } have_precision = true; break; // fetch length from argument list instead of the format // string itself case '*': { int val = va_arg (args, int); if (val >= 0) { wp_value = val; } else if (have_precision) { wp_value = 0; } else { flags.left_align = true; wp_value = -val; } have_wp_value = true; break; } // format field width. zero needs special treatment // as when it occurs as first number it is the // flag to pad with zeroes instead of spaces case '0': // a leading zero means filling with zeros // it must be a leading zero if 'width' is zero // otherwise it is in a number as in "10" if (wp_value == 0 && !have_precision) { flags.fill_zero = !flags.left_align; break; } /*@fallthrough@ */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': wp_value *= 10; wp_value += character - '0'; have_wp_value = true; break; // placeholder for one character case 'c': character = va_arg (args, int); if (! have_precision && ! have_wp_value) { goto write_character; } char_p = buffer; buffer[0] = character; buffer[1] = 0; goto emit_string; // placeholder for arbitrary length null terminated // string case 's': char_p = va_arg (args, char *); emit_string: /* Note: Zero-padding on strings is undefined; it * is legitimate to zero-pad */ if (have_precision) { flags.truncate_precision = true; flags.precision = wp_value; } else if (have_wp_value) { width = wp_value; } character_count += print_field(write_char, (char_p != NULL) ? char_p : "(null)", width, flags); mode = DIRECT; break; // placeholder for an address // addresses are automatically in alternate form and // hexadecimal. case 'p': number.ptr = (intptr_t) va_arg (args, void *); number.ptr &= UINTPTR_MAX; radix = 16; flags.is_alternate_form = (0 != number.ptr); goto emit_number; // placeholder for hexadecimal output case 'X': flags.uppercase = true; /*@fallthrough@ */ case 'x': radix = 16; goto fetch_number; // placeholder for octal output case 'o': radix = 8; goto fetch_number; // placeholder for signed numbers case 'd': case 'i': flags.is_signed = true; /*@fallthrough@ */ // placeholder for unsigned numbers case 'u': radix = 10; // label for number outputs including argument fetching fetch_number: #if __MSP430LIBC_PRINTF_INT64__ if (flags.is_long64) { number.i64 = va_arg (args, int64_t); is_zero = (number.i64 == 0); is_negative = (number.i64 < 0); } else #endif /* __MSP430LIBC_PRINTF_INT64__ */ #if __MSP430LIBC_PRINTF_INT32__ if (flags.is_long32) { number.i32 = va_arg (args, int32_t); is_zero = (number.i32 == 0); is_negative = (number.i32 < 0); } else #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT20__ if (flags.is_long20) { number.i20 = va_arg (args, int20_t); is_zero = (number.i20 == 0); is_negative = (number.i20 < 0); } else #endif /* __MSP430LIBC_PRINTF_INT20__ */ { number.i16 = va_arg (args, int16_t); is_zero = (number.i16 == 0); is_negative = (number.i16 < 0); } // label for number outputs excluding argument fetching // 'number' already contains the value emit_number: // only non-zero numbers get hex/octal alternate form if (flags.is_alternate_form && !is_zero) { if (radix == 16) { flags.emit_hex_prefix = true; } else if (radix == 8) { flags.emit_octal_prefix = true; } } if (flags.is_signed && is_negative) { // save sign for radix 10 conversion flags.sign_char = '-'; #if __MSP430LIBC_PRINTF_INT64__ if (flags.is_long64) { number.i64 = -number.i64; } else #endif /* __MSP430LIBC_PRINTF_INT64__ */ #if __MSP430LIBC_PRINTF_INT32__ if (flags.is_long32) number.i32 = -number.i32; else #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT20__ if (flags.is_long20) number.i20 = -number.i20; else #endif /* __MSP430LIBC_PRINTF_INT20__ */ number.i16 = -number.i16; } // go to the end of the buffer and null terminate char_p = &buffer[sizeof (buffer) - 1]; *char_p-- = '\0'; // divide and save digits, fill from the lowest // significant digit #define CONVERT_LOOP(_unsigned, _number) \ do \ { \ int digit = (_unsigned) _number % radix; \ if (digit < 10) \ { \ *char_p-- = digit + '0'; \ } \ else \ { \ *char_p-- = digit + (flags.uppercase ? ('A' - 10) : ('a' - 10)); \ } \ _number = ((_unsigned) _number) / radix; \ } \ while ((_unsigned) _number > 0) #if __MSP430LIBC_PRINTF_INT64__ if (flags.is_long64) CONVERT_LOOP (uint64_t, number.i64); else #endif /* __MSP430LIBC_PRINTF_INT64__ */ #if __MSP430LIBC_PRINTF_INT32__ if (flags.is_long32) CONVERT_LOOP (uint32_t, number.i32); else #endif /* __MSP430LIBC_PRINTF_INT32__ */ #if __MSP430LIBC_PRINTF_INT20__ if (flags.is_long20) CONVERT_LOOP (uint20_t, number.i20); else #endif /* __MSP430LIBC_PRINTF_INT20__ */ CONVERT_LOOP (uint16_t, number.i16); #undef CONVERT_LOOP // only decimal numbers get signs if (radix != 10) { flags.sign_char = 0; } // write padded result if (have_precision) { int number_width = buffer + sizeof (buffer) - char_p - 2; if (number_width < wp_value) { flags.zero_pad_precision = true; flags.precision = wp_value - number_width; } } else if (have_wp_value) { width = wp_value; } character_count += print_field(write_char, 1 + char_p, width, flags); mode = DIRECT; break; default: bad_format: while (specifier < format) { write_char (*specifier++); ++character_count; } mode = DIRECT; break; } } } va_end (args); return character_count; }
bsd-3-clause
MarginC/kame
openbsd/sys/scsi/atapi_cd.h
4714
/* $OpenBSD: atapi_cd.h,v 1.1 1999/07/20 06:21:59 csapuntz Exp $ */ /* $NetBSD: atapi_cd.h,v 1.9 1998/07/13 16:50:56 thorpej Exp $ */ /* * Copyright (c) 1996 Manuel Bouyer. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Manuel Bouyer. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define ATAPI_LOAD_UNLOAD 0xa6 struct atapi_load_unload { u_int8_t opcode; u_int8_t unused1[3]; u_int8_t options; u_int8_t unused2[3]; u_int8_t slot; u_int8_t unused3[3]; }; struct atapi_cdrom_page { u_int8_t page; u_int8_t length; u_int8_t reserved; u_int8_t inact_mult; u_int8_t spm[2]; u_int8_t fps[2]; }; struct atapi_cap_page { /* Capabilities page */ u_int8_t page_code; u_int8_t param_len; u_int8_t reserved1[2]; u_int8_t cap1; #define AUDIO_PLAY 0x01 /* audio play supported */ #define AV_COMPOSITE /* composite audio/video supported */ #define DA_PORT1 /* digital audio on port 1 */ #define DA_PORT2 /* digital audio on port 2 */ #define M2F1 /* mode 2 form 1 (XA) read */ #define M2F2 /* mode 2 form 2 format */ #define CD_MULTISESSION /* multi-session photo-CD */ u_int8_t cap2; #define CD_DA 0x01 /* audio-CD read supported */ #define CD_DA_STREAM 0x02 /* CD-DA streaming */ #define RW_SUB 0x04 /* combined R-W subchannels */ #define RW_SUB_CORR 0x08 /* R-W subchannel data corrected */ #define C2_ERRP 0x10 /* C2 error pointers supported */ #define ISRC 0x20 /* can return the ISRC */ #define UPC 0x40 /* can return the catalog number UPC */ u_int8_t m_status; #define CANLOCK 0x01 /* could be locked */ #define LOCK_STATE 0x02 /* current lock state */ #define PREVENT_JUMP 0x04 /* prevent jumper installed */ #define CANEJECT 0x08 /* can eject */ #define MECH_MASK 0xe0 /* loading mechanism type */ #define MECH_CADDY 0x00 #define MECH_TRAY 0x20 #define MECH_POPUP 0x40 #define MECH_CHANGER_INDIV 0x80 #define MECH_CHANGER_CARTRIDGE 0xa0 u_int8_t cap3; #define SEPARATE_VOL 0x01 /* independent volume of channels */ #define SEPARATE_MUTE 0x02 /* independent mute of channels */ #define SUPP_DISK_PRESENT 0x04 /* changer can report contents of slots */ #define SSS 0x08 /* software slot selection */ u_int8_t max_speed[2]; /* max raw data rate in bytes/1000 */ u_int8_t max_vol_levels[2]; /* number of discrete volume levels */ u_int8_t buf_size[2]; /* internal buffer size in bytes/1024 */ u_int8_t cur_speed[2]; /* current data rate in bytes/1000 */ /* Digital drive output format description (optional?) */ u_int8_t reserved2; u_int8_t dig_output; /* Digital drive output format description */ u_int8_t reserved3[2]; }; #define ATAPI_CDROM_PAGE 0x0d #define ATAPI_AUDIO_PAGE 0x0e #define ATAPI_AUDIO_PAGE_MASK 0x4e #define ATAPI_CAP_PAGE 0x2a union atapi_cd_pages { u_int8_t page_code; struct atapi_cdrom_page cdrom; struct atapi_cap_page cap; struct cd_audio_page audio; }; struct atapi_cd_mode_data { struct atapi_mode_header header; union atapi_cd_pages pages; }; #define AUDIOPAGESIZE \ (sizeof(struct atapi_mode_header) + sizeof(struct cd_audio_page)) #define CDROMPAGESIZE \ (sizeof(struct atapi_mode_header) + sizeof(struct atapi_cdrom_page)) #define CAPPAGESIZE \ (sizeof(struct atapi_mode_header) + sizeof(struct atapi_cap_page))
bsd-3-clause
foxostro/GutsyStormCocoa
GutsyStorm/GSVectorUtils.h
445
// // GSVectorUtils.h // GutsyStorm // // Created by Andrew Fox on 3/18/12. // Copyright © 2012-2016 Andrew Fox. All rights reserved. // #import <simd/vector.h> NSUInteger vector_hash(vector_float3 v); static inline vector_float3 vector_make(float x, float y, float z) { return (vector_float3){x, y, z}; } static inline BOOL vector_equal(vector_float3 a, vector_float3 b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z); }
bsd-3-clause
hostkerala/yii2-test
backend/controllers/CategoriesController.php
3237
<?php namespace backend\controllers; use Yii; use common\models\Categories; use common\models\CategoriesSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * Created By Roopan v v <[email protected]> * Date : 24-04-2015 * Time :3:00 PM * CategoriesController implements the CRUD actions for Categories model. */ class CategoriesController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Lists all Categories models. * @return mixed */ public function actionIndex() { $searchModel = new CategoriesSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Categories model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Categories model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Categories(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Categories model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Categories model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Categories model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Categories the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Categories::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
bsd-3-clause
loopCM/chromium
content/browser/gpu/gpu_data_manager_impl.cc
7341
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gpu/gpu_data_manager_impl.h" #include "content/browser/gpu/gpu_data_manager_impl_private.h" namespace content { // static GpuDataManager* GpuDataManager::GetInstance() { return GpuDataManagerImpl::GetInstance(); } // static GpuDataManagerImpl* GpuDataManagerImpl::GetInstance() { return Singleton<GpuDataManagerImpl>::get(); } void GpuDataManagerImpl::InitializeForTesting( const std::string& gpu_blacklist_json, const GPUInfo& gpu_info) { base::AutoLock auto_lock(lock_); private_->InitializeForTesting(gpu_blacklist_json, gpu_info); } bool GpuDataManagerImpl::IsFeatureBlacklisted(int feature) const { base::AutoLock auto_lock(lock_); return private_->IsFeatureBlacklisted(feature); } GPUInfo GpuDataManagerImpl::GetGPUInfo() const { base::AutoLock auto_lock(lock_); return private_->GetGPUInfo(); } void GpuDataManagerImpl::GetGpuProcessHandles( const GetGpuProcessHandlesCallback& callback) const { base::AutoLock auto_lock(lock_); private_->GetGpuProcessHandles(callback); } bool GpuDataManagerImpl::GpuAccessAllowed(std::string* reason) const { base::AutoLock auto_lock(lock_); return private_->GpuAccessAllowed(reason); } void GpuDataManagerImpl::RequestCompleteGpuInfoIfNeeded() { base::AutoLock auto_lock(lock_); private_->RequestCompleteGpuInfoIfNeeded(); } bool GpuDataManagerImpl::IsCompleteGpuInfoAvailable() const { base::AutoLock auto_lock(lock_); return private_->IsCompleteGpuInfoAvailable(); } void GpuDataManagerImpl::RequestVideoMemoryUsageStatsUpdate() const { base::AutoLock auto_lock(lock_); private_->RequestVideoMemoryUsageStatsUpdate(); } bool GpuDataManagerImpl::ShouldUseSwiftShader() const { base::AutoLock auto_lock(lock_); return private_->ShouldUseSwiftShader(); } void GpuDataManagerImpl::RegisterSwiftShaderPath( const base::FilePath& path) { base::AutoLock auto_lock(lock_); private_->RegisterSwiftShaderPath(path); } void GpuDataManagerImpl::AddObserver( GpuDataManagerObserver* observer) { base::AutoLock auto_lock(lock_); private_->AddObserver(observer); } void GpuDataManagerImpl::RemoveObserver( GpuDataManagerObserver* observer) { base::AutoLock auto_lock(lock_); private_->RemoveObserver(observer); } void GpuDataManagerImpl::UnblockDomainFrom3DAPIs(const GURL& url) { base::AutoLock auto_lock(lock_); private_->UnblockDomainFrom3DAPIs(url); } void GpuDataManagerImpl::DisableGpuWatchdog() { base::AutoLock auto_lock(lock_); private_->DisableGpuWatchdog(); } void GpuDataManagerImpl::SetGLStrings(const std::string& gl_vendor, const std::string& gl_renderer, const std::string& gl_version) { base::AutoLock auto_lock(lock_); private_->SetGLStrings(gl_vendor, gl_renderer, gl_version); } void GpuDataManagerImpl::GetGLStrings(std::string* gl_vendor, std::string* gl_renderer, std::string* gl_version) { base::AutoLock auto_lock(lock_); private_->GetGLStrings(gl_vendor, gl_renderer, gl_version); } void GpuDataManagerImpl::DisableHardwareAcceleration() { base::AutoLock auto_lock(lock_); private_->DisableHardwareAcceleration(); } void GpuDataManagerImpl::Initialize() { base::AutoLock auto_lock(lock_); private_->Initialize(); } void GpuDataManagerImpl::UpdateGpuInfo(const GPUInfo& gpu_info) { base::AutoLock auto_lock(lock_); private_->UpdateGpuInfo(gpu_info); } void GpuDataManagerImpl::UpdateVideoMemoryUsageStats( const GPUVideoMemoryUsageStats& video_memory_usage_stats) { base::AutoLock auto_lock(lock_); private_->UpdateVideoMemoryUsageStats(video_memory_usage_stats); } void GpuDataManagerImpl::AppendRendererCommandLine( CommandLine* command_line) const { base::AutoLock auto_lock(lock_); private_->AppendRendererCommandLine(command_line); } void GpuDataManagerImpl::AppendGpuCommandLine( CommandLine* command_line) const { base::AutoLock auto_lock(lock_); private_->AppendGpuCommandLine(command_line); } void GpuDataManagerImpl::AppendPluginCommandLine( CommandLine* command_line) const { base::AutoLock auto_lock(lock_); private_->AppendPluginCommandLine(command_line); } void GpuDataManagerImpl::UpdateRendererWebPrefs( WebPreferences* prefs) const { base::AutoLock auto_lock(lock_); private_->UpdateRendererWebPrefs(prefs); } GpuSwitchingOption GpuDataManagerImpl::GetGpuSwitchingOption() const { base::AutoLock auto_lock(lock_); return private_->GetGpuSwitchingOption(); } std::string GpuDataManagerImpl::GetBlacklistVersion() const { base::AutoLock auto_lock(lock_); return private_->GetBlacklistVersion(); } base::ListValue* GpuDataManagerImpl::GetBlacklistReasons() const { base::AutoLock auto_lock(lock_); return private_->GetBlacklistReasons(); } void GpuDataManagerImpl::AddLogMessage(int level, const std::string& header, const std::string& message) { base::AutoLock auto_lock(lock_); private_->AddLogMessage(level, header, message); } void GpuDataManagerImpl::ProcessCrashed( base::TerminationStatus exit_code) { base::AutoLock auto_lock(lock_); private_->ProcessCrashed(exit_code); } base::ListValue* GpuDataManagerImpl::GetLogMessages() const { base::AutoLock auto_lock(lock_); return private_->GetLogMessages(); } void GpuDataManagerImpl::HandleGpuSwitch() { base::AutoLock auto_lock(lock_); private_->HandleGpuSwitch(); } #if defined(OS_WIN) bool GpuDataManagerImpl::IsUsingAcceleratedSurface() const { base::AutoLock auto_lock(lock_); return private_->IsUsingAcceleratedSurface(); } #endif void GpuDataManagerImpl::BlockDomainFrom3DAPIs( const GURL& url, DomainGuilt guilt) { base::AutoLock auto_lock(lock_); private_->BlockDomainFrom3DAPIs(url, guilt); } bool GpuDataManagerImpl::Are3DAPIsBlocked(const GURL& url, int render_process_id, int render_view_id, ThreeDAPIType requester) { base::AutoLock auto_lock(lock_); return private_->Are3DAPIsBlocked( url, render_process_id, render_view_id, requester); } void GpuDataManagerImpl::DisableDomainBlockingFor3DAPIsForTesting() { base::AutoLock auto_lock(lock_); private_->DisableDomainBlockingFor3DAPIsForTesting(); } size_t GpuDataManagerImpl::GetBlacklistedFeatureCount() const { base::AutoLock auto_lock(lock_); return private_->GetBlacklistedFeatureCount(); } void GpuDataManagerImpl::Notify3DAPIBlocked(const GURL& url, int render_process_id, int render_view_id, ThreeDAPIType requester) { base::AutoLock auto_lock(lock_); private_->Notify3DAPIBlocked( url, render_process_id, render_view_id, requester); } GpuDataManagerImpl::GpuDataManagerImpl() : private_(GpuDataManagerImplPrivate::Create(this)) { } GpuDataManagerImpl::~GpuDataManagerImpl() { } } // namespace content
bsd-3-clause
INCF/lib9ML
test/unittests/abstraction_test/dynamics_test.py
37676
import unittest from sympy import sympify from nineml.abstraction import ( Dynamics, AnalogSendPort, Alias, AnalogReceivePort, AnalogReducePort, Regime, On, OutputEvent, EventReceivePort, Constant, StateVariable, Parameter, OnCondition, OnEvent, Trigger) import nineml.units as un from nineml.exceptions import NineMLMathParseError, NineMLUsageError from nineml.document import Document from nineml.utils.iterables import unique_by_id class ComponentClass_test(unittest.TestCase): def test_aliases(self): # Signature: name # Forwarding function to self.dynamics.aliases # No Aliases: self.assertEqual( list(Dynamics(name='C1').aliases), [] ) # 2 Aliases C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1']) self.assertEqual(len(list((C.aliases))), 2) self.assertEqual( set(C.alias_names), set(['G', 'H']) ) C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1', Alias('I', '3')]) self.assertEqual(len(list((C.aliases))), 3) self.assertEqual( set(C.alias_names), set(['G', 'H', 'I']) ) # Using DynamicsBlock Parameter: C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1']) self.assertEqual(len(list((C.aliases))), 2) self.assertEqual( set(C.alias_names), set(['G', 'H']) ) C = Dynamics(name='C1', aliases=['G:= 0', 'H:=1', Alias('I', '3')]) self.assertEqual(len(list((C.aliases))), 3) self.assertEqual( set(C.alias_names), set(['G', 'H', 'I']) ) # Invalid Construction: # Invalid Valid String: self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H=0'] ) # Duplicate Alias Names: Dynamics(name='C1', aliases=['H:=0', 'G:=1']) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H:=0', 'H:=1'] ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H:=0', Alias('H', '1')] ) # Self referential aliases: self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H := H +1'], ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H := G + 1', 'G := H + 1'], ) # Referencing none existent symbols: self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H := G + I'], parameters=['P1'], ) # Invalid Names: self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['H.2 := 0'], ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['2H := 0'], ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['E(H) := 0'], ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['tanh := 0'], ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['t := 0'], ) def test_aliases_map(self): # Signature: name # Forwarding function to self.dynamics.alias_map self.assertEqual( Dynamics(name='C1')._aliases, {} ) c1 = Dynamics(name='C1', aliases=['A:=3']) self.assertEqual(c1.alias('A').rhs_as_python_func(), 3) self.assertEqual(len(c1._aliases), 1) c2 = Dynamics(name='C1', aliases=['A:=3', 'B:=5']) self.assertEqual(c2.alias('A').rhs_as_python_func(), 3) self.assertEqual(c2.alias('B').rhs_as_python_func(), 5) self.assertEqual(len(c2._aliases), 2) c3 = Dynamics(name='C1', aliases=['C:=13', 'Z:=15']) self.assertEqual(c3.alias('C').rhs_as_python_func(), 13) self.assertEqual(c3.alias('Z').rhs_as_python_func(), 15) self.assertEqual(len(c3._aliases), 2) def test_analog_ports(self): # Signature: name # No Docstring c = Dynamics(name='C1') self.assertEqual(len(list(c.analog_ports)), 0) c = Dynamics(name='C1') self.assertEqual(len(list(c.analog_ports)), 0) c = Dynamics(name='C1', aliases=['A:=2'], analog_ports=[AnalogSendPort('A')]) self.assertEqual(len(list(c.analog_ports)), 1) self.assertEqual(list(c.analog_ports)[0].mode, 'send') self.assertEqual(len(list(c.analog_send_ports)), 1) self.assertEqual(len(list(c.analog_receive_ports)), 0) self.assertEqual(len(list(c.analog_reduce_ports)), 0) c = Dynamics(name='C1', analog_ports=[AnalogReceivePort('B')]) self.assertEqual(len(list(c.analog_ports)), 1) self.assertEqual(list(c.analog_ports)[0].mode, 'recv') self.assertEqual(len(list(c.analog_send_ports)), 0) self.assertEqual(len(list(c.analog_receive_ports)), 1) self.assertEqual(len(list(c.analog_reduce_ports)), 0) c = Dynamics(name='C1', analog_ports=[AnalogReducePort('B', operator='+')]) self.assertEqual(len(list(c.analog_ports)), 1) self.assertEqual(list(c.analog_ports)[0].mode, 'reduce') self.assertEqual(list(c.analog_ports)[0].operator, '+') self.assertEqual(len(list(c.analog_send_ports)), 0) self.assertEqual(len(list(c.analog_receive_ports)), 0) self.assertEqual(len(list(c.analog_reduce_ports)), 1) # Duplicate Port Names: self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['A1:=1'], analog_ports=[AnalogReducePort('B', operator='+'), AnalogSendPort('B')] ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['A1:=1'], analog_ports=[AnalogSendPort('A'), AnalogSendPort('A')] ) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['A1:=1'], analog_ports=[AnalogReceivePort('A'), AnalogReceivePort('A')] ) self.assertRaises( NineMLUsageError, lambda: Dynamics(name='C1', analog_ports=[AnalogReceivePort('1')]) ) self.assertRaises( NineMLUsageError, lambda: Dynamics(name='C1', analog_ports=[AnalogReceivePort('?')]) ) def duplicate_port_name_event_analog(self): # Check different names are OK: Dynamics( name='C1', aliases=['A1:=1'], event_ports=[EventReceivePort('A')], analog_ports=[AnalogSendPort('A')]) self.assertRaises( NineMLUsageError, Dynamics, name='C1', aliases=['A1:=1'], event_ports=[EventReceivePort('A')], analog_ports=[AnalogSendPort('A')] ) def test_event_ports(self): # Signature: name # No Docstring # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=Regime( transitions=[ On('V > a', do=OutputEvent('ev_port1')), On('V > b', do=OutputEvent('ev_port1')), On('V < c', do=OutputEvent('ev_port2')), ] ), ) self.assertEqual(len(list(c.event_ports)), 2) # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=[ Regime(name='r1', transitions=[ On('V > a', do=OutputEvent('ev_port1'), to='r2'), On('V < b', do=OutputEvent('ev_port2'))]), Regime(name='r2', transitions=[ On('V > a', do=OutputEvent('ev_port2'), to='r1'), On('V < b', do=OutputEvent('ev_port3'))]) ] ) self.assertEqual(len(list(c.event_ports)), 3) # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=[ Regime(name='r1', transitions=[ On('spikeinput1', do=[]), On('spikeinput2', do=OutputEvent('ev_port2'), to='r2')]), Regime(name='r2', transitions=[ On('V > a', do=OutputEvent('ev_port2')), On('spikeinput3', do=OutputEvent('ev_port3'), to='r1')]) ] ) self.assertEqual(len(list(c.event_ports)), 5) def test_parameters(self): # Signature: name # No Docstring # No parameters; nothing to infer c = Dynamics(name='cl') self.assertEqual(len(list(c.parameters)), 0) # Mismatch between inferred and actual parameters self.assertRaises( NineMLUsageError, Dynamics, name='cl', parameters=['a']) # Single parameter inference from an alias block c = Dynamics(name='cl', aliases=['A1:=a']) self.assertEqual(len(list(c.parameters)), 1) self.assertEqual(list(c.parameters)[0].name, 'a') # More complex inference: c = Dynamics(name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], constants=[Constant('pi', 3.141592653589793)]) self.assertEqual(len(list(c.parameters)), 3) self.assertEqual(sorted([p.name for p in c.parameters]), ['a', 'b', 'e']) # From State Assignments and Differential Equations, and Conditionals c = Dynamics(name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], regimes=Regime('dX/dt = (6 + c + sin(d))/t', 'dV/dt = 1.0/t', transitions=On('V>Vt', do=['X = X + f', 'V=0'])), constants=[Constant('pi', 3.1415926535)]) self.assertEqual(len(list(c.parameters)), 7) self.assertEqual( sorted([p.name for p in c.parameters]), ['Vt', 'a', 'b', 'c', 'd', 'e', 'f']) self.assertRaises( NineMLUsageError, Dynamics, name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], regimes=Regime('dX/dt = 6 + c + sin(d)', 'dV/dt = 1.0', transitions=On('V>Vt', do=['X = X + f', 'V=0']) ), parameters=['a', 'b', 'c']) def test_regimes(self): c = Dynamics(name='cl', ) self.assertEqual(len(list(c.regimes)), 0) c = Dynamics(name='cl', regimes=Regime('dX/dt=1/t', name='r1', transitions=On('X>X1', do=['X = X0'], to=None))) self.assertEqual(len(list(c.regimes)), 1) c = Dynamics(name='cl', regimes=[ Regime('dX/dt=1/t', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX/dt=1/t', name='r2', transitions=On('X>X1', do=['X=X0'], to='r3')), Regime('dX/dt=1/t', name='r3', transitions=On('X>X1', do=['X=X0'], to='r4')), Regime('dX/dt=1/t', name='r4', transitions=On('X>X1', do=['X=X0'], to='r1'))]) self.assertEqual(len(list(c.regimes)), 4) self.assertEqual( set(c.regime_names), set(['r1', 'r2', 'r3', 'r4']) ) c = Dynamics(name='cl', regimes=[ Regime('dX/dt=1/t', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX/dt=1/t', name='r2', transitions=On('X>X1', do=['X=X0'], to='r3')), Regime('dX/dt=1/t', name='r3', transitions=On('X>X1', do=['X=X0'], to='r4')), Regime('dX/dt=1/t', name='r4', transitions=On('X>X1', do=['X=X0'], to='r1'))]) self.assertEqual(len(list(c.regimes)), 4) self.assertEqual( set([r.name for r in c.regimes]), set(['r1', 'r2', 'r3', 'r4']) ) # Duplicate Names: self.assertRaises( NineMLUsageError, Dynamics, name='cl', regimes=[ Regime('dX/dt=1/t', name='r', transitions=On('X>X1', do=['X=X0'])), Regime('dX/dt=1/t', name='r', transitions=On('X>X1', do=['X=X0'],)), ] ) def test_regime_aliases(self): a = Dynamics( name='a', aliases=[Alias('A', '4/t')], regimes=[ Regime('dX/dt=1/t + A', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX/dt=1/t + A', name='r2', transitions=On('X>X1', do=['X=X0'], to='r1'), aliases=[Alias('A', '8 / t')])]) self.assertEqual(a.regime('r2').alias('A'), Alias('A', '8 / t')) self.assertRaises( NineMLUsageError, Dynamics, name='a', regimes=[ Regime('dX/dt=1/t + A', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX/dt=1/t + A', name='r2', transitions=On('X>X1', do=['X=X0'], to='r1'), aliases=[Alias('A', '8 / t')])]) document = Document() a_xml = a.serialize(format='xml', version=1, document=document) b = Dynamics.unserialize(a_xml, format='xml', version=1, document=Document(un.dimensionless.clone())) self.assertEqual(a, b, "Dynamics with regime-specific alias failed xml " "roundtrip:\n{}".format(a.find_mismatch(b))) def test_state_variables(self): # No parameters; nothing to infer c = Dynamics(name='cl') self.assertEqual(len(list(c.state_variables)), 0) # From State Assignments and Differential Equations, and Conditionals c = Dynamics( name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], regimes=Regime('dX/dt = (6 + c + sin(d))/t', 'dV/dt = 1.0/t', transitions=On('V>Vt', do=['X = X + f', 'V=0']))) self.assertEqual( set(c.state_variable_names), set(['X', 'V'])) self.assertRaises( NineMLUsageError, Dynamics, name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], regimes=Regime('dX/dt = 6 + c + sin(d)', 'dV/dt = 1.0', transitions=On('V>Vt', do=['X = X + f', 'V=0']) ), state_variables=['X']) # Shouldn't pick up 'e' as a parameter: self.assertRaises( NineMLUsageError, Dynamics, name='cl', aliases=['A1:=a+e', 'B1:=a+pi+b'], regimes=Regime('dX/dt = 6 + c + sin(d)', 'dV/dt = 1.0', transitions=On('V>Vt', do=['X = X + f', 'V=0']) ), state_variables=['X', 'V', 'Vt']) c = Dynamics(name='cl', regimes=[ Regime('dX1/dt=1/t', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX1/dt=1/t', name='r2', transitions=On('X>X1', do=['X=X0'], to='r3')), Regime('dX2/dt=1/t', name='r3', transitions=On('X>X1', do=['X=X0'], to='r4')), Regime('dX2/dt=1/t', name='r4', transitions=On('X>X1', do=['X=X0'], to='r1'))]) self.assertEqual(set(c.state_variable_names), set(['X1', 'X2', 'X'])) def test_transitions(self): c = Dynamics(name='cl', regimes=[ Regime('dX1/dt=1/t', name='r1', transitions=[On('X>X1', do=['X=X0'], to='r2'), On('X>X2', do=['X=X0'], to='r3'), ] ), Regime('dX1/dt=1/t', name='r2', transitions=On('X>X1', do=['X=X0'], to='r3'),), Regime('dX2/dt=1/t', name='r3', transitions=[On('X>X1', do=['X=X0'], to='r4'), On('X>X2', do=['X=X0'], to=None)]), Regime('dX2/dt=1/t', name='r4', transitions=On('X>X1', do=['X=X0'], to=None))]) self.assertEqual(len(list(c.all_transitions())), 6) r1 = c.regime('r1') r2 = c.regime('r2') r3 = c.regime('r3') r4 = c.regime('r4') self.assertEqual(len(list(r1.transitions)), 2) self.assertEqual(len(list(r2.transitions)), 1) self.assertEqual(len(list(r3.transitions)), 2) self.assertEqual(len(list(r4.transitions)), 1) def target_regimes(regime): return unique_by_id(t.target_regime for t in regime.transitions) self.assertEqual(target_regimes(r1), [r2, r3]) self.assertEqual(target_regimes(r2), [r3]) self.assertEqual(target_regimes(r3), [r3, r4]) self.assertEqual(target_regimes(r4), [r4]) def test_all_expressions(self): a = Dynamics( name='A', aliases=['A1:=P1 * SV2', 'A2 := ARP1 + SV2', 'A3 := SV1'], state_variables=[ StateVariable('SV1', dimension=un.voltage), StateVariable('SV2', dimension=un.current)], regimes=[ Regime( 'dSV1/dt = -SV1 / P2', 'dSV2/dt = A3 / ARP2 + SV2 / P2', transitions=[On('SV1 > P3', do=[OutputEvent('emit')]), On('spikein', do=[OutputEvent('emit')])], name='R1' ), Regime(name='R2', transitions=On('(SV1 > C1) & (SV2 < P4)', to='R1')) ], analog_ports=[AnalogReceivePort('ARP1', dimension=un.current), AnalogReceivePort('ARP2', dimension=(un.resistance * un.time)), AnalogSendPort('A1', dimension=un.voltage * un.current), AnalogSendPort('A2', dimension=un.current)], parameters=[Parameter('P1', dimension=un.voltage), Parameter('P2', dimension=un.time), Parameter('P3', dimension=un.voltage), Parameter('P4', dimension=un.current)], constants=[Constant('C1', value=1.0, units=un.mV)] ) self.assertEqual( set(a.all_expressions), set(( sympify('P1 * SV2'), sympify('ARP1 + SV2'), sympify('SV1'), sympify('-SV1 / P2'), sympify('-SV1 / P2'), sympify('A3 / ARP2 + SV2 / P2'), sympify('SV1 > P3'), sympify('(SV1 > C1) & (SV2 < P4)'))), "All expressions were not extracted from component class") class TestOn(unittest.TestCase): def test_On(self): # Signature: name(trigger, do=None, to=None) # No Docstring # Test that we are correctly inferring OnEvents and OnConditions. self.assertEqual(type(On('V>0')), OnCondition) self.assertEqual(type(On('V<0')), OnCondition) self.assertEqual(type(On('(V<0) & (K>0)')), OnCondition) self.assertEqual(type(On('V==0')), OnCondition) self.assertEqual( type(On("q > 1 / (( 1 + mg_conc * eta * exp ( -1 * gamma*V)))")), OnCondition) self.assertEqual(type(On('SP0')), OnEvent) self.assertEqual(type(On('SP1')), OnEvent) # Check we can use 'do' with single and multiple values tr = On('V>0') self.assertEqual(len(list(tr.output_events)), 0) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('SP0') self.assertEqual(len(list(tr.output_events)), 0) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('V>0', do=OutputEvent('spike')) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('SP0', do=OutputEvent('spike')) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('V>0', do=[OutputEvent('spike')]) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('SP0', do=[OutputEvent('spike')]) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 0) tr = On('V>0', do=['y=2', OutputEvent('spike'), 'x=1']) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 2) tr = On('SP0', do=['y=2', OutputEvent('spike'), 'x=1']) self.assertEqual(len(list(tr.output_events)), 1) self.assertEqual(len(list(tr.state_assignments)), 2) class OnCondition_test(unittest.TestCase): def test_trigger(self): invalid_triggers = ['true(', 'V < (V+10', 'V (< V+10)', 'V (< V+10)', '1 / ( 1 + mg_conc * eta * exp(-1 * gamma*V))' '1..0' '..0'] for tr in invalid_triggers: self.assertRaises(NineMLMathParseError, OnCondition, tr) # Test Come Conditions: namespace = { "A": 10, "B": 5, "tau_r": 5, "V": 20, "Vth": -50.0, "t_spike": 1.0, "q": 11.0, "t": 0.9, "tref": 0.1 } cond_exprs = [ ["A > -B/tau_r", ("A", "B", "tau_r"), ()], ["(V > 1.0) & !(V<10.0)", ("V",), ()], ["!!(V>10)", ("V"), ()], ["!!(V>10)", ("V"), ()], ["V>exp(Vth)", ("V", "Vth"), ('exp',)], ["!(V>Vth)", ("V", "Vth"), ()], ["!(V>Vth)", ("V", "Vth"), ()], ["exp(V)>Vth", ("V", "Vth"), ("exp",)], ["true", (), ()], ["(V < (Vth+q)) & (t > t_spike)", ("t_spike", "t", "q", "Vth", "V"), ()], ["(V < (Vth+q)) | (t > t_spike)", ("t_spike", "Vth", "q", "V", "t"), ()], ["(true)", (), ()], ["!true", (), ()], ["!false", (), ()], ["t >= t_spike + tref", ("t", "t_spike", "tref"), ()], ["true & !false", (), ()] ] return_values = [ True, True, True, True, True, False, False, True, True, False, False, True, False, True, False, True ] for i, (expr, expt_vars, expt_funcs) in enumerate(cond_exprs): c = OnCondition(trigger=expr) self.assertEqual(set(c.trigger.rhs_symbol_names), set(expt_vars)) self.assertEqual(set(str(f) for f in c.trigger.rhs_funcs), set(expt_funcs)) python_func = c.trigger.rhs_as_python_func param_dict = dict([(v, namespace[v]) for v in expt_vars]) self.assertEqual(return_values[i], python_func(**param_dict)) def test_trigger_crossing_time_expr(self): self.assertEqual(Trigger('t > t_next').crossing_time_expr.rhs, sympify('t_next')) self.assertEqual(Trigger('t^2 > t_next').crossing_time_expr, None) self.assertEqual(Trigger('a < b').crossing_time_expr, None) self.assertEqual( Trigger('t > t_next || t > t_next2').crossing_time_expr.rhs, sympify('Min(t_next, t_next2)')) self.assertEqual( Trigger('t > t_next || a < b').crossing_time_expr, None) def test_make_strict(self): self.assertEqual( Trigger._make_strict( sympify('(a >= 0.5) & ~(b < (10 * c * e)) | (c <= d)')), sympify('(a > 0.5) & (b > (10 * c * e)) | (c < d)')) class OnEvent_test(unittest.TestCase): def test_Constructor(self): pass def test_src_port_name(self): self.assertRaises(NineMLUsageError, OnEvent, '1MyEvent1 ') self.assertRaises(NineMLUsageError, OnEvent, 'MyEvent1 2') self.assertRaises(NineMLUsageError, OnEvent, 'MyEvent1* ') self.assertEqual(OnEvent(' MyEvent1 ').src_port_name, 'MyEvent1') self.assertEqual(OnEvent(' MyEvent2').src_port_name, 'MyEvent2') class Regime_test(unittest.TestCase): def test_Constructor(self): pass def test_add_on_condition(self): # Signature: name(self, on_condition) # Add an OnCondition transition which leaves this regime # # If the on_condition object has not had its target regime name set in # the constructor, or by calling its ``set_target_regime_name()``, then # the target is assumed to be this regime, and will be set # appropriately. # # The source regime for this transition will be set as this regime. r = Regime(name='R1') self.assertEqual(unique_by_id(r.on_conditions), []) r.add(OnCondition('sp1>0')) self.assertEqual(len(unique_by_id(r.on_conditions)), 1) self.assertEqual(len(unique_by_id(r.on_events)), 0) self.assertEqual(len(unique_by_id(r.transitions)), 1) def test_add_on_event(self): # Signature: name(self, on_event) # Add an OnEvent transition which leaves this regime # # If the on_event object has not had its target regime name set in the # constructor, or by calling its ``set_target_regime_name()``, then the # target is assumed to be this regime, and will be set appropriately. # # The source regime for this transition will be set as this regime. # from nineml.abstraction.component.dynamics import Regime r = Regime(name='R1') self.assertEqual(unique_by_id(r.on_events), []) r.add(OnEvent('sp')) self.assertEqual(len(unique_by_id(r.on_events)), 1) self.assertEqual(len(unique_by_id(r.on_conditions)), 0) self.assertEqual(len(unique_by_id(r.transitions)), 1) def test_get_next_name(self): # Signature: name(cls) # Return the next distinct autogenerated name n1 = Regime.get_next_name() n2 = Regime.get_next_name() n3 = Regime.get_next_name() self.assertNotEqual(n1, n2) self.assertNotEqual(n2, n3) def test_name(self): self.assertRaises(NineMLUsageError, Regime, name='&Hello') self.assertRaises(NineMLUsageError, Regime, name='2Hello') self.assertEqual(Regime(name='Hello').name, 'Hello') self.assertEqual(Regime(name='Hello2').name, 'Hello2') def test_time_derivatives(self): # Signature: name # Returns the state-variable time-derivatives in this regime. # # .. note:: # # This is not guarenteed to contain the time derivatives for all # the state-variables specified in the component. If they are not # defined, they are assumed to be zero in this regime. r = Regime('dX1/dt=0', 'dX2/dt=0', name='r1') self.assertEqual( set([td.variable for td in r.time_derivatives]), set(['X1', 'X2'])) # Defining a time derivative twice: self.assertRaises( NineMLUsageError, Regime, 'dX/dt=1', 'dX/dt=2') # Assigning to a value: self.assertRaises( NineMLUsageError, Regime, 'X=1') class StateVariable_test(unittest.TestCase): def test_name(self): # Signature: name # No Docstring self.assertRaises(NineMLUsageError, StateVariable, name='&Hello') self.assertRaises(NineMLUsageError, StateVariable, name='2Hello') self.assertEqual(StateVariable(name='Hello').name, 'Hello') self.assertEqual(StateVariable(name='Hello2').name, 'Hello2') class Query_test(unittest.TestCase): def test_event_send_receive_ports(self): # Signature: name(self) # Get the ``recv`` EventPorts # from nineml.abstraction.component.componentqueryer import # ComponentClassQueryer # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=Regime( transitions=[ On('in_ev1', do=OutputEvent('ev_port1')), On('V < b', do=OutputEvent('ev_port1')), On('V < c', do=OutputEvent('ev_port2')), ] ), ) self.assertEqual(len(list(c.event_receive_ports)), 1) self.assertEqual((list(list(c.event_receive_ports))[0]).name, 'in_ev1') self.assertEqual(len(list(c.event_send_ports)), 2) self.assertEqual(set(c.event_send_port_names), set(['ev_port1', 'ev_port2'])) # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=[ Regime(name='r1', transitions=[ On('V > a', do=OutputEvent('ev_port1'), to='r2'), On('in_ev1', do=OutputEvent('ev_port2'))]), Regime(name='r2', transitions=[ On('V > a', do=OutputEvent('ev_port2'), to='r1'), On('in_ev2', do=OutputEvent('ev_port3'))]) ] ) self.assertEqual(len(list(c.event_receive_ports)), 2) self.assertEqual(set(c.event_receive_port_names), set(['in_ev1', 'in_ev2'])) self.assertEqual(len(list(c.event_send_ports)), 3) self.assertEqual(set(c.event_send_port_names), set(['ev_port1', 'ev_port2', 'ev_port3'])) # Check inference of output event ports: c = Dynamics( name='Comp1', regimes=[ Regime(name='r1', transitions=[ On('spikeinput1', do=[]), On('spikeinput2', do=[ OutputEvent('ev_port1'), OutputEvent('ev_port2')], to='r2')]), Regime(name='r2', transitions=[ On('V > a', do=OutputEvent('ev_port2')), On('spikeinput3', do=OutputEvent('ev_port3'), to='r1')]) ] ) self.assertEqual(len(list(c.event_receive_ports)), 3) self.assertEqual(set(c.event_receive_port_names), set(['spikeinput1', 'spikeinput2', 'spikeinput3'])) self.assertEqual(len(list(c.event_send_ports)), 3) self.assertEqual(set(c.event_send_port_names), set(['ev_port1', 'ev_port2', 'ev_port3'])) def test_ports(self): # Signature: name # Return an iterator over all the port (Event & Analog) in the # component # from nineml.abstraction.component.componentqueryer import # ComponentClassQueryer c = Dynamics( name='Comp1', regimes=[ Regime(name='r1', transitions=[ On('spikeinput1', do=[]), On('spikeinput2', do=OutputEvent('ev_port2'), to='r2')]), Regime(name='r2', transitions=[ On('V > a', do=OutputEvent('ev_port2')), On('spikeinput3', do=OutputEvent('ev_port3'), to='r1')]) ], aliases=['A1:=0', 'C:=0'], analog_ports=[AnalogSendPort('A1'), AnalogReceivePort('B'), AnalogSendPort('C')] ) ports = list(list(c.ports)) port_names = [p.name for p in ports] self.assertEqual(len(port_names), 8) self.assertEqual(set(port_names), set(['A1', 'B', 'C', 'spikeinput1', 'spikeinput2', 'spikeinput3', 'ev_port2', 'ev_port3']) ) def test_regime(self): # Signature: name(self, name=None) # Find a regime in the component by name # from nineml.abstraction.component.componentqueryer import # ComponentClassQueryer c = Dynamics(name='cl', regimes=[ Regime('dX/dt=1/t', name='r1', transitions=On('X>X1', do=['X=X0'], to='r2')), Regime('dX/dt=1/t', name='r2', transitions=On('X>X1', do=['X=X0'], to='r3')), Regime('dX/dt=1/t', name='r3', transitions=On('X>X1', do=['X=X0'], to='r4')), Regime('dX/dt=1/t', name='r4', transitions=On('X>X1', do=['X=X0'], to='r1'))]) self.assertEqual(c.regime(name='r1').name, 'r1') self.assertEqual(c.regime(name='r2').name, 'r2') self.assertEqual(c.regime(name='r3').name, 'r3') self.assertEqual(c.regime(name='r4').name, 'r4')
bsd-3-clause
kkurzhal/space-shooter
Assets/Scripts/DestroyByContact.cs
1125
using UnityEngine; using System.Collections; public class DestroyByContact : MonoBehaviour { public GameObject explosion; public GameObject playerExplosion; public int scoreValue; private GameController gameController; void Start() { GameObject gameControllerObject = GameObject.FindWithTag("GameController"); if(gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController>(); } if(gameController == null) { Debug.Log("Cannot find 'GameController script"); } } void OnTriggerEnter(Collider other) { if (other.tag != "Boundary") { Instantiate(explosion, transform.position, transform.rotation); if (other.tag == "Player") { Instantiate(playerExplosion, other.transform.position, other.transform.rotation); gameController.endGame(); } Destroy(other.gameObject); Destroy(gameObject); gameController.AddScore(scoreValue); } } }
bsd-3-clause
Caleydo/caleydo
org.caleydo.data.importer/src/org/caleydo/data/importer/tcga/FirehoseProvider.java
19060
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license ******************************************************************************/ package org.caleydo.data.importer.tcga; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.archivers.ArchiveEntry; //import net.java.truevfs.access.TFile; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.lang.SystemUtils; import org.caleydo.core.util.collection.Pair; import org.caleydo.data.importer.tcga.model.TumorType; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import com.google.common.io.Closeables; public final class FirehoseProvider { private static final Logger log = Logger.getLogger(FirehoseProvider.class.getName()); private static final int LEVEL = 4; private static final int LEVEL3 = 3; private final TumorType tumor; private final String tumorSample; private final Date analysisRun; private final Date dataRun; private final File tmpAnalysisDir; private final File tmpDataDir; private final Settings settings; private final Calendar relevantDate; FirehoseProvider(TumorType tumor, Date analysisRun, Date dataRun, Settings settings) { this.tumor = tumor; this.relevantDate = Calendar.getInstance(); this.relevantDate.setTime(analysisRun); this.tumorSample = guessTumorSample(tumor, this.relevantDate, settings); this.analysisRun = analysisRun; this.dataRun = dataRun; this.settings = settings; String tmpDir = settings.getTemporaryDirectory(); this.tmpAnalysisDir = createTempDirectory(tmpDir, analysisRun, tumor.getName()); this.tmpDataDir = createTempDirectory(tmpDir, dataRun, tumor.getName()); } /** * logic determining the tumor sample based on the analysis run * * @param tumor * @param date * @return */ private static String guessTumorSample(TumorType tumor, Calendar cal, Settings settings) { if (settings.isAwgRun()) return tumor.toString(); if (cal.get(Calendar.YEAR) >= 2013 && tumor.toString().equalsIgnoreCase("SKCM")) return tumor + "-TM"; if (cal.get(Calendar.YEAR) >= 2013 && tumor.toString().equalsIgnoreCase("LAML")) return tumor + "-TB"; if (cal.get(Calendar.YEAR) >= 2013) return tumor + "-TP"; return tumor.toString(); } /** * @return */ public boolean is2014Run() { return relevantDate.get(Calendar.YEAR) >= 2014; } public boolean isPost2015() { return relevantDate.get(Calendar.YEAR) >= 2015; } public boolean isPost2015908() { return relevantDate.get(Calendar.YEAR) >= 2015 && relevantDate.get(Calendar.MONTH) >= Calendar.AUGUST; } public boolean isPost20140416() { return relevantDate.get(Calendar.YEAR) >= 2014 && relevantDate.get(Calendar.MONTH) >= Calendar.APRIL; } private String getFileName(String suffix) { return tumorSample + suffix; } private File createTempDirectory(String tmpOutputDirectory, Date run, String tumor) { String runId; if (run == null) runId = "unknown"; else { runId = Settings.formatClean(run); } return new File(tmpOutputDirectory + runId + SystemUtils.FILE_SEPARATOR + tumor + SystemUtils.FILE_SEPARATOR); } private Pair<TCGAFileInfo, Boolean> findStandardSampledClusteredFile(EDataSetType type) { return Pair.make(extractAnalysisRunFile(".expclu.gct", type.getTCGAAbbr() + "_Clustering_CNMF", LEVEL), false); } public Pair<TCGAFileInfo, Boolean> findRPPAMatrixFile(boolean loadFullGenes) { return findStandardSampledClusteredFile(EDataSetType.RPPA); } public Pair<TCGAFileInfo, Boolean> findMethylationMatrixFile(boolean loadFullGenes) { return findStandardSampledClusteredFile(EDataSetType.methylation); } public Pair<TCGAFileInfo, Boolean> findmRNAMatrixFile(boolean loadFullGenes) { if (loadFullGenes) { TCGAFileInfo r; if (isPost20140416()) { r = extractDataRunFile(".medianexp.txt", "mRNA_Preprocess_Median", isPost2015() ? LEVEL3 : LEVEL); } else { r = extractAnalysisRunFile(getFileName(".medianexp.txt"), "mRNA_Preprocess_Median", LEVEL); } if (r != null) return Pair.make(r, true); } return findStandardSampledClusteredFile(EDataSetType.mRNA); } public Pair<TCGAFileInfo, Boolean> findmRNAseqMatrixFile(boolean loadFullGenes) { if (loadFullGenes) { TCGAFileInfo r = extractDataRunFile(".uncv2.mRNAseq_RSEM_normalized_log2.txt", "mRNAseq_Preprocess", isPost20140416() ? LEVEL3 : LEVEL, isPost2015908() ? 1 : 0); if (r == null) r = extractDataRunFile(".uncv1.mRNAseq_RPKM_log2.txt", "mRNAseq_Preprocess", isPost20140416() ? LEVEL3 : LEVEL); if (r == null) r = extractDataRunFile(".mRNAseq_RPKM_log2.txt", "mRNAseq_Preprocess", isPost20140416() ? 3 : LEVEL); if (r != null) { r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.mRNAseq)); return Pair.make(r, true); } } return findStandardSampledClusteredFile(EDataSetType.mRNAseq); } private TCGAFileInfo filterColumns(TCGAFileInfo full, Pair<TCGAFileInfo, Boolean> sampled) { File in = full.getFile(); File out = new File(in.getParentFile(), "F" + in.getName()); TCGAFileInfo r = new TCGAFileInfo(out, full.getArchiveURL(), full.getSourceFileName()); if (out.exists() && !settings.isCleanCache()) return r; assert full != null; if (sampled == null || sampled.getFirst() == null) { log.severe("can't filter the full gene file: " + in + " - sampled not found"); return full; } // full: 1row, 2col // sampled: 3row, 3col Set<String> good = readGoodSamples(sampled.getFirst().getFile()); if (good == null) return full; try (BufferedReader fin = new BufferedReader(new FileReader(in)); PrintWriter w = new PrintWriter(out)) { String[] header = fin.readLine().split("\t"); BitSet bad = filterCols(header, good); { StringBuilder b = new StringBuilder(); for (int i = bad.nextSetBit(0); i >= 0; i = bad.nextSetBit(i + 1)) b.append(' ').append(header[i]); log.warning("remove bad samples of " + in + ":" + b); } w.append(header[0]); for (int i = 1; i < header.length; ++i) { if (bad.get(i)) continue; w.append('\t').append(header[i]); } String line; while ((line = fin.readLine()) != null) { w.println(); int t = line.indexOf('\t'); w.append(line.subSequence(0, t)); int prev = t; int i = 1; for (t = line.indexOf('\t', t + 1); t >= 0; t = line.indexOf('\t', t + 1), ++i) { if (!bad.get(i)) w.append(line.subSequence(prev, t)); prev = t; } if (!bad.get(i)) w.append(line.subSequence(prev, line.length())); } } catch (IOException e) { log.log(Level.SEVERE, "can't filter full file: " + in, e); } return r; } /** * @param header * @param good * @return */ private static BitSet filterCols(String[] header, Set<String> good) { BitSet r = new BitSet(header.length); for (int i = 0; i < header.length; ++i) if (!good.contains(header[i])) r.set(i); return r; } private static Set<String> readGoodSamples(File file) { // sampled: 3row, >=3col try (BufferedReader r = new BufferedReader(new FileReader(file))) { r.readLine(); r.readLine(); String line = r.readLine(); String[] samples = line.split("\t"); return ImmutableSet.copyOf(Arrays.copyOfRange(samples, 2, samples.length)); } catch (IOException e) { log.log(Level.SEVERE, "can't read sample header from: " + file, e); } return null; } public Pair<TCGAFileInfo, Boolean> findmicroRNAMatrixFile(boolean loadFullGenes) { if (loadFullGenes) { TCGAFileInfo r = extractDataRunFile(".miR_expression.txt", "miR_Preprocess", isPost20140416() ? 3 : LEVEL); if (r != null) { r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.microRNA)); return Pair.make(r, true); } } return findStandardSampledClusteredFile(EDataSetType.microRNA); } public Pair<TCGAFileInfo, Boolean> findmicroRNAseqMatrixFile(boolean loadFullGenes) { if (loadFullGenes) { TCGAFileInfo r = extractAnalysisRunFile(getFileName(".uncv2.miRseq_RSEM_normalized_log2.txt"), "miRseq_Preprocess", isPost20140416() ? 3 : LEVEL); if (r == null) r = extractAnalysisRunFile(getFileName(".miRseq_RPKM_log2.txt"), "miRseq_Preprocess", LEVEL); if (r != null) { r = filterColumns(r, findStandardSampledClusteredFile(EDataSetType.microRNA)); return Pair.make(r, true); } } return findStandardSampledClusteredFile(EDataSetType.microRNAseq); } public TCGAFileInfo findHiearchicalGrouping(EDataSetType type) { return extractAnalysisRunFile(isPost2015() ? "clus.membership.txt" : getFileName(".allclusters.txt"), type.getTCGAAbbr() + "_Clustering_Consensus" + (isPost2015() ? "_Plus" : ""), LEVEL); } public TCGAFileInfo findCNMFGroupingFile(EDataSetType type) { return extractAnalysisRunFile(".membership.txt", type.getTCGAAbbr() + "_Clustering_CNMF", LEVEL); } public TCGAFileInfo findCopyNumberFile() { return extractAnalysisRunFile("all_thresholded.by_genes.txt", "CopyNumber_Gistic2", LEVEL); } public TCGAFileInfo findClinicalDataFile() { return extractDataRunFile(".clin.merged.txt", "Merge_Clinical", 1); } public TCGAFileInfo findMutSigReport() { return extractAnalysisRunFile(getFileName(".sig_genes.txt"), "MutSigNozzleReportCV", LEVEL); } public Pair<TCGAFileInfo, Integer> findMutationFile() { int startColumn = 8; TCGAFileInfo mutationFile = null; if (relevantDate.get(Calendar.YEAR) < 2013) { // test only for the <= 2012 mutationFile = extractAnalysisRunFile(getFileName(".per_gene.mutation_counts.txt"), "Mutation_Significance", LEVEL); if (mutationFile == null) mutationFile = extractAnalysisRunFile(getFileName(".per_gene.mutation_counts.txt"), "MutSigRun2.0", LEVEL); } if (mutationFile == null) { // TODO always the -TP version TCGAFileInfo maf = null; if (!this.settings.isAwgRun()) { maf = extractAnalysisRunFile(tumor + "-TP.final_analysis_set.maf", "MutSigNozzleReport2.0", LEVEL); } else { maf = extractAnalysisRunFile(tumor + ".final_analysis_set.maf", "MutSigNozzleReport2.0", LEVEL); } if (maf != null) { return Pair.make( new TCGAFileInfo(parseMAF(maf.getFile()), maf.getArchiveURL(), maf.getSourceFileName()), 1); } } return Pair.make(mutationFile, startColumn); } /** * @return */ public String getReportURL() { return settings.getReportUrl(analysisRun, tumor); } private TCGAFileInfo extractAnalysisRunFile(String fileName, String pipelineName, int level) { return extractFile(fileName, pipelineName, level, true, false, 0); } private TCGAFileInfo extractDataRunFile(String fileName, String pipelineName, int level, int flag) { return extractFile(fileName, pipelineName, level, false, true, flag); } private TCGAFileInfo extractDataRunFile(String fileName, String pipelineName, int level) { return extractFile(fileName, pipelineName, level, false, true, 0); } private TCGAFileInfo extractFile(String fileName, String pipelineName, int level, boolean isAnalysisRun, boolean hasTumor, int flag) { Date id = isAnalysisRun ? analysisRun : dataRun; String label = "unknown"; // extract file to temp directory and return path to file URL url; try { if (isAnalysisRun) url = settings.getAnalysisURL(id, tumor, tumorSample, pipelineName, level); else url = settings.getDataURL(id, tumor, tumorSample, pipelineName, level, flag); String urlString = url.getPath(); label = urlString.substring(urlString.lastIndexOf('/') + 1, urlString.length()); File outputDir = new File(isAnalysisRun ? tmpAnalysisDir : tmpDataDir, label); outputDir.mkdirs(); return extractFileFromTarGzArchive(url, fileName, outputDir, hasTumor); } catch (MalformedURLException e) { log.log(Level.SEVERE, "invalid url generated from: " + id + " " + tumor + " " + tumorSample + " " + pipelineName + " " + level); return null; } } private TCGAFileInfo extractFileFromTarGzArchive(URL inUrl, String fileToExtract, File outputDirectory, boolean hasTumor) { log.info(inUrl + " download and extract: " + fileToExtract); File targetFile = new File(outputDirectory, fileToExtract); // use cached if (targetFile.exists() && !settings.isCleanCache()) { log.fine(inUrl + " cache hit"); return new TCGAFileInfo(targetFile, inUrl, targetFile.getName()); } File notFound = new File(outputDirectory, fileToExtract + "-notfound"); if (notFound.exists() && !settings.isCleanCache()) { log.warning(inUrl + " marked as not found"); return null; } String alternativeName = fileToExtract; if (hasTumor) { alternativeName = "/" + tumor.getBaseName() + fileToExtract; fileToExtract = "/" + tumor + fileToExtract; } TarArchiveInputStream tarIn = null; OutputStream out = null; try { // copy and buffer the whole file InputStream in = new BufferedInputStream(inUrl.openStream()); // CASE 1 we use the truevfs library // String tmpFile = targetFile.getAbsolutePath() + ".tmp.tar.gz"; // out = new BufferedOutputStream(new FileOutputStream(tmpFile)); // ByteStreams.copy(in, out); // out.close(); // TFile archive = new TFile(tmpFile); // TFile act = null; // outer: for (TFile member : archive.listFiles()) { // for (TFile mm : member.listFiles()) { // String name = member.getName() + '/' + mm.getName(); // System.out.println(name); // if (name.endsWith(fileToExtract) || name.endsWith(alternativeName)) { // act = mm; // break outer; // } // } // } // // if (act != null) // act.cp(targetFile); // if (act == null) // no entry found // throw new FileNotFoundException("no entry named: " + fileToExtract + " found"); // CASE 2 we use apache commons tarIn = new TarArchiveInputStream(new GZIPInputStream(in)); // search the correct entry ArchiveEntry act = tarIn.getNextEntry(); while (act != null && !act.getName().endsWith(fileToExtract) && !act.getName().endsWith(alternativeName)) { System.out.println(act.getName()); act = tarIn.getNextEntry(); } if (act == null) // no entry found throw new FileNotFoundException("no entry named: " + fileToExtract + " found"); byte[] buf = new byte[4096]; int n; targetFile.getParentFile().mkdirs(); // use a temporary file to recognize if we have aborted between run String tmpFile = targetFile.getAbsolutePath() + ".tmp"; out = new BufferedOutputStream(new FileOutputStream(tmpFile)); while ((n = tarIn.read(buf, 0, 4096)) > -1) out.write(buf, 0, n); out.close(); Files.move(new File(tmpFile).toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); log.info(inUrl + " extracted " + fileToExtract); return new TCGAFileInfo(targetFile, inUrl, targetFile.getName()); } catch (FileNotFoundException e) { log.log(Level.WARNING, inUrl + " can't extract" + fileToExtract + ": file not found", e); // file was not found, create a marker to remember this for quicker checks notFound.getParentFile().mkdirs(); try { notFound.createNewFile(); } catch (IOException e1) { log.log(Level.WARNING, inUrl + " can't create not-found marker", e); } return null; } catch (Exception e) { log.log(Level.SEVERE, inUrl + " can't extract" + fileToExtract + ": " + e.getMessage(), e); return null; } finally { Closeables.closeQuietly(tarIn); Closeables.closeQuietly(out); } } private static File parseMAF(File maf) { File out = new File(maf.getParentFile(), "P" + maf.getName()); if (out.exists()) return out; log.fine(maf.getAbsolutePath() + " parsing maf file"); final String TAB = "\t"; CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); decoder.onMalformedInput(CodingErrorAction.IGNORE); try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(maf.toPath()), decoder))) { List<String> header = Arrays.asList(reader.readLine().split(TAB)); int geneIndex = header.indexOf("Hugo_Symbol"); int sampleIndex = header.indexOf("Tumor_Sample_Barcode"); // gene x sample x mutated Table<String, String, Boolean> mutated = TreeBasedTable.create(); String line = null; // int i = 1; while ((line = reader.readLine()) != null) { String[] columns = line.split(TAB); mutated.put(columns[geneIndex], columns[sampleIndex], Boolean.TRUE); // System.out.println(i++); } File tmp = new File(out.getParentFile(), out.getName() + ".tmp"); PrintWriter w = new PrintWriter(tmp); w.append("Hugo_Symbol"); List<String> cols = new ArrayList<>(mutated.columnKeySet()); for (String sample : cols) { w.append(TAB).append(sample); } w.println(); Set<String> rows = mutated.rowKeySet(); for (String gene : rows) { w.append(gene); for (String sample : cols) { w.append(TAB).append(mutated.contains(gene, sample) ? '1' : '0'); } w.println(); } w.close(); Files.move(tmp.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING); log.fine(maf.getAbsolutePath() + " parsed maf file stats: " + mutated.size() + " " + rows.size() + " " + cols.size()); return out; } catch (IOException e) { log.log(Level.SEVERE, maf.getAbsolutePath() + " maf parsing error: " + e.getMessage(), e); } return null; } public static void main(String[] args) { File file = new File( "/home/alexsb/Dropbox/Caleydo/data/ccle/CCLE_hybrid_capture1650_hg19_NoCommonSNPs_CDS_2012.05.07.maf"); file = parseMAF(file); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("FirehoseProvider["); builder.append(tumor); builder.append("/"); builder.append(tumorSample); builder.append("@"); builder.append(Settings.format(analysisRun)); builder.append(","); builder.append(Settings.format(dataRun)); builder.append("]"); return builder.toString(); } }
bsd-3-clause
e1528532/libelektra
src/tools/qt-gui/qml/TooltipCreator.js
1067
.pragma library var tooltip = null function create(name, value, meta, defaultMargins, x, y, parent) { var component = Qt.createComponent("ToolTip.qml") var properties = {} properties.name = name properties.value = value properties.meta = meta properties.defaultMargins = defaultMargins properties.parentWidth = parent.width properties.parentHeight = parent.height tooltip = component.createObject(parent, properties); if (tooltip === null) console.error("error creating tooltip: " + component.errorString()) tooltip.x = x tooltip.y = y return tooltip } function createHelp(helpText, defaultMargins, x, y, parent) { var component = Qt.createComponent("Help.qml") var properties = {} properties.helpText = helpText properties.defaultMargins = defaultMargins tooltip = component.createObject(parent, properties); if (tooltip === null) console.error("error creating tooltip: " + component.errorString()) tooltip.x = x tooltip.y = y return tooltip } function destroy() { if (tooltip){ tooltip.destroy() tooltip = null } }
bsd-3-clause
NServiceKit/NServiceKit.OrmLite
src/NServiceKit.OrmLite.MySql.Tests/DateTimeColumnTest.cs
3031
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using NServiceKit.DataAnnotations; using NServiceKit.DesignPatterns.Model; namespace NServiceKit.OrmLite.MySql.Tests { /// <summary>A date time column test.</summary> [TestFixture] public class DateTimeColumnTest : OrmLiteTestBase { /// <summary>Can create table containing date time column.</summary> [Test] public void Can_create_table_containing_DateTime_column() { using (var db = OpenDbConnection()) { db.CreateTable<Analyze>(true); } } /// <summary>Can store date time value.</summary> [Test] public void Can_store_DateTime_Value() { using (var db = OpenDbConnection()) { db.CreateTable<Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); } } /// <summary>Can store and retrieve date time value.</summary> [Test] public void Can_store_and_retrieve_DateTime_Value() { using (var db = OpenDbConnection()) { db.CreateTable<Analyze>(true); var obj = new Analyze { Id = 1, Date = DateTime.Now, Url = "http://www.google.com" }; db.Save(obj); var id = (int)db.GetLastInsertId(); var target = db.QueryById<Analyze>(id); Assert.IsNotNull(target); Assert.AreEqual(id, target.Id); Assert.AreEqual(obj.Date.ToString("yyyy-MM-dd HH:mm:ss"), target.Date.ToString("yyyy-MM-dd HH:mm:ss")); Assert.AreEqual(obj.Url, target.Url); } } /// <summary> /// Provided by RyogoNA in issue #38 /// https://github.com/ServiceStack/ServiceStack.OrmLite/issues/38#issuecomment-4625178. /// </summary> [Alias("Analyzes")] public class Analyze : IHasId<int> { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> [AutoIncrement] [PrimaryKey] public int Id { get; set; } /// <summary>Gets or sets the Date/Time of the date.</summary> /// <value>The date.</value> [Alias("AnalyzeDate")] public DateTime Date { get; set; } /// <summary>Gets or sets URL of the document.</summary> /// <value>The URL.</value> public string Url { get; set; } } } }
bsd-3-clause
stan-dev/math
test/unit/math/opencl/rev/double_exponential_lpdf_test.cpp
6853
#ifdef STAN_OPENCL #include <stan/math/opencl/rev.hpp> #include <stan/math.hpp> #include <gtest/gtest.h> #include <test/unit/math/opencl/util.hpp> #include <vector> TEST(ProbDistributionsDoubleExponential, error_checking) { int N = 3; Eigen::VectorXd y(N); y << -0.3, 0.8, 1.5; Eigen::VectorXd y_size(N - 1); y_size << 0.3, 0.8; Eigen::VectorXd y_value(N); y_value << 0.3, INFINITY, 0.5; Eigen::VectorXd mu(N); mu << 0.3, 0.8, -1.7; Eigen::VectorXd mu_size(N - 1); mu_size << 0.3, 0.8; Eigen::VectorXd mu_value(N); mu_value << 0.3, INFINITY, 0.5; Eigen::VectorXd sigma(N); sigma << 0.3, 0.8, 4.2; Eigen::VectorXd sigma_size(N - 1); sigma_size << 0.3, 0.8; Eigen::VectorXd sigma_value(N); sigma_value << 0.3, -0.8, 0.5; stan::math::matrix_cl<double> y_cl(y); stan::math::matrix_cl<double> y_size_cl(y_size); stan::math::matrix_cl<double> y_value_cl(y_value); stan::math::matrix_cl<double> mu_cl(mu); stan::math::matrix_cl<double> mu_size_cl(mu_size); stan::math::matrix_cl<double> mu_value_cl(mu_value); stan::math::matrix_cl<double> sigma_cl(sigma); stan::math::matrix_cl<double> sigma_size_cl(sigma_size); stan::math::matrix_cl<double> sigma_value_cl(sigma_value); EXPECT_NO_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_cl)); EXPECT_THROW(stan::math::double_exponential_lpdf(y_size_cl, mu_cl, sigma_cl), std::invalid_argument); EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_size_cl, sigma_cl), std::invalid_argument); EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_size_cl), std::invalid_argument); EXPECT_THROW(stan::math::double_exponential_lpdf(y_value_cl, mu_cl, sigma_cl), std::domain_error); EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_value_cl, sigma_cl), std::domain_error); EXPECT_THROW(stan::math::double_exponential_lpdf(y_cl, mu_cl, sigma_value_cl), std::domain_error); } auto double_exponential_lpdf_functor = [](const auto& n, const auto& mu, const auto& sigma) { return stan::math::double_exponential_lpdf(n, mu, sigma); }; auto double_exponential_lpdf_functor_propto = [](const auto& n, const auto& mu, const auto& sigma) { return stan::math::double_exponential_lpdf<true>(n, mu, sigma); }; TEST(ProbDistributionsDoubleExponential, opencl_matches_cpu_small) { int N = 3; Eigen::VectorXd y(N); y << -0.3, 0.8, 1.5; Eigen::VectorXd mu(N); mu << 0.3, 0.8, -1.7; Eigen::VectorXd sigma(N); sigma << 0.3, 0.8, 4.2; stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor, y, mu, sigma); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor_propto, y, mu, sigma); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor, y.transpose().eval(), mu.transpose().eval(), sigma.transpose().eval()); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor_propto, y.transpose().eval(), mu.transpose().eval(), sigma.transpose().eval()); } TEST(ProbDistributionsDoubleExponential, opencl_broadcast_y) { int N = 3; double y_scal = -2.3; Eigen::VectorXd mu(N); mu << 0.3, 0.8, -1.7; Eigen::VectorXd sigma(N); sigma << 0.3, 0.8, 4.2; stan::math::test::test_opencl_broadcasting_prim_rev<0>( double_exponential_lpdf_functor, y_scal, mu, sigma); stan::math::test::test_opencl_broadcasting_prim_rev<0>( double_exponential_lpdf_functor_propto, y_scal, mu, sigma); stan::math::test::test_opencl_broadcasting_prim_rev<0>( double_exponential_lpdf_functor, y_scal, mu.transpose().eval(), sigma); stan::math::test::test_opencl_broadcasting_prim_rev<0>( double_exponential_lpdf_functor_propto, y_scal, mu, sigma.transpose().eval()); } TEST(ProbDistributionsDoubleExponential, opencl_broadcast_mu) { int N = 3; Eigen::VectorXd y(N); y << 0.3, 0.8, -1.7; double mu_scal = -2.3; Eigen::VectorXd sigma(N); sigma << 0.3, 0.8, 4.2; stan::math::test::test_opencl_broadcasting_prim_rev<1>( double_exponential_lpdf_functor, y, mu_scal, sigma); stan::math::test::test_opencl_broadcasting_prim_rev<1>( double_exponential_lpdf_functor_propto, y, mu_scal, sigma); stan::math::test::test_opencl_broadcasting_prim_rev<1>( double_exponential_lpdf_functor, y.transpose().eval(), mu_scal, sigma); stan::math::test::test_opencl_broadcasting_prim_rev<1>( double_exponential_lpdf_functor_propto, y, mu_scal, sigma.transpose().eval()); } TEST(ProbDistributionsDoubleExponential, opencl_broadcast_sigma) { int N = 3; Eigen::VectorXd y(N); y << 0.3, 0.8, -1.7; Eigen::VectorXd mu(N); mu << 0.3, 0.8, 4.2; double sigma_scal = 2.3; stan::math::test::test_opencl_broadcasting_prim_rev<2>( double_exponential_lpdf_functor, y, mu, sigma_scal); stan::math::test::test_opencl_broadcasting_prim_rev<2>( double_exponential_lpdf_functor_propto, y, mu, sigma_scal); stan::math::test::test_opencl_broadcasting_prim_rev<2>( double_exponential_lpdf_functor, y.transpose().eval(), mu, sigma_scal); stan::math::test::test_opencl_broadcasting_prim_rev<2>( double_exponential_lpdf_functor_propto, y, mu.transpose().eval(), sigma_scal); } TEST(ProbDistributionsDoubleExponential, opencl_matches_cpu_big) { int N = 153; Eigen::Matrix<double, Eigen::Dynamic, 1> y = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1); Eigen::Matrix<double, Eigen::Dynamic, 1> mu = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1); Eigen::Matrix<double, Eigen::Dynamic, 1> sigma = Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1).abs(); stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor, y, mu, sigma); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor_propto, y, mu, sigma); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor, y.transpose().eval(), mu.transpose().eval(), sigma.transpose().eval()); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor_propto, y.transpose().eval(), mu.transpose().eval(), sigma.transpose().eval()); } TEST(ProbDistributionsDoubleExponential, opencl_y_mu_scalar) { int N = 3; double y = -0.3; double mu = 0.8; Eigen::VectorXd sigma(N); sigma << 0.3, 0.8, 4.2; stan::math::test::compare_cpu_opencl_prim_rev(double_exponential_lpdf_functor, y, mu, sigma); stan::math::test::compare_cpu_opencl_prim_rev( double_exponential_lpdf_functor_propto, y, mu, sigma); } #endif
bsd-3-clause
dharple/detox
bin/generate-builtin.sh
526
#!/usr/bin/env bash # # Generate src/builtin_table.c # PROJECT_ROOT=$(dirname "$(dirname "$(realpath "$0")")") cd "$PROJECT_ROOT" || exit SRCDIR=$PROJECT_ROOT/src GENERATE=$SRCDIR/generate-builtin-table if [ ! -x "$GENERATE" ] ; then echo "please build $GENERATE first" exit 1 fi cp "$SRCDIR"/builtin_table.c.in "$SRCDIR"/builtin_table.c for TABLE in safe iso8859_1 unicode cp1252 ; do echo "process builtin $TABLE" $GENERATE "$PROJECT_ROOT"/table/$TABLE.tbl | sed -e"s/NEW/$TABLE/" >> "$SRCDIR"/builtin_table.c done
bsd-3-clause
nordsoftware/yii2-account
tests/codeception/acceptance/02-LoginCept.php
235
<?php $I = new AcceptanceTester\AccountSteps($scenario); $I->wantTo('log in using an existing account and see the result'); $I->amOnPage(\LoginPage::$URL); $I->login('demo', 'demo1234'); $I->dontSee('Incorrect username or password.');
bsd-3-clause
ARCCN/hcprobe
src/Network/Openflow/Ethernet/IPv4.hs
1878
{-# LANGUAGE BangPatterns #-} module Network.Openflow.Ethernet.IPv4 (IPv4Flag(..), IPv4(..), putIPv4Pkt) where import Network.Openflow.Ethernet.Types import Network.Openflow.Misc import Data.Word -- import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import Network.Openflow.StrictPut import Data.Bits import System.IO.Unsafe data IPv4Flag = DF | MF | Res deriving (Eq, Ord, Show, Read) instance Enum IPv4Flag where fromEnum DF = 4 fromEnum MF = 2 fromEnum Res = 1 toEnum _ = error "method is not supported yet" class IPv4 a where ipHeaderLen :: a -> Word8 ipVersion :: a -> Word8 ipTOS :: a -> Word8 ipID :: a -> Word16 ipFlags :: a -> Word8 ipFragOffset :: a -> Word16 ipTTL :: a -> Word8 ipProto :: a -> Word8 ipSrc :: a -> IPv4Addr ipDst :: a -> IPv4Addr ipPutPayload :: a -> PutM () putIPv4Pkt :: IPv4 a => a -> PutM () putIPv4Pkt x = do start <- marker putWord8 lenIhl putWord8 tos totLen <- delayedWord16be putWord16be ipId putWord16be flagsOff putWord8 ttl putWord8 proto acrc <- delayedWord16be putIP ipS putIP ipD hlen <- distance start ipPutPayload x undelay totLen . Word16be . fromIntegral =<< distance start undelay acrc (Word16be $ csum16' (unsafeDupablePerformIO $ BS.unsafePackAddressLen hlen (toAddr start))) where lenIhl = (ihl .&. 0xF) .|. (ver `shiftL` 4 .&. 0xF0) ihl = ipHeaderLen x ver = ipVersion x tos = ipTOS x ipId = ipID x flagsOff = (off .&. 0x1FFF) .|. ((fromIntegral flags) `shiftL` 13) flags = ipFlags x -- totLen = fromIntegral $ 4*(ipHeaderLen x) + fromIntegral (BS.length body) off = ipFragOffset x ttl = ipTTL x proto = ipProto x ipS = ipSrc x ipD = ipDst x
bsd-3-clause
jneslen/matrix42
application/logs/2012/05/21.php
7013
<?php defined('SYSPATH') or die('No direct script access.'); ?> 2012-05-21 08:47:09 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ] 2012-05-21 08:47:09 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ] -- #0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #1 {main} 2012-05-21 15:44:38 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] 2012-05-21 15:44:38 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] -- #0 /Volumes/Files/Sites/darth/bane/system/classes/kohana/cookie.php(115): Kohana_Cookie::salt('campaign_code', '200') #1 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::set('campaign_code', '200') #2 [internal function]: Controller_Public_Solutions->before() #3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions)) #4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request)) #5 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request)) #6 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #7 {main} 2012-05-21 15:44:43 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] 2012-05-21 15:44:43 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] -- #0 /Volumes/Files/Sites/darth/bane/system/classes/kohana/cookie.php(115): Kohana_Cookie::salt('campaign_code', '200') #1 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::set('campaign_code', '200') #2 [internal function]: Controller_Public_Solutions->before() #3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions)) #4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request)) #5 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request)) #6 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #7 {main} 2012-05-21 15:46:01 --- ERROR: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] 2012-05-21 15:46:01 --- STRACE: Kohana_Exception [ 0 ]: A valid cookie salt is required. Please set Cookie::$salt. ~ SYSPATH/classes/kohana/cookie.php [ 152 ] -- #0 /Volumes/Files/Sites/darth/bane/application/classes/controller/public/solutions.php(7): Kohana_Cookie::salt('campaign_code', '200') #1 [internal function]: Controller_Public_Solutions->before() #2 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client/internal.php(103): ReflectionMethod->invoke(Object(Controller_Public_Solutions)) #3 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request/client.php(64): Kohana_Request_Client_Internal->execute_request(Object(Request)) #4 /Volumes/Files/Sites/darth/bane/system/classes/kohana/request.php(1138): Kohana_Request_Client->execute(Object(Request)) #5 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #6 {main} 2012-05-21 23:27:16 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ] 2012-05-21 23:27:16 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: favicon.ico ~ SYSPATH/classes/kohana/request.php [ 1126 ] -- #0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #1 {main} 2012-05-21 23:27:47 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ] 2012-05-21 23:27:47 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ] -- #0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #1 {main} 2012-05-21 23:35:43 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] 2012-05-21 23:35:43 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] -- #0 [internal function]: Kohana_Core::shutdown_handler() #1 {main} 2012-05-21 23:36:07 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] 2012-05-21 23:36:07 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] -- #0 [internal function]: Kohana_Core::shutdown_handler() #1 {main} 2012-05-21 23:36:14 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] 2012-05-21 23:36:14 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] -- #0 [internal function]: Kohana_Core::shutdown_handler() #1 {main} 2012-05-21 23:36:18 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] 2012-05-21 23:36:18 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] -- #0 [internal function]: Kohana_Core::shutdown_handler() #1 {main} 2012-05-21 23:36:22 --- ERROR: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] 2012-05-21 23:36:22 --- STRACE: ErrorException [ 1 ]: Call to a member function set() on a non-object ~ APPPATH/classes/controller/admin/leads.php [ 171 ] -- #0 [internal function]: Kohana_Core::shutdown_handler() #1 {main} 2012-05-21 23:37:28 --- ERROR: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ] 2012-05-21 23:37:28 --- STRACE: HTTP_Exception_404 [ 404 ]: Unable to find a route to match the URI: assets/js/plugins/themes/apple/style.css ~ SYSPATH/classes/kohana/request.php [ 1126 ] -- #0 /Volumes/Files/Sites/darth/bane/index.php(103): Kohana_Request->execute() #1 {main}
bsd-3-clause
Junaid-Farid/staylance-new
frontend/views/travellerslanguages/update.php
3419
<div class="container"> <?php use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\TravellerPhoto */ $this->title = Yii::t('app', 'Update Traveller Languages'); ?> <div class="traveller-photo-create"> <div class="col-md-11 col-md-offset-1"> <ul class="traveller-steps"> <li id="active-breadcrumbs">Account Info</li> <li id="active-breadcrumbs">Profile</li> <li id="active-breadcrumbs">About You</li> <li>Gallery</li> <li>Get Verified</li> </ul> </div> <div class="col-md-10 col-md-offset-1"> <div class="travellers-form"> <div class="row"> <div class="col-lg-8"> <h1 class="Step-title">About You > Languages </h1> <?= $this->render('_form', [ 'model' => $model, 'traveller_id' => $traveller_id, 'Languages' => $Languages, ]) ?> </div> <div class="col-lg-4 join-message"> <h3> Thanks You for joining Staylance!</h3> <p>Welcome our community,we wish you a wonderful time. Please complete your profile</p> <br><br><br><br><br><br><br> </div> </div> </div> </div> </div> </div> <div class="form-group wrap_container"> <div class="row"> <div class="col-md-4"> <?php if (count($travellerprofile) > 0) { ?> <a href="<?php echo Url::to(['/travellersprofile/update', 'id' => $travellerprofile->id]); ?>" class="btn btn-arrow"> <i class="fa fa-arrow-left"></i> </a> <a href="<?php echo Url::to(['/travellersprofile/update', 'id' => $travellerprofile->id]); ?>" class="btn btn-back-text">back</a> <?php } else { ?> <a href="<?php echo Url::to(['/travellersprofile/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-arrow"> <i class="fa fa-arrow-left"></i> </a> <a href="<?php echo Url::to(['/travellersprofile/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-back-text">back</a> <?php } ?> </div> <div class="col-md-4 align-center"> <?php if (count($travellerfood) > 0) { ?> <a href="<?php echo Url::to(['/travellersfood/update', 'id' => $travellerfood->id]); ?>" class="btn btn-success btn-skip">I will do this later</a> <?php } else { ?> <a href="<?php echo Url::to(['/travellersfood/create', 'traveller_id' => $traveller_id]); ?>" class="btn btn-success btn-skip">I will do this later</a> <?php } ?> </div> <div class="right-align col-md-4"> <?= Html::submitButton(Yii::t('app', 'next step'), ['class' => 'btn btn-next-text btn-arrow']) ?> <?= Html::submitButton(Yii::t('app', '<i class="fa fa-arrow-right"></i>'), ['class' => 'btn btn-arrow']) ?> <?php ActiveForm::end(); ?> </div> </div>
bsd-3-clause
jeremyclifton/sitecore-testing-automator
Data/TestAutomator/TestResult.cs
1373
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml.XPath; namespace JeremyClifton.Data.TestAutomator { public class TestResult { private XElement _data; public XElement Data { get { return _data; } } private List<string> _messages = new List<string>(); public List<string> Messages { get { return _messages; } } private string _output; public string Output { get { return _output; } } public string RawXml { get { return _data.ToString(); } } public TestResult() { throw new Exception("Not implemented!"); } public TestResult(XElement xml) { _data = xml; InitMessages(); InitOutput(); } private void InitMessages() { foreach (XElement el in _data.XPathSelectElements("//messages/message")) { _messages.Add(el.Value); } } private void InitOutput() { XElement el = _data.XPathSelectElement("//output"); if (el != null) { _output = el.Value; } } } }
bsd-3-clause
mistermarco/swat
stanford.database.php
7278
<?php /** * StanfordDatabase is an extension of MySQLi intended to assist developers in creating secure database-enabled applications * * Copyright 2008,2009 Board of Trustees, Leland Stanford Jr. University * See LICENSE for licensing terms. * */ class StanfordDatabase extends MySQLi { const VERSION = "1.0.0"; const HOST_STANDARD = "mysql-user.stanford.edu"; const HOST_ENCRYPTED = "127.0.0.1"; private $username; // Username private $password; // Password private $database; // Name of database private $host; // Host private $connected; // Connected to database? private $mysql_sessions; // MySQL-based sessions enabled? /** * Create a new StanfordDatabase object and initialize mysqli * * @param string username The username used to connect to the database * @param string password The password used to connect to the database * @param string database The name of the database * @param boolean use_encryption Use encryption? True or false. Default is false. */ function __construct($username='', $password='', $database='', $use_encryption=false) { $this->username = $username; $this->password = $password; $this->database = $database; // Connect using a different host address depending on the need for full encryption if($use_encryption == true) { $this->host = StanfordDatabase::HOST_ENCRYPTED; } else { $this->host = StanfordDatabase::HOST_STANDARD; } // Important - initialize the mysqli object $link = parent::init(); } /** * Destructor closes the database connection */ function __destruct() { $this->close(); } /** * Gets the version number of the class * * @return string The version number */ function get_version() { return self::VERSION; } /** * Sets the name of the database * * @param string database The name of the database */ function set_database($database) { $this->database = $database; } /** * Sets the username used to connect to the database * * @param string username The username */ function set_username($username) { $this->username = $username; } /** * Sets the password used to connect to the database * * @param string password The password */ function set_password($password) { $this->password = $password; } /** * Sets the host to connect to depending on whether or not to use encryption * * @param boolean value Should be set to true if using encryption, false to disable encryption. */ function use_encryption($value=true) { // Must call this function before connecting if($this->is_connected() == true) { throw new Exception("StanfordDatabase error -- call use_encryption() before connect()"); } if($value == true) { $this->host = StanfordDatabase::HOST_ENCRYPTED; } else { $this->host = StanfordDatabase::HOST_STANDARD; } } /** * Connects to the database using the given credentials. */ function connect() { // Check if already connected if($this->is_connected() == true) return true; // Check for necessary information if($this->host == '' || $this->database == '' || $this->username == '') { throw new Exception("Cannot connect to the database -- missing required information"); } // Try to connect $result = @parent::real_connect($this->host, $this->username, $this->password, $this->database); // Check the result if($result == true) { // Connected successfully $this->connected = true; return true; } else { // Error throw new Exception("Cannot connect to the database -- " . mysqli_connect_error()); } } /** * Closes the connection to the database */ function close() { // Check if connected if($this->is_connected()) { // Check if disconnected successfully if(parent::close() == true) { // Set connected to false and return true $this->connected = false; return true; } } // Unable to disconnect return false; } /** * Checks if MySQL is connected * * @return boolean True if connected, false otherwise */ function is_connected() { return $this->connected; } /** * Checks if the connection is encrypted * * @return boolean True if encrypted, false otherwise */ function connection_is_encrypted() { if($this->host == self::HOST_ENCRYPTED) { return true; } else { return false; } } /** * Sets up MySQL-based sessions. Database settings must be configured before calling this function. * * @date December 3, 2008 * * @throws An Exception when database cannot be connected to or when creating a new php_sessions table fails * * @return boolean True on success, exception on failure */ function setup_mysql_sessions() { // Connect to database $this->connect(); // Check connection if($this->is_connected() == false) { throw new Exception("Unable to set up MySQL-based sessions -- cannot connect to database."); } // Check if table exists $sql = "SHOW TABLES LIKE 'php_sessions'"; $result = $this->query($sql); // If not.. if(mysqli_num_rows($result) == 0) { // Create table $create_table = "CREATE TABLE php_sessions ( sessionid varchar(40) BINARY NOT NULL DEFAULT '', expiry int(10) UNSIGNED NOT NULL DEFAULT '0', value text NOT NULL, PRIMARY KEY (sessionid) ) TYPE=MyISAM COMMENT='Sessions';"; $result = $this->query($create_table); if($result == false) { throw new Exception("Unable to set up MySQL-based sessions -- cannot create new table 'php_sessions.'"); } } // The variables below are used by an external script that enables MySQL-based sessions // They are required so that the other script can connect to the database global $STANFORD_DB, $STANFORD_DB_USER, $STANFORD_DB_PASS, $STANFORD_DB_HOST; $STANFORD_DB = $this->database; $STANFORD_DB_USER = $this->username; $STANFORD_DB_PASS = $this->password; $STANFORD_DB_HOST = $this->host; // Include custom session handler functions stored on the server require_once '/etc/php5/init/sessions.php'; // Set MySQL sessions flag to true $this->mysql_sessions = true; return true; } /** * Checks if the script is using MySQL-based sessions (established using setup_mysql_sessions) * * @return boolean True or false */ function using_mysql_sessions() { // Return true if the mysql_sessions flag is set to true and the session.save_handler configuration directive is set to user return ($this->mysql_sessions == true) && (ini_get('session.save_handler') == 'user'); } } ?>
bsd-3-clause
FbN/Zend-Framework-Namespaced-
Zend/Dojo/View/Helper/ContentPane.php
2024
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Dojo * @subpackage View * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: ContentPane.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * @namespace */ namespace Zend\Dojo\View\Helper; /** Zend_Dojo_View_Helper_DijitContainer */ require_once 'Zend/Dojo/View/Helper/DijitContainer.php'; /** * Dojo ContentPane dijit * * @uses Zend_Dojo_View_Helper_DijitContainer * @package Zend_Dojo * @subpackage View * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ContentPane extends DijitContainer { /** * Dijit being used * @var string */ protected $_dijit = 'dijit.layout.ContentPane'; /** * Module being used * @var string */ protected $_module = 'dijit.layout.ContentPane'; /** * dijit.layout.ContentPane * * @param string $id * @param string $content * @param array $params Parameters to use for dijit creation * @param array $attribs HTML attributes * @return string */ public function contentPane($id = null, $content = '', array $params = array(), array $attribs = array()) { if (0 === func_num_args()) { return $this; } return $this->_createLayoutContainer($id, $content, $params, $attribs); } }
bsd-3-clause
Ashoat/squadcal
native/media/ffmpeg.js
4898
// @flow import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg'; import { getHasMultipleFramesProbeCommand } from 'lib/media/video-utils'; import type { Dimensions, FFmpegStatistics, VideoInfo, } from 'lib/types/media-types'; const maxSimultaneousCalls = { process: 1, probe: 1, }; type CallCounter = typeof maxSimultaneousCalls; type QueuedCommandType = $Keys<CallCounter>; type QueuedCommand = { type: QueuedCommandType, runCommand: () => Promise<void>, }; class FFmpeg { queue: QueuedCommand[] = []; currentCalls: CallCounter = { process: 0, probe: 0 }; queueCommand<R>( type: QueuedCommandType, wrappedCommand: () => Promise<R>, ): Promise<R> { return new Promise((resolve, reject) => { const runCommand = async () => { try { const result = await wrappedCommand(); this.currentCalls[type]--; this.possiblyRunCommands(); resolve(result); } catch (e) { reject(e); } }; this.queue.push({ type, runCommand }); this.possiblyRunCommands(); }); } possiblyRunCommands() { let openSlots = {}; for (const type in this.currentCalls) { const currentCalls = this.currentCalls[type]; const maxCalls = maxSimultaneousCalls[type]; const callsLeft = maxCalls - currentCalls; if (!callsLeft) { return; } else if (currentCalls) { openSlots = { [type]: callsLeft }; break; } else { openSlots[type] = callsLeft; } } const toDefer = [], toRun = []; for (const command of this.queue) { const type: string = command.type; if (openSlots[type]) { openSlots = { [type]: openSlots[type] - 1 }; this.currentCalls[type]++; toRun.push(command); } else { toDefer.push(command); } } this.queue = toDefer; toRun.forEach(({ runCommand }) => runCommand()); } transcodeVideo( ffmpegCommand: string, inputVideoDuration: number, onTranscodingProgress: (percent: number) => void, ): Promise<{ rc: number, lastStats: ?FFmpegStatistics }> { const duration = inputVideoDuration > 0 ? inputVideoDuration : 0.001; const wrappedCommand = async () => { RNFFmpegConfig.resetStatistics(); let lastStats; RNFFmpegConfig.enableStatisticsCallback( (statisticsData: FFmpegStatistics) => { lastStats = statisticsData; const { time } = statisticsData; onTranscodingProgress(time / 1000 / duration); }, ); const ffmpegResult = await RNFFmpeg.execute(ffmpegCommand); return { ...ffmpegResult, lastStats }; }; return this.queueCommand('process', wrappedCommand); } generateThumbnail(videoPath: string, outputPath: string): Promise<number> { const wrappedCommand = () => FFmpeg.innerGenerateThumbnail(videoPath, outputPath); return this.queueCommand('process', wrappedCommand); } static async innerGenerateThumbnail( videoPath: string, outputPath: string, ): Promise<number> { const thumbnailCommand = `-i ${videoPath} -frames 1 -f singlejpeg ${outputPath}`; const { rc } = await RNFFmpeg.execute(thumbnailCommand); return rc; } getVideoInfo(path: string): Promise<VideoInfo> { const wrappedCommand = () => FFmpeg.innerGetVideoInfo(path); return this.queueCommand('probe', wrappedCommand); } static async innerGetVideoInfo(path: string): Promise<VideoInfo> { const info = await RNFFprobe.getMediaInformation(path); const videoStreamInfo = FFmpeg.getVideoStreamInfo(info); const codec = videoStreamInfo?.codec; const dimensions = videoStreamInfo && videoStreamInfo.dimensions; const format = info.format.split(','); const duration = info.duration / 1000; return { codec, format, dimensions, duration }; } static getVideoStreamInfo( info: Object, ): ?{ +codec: string, +dimensions: Dimensions } { if (!info.streams) { return null; } for (const stream of info.streams) { if (stream.type === 'video') { const codec: string = stream.codec; const width: number = stream.width; const height: number = stream.height; return { codec, dimensions: { width, height } }; } } return null; } hasMultipleFrames(path: string): Promise<boolean> { const wrappedCommand = () => FFmpeg.innerHasMultipleFrames(path); return this.queueCommand('probe', wrappedCommand); } static async innerHasMultipleFrames(path: string): Promise<boolean> { await RNFFprobe.execute(getHasMultipleFramesProbeCommand(path)); const probeOutput = await RNFFmpegConfig.getLastCommandOutput(); const numFrames = parseInt(probeOutput.lastCommandOutput); return numFrames > 1; } } const ffmpeg: FFmpeg = new FFmpeg(); export { ffmpeg };
bsd-3-clause
v-joy/v-joy
views/authitemchild/update.php
640
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\AuthItemChild */ $this->title = Yii::t('app', '更新: ', [ 'modelClass' => 'Auth Item Child', ]) . ' ' . $model->parent; $this->params['breadcrumbs'][] = ['label' => '权限关系', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->parent, 'url' => ['view', 'parent' => $model->parent, 'child' => $model->child]]; $this->params['breadcrumbs'][] = '更新'; ?> <div class="auth-item-child-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
bsd-3-clause
lipsia-fmri/lipsia
src/lib_viaio/znzlib.c
7892
/** \file znzlib.c \brief Low level i/o interface to compressed and noncompressed files. Written by Mark Jenkinson, FMRIB This library provides an interface to both compressed (gzip/zlib) and uncompressed (normal) file IO. The functions are written to have the same interface as the standard file IO functions. To use this library instead of normal file IO, the following changes are required: - replace all instances of FILE* with znzFile - change the name of all function calls, replacing the initial character f with the znz (e.g. fseek becomes znzseek) one exception is rewind() -> znzrewind() - add a third parameter to all calls to znzopen (previously fopen) that specifies whether to use compression (1) or not (0) - use znz_isnull rather than any (pointer == NULL) comparisons in the code for znzfile types (normally done after a return from znzopen) NB: seeks for writable files with compression are quite restricted */ #include <nifti/znzlib.h> /* znzlib.c (zipped or non-zipped library) ***** This code is released to the public domain. ***** ***** Author: Mark Jenkinson, FMRIB Centre, University of Oxford ***** ***** Date: September 2004 ***** ***** Neither the FMRIB Centre, the University of Oxford, nor any of ***** ***** its employees imply any warranty of usefulness of this software ***** ***** for any purpose, and do not assume any liability for damages, ***** ***** incidental or otherwise, caused by any use of this document. ***** */ /* Note extra argument (use_compression) where use_compression==0 is no compression use_compression!=0 uses zlib (gzip) compression */ znzFile znzopen(const char *path, const char *mode, int use_compression) { znzFile file; file = (znzFile) calloc(1,sizeof(struct znzptr)); if( file == NULL ){ fprintf(stderr,"** ERROR: znzopen failed to alloc znzptr\n"); return NULL; } file->nzfptr = NULL; #ifdef HAVE_ZLIB file->zfptr = NULL; if (use_compression) { file->withz = 1; if((file->zfptr = gzopen(path,mode)) == NULL) { free(file); file = NULL; } } else { #endif file->withz = 0; if((file->nzfptr = fopen(path,mode)) == NULL) { free(file); file = NULL; } #ifdef HAVE_ZLIB } #endif return file; } znzFile znzdopen(int fd, const char *mode, int use_compression) { znzFile file; file = (znzFile) calloc(1,sizeof(struct znzptr)); if( file == NULL ){ fprintf(stderr,"** ERROR: znzdopen failed to alloc znzptr\n"); return NULL; } #ifdef HAVE_ZLIB if (use_compression) { file->withz = 1; file->zfptr = gzdopen(fd,mode); file->nzfptr = NULL; } else { #endif file->withz = 0; #ifdef HAVE_FDOPEN file->nzfptr = fdopen(fd,mode); #endif #ifdef HAVE_ZLIB file->zfptr = NULL; }; #endif return file; } int Xznzclose(znzFile * file) { int retval = 0; if (*file!=NULL) { #ifdef HAVE_ZLIB if ((*file)->zfptr!=NULL) { retval = gzclose((*file)->zfptr); } #endif if ((*file)->nzfptr!=NULL) { retval = fclose((*file)->nzfptr); } free(*file); *file = NULL; } return retval; } /* we already assume ints are 4 bytes */ #undef ZNZ_MAX_BLOCK_SIZE #define ZNZ_MAX_BLOCK_SIZE (1<<30) size_t znzread(void* buf, size_t size, size_t nmemb, znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) { /* gzread/write take unsigned int length, so maybe read in int pieces (noted by M Hanke, example given by M Adler) 6 July 2010 [rickr] */ while( remain > 0 ) { n2read = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; nread = gzread(file->zfptr, (void *)cbuf, n2read); if( nread < 0 ) return nread; /* returns -1 on error */ remain -= nread; cbuf += nread; /* require reading n2read bytes, so we don't get stuck */ if( nread < (int)n2read ) break; /* return will be short */ } /* warn of a short read that will seem complete */ if( remain > 0 && remain < size ) fprintf(stderr,"** znzread: read short by %u bytes\n",(unsigned)remain); return nmemb - remain/size; /* return number of members processed */ } #endif return fread(buf,size,nmemb,file->nzfptr); } size_t znzwrite(const void* buf, size_t size, size_t nmemb, znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) { while( remain > 0 ) { n2write = (remain < ZNZ_MAX_BLOCK_SIZE) ? remain : ZNZ_MAX_BLOCK_SIZE; nwritten = gzwrite(file->zfptr, (const void *)cbuf, n2write); /* gzread returns 0 on error, but in case that ever changes... */ if( nwritten < 0 ) return nwritten; remain -= nwritten; cbuf += nwritten; /* require writing n2write bytes, so we don't get stuck */ if( nwritten < (int)n2write ) break; } /* warn of a short write that will seem complete */ if( remain > 0 && remain < size ) fprintf(stderr,"** znzwrite: write short by %u bytes\n",(unsigned)remain); return nmemb - remain/size; /* return number of members processed */ } #endif return fwrite(buf,size,nmemb,file->nzfptr); } long znzseek(znzFile file, long offset, int whence) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return (long) gzseek(file->zfptr,offset,whence); #endif return fseek(file->nzfptr,offset,whence); } int znzrewind(znzFile stream) { if (stream==NULL) { return 0; } #ifdef HAVE_ZLIB /* On some systems, gzrewind() fails for uncompressed files. Use gzseek(), instead. 10, May 2005 [rickr] if (stream->zfptr!=NULL) return gzrewind(stream->zfptr); */ if (stream->zfptr!=NULL) return (int)gzseek(stream->zfptr, 0L, SEEK_SET); #endif rewind(stream->nzfptr); return 0; } long znztell(znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return (long) gztell(file->zfptr); #endif return ftell(file->nzfptr); } int znzputs(const char * str, znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzputs(file->zfptr,str); #endif return fputs(str,file->nzfptr); } char * znzgets(char* str, int size, znzFile file) { if (file==NULL) { return NULL; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzgets(file->zfptr,str,size); #endif return fgets(str,size,file->nzfptr); } int znzflush(znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzflush(file->zfptr,Z_SYNC_FLUSH); #endif return fflush(file->nzfptr); } int znzeof(znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzeof(file->zfptr); #endif return feof(file->nzfptr); } int znzputc(int c, znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzputc(file->zfptr,c); #endif return fputc(c,file->nzfptr); } int znzgetc(znzFile file) { if (file==NULL) { return 0; } #ifdef HAVE_ZLIB if (file->zfptr!=NULL) return gzgetc(file->zfptr); #endif return fgetc(file->nzfptr); } #if !defined (WIN32) int znzprintf(znzFile stream, const char *format, ...) { int retval=0; va_list va; if (stream==NULL) { return 0; } va_start(va, format); #ifdef HAVE_ZLIB if (stream->zfptr!=NULL) { int size; /* local to HAVE_ZLIB block */ size = strlen(format) + 1000000; /* overkill I hope */ tmpstr = (char *)calloc(1, size); if( tmpstr == NULL ){ fprintf(stderr,"** ERROR: znzprintf failed to alloc %d bytes\n", size); return retval; } vsprintf(tmpstr,format,va); retval=gzprintf(stream->zfptr,"%s",tmpstr); free(tmpstr); } else #endif { retval=vfprintf(stream->nzfptr,format,va); } va_end(va); return retval; } #endif
bsd-3-clause
wooster/django-topsoil
tests/test_provider/testapp/models.py
430
from django.db import models class Place(models.Model): name = models.CharField(max_length=128) url = models.URLField(max_length=256, verify_exists=False) date = models.DateTimeField(auto_now_add=True) class Meta(object): topsoil_exclude = ['date'] def get_absolute_url(self): return "/places/%i" % self.id def get_edit_url(self): return "/places/%i/edit" % self.id
bsd-3-clause
wnoc-drexel/gem5-stable
src/doxygen/html/rob__impl_8hh-source.html
60497
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>gem5: cpu/o3/rob_impl.hh Source File</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="classes.html"><span>Classes</span></a></li> <li id="current"><a href="files.html"><span>Files</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul></div> <h1>cpu/o3/rob_impl.hh</h1><a href="rob__impl_8hh.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*</span> <a name="l00002"></a>00002 <span class="comment"> * Copyright (c) 2012 ARM Limited</span> <a name="l00003"></a>00003 <span class="comment"> * All rights reserved</span> <a name="l00004"></a>00004 <span class="comment"> *</span> <a name="l00005"></a>00005 <span class="comment"> * The license below extends only to copyright in the software and shall</span> <a name="l00006"></a>00006 <span class="comment"> * not be construed as granting a license to any other intellectual</span> <a name="l00007"></a>00007 <span class="comment"> * property including but not limited to intellectual property relating</span> <a name="l00008"></a>00008 <span class="comment"> * to a hardware implementation of the functionality of the software</span> <a name="l00009"></a>00009 <span class="comment"> * licensed hereunder. You may use the software subject to the license</span> <a name="l00010"></a>00010 <span class="comment"> * terms below provided that you ensure that this notice is replicated</span> <a name="l00011"></a>00011 <span class="comment"> * unmodified and in its entirety in all distributions of the software,</span> <a name="l00012"></a>00012 <span class="comment"> * modified or unmodified, in source code or in binary form.</span> <a name="l00013"></a>00013 <span class="comment"> *</span> <a name="l00014"></a>00014 <span class="comment"> * Copyright (c) 2004-2006 The Regents of The University of Michigan</span> <a name="l00015"></a>00015 <span class="comment"> * All rights reserved.</span> <a name="l00016"></a>00016 <span class="comment"> *</span> <a name="l00017"></a>00017 <span class="comment"> * Redistribution and use in source and binary forms, with or without</span> <a name="l00018"></a>00018 <span class="comment"> * modification, are permitted provided that the following conditions are</span> <a name="l00019"></a>00019 <span class="comment"> * met: redistributions of source code must retain the above copyright</span> <a name="l00020"></a>00020 <span class="comment"> * notice, this list of conditions and the following disclaimer;</span> <a name="l00021"></a>00021 <span class="comment"> * redistributions in binary form must reproduce the above copyright</span> <a name="l00022"></a>00022 <span class="comment"> * notice, this list of conditions and the following disclaimer in the</span> <a name="l00023"></a>00023 <span class="comment"> * documentation and/or other materials provided with the distribution;</span> <a name="l00024"></a>00024 <span class="comment"> * neither the name of the copyright holders nor the names of its</span> <a name="l00025"></a>00025 <span class="comment"> * contributors may be used to endorse or promote products derived from</span> <a name="l00026"></a>00026 <span class="comment"> * this software without specific prior written permission.</span> <a name="l00027"></a>00027 <span class="comment"> *</span> <a name="l00028"></a>00028 <span class="comment"> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS</span> <a name="l00029"></a>00029 <span class="comment"> * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT</span> <a name="l00030"></a>00030 <span class="comment"> * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR</span> <a name="l00031"></a>00031 <span class="comment"> * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT</span> <a name="l00032"></a>00032 <span class="comment"> * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,</span> <a name="l00033"></a>00033 <span class="comment"> * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT</span> <a name="l00034"></a>00034 <span class="comment"> * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,</span> <a name="l00035"></a>00035 <span class="comment"> * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY</span> <a name="l00036"></a>00036 <span class="comment"> * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT</span> <a name="l00037"></a>00037 <span class="comment"> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE</span> <a name="l00038"></a>00038 <span class="comment"> * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span> <a name="l00039"></a>00039 <span class="comment"> *</span> <a name="l00040"></a>00040 <span class="comment"> * Authors: Kevin Lim</span> <a name="l00041"></a>00041 <span class="comment"> * Korey Sewell</span> <a name="l00042"></a>00042 <span class="comment"> */</span> <a name="l00043"></a>00043 <a name="l00044"></a>00044 <span class="preprocessor">#ifndef __CPU_O3_ROB_IMPL_HH__</span> <a name="l00045"></a>00045 <span class="preprocessor"></span><span class="preprocessor">#define __CPU_O3_ROB_IMPL_HH__</span> <a name="l00046"></a>00046 <span class="preprocessor"></span> <a name="l00047"></a>00047 <span class="preprocessor">#include &lt;list&gt;</span> <a name="l00048"></a>00048 <a name="l00049"></a>00049 <span class="preprocessor">#include "<a class="code" href="rob_8hh.html">cpu/o3/rob.hh</a>"</span> <a name="l00050"></a>00050 <span class="preprocessor">#include "debug/Fetch.hh"</span> <a name="l00051"></a>00051 <span class="preprocessor">#include "debug/ROB.hh"</span> <a name="l00052"></a>00052 <span class="preprocessor">#include "params/DerivO3CPU.hh"</span> <a name="l00053"></a>00053 <a name="l00054"></a>00054 <span class="keyword">using namespace </span>std; <a name="l00055"></a>00055 <a name="l00056"></a>00056 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00057"></a><a class="code" href="classROB.html#cf2099d62ec33cb251d1fb732e18b297">00057</a> <a class="code" href="classROB.html#cf2099d62ec33cb251d1fb732e18b297">ROB&lt;Impl&gt;::ROB</a>(O3CPU *_cpu, DerivO3CPUParams *params) <a name="l00058"></a>00058 : cpu(_cpu), <a name="l00059"></a>00059 numEntries(params-&gt;numROBEntries), <a name="l00060"></a>00060 squashWidth(params-&gt;squashWidth), <a name="l00061"></a>00061 numInstsInROB(0), <a name="l00062"></a>00062 numThreads(params-&gt;numThreads) <a name="l00063"></a>00063 { <a name="l00064"></a>00064 std::string policy = params-&gt;smtROBPolicy; <a name="l00065"></a>00065 <a name="l00066"></a>00066 <span class="comment">//Convert string to lowercase</span> <a name="l00067"></a>00067 std::transform(policy.begin(), policy.end(), policy.begin(), <a name="l00068"></a>00068 (int(*)(int)) tolower); <a name="l00069"></a>00069 <a name="l00070"></a>00070 <span class="comment">//Figure out rob policy</span> <a name="l00071"></a>00071 <span class="keywordflow">if</span> (policy == <span class="stringliteral">"dynamic"</span>) { <a name="l00072"></a>00072 <a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> = <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7d33ca9daff4e5afab5345cb3dfe41420">Dynamic</a>; <a name="l00073"></a>00073 <a name="l00074"></a>00074 <span class="comment">//Set Max Entries to Total ROB Capacity</span> <a name="l00075"></a>00075 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) { <a name="l00076"></a>00076 <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] = <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a>; <a name="l00077"></a>00077 } <a name="l00078"></a>00078 <a name="l00079"></a>00079 } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (policy == <span class="stringliteral">"partitioned"</span>) { <a name="l00080"></a>00080 <a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> = <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7b1fec8700b82bd704d606a1376776363">Partitioned</a>; <a name="l00081"></a>00081 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(Fetch, <span class="stringliteral">"ROB sharing policy set to Partitioned\n"</span>); <a name="l00082"></a>00082 <a name="l00083"></a>00083 <span class="comment">//@todo:make work if part_amt doesnt divide evenly.</span> <a name="l00084"></a>00084 <span class="keywordtype">int</span> part_amt = <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a> / <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; <a name="l00085"></a>00085 <a name="l00086"></a>00086 <span class="comment">//Divide ROB up evenly</span> <a name="l00087"></a>00087 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) { <a name="l00088"></a>00088 <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] = part_amt; <a name="l00089"></a>00089 } <a name="l00090"></a>00090 <a name="l00091"></a>00091 } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (policy == <span class="stringliteral">"threshold"</span>) { <a name="l00092"></a>00092 <a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> = <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7d6e5a4ac9a3d34cc2ad439dbcb9372b1">Threshold</a>; <a name="l00093"></a>00093 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(Fetch, <span class="stringliteral">"ROB sharing policy set to Threshold\n"</span>); <a name="l00094"></a>00094 <a name="l00095"></a>00095 <span class="keywordtype">int</span> threshold = params-&gt;smtROBThreshold;; <a name="l00096"></a>00096 <a name="l00097"></a>00097 <span class="comment">//Divide up by threshold amount</span> <a name="l00098"></a>00098 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) { <a name="l00099"></a>00099 <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] = threshold; <a name="l00100"></a>00100 } <a name="l00101"></a>00101 } <span class="keywordflow">else</span> { <a name="l00102"></a>00102 assert(0 &amp;&amp; <span class="stringliteral">"Invalid ROB Sharing Policy.Options Are:{Dynamic,"</span> <a name="l00103"></a>00103 <span class="stringliteral">"Partitioned, Threshold}"</span>); <a name="l00104"></a>00104 } <a name="l00105"></a>00105 <a name="l00106"></a>00106 <a class="code" href="classROB.html#98258517d5e2926b8589bdd0c6042438">resetState</a>(); <a name="l00107"></a>00107 } <a name="l00108"></a>00108 <a name="l00109"></a>00109 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00110"></a>00110 <span class="keywordtype">void</span> <a name="l00111"></a><a class="code" href="classROB.html#98258517d5e2926b8589bdd0c6042438">00111</a> <a class="code" href="classROB.html#98258517d5e2926b8589bdd0c6042438">ROB&lt;Impl&gt;::resetState</a>() <a name="l00112"></a>00112 { <a name="l00113"></a>00113 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) { <a name="l00114"></a>00114 <a class="code" href="classROB.html#be6180a044a51869c37f1a9eb6a55e6a">doneSquashing</a>[tid] = <span class="keyword">true</span>; <a name="l00115"></a>00115 <a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid] = 0; <a name="l00116"></a>00116 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00117"></a>00117 <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid] = 0; <a name="l00118"></a>00118 } <a name="l00119"></a>00119 <a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a> = 0; <a name="l00120"></a>00120 <a name="l00121"></a>00121 <span class="comment">// Initialize the "universal" ROB head &amp; tail point to invalid</span> <a name="l00122"></a>00122 <span class="comment">// pointers</span> <a name="l00123"></a>00123 <a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[0].end(); <a name="l00124"></a>00124 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[0].end(); <a name="l00125"></a>00125 } <a name="l00126"></a>00126 <a name="l00127"></a>00127 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00128"></a>00128 std::string <a name="l00129"></a><a class="code" href="classROB.html#9a858a2e3b275030abc2d40fa3af09fc">00129</a> <a class="code" href="classROB.html#9a858a2e3b275030abc2d40fa3af09fc">ROB&lt;Impl&gt;::name</a>()<span class="keyword"> const</span> <a name="l00130"></a>00130 <span class="keyword"></span>{ <a name="l00131"></a>00131 <span class="keywordflow">return</span> <a class="code" href="classROB.html#547d1acd190618ec7da8d494f6d75360">cpu</a>-&gt;name() + <span class="stringliteral">".rob"</span>; <a name="l00132"></a>00132 } <a name="l00133"></a>00133 <a name="l00134"></a>00134 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00135"></a>00135 <span class="keywordtype">void</span> <a name="l00136"></a><a class="code" href="classROB.html#46af622c907c98f0b3cfb007c6e4d3a4">00136</a> <a class="code" href="classROB.html#46af622c907c98f0b3cfb007c6e4d3a4">ROB&lt;Impl&gt;::setActiveThreads</a>(<a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;</a> *at_ptr) <a name="l00137"></a>00137 { <a name="l00138"></a>00138 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"Setting active threads list pointer.\n"</span>); <a name="l00139"></a>00139 <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a> = at_ptr; <a name="l00140"></a>00140 } <a name="l00141"></a>00141 <a name="l00142"></a>00142 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00143"></a>00143 <span class="keywordtype">void</span> <a name="l00144"></a><a class="code" href="classROB.html#2639096384ac84f969eef5b36effc9a5">00144</a> <a class="code" href="classROB.html#2639096384ac84f969eef5b36effc9a5">ROB&lt;Impl&gt;::drainSanityCheck</a>()<span class="keyword"> const</span> <a name="l00145"></a>00145 <span class="keyword"></span>{ <a name="l00146"></a>00146 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) <a name="l00147"></a>00147 assert(<a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].empty()); <a name="l00148"></a>00148 assert(<a class="code" href="classROB.html#e31e8fb5da5296ecbf7b1d7bdf86012d">isEmpty</a>()); <a name="l00149"></a>00149 } <a name="l00150"></a>00150 <a name="l00151"></a>00151 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00152"></a>00152 <span class="keywordtype">void</span> <a name="l00153"></a><a class="code" href="classROB.html#a709be7e2a4b9e553b690a64004a767e">00153</a> <a class="code" href="classROB.html#a709be7e2a4b9e553b690a64004a767e">ROB&lt;Impl&gt;::takeOverFrom</a>() <a name="l00154"></a>00154 { <a name="l00155"></a>00155 <a class="code" href="classROB.html#98258517d5e2926b8589bdd0c6042438">resetState</a>(); <a name="l00156"></a>00156 } <a name="l00157"></a>00157 <a name="l00158"></a>00158 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00159"></a>00159 <span class="keywordtype">void</span> <a name="l00160"></a><a class="code" href="classROB.html#8a9ef8faeea3e6c2f1510b325039636e">00160</a> <a class="code" href="classROB.html#8a9ef8faeea3e6c2f1510b325039636e">ROB&lt;Impl&gt;::resetEntries</a>() <a name="l00161"></a>00161 { <a name="l00162"></a>00162 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> != <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7d33ca9daff4e5afab5345cb3dfe41420">Dynamic</a> || <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a> &gt; 1) { <a name="l00163"></a>00163 <span class="keywordtype">int</span> active_threads = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;size(); <a name="l00164"></a>00164 <a name="l00165"></a>00165 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> threads = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;begin(); <a name="l00166"></a>00166 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> end = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;end(); <a name="l00167"></a>00167 <a name="l00168"></a>00168 <span class="keywordflow">while</span> (threads != end) { <a name="l00169"></a>00169 <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = *threads++; <a name="l00170"></a>00170 <a name="l00171"></a>00171 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> == <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7b1fec8700b82bd704d606a1376776363">Partitioned</a>) { <a name="l00172"></a>00172 <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] = <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a> / active_threads; <a name="l00173"></a>00173 } <span class="keywordflow">else</span> <span class="keywordflow">if</span> (<a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> == <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7d6e5a4ac9a3d34cc2ad439dbcb9372b1">Threshold</a> &amp;&amp; active_threads == 1) { <a name="l00174"></a>00174 <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] = <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a>; <a name="l00175"></a>00175 } <a name="l00176"></a>00176 } <a name="l00177"></a>00177 } <a name="l00178"></a>00178 } <a name="l00179"></a>00179 <a name="l00180"></a>00180 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00181"></a>00181 <span class="keywordtype">int</span> <a name="l00182"></a><a class="code" href="classROB.html#3e9c65a72180dbe26dfafa0d01e9c698">00182</a> <a class="code" href="classROB.html#3e9c65a72180dbe26dfafa0d01e9c698">ROB&lt;Impl&gt;::entryAmount</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> num_threads) <a name="l00183"></a>00183 { <a name="l00184"></a>00184 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#6edbf24f38e011c8343ef25eaba363c9">robPolicy</a> == <a class="code" href="classROB.html#2e5c35ef2d7eacc40df4f2a64077fca7b1fec8700b82bd704d606a1376776363">Partitioned</a>) { <a name="l00185"></a>00185 <span class="keywordflow">return</span> <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a> / num_threads; <a name="l00186"></a>00186 } <span class="keywordflow">else</span> { <a name="l00187"></a>00187 <span class="keywordflow">return</span> 0; <a name="l00188"></a>00188 } <a name="l00189"></a>00189 } <a name="l00190"></a>00190 <a name="l00191"></a>00191 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00192"></a>00192 <span class="keywordtype">int</span> <a name="l00193"></a><a class="code" href="classROB.html#86cc73426855288d19a3acaf06595506">00193</a> <a class="code" href="classROB.html#86cc73426855288d19a3acaf06595506">ROB&lt;Impl&gt;::countInsts</a>() <a name="l00194"></a>00194 { <a name="l00195"></a>00195 <span class="keywordtype">int</span> <a class="code" href="namespaceStats.html#4a8d8ef967fddb728594b751a6170802">total</a> = 0; <a name="l00196"></a>00196 <a name="l00197"></a>00197 <span class="keywordflow">for</span> (<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = 0; tid &lt; <a class="code" href="classROB.html#43040dd04c8a6e4f2f264b3ba0c5a88c">numThreads</a>; tid++) <a name="l00198"></a>00198 total += <a class="code" href="classROB.html#86cc73426855288d19a3acaf06595506">countInsts</a>(tid); <a name="l00199"></a>00199 <a name="l00200"></a>00200 <span class="keywordflow">return</span> total; <a name="l00201"></a>00201 } <a name="l00202"></a>00202 <a name="l00203"></a>00203 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00204"></a>00204 <span class="keywordtype">int</span> <a name="l00205"></a><a class="code" href="classROB.html#43ece4c6e4170e14078d5cdfff34e44b">00205</a> <a class="code" href="classROB.html#86cc73426855288d19a3acaf06595506">ROB&lt;Impl&gt;::countInsts</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00206"></a>00206 { <a name="l00207"></a>00207 <span class="keywordflow">return</span> <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].size(); <a name="l00208"></a>00208 } <a name="l00209"></a>00209 <a name="l00210"></a>00210 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00211"></a>00211 <span class="keywordtype">void</span> <a name="l00212"></a><a class="code" href="classROB.html#a1995080bfd1a0a56e594a404fb92084">00212</a> <a class="code" href="classROB.html#a1995080bfd1a0a56e594a404fb92084">ROB&lt;Impl&gt;::insertInst</a>(<a class="code" href="namespaceThePipeline.html#bc1e44a9461ed60edcea0910393f7823">DynInstPtr</a> &amp;inst) <a name="l00213"></a>00213 { <a name="l00214"></a>00214 assert(inst); <a name="l00215"></a>00215 <a name="l00216"></a>00216 <a class="code" href="classROB.html#af1d375cbd448ef70b83f77615f2bd2e">robWrites</a>++; <a name="l00217"></a>00217 <a name="l00218"></a>00218 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"Adding inst PC %s to the ROB.\n"</span>, inst-&gt;pcState()); <a name="l00219"></a>00219 <a name="l00220"></a>00220 assert(<a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a> != <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a>); <a name="l00221"></a>00221 <a name="l00222"></a>00222 <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = inst-&gt;threadNumber; <a name="l00223"></a>00223 <a name="l00224"></a>00224 <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].push_back(inst); <a name="l00225"></a>00225 <a name="l00226"></a>00226 <span class="comment">//Set Up head iterator if this is the 1st instruction in the ROB</span> <a name="l00227"></a>00227 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a> == 0) { <a name="l00228"></a>00228 <a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); <a name="l00229"></a>00229 assert((*<a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a>) == inst); <a name="l00230"></a>00230 } <a name="l00231"></a>00231 <a name="l00232"></a>00232 <span class="comment">//Must Decrement for iterator to actually be valid since __.end()</span> <a name="l00233"></a>00233 <span class="comment">//actually points to 1 after the last inst</span> <a name="l00234"></a>00234 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00235"></a>00235 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a>--; <a name="l00236"></a>00236 <a name="l00237"></a>00237 inst-&gt;setInROB(); <a name="l00238"></a>00238 <a name="l00239"></a>00239 ++<a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a>; <a name="l00240"></a>00240 ++<a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid]; <a name="l00241"></a>00241 <a name="l00242"></a>00242 assert((*<a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a>) == inst); <a name="l00243"></a>00243 <a name="l00244"></a>00244 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%i] Now has %d instructions.\n"</span>, tid, <a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid]); <a name="l00245"></a>00245 } <a name="l00246"></a>00246 <a name="l00247"></a>00247 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00248"></a>00248 <span class="keywordtype">void</span> <a name="l00249"></a><a class="code" href="classROB.html#18a32d68fed4751ca76874079998c907">00249</a> <a class="code" href="classROB.html#18a32d68fed4751ca76874079998c907">ROB&lt;Impl&gt;::retireHead</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00250"></a>00250 { <a name="l00251"></a>00251 <a class="code" href="classROB.html#af1d375cbd448ef70b83f77615f2bd2e">robWrites</a>++; <a name="l00252"></a>00252 <a name="l00253"></a>00253 assert(<a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a> &gt; 0); <a name="l00254"></a>00254 <a name="l00255"></a>00255 <span class="comment">// Get the head ROB instruction.</span> <a name="l00256"></a>00256 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> head_it = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); <a name="l00257"></a>00257 <a name="l00258"></a>00258 <a class="code" href="classROB.html#7f327b74807aea2dfbcfaa78ec595707">DynInstPtr</a> head_inst = (*head_it); <a name="l00259"></a>00259 <a name="l00260"></a>00260 assert(head_inst-&gt;readyToCommit()); <a name="l00261"></a>00261 <a name="l00262"></a>00262 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%u]: Retiring head instruction, "</span> <a name="l00263"></a>00263 <span class="stringliteral">"instruction PC %s, [sn:%lli]\n"</span>, tid, head_inst-&gt;pcState(), <a name="l00264"></a>00264 head_inst-&gt;seqNum); <a name="l00265"></a>00265 <a name="l00266"></a>00266 --<a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a>; <a name="l00267"></a>00267 --<a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid]; <a name="l00268"></a>00268 <a name="l00269"></a>00269 head_inst-&gt;clearInROB(); <a name="l00270"></a>00270 head_inst-&gt;setCommitted(); <a name="l00271"></a>00271 <a name="l00272"></a>00272 <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].erase(head_it); <a name="l00273"></a>00273 <a name="l00274"></a>00274 <span class="comment">//Update "Global" Head of ROB</span> <a name="l00275"></a>00275 <a class="code" href="classROB.html#47b9b46cef66a6ac33a90dee612b426e">updateHead</a>(); <a name="l00276"></a>00276 <a name="l00277"></a>00277 <span class="comment">// @todo: A special case is needed if the instruction being</span> <a name="l00278"></a>00278 <span class="comment">// retired is the only instruction in the ROB; otherwise the tail</span> <a name="l00279"></a>00279 <span class="comment">// iterator will become invalidated.</span> <a name="l00280"></a>00280 <a class="code" href="classROB.html#547d1acd190618ec7da8d494f6d75360">cpu</a>-&gt;removeFrontInst(head_inst); <a name="l00281"></a>00281 } <a name="l00282"></a>00282 <a name="l00283"></a>00283 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00284"></a>00284 <span class="keywordtype">bool</span> <a name="l00285"></a><a class="code" href="classROB.html#4e9294f8ff195d57376112736100457a">00285</a> <a class="code" href="classROB.html#4e9294f8ff195d57376112736100457a">ROB&lt;Impl&gt;::isHeadReady</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00286"></a>00286 { <a name="l00287"></a>00287 <a class="code" href="classROB.html#3794ec2519348233033e299dca831ccf">robReads</a>++; <a name="l00288"></a>00288 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid] != 0) { <a name="l00289"></a>00289 <span class="keywordflow">return</span> <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].front()-&gt;readyToCommit(); <a name="l00290"></a>00290 } <a name="l00291"></a>00291 <a name="l00292"></a>00292 <span class="keywordflow">return</span> <span class="keyword">false</span>; <a name="l00293"></a>00293 } <a name="l00294"></a>00294 <a name="l00295"></a>00295 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00296"></a>00296 <span class="keywordtype">bool</span> <a name="l00297"></a><a class="code" href="classROB.html#9312a08677758256b9b4c8e5ab1ce5ed">00297</a> <a class="code" href="classROB.html#9312a08677758256b9b4c8e5ab1ce5ed">ROB&lt;Impl&gt;::canCommit</a>() <a name="l00298"></a>00298 { <a name="l00299"></a>00299 <span class="comment">//@todo: set ActiveThreads through ROB or CPU</span> <a name="l00300"></a>00300 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> threads = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;begin(); <a name="l00301"></a>00301 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> end = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;end(); <a name="l00302"></a>00302 <a name="l00303"></a>00303 <span class="keywordflow">while</span> (threads != end) { <a name="l00304"></a>00304 <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = *threads++; <a name="l00305"></a>00305 <a name="l00306"></a>00306 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#4e9294f8ff195d57376112736100457a">isHeadReady</a>(tid)) { <a name="l00307"></a>00307 <span class="keywordflow">return</span> <span class="keyword">true</span>; <a name="l00308"></a>00308 } <a name="l00309"></a>00309 } <a name="l00310"></a>00310 <a name="l00311"></a>00311 <span class="keywordflow">return</span> <span class="keyword">false</span>; <a name="l00312"></a>00312 } <a name="l00313"></a>00313 <a name="l00314"></a>00314 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00315"></a>00315 <span class="keywordtype">unsigned</span> <a name="l00316"></a><a class="code" href="classROB.html#be6cc486f780058f186bce551582037a">00316</a> <a class="code" href="classROB.html#be6cc486f780058f186bce551582037a">ROB&lt;Impl&gt;::numFreeEntries</a>() <a name="l00317"></a>00317 { <a name="l00318"></a>00318 <span class="keywordflow">return</span> <a class="code" href="classROB.html#020f98a44f671983f11b25f96786e764">numEntries</a> - <a class="code" href="classROB.html#fd02facdf960fae5dac526273dae8d6c">numInstsInROB</a>; <a name="l00319"></a>00319 } <a name="l00320"></a>00320 <a name="l00321"></a>00321 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00322"></a>00322 <span class="keywordtype">unsigned</span> <a name="l00323"></a><a class="code" href="classROB.html#a6a3bdec956f9a6f42cb3a5fd5751fb1">00323</a> <a class="code" href="classROB.html#be6cc486f780058f186bce551582037a">ROB&lt;Impl&gt;::numFreeEntries</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00324"></a>00324 { <a name="l00325"></a>00325 <span class="keywordflow">return</span> <a class="code" href="classROB.html#4fff9ce730d893a1977367e25cb0039a">maxEntries</a>[tid] - <a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid]; <a name="l00326"></a>00326 } <a name="l00327"></a>00327 <a name="l00328"></a>00328 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00329"></a>00329 <span class="keywordtype">void</span> <a name="l00330"></a><a class="code" href="classROB.html#94ba76e19a899883e5427f8e27be7b8f">00330</a> <a class="code" href="classROB.html#94ba76e19a899883e5427f8e27be7b8f">ROB&lt;Impl&gt;::doSquash</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00331"></a>00331 { <a name="l00332"></a>00332 <a class="code" href="classROB.html#af1d375cbd448ef70b83f77615f2bd2e">robWrites</a>++; <a name="l00333"></a>00333 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%u]: Squashing instructions until [sn:%i].\n"</span>, <a name="l00334"></a>00334 tid, <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid]); <a name="l00335"></a>00335 <a name="l00336"></a>00336 assert(<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] != <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end()); <a name="l00337"></a>00337 <a name="l00338"></a>00338 <span class="keywordflow">if</span> ((*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;seqNum &lt; <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid]) { <a name="l00339"></a>00339 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%u]: Done squashing instructions.\n"</span>, <a name="l00340"></a>00340 tid); <a name="l00341"></a>00341 <a name="l00342"></a>00342 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00343"></a>00343 <a name="l00344"></a>00344 <a class="code" href="classROB.html#be6180a044a51869c37f1a9eb6a55e6a">doneSquashing</a>[tid] = <span class="keyword">true</span>; <a name="l00345"></a>00345 <span class="keywordflow">return</span>; <a name="l00346"></a>00346 } <a name="l00347"></a>00347 <a name="l00348"></a>00348 <span class="keywordtype">bool</span> robTailUpdate = <span class="keyword">false</span>; <a name="l00349"></a>00349 <a name="l00350"></a>00350 <span class="keywordflow">for</span> (<span class="keywordtype">int</span> numSquashed = 0; <a name="l00351"></a>00351 numSquashed &lt; <a class="code" href="classROB.html#905b991e466115af182d77afe060725f">squashWidth</a> &amp;&amp; <a name="l00352"></a>00352 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] != <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end() &amp;&amp; <a name="l00353"></a>00353 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;seqNum &gt; <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid]; <a name="l00354"></a>00354 ++numSquashed) <a name="l00355"></a>00355 { <a name="l00356"></a>00356 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%u]: Squashing instruction PC %s, seq num %i.\n"</span>, <a name="l00357"></a>00357 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;threadNumber, <a name="l00358"></a>00358 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;pcState(), <a name="l00359"></a>00359 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;seqNum); <a name="l00360"></a>00360 <a name="l00361"></a>00361 <span class="comment">// Mark the instruction as squashed, and ready to commit so that</span> <a name="l00362"></a>00362 <span class="comment">// it can drain out of the pipeline.</span> <a name="l00363"></a>00363 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;setSquashed(); <a name="l00364"></a>00364 <a name="l00365"></a>00365 (*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;setCanCommit(); <a name="l00366"></a>00366 <a name="l00367"></a>00367 <a name="l00368"></a>00368 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] == <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin()) { <a name="l00369"></a>00369 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(ROB, <span class="stringliteral">"Reached head of instruction list while "</span> <a name="l00370"></a>00370 <span class="stringliteral">"squashing.\n"</span>); <a name="l00371"></a>00371 <a name="l00372"></a>00372 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00373"></a>00373 <a name="l00374"></a>00374 <a class="code" href="classROB.html#be6180a044a51869c37f1a9eb6a55e6a">doneSquashing</a>[tid] = <span class="keyword">true</span>; <a name="l00375"></a>00375 <a name="l00376"></a>00376 <span class="keywordflow">return</span>; <a name="l00377"></a>00377 } <a name="l00378"></a>00378 <a name="l00379"></a>00379 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> tail_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00380"></a>00380 tail_thread--; <a name="l00381"></a>00381 <a name="l00382"></a>00382 <span class="keywordflow">if</span> ((*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid]) == (*tail_thread)) <a name="l00383"></a>00383 robTailUpdate = <span class="keyword">true</span>; <a name="l00384"></a>00384 <a name="l00385"></a>00385 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid]--; <a name="l00386"></a>00386 } <a name="l00387"></a>00387 <a name="l00388"></a>00388 <a name="l00389"></a>00389 <span class="comment">// Check if ROB is done squashing.</span> <a name="l00390"></a>00390 <span class="keywordflow">if</span> ((*<a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid])-&gt;seqNum &lt;= <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid]) { <a name="l00391"></a>00391 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"[tid:%u]: Done squashing instructions.\n"</span>, <a name="l00392"></a>00392 tid); <a name="l00393"></a>00393 <a name="l00394"></a>00394 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00395"></a>00395 <a name="l00396"></a>00396 <a class="code" href="classROB.html#be6180a044a51869c37f1a9eb6a55e6a">doneSquashing</a>[tid] = <span class="keyword">true</span>; <a name="l00397"></a>00397 } <a name="l00398"></a>00398 <a name="l00399"></a>00399 <span class="keywordflow">if</span> (robTailUpdate) { <a name="l00400"></a>00400 <a class="code" href="classROB.html#3ad0c75a8554836c854b2b12145e9850">updateTail</a>(); <a name="l00401"></a>00401 } <a name="l00402"></a>00402 } <a name="l00403"></a>00403 <a name="l00404"></a>00404 <a name="l00405"></a>00405 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00406"></a>00406 <span class="keywordtype">void</span> <a name="l00407"></a><a class="code" href="classROB.html#47b9b46cef66a6ac33a90dee612b426e">00407</a> <a class="code" href="classROB.html#47b9b46cef66a6ac33a90dee612b426e">ROB&lt;Impl&gt;::updateHead</a>() <a name="l00408"></a>00408 { <a name="l00409"></a>00409 <a class="code" href="inst__seq_8hh.html#258d93d98edaedee089435c19ea2ea2e">InstSeqNum</a> lowest_num = 0; <a name="l00410"></a>00410 <span class="keywordtype">bool</span> first_valid = <span class="keyword">true</span>; <a name="l00411"></a>00411 <a name="l00412"></a>00412 <span class="comment">// @todo: set ActiveThreads through ROB or CPU</span> <a name="l00413"></a>00413 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> threads = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;begin(); <a name="l00414"></a>00414 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> end = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;end(); <a name="l00415"></a>00415 <a name="l00416"></a>00416 <span class="keywordflow">while</span> (threads != end) { <a name="l00417"></a>00417 <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = *threads++; <a name="l00418"></a>00418 <a name="l00419"></a>00419 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].empty()) <a name="l00420"></a>00420 <span class="keywordflow">continue</span>; <a name="l00421"></a>00421 <a name="l00422"></a>00422 <span class="keywordflow">if</span> (first_valid) { <a name="l00423"></a>00423 <a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); <a name="l00424"></a>00424 lowest_num = (*head)-&gt;seqNum; <a name="l00425"></a>00425 first_valid = <span class="keyword">false</span>; <a name="l00426"></a>00426 <span class="keywordflow">continue</span>; <a name="l00427"></a>00427 } <a name="l00428"></a>00428 <a name="l00429"></a>00429 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> head_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); <a name="l00430"></a>00430 <a name="l00431"></a>00431 <a class="code" href="classROB.html#7f327b74807aea2dfbcfaa78ec595707">DynInstPtr</a> head_inst = (*head_thread); <a name="l00432"></a>00432 <a name="l00433"></a>00433 assert(head_inst != 0); <a name="l00434"></a>00434 <a name="l00435"></a>00435 <span class="keywordflow">if</span> (head_inst-&gt;seqNum &lt; lowest_num) { <a name="l00436"></a>00436 <a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a> = head_thread; <a name="l00437"></a>00437 lowest_num = head_inst-&gt;seqNum; <a name="l00438"></a>00438 } <a name="l00439"></a>00439 } <a name="l00440"></a>00440 <a name="l00441"></a>00441 <span class="keywordflow">if</span> (first_valid) { <a name="l00442"></a>00442 <a class="code" href="classROB.html#8f41b8c29dce28d9c843a91cc5a60dc6">head</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[0].end(); <a name="l00443"></a>00443 } <a name="l00444"></a>00444 <a name="l00445"></a>00445 } <a name="l00446"></a>00446 <a name="l00447"></a>00447 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00448"></a>00448 <span class="keywordtype">void</span> <a name="l00449"></a><a class="code" href="classROB.html#3ad0c75a8554836c854b2b12145e9850">00449</a> <a class="code" href="classROB.html#3ad0c75a8554836c854b2b12145e9850">ROB&lt;Impl&gt;::updateTail</a>() <a name="l00450"></a>00450 { <a name="l00451"></a>00451 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[0].end(); <a name="l00452"></a>00452 <span class="keywordtype">bool</span> first_valid = <span class="keyword">true</span>; <a name="l00453"></a>00453 <a name="l00454"></a>00454 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> threads = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;begin(); <a name="l00455"></a>00455 <a class="code" href="classstd_1_1list.html">list&lt;ThreadID&gt;::iterator</a> end = <a class="code" href="classROB.html#05fbdf274bef1bf49708dd5f197829ab">activeThreads</a>-&gt;end(); <a name="l00456"></a>00456 <a name="l00457"></a>00457 <span class="keywordflow">while</span> (threads != end) { <a name="l00458"></a>00458 <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid = *threads++; <a name="l00459"></a>00459 <a name="l00460"></a>00460 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].empty()) { <a name="l00461"></a>00461 <span class="keywordflow">continue</span>; <a name="l00462"></a>00462 } <a name="l00463"></a>00463 <a name="l00464"></a>00464 <span class="comment">// If this is the first valid then assign w/out</span> <a name="l00465"></a>00465 <span class="comment">// comparison</span> <a name="l00466"></a>00466 <span class="keywordflow">if</span> (first_valid) { <a name="l00467"></a>00467 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a> = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00468"></a>00468 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a>--; <a name="l00469"></a>00469 first_valid = <span class="keyword">false</span>; <a name="l00470"></a>00470 <span class="keywordflow">continue</span>; <a name="l00471"></a>00471 } <a name="l00472"></a>00472 <a name="l00473"></a>00473 <span class="comment">// Assign new tail if this thread's tail is younger</span> <a name="l00474"></a>00474 <span class="comment">// than our current "tail high"</span> <a name="l00475"></a>00475 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> tail_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00476"></a>00476 tail_thread--; <a name="l00477"></a>00477 <a name="l00478"></a>00478 <span class="keywordflow">if</span> ((*tail_thread)-&gt;seqNum &gt; (*tail)-&gt;seqNum) { <a name="l00479"></a>00479 <a class="code" href="classROB.html#3a5793f54f42f11d5b8eae027733a742">tail</a> = tail_thread; <a name="l00480"></a>00480 } <a name="l00481"></a>00481 } <a name="l00482"></a>00482 } <a name="l00483"></a>00483 <a name="l00484"></a>00484 <a name="l00485"></a>00485 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00486"></a>00486 <span class="keywordtype">void</span> <a name="l00487"></a><a class="code" href="classROB.html#a2458f0cf6b6244583dae15ebce197cc">00487</a> <a class="code" href="classROB.html#a2458f0cf6b6244583dae15ebce197cc">ROB&lt;Impl&gt;::squash</a>(<a class="code" href="inst__seq_8hh.html#258d93d98edaedee089435c19ea2ea2e">InstSeqNum</a> squash_num, <a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00488"></a>00488 { <a name="l00489"></a>00489 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#e31e8fb5da5296ecbf7b1d7bdf86012d">isEmpty</a>(tid)) { <a name="l00490"></a>00490 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"Does not need to squash due to being empty "</span> <a name="l00491"></a>00491 <span class="stringliteral">"[sn:%i]\n"</span>, <a name="l00492"></a>00492 squash_num); <a name="l00493"></a>00493 <a name="l00494"></a>00494 <span class="keywordflow">return</span>; <a name="l00495"></a>00495 } <a name="l00496"></a>00496 <a name="l00497"></a>00497 <a class="code" href="base_2trace_8hh.html#2df3201419df2f91d2b34b10ba16b944">DPRINTF</a>(<a class="code" href="classROB.html">ROB</a>, <span class="stringliteral">"Starting to squash within the ROB.\n"</span>); <a name="l00498"></a>00498 <a name="l00499"></a>00499 <a class="code" href="classROB.html#b74a139a4e29cfcd216f6a830563f0be">robStatus</a>[tid] = <a class="code" href="classROB.html#6cc6a0d16cd1a12a51c58c5a063a4ac8b3506d41e4ed02df60c4e30c19e7d384">ROBSquashing</a>; <a name="l00500"></a>00500 <a name="l00501"></a>00501 <a class="code" href="classROB.html#be6180a044a51869c37f1a9eb6a55e6a">doneSquashing</a>[tid] = <span class="keyword">false</span>; <a name="l00502"></a>00502 <a name="l00503"></a>00503 <a class="code" href="classROB.html#5ebe9639d53c2183b56df6fe47872529">squashedSeqNum</a>[tid] = squash_num; <a name="l00504"></a>00504 <a name="l00505"></a>00505 <span class="keywordflow">if</span> (!<a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].empty()) { <a name="l00506"></a>00506 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> tail_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00507"></a>00507 tail_thread--; <a name="l00508"></a>00508 <a name="l00509"></a>00509 <a class="code" href="classROB.html#e0eb5260c47576b6c4aa2467e5b32b41">squashIt</a>[tid] = tail_thread; <a name="l00510"></a>00510 <a name="l00511"></a>00511 <a class="code" href="classROB.html#94ba76e19a899883e5427f8e27be7b8f">doSquash</a>(tid); <a name="l00512"></a>00512 } <a name="l00513"></a>00513 } <a name="l00514"></a>00514 <a name="l00515"></a>00515 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00516"></a>00516 <span class="keyword">typename</span> <a class="code" href="namespaceThePipeline.html#bc1e44a9461ed60edcea0910393f7823">Impl::DynInstPtr</a> <a name="l00517"></a><a class="code" href="classROB.html#a46645060aeefcc7631eec2043c5c956">00517</a> <a class="code" href="classROB.html#a46645060aeefcc7631eec2043c5c956">ROB&lt;Impl&gt;::readHeadInst</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00518"></a>00518 { <a name="l00519"></a>00519 <span class="keywordflow">if</span> (<a class="code" href="classROB.html#e86d5bef786cc9e1688f6b1c1884311a">threadEntries</a>[tid] != 0) { <a name="l00520"></a>00520 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> head_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); <a name="l00521"></a>00521 <a name="l00522"></a>00522 assert((*head_thread)-&gt;isInROB()); <a name="l00523"></a>00523 <a name="l00524"></a>00524 <span class="keywordflow">return</span> *head_thread; <a name="l00525"></a>00525 } <span class="keywordflow">else</span> { <a name="l00526"></a>00526 <span class="keywordflow">return</span> <a class="code" href="classROB.html#b1df8b3b44dd57ea41403c3d550ad932">dummyInst</a>; <a name="l00527"></a>00527 } <a name="l00528"></a>00528 } <a name="l00529"></a>00529 <a name="l00530"></a>00530 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00531"></a>00531 <span class="keyword">typename</span> <a class="code" href="namespaceThePipeline.html#bc1e44a9461ed60edcea0910393f7823">Impl::DynInstPtr</a> <a name="l00532"></a><a class="code" href="classROB.html#1deca6a622761c1af91516f6f195b34f">00532</a> <a class="code" href="classROB.html#1deca6a622761c1af91516f6f195b34f">ROB&lt;Impl&gt;::readTailInst</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid) <a name="l00533"></a>00533 { <a name="l00534"></a>00534 <a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> tail_thread = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); <a name="l00535"></a>00535 tail_thread--; <a name="l00536"></a>00536 <a name="l00537"></a>00537 <span class="keywordflow">return</span> *tail_thread; <a name="l00538"></a>00538 } <a name="l00539"></a>00539 <a name="l00540"></a>00540 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00541"></a>00541 <span class="keywordtype">void</span> <a name="l00542"></a><a class="code" href="classROB.html#9a5da772c52907fd1c56bb0369b1973f">00542</a> <a class="code" href="classROB.html#9a5da772c52907fd1c56bb0369b1973f">ROB&lt;Impl&gt;::regStats</a>() <a name="l00543"></a>00543 { <a name="l00544"></a>00544 <span class="keyword">using namespace </span>Stats; <a name="l00545"></a>00545 <a class="code" href="classROB.html#3794ec2519348233033e299dca831ccf">robReads</a> <a name="l00546"></a>00546 .<a class="code" href="classStats_1_1DataWrap.html#8f6effeadf113613c8e96c732bef7228">name</a>(<a class="code" href="classROB.html#9a858a2e3b275030abc2d40fa3af09fc">name</a>() + <span class="stringliteral">".rob_reads"</span>) <a name="l00547"></a>00547 .desc(<span class="stringliteral">"The number of ROB reads"</span>); <a name="l00548"></a>00548 <a name="l00549"></a>00549 <a class="code" href="classROB.html#af1d375cbd448ef70b83f77615f2bd2e">robWrites</a> <a name="l00550"></a>00550 .<a class="code" href="classStats_1_1DataWrap.html#8f6effeadf113613c8e96c732bef7228">name</a>(<a class="code" href="classROB.html#9a858a2e3b275030abc2d40fa3af09fc">name</a>() + <span class="stringliteral">".rob_writes"</span>) <a name="l00551"></a>00551 .desc(<span class="stringliteral">"The number of ROB writes"</span>); <a name="l00552"></a>00552 } <a name="l00553"></a>00553 <a name="l00554"></a>00554 <span class="keyword">template</span> &lt;<span class="keyword">class</span> Impl&gt; <a name="l00555"></a>00555 <span class="keyword">typename</span> <a class="code" href="namespaceThePipeline.html#bc1e44a9461ed60edcea0910393f7823">Impl::DynInstPtr</a> <a name="l00556"></a><a class="code" href="classROB.html#e9a7411d038900f195eb0692d752250f">00556</a> <a class="code" href="classROB.html#e9a7411d038900f195eb0692d752250f">ROB&lt;Impl&gt;::findInst</a>(<a class="code" href="base_2types_8hh.html#b39b1a4f9dad884694c7a74ed69e6a6b">ThreadID</a> tid, <a class="code" href="inst__seq_8hh.html#258d93d98edaedee089435c19ea2ea2e">InstSeqNum</a> squash_inst) <a name="l00557"></a>00557 { <a name="l00558"></a>00558 <span class="keywordflow">for</span> (<a class="code" href="classROB.html#4738e6e5352063612e0cdad116b55f46">InstIt</a> it = <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].begin(); it != <a class="code" href="classROB.html#d09201cbb778aa67ffd3998f959ab1dd">instList</a>[tid].end(); it++) { <a name="l00559"></a>00559 <span class="keywordflow">if</span> ((*it)-&gt;seqNum == squash_inst) { <a name="l00560"></a>00560 <span class="keywordflow">return</span> *it; <a name="l00561"></a>00561 } <a name="l00562"></a>00562 } <a name="l00563"></a>00563 <span class="keywordflow">return</span> NULL; <a name="l00564"></a>00564 } <a name="l00565"></a>00565 <a name="l00566"></a>00566 <span class="preprocessor">#endif//__CPU_O3_ROB_IMPL_HH__</span> </pre></div><hr size="1"><address style="align: right;"><small> Generated on Fri Apr 17 12:38:48 2015 for gem5 by <a href="http://www.doxygen.org/index.html"> doxygen</a> 1.4.7</small></address> </body> </html>
bsd-3-clause
iiman/mytardis
tardis/tardis_portal/templates/tardis_portal/ajax/dataset_metadata.html
1952
{% load url from future %} {% load capture %} {% if has_write_permissions and not dataset.immutable %} <div class="pull-right"> <a title="Add" href="{% url 'tardis.tardis_portal.views.add_dataset_par' dataset.id %}" class="add-metadata btn btn-primary btn-mini" data-toggle_selector="#dataset_metadata_toggle_{{dataset.id}}"> <i class="icon-plus"></i> Add </a> </div> {% endif %} <h3>Metadata</h3> {% for parameterset in parametersets %} {% capture as edit_control %} {% if has_write_permissions and not parameterset.schema.immutable %} <div class="pull-right"> <a class="edit-metadata btn btn-mini btn-warning" href="{% url 'tardis.tardis_portal.views.edit_dataset_par' parameterset.id %}"> <i class="icon-pencil"></i> Edit </a> </div> {% endif %} {% endcapture %} <div style="margin-top: 10px"> {% with parameters=parameterset.datasetparameter_set.all %} <table class="parameter_table table table-bordered {{ parameterset.schema.name|slugify }}"> <tr> <th class="schema_name" title="{{ parameterset.schema.namespace }} {{ parameterset.schema.immutable|yesno:'(immutable),' }}" colspan="2"> {% if parameterset.schema.name %} {{ parameterset.schema.name }} {% endif %} {% if edit_control %} {{ edit_control }} {% endif %} </th> </tr> {% for parameter in parameters %} <tr> <td class="parameter_name">{{ parameter.name.full_name }}</td> <td class="parameter_value"> {% if parameter.name.isLongString %} {{ parameter.get|linebreaks }} {% else %} {{ parameter.get }} {% endif %} </td> </tr> {% endfor %} </table> {% endwith %} </div> {% empty %} <div class="alert alert-info"> There is no metadata for this dataset. </div> {% endfor %}
bsd-3-clause