code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# just for compatibility; requiring "sha1" is obsoleted # # $RoughId: sha1.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ # $Id: sha1.rb 2062 2006-06-10 19:14:15Z headius $ require 'digest/sha1' SHA1 = Digest::SHA1 class SHA1 def self.sha1(*args) new(*args) end end
nicksieger/advent-jruby
vendor/jruby-1.1.6RC1/lib/ruby/1.8/sha1.rb
Ruby
mit
269
module E.Binary() where import Data.Binary import E.Type import FrontEnd.HsSyn() import Name.Binary() import Support.MapBinaryInstance import {-# SOURCE #-} Info.Binary(putInfo,getInfo) instance Binary TVr where put TVr { tvrIdent = eid, tvrType = e, tvrInfo = nf} = do put eid put e putInfo nf get = do x <- get e <- get nf <- getInfo return $ TVr x e nf instance Data.Binary.Binary RuleType where put RuleSpecialization = do Data.Binary.putWord8 0 put RuleUser = do Data.Binary.putWord8 1 put RuleCatalyst = do Data.Binary.putWord8 2 get = do h <- Data.Binary.getWord8 case h of 0 -> do return RuleSpecialization 1 -> do return RuleUser 2 -> do return RuleCatalyst _ -> fail "invalid binary data found" instance Data.Binary.Binary Rule where put (Rule aa ab ac ad ae af ag ah) = do Data.Binary.put aa putList ab putList ac putLEB128 $ fromIntegral ad Data.Binary.put ae Data.Binary.put af Data.Binary.put ag Data.Binary.put ah get = do aa <- get ab <- getList ac <- getList ad <- fromIntegral `fmap` getLEB128 ae <- get af <- get ag <- get ah <- get return (Rule aa ab ac ad ae af ag ah) instance Data.Binary.Binary ARules where put (ARules aa ab) = do Data.Binary.put aa putList ab get = do aa <- get ab <- getList return (ARules aa ab) instance (Data.Binary.Binary e, Data.Binary.Binary t) => Data.Binary.Binary (Lit e t) where put (LitInt aa ab) = do Data.Binary.putWord8 0 Data.Binary.put aa Data.Binary.put ab put (LitCons ac ad ae af) = do Data.Binary.putWord8 1 Data.Binary.put ac putList ad Data.Binary.put ae Data.Binary.put af get = do h <- Data.Binary.getWord8 case h of 0 -> do aa <- Data.Binary.get ab <- Data.Binary.get return (LitInt aa ab) 1 -> do ac <- Data.Binary.get ad <- getList ae <- Data.Binary.get af <- Data.Binary.get return (LitCons ac ad ae af) _ -> fail "invalid binary data found" instance Data.Binary.Binary ESort where put EStar = do Data.Binary.putWord8 0 put EBang = do Data.Binary.putWord8 1 put EHash = do Data.Binary.putWord8 2 put ETuple = do Data.Binary.putWord8 3 put EHashHash = do Data.Binary.putWord8 4 put EStarStar = do Data.Binary.putWord8 5 put (ESortNamed aa) = do Data.Binary.putWord8 6 Data.Binary.put aa get = do h <- Data.Binary.getWord8 case h of 0 -> do return EStar 1 -> do return EBang 2 -> do return EHash 3 -> do return ETuple 4 -> do return EHashHash 5 -> do return EStarStar 6 -> do aa <- Data.Binary.get return (ESortNamed aa) _ -> fail "invalid binary data found" instance Data.Binary.Binary E where put (EAp aa ab) = do Data.Binary.putWord8 0 Data.Binary.put aa Data.Binary.put ab put (ELam ac ad) = do Data.Binary.putWord8 1 Data.Binary.put ac Data.Binary.put ad put (EPi ae af) = do Data.Binary.putWord8 2 Data.Binary.put ae Data.Binary.put af put (EVar ag) = do Data.Binary.putWord8 3 Data.Binary.put ag put Unknown = do Data.Binary.putWord8 4 put (ESort ah) = do Data.Binary.putWord8 5 Data.Binary.put ah put (ELit ai) = do Data.Binary.putWord8 6 Data.Binary.put ai put (ELetRec aj ak) = do Data.Binary.putWord8 7 putList aj Data.Binary.put ak put (EPrim al am an) = do Data.Binary.putWord8 8 Data.Binary.put al Data.Binary.put am Data.Binary.put an put (EError ao ap) = do Data.Binary.putWord8 9 Data.Binary.put ao Data.Binary.put ap put (ECase aq ar as at au av) = do Data.Binary.putWord8 10 Data.Binary.put aq Data.Binary.put ar Data.Binary.put as putList at Data.Binary.put au Data.Binary.put av get = do h <- Data.Binary.getWord8 case h of 0 -> do aa <- Data.Binary.get ab <- Data.Binary.get return (EAp aa ab) 1 -> do ac <- Data.Binary.get ad <- Data.Binary.get return (ELam ac ad) 2 -> do ae <- Data.Binary.get af <- Data.Binary.get return (EPi ae af) 3 -> do ag <- Data.Binary.get return (EVar ag) 4 -> do return Unknown 5 -> do ah <- Data.Binary.get return (ESort ah) 6 -> do ai <- Data.Binary.get return (ELit ai) 7 -> do aj <- getList ak <- Data.Binary.get return (ELetRec aj ak) 8 -> do al <- Data.Binary.get am <- Data.Binary.get an <- Data.Binary.get return (EPrim al am an) 9 -> do ao <- Data.Binary.get ap <- Data.Binary.get return (EError ao ap) 10 -> do aq <- Data.Binary.get ar <- Data.Binary.get as <- Data.Binary.get at <- getList au <- Data.Binary.get av <- Data.Binary.get return (ECase aq ar as at au av) _ -> fail "invalid binary data found" instance (Data.Binary.Binary e) => Data.Binary.Binary (Alt e) where put (Alt aa ab) = do Data.Binary.put aa Data.Binary.put ab get = do aa <- get ab <- get return (Alt aa ab)
m-alvarez/jhc
src/E/Binary.hs
Haskell
mit
5,542
/*************************************************************************/ /* canvas_layer.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #ifndef CANVAS_LAYER_H #define CANVAS_LAYER_H #include "scene/main/node.h" #include "scene/resources/world_2d.h" class Viewport; class CanvasLayer : public Node { OBJ_TYPE( CanvasLayer, Node ); bool locrotscale_dirty; Vector2 ofs; Vector2 scale; real_t rot; int layer; Matrix32 transform; Ref<World2D> canvas; RID viewport; Viewport *vp; void _set_rotationd(real_t p_rotation); real_t _get_rotationd() const; void _update_xform(); void _update_locrotscale(); protected: void _notification(int p_what); static void _bind_methods(); public: void set_layer(int p_xform); int get_layer() const; void set_transform(const Matrix32& p_xform); Matrix32 get_transform() const; void set_offset(const Vector2& p_offset); Vector2 get_offset() const; void set_rotation(real_t p_rotation); real_t get_rotation() const; void set_scale(const Vector2& p_scale); Vector2 get_scale() const; Ref<World2D> get_world_2d() const; Size2 get_viewport_size() const; RID get_viewport() const; CanvasLayer(); }; #endif // CANVAS_LAYER_H
DustinTriplett/godot
scene/main/canvas_layer.h
C
mit
3,187
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\ProductBundle\Form\Type; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductOptionInterface; use Sylius\Component\Product\Resolver\AvailableProductOptionValuesResolverInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; final class ProductOptionValueChoiceType extends AbstractType { /** @var AvailableProductOptionValuesResolverInterface|null */ private $availableProductOptionValuesResolver; public function __construct(?AvailableProductOptionValuesResolverInterface $availableProductOptionValuesResolver = null) { if (null === $availableProductOptionValuesResolver) { @trigger_error( 'Not passing availableProductOptionValuesResolver thru constructor is deprecated in Sylius 1.8 and ' . 'it will be removed in Sylius 2.0' ); } $this->availableProductOptionValuesResolver = $availableProductOptionValuesResolver; } public function configureOptions(OptionsResolver $resolver): void { $resolver ->setDefaults([ 'choices' => function (Options $options): iterable { $productOption = $options['option']; if (true === $options['only_available_values']) { if (null === $options['product']) { throw new \RuntimeException( 'You must specify the "product" option when "only_available_values" is true.' ); } if (null === $this->availableProductOptionValuesResolver) { throw new \RuntimeException( sprintf( 'Cannot provide only available values in "%s" because a "%s" is required but ' . 'none has been set.', __CLASS__, AvailableProductOptionValuesResolverInterface::class ) ); } return $this->availableProductOptionValuesResolver->resolve( $options['product'], $productOption ); } return $productOption->getValues(); }, 'choice_value' => 'code', 'choice_label' => 'value', 'choice_translation_domain' => false, 'only_available_values' => false, 'product' => null, ]) ->setRequired([ 'option', ]) ->addAllowedTypes('option', [ProductOptionInterface::class]) ->addAllowedTypes('product', ['null', ProductInterface::class]) ; } public function getParent(): string { return ChoiceType::class; } public function getBlockPrefix(): string { return 'sylius_product_option_value_choice'; } }
pjedrzejewski/Sylius
src/Sylius/Bundle/ProductBundle/Form/Type/ProductOptionValueChoiceType.php
PHP
mit
3,559
import Stream from "./stream"; /* Check whether an object is a stream or not @public @for Ember.stream @function isStream @param {Object|Stream} object object to check whether it is a stream @return {Boolean} `true` if the object is a stream, `false` otherwise */ export function isStream(object) { return object && object.isStream; } /* A method of subscribing to a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function subscribe @param {Object|Stream} object object or stream to potentially subscribe to @param {Function} callback function to run when stream value changes @param {Object} [context] the callback will be executed with this context if it is provided */ export function subscribe(object, callback, context) { if (object && object.isStream) { return object.subscribe(callback, context); } } /* A method of unsubscribing from a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function unsubscribe @param {Object|Stream} object object or stream to potentially unsubscribe from @param {Function} callback function originally passed to `subscribe()` @param {Object} [context] object originally passed to `subscribe()` */ export function unsubscribe(object, callback, context) { if (object && object.isStream) { object.unsubscribe(callback, context); } } /* Retrieve the value of a stream, or in the case a non-stream object is passed, return the object itself. @public @for Ember.stream @function read @param {Object|Stream} object object to return the value of @return the stream's current value, or the non-stream object itself */ export function read(object) { if (object && object.isStream) { return object.value(); } else { return object; } } /* Map an array, replacing any streams with their values. @public @for Ember.stream @function readArray @param {Array} array The array to read values from @return {Array} a new array of the same length with the values of non-stream objects mapped from their original positions untouched, and the values of stream objects retaining their original position and replaced with the stream's current value. */ export function readArray(array) { var length = array.length; var ret = new Array(length); for (var i = 0; i < length; i++) { ret[i] = read(array[i]); } return ret; } /* Map a hash, replacing any stream property values with the current value of that stream. @public @for Ember.stream @function readHash @param {Object} object The hash to read keys and values from @return {Object} a new object with the same keys as the passed object. The property values in the new object are the original values in the case of non-stream objects, and the streams' current values in the case of stream objects. */ export function readHash(object) { var ret = {}; for (var key in object) { ret[key] = read(object[key]); } return ret; } /* Check whether an array contains any stream values @public @for Ember.stream @function scanArray @param {Array} array array given to a handlebars helper @return {Boolean} `true` if the array contains a stream/bound value, `false` otherwise */ export function scanArray(array) { var length = array.length; var containsStream = false; for (var i = 0; i < length; i++) { if (isStream(array[i])) { containsStream = true; break; } } return containsStream; } /* Check whether a hash has any stream property values @public @for Ember.stream @function scanHash @param {Object} hash "hash" argument given to a handlebars helper @return {Boolean} `true` if the object contains a stream/bound value, `false` otherwise */ export function scanHash(hash) { var containsStream = false; for (var prop in hash) { if (isStream(hash[prop])) { containsStream = true; break; } } return containsStream; } /* Join an array, with any streams replaced by their current values @public @for Ember.stream @function concat @param {Array} array An array containing zero or more stream objects and zero or more non-stream objects @param {String} separator string to be used to join array elements @return {String} String with array elements concatenated and joined by the provided separator, and any stream array members having been replaced by the current value of the stream */ export function concat(array, separator) { // TODO: Create subclass ConcatStream < Stream. Defer // subscribing to streams until the value() is called. var hasStream = scanArray(array); if (hasStream) { var i, l; var stream = new Stream(function() { return concat(readArray(array), separator); }, function() { var labels = labelsFor(array); return `concat([${labels.join(', ')}]; separator=${inspect(separator)})`; }); for (i = 0, l=array.length; i < l; i++) { subscribe(array[i], stream.notify, stream); } // used by angle bracket components to detect an attribute was provided // as a string literal stream.isConcat = true; return stream; } else { return array.join(separator); } } export function labelsFor(streams) { var labels = []; for (var i=0, l=streams.length; i<l; i++) { var stream = streams[i]; labels.push(labelFor(stream)); } return labels; } export function labelsForObject(streams) { var labels = []; for (var prop in streams) { labels.push(`${prop}: ${inspect(streams[prop])}`); } return labels.length ? `{ ${labels.join(', ')} }` : "{}"; } export function labelFor(maybeStream) { if (isStream(maybeStream)) { var stream = maybeStream; return typeof stream.label === 'function' ? stream.label() : stream.label; } else { return inspect(maybeStream); } } function inspect(value) { switch (typeof value) { case 'string': return `"${value}"`; case 'object': return "{ ... }"; case 'function': return "function() { ... }"; default: return String(value); } } export function or(first, second) { var stream = new Stream(function() { return first.value() || second.value(); }, function() { return `${labelFor(first)} || ${labelFor(second)}`; }); stream.addDependency(first); stream.addDependency(second); return stream; } export function addDependency(stream, dependency) { Ember.assert("Cannot add a stream as a dependency to a non-stream", isStream(stream) || !isStream(dependency)); if (isStream(stream)) { stream.addDependency(dependency); } } export function zip(streams, callback, label) { Ember.assert("Must call zip with a label", !!label); var stream = new Stream(function() { var array = readArray(streams); return callback ? callback(array) : array; }, function() { return `${label}(${labelsFor(streams)})`; }); for (var i=0, l=streams.length; i<l; i++) { stream.addDependency(streams[i]); } return stream; } export function zipHash(object, callback, label) { Ember.assert("Must call zipHash with a label", !!label); var stream = new Stream(function() { var hash = readHash(object); return callback ? callback(hash) : hash; }, function() { return `${label}(${labelsForObject(object)})`; }); for (var prop in object) { stream.addDependency(object[prop]); } return stream; } /** Generate a new stream by providing a source stream and a function that can be used to transform the stream's value. In the case of a non-stream object, returns the result of the function. The value to transform would typically be available to the function you pass to `chain()` via scope. For example: ```javascript var source = ...; // stream returning a number // or a numeric (non-stream) object var result = chain(source, function() { var currentValue = read(source); return currentValue + 1; }); ``` In the example, result is a stream if source is a stream, or a number of source was numeric. @public @for Ember.stream @function chain @param {Object|Stream} value A stream or non-stream object @param {Function} fn function to be run when the stream value changes, or to be run once in the case of a non-stream object @return {Object|Stream} In the case of a stream `value` parameter, a new stream that will be updated with the return value of the provided function `fn`. In the case of a non-stream object, the return value of the provided function `fn`. */ export function chain(value, fn, label) { Ember.assert("Must call chain with a label", !!label); if (isStream(value)) { var stream = new Stream(fn, function() { return `${label}(${labelFor(value)})`; }); stream.addDependency(value); return stream; } else { return fn(); } } export function setValue(object, value) { if (object && object.isStream) { object.setValue(value); } }
thejameskyle/ember.js
packages/ember-metal/lib/streams/utils.js
JavaScript
mit
9,391
<h3>About SlimIt</h3> <p> SlimIt is a JavaScript minifier </p> <h3>Useful Links</h3> <ul> <li><a href="http://pypi.python.org/pypi/slimit">SlimIt @ PyPI</a></li> <li><a href="http://github.com/rspivak/slimit">SlimIt @ GitHub</a></li> </ul> <h3>Author</h3> <p> <a href="http://ruslanspivak.com"> <img src="{{ pathto('_static/feed-24x24.png', 1) }}" alt="blog" /> </a> <a href="http://ca.linkedin.com/in/ruslanspivak"> <img src="{{ pathto('_static/linkedin-24x24.png', 1) }}" alt="linkedin" /> </a> <a href="http://twitter.com/alienoid"> <img src="{{ pathto('_static/twitter-24x24.png', 1) }}" alt="twitter" /> </a> <a href="http://github.com/rspivak"> <img src="{{ pathto('_static/github-24x24.png', 1) }}" alt="github" /> </a> </p>
slideclick/slimit
docs/source/_templates/sidebarintro.html
HTML
mit
770
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("huntercoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
chronokings/huntercoin
src/qt/qrcodedialog.cpp
C++
mit
4,361
import { ViewResources } from 'aurelia-templating'; import { Validator } from '../validator'; import { ValidateResult } from '../validate-result'; import { Rule } from './rule'; import { ValidationMessageProvider } from './validation-messages'; /** * Validates. * Responsible for validating objects and properties. */ export declare class StandardValidator extends Validator { static inject: (typeof ViewResources | typeof ValidationMessageProvider)[]; private messageProvider; private lookupFunctions; private getDisplayName; constructor(messageProvider: ValidationMessageProvider, resources: ViewResources); /** * Validates the specified property. * @param object The object to validate. * @param propertyName The name of the property to validate. * @param rules Optional. If unspecified, the rules will be looked up using the metadata * for the object created by ValidationRules....on(class/object) */ validateProperty(object: any, propertyName: string, rules?: any): Promise<ValidateResult[]>; /** * Validates all rules for specified object and it's properties. * @param object The object to validate. * @param rules Optional. If unspecified, the rules will be looked up using the metadata * for the object created by ValidationRules....on(class/object) */ validateObject(object: any, rules?: any): Promise<ValidateResult[]>; /** * Determines whether a rule exists in a set of rules. * @param rules The rules to search. * @parem rule The rule to find. */ ruleExists(rules: Rule<any, any>[][], rule: Rule<any, any>): boolean; private getMessage(rule, object, value); private validateRuleSequence(object, propertyName, ruleSequence, sequence, results); private validate(object, propertyName, rules); }
manuel-guilbault/aurelia-validation
dist/system/implementation/standard-validator.d.ts
TypeScript
mit
1,838
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class logTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunLogTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; BigInteger bi; // Log Method - Log(1,+Infinity) Assert.Equal(0, BigInteger.Log(1, Double.PositiveInfinity)); // Log Method - Log(1,0) VerifyLogString("0 1 bLog"); // Log Method - Log(0, >1) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 10); VerifyLogString(Print(tempByteArray1) + "0 bLog"); } // Log Method - Log(0, 0>x>1) for (int i = 0; i < s_samples; i++) { Assert.Equal(Double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble())); } // Log Method - base = 0 for (int i = 0; i < s_samples; i++) { bi = 1; while (bi == 1) { bi = new BigInteger(GetRandomPosByteArray(s_random, 8)); } Assert.True((Double.IsNaN(BigInteger.Log(bi, 0)))); } // Log Method - base = 1 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyLogString("1 " + Print(tempByteArray1) + "bLog"); } // Log Method - base = NaN for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.NaN))); } // Log Method - base = +Infinity for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.PositiveInfinity))); } // Log Method - Log(0,1) VerifyLogString("1 0 bLog"); // Log Method - base < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 10); tempByteArray2 = GetRandomNegByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble()))); } // Log Method - value < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomNegByteArray(s_random, 10); tempByteArray2 = GetRandomPosByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); } // Log Method - Small BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10)); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - Large BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100))); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 3); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - one small and one large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 1); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - two large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - Very Large BigInteger 1 << 128 << Int.MaxValue and 2 LargeValueLogTests(128, 1); } [Fact] [OuterLoop] public static void RunLargeValueLogTests() { LargeValueLogTests(0, 5, 64, 4); } /// <summary> /// Test Log Method on Very Large BigInteger more than (1 &lt&lt Int.MaxValue) by base 2 /// Tested BigInteger are: pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit]) /// Note: /// ToString() can not operate such large values /// VerifyLogString() can not operate such large values, /// Math.Log() can not operate such large values /// </summary> private static void LargeValueLogTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1) { BigInteger init = BigInteger.One << startShift; double logbase = 2D; for (int i = 0; i < smallShiftLoopLimit; i++) { BigInteger temp = init << ((i + 1) * smallShift); for (int j = 0; j<bigShiftLoopLimit; j++) { temp = temp << Int32.MaxValue; double expected = (double)startShift + smallShift * (double)(i + 1) + Int32.MaxValue * (double)(j + 1); Assert.True(ApproxEqual(BigInteger.Log(temp, logbase), expected)); } } } private static void VerifyLogString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static Byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; i++) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static Byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } private static bool ApproxEqual(double value1, double value2) { //Special case values; if (Double.IsNaN(value1)) { return Double.IsNaN(value2); } if (Double.IsNegativeInfinity(value1)) { return Double.IsNegativeInfinity(value2); } if (Double.IsPositiveInfinity(value1)) { return Double.IsPositiveInfinity(value2); } if (value2 == 0) { return (value1 == 0); } double result = Math.Abs((value1 / value2) - 1); return (result <= Double.Parse("1e-15")); } } }
mokchhya/corefx
src/System.Runtime.Numerics/tests/BigInteger/log.cs
C#
mit
9,543
<?php /** * Tests for the Diffie-Hellman key exchange implementation in the * OpenID library. * * PHP versions 4 and 5 * * LICENSE: See the COPYING file included in this distribution. * * @package OpenID * @author JanRain, Inc. <[email protected]> * @copyright 2005-2008 Janrain, Inc. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache */ require_once 'PHPUnit.php'; require_once 'Auth/OpenID/DiffieHellman.php'; require_once 'Tests/Auth/OpenID/TestUtil.php'; class Tests_Auth_OpenID_DiffieHellman_CheckCases extends PHPUnit_TestCase { function Tests_Auth_OpenID_DiffieHellman_CheckCases($cases, $n) { $this->cases = $cases; $this->n = $n; } function runTest() { $this->assertEquals($this->n, count($this->cases)); } } class Tests_Auth_OpenID_DiffieHellman_Private extends PHPUnit_TestCase { function Tests_Auth_OpenID_DiffieHellman_Private($name, $input, $expected) { $this->setName("$name"); $this->input = $input; $this->expected = $expected; } function runTest() { $lib =& Auth_OpenID_getMathLib(); $dh = new Auth_OpenID_DiffieHellman(null, null, $this->input); $this->assertEquals($lib->cmp($this->expected, $dh->getPublicKey()), 0); } } class Tests_Auth_OpenID_DiffieHellman_Exch extends PHPUnit_TestCase { function Tests_Auth_OpenID_DiffieHellman_Exch($name, $p1, $p2, $shared) { $this->setName("$name"); $this->p1 = $p1; $this->p2 = $p2; $this->shared = $shared; } function runTest() { $lib =& Auth_OpenID_getMathLib(); $shared = $lib->init($this->shared); $dh1 = new Auth_OpenID_DiffieHellman(null, null, $this->p1); $dh2 = new Auth_OpenID_DiffieHellman(null, null, $this->p2); $sh1 = $dh1->getSharedSecret($dh2->getPublicKey()); $sh2 = $dh2->getSharedSecret($dh1->getPublicKey()); $this->assertEquals($lib->cmp($shared, $sh1), 0); $this->assertEquals($lib->cmp($shared, $sh2), 0); } } class Tests_Auth_OpenID_DiffieHellman extends PHPUnit_TestSuite { function _readPrivateTestCases() { $lines = Tests_Auth_OpenID_readlines('dhpriv'); $cases = array(); foreach ($lines as $line) { $case = array(); if (!preg_match('/^(\d+) (\d+)\n$/', $line, $case)) { trigger_error("Bad test input: $line", E_USER_ERROR); } $c = count($case); if ($c != 3) { trigger_error("Wrong number of elements in parsed case: $c", E_USER_ERROR); } array_shift($case); $cases[] = $case; } return $cases; } function _readExchTestCases() { $lines = Tests_Auth_OpenID_readlines('dhexch'); $cases = array(); foreach ($lines as $line) { $case = array(); if (!preg_match('/^(\d+) (\d+) (\d+)\n$/', $line, $case)) { trigger_error("Bad test input: $line", E_USER_ERROR); } $c = count($case); if ($c != 4) { trigger_error("Wrong number of elements in parsed case: $c", E_USER_ERROR); } array_shift($case); $cases[] = $case; } return $cases; } function Tests_Auth_OpenID_DiffieHellman($name) { $this->setName($name); $priv_cases = Tests_Auth_OpenID_DiffieHellman::_readPrivateTestCases(); $sanity = new Tests_Auth_OpenID_DiffieHellman_CheckCases( $priv_cases, 29); $sanity->setName('Check parsing of priv test data'); $this->addTest($sanity); $exch_cases = Tests_Auth_OpenID_DiffieHellman::_readExchTestCases(); $sanity = new Tests_Auth_OpenID_DiffieHellman_CheckCases( $exch_cases, 25); $sanity->setName('Check parsing of exch test data'); $this->addTest($sanity); if (!defined('Auth_OpenID_NO_MATH_SUPPORT')) { if (defined('Tests_Auth_OpenID_thorough')) { $npriv = count($priv_cases); $nexch = count($exch_cases); } else { $npriv = 1; $nexch = 3; } for ($i = 0; $i < $npriv; $i++) { list($input, $expected) = $priv_cases[$i]; $one = new Tests_Auth_OpenID_DiffieHellman_Private( "DHPriv $i", $input, $expected); $this->addTest($one); } for ($i = 0; $i < $nexch; $i++) { $case = $exch_cases[$i]; $one = new Tests_Auth_OpenID_DiffieHellman_Exch( $i, $case[0], $case[1], $case[2]); $this->addTest($one); } } } } ?>
Symfony-Plugins/ysfOpenPlugin
test/unit/openid/Auth/OpenID/DiffieHellman.php
PHP
mit
4,896
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/Arrows.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_AMS'], { 0x2190: [437,-64,500,64,422], // LEFTWARDS ARROW 0x2192: [437,-64,500,58,417], // RIGHTWARDS ARROW 0x219A: [437,-60,1000,56,942], // LEFTWARDS ARROW WITH STROKE 0x219B: [437,-60,1000,54,942], // RIGHTWARDS ARROW WITH STROKE 0x219E: [417,-83,1000,56,944], // LEFTWARDS TWO HEADED ARROW 0x21A0: [417,-83,1000,55,943], // RIGHTWARDS TWO HEADED ARROW 0x21A2: [417,-83,1111,56,1031], // LEFTWARDS ARROW WITH TAIL 0x21A3: [417,-83,1111,79,1054], // RIGHTWARDS ARROW WITH TAIL 0x21AB: [575,41,1000,56,964], // LEFTWARDS ARROW WITH LOOP 0x21AC: [575,41,1000,35,943], // RIGHTWARDS ARROW WITH LOOP 0x21AD: [417,-83,1389,57,1331], // LEFT RIGHT WAVE ARROW 0x21AE: [437,-60,1000,56,942], // LEFT RIGHT ARROW WITH STROKE 0x21B0: [722,0,500,56,444], // UPWARDS ARROW WITH TIP LEFTWARDS 0x21B1: [722,0,500,55,443], // UPWARDS ARROW WITH TIP RIGHTWARDS 0x21B6: [461,1,1000,17,950], // ANTICLOCKWISE TOP SEMICIRCLE ARROW 0x21B7: [460,1,1000,46,982], // CLOCKWISE TOP SEMICIRCLE ARROW 0x21BA: [650,83,778,56,722], // ANTICLOCKWISE OPEN CIRCLE ARROW 0x21BB: [650,83,778,56,721], // CLOCKWISE OPEN CIRCLE ARROW 0x21BE: [694,194,417,188,375], // UPWARDS HARPOON WITH BARB RIGHTWARDS 0x21BF: [694,194,417,41,228], // UPWARDS HARPOON WITH BARB LEFTWARDS 0x21C2: [694,194,417,188,375], // DOWNWARDS HARPOON WITH BARB RIGHTWARDS 0x21C3: [694,194,417,41,228], // DOWNWARDS HARPOON WITH BARB LEFTWARDS 0x21C4: [667,0,1000,55,944], // RIGHTWARDS ARROW OVER LEFTWARDS ARROW 0x21C6: [667,0,1000,55,944], // LEFTWARDS ARROW OVER RIGHTWARDS ARROW 0x21C7: [583,83,1000,55,944], // LEFTWARDS PAIRED ARROWS 0x21C8: [694,193,833,83,749], // UPWARDS PAIRED ARROWS 0x21C9: [583,83,1000,55,944], // RIGHTWARDS PAIRED ARROWS 0x21CA: [694,194,833,83,749], // DOWNWARDS PAIRED ARROWS 0x21CB: [514,14,1000,55,944], // LEFTWARDS HARPOON OVER RIGHTWARDS HARPOON 0x21CC: [514,14,1000,55,944], // RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON 0x21CD: [534,35,1000,54,942], // LEFTWARDS DOUBLE ARROW WITH STROKE 0x21CE: [534,37,1000,32,965], // LEFT RIGHT DOUBLE ARROW WITH STROKE 0x21CF: [534,35,1000,55,943], // RIGHTWARDS DOUBLE ARROW WITH STROKE 0x21DA: [611,111,1000,76,944], // LEFTWARDS TRIPLE ARROW 0x21DB: [611,111,1000,55,923], // RIGHTWARDS TRIPLE ARROW 0x21DD: [417,-83,1000,56,943], // RIGHTWARDS SQUIGGLE ARROW 0x21E0: [437,-64,1334,64,1251], // LEFTWARDS DASHED ARROW 0x21E2: [437,-64,1334,84,1251] // RIGHTWARDS DASHED ARROW } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/AMS/Regular/Arrows.js");
masterfish2015/my_project
半导体物理/js/mathjax/unpacked/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/Arrows.js
JavaScript
mit
3,734
using System; using System.Diagnostics; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Web; using System.Security; using System.Security.Permissions; namespace umbraco.BusinessLogic.Utils { /// <summary> /// Represents the Umbraco Typeresolver class. /// The typeresolver is a collection of utillities for finding and determining types and classes with reflection. /// </summary> [Serializable] [Obsolete("This class is not longer used and will be removed in future versions")] public class TypeResolver : MarshalByRefObject { /// <summary> /// Gets a collection of assignables of type T from a collection of a specific file type from a specified path. /// </summary> /// <typeparam name="T">The Type</typeparam> /// <param name="path">The path.</param> /// <param name="filePattern">The file pattern.</param> /// <returns></returns> public static string[] GetAssignablesFromType<T>(string path, string filePattern) { FileInfo[] fis = Array.ConvertAll<string, FileInfo>( Directory.GetFiles(path, filePattern), delegate(string s) { return new FileInfo(s); }); string[] absoluteFiles = Array.ConvertAll<FileInfo, string>( fis, delegate(FileInfo fi) { return fi.FullName; }); return GetAssignablesFromType<T>(absoluteFiles); } /// <summary> /// Gets a collection of assignables of type T from a collection of files /// </summary> /// <typeparam name="T"></typeparam> /// <param name="files">The files.</param> /// <returns></returns> public static string[] GetAssignablesFromType<T>(string[] files) { AppDomain sandbox = AppDomain.CurrentDomain; if (Umbraco.Core.SystemUtilities.GetCurrentTrustLevel() == AspNetHostingPermissionLevel.Unrestricted ) { AppDomainSetup domainSetup = new AppDomainSetup(); domainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; domainSetup.ApplicationName = "Umbraco_Sandbox_" + Guid.NewGuid(); domainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; domainSetup.DynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase; domainSetup.LicenseFile = AppDomain.CurrentDomain.SetupInformation.LicenseFile; domainSetup.LoaderOptimization = AppDomain.CurrentDomain.SetupInformation.LoaderOptimization; domainSetup.PrivateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; domainSetup.PrivateBinPathProbe = AppDomain.CurrentDomain.SetupInformation.PrivateBinPathProbe; domainSetup.ShadowCopyFiles = "false"; PermissionSet trustedLoadFromRemoteSourceGrantSet = new PermissionSet(PermissionState.Unrestricted); sandbox = AppDomain.CreateDomain("Sandbox", AppDomain.CurrentDomain.Evidence, domainSetup, trustedLoadFromRemoteSourceGrantSet); // sandbox = AppDomain.CreateDomain("Sandbox", AppDomain.CurrentDomain.Evidence, domainSetup); } try { TypeResolver typeResolver = (TypeResolver)sandbox.CreateInstanceAndUnwrap( typeof(TypeResolver).Assembly.GetName().Name, typeof(TypeResolver).FullName); return typeResolver.GetTypes(typeof(T), files); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { if (Umbraco.Core.SystemUtilities.GetCurrentTrustLevel() == AspNetHostingPermissionLevel.Unrestricted) { AppDomain.Unload(sandbox); } } return new string[0]; } /// <summary> /// Returns of a collection of type names from a collection of assembky files. /// </summary> /// <param name="assignTypeFrom">The assign type.</param> /// <param name="assemblyFiles">The assembly files.</param> /// <returns></returns> public string[] GetTypes(Type assignTypeFrom, string[] assemblyFiles) { List<string> result = new List<string>(); foreach (string fileName in assemblyFiles) { if (!File.Exists(fileName)) continue; try { Assembly assembly = Assembly.LoadFile(fileName); if (assembly != null) { foreach (Type t in assembly.GetExportedTypes()) { if (!t.IsInterface && assignTypeFrom.IsAssignableFrom(t)) result.Add(t.AssemblyQualifiedName); } } } catch (Exception e) { Debug.WriteLine(string.Format("Error loading assembly: {0}\n{1}", fileName, e)); } } return result.ToArray(); } // zb-00044 #29989 : helper method to help injecting services (poor man's ioc) /// <summary> /// Creates an instance of the type indicated by <paramref name="fullName"/> and ensures /// it implements the interface indicated by <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type of the service interface.</typeparam> /// <param name="service">The name of the service we're trying to implement.</param> /// <param name="fullName">The full name of the type implementing the service.</param> /// <returns>A class implementing <typeparamref name="T"/>.</returns> public static T CreateInstance<T>(string service, string fullName) where T : class { // try to get the assembly and type names var parts = fullName.Split(','); if (parts.Length != 2) throw new Exception(string.Format("Can not create instance for '{0}': '{1}' is not a valid type full name.", service, fullName)); string typeName = parts[0]; string assemblyName = parts[1]; T impl; Assembly assembly; Type type; // try to load the assembly try { assembly = Assembly.Load(assemblyName); } catch (Exception e) { throw new Exception(string.Format("Can not create instance for '{0}', failed to load assembly '{1}': {2} was thrown ({3}).", service, assemblyName, e.GetType().FullName, e.Message)); } // try to get the type try { type = assembly.GetType(typeName); } catch (Exception e) { throw new Exception(string.Format("Can not create instance for '{0}': failed to get type '{1}' in assembly '{2}': {3} was thrown ({4}).", service, typeName, assemblyName, e.GetType().FullName, e.Message)); } if (type == null) throw new Exception(string.Format("Can not create instance for '{0}': failed to get type '{1}' in assembly '{2}'.", service, typeName, assemblyName)); // try to instanciate the type try { impl = Activator.CreateInstance(type) as T; } catch (Exception e) { throw new Exception(string.Format("Can not create instance for '{0}': failed to instanciate: {1} was thrown ({2}).", service, e.GetType().FullName, e.Message)); } // ensure it implements the requested type if (impl == null) throw new Exception(string.Format("Can not create instance for '{0}': type '{1}' does not implement '{2}'.", service, fullName, typeof(T).FullName)); return impl; } } }
dampee/Umbraco-CMS
src/umbraco.businesslogic/Utils/TypeResolver.cs
C#
mit
7,946
# -*- coding: utf-8 -*- # This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) from django.contrib.gis.db import models class AOIManager(models.GeoManager): def add_filters(self, **kwargs): """ Returns the queryset with new filters """ return super(AOIManager, self).get_query_set().filter(**kwargs) def unassigned(self): """ Returns unassigned AOIs. """ return self.add_filters(status='Unassigned') def assigned(self): """ Returns assigned AOIs. """ return self.add_filters(status='Assigned') def in_work(self): """ Returns AOIs in work. """ return self.add_filters(status='In Work') def submitted(self): """ Returns submitted AOIs. """ return self.add_filters(status='Submitted') def completed(self): """ Returns completed AOIs. """ return self.add_filters(status='Completed')
stephenrjones/geoq
geoq/core/managers.py
Python
mit
1,155
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_raw_socket::async_send (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../async_send.html" title="basic_raw_socket::async_send"> <link rel="prev" href="../async_send.html" title="basic_raw_socket::async_send"> <link rel="next" href="overload2.html" title="basic_raw_socket::async_send (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../async_send.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../async_send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_raw_socket.async_send.overload1"></a><a class="link" href="overload1.html" title="basic_raw_socket::async_send (1 of 2 overloads)">basic_raw_socket::async_send (1 of 2 overloads)</a> </h5></div></div></div> <p> Start an asynchronous send on a connected socket. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="../../WriteHandler.html" title="Write handler requirements">WriteHandler</a><span class="special">&gt;</span> <a class="link" href="../../asynchronous_operations.html#boost_asio.reference.asynchronous_operations.return_type_of_an_initiating_function"><span class="emphasis"><em>void-or-deduced</em></span></a> <span class="identifier">async_send</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">WriteHandler</span> <span class="identifier">handler</span><span class="special">);</span> </pre> <p> This function is used to send data on the raw socket. The function call will block until the data has been sent successfully or an error occurs. </p> <h6> <a name="boost_asio.reference.basic_raw_socket.async_send.overload1.h0"></a> <span class="phrase"><a name="boost_asio.reference.basic_raw_socket.async_send.overload1.parameters"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_raw_socket.async_send.overload1.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl class="variablelist"> <dt><span class="term">buffers</span></dt> <dd><p> One or more data buffers to be sent on the socket. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called. </p></dd> <dt><span class="term">handler</span></dt> <dd> <p> The handler to be called when the send operation completes. Copies will be made of the handler as required. The function signature of the handler must be: </p> <pre class="programlisting"><span class="keyword">void</span> <span class="identifier">handler</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span><span class="special">&amp;</span> <span class="identifier">error</span><span class="special">,</span> <span class="comment">// Result of operation.</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">bytes_transferred</span> <span class="comment">// Number of bytes sent.</span> <span class="special">);</span> </pre> <p> Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">::</span><span class="identifier">post</span><span class="special">()</span></code>. </p> </dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_raw_socket.async_send.overload1.h1"></a> <span class="phrase"><a name="boost_asio.reference.basic_raw_socket.async_send.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_raw_socket.async_send.overload1.remarks">Remarks</a> </h6> <p> The async_send operation can only be used with a connected socket. Use the async_send_to function to send data on an unconnected raw socket. </p> <h6> <a name="boost_asio.reference.basic_raw_socket.async_send.overload1.h2"></a> <span class="phrase"><a name="boost_asio.reference.basic_raw_socket.async_send.overload1.example"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_raw_socket.async_send.overload1.example">Example</a> </h6> <p> To send a single data buffer use the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> function as follows: </p> <pre class="programlisting"><span class="identifier">socket</span><span class="special">.</span><span class="identifier">async_send</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">buffer</span><span class="special">(</span><span class="identifier">data</span><span class="special">,</span> <span class="identifier">size</span><span class="special">),</span> <span class="identifier">handler</span><span class="special">);</span> </pre> <p> See the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> documentation for information on sending multiple buffers in one go, and how to use it with arrays, boost::array or std::vector. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2014 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../async_send.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../async_send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
rkq/cxxexp
third-party/src/boost_1_56_0/doc/html/boost_asio/reference/basic_raw_socket/async_send/overload1.html
HTML
mit
8,903
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Stream ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; using System.Threading; using System.Runtime.InteropServices; //using System.Runtime.Remoting.Messaging; using System.Security; using System.Security.Permissions; namespace System.IO { [Serializable()] public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); public abstract bool CanRead { get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { get; } public virtual bool CanTimeout { get { return false; } } public abstract bool CanWrite { get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } set { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } } public virtual int WriteTimeout { get { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } set { #if EXCEPTION_STRINGS throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_TimeoutsNotSupported" ) ); #else throw new InvalidOperationException(); #endif } } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { Dispose( true ); GC.SuppressFinalize( this ); } public void Dispose() { Close(); } protected virtual void Dispose( bool disposing ) { //// // Note: Never change this to call other virtual methods on Stream //// // like Write, since the state on subclasses has already been //// // torn down. This is the last code to run on cleanup for a stream. //// if((disposing) && (_asyncActiveEvent != null)) //// _CloseAsyncActiveEvent( Interlocked.Decrement( ref _asyncActiveCount ) ); } //// private void _CloseAsyncActiveEvent( int asyncActiveCount ) //// { //// BCLDebug.Assert( _asyncActiveCount >= 0, "ref counting mismatch, possible race in the code" ); //// //// // If no pending async IO, close the event //// if((_asyncActiveEvent != null) && (asyncActiveCount == 0)) //// { //// _asyncActiveEvent.Close(); //// _asyncActiveEvent = null; //// } //// } public abstract void Flush(); [Obsolete( "CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead." )] protected virtual WaitHandle CreateWaitHandle() { return new ManualResetEvent( false ); } [HostProtection( ExternalThreading = true )] public virtual IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { if(!CanRead) __Error.ReadNotSupported(); // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult = new SynchronousAsyncResult( state, false ); try { int numRead = Read( buffer, offset, count ); asyncResult._numRead = numRead; if(callback != null) callback( asyncResult ); } catch(IOException e) { asyncResult._exception = e; } finally { asyncResult._isCompleted = true; asyncResult._waitHandle.Set(); } return asyncResult; } public virtual int EndRead( IAsyncResult asyncResult ) { if(asyncResult == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "asyncResult" ); #else throw new ArgumentNullException(); #endif SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if(ar == null || ar.IsWrite) __Error.WrongAsyncResult(); if(ar._EndXxxCalled) __Error.EndReadCalledTwice(); ar._EndXxxCalled = true; if(ar._exception != null) throw ar._exception; return ar._numRead; } [HostProtection( ExternalThreading = true )] public virtual IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { if(!CanWrite) __Error.WriteNotSupported(); // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult = new SynchronousAsyncResult( state, true ); try { Write( buffer, offset, count ); if(callback != null) callback( asyncResult ); } catch(IOException e) { asyncResult._exception = e; } finally { asyncResult._isCompleted = true; asyncResult._waitHandle.Set(); } return asyncResult; } public virtual void EndWrite( IAsyncResult asyncResult ) { if(asyncResult == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "asyncResult" ); #else throw new ArgumentNullException(); #endif SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if(ar == null || !ar.IsWrite) __Error.WrongAsyncResult(); if(ar._EndXxxCalled) __Error.EndWriteCalledTwice(); ar._EndXxxCalled = true; if(ar._exception != null) throw ar._exception; } public abstract long Seek( long offset, SeekOrigin origin ); public abstract void SetLength( long value ); public abstract int Read( [In, Out] byte[] buffer, int offset, int count ); // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { byte[] oneByteArray = new byte[1]; int r = Read( oneByteArray, 0, 1 ); if(r == 0) return -1; return oneByteArray[0]; } public abstract void Write( byte[] buffer, int offset, int count ); // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte( byte value ) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write( oneByteArray, 0, 1 ); } [HostProtection( Synchronization = true )] public static Stream Synchronized( Stream stream ) { if(stream == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream" ); #else throw new ArgumentNullException(); #endif if(stream is SyncStream) return stream; return new SyncStream( stream ); } [Serializable] private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return true; } } public override bool CanSeek { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } // No need to override Close public override void Flush() { } public override int Read( [In, Out] byte[] buffer, int offset, int count ) { return 0; } public override int ReadByte() { return -1; } public override void Write( byte[] buffer, int offset, int count ) { } public override void WriteByte( byte value ) { } public override long Seek( long offset, SeekOrigin origin ) { return 0; } public override void SetLength( long length ) { } } // Used as the IAsyncResult object when using asynchronous IO methods // on the base Stream class. Note I'm not using async delegates, so // this is necessary. private sealed class SynchronousAsyncResult : IAsyncResult { internal ManualResetEvent _waitHandle; internal Object _stateObject; internal int _numRead; internal bool _isCompleted; internal bool _isWrite; internal bool _EndXxxCalled; internal Exception _exception; internal SynchronousAsyncResult( Object asyncStateObject, bool isWrite ) { _stateObject = asyncStateObject; _isWrite = isWrite; _waitHandle = new ManualResetEvent( false ); } public bool IsCompleted { get { return _isCompleted; } } public WaitHandle AsyncWaitHandle { get { return _waitHandle; } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal bool IsWrite { get { return _isWrite; } } } // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. [Serializable()] internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; internal SyncStream( Stream stream ) { if(stream == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "stream" ); #else throw new ArgumentNullException(); #endif _stream = stream; } public override bool CanRead { get { return _stream.CanRead; } } public override bool CanWrite { get { return _stream.CanWrite; } } public override bool CanSeek { get { return _stream.CanSeek; } } public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { lock(_stream) { return _stream.Length; } } } public override long Position { get { lock(_stream) { return _stream.Position; } } set { lock(_stream) { _stream.Position = value; } } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock(_stream) { try { _stream.Close(); } finally { base.Dispose( true ); } } } protected override void Dispose( bool disposing ) { lock(_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if(disposing) { ((IDisposable)_stream).Dispose(); } } finally { base.Dispose( disposing ); } } } public override void Flush() { lock(_stream) { _stream.Flush(); } } public override int Read( [In, Out]byte[] bytes, int offset, int count ) { lock(_stream) { return _stream.Read( bytes, offset, count ); } } public override int ReadByte() { lock(_stream) { return _stream.ReadByte(); } } [HostProtection( ExternalThreading = true )] public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { lock(_stream) { return _stream.BeginRead( buffer, offset, count, callback, state ); } } public override int EndRead( IAsyncResult asyncResult ) { lock(_stream) { return _stream.EndRead( asyncResult ); } } public override long Seek( long offset, SeekOrigin origin ) { lock(_stream) { return _stream.Seek( offset, origin ); } } public override void SetLength( long length ) { lock(_stream) { _stream.SetLength( length ); } } public override void Write( byte[] bytes, int offset, int count ) { lock(_stream) { _stream.Write( bytes, offset, count ); } } public override void WriteByte( byte b ) { lock(_stream) { _stream.WriteByte( b ); } } [HostProtection( ExternalThreading = true )] public override IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, Object state ) { lock(_stream) { return _stream.BeginWrite( buffer, offset, count, callback, state ); } } public override void EndWrite( IAsyncResult asyncResult ) { lock(_stream) { _stream.EndWrite( asyncResult ); } } } } }
smaillet-ms/llilum
Zelig/Zelig/RunTime/Framework/mscorlib/System/IO/Stream.cs
C#
mit
19,739
# Taken from https://gist.github.com/238158/487a411c392e1fb2a0c00347e32444320f5cdd49 module ActiveResource # # The FakeResource fakes ActiveResources so that no real resources are transferred. It catches the creation methods # and stores the resources internally instead of sending to a remote service and responds these resources back on # request. # # Additionally it adds a save! method and can be used in conjunction with Cucumber/Pickle/FactoryGirl to fully # fake a back end service in the BDD cycle # module FakeResource extend ActiveSupport::Concern @@fake_resources = [] @@enabled = false def self.enable @@enabled = true end def self.disable @@enabled = false self.clean end def self.clean FakeWeb.clean_registry @@fake_resources = [] end included do def save_with_fake_resource if @@enabled @@fake_resources << self update_fake_responses else save_without_fake_resource end end alias_method_chain :save, :fake_resource def destroy_with_fake_resource if @@enabled @@fake_resources.delete(self) update_fake_responses else destroy_without_fake_resource end end alias_method_chain :destroy, :fake_resource def self.delete(id, options = {}) if @@enabled @@fake_resources.delete_if {|r| r.id == id } #update_fake_responses else super end end def self.exists?(id, options = {}) if @@enabled not @@fake_resources.select {|r| r.id == id}.blank? else super end end end def save! if @@enabled save else super end end private def update_fake_responses FakeWeb.clean_registry @@fake_resources.each do |r| FakeWeb.register_uri(:get, element_uri, :body => r.to_xml) end FakeWeb.register_uri(:get, collection_uri, :body => @@fake_resources.to_xml) end def element_uri "#{base_uri}#{element_path}" end def collection_uri "#{base_uri}#{collection_path}" end def base_uri "#{connection.site.scheme}://#{connection.user}:#{connection.password}@#{connection.site.host}:#{connection.site.port}" end end end
chase439/chargify_api_ares
spec/support/fake_resource.rb
Ruby
mit
2,402
/**************************************************************************** ** Meta object code from reading C++ file 'client.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../include/client.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'client.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_ONVIF__Client_t { QByteArrayData data[1]; char stringdata[14]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ONVIF__Client_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ONVIF__Client_t qt_meta_stringdata_ONVIF__Client = { { QT_MOC_LITERAL(0, 0, 13) // "ONVIF::Client" }, "ONVIF::Client" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ONVIF__Client[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void ONVIF::Client::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject ONVIF::Client::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_ONVIF__Client.data, qt_meta_data_ONVIF__Client, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *ONVIF::Client::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ONVIF::Client::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_ONVIF__Client.stringdata)) return static_cast<void*>(const_cast< Client*>(this)); return QObject::qt_metacast(_clname); } int ONVIF::Client::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
xiaojuntong/opencvr
3rdparty/onvifc/win32/GeneratedFiles/Release/moc_client.cpp
C++
mit
2,654
""" Support for EnOcean binary sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/binary_sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( BinarySensorDevice, PLATFORM_SCHEMA, SENSOR_CLASSES_SCHEMA) from homeassistant.components import enocean from homeassistant.const import (CONF_NAME, CONF_ID, CONF_SENSOR_CLASS) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['enocean'] DEFAULT_NAME = 'EnOcean binary sensor' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ID): vol.All(cv.ensure_list, [vol.Coerce(int)]), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SENSOR_CLASS, default=None): SENSOR_CLASSES_SCHEMA, }) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Binary Sensor platform fo EnOcean.""" dev_id = config.get(CONF_ID) devname = config.get(CONF_NAME) sensor_class = config.get(CONF_SENSOR_CLASS) add_devices([EnOceanBinarySensor(dev_id, devname, sensor_class)]) class EnOceanBinarySensor(enocean.EnOceanDevice, BinarySensorDevice): """Representation of EnOcean binary sensors such as wall switches.""" def __init__(self, dev_id, devname, sensor_class): """Initialize the EnOcean binary sensor.""" enocean.EnOceanDevice.__init__(self) self.stype = "listener" self.dev_id = dev_id self.which = -1 self.onoff = -1 self.devname = devname self._sensor_class = sensor_class @property def name(self): """The default name for the binary sensor.""" return self.devname @property def sensor_class(self): """Return the class of this sensor.""" return self._sensor_class def value_changed(self, value, value2): """Fire an event with the data that have changed. This method is called when there is an incoming packet associated with this platform. """ self.update_ha_state() if value2 == 0x70: self.which = 0 self.onoff = 0 elif value2 == 0x50: self.which = 0 self.onoff = 1 elif value2 == 0x30: self.which = 1 self.onoff = 0 elif value2 == 0x10: self.which = 1 self.onoff = 1 self.hass.bus.fire('button_pressed', {"id": self.dev_id, 'pushed': value, 'which': self.which, 'onoff': self.onoff})
xifle/home-assistant
homeassistant/components/binary_sensor/enocean.py
Python
mit
2,747
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*++ Module Name: directory.c Abstract: Implementation of the file WIN API for the PAL Revision History: --*/ #include "pal/palinternal.h" #include "pal/dbgmsg.h" #include "pal/file.h" #include "pal/stackstring.hpp" #include <stdlib.h> #include <sys/param.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> SET_DEFAULT_DEBUG_CHANNEL(FILE); /*++ Function: CreateDirectoryW Note: lpSecurityAttributes always NULL. See MSDN doc. --*/ BOOL PALAPI CreateDirectoryW( IN LPCWSTR lpPathName, IN LPSECURITY_ATTRIBUTES lpSecurityAttributes) { BOOL bRet = FALSE; DWORD dwLastError = 0; int mb_size; char *mb_dir = NULL; PERF_ENTRY(CreateDirectoryW); ENTRY("CreateDirectoryW(lpPathName=%p (%S), lpSecurityAttr=%p)\n", lpPathName?lpPathName:W16_NULLSTRING, lpPathName?lpPathName:W16_NULLSTRING, lpSecurityAttributes); if ( lpSecurityAttributes ) { ASSERT("lpSecurityAttributes is not NULL as it should be\n"); dwLastError = ERROR_INVALID_PARAMETER; goto done; } /* translate the wide char lpPathName string to multibyte string */ if(0 == (mb_size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, NULL, 0, NULL, NULL ))) { ASSERT("WideCharToMultiByte failure! error is %d\n", GetLastError()); dwLastError = ERROR_INTERNAL_ERROR; goto done; } if (((mb_dir = (char *)PAL_malloc(mb_size)) == NULL) || (WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, mb_dir, mb_size, NULL, NULL) != mb_size)) { ASSERT("WideCharToMultiByte or PAL_malloc failure! LastError:%d errno:%d\n", GetLastError(), errno); dwLastError = ERROR_INTERNAL_ERROR; goto done; } bRet = CreateDirectoryA(mb_dir,NULL); done: if( dwLastError ) { SetLastError( dwLastError ); } if (mb_dir != NULL) { PAL_free(mb_dir); } LOGEXIT("CreateDirectoryW returns BOOL %d\n", bRet); PERF_EXIT(CreateDirectoryW); return bRet; } /*++ Routine Name: RemoveDirectoryHelper Routine Description: Core function which removes a directory. Called by RemoveDirectory[AW] Parameters: LPSTR lpPathName - [in/out] The directory name to remove. It is converted in place to a unix path. Return Value: BOOL - TRUE <=> successful --*/ static BOOL RemoveDirectoryHelper ( LPSTR lpPathName, LPDWORD dwLastError ) { BOOL bRet = FALSE; *dwLastError = 0; FILEDosToUnixPathA( lpPathName ); if ( !FILEGetFileNameFromSymLink(lpPathName)) { FILEGetProperNotFoundError( lpPathName, dwLastError ); goto done; } if ( rmdir(lpPathName) != 0 ) { TRACE("Removal of directory [%s] was unsuccessful, errno = %d.\n", lpPathName, errno); switch( errno ) { case ENOTDIR: /* FALL THROUGH */ case ENOENT: { struct stat stat_data; if ( stat( lpPathName, &stat_data) == 0 && (stat_data.st_mode & S_IFMT) == S_IFREG ) { /* Not a directory, it is a file. */ *dwLastError = ERROR_DIRECTORY; } else { FILEGetProperNotFoundError( lpPathName, dwLastError ); } break; } case ENOTEMPTY: *dwLastError = ERROR_DIR_NOT_EMPTY; break; default: *dwLastError = ERROR_ACCESS_DENIED; } } else { TRACE("Removal of directory [%s] was successful.\n", lpPathName); bRet = TRUE; } done: return bRet; } /*++ Function: RemoveDirectoryA See MSDN doc. --*/ BOOL PALAPI RemoveDirectoryA( IN LPCSTR lpPathName) { DWORD dwLastError = 0; BOOL bRet = FALSE; PathCharString mb_dirPathString; size_t length; char * mb_dir; PERF_ENTRY(RemoveDirectoryA); ENTRY("RemoveDirectoryA(lpPathName=%p (%s))\n", lpPathName, lpPathName); if (lpPathName == NULL) { dwLastError = ERROR_PATH_NOT_FOUND; goto done; } length = strlen(lpPathName); mb_dir = mb_dirPathString.OpenStringBuffer(length); if (NULL == mb_dir) { dwLastError = ERROR_NOT_ENOUGH_MEMORY; goto done; } if (strncpy_s (mb_dir, sizeof(char) * (length+1), lpPathName, MAX_LONGPATH) != SAFECRT_SUCCESS) { mb_dirPathString.CloseBuffer(length); WARN("mb_dir is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH); dwLastError = ERROR_FILENAME_EXCED_RANGE; goto done; } mb_dirPathString.CloseBuffer(length); bRet = RemoveDirectoryHelper (mb_dir, &dwLastError); done: if( dwLastError ) { SetLastError( dwLastError ); } LOGEXIT("RemoveDirectoryA returns BOOL %d\n", bRet); PERF_EXIT(RemoveDirectoryA); return bRet; } /*++ Function: RemoveDirectoryW See MSDN doc. --*/ BOOL PALAPI RemoveDirectoryW( IN LPCWSTR lpPathName) { PathCharString mb_dirPathString; int mb_size; DWORD dwLastError = 0; BOOL bRet = FALSE; size_t length; char * mb_dir; PERF_ENTRY(RemoveDirectoryW); ENTRY("RemoveDirectoryW(lpPathName=%p (%S))\n", lpPathName?lpPathName:W16_NULLSTRING, lpPathName?lpPathName:W16_NULLSTRING); if (lpPathName == NULL) { dwLastError = ERROR_PATH_NOT_FOUND; goto done; } length = (PAL_wcslen(lpPathName)+1) * 3; mb_dir = mb_dirPathString.OpenStringBuffer(length); if (NULL == mb_dir) { dwLastError = ERROR_NOT_ENOUGH_MEMORY; goto done; } mb_size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, mb_dir, length, NULL, NULL ); mb_dirPathString.CloseBuffer(mb_size); if( mb_size == 0 ) { dwLastError = GetLastError(); if( dwLastError == ERROR_INSUFFICIENT_BUFFER ) { WARN("lpPathName is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH); dwLastError = ERROR_FILENAME_EXCED_RANGE; } else { ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); dwLastError = ERROR_INTERNAL_ERROR; } goto done; } if ((bRet = RemoveDirectoryHelper (mb_dir, &dwLastError))) { TRACE("Removal of directory [%s] was successful.\n", mb_dir); } done: if( dwLastError ) { SetLastError( dwLastError ); } LOGEXIT("RemoveDirectoryW returns BOOL %d\n", bRet); PERF_EXIT(RemoveDirectoryW); return bRet; } /*++ Function: GetCurrentDirectoryA See MSDN doc. --*/ DWORD PALAPI GetCurrentDirectoryA( IN DWORD nBufferLength, OUT LPSTR lpBuffer) { DWORD dwDirLen = 0; DWORD dwLastError = 0; char *current_dir; PERF_ENTRY(GetCurrentDirectoryA); ENTRY("GetCurrentDirectoryA(nBufferLength=%u, lpBuffer=%p)\n", nBufferLength, lpBuffer); /* NULL first arg means getcwd will allocate the string */ current_dir = PAL__getcwd( NULL, MAX_LONGPATH + 1 ); if ( !current_dir ) { WARN( "PAL__getcwd returned NULL\n" ); dwLastError = DIRGetLastErrorFromErrno(); goto done; } dwDirLen = strlen( current_dir ); /* if the supplied buffer isn't long enough, return the required length, including room for the NULL terminator */ if ( nBufferLength <= dwDirLen ) { ++dwDirLen; /* include space for the NULL */ goto done; } else { strcpy_s( lpBuffer, nBufferLength, current_dir ); } done: PAL_free( current_dir ); if ( dwLastError ) { SetLastError(dwLastError); } LOGEXIT("GetCurrentDirectoryA returns DWORD %u\n", dwDirLen); PERF_EXIT(GetCurrentDirectoryA); return dwDirLen; } /*++ Function: GetCurrentDirectoryW See MSDN doc. --*/ DWORD PALAPI GetCurrentDirectoryW( IN DWORD nBufferLength, OUT LPWSTR lpBuffer) { DWORD dwWideLen = 0; DWORD dwLastError = 0; char *current_dir; int dir_len; PERF_ENTRY(GetCurrentDirectoryW); ENTRY("GetCurrentDirectoryW(nBufferLength=%u, lpBuffer=%p)\n", nBufferLength, lpBuffer); current_dir = PAL__getcwd( NULL, MAX_LONGPATH + 1 ); if ( !current_dir ) { WARN( "PAL__getcwd returned NULL\n" ); dwLastError = DIRGetLastErrorFromErrno(); goto done; } dir_len = strlen( current_dir ); dwWideLen = MultiByteToWideChar( CP_ACP, 0, current_dir, dir_len, NULL, 0 ); /* if the supplied buffer isn't long enough, return the required length, including room for the NULL terminator */ if ( nBufferLength > dwWideLen ) { if(!MultiByteToWideChar( CP_ACP, 0, current_dir, dir_len + 1, lpBuffer, nBufferLength )) { ASSERT("MultiByteToWideChar failure!\n"); dwWideLen = 0; dwLastError = ERROR_INTERNAL_ERROR; } } else { ++dwWideLen; /* include space for the NULL */ } done: PAL_free( current_dir ); if ( dwLastError ) { SetLastError(dwLastError); } LOGEXIT("GetCurrentDirectoryW returns DWORD %u\n", dwWideLen); PERF_EXIT(GetCurrentDirectoryW); return dwWideLen; } /*++ Function: SetCurrentDirectoryW See MSDN doc. --*/ BOOL PALAPI SetCurrentDirectoryW( IN LPCWSTR lpPathName) { BOOL bRet; DWORD dwLastError = 0; PathCharString dirPathString; int size; size_t length; char * dir; PERF_ENTRY(SetCurrentDirectoryW); ENTRY("SetCurrentDirectoryW(lpPathName=%p (%S))\n", lpPathName?lpPathName:W16_NULLSTRING, lpPathName?lpPathName:W16_NULLSTRING); /*check if the given path is null. If so return FALSE*/ if (lpPathName == NULL ) { ERROR("Invalid path/directory name\n"); dwLastError = ERROR_INVALID_NAME; bRet = FALSE; goto done; } length = (PAL_wcslen(lpPathName)+1) * 3; dir = dirPathString.OpenStringBuffer(length); if (NULL == dir) { dwLastError = ERROR_NOT_ENOUGH_MEMORY; bRet = FALSE; goto done; } size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, dir, length, NULL, NULL ); dirPathString.CloseBuffer(size); if( size == 0 ) { dwLastError = GetLastError(); if( dwLastError == ERROR_INSUFFICIENT_BUFFER ) { WARN("lpPathName is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH); dwLastError = ERROR_FILENAME_EXCED_RANGE; } else { ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); dwLastError = ERROR_INTERNAL_ERROR; } bRet = FALSE; goto done; } bRet = SetCurrentDirectoryA(dir); done: if( dwLastError ) { SetLastError(dwLastError); } LOGEXIT("SetCurrentDirectoryW returns BOOL %d\n", bRet); PERF_EXIT(SetCurrentDirectoryW); return bRet; } /*++ Function: CreateDirectoryA Note: lpSecurityAttributes always NULL. See MSDN doc. --*/ BOOL PALAPI CreateDirectoryA( IN LPCSTR lpPathName, IN LPSECURITY_ATTRIBUTES lpSecurityAttributes) { BOOL bRet = FALSE; DWORD dwLastError = 0; char *realPath; LPSTR UnixPathName = NULL; int pathLength; int i; const int mode = S_IRWXU | S_IRWXG | S_IRWXO; PERF_ENTRY(CreateDirectoryA); ENTRY("CreateDirectoryA(lpPathName=%p (%s), lpSecurityAttr=%p)\n", lpPathName?lpPathName:"NULL", lpPathName?lpPathName:"NULL", lpSecurityAttributes); if ( lpSecurityAttributes ) { ASSERT("lpSecurityAttributes is not NULL as it should be\n"); dwLastError = ERROR_INVALID_PARAMETER; goto done; } // Windows returns ERROR_PATH_NOT_FOUND when called with NULL. // If we don't have this check, strdup(NULL) segfaults. if (lpPathName == NULL) { ERROR("CreateDirectoryA called with NULL pathname!\n"); dwLastError = ERROR_PATH_NOT_FOUND; goto done; } UnixPathName = PAL__strdup(lpPathName); if (UnixPathName == NULL ) { ERROR("PAL__strdup() failed\n"); dwLastError = ERROR_NOT_ENOUGH_MEMORY; goto done; } FILEDosToUnixPathA( UnixPathName ); // Remove any trailing slashes at the end because mkdir might not // handle them appropriately on all platforms. pathLength = strlen(UnixPathName); i = pathLength; while(i > 1) { if(UnixPathName[i - 1] =='/') { UnixPathName[i - 1]='\0'; i--; } else { break; } } // Check the constraint for the real path length (should be < MAX_LONGPATH). // Get an absolute path. if (UnixPathName[0] == '/') { realPath = UnixPathName; } else { const char *cwd = PAL__getcwd(NULL, MAX_LONGPATH); if (NULL == cwd) { WARN("Getcwd failed with errno=%d [%s]\n", errno, strerror(errno)); dwLastError = DIRGetLastErrorFromErrno(); goto done; } // Copy cwd, '/', path int iLen = strlen(cwd) + 1 + pathLength + 1; realPath = static_cast<char *>(alloca(iLen)); sprintf_s(realPath, iLen, "%s/%s", cwd, UnixPathName); PAL_free((char *)cwd); } // Canonicalize the path so we can determine its length. FILECanonicalizePath(realPath); if (strlen(realPath) >= MAX_LONGPATH) { WARN("UnixPathName is larger than MAX_LONGPATH (%d)!\n", MAX_LONGPATH); dwLastError = ERROR_FILENAME_EXCED_RANGE; goto done; } if ( mkdir(realPath, mode) != 0 ) { TRACE("Creation of directory [%s] was unsuccessful, errno = %d.\n", UnixPathName, errno); switch( errno ) { case ENOTDIR: /* FALL THROUGH */ case ENOENT: FILEGetProperNotFoundError( realPath, &dwLastError ); goto done; case EEXIST: dwLastError = ERROR_ALREADY_EXISTS; break; default: dwLastError = ERROR_ACCESS_DENIED; } } else { TRACE("Creation of directory [%s] was successful.\n", UnixPathName); bRet = TRUE; } done: if( dwLastError ) { SetLastError( dwLastError ); } PAL_free( UnixPathName ); LOGEXIT("CreateDirectoryA returns BOOL %d\n", bRet); PERF_EXIT(CreateDirectoryA); return bRet; } /*++ Function: SetCurrentDirectoryA See MSDN doc. --*/ BOOL PALAPI SetCurrentDirectoryA( IN LPCSTR lpPathName) { BOOL bRet = FALSE; DWORD dwLastError = 0; int result; LPSTR UnixPathName = NULL; PERF_ENTRY(SetCurrentDirectoryA); ENTRY("SetCurrentDirectoryA(lpPathName=%p (%s))\n", lpPathName?lpPathName:"NULL", lpPathName?lpPathName:"NULL"); /*check if the given path is null. If so return FALSE*/ if (lpPathName == NULL ) { ERROR("Invalid path/directory name\n"); dwLastError = ERROR_INVALID_NAME; goto done; } if (strlen(lpPathName) >= MAX_LONGPATH) { WARN("Path/directory name longer than MAX_LONGPATH characters\n"); dwLastError = ERROR_FILENAME_EXCED_RANGE; goto done; } UnixPathName = PAL__strdup(lpPathName); if (UnixPathName == NULL ) { ERROR("PAL__strdup() failed\n"); dwLastError = ERROR_NOT_ENOUGH_MEMORY; goto done; } FILEDosToUnixPathA( UnixPathName ); TRACE("Attempting to open Unix dir [%s]\n", UnixPathName); result = chdir(UnixPathName); if ( result == 0 ) { bRet = TRUE; } else { if ( errno == ENOTDIR || errno == ENOENT ) { struct stat stat_data; if ( stat( UnixPathName, &stat_data) == 0 && (stat_data.st_mode & S_IFMT) == S_IFREG ) { /* Not a directory, it is a file. */ dwLastError = ERROR_DIRECTORY; } else { FILEGetProperNotFoundError( UnixPathName, &dwLastError ); } TRACE("chdir() failed, path was invalid.\n"); } else { dwLastError = ERROR_ACCESS_DENIED; ERROR("chdir() failed; errno is %d (%s)\n", errno, strerror(errno)); } } done: if( dwLastError ) { SetLastError(dwLastError); } if(UnixPathName != NULL) { PAL_free( UnixPathName ); } LOGEXIT("SetCurrentDirectoryA returns BOOL %d\n", bRet); PERF_EXIT(SetCurrentDirectoryA); return bRet; }
sperling/coreclr
src/pal/src/file/directory.cpp
C++
mit
17,336
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Azure.Management.DataLake.Analytics; using Newtonsoft.Json; using System.Linq; /// <summary> /// A Data Lake Analytics catalog U-SQL table valued function item. /// </summary> public partial class USqlTableValuedFunction : CatalogItem { /// <summary> /// Initializes a new instance of the USqlTableValuedFunction class. /// </summary> public USqlTableValuedFunction() { CustomInit(); } /// <summary> /// Initializes a new instance of the USqlTableValuedFunction class. /// </summary> /// <param name="computeAccountName">the name of the Data Lake /// Analytics account.</param> /// <param name="version">the version of the catalog item.</param> /// <param name="databaseName">the name of the database.</param> /// <param name="schemaName">the name of the schema associated with /// this database.</param> /// <param name="name">the name of the table valued function.</param> /// <param name="definition">the definition of the table valued /// function.</param> public USqlTableValuedFunction(string computeAccountName = default(string), System.Guid? version = default(System.Guid?), string databaseName = default(string), string schemaName = default(string), string name = default(string), string definition = default(string)) : base(computeAccountName, version) { DatabaseName = databaseName; SchemaName = schemaName; Name = name; Definition = definition; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the name of the database. /// </summary> [JsonProperty(PropertyName = "databaseName")] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the name of the schema associated with this database. /// </summary> [JsonProperty(PropertyName = "schemaName")] public string SchemaName { get; set; } /// <summary> /// Gets or sets the name of the table valued function. /// </summary> [JsonProperty(PropertyName = "tvfName")] public string Name { get; set; } /// <summary> /// Gets or sets the definition of the table valued function. /// </summary> [JsonProperty(PropertyName = "definition")] public string Definition { get; set; } } }
AzCiS/azure-sdk-for-net
src/SDKs/DataLake.Analytics/Management.DataLake.Analytics/Generated/Models/USqlTableValuedFunction.cs
C#
mit
3,189
<?php return [ 'contact' => '联系我们', 'name' => '名字', 'email' => '邮箱', 'message' => '信息', 'name_placeholder' => '请输入全名', 'email_placeholder' => '您的邮箱', 'message_placeholder' => '我们可以怎样帮助您?', 'contact_us' => '联系我们!', 'thanks' => '谢谢!您很快会收到我们的答复!', 'type_of_request' => '主题', ];
nicerway/tongyong
resources/lang/zh-CN/about.php
PHP
mit
504
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Externs for the Google Maps v3 API. * @see http://code.google.com/apis/maps/documentation/javascript/reference.html * @externs */ google.maps = {}; /** * @enum {number|string} */ google.maps.Animation = { BOUNCE: '', DROP: '' }; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.BicyclingLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.BicyclingLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.BicyclingLayer.prototype.setMap = function(map) {}; /** * @param {(google.maps.CircleOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Circle = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Circle.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Circle.prototype.getCenter = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Circle.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Circle.prototype.getMap = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Circle.prototype.getRadius = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Circle.prototype.getVisible = function() {}; /** * @param {google.maps.LatLng} center * @return {undefined} */ google.maps.Circle.prototype.setCenter = function(center) {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Circle.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Circle.prototype.setMap = function(map) {}; /** * @param {google.maps.CircleOptions|Object.<string>} options * @return {undefined} */ google.maps.Circle.prototype.setOptions = function(options) {}; /** * @param {number} radius * @return {undefined} */ google.maps.Circle.prototype.setRadius = function(radius) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Circle.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.CircleOptions = function() {}; /** * @type {google.maps.LatLng} */ google.maps.CircleOptions.prototype.center; /** * @type {boolean} */ google.maps.CircleOptions.prototype.clickable; /** * @type {boolean} */ google.maps.CircleOptions.prototype.editable; /** * @type {string} */ google.maps.CircleOptions.prototype.fillColor; /** * @type {number} */ google.maps.CircleOptions.prototype.fillOpacity; /** * @type {google.maps.Map} */ google.maps.CircleOptions.prototype.map; /** * @type {number} */ google.maps.CircleOptions.prototype.radius; /** * @type {string} */ google.maps.CircleOptions.prototype.strokeColor; /** * @type {number} */ google.maps.CircleOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.CircleOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.CircleOptions.prototype.visible; /** * @type {number} */ google.maps.CircleOptions.prototype.zIndex; /** * @enum {number|string} */ google.maps.ControlPosition = { BOTTOM_CENTER: '', BOTTOM_LEFT: '', BOTTOM_RIGHT: '', LEFT_BOTTOM: '', LEFT_CENTER: '', LEFT_TOP: '', RIGHT_BOTTOM: '', RIGHT_CENTER: '', RIGHT_TOP: '', TOP_CENTER: '', TOP_LEFT: '', TOP_RIGHT: '' }; /** * @constructor */ google.maps.DirectionsLeg = function() {}; /** * @type {google.maps.Distance} */ google.maps.DirectionsLeg.prototype.arrival_time; /** * @type {google.maps.Duration} */ google.maps.DirectionsLeg.prototype.departure_time; /** * @type {google.maps.Distance} */ google.maps.DirectionsLeg.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DirectionsLeg.prototype.duration; /** * @type {string} */ google.maps.DirectionsLeg.prototype.end_address; /** * @type {google.maps.LatLng} */ google.maps.DirectionsLeg.prototype.end_location; /** * @type {string} */ google.maps.DirectionsLeg.prototype.start_address; /** * @type {google.maps.LatLng} */ google.maps.DirectionsLeg.prototype.start_location; /** * @type {Array.<google.maps.DirectionsStep>} */ google.maps.DirectionsLeg.prototype.steps; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsLeg.prototype.via_waypoints; /** * @param {(google.maps.DirectionsRendererOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.DirectionsRenderer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.DirectionsResult} */ google.maps.DirectionsRenderer.prototype.getDirections = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.DirectionsRenderer.prototype.getMap = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.DirectionsRenderer.prototype.getPanel = function() {}; /** * @nosideeffects * @return {number} */ google.maps.DirectionsRenderer.prototype.getRouteIndex = function() {}; /** * @param {google.maps.DirectionsResult} directions * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setDirections = function(directions) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setMap = function(map) {}; /** * @param {google.maps.DirectionsRendererOptions|Object.<string>} options * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setOptions = function(options) {}; /** * @param {Node} panel * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setPanel = function(panel) {}; /** * @param {number} routeIndex * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setRouteIndex = function(routeIndex) {}; /** * @constructor */ google.maps.DirectionsRendererOptions = function() {}; /** * @type {google.maps.DirectionsResult} */ google.maps.DirectionsRendererOptions.prototype.directions; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.draggable; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.hideRouteList; /** * @type {google.maps.InfoWindow} */ google.maps.DirectionsRendererOptions.prototype.infoWindow; /** * @type {google.maps.Map} */ google.maps.DirectionsRendererOptions.prototype.map; /** * @type {google.maps.MarkerOptions|Object.<string>} */ google.maps.DirectionsRendererOptions.prototype.markerOptions; /** * @type {Node} */ google.maps.DirectionsRendererOptions.prototype.panel; /** * @type {google.maps.PolylineOptions|Object.<string>} */ google.maps.DirectionsRendererOptions.prototype.polylineOptions; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.preserveViewport; /** * @type {number} */ google.maps.DirectionsRendererOptions.prototype.routeIndex; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressBicyclingLayer; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressInfoWindows; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressMarkers; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressPolylines; /** * @constructor */ google.maps.DirectionsRequest = function() {}; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.avoidHighways; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.avoidTolls; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsRequest.prototype.destination; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.optimizeWaypoints; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsRequest.prototype.origin; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.provideRouteAlternatives; /** * @type {string} */ google.maps.DirectionsRequest.prototype.region; /** * @type {google.maps.TransitOptions|Object.<string>} */ google.maps.DirectionsRequest.prototype.transitOptions; /** * @type {google.maps.TravelMode} */ google.maps.DirectionsRequest.prototype.travelMode; /** * @type {google.maps.UnitSystem} */ google.maps.DirectionsRequest.prototype.unitSystem; /** * @type {Array.<google.maps.DirectionsWaypoint>} */ google.maps.DirectionsRequest.prototype.waypoints; /** * @constructor */ google.maps.DirectionsResult = function() {}; /** * @type {Array.<google.maps.DirectionsRoute>} */ google.maps.DirectionsResult.prototype.routes; /** * @constructor */ google.maps.DirectionsRoute = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.DirectionsRoute.prototype.bounds; /** * @type {string} */ google.maps.DirectionsRoute.prototype.copyrights; /** * @type {Array.<google.maps.DirectionsLeg>} */ google.maps.DirectionsRoute.prototype.legs; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsRoute.prototype.overview_path; /** * @type {Array.<string>} */ google.maps.DirectionsRoute.prototype.warnings; /** * @type {Array.<number>} */ google.maps.DirectionsRoute.prototype.waypoint_order; /** * @constructor */ google.maps.DirectionsService = function() {}; /** * @param {google.maps.DirectionsRequest|Object.<string>} request * @param {function(google.maps.DirectionsResult, google.maps.DirectionsStatus)} callback * @return {undefined} */ google.maps.DirectionsService.prototype.route = function(request, callback) {}; /** * @enum {number|string} */ google.maps.DirectionsStatus = { INVALID_REQUEST: '', MAX_WAYPOINTS_EXCEEDED: '', NOT_FOUND: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.DirectionsStep = function() {}; /** * @type {google.maps.Distance} */ google.maps.DirectionsStep.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DirectionsStep.prototype.duration; /** * @type {google.maps.LatLng} */ google.maps.DirectionsStep.prototype.end_location; /** * @type {string} */ google.maps.DirectionsStep.prototype.instructions; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsStep.prototype.path; /** * @type {google.maps.LatLng} */ google.maps.DirectionsStep.prototype.start_location; /** * @type {google.maps.DirectionsStep} */ google.maps.DirectionsStep.prototype.steps; /** * @type {google.maps.TransitDetails} */ google.maps.DirectionsStep.prototype.transit; /** * @type {google.maps.TravelMode} */ google.maps.DirectionsStep.prototype.travel_mode; /** * @constructor */ google.maps.DirectionsWaypoint = function() {}; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsWaypoint.prototype.location; /** * @type {boolean} */ google.maps.DirectionsWaypoint.prototype.stopover; /** * @constructor */ google.maps.Distance = function() {}; /** * @type {string} */ google.maps.Distance.prototype.text; /** * @type {number} */ google.maps.Distance.prototype.value; /** * @enum {number|string} */ google.maps.DistanceMatrixElementStatus = { NOT_FOUND: '', OK: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.DistanceMatrixRequest = function() {}; /** * @type {boolean} */ google.maps.DistanceMatrixRequest.prototype.avoidHighways; /** * @type {boolean} */ google.maps.DistanceMatrixRequest.prototype.avoidTolls; /** * @type {Array.<google.maps.LatLng>|Array.<string>} */ google.maps.DistanceMatrixRequest.prototype.destinations; /** * @type {Array.<google.maps.LatLng>|Array.<string>} */ google.maps.DistanceMatrixRequest.prototype.origins; /** * @type {string} */ google.maps.DistanceMatrixRequest.prototype.region; /** * @type {google.maps.TravelMode} */ google.maps.DistanceMatrixRequest.prototype.travelMode; /** * @type {google.maps.UnitSystem} */ google.maps.DistanceMatrixRequest.prototype.unitSystem; /** * @constructor */ google.maps.DistanceMatrixResponse = function() {}; /** * @type {Array.<string>} */ google.maps.DistanceMatrixResponse.prototype.destinationAddresses; /** * @type {Array.<string>} */ google.maps.DistanceMatrixResponse.prototype.originAddresses; /** * @type {Array.<google.maps.DistanceMatrixResponseRow>} */ google.maps.DistanceMatrixResponse.prototype.rows; /** * @constructor */ google.maps.DistanceMatrixResponseElement = function() {}; /** * @type {google.maps.Distance} */ google.maps.DistanceMatrixResponseElement.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DistanceMatrixResponseElement.prototype.duration; /** * @type {google.maps.DistanceMatrixElementStatus} */ google.maps.DistanceMatrixResponseElement.prototype.status; /** * @constructor */ google.maps.DistanceMatrixResponseRow = function() {}; /** * @type {Array.<google.maps.DistanceMatrixResponseElement>} */ google.maps.DistanceMatrixResponseRow.prototype.elements; /** * @constructor */ google.maps.DistanceMatrixService = function() {}; /** * @param {google.maps.DistanceMatrixRequest|Object.<string>} request * @param {function(google.maps.DistanceMatrixResponse, google.maps.DistanceMatrixStatus)} callback * @return {undefined} */ google.maps.DistanceMatrixService.prototype.getDistanceMatrix = function(request, callback) {}; /** * @enum {number|string} */ google.maps.DistanceMatrixStatus = { INVALID_REQUEST: '', MAX_DIMENSIONS_EXCEEDED: '', MAX_ELEMENTS_EXCEEDED: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '' }; /** * @constructor */ google.maps.Duration = function() {}; /** * @type {string} */ google.maps.Duration.prototype.text; /** * @type {number} */ google.maps.Duration.prototype.value; /** * @constructor */ google.maps.ElevationResult = function() {}; /** * @type {number} */ google.maps.ElevationResult.prototype.elevation; /** * @type {google.maps.LatLng} */ google.maps.ElevationResult.prototype.location; /** * @type {number} */ google.maps.ElevationResult.prototype.resolution; /** * @constructor */ google.maps.ElevationService = function() {}; /** * @param {google.maps.PathElevationRequest|Object.<string>} request * @param {function(Array.<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback * @return {undefined} */ google.maps.ElevationService.prototype.getElevationAlongPath = function(request, callback) {}; /** * @param {google.maps.LocationElevationRequest|Object.<string>} request * @param {function(Array.<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback * @return {undefined} */ google.maps.ElevationService.prototype.getElevationForLocations = function(request, callback) {}; /** * @enum {number|string} */ google.maps.ElevationStatus = { INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '' }; /** * @constructor */ google.maps.FusionTablesCell = function() {}; /** * @type {string} */ google.maps.FusionTablesCell.prototype.columnName; /** * @type {string} */ google.maps.FusionTablesCell.prototype.value; /** * @constructor */ google.maps.FusionTablesHeatmap = function() {}; /** * @type {boolean} */ google.maps.FusionTablesHeatmap.prototype.enabled; /** * @param {google.maps.FusionTablesLayerOptions|Object.<string>} options * @extends {google.maps.MVCObject} * @constructor */ google.maps.FusionTablesLayer = function(options) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.FusionTablesLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.FusionTablesLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.FusionTablesLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.FusionTablesLayer.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.FusionTablesLayerOptions = function() {}; /** * @type {boolean} */ google.maps.FusionTablesLayerOptions.prototype.clickable; /** * @type {google.maps.FusionTablesHeatmap} */ google.maps.FusionTablesLayerOptions.prototype.heatmap; /** * @type {google.maps.Map} */ google.maps.FusionTablesLayerOptions.prototype.map; /** * @type {google.maps.FusionTablesQuery} */ google.maps.FusionTablesLayerOptions.prototype.query; /** * @type {Array.<google.maps.FusionTablesStyle>} */ google.maps.FusionTablesLayerOptions.prototype.styles; /** * @type {boolean} */ google.maps.FusionTablesLayerOptions.prototype.suppressInfoWindows; /** * @constructor */ google.maps.FusionTablesMarkerOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesMarkerOptions.prototype.iconName; /** * @constructor */ google.maps.FusionTablesMouseEvent = function() {}; /** * @type {string} */ google.maps.FusionTablesMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.FusionTablesMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.FusionTablesMouseEvent.prototype.pixelOffset; /** * @type {Object} */ google.maps.FusionTablesMouseEvent.prototype.row; /** * @constructor */ google.maps.FusionTablesPolygonOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesPolygonOptions.prototype.fillColor; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.fillOpacity; /** * @type {string} */ google.maps.FusionTablesPolygonOptions.prototype.strokeColor; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.strokeWeight; /** * @constructor */ google.maps.FusionTablesPolylineOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesPolylineOptions.prototype.strokeColor; /** * @type {number} */ google.maps.FusionTablesPolylineOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.FusionTablesPolylineOptions.prototype.strokeWeight; /** * @constructor */ google.maps.FusionTablesQuery = function() {}; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.from; /** * @type {number} */ google.maps.FusionTablesQuery.prototype.limit; /** * @type {number} */ google.maps.FusionTablesQuery.prototype.offset; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.orderBy; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.select; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.where; /** * @constructor */ google.maps.FusionTablesStyle = function() {}; /** * @type {google.maps.FusionTablesMarkerOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.markerOptions; /** * @type {google.maps.FusionTablesPolygonOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.polygonOptions; /** * @type {google.maps.FusionTablesPolylineOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.polylineOptions; /** * @type {string} */ google.maps.FusionTablesStyle.prototype.where; /** * @constructor */ google.maps.Geocoder = function() {}; /** * @param {google.maps.GeocoderRequest|Object.<string>} request * @param {function(Array.<google.maps.GeocoderResult>, google.maps.GeocoderStatus)} callback * @return {undefined} */ google.maps.Geocoder.prototype.geocode = function(request, callback) {}; /** * @constructor */ google.maps.GeocoderAddressComponent = function() {}; /** * @type {string} */ google.maps.GeocoderAddressComponent.prototype.long_name; /** * @type {string} */ google.maps.GeocoderAddressComponent.prototype.short_name; /** * @type {Array.<string>} */ google.maps.GeocoderAddressComponent.prototype.types; /** * @constructor */ google.maps.GeocoderGeometry = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderGeometry.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.GeocoderGeometry.prototype.location; /** * @type {google.maps.GeocoderLocationType} */ google.maps.GeocoderGeometry.prototype.location_type; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderGeometry.prototype.viewport; /** * @enum {number|string} */ google.maps.GeocoderLocationType = { APPROXIMATE: '', GEOMETRIC_CENTER: '', RANGE_INTERPOLATED: '', ROOFTOP: '' }; /** * @constructor */ google.maps.GeocoderRequest = function() {}; /** * @type {string} */ google.maps.GeocoderRequest.prototype.address; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderRequest.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.GeocoderRequest.prototype.location; /** * @type {string} */ google.maps.GeocoderRequest.prototype.region; /** * @constructor */ google.maps.GeocoderResult = function() {}; /** * @type {Array.<google.maps.GeocoderAddressComponent>} */ google.maps.GeocoderResult.prototype.address_components; /** * @type {string} */ google.maps.GeocoderResult.prototype.formatted_address; /** * @type {google.maps.GeocoderGeometry} */ google.maps.GeocoderResult.prototype.geometry; /** * @type {Array.<string>} */ google.maps.GeocoderResult.prototype.types; /** * @enum {number|string} */ google.maps.GeocoderStatus = { ERROR: '', INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @param {string} url * @param {google.maps.LatLngBounds} bounds * @param {(google.maps.GroundOverlayOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.GroundOverlay = function(url, bounds, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.GroundOverlay.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.GroundOverlay.prototype.getMap = function() {}; /** * @nosideeffects * @return {number} */ google.maps.GroundOverlay.prototype.getOpacity = function() {}; /** * @nosideeffects * @return {string} */ google.maps.GroundOverlay.prototype.getUrl = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.GroundOverlay.prototype.setMap = function(map) {}; /** * @param {number} opacity * @return {undefined} */ google.maps.GroundOverlay.prototype.setOpacity = function(opacity) {}; /** * @constructor */ google.maps.GroundOverlayOptions = function() {}; /** * @type {boolean} */ google.maps.GroundOverlayOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.GroundOverlayOptions.prototype.map; /** * @type {number} */ google.maps.GroundOverlayOptions.prototype.opacity; /** * @constructor */ google.maps.IconSequence = function() {}; /** * @type {google.maps.Symbol} */ google.maps.IconSequence.prototype.icon; /** * @type {string} */ google.maps.IconSequence.prototype.offset; /** * @type {string} */ google.maps.IconSequence.prototype.repeat; /** * @param {google.maps.ImageMapTypeOptions|Object.<string>} opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.ImageMapType = function(opts) {}; /** * @nosideeffects * @return {number} */ google.maps.ImageMapType.prototype.getOpacity = function() {}; /** * @param {number} opacity * @return {undefined} */ google.maps.ImageMapType.prototype.setOpacity = function(opacity) {}; /** * @constructor */ google.maps.ImageMapTypeOptions = function() {}; /** * @type {string} */ google.maps.ImageMapTypeOptions.prototype.alt; /** * @type {function(google.maps.Point, number):string} */ google.maps.ImageMapTypeOptions.prototype.getTileUrl; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.maxZoom; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.minZoom; /** * @type {string} */ google.maps.ImageMapTypeOptions.prototype.name; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.opacity; /** * @type {google.maps.Size} */ google.maps.ImageMapTypeOptions.prototype.tileSize; /** * @param {(google.maps.InfoWindowOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.InfoWindow = function(opt_opts) {}; /** * @return {undefined} */ google.maps.InfoWindow.prototype.close = function() {}; /** * @nosideeffects * @return {string|Node} */ google.maps.InfoWindow.prototype.getContent = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.InfoWindow.prototype.getPosition = function() {}; /** * @nosideeffects * @return {number} */ google.maps.InfoWindow.prototype.getZIndex = function() {}; /** * @param {(google.maps.Map|google.maps.StreetViewPanorama)=} opt_map * @param {google.maps.MVCObject=} opt_anchor * @return {undefined} */ google.maps.InfoWindow.prototype.open = function(opt_map, opt_anchor) {}; /** * @param {string|Node} content * @return {undefined} */ google.maps.InfoWindow.prototype.setContent = function(content) {}; /** * @param {google.maps.InfoWindowOptions|Object.<string>} options * @return {undefined} */ google.maps.InfoWindow.prototype.setOptions = function(options) {}; /** * @param {google.maps.LatLng} position * @return {undefined} */ google.maps.InfoWindow.prototype.setPosition = function(position) {}; /** * @param {number} zIndex * @return {undefined} */ google.maps.InfoWindow.prototype.setZIndex = function(zIndex) {}; /** * @constructor */ google.maps.InfoWindowOptions = function() {}; /** * @type {string|Node} */ google.maps.InfoWindowOptions.prototype.content; /** * @type {boolean} */ google.maps.InfoWindowOptions.prototype.disableAutoPan; /** * @type {number} */ google.maps.InfoWindowOptions.prototype.maxWidth; /** * @type {google.maps.Size} */ google.maps.InfoWindowOptions.prototype.pixelOffset; /** * @type {google.maps.LatLng} */ google.maps.InfoWindowOptions.prototype.position; /** * @type {number} */ google.maps.InfoWindowOptions.prototype.zIndex; /** * @constructor */ google.maps.KmlAuthor = function() {}; /** * @type {string} */ google.maps.KmlAuthor.prototype.email; /** * @type {string} */ google.maps.KmlAuthor.prototype.name; /** * @type {string} */ google.maps.KmlAuthor.prototype.uri; /** * @constructor */ google.maps.KmlFeatureData = function() {}; /** * @type {google.maps.KmlAuthor} */ google.maps.KmlFeatureData.prototype.author; /** * @type {string} */ google.maps.KmlFeatureData.prototype.description; /** * @type {string} */ google.maps.KmlFeatureData.prototype.id; /** * @type {string} */ google.maps.KmlFeatureData.prototype.infoWindowHtml; /** * @type {string} */ google.maps.KmlFeatureData.prototype.name; /** * @type {string} */ google.maps.KmlFeatureData.prototype.snippet; /** * @param {string} url * @param {(google.maps.KmlLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.KmlLayer = function(url, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.KmlLayer.prototype.getDefaultViewport = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.KmlLayer.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.KmlLayerMetadata} */ google.maps.KmlLayer.prototype.getMetadata = function() {}; /** * @nosideeffects * @return {google.maps.KmlLayerStatus} */ google.maps.KmlLayer.prototype.getStatus = function() {}; /** * @nosideeffects * @return {string} */ google.maps.KmlLayer.prototype.getUrl = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.KmlLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.KmlLayerMetadata = function() {}; /** * @type {google.maps.KmlAuthor} */ google.maps.KmlLayerMetadata.prototype.author; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.description; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.name; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.snippet; /** * @constructor */ google.maps.KmlLayerOptions = function() {}; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.KmlLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.preserveViewport; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.suppressInfoWindows; /** * @enum {number|string} */ google.maps.KmlLayerStatus = { DOCUMENT_NOT_FOUND: '', DOCUMENT_TOO_LARGE: '', FETCH_ERROR: '', INVALID_DOCUMENT: '', INVALID_REQUEST: '', LIMITS_EXCEEDED: '', OK: '', TIMED_OUT: '', UNKNOWN: '' }; /** * @constructor */ google.maps.KmlMouseEvent = function() {}; /** * @type {google.maps.KmlFeatureData} */ google.maps.KmlMouseEvent.prototype.featureData; /** * @type {google.maps.LatLng} */ google.maps.KmlMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.KmlMouseEvent.prototype.pixelOffset; /** * @param {number} lat * @param {number} lng * @param {boolean=} opt_noWrap * @constructor */ google.maps.LatLng = function(lat, lng, opt_noWrap) {}; /** * @param {google.maps.LatLng} other * @return {boolean} */ google.maps.LatLng.prototype.equals = function(other) {}; /** * @return {number} */ google.maps.LatLng.prototype.lat = function() {}; /** * @return {number} */ google.maps.LatLng.prototype.lng = function() {}; /** * @return {string} */ google.maps.LatLng.prototype.toString = function() {}; /** * @param {number=} opt_precision * @return {string} */ google.maps.LatLng.prototype.toUrlValue = function(opt_precision) {}; /** * @param {google.maps.LatLng=} opt_sw * @param {google.maps.LatLng=} opt_ne * @constructor */ google.maps.LatLngBounds = function(opt_sw, opt_ne) {}; /** * @param {google.maps.LatLng} latLng * @return {boolean} */ google.maps.LatLngBounds.prototype.contains = function(latLng) {}; /** * @param {google.maps.LatLngBounds} other * @return {boolean} */ google.maps.LatLngBounds.prototype.equals = function(other) {}; /** * @param {google.maps.LatLng} point * @return {google.maps.LatLngBounds} */ google.maps.LatLngBounds.prototype.extend = function(point) {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getCenter = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getNorthEast = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getSouthWest = function() {}; /** * @param {google.maps.LatLngBounds} other * @return {boolean} */ google.maps.LatLngBounds.prototype.intersects = function(other) {}; /** * @return {boolean} */ google.maps.LatLngBounds.prototype.isEmpty = function() {}; /** * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.toSpan = function() {}; /** * @return {string} */ google.maps.LatLngBounds.prototype.toString = function() {}; /** * @param {number=} opt_precision * @return {string} */ google.maps.LatLngBounds.prototype.toUrlValue = function(opt_precision) {}; /** * @param {google.maps.LatLngBounds} other * @return {google.maps.LatLngBounds} */ google.maps.LatLngBounds.prototype.union = function(other) {}; /** * @constructor */ google.maps.LocationElevationRequest = function() {}; /** * @type {Array.<google.maps.LatLng>} */ google.maps.LocationElevationRequest.prototype.locations; /** * @param {Array=} opt_array * @extends {google.maps.MVCObject} * @constructor */ google.maps.MVCArray = function(opt_array) {}; /** * @return {undefined} */ google.maps.MVCArray.prototype.clear = function() {}; /** * @param {function(?, number)} callback * @return {undefined} */ google.maps.MVCArray.prototype.forEach = function(callback) {}; /** * @nosideeffects * @return {Array} */ google.maps.MVCArray.prototype.getArray = function() {}; /** * @param {number} i * @return {*} */ google.maps.MVCArray.prototype.getAt = function(i) {}; /** * @nosideeffects * @return {number} */ google.maps.MVCArray.prototype.getLength = function() {}; /** * @param {number} i * @param {*} elem * @return {undefined} */ google.maps.MVCArray.prototype.insertAt = function(i, elem) {}; /** * @return {*} */ google.maps.MVCArray.prototype.pop = function() {}; /** * @param {*} elem * @return {number} */ google.maps.MVCArray.prototype.push = function(elem) {}; /** * @param {number} i * @return {*} */ google.maps.MVCArray.prototype.removeAt = function(i) {}; /** * @param {number} i * @param {*} elem * @return {undefined} */ google.maps.MVCArray.prototype.setAt = function(i, elem) {}; /** * @constructor */ google.maps.MVCObject = function() {}; /** * @param {string} key * @param {google.maps.MVCObject} target * @param {?string=} opt_targetKey * @param {boolean=} opt_noNotify * @return {undefined} */ google.maps.MVCObject.prototype.bindTo = function(key, target, opt_targetKey, opt_noNotify) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.changed = function(key) {}; /** * @param {string} key * @return {*} */ google.maps.MVCObject.prototype.get = function(key) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.notify = function(key) {}; /** * @param {string} key * @param {?} value * @return {undefined} */ google.maps.MVCObject.prototype.set = function(key, value) {}; /** * @param {Object|undefined} values * @return {undefined} */ google.maps.MVCObject.prototype.setValues = function(values) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.unbind = function(key) {}; /** * @return {undefined} */ google.maps.MVCObject.prototype.unbindAll = function() {}; /** * @param {Node} mapDiv * @param {(google.maps.MapOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Map = function(mapDiv, opt_opts) {}; /** * @type {Array.<google.maps.MVCArray.<Node>>} */ google.maps.Map.prototype.controls; /** * @type {google.maps.MapTypeRegistry} */ google.maps.Map.prototype.mapTypes; /** * @type {google.maps.MVCArray.<google.maps.MapType>} */ google.maps.Map.prototype.overlayMapTypes; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.Map.prototype.fitBounds = function(bounds) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Map.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Map.prototype.getCenter = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.Map.prototype.getDiv = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getHeading = function() {}; /** * @nosideeffects * @return {google.maps.MapTypeId|string} */ google.maps.Map.prototype.getMapTypeId = function() {}; /** * @nosideeffects * @return {google.maps.Projection} */ google.maps.Map.prototype.getProjection = function() {}; /** * @nosideeffects * @return {google.maps.StreetViewPanorama} */ google.maps.Map.prototype.getStreetView = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getTilt = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getZoom = function() {}; /** * @param {number} x * @param {number} y * @return {undefined} */ google.maps.Map.prototype.panBy = function(x, y) {}; /** * @param {google.maps.LatLng} latLng * @return {undefined} */ google.maps.Map.prototype.panTo = function(latLng) {}; /** * @param {google.maps.LatLngBounds} latLngBounds * @return {undefined} */ google.maps.Map.prototype.panToBounds = function(latLngBounds) {}; /** * @param {google.maps.LatLng} latlng * @return {undefined} */ google.maps.Map.prototype.setCenter = function(latlng) {}; /** * @param {number} heading * @return {undefined} */ google.maps.Map.prototype.setHeading = function(heading) {}; /** * @param {google.maps.MapTypeId|string} mapTypeId * @return {undefined} */ google.maps.Map.prototype.setMapTypeId = function(mapTypeId) {}; /** * @param {google.maps.MapOptions|Object.<string>} options * @return {undefined} */ google.maps.Map.prototype.setOptions = function(options) {}; /** * @param {google.maps.StreetViewPanorama} panorama * @return {undefined} */ google.maps.Map.prototype.setStreetView = function(panorama) {}; /** * @param {number} tilt * @return {undefined} */ google.maps.Map.prototype.setTilt = function(tilt) {}; /** * @param {number} zoom * @return {undefined} */ google.maps.Map.prototype.setZoom = function(zoom) {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.MapCanvasProjection = function() {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.MapCanvasProjection.prototype.fromContainerPixelToLatLng = function(pixel, opt_nowrap) {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.MapCanvasProjection.prototype.fromDivPixelToLatLng = function(pixel, opt_nowrap) {}; /** * @param {google.maps.LatLng} latLng * @return {google.maps.Point} */ google.maps.MapCanvasProjection.prototype.fromLatLngToContainerPixel = function(latLng) {}; /** * @param {google.maps.LatLng} latLng * @return {google.maps.Point} */ google.maps.MapCanvasProjection.prototype.fromLatLngToDivPixel = function(latLng) {}; /** * @nosideeffects * @return {number} */ google.maps.MapCanvasProjection.prototype.getWorldWidth = function() {}; /** * @constructor */ google.maps.MapOptions = function() {}; /** * @type {string} */ google.maps.MapOptions.prototype.backgroundColor; /** * @type {google.maps.LatLng} */ google.maps.MapOptions.prototype.center; /** * @type {boolean} */ google.maps.MapOptions.prototype.disableDefaultUI; /** * @type {boolean} */ google.maps.MapOptions.prototype.disableDoubleClickZoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.draggable; /** * @type {string} */ google.maps.MapOptions.prototype.draggableCursor; /** * @type {string} */ google.maps.MapOptions.prototype.draggingCursor; /** * @type {number} */ google.maps.MapOptions.prototype.heading; /** * @type {boolean} */ google.maps.MapOptions.prototype.keyboardShortcuts; /** * @type {boolean} */ google.maps.MapOptions.prototype.mapMaker; /** * @type {boolean} */ google.maps.MapOptions.prototype.mapTypeControl; /** * @type {google.maps.MapTypeControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.mapTypeControlOptions; /** * @type {google.maps.MapTypeId} */ google.maps.MapOptions.prototype.mapTypeId; /** * @type {number} */ google.maps.MapOptions.prototype.maxZoom; /** * @type {number} */ google.maps.MapOptions.prototype.minZoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.noClear; /** * @type {boolean} */ google.maps.MapOptions.prototype.overviewMapControl; /** * @type {google.maps.OverviewMapControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.overviewMapControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.panControl; /** * @type {google.maps.PanControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.panControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.rotateControl; /** * @type {google.maps.RotateControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.rotateControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.scaleControl; /** * @type {google.maps.ScaleControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.scaleControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.scrollwheel; /** * @type {google.maps.StreetViewPanorama} */ google.maps.MapOptions.prototype.streetView; /** * @type {boolean} */ google.maps.MapOptions.prototype.streetViewControl; /** * @type {google.maps.StreetViewControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.streetViewControlOptions; /** * @type {Array.<google.maps.MapTypeStyle>} */ google.maps.MapOptions.prototype.styles; /** * @type {number} */ google.maps.MapOptions.prototype.tilt; /** * @type {number} */ google.maps.MapOptions.prototype.zoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.zoomControl; /** * @type {google.maps.ZoomControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.zoomControlOptions; /** * @constructor */ google.maps.MapPanes = function() {}; /** * @type {Node} */ google.maps.MapPanes.prototype.floatPane; /** * @type {Node} */ google.maps.MapPanes.prototype.floatShadow; /** * @type {Node} */ google.maps.MapPanes.prototype.mapPane; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayImage; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayLayer; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayMouseTarget; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayShadow; /** * @constructor */ google.maps.MapType = function() {}; /** * @type {string} */ google.maps.MapType.prototype.alt; /** * @type {number} */ google.maps.MapType.prototype.maxZoom; /** * @type {number} */ google.maps.MapType.prototype.minZoom; /** * @type {string} */ google.maps.MapType.prototype.name; /** * @type {google.maps.Projection} */ google.maps.MapType.prototype.projection; /** * @type {number} */ google.maps.MapType.prototype.radius; /** * @type {google.maps.Size} */ google.maps.MapType.prototype.tileSize; /** * @param {google.maps.Point} tileCoord * @param {number} zoom * @param {Document} ownerDocument * @return {Node} */ google.maps.MapType.prototype.getTile = function(tileCoord, zoom, ownerDocument) {}; /** * @param {Node} tile * @return {undefined} */ google.maps.MapType.prototype.releaseTile = function(tile) {}; /** * @constructor */ google.maps.MapTypeControlOptions = function() {}; /** * @type {Array.<google.maps.MapTypeId>|Array.<string>} */ google.maps.MapTypeControlOptions.prototype.mapTypeIds; /** * @type {google.maps.ControlPosition} */ google.maps.MapTypeControlOptions.prototype.position; /** * @type {google.maps.MapTypeControlStyle} */ google.maps.MapTypeControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.MapTypeControlStyle = { DEFAULT: '', DROPDOWN_MENU: '', HORIZONTAL_BAR: '' }; /** * @enum {number|string} */ google.maps.MapTypeId = { HYBRID: '', ROADMAP: '', SATELLITE: '', TERRAIN: '' }; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.MapTypeRegistry = function() {}; /** * @param {string} id * @param {google.maps.MapType} mapType * @return {undefined} * @override */ google.maps.MapTypeRegistry.prototype.set = function(id, mapType) {}; /** * @constructor */ google.maps.MapTypeStyle = function() {}; /** * @type {string} */ google.maps.MapTypeStyle.prototype.elementType; /** * @type {string} */ google.maps.MapTypeStyle.prototype.featureType; /** * @type {Array.<google.maps.MapTypeStyler>} */ google.maps.MapTypeStyle.prototype.stylers; /** * @constructor */ google.maps.MapTypeStyler = function() {}; /** * @type {number} */ google.maps.MapTypeStyler.prototype.gamma; /** * @type {string} */ google.maps.MapTypeStyler.prototype.hue; /** * @type {boolean} */ google.maps.MapTypeStyler.prototype.invert_lightness; /** * @type {number} */ google.maps.MapTypeStyler.prototype.lightness; /** * @type {number} */ google.maps.MapTypeStyler.prototype.saturation; /** * @type {string} */ google.maps.MapTypeStyler.prototype.visibility; /** * @constructor */ google.maps.MapsEventListener = function() {}; /** * @param {(google.maps.MarkerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Marker = function(opt_opts) {}; /** * @nosideeffects * @return {?google.maps.Animation} */ google.maps.Marker.prototype.getAnimation = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getClickable = function() {}; /** * @nosideeffects * @return {string} */ google.maps.Marker.prototype.getCursor = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getDraggable = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getFlat = function() {}; /** * @nosideeffects * @return {string|google.maps.MarkerImage} */ google.maps.Marker.prototype.getIcon = function() {}; /** * @nosideeffects * @return {google.maps.Map|google.maps.StreetViewPanorama} */ google.maps.Marker.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Marker.prototype.getPosition = function() {}; /** * @nosideeffects * @return {string|google.maps.MarkerImage} */ google.maps.Marker.prototype.getShadow = function() {}; /** * @nosideeffects * @return {google.maps.MarkerShape} */ google.maps.Marker.prototype.getShape = function() {}; /** * @nosideeffects * @return {string} */ google.maps.Marker.prototype.getTitle = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getVisible = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Marker.prototype.getZIndex = function() {}; /** * @param {?google.maps.Animation} animation * @return {undefined} */ google.maps.Marker.prototype.setAnimation = function(animation) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setClickable = function(flag) {}; /** * @param {string} cursor * @return {undefined} */ google.maps.Marker.prototype.setCursor = function(cursor) {}; /** * @param {?boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setDraggable = function(flag) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setFlat = function(flag) {}; /** * @param {string|google.maps.MarkerImage} icon * @return {undefined} */ google.maps.Marker.prototype.setIcon = function(icon) {}; /** * @param {google.maps.Map|google.maps.StreetViewPanorama} map * @return {undefined} */ google.maps.Marker.prototype.setMap = function(map) {}; /** * @param {google.maps.MarkerOptions|Object.<string>} options * @return {undefined} */ google.maps.Marker.prototype.setOptions = function(options) {}; /** * @param {google.maps.LatLng} latlng * @return {undefined} */ google.maps.Marker.prototype.setPosition = function(latlng) {}; /** * @param {string|google.maps.MarkerImage} shadow * @return {undefined} */ google.maps.Marker.prototype.setShadow = function(shadow) {}; /** * @param {google.maps.MarkerShape} shape * @return {undefined} */ google.maps.Marker.prototype.setShape = function(shape) {}; /** * @param {string} title * @return {undefined} */ google.maps.Marker.prototype.setTitle = function(title) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Marker.prototype.setVisible = function(visible) {}; /** * @param {number} zIndex * @return {undefined} */ google.maps.Marker.prototype.setZIndex = function(zIndex) {}; /** * @constant * @type {number|string} */ google.maps.Marker.MAX_ZINDEX; /** * @param {string} url * @param {google.maps.Size=} opt_size * @param {google.maps.Point=} opt_origin * @param {google.maps.Point=} opt_anchor * @param {google.maps.Size=} opt_scaledSize * @constructor */ google.maps.MarkerImage = function(url, opt_size, opt_origin, opt_anchor, opt_scaledSize) {}; /** * @type {google.maps.Point} */ google.maps.MarkerImage.prototype.anchor; /** * @type {google.maps.Point} */ google.maps.MarkerImage.prototype.origin; /** * @type {google.maps.Size} */ google.maps.MarkerImage.prototype.scaledSize; /** * @type {google.maps.Size} */ google.maps.MarkerImage.prototype.size; /** * @type {string} */ google.maps.MarkerImage.prototype.url; /** * @constructor */ google.maps.MarkerOptions = function() {}; /** * @type {google.maps.Animation} */ google.maps.MarkerOptions.prototype.animation; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.clickable; /** * @type {string} */ google.maps.MarkerOptions.prototype.cursor; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.draggable; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.flat; /** * @type {string|google.maps.MarkerImage|google.maps.Symbol} */ google.maps.MarkerOptions.prototype.icon; /** * @type {google.maps.Map|google.maps.StreetViewPanorama} */ google.maps.MarkerOptions.prototype.map; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.optimized; /** * @type {google.maps.LatLng} */ google.maps.MarkerOptions.prototype.position; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.raiseOnDrag; /** * @type {string|google.maps.MarkerImage|google.maps.Symbol} */ google.maps.MarkerOptions.prototype.shadow; /** * @type {google.maps.MarkerShape} */ google.maps.MarkerOptions.prototype.shape; /** * @type {string} */ google.maps.MarkerOptions.prototype.title; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.visible; /** * @type {number} */ google.maps.MarkerOptions.prototype.zIndex; /** * @constructor */ google.maps.MarkerShape = function() {}; /** * @type {Array.<number>} */ google.maps.MarkerShape.prototype.coords; /** * @type {string} */ google.maps.MarkerShape.prototype.type; /** * @constructor */ google.maps.MaxZoomResult = function() {}; /** * @type {google.maps.MaxZoomStatus} */ google.maps.MaxZoomResult.prototype.status; /** * @type {number} */ google.maps.MaxZoomResult.prototype.zoom; /** * @constructor */ google.maps.MaxZoomService = function() {}; /** * @param {google.maps.LatLng} latlng * @param {function(google.maps.MaxZoomResult)} callback * @return {undefined} */ google.maps.MaxZoomService.prototype.getMaxZoomAtLatLng = function(latlng, callback) {}; /** * @enum {number|string} */ google.maps.MaxZoomStatus = { ERROR: '', OK: '' }; /** * @constructor */ google.maps.MouseEvent = function() {}; /** * @type {google.maps.LatLng} */ google.maps.MouseEvent.prototype.latLng; /** * @return {undefined} */ google.maps.MouseEvent.prototype.stop = function() {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.OverlayView = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.draw = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.OverlayView.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MapPanes} */ google.maps.OverlayView.prototype.getPanes = function() {}; /** * @nosideeffects * @return {google.maps.MapCanvasProjection} */ google.maps.OverlayView.prototype.getProjection = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.onAdd = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.onRemove = function() {}; /** * @param {google.maps.Map|google.maps.StreetViewPanorama} map * @return {undefined} */ google.maps.OverlayView.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.OverviewMapControlOptions = function() {}; /** * @type {boolean} */ google.maps.OverviewMapControlOptions.prototype.opened; /** * @constructor */ google.maps.PanControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.PanControlOptions.prototype.position; /** * @constructor */ google.maps.PathElevationRequest = function() {}; /** * @type {Array.<google.maps.LatLng>} */ google.maps.PathElevationRequest.prototype.path; /** * @type {number} */ google.maps.PathElevationRequest.prototype.samples; /** * @param {number} x * @param {number} y * @constructor */ google.maps.Point = function(x, y) {}; /** * @type {number} */ google.maps.Point.prototype.x; /** * @type {number} */ google.maps.Point.prototype.y; /** * @param {google.maps.Point} other * @return {boolean} */ google.maps.Point.prototype.equals = function(other) {}; /** * @return {string} */ google.maps.Point.prototype.toString = function() {}; /** * @extends {google.maps.MouseEvent} * @constructor */ google.maps.PolyMouseEvent = function() {}; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.edge; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.path; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.vertex; /** * @param {(google.maps.PolygonOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Polygon = function(opt_opts) {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polygon.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Polygon.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.Polygon.prototype.getPath = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>} */ google.maps.Polygon.prototype.getPaths = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polygon.prototype.getVisible = function() {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Polygon.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Polygon.prototype.setMap = function(map) {}; /** * @param {google.maps.PolygonOptions|Object.<string>} options * @return {undefined} */ google.maps.Polygon.prototype.setOptions = function(options) {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} path * @return {undefined} */ google.maps.Polygon.prototype.setPath = function(path) {}; /** * @param {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>|google.maps.MVCArray.<google.maps.LatLng>|Array.<Array.<google.maps.LatLng>>|Array.<google.maps.LatLng>} paths * @return {undefined} */ google.maps.Polygon.prototype.setPaths = function(paths) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Polygon.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.PolygonOptions = function() {}; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.clickable; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.editable; /** * @type {string} */ google.maps.PolygonOptions.prototype.fillColor; /** * @type {number} */ google.maps.PolygonOptions.prototype.fillOpacity; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.geodesic; /** * @type {google.maps.Map} */ google.maps.PolygonOptions.prototype.map; /** * @type {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>|google.maps.MVCArray.<google.maps.LatLng>|Array.<Array.<google.maps.LatLng>>|Array.<google.maps.LatLng>} */ google.maps.PolygonOptions.prototype.paths; /** * @type {string} */ google.maps.PolygonOptions.prototype.strokeColor; /** * @type {number} */ google.maps.PolygonOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.PolygonOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.visible; /** * @type {number} */ google.maps.PolygonOptions.prototype.zIndex; /** * @param {(google.maps.PolylineOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Polyline = function(opt_opts) {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polyline.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Polyline.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.Polyline.prototype.getPath = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polyline.prototype.getVisible = function() {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Polyline.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Polyline.prototype.setMap = function(map) {}; /** * @param {google.maps.PolylineOptions|Object.<string>} options * @return {undefined} */ google.maps.Polyline.prototype.setOptions = function(options) {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} path * @return {undefined} */ google.maps.Polyline.prototype.setPath = function(path) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Polyline.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.PolylineOptions = function() {}; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.clickable; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.editable; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.geodesic; /** * @type {Array.<google.maps.IconSequence>} */ google.maps.PolylineOptions.prototype.icons; /** * @type {google.maps.Map} */ google.maps.PolylineOptions.prototype.map; /** * @type {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} */ google.maps.PolylineOptions.prototype.path; /** * @type {string} */ google.maps.PolylineOptions.prototype.strokeColor; /** * @type {number} */ google.maps.PolylineOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.PolylineOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.visible; /** * @type {number} */ google.maps.PolylineOptions.prototype.zIndex; /** * @constructor */ google.maps.Projection = function() {}; /** * @param {google.maps.LatLng} latLng * @param {google.maps.Point=} opt_point * @return {google.maps.Point} */ google.maps.Projection.prototype.fromLatLngToPoint = function(latLng, opt_point) {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.Projection.prototype.fromPointToLatLng = function(pixel, opt_nowrap) {}; /** * @param {(google.maps.RectangleOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Rectangle = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Rectangle.prototype.getBounds = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Rectangle.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Rectangle.prototype.getMap = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Rectangle.prototype.getVisible = function() {}; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.Rectangle.prototype.setBounds = function(bounds) {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Rectangle.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Rectangle.prototype.setMap = function(map) {}; /** * @param {google.maps.RectangleOptions|Object.<string>} options * @return {undefined} */ google.maps.Rectangle.prototype.setOptions = function(options) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Rectangle.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.RectangleOptions = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.RectangleOptions.prototype.bounds; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.clickable; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.editable; /** * @type {string} */ google.maps.RectangleOptions.prototype.fillColor; /** * @type {number} */ google.maps.RectangleOptions.prototype.fillOpacity; /** * @type {google.maps.Map} */ google.maps.RectangleOptions.prototype.map; /** * @type {string} */ google.maps.RectangleOptions.prototype.strokeColor; /** * @type {number} */ google.maps.RectangleOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.RectangleOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.visible; /** * @type {number} */ google.maps.RectangleOptions.prototype.zIndex; /** * @constructor */ google.maps.RotateControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.RotateControlOptions.prototype.position; /** * @constructor */ google.maps.ScaleControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.ScaleControlOptions.prototype.position; /** * @type {google.maps.ScaleControlStyle} */ google.maps.ScaleControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.ScaleControlStyle = { DEFAULT: '' }; /** * @param {number} width * @param {number} height * @param {string=} opt_widthUnit * @param {string=} opt_heightUnit * @constructor */ google.maps.Size = function(width, height, opt_widthUnit, opt_heightUnit) {}; /** * @type {number} */ google.maps.Size.prototype.height; /** * @type {number} */ google.maps.Size.prototype.width; /** * @param {google.maps.Size} other * @return {boolean} */ google.maps.Size.prototype.equals = function(other) {}; /** * @return {string} */ google.maps.Size.prototype.toString = function() {}; /** * @constructor */ google.maps.StreetViewAddressControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.StreetViewAddressControlOptions.prototype.position; /** * @constructor */ google.maps.StreetViewControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.StreetViewControlOptions.prototype.position; /** * @constructor */ google.maps.StreetViewLink = function() {}; /** * @type {string} */ google.maps.StreetViewLink.prototype.description; /** * @type {number} */ google.maps.StreetViewLink.prototype.heading; /** * @type {string} */ google.maps.StreetViewLink.prototype.pano; /** * @constructor */ google.maps.StreetViewLocation = function() {}; /** * @type {string} */ google.maps.StreetViewLocation.prototype.description; /** * @type {google.maps.LatLng} */ google.maps.StreetViewLocation.prototype.latLng; /** * @type {string} */ google.maps.StreetViewLocation.prototype.pano; /** * @param {Node} container * @param {(google.maps.StreetViewPanoramaOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.StreetViewPanorama = function(container, opt_opts) {}; /** * @type {Array.<google.maps.MVCArray.<Node>>} */ google.maps.StreetViewPanorama.prototype.controls; /** * @nosideeffects * @return {Array.<google.maps.StreetViewLink>} */ google.maps.StreetViewPanorama.prototype.getLinks = function() {}; /** * @nosideeffects * @return {string} */ google.maps.StreetViewPanorama.prototype.getPano = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.StreetViewPanorama.prototype.getPosition = function() {}; /** * @nosideeffects * @return {google.maps.StreetViewPov} */ google.maps.StreetViewPanorama.prototype.getPov = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.StreetViewPanorama.prototype.getVisible = function() {}; /** * @param {function(string):google.maps.StreetViewPanoramaData} provider * @return {undefined} */ google.maps.StreetViewPanorama.prototype.registerPanoProvider = function(provider) {}; /** * @param {string} pano * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPano = function(pano) {}; /** * @param {google.maps.LatLng} latLng * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPosition = function(latLng) {}; /** * @param {google.maps.StreetViewPov} pov * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPov = function(pov) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setVisible = function(flag) {}; /** * @constructor */ google.maps.StreetViewPanoramaData = function() {}; /** * @type {string} */ google.maps.StreetViewPanoramaData.prototype.copyright; /** * @type {string} */ google.maps.StreetViewPanoramaData.prototype.imageDate; /** * @type {Array.<google.maps.StreetViewLink>} */ google.maps.StreetViewPanoramaData.prototype.links; /** * @type {google.maps.StreetViewLocation} */ google.maps.StreetViewPanoramaData.prototype.location; /** * @type {google.maps.StreetViewTileData} */ google.maps.StreetViewPanoramaData.prototype.tiles; /** * @constructor */ google.maps.StreetViewPanoramaOptions = function() {}; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.addressControl; /** * @type {google.maps.StreetViewAddressControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.addressControlOptions; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.clickToGo; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.disableDoubleClickZoom; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.enableCloseButton; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.imageDateControl; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.linksControl; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.panControl; /** * @type {google.maps.PanControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.panControlOptions; /** * @type {string} */ google.maps.StreetViewPanoramaOptions.prototype.pano; /** * @type {function(string):google.maps.StreetViewPanoramaData} */ google.maps.StreetViewPanoramaOptions.prototype.panoProvider; /** * @type {google.maps.LatLng} */ google.maps.StreetViewPanoramaOptions.prototype.position; /** * @type {google.maps.StreetViewPov} */ google.maps.StreetViewPanoramaOptions.prototype.pov; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.scrollwheel; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.visible; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.zoomControl; /** * @type {google.maps.ZoomControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.zoomControlOptions; /** * @constructor */ google.maps.StreetViewPov = function() {}; /** * @type {number} */ google.maps.StreetViewPov.prototype.heading; /** * @type {number} */ google.maps.StreetViewPov.prototype.pitch; /** * @type {number} */ google.maps.StreetViewPov.prototype.zoom; /** * @constructor */ google.maps.StreetViewService = function() {}; /** * @param {string} pano * @param {function(google.maps.StreetViewPanoramaData, google.maps.StreetViewStatus)} callback * @return {undefined} */ google.maps.StreetViewService.prototype.getPanoramaById = function(pano, callback) {}; /** * @param {google.maps.LatLng} latlng * @param {number} radius * @param {function(google.maps.StreetViewPanoramaData, google.maps.StreetViewStatus)} callback * @return {undefined} */ google.maps.StreetViewService.prototype.getPanoramaByLocation = function(latlng, radius, callback) {}; /** * @enum {number|string} */ google.maps.StreetViewStatus = { OK: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.StreetViewTileData = function() {}; /** * @type {number} */ google.maps.StreetViewTileData.prototype.centerHeading; /** * @type {google.maps.Size} */ google.maps.StreetViewTileData.prototype.tileSize; /** * @type {google.maps.Size} */ google.maps.StreetViewTileData.prototype.worldSize; /** * @param {string} pano * @param {number} tileZoom * @param {number} tileX * @param {number} tileY * @return {string} */ google.maps.StreetViewTileData.prototype.getTileUrl = function(pano, tileZoom, tileX, tileY) {}; /** * @param {Array.<google.maps.MapTypeStyle>} styles * @param {(google.maps.StyledMapTypeOptions|Object.<string>)=} opt_options * @constructor */ google.maps.StyledMapType = function(styles, opt_options) {}; /** * @constructor */ google.maps.StyledMapTypeOptions = function() {}; /** * @type {string} */ google.maps.StyledMapTypeOptions.prototype.alt; /** * @type {number} */ google.maps.StyledMapTypeOptions.prototype.maxZoom; /** * @type {number} */ google.maps.StyledMapTypeOptions.prototype.minZoom; /** * @type {string} */ google.maps.StyledMapTypeOptions.prototype.name; /** * @constructor */ google.maps.Symbol = function() {}; /** * @type {google.maps.Point} */ google.maps.Symbol.prototype.anchor; /** * @type {string} */ google.maps.Symbol.prototype.fillColor; /** * @type {number} */ google.maps.Symbol.prototype.fillOpacity; /** * @type {google.maps.SymbolPath|string} */ google.maps.Symbol.prototype.path; /** * @type {number} */ google.maps.Symbol.prototype.rotation; /** * @type {number} */ google.maps.Symbol.prototype.scale; /** * @type {string} */ google.maps.Symbol.prototype.strokeColor; /** * @type {number} */ google.maps.Symbol.prototype.strokeOpacity; /** * @type {number} */ google.maps.Symbol.prototype.strokeWeight; /** * @enum {number|string} */ google.maps.SymbolPath = { BACKWARD_CLOSED_ARROW: '', BACKWARD_OPEN_ARROW: '', CIRCLE: '', FORWARD_CLOSED_ARROW: '', FORWARD_OPEN_ARROW: '' }; /** * @constructor */ google.maps.Time = function() {}; /** * @type {string} */ google.maps.Time.prototype.text; /** * @type {string} */ google.maps.Time.prototype.time_zone; /** * @type {Date} */ google.maps.Time.prototype.value; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.TrafficLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.TrafficLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.TrafficLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.TransitAgency = function() {}; /** * @type {string} */ google.maps.TransitAgency.prototype.name; /** * @type {string} */ google.maps.TransitAgency.prototype.phone; /** * @type {string} */ google.maps.TransitAgency.prototype.url; /** * @constructor */ google.maps.TransitDetails = function() {}; /** * @type {google.maps.TransitStop} */ google.maps.TransitDetails.prototype.arrival_stop; /** * @type {google.maps.Time} */ google.maps.TransitDetails.prototype.arrival_time; /** * @type {google.maps.TransitStop} */ google.maps.TransitDetails.prototype.departure_stop; /** * @type {google.maps.Time} */ google.maps.TransitDetails.prototype.departure_time; /** * @type {string} */ google.maps.TransitDetails.prototype.headsign; /** * @type {number} */ google.maps.TransitDetails.prototype.headway; /** * @type {google.maps.TransitLine} */ google.maps.TransitDetails.prototype.line; /** * @type {number} */ google.maps.TransitDetails.prototype.num_stops; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.TransitLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.TransitLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.TransitLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.TransitLine = function() {}; /** * @type {Array.<google.maps.TransitAgency>} */ google.maps.TransitLine.prototype.agencies; /** * @type {string} */ google.maps.TransitLine.prototype.color; /** * @type {string} */ google.maps.TransitLine.prototype.icon; /** * @type {string} */ google.maps.TransitLine.prototype.name; /** * @type {string} */ google.maps.TransitLine.prototype.short_name; /** * @type {string} */ google.maps.TransitLine.prototype.text_color; /** * @type {string} */ google.maps.TransitLine.prototype.url; /** * @type {google.maps.TransitVehicle} */ google.maps.TransitLine.prototype.vehicle; /** * @constructor */ google.maps.TransitOptions = function() {}; /** * @type {Date} */ google.maps.TransitOptions.prototype.arrivalTime; /** * @type {Date} */ google.maps.TransitOptions.prototype.departureTime; /** * @constructor */ google.maps.TransitStop = function() {}; /** * @type {google.maps.LatLng} */ google.maps.TransitStop.prototype.location; /** * @type {string} */ google.maps.TransitStop.prototype.name; /** * @constructor */ google.maps.TransitVehicle = function() {}; /** * @type {string} */ google.maps.TransitVehicle.prototype.icon; /** * @type {string} */ google.maps.TransitVehicle.prototype.local_icon; /** * @type {string} */ google.maps.TransitVehicle.prototype.name; /** * @enum {number|string} */ google.maps.TravelMode = { BICYCLING: '', DRIVING: '', TRANSIT: '', WALKING: '' }; /** * @enum {number|string} */ google.maps.UnitSystem = { IMPERIAL: '', METRIC: '' }; /** * @constructor */ google.maps.ZoomControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.ZoomControlOptions.prototype.position; /** * @type {google.maps.ZoomControlStyle} */ google.maps.ZoomControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.ZoomControlStyle = { DEFAULT: '', LARGE: '', SMALL: '' }; // Namespace google.maps.adsense = {}; /** * @enum {number|string} */ google.maps.adsense.AdFormat = { BANNER: '', BUTTON: '', HALF_BANNER: '', LARGE_RECTANGLE: '', LEADERBOARD: '', MEDIUM_RECTANGLE: '', SKYSCRAPER: '', SMALL_RECTANGLE: '', SMALL_SQUARE: '', SQUARE: '', VERTICAL_BANNER: '', WIDE_SKYSCRAPER: '' }; /** * @param {Node} container * @param {google.maps.adsense.AdUnitOptions|Object.<string>} opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.adsense.AdUnit = function(container, opts) {}; /** * @nosideeffects * @return {string} */ google.maps.adsense.AdUnit.prototype.getChannelNumber = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.adsense.AdUnit.prototype.getContainer = function() {}; /** * @nosideeffects * @return {google.maps.adsense.AdFormat} */ google.maps.adsense.AdUnit.prototype.getFormat = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.adsense.AdUnit.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.ControlPosition} */ google.maps.adsense.AdUnit.prototype.getPosition = function() {}; /** * @nosideeffects * @return {string} */ google.maps.adsense.AdUnit.prototype.getPublisherId = function() {}; /** * @param {string} channelNumber * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setChannelNumber = function(channelNumber) {}; /** * @param {google.maps.adsense.AdFormat} format * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setFormat = function(format) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setMap = function(map) {}; /** * @param {google.maps.ControlPosition} position * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setPosition = function(position) {}; /** * @constructor */ google.maps.adsense.AdUnitOptions = function() {}; /** * @type {string} */ google.maps.adsense.AdUnitOptions.prototype.channelNumber; /** * @type {google.maps.adsense.AdFormat} */ google.maps.adsense.AdUnitOptions.prototype.format; /** * @type {google.maps.Map} */ google.maps.adsense.AdUnitOptions.prototype.map; /** * @type {google.maps.ControlPosition} */ google.maps.adsense.AdUnitOptions.prototype.position; /** * @type {string} */ google.maps.adsense.AdUnitOptions.prototype.publisherId; // Namespace google.maps.drawing = {}; /** * @constructor */ google.maps.drawing.DrawingControlOptions = function() {}; /** * @type {Array.<google.maps.drawing.OverlayType>} */ google.maps.drawing.DrawingControlOptions.prototype.drawingModes; /** * @type {google.maps.ControlPosition} */ google.maps.drawing.DrawingControlOptions.prototype.position; /** * @param {(google.maps.drawing.DrawingManagerOptions|Object.<string>)=} opt_options * @extends {google.maps.MVCObject} * @constructor */ google.maps.drawing.DrawingManager = function(opt_options) {}; /** * @nosideeffects * @return {?google.maps.drawing.OverlayType} */ google.maps.drawing.DrawingManager.prototype.getDrawingMode = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.drawing.DrawingManager.prototype.getMap = function() {}; /** * @param {?google.maps.drawing.OverlayType} drawingMode * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setDrawingMode = function(drawingMode) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setMap = function(map) {}; /** * @param {google.maps.drawing.DrawingManagerOptions|Object.<string>} options * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.drawing.DrawingManagerOptions = function() {}; /** * @type {google.maps.CircleOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.circleOptions; /** * @type {boolean} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingControl; /** * @type {google.maps.drawing.DrawingControlOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingControlOptions; /** * @type {google.maps.drawing.OverlayType} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingMode; /** * @type {google.maps.Map} */ google.maps.drawing.DrawingManagerOptions.prototype.map; /** * @type {google.maps.MarkerOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.markerOptions; /** * @type {google.maps.PolygonOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.polygonOptions; /** * @type {google.maps.PolylineOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.polylineOptions; /** * @type {google.maps.RectangleOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.rectangleOptions; /** * @constructor */ google.maps.drawing.OverlayCompleteEvent = function() {}; /** * @type {google.maps.Marker|google.maps.Polygon|google.maps.Polyline|google.maps.Rectangle|google.maps.Circle} */ google.maps.drawing.OverlayCompleteEvent.prototype.overlay; /** * @type {google.maps.drawing.OverlayType} */ google.maps.drawing.OverlayCompleteEvent.prototype.type; /** * @enum {number|string} */ google.maps.drawing.OverlayType = { CIRCLE: '', MARKER: '', POLYGON: '', POLYLINE: '', RECTANGLE: '' }; // Namespace google.maps.event = {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @param {boolean=} opt_capture * @return {google.maps.MapsEventListener} */ google.maps.event.addDomListener = function(instance, eventName, handler, opt_capture) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @param {boolean=} opt_capture * @return {google.maps.MapsEventListener} */ google.maps.event.addDomListenerOnce = function(instance, eventName, handler, opt_capture) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @return {google.maps.MapsEventListener} */ google.maps.event.addListener = function(instance, eventName, handler) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @return {google.maps.MapsEventListener} */ google.maps.event.addListenerOnce = function(instance, eventName, handler) {}; /** * @param {Object} instance * @return {undefined} */ google.maps.event.clearInstanceListeners = function(instance) {}; /** * @param {Object} instance * @param {string} eventName * @return {undefined} */ google.maps.event.clearListeners = function(instance, eventName) {}; /** * @param {google.maps.MapsEventListener} listener * @return {undefined} */ google.maps.event.removeListener = function(listener) {}; /** * @param {Object} instance * @param {string} eventName * @param {...*} var_args * @return {undefined} */ google.maps.event.trigger = function(instance, eventName, var_args) {}; // Namespace google.maps.geometry = {}; // Namespace google.maps.geometry.encoding = {}; /** * @param {string} encodedPath * @return {Array.<google.maps.LatLng>} */ google.maps.geometry.encoding.decodePath = function(encodedPath) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @return {string} */ google.maps.geometry.encoding.encodePath = function(path) {}; // Namespace google.maps.geometry.poly = {}; /** * @param {google.maps.LatLng} point * @param {google.maps.Polygon} polygon * @return {boolean} */ google.maps.geometry.poly.containsLocation = function(point, polygon) {}; /** * @param {google.maps.LatLng} point * @param {google.maps.Polygon|google.maps.Polyline} poly * @param {number=} opt_tolerance * @return {boolean} */ google.maps.geometry.poly.isLocationOnEdge = function(point, poly, opt_tolerance) {}; // Namespace google.maps.geometry.spherical = {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeArea = function(path, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeDistanceBetween = function(from, to, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @return {number} */ google.maps.geometry.spherical.computeHeading = function(from, to) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeLength = function(path, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {number} distance * @param {number} heading * @param {number=} opt_radius * @return {google.maps.LatLng} */ google.maps.geometry.spherical.computeOffset = function(from, distance, heading, opt_radius) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} loop * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeSignedArea = function(loop, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @param {number} fraction * @return {google.maps.LatLng} */ google.maps.geometry.spherical.interpolate = function(from, to, fraction) {}; // Namespace google.maps.panoramio = {}; /** * @constructor */ google.maps.panoramio.PanoramioFeature = function() {}; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.author; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.photoId; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.title; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.url; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.userId; /** * @param {(google.maps.panoramio.PanoramioLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.panoramio.PanoramioLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.panoramio.PanoramioLayer.prototype.getMap = function() {}; /** * @nosideeffects * @return {string} */ google.maps.panoramio.PanoramioLayer.prototype.getTag = function() {}; /** * @nosideeffects * @return {string} */ google.maps.panoramio.PanoramioLayer.prototype.getUserId = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.panoramio.PanoramioLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setOptions = function(options) {}; /** * @param {string} tag * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setTag = function(tag) {}; /** * @param {string} userId * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setUserId = function(userId) {}; /** * @constructor */ google.maps.panoramio.PanoramioLayerOptions = function() {}; /** * @type {boolean} */ google.maps.panoramio.PanoramioLayerOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.panoramio.PanoramioLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.panoramio.PanoramioLayerOptions.prototype.suppressInfoWindows; /** * @type {string} */ google.maps.panoramio.PanoramioLayerOptions.prototype.tag; /** * @type {string} */ google.maps.panoramio.PanoramioLayerOptions.prototype.userId; /** * @constructor */ google.maps.panoramio.PanoramioMouseEvent = function() {}; /** * @type {google.maps.panoramio.PanoramioFeature} */ google.maps.panoramio.PanoramioMouseEvent.prototype.featureDetails; /** * @type {string} */ google.maps.panoramio.PanoramioMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.panoramio.PanoramioMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.panoramio.PanoramioMouseEvent.prototype.pixelOffset; // Namespace google.maps.places = {}; /** * @param {HTMLInputElement} inputField * @param {(google.maps.places.AutocompleteOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.places.Autocomplete = function(inputField, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.places.Autocomplete.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.places.PlaceResult} */ google.maps.places.Autocomplete.prototype.getPlace = function() {}; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.places.Autocomplete.prototype.setBounds = function(bounds) {}; /** * @param {google.maps.places.ComponentRestrictions} restrictions * @return {undefined} */ google.maps.places.Autocomplete.prototype.setComponentRestrictions = function(restrictions) {}; /** * @param {Array.<string>} types * @return {undefined} */ google.maps.places.Autocomplete.prototype.setTypes = function(types) {}; /** * @constructor */ google.maps.places.AutocompleteOptions = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.AutocompleteOptions.prototype.bounds; /** * @type {google.maps.places.ComponentRestrictions} */ google.maps.places.AutocompleteOptions.prototype.componentRestrictions; /** * @type {Array.<string>} */ google.maps.places.AutocompleteOptions.prototype.types; /** * @constructor */ google.maps.places.ComponentRestrictions = function() {}; /** * @type {string} */ google.maps.places.ComponentRestrictions.prototype.country; /** * @constructor */ google.maps.places.PlaceDetailsRequest = function() {}; /** * @type {string} */ google.maps.places.PlaceDetailsRequest.prototype.reference; /** * @constructor */ google.maps.places.PlaceGeometry = function() {}; /** * @type {google.maps.LatLng} */ google.maps.places.PlaceGeometry.prototype.location; /** * @type {google.maps.LatLngBounds} */ google.maps.places.PlaceGeometry.prototype.viewport; /** * @constructor */ google.maps.places.PlaceResult = function() {}; /** * @type {Array.<google.maps.GeocoderAddressComponent>} */ google.maps.places.PlaceResult.prototype.address_components; /** * @type {string} */ google.maps.places.PlaceResult.prototype.formatted_address; /** * @type {string} */ google.maps.places.PlaceResult.prototype.formatted_phone_number; /** * @type {google.maps.places.PlaceGeometry} */ google.maps.places.PlaceResult.prototype.geometry; /** * @type {Array.<string>} */ google.maps.places.PlaceResult.prototype.html_attributions; /** * @type {string} */ google.maps.places.PlaceResult.prototype.icon; /** * @type {string} */ google.maps.places.PlaceResult.prototype.id; /** * @type {string} */ google.maps.places.PlaceResult.prototype.international_phone_number; /** * @type {string} */ google.maps.places.PlaceResult.prototype.name; /** * @type {number} */ google.maps.places.PlaceResult.prototype.rating; /** * @type {string} */ google.maps.places.PlaceResult.prototype.reference; /** * @type {Array.<string>} */ google.maps.places.PlaceResult.prototype.types; /** * @type {string} */ google.maps.places.PlaceResult.prototype.url; /** * @type {string} */ google.maps.places.PlaceResult.prototype.vicinity; /** * @type {string} */ google.maps.places.PlaceResult.prototype.website; /** * @constructor */ google.maps.places.PlaceSearchPagination = function() {}; /** * @type {boolean} */ google.maps.places.PlaceSearchPagination.prototype.hasNextPage; /** * @return {undefined} */ google.maps.places.PlaceSearchPagination.prototype.nextPage = function() {}; /** * @constructor */ google.maps.places.PlaceSearchRequest = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.PlaceSearchRequest.prototype.bounds; /** * @type {string} */ google.maps.places.PlaceSearchRequest.prototype.keyword; /** * @type {google.maps.LatLng} */ google.maps.places.PlaceSearchRequest.prototype.location; /** * @type {string} */ google.maps.places.PlaceSearchRequest.prototype.name; /** * @type {number} */ google.maps.places.PlaceSearchRequest.prototype.radius; /** * @type {google.maps.places.RankBy} */ google.maps.places.PlaceSearchRequest.prototype.rankBy; /** * @type {Array.<string>} */ google.maps.places.PlaceSearchRequest.prototype.types; /** * @param {HTMLDivElement|google.maps.Map} attrContainer * @constructor */ google.maps.places.PlacesService = function(attrContainer) {}; /** * @param {google.maps.places.PlaceDetailsRequest|Object.<string>} request * @param {function(google.maps.places.PlaceResult, google.maps.places.PlacesServiceStatus)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.getDetails = function(request, callback) {}; /** * @param {google.maps.places.PlaceSearchRequest|Object.<string>} request * @param {function(Array.<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus, google.maps.places.PlaceSearchPagination)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.nearbySearch = function(request, callback) {}; /** * @param {google.maps.places.TextSearchRequest|Object.<string>} request * @param {function(Array.<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.textSearch = function(request, callback) {}; /** * @enum {number|string} */ google.maps.places.PlacesServiceStatus = { INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @enum {number|string} */ google.maps.places.RankBy = { DISTANCE: '', PROMINENCE: '' }; /** * @constructor */ google.maps.places.TextSearchRequest = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.TextSearchRequest.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.places.TextSearchRequest.prototype.location; /** * @type {string} */ google.maps.places.TextSearchRequest.prototype.query; /** * @type {number} */ google.maps.places.TextSearchRequest.prototype.radius; // Namespace google.maps.visualization = {}; /** * @param {(google.maps.visualization.HeatmapLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.visualization.HeatmapLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng|google.maps.visualization.WeightedLocation>} */ google.maps.visualization.HeatmapLayer.prototype.getData = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.visualization.HeatmapLayer.prototype.getMap = function() {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng|google.maps.visualization.WeightedLocation>|Array.<google.maps.LatLng|google.maps.visualization.WeightedLocation>} data * @return {undefined} */ google.maps.visualization.HeatmapLayer.prototype.setData = function(data) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.visualization.HeatmapLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.visualization.HeatmapLayerOptions = function() {}; /** * @type {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.visualization.HeatmapLayerOptions.prototype.data; /** * @type {boolean} */ google.maps.visualization.HeatmapLayerOptions.prototype.dissipating; /** * @type {Array.<string>} */ google.maps.visualization.HeatmapLayerOptions.prototype.gradient; /** * @type {google.maps.Map} */ google.maps.visualization.HeatmapLayerOptions.prototype.map; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.maxIntensity; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.opacity; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.radius; /** * @constructor */ google.maps.visualization.WeightedLocation = function() {}; /** * @type {google.maps.LatLng} */ google.maps.visualization.WeightedLocation.prototype.location; /** * @type {number} */ google.maps.visualization.WeightedLocation.prototype.weight; // Namespace google.maps.weather = {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.weather.CloudLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.weather.CloudLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.weather.CloudLayer.prototype.setMap = function(map) {}; /** * @enum {number|string} */ google.maps.weather.LabelColor = { BLACK: '', WHITE: '' }; /** * @enum {number|string} */ google.maps.weather.TemperatureUnit = { CELSIUS: '', FAHRENHEIT: '' }; /** * @constructor */ google.maps.weather.WeatherConditions = function() {}; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.day; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.description; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.high; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.humidity; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.low; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.shortDay; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.temperature; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.windDirection; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.windSpeed; /** * @constructor */ google.maps.weather.WeatherFeature = function() {}; /** * @type {google.maps.weather.WeatherConditions} */ google.maps.weather.WeatherFeature.prototype.current; /** * @type {Array.<google.maps.weather.WeatherForecast>} */ google.maps.weather.WeatherFeature.prototype.forecast; /** * @type {string} */ google.maps.weather.WeatherFeature.prototype.location; /** * @type {google.maps.weather.TemperatureUnit} */ google.maps.weather.WeatherFeature.prototype.temperatureUnit; /** * @type {google.maps.weather.WindSpeedUnit} */ google.maps.weather.WeatherFeature.prototype.windSpeedUnit; /** * @constructor */ google.maps.weather.WeatherForecast = function() {}; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.day; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.description; /** * @type {number} */ google.maps.weather.WeatherForecast.prototype.high; /** * @type {number} */ google.maps.weather.WeatherForecast.prototype.low; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.shortDay; /** * @param {(google.maps.weather.WeatherLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.weather.WeatherLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.weather.WeatherLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.weather.WeatherLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.weather.WeatherLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.weather.WeatherLayer.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.weather.WeatherLayerOptions = function() {}; /** * @type {boolean} */ google.maps.weather.WeatherLayerOptions.prototype.clickable; /** * @type {google.maps.weather.LabelColor} */ google.maps.weather.WeatherLayerOptions.prototype.labelColor; /** * @type {google.maps.Map} */ google.maps.weather.WeatherLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.weather.WeatherLayerOptions.prototype.suppressInfoWindows; /** * @type {google.maps.weather.TemperatureUnit} */ google.maps.weather.WeatherLayerOptions.prototype.temperatureUnits; /** * @type {google.maps.weather.WindSpeedUnit} */ google.maps.weather.WeatherLayerOptions.prototype.windSpeedUnits; /** * @constructor */ google.maps.weather.WeatherMouseEvent = function() {}; /** * @type {google.maps.weather.WeatherFeature} */ google.maps.weather.WeatherMouseEvent.prototype.featureDetails; /** * @type {string} */ google.maps.weather.WeatherMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.weather.WeatherMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.weather.WeatherMouseEvent.prototype.pixelOffset; /** * @enum {number|string} */ google.maps.weather.WindSpeedUnit = { KILOMETERS_PER_HOUR: '', METERS_PER_SECOND: '', MILES_PER_HOUR: '' };
joshuamiller/hbg-crime
src/cljs/google_maps_api_v3.js
JavaScript
mit
99,957
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: src/input/Input.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/default.css"> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div style="position: absolute; width: 143px; height: 31px; right: 10px; top: 10px; z-index: 1050"><a href="http://phaser.io"><img src="img/phaser.png" border="0" /></a></div> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser API</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> <li class="class-depth-0"> <a href="Phaser.KeyCode.html">KeyCode</a> </li> <li class="class-depth-0"> <a href="PIXI.html">PIXI</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArraySet.html">ArraySet</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayUtils.html">ArrayUtils</a> </li> <li class="class-depth-1"> <a href="Phaser.AudioSprite.html">AudioSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Angle.html">Angle</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Animation.html">Animation</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.AutoCull.html">AutoCull</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Bounds.html">Bounds</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.BringToTop.html">BringToTop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Core.html">Core</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Crop.html">Crop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Delta.html">Delta</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Destroy.html">Destroy</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.FixedToCamera.html">FixedToCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Health.html">Health</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InCamera.html">InCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InputEnabled.html">InputEnabled</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InWorld.html">InWorld</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LifeSpan.html">LifeSpan</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LoadTexture.html">LoadTexture</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Overlap.html">Overlap</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.PhysicsBody.html">PhysicsBody</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Reset.html">Reset</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.ScaleMinMax.html">ScaleMinMax</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Smoothed.html">Smoothed</a> </li> <li class="class-depth-1"> <a href="Phaser.Create.html">Create</a> </li> <li class="class-depth-1"> <a href="Phaser.Creature.html">Creature</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.DeviceButton.html">DeviceButton</a> </li> <li class="class-depth-1"> <a href="Phaser.DOM.html">DOM</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexGrid.html">FlexGrid</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexLayer.html">FlexLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.ImageCollection.html">ImageCollection</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Matrix.html">Matrix</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-2"> <a href="Phaser.Particles.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.TilemapCollision.html">TilemapCollision</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RotationalSpring.html">RotationalSpring</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.PointerMode.html">PointerMode</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="Phaser.RoundedRectangle.html">RoundedRectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenData.html">TweenData</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.Video.html">Video</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> <li class="class-depth-1"> <a href="PIXI.AbstractFilter.html">AbstractFilter</a> </li> <li class="class-depth-1"> <a href="PIXI.BaseTexture.html">BaseTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasBuffer.html">CanvasBuffer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasGraphics.html">CanvasGraphics</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasMaskManager.html">CanvasMaskManager</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasPool.html">CanvasPool</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasRenderer.html">CanvasRenderer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasTinter.html">CanvasTinter</a> </li> <li class="class-depth-1"> <a href="PIXI.ComplexPrimitiveShader.html">ComplexPrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObject.html">DisplayObject</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObjectContainer.html">DisplayObjectContainer</a> </li> <li class="class-depth-1"> <a href="PIXI.EarCut.html">EarCut</a> </li> <li class="class-depth-1"> <a href="PIXI.Event.html">Event</a> </li> <li class="class-depth-1"> <a href="PIXI.EventTarget.html">EventTarget</a> </li> <li class="class-depth-1"> <a href="PIXI.FilterTexture.html">FilterTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="PIXI.GraphicsData.html">GraphicsData</a> </li> <li class="class-depth-1"> <a href="PIXI.PIXI.html">PIXI</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiFastShader.html">PixiFastShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiShader.html">PixiShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PolyK.html">PolyK</a> </li> <li class="class-depth-1"> <a href="PIXI.PrimitiveShader.html">PrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="PIXI.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="PIXI.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.Strip.html">Strip</a> </li> <li class="class-depth-1"> <a href="PIXI.StripShader.html">StripShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Texture.html">Texture</a> </li> <li class="class-depth-1"> <a href="PIXI.TilingSprite.html">TilingSprite</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLBlendModeManager.html">WebGLBlendModeManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFastSpriteBatch.html">WebGLFastSpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFilterManager.html">WebGLFilterManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLRenderer.html">WebGLRenderer</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="global.html#AUTO">AUTO</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPDATA">BITMAPDATA</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPTEXT">BITMAPTEXT</a> </li> <li class="class-depth-0"> <a href="global.html#blendModes">blendModes</a> </li> <li class="class-depth-0"> <a href="global.html#BUTTON">BUTTON</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS">CANVAS</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS_FILTER">CANVAS_FILTER</a> </li> <li class="class-depth-0"> <a href="global.html#CIRCLE">CIRCLE</a> </li> <li class="class-depth-0"> <a href="global.html#CREATURE">CREATURE</a> </li> <li class="class-depth-0"> <a href="global.html#DOWN">DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ELLIPSE">ELLIPSE</a> </li> <li class="class-depth-0"> <a href="global.html#EMITTER">EMITTER</a> </li> <li class="class-depth-0"> <a href="global.html#GAMES">GAMES</a> </li> <li class="class-depth-0"> <a href="global.html#GRAPHICS">GRAPHICS</a> </li> <li class="class-depth-0"> <a href="global.html#GROUP">GROUP</a> </li> <li class="class-depth-0"> <a href="global.html#HEADLESS">HEADLESS</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#PENDING_ATLAS">PENDING_ATLAS</a> </li> <li class="class-depth-0"> <a href="global.html#POINT">POINT</a> </li> <li class="class-depth-0"> <a href="global.html#POINTER">POINTER</a> </li> <li class="class-depth-0"> <a href="global.html#POLYGON">POLYGON</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#RENDERTEXTURE">RENDERTEXTURE</a> </li> <li class="class-depth-0"> <a href="global.html#RETROFONT">RETROFONT</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT">RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ROPE">ROPE</a> </li> <li class="class-depth-0"> <a href="global.html#ROUNDEDRECTANGLE">ROUNDEDRECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#scaleModes">scaleModes</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITE">SPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITEBATCH">SPRITEBATCH</a> </li> <li class="class-depth-0"> <a href="global.html#TEXT">TEXT</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAP">TILEMAP</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAPLAYER">TILEMAPLAYER</a> </li> <li class="class-depth-0"> <a href="global.html#TILESPRITE">TILESPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#UP">UP</a> </li> <li class="class-depth-0"> <a href="global.html#VERSION">VERSION</a> </li> <li class="class-depth-0"> <a href="global.html#VIDEO">VIDEO</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL">WEBGL</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL_FILTER">WEBGL_FILTER</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Core<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Game.html">Game</a></li> <li class="class-depth-1"><a href="Phaser.Group.html">Group</a></li> <li class="class-depth-1"><a href="Phaser.World.html">World</a></li> <li class="class-depth-1"><a href="Phaser.Loader.html">Loader</a></li> <li class="class-depth-1"><a href="Phaser.Cache.html">Cache</a></li> <li class="class-depth-1"><a href="Phaser.Time.html">Time</a></li> <li class="class-depth-1"><a href="Phaser.Camera.html">Camera</a></li> <li class="class-depth-1"><a href="Phaser.StateManager.html">State Manager</a></li> <li class="class-depth-1"><a href="Phaser.TweenManager.html">Tween Manager</a></li> <li class="class-depth-1"><a href="Phaser.SoundManager.html">Sound Manager</a></li> <li class="class-depth-1"><a href="Phaser.Input.html">Input Manager</a></li> <li class="class-depth-1"><a href="Phaser.ScaleManager.html">Scale Manager</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Game Objects<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.GameObjectFactory.html">Factory (game.add)</a></li> <li class="class-depth-1"><a href="Phaser.GameObjectCreator.html">Creator (game.make)</a></li> <li class="class-depth-1"><a href="Phaser.Sprite.html">Sprite</a></li> <li class="class-depth-1"><a href="Phaser.Image.html">Image</a></li> <li class="class-depth-1"><a href="Phaser.Sound.html">Sound</a></li> <li class="class-depth-1"><a href="Phaser.Video.html">Video</a></li> <li class="class-depth-1"><a href="Phaser.Particles.Arcade.Emitter.html">Particle Emitter</a></li> <li class="class-depth-1"><a href="Phaser.Particle.html">Particle</a></li> <li class="class-depth-1"><a href="Phaser.Text.html">Text</a></li> <li class="class-depth-1"><a href="Phaser.Tween.html">Tween</a></li> <li class="class-depth-1"><a href="Phaser.BitmapText.html">BitmapText</a></li> <li class="class-depth-1"><a href="Phaser.Tilemap.html">Tilemap</a></li> <li class="class-depth-1"><a href="Phaser.BitmapData.html">BitmapData</a></li> <li class="class-depth-1"><a href="Phaser.RetroFont.html">RetroFont</a></li> <li class="class-depth-1"><a href="Phaser.Button.html">Button</a></li> <li class="class-depth-1"><a href="Phaser.Animation.html">Animation</a></li> <li class="class-depth-1"><a href="Phaser.Graphics.html">Graphics</a></li> <li class="class-depth-1"><a href="Phaser.RenderTexture.html">RenderTexture</a></li> <li class="class-depth-1"><a href="Phaser.TileSprite.html">TileSprite</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Geometry<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Circle.html">Circle</a></li> <li class="class-depth-1"><a href="Phaser.Ellipse.html">Ellipse</a></li> <li class="class-depth-1"><a href="Phaser.Line.html">Line</a></li> <li class="class-depth-1"><a href="Phaser.Matrix.html">Matrix</a></li> <li class="class-depth-1"><a href="Phaser.Point.html">Point</a></li> <li class="class-depth-1"><a href="Phaser.Polygon.html">Polygon</a></li> <li class="class-depth-1"><a href="Phaser.Rectangle.html">Rectangle</a></li> <li class="class-depth-1"><a href="Phaser.RoundedRectangle.html">Rounded Rectangle</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Physics<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Physics.Arcade.html">Arcade Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Arcade.Body.html">Body</a></li> <li class="class-depth-1"><a href="Phaser.Physics.P2.html">P2 Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Spring.html">Spring</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a></li> <li class="class-depth-1"><a href="Phaser.Physics.Ninja.html">Ninja Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Body.html">Body</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Input<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.InputHandler.html">Input Handler</a></li> <li class="class-depth-1"><a href="Phaser.Pointer.html">Pointer</a></li> <li class="class-depth-1"><a href="Phaser.DeviceButton.html">Device Button</a></li> <li class="class-depth-1"><a href="Phaser.Mouse.html">Mouse</a></li> <li class="class-depth-1"><a href="Phaser.Keyboard.html">Keyboard</a></li> <li class="class-depth-1"><a href="Phaser.Key.html">Key</a></li> <li class="class-depth-1"><a href="Phaser.Gamepad.html">Gamepad</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Community<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="http://phaser.io">Phaser Web Site</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser">Phaser Github</a></li> <li class="class-depth-1"><a href="http://phaser.io/examples">Phaser Examples</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-plugins">Phaser Plugins</a></li> <li class="class-depth-1"><a href="http://www.html5gamedevs.com/forum/14-phaser/">Forum</a></li> <li class="class-depth-1"><a href="http://stackoverflow.com/questions/tagged/phaser-framework">Stack Overflow</a></li> <li class="class-depth-1"><a href="http://phaser.io/learn">Tutorials</a></li> <li class="class-depth-1"><a href="https://confirmsubscription.com/h/r/369DE48E3E86AF1E">Newsletter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/twitter">Twitter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/irc">IRC</a></li> <li class="class-depth-1"><a href="https://www.codeandweb.com/texturepacker/phaser">Texture Packer</a></li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: src/input/Input.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Richard Davey &lt;[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer. * The Input manager is updated automatically by the core game loop. * * @class Phaser.Input * @constructor * @param {Phaser.Game} game - Current game instance. */ Phaser.Input = function (game) { /** * @property {Phaser.Game} game - A reference to the currently running game. */ this.game = game; /** * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection. * @default */ this.hitCanvas = null; /** * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas. * @default */ this.hitContext = null; /** * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM. * To add a callback to this array please use `Input.addMoveCallback`. * @property {array} moveCallbacks * @protected */ this.moveCallbacks = []; /** * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on. * @default */ this.pollRate = 0; /** * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves. * * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`. * @property {boolean} enabled * @default */ this.enabled = true; /** * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device. * @default */ this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE; /** * @property {Phaser.Point} position - A point object representing the current position of the Pointer. * @default */ this.position = null; /** * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly. */ this.speed = null; /** * A Circle object centered on the x/y screen coordinates of the Input. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. * @property {Phaser.Circle} circle */ this.circle = null; /** * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1. */ this.scale = null; /** * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1. * @default -1 (Limited by total pointers.) */ this.maxPointers = -1; /** * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click. * @default */ this.tapRate = 200; /** * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click. * @default */ this.doubleTapRate = 300; /** * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event. * @default */ this.holdRate = 2000; /** * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed. * @default */ this.justPressedRate = 200; /** * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased . * @default */ this.justReleasedRate = 200; /** * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. * The history is cleared each time the Pointer is pressed down. * The history is updated at the rate specified in Input.pollRate * @property {boolean} recordPointerHistory * @default */ this.recordPointerHistory = false; /** * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history. * @default */ this.recordRate = 100; /** * The total number of entries that can be recorded into the Pointer objects tracking history. * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history. * @property {number} recordLimit * @default */ this.recordLimit = 100; /** * @property {Phaser.Pointer} pointer1 - A Pointer object. */ this.pointer1 = null; /** * @property {Phaser.Pointer} pointer2 - A Pointer object. */ this.pointer2 = null; /** * @property {Phaser.Pointer} pointer3 - A Pointer object. */ this.pointer3 = null; /** * @property {Phaser.Pointer} pointer4 - A Pointer object. */ this.pointer4 = null; /** * @property {Phaser.Pointer} pointer5 - A Pointer object. */ this.pointer5 = null; /** * @property {Phaser.Pointer} pointer6 - A Pointer object. */ this.pointer6 = null; /** * @property {Phaser.Pointer} pointer7 - A Pointer object. */ this.pointer7 = null; /** * @property {Phaser.Pointer} pointer8 - A Pointer object. */ this.pointer8 = null; /** * @property {Phaser.Pointer} pointer9 - A Pointer object. */ this.pointer9 = null; /** * @property {Phaser.Pointer} pointer10 - A Pointer object. */ this.pointer10 = null; /** * An array of non-mouse pointers that have been added to the game. * The properties `pointer1..N` are aliases for `pointers[0..N-1]`. * @property {Phaser.Pointer[]} pointers * @public * @readonly */ this.pointers = []; /** * The most recently active Pointer object. * * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. * * @property {Phaser.Pointer} activePointer */ this.activePointer = null; /** * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. * * @property {Pointer} mousePointer */ this.mousePointer = null; /** * The Mouse Input manager. * * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer * which normalizes all the input values for you, regardless of browser. * * @property {Phaser.Mouse} mouse */ this.mouse = null; /** * The Keyboard Input manager. * * @property {Phaser.Keyboard} keyboard */ this.keyboard = null; /** * The Touch Input manager. * * You should not usually access this manager directly, but instead use Input.activePointer * which normalizes all the input values for you, regardless of browser. * * @property {Phaser.Touch} touch */ this.touch = null; /** * The MSPointer Input manager. * * You should not usually access this manager directly, but instead use Input.activePointer * which normalizes all the input values for you, regardless of browser. * * @property {Phaser.MSPointer} mspointer */ this.mspointer = null; /** * The Gamepad Input manager. * * @property {Phaser.Gamepad} gamepad */ this.gamepad = null; /** * If the Input Manager has been reset locked then all calls made to InputManager.reset, * such as from a State change, are ignored. * @property {boolean} resetLocked * @default */ this.resetLocked = false; /** * A Signal that is dispatched each time a pointer is pressed down. * @property {Phaser.Signal} onDown */ this.onDown = null; /** * A Signal that is dispatched each time a pointer is released. * @property {Phaser.Signal} onUp */ this.onUp = null; /** * A Signal that is dispatched each time a pointer is tapped. * @property {Phaser.Signal} onTap */ this.onTap = null; /** * A Signal that is dispatched each time a pointer is held down. * @property {Phaser.Signal} onHold */ this.onHold = null; /** * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value. * This is useful when stacking UI layers. Set to zero to disable. * @property {number} minPriorityID * @default */ this.minPriorityID = 0; /** * A list of interactive objects. The InputHandler components add and remove themselves from this list. * @property {Phaser.ArraySet} interactiveItems */ this.interactiveItems = new Phaser.ArraySet(); /** * @property {Phaser.Point} _localPoint - Internal cache var. * @private */ this._localPoint = new Phaser.Point(); /** * @property {number} _pollCounter - Internal var holding the current poll counter. * @private */ this._pollCounter = 0; /** * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer. * @private */ this._oldPosition = null; /** * @property {number} _x - x coordinate of the most recent Pointer event * @private */ this._x = 0; /** * @property {number} _y - Y coordinate of the most recent Pointer event * @private */ this._y = 0; }; /** * @constant * @type {number} */ Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; /** * @constant * @type {number} */ Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; /** * @constant * @type {number} */ Phaser.Input.MOUSE_TOUCH_COMBINE = 2; /** * The maximum number of pointers that can be added. This excludes the mouse pointer. * @constant * @type {integer} */ Phaser.Input.MAX_POINTERS = 10; Phaser.Input.prototype = { /** * Starts the Input Manager running. * * @method Phaser.Input#boot * @protected */ boot: function () { this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR); this.addPointer(); this.addPointer(); this.mouse = new Phaser.Mouse(this.game); this.touch = new Phaser.Touch(this.game); this.mspointer = new Phaser.MSPointer(this.game); if (Phaser.Keyboard) { this.keyboard = new Phaser.Keyboard(this.game); } if (Phaser.Gamepad) { this.gamepad = new Phaser.Gamepad(this.game); } this.onDown = new Phaser.Signal(); this.onUp = new Phaser.Signal(); this.onTap = new Phaser.Signal(); this.onHold = new Phaser.Signal(); this.scale = new Phaser.Point(1, 1); this.speed = new Phaser.Point(); this.position = new Phaser.Point(); this._oldPosition = new Phaser.Point(); this.circle = new Phaser.Circle(0, 0, 44); this.activePointer = this.mousePointer; this.hitCanvas = PIXI.CanvasPool.create(this, 1, 1); this.hitContext = this.hitCanvas.getContext('2d'); this.mouse.start(); this.touch.start(); this.mspointer.start(); this.mousePointer.active = true; if (this.keyboard) { this.keyboard.start(); } var _this = this; this._onClickTrampoline = function (event) { _this.onClickTrampoline(event); }; this.game.canvas.addEventListener('click', this._onClickTrampoline, false); }, /** * Stops all of the Input Managers from running. * * @method Phaser.Input#destroy */ destroy: function () { this.mouse.stop(); this.touch.stop(); this.mspointer.stop(); if (this.keyboard) { this.keyboard.stop(); } if (this.gamepad) { this.gamepad.stop(); } this.moveCallbacks = []; PIXI.CanvasPool.remove(this); this.game.canvas.removeEventListener('click', this._onClickTrampoline); }, /** * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove. * * The callback will be sent 4 parameters: The Pointer that moved, the x position of the pointer, the y position and the down state. * * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best * to only use if you've limited input to a single pointer (i.e. mouse or touch). * * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback. * * @method Phaser.Input#addMoveCallback * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event. * @param {object} context - The context in which the callback will be called. */ addMoveCallback: function (callback, context) { this.moveCallbacks.push({ callback: callback, context: context }); }, /** * Removes the callback from the Phaser.Input.moveCallbacks array. * * @method Phaser.Input#deleteMoveCallback * @param {function} callback - The callback to be removed. * @param {object} context - The context in which the callback exists. */ deleteMoveCallback: function (callback, context) { var i = this.moveCallbacks.length; while (i--) { if (this.moveCallbacks[i].callback === callback &amp;&amp; this.moveCallbacks[i].context === context) { this.moveCallbacks.splice(i, 1); return; } } }, /** * Add a new Pointer object to the Input Manager. * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`. * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10). * * @method Phaser.Input#addPointer * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added. */ addPointer: function () { if (this.pointers.length >= Phaser.Input.MAX_POINTERS) { console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached."); return null; } var id = this.pointers.length + 1; var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.TOUCH); this.pointers.push(pointer); this['pointer' + id] = pointer; return pointer; }, /** * Updates the Input Manager. Called by the core Game loop. * * @method Phaser.Input#update * @protected */ update: function () { if (this.keyboard) { this.keyboard.update(); } if (this.pollRate > 0 &amp;&amp; this._pollCounter &lt; this.pollRate) { this._pollCounter++; return; } this.speed.x = this.position.x - this._oldPosition.x; this.speed.y = this.position.y - this._oldPosition.y; this._oldPosition.copyFrom(this.position); this.mousePointer.update(); if (this.gamepad &amp;&amp; this.gamepad.active) { this.gamepad.update(); } for (var i = 0; i &lt; this.pointers.length; i++) { this.pointers[i].update(); } this._pollCounter = 0; }, /** * Reset all of the Pointers and Input states. * * The optional `hard` parameter will reset any events or callbacks that may be bound. * Input.reset is called automatically during a State change or if a game loses focus / visibility. * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`. * * @method Phaser.Input#reset * @public * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will. */ reset: function (hard) { if (!this.game.isBooted || this.resetLocked) { return; } if (hard === undefined) { hard = false; } this.mousePointer.reset(); if (this.keyboard) { this.keyboard.reset(hard); } if (this.gamepad) { this.gamepad.reset(); } for (var i = 0; i &lt; this.pointers.length; i++) { this.pointers[i].reset(); } if (this.game.canvas.style.cursor !== 'none') { this.game.canvas.style.cursor = 'inherit'; } if (hard) { this.onDown.dispose(); this.onUp.dispose(); this.onTap.dispose(); this.onHold.dispose(); this.onDown = new Phaser.Signal(); this.onUp = new Phaser.Signal(); this.onTap = new Phaser.Signal(); this.onHold = new Phaser.Signal(); this.moveCallbacks = []; } this._pollCounter = 0; }, /** * Resets the speed and old position properties. * * @method Phaser.Input#resetSpeed * @param {number} x - Sets the oldPosition.x value. * @param {number} y - Sets the oldPosition.y value. */ resetSpeed: function (x, y) { this._oldPosition.setTo(x, y); this.speed.setTo(0, 0); }, /** * Find the first free Pointer object and start it, passing in the event data. * This is called automatically by Phaser.Touch and Phaser.MSPointer. * * @method Phaser.Input#startPointer * @protected * @param {any} event - The event data from the Touch event. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. */ startPointer: function (event) { if (this.maxPointers >= 0 &amp;&amp; this.countActivePointers(this.maxPointers) >= this.maxPointers) { return null; } if (!this.pointer1.active) { return this.pointer1.start(event); } if (!this.pointer2.active) { return this.pointer2.start(event); } for (var i = 2; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (!pointer.active) { return pointer.start(event); } } return null; }, /** * Updates the matching Pointer object, passing in the event data. * This is called automatically and should not normally need to be invoked. * * @method Phaser.Input#updatePointer * @protected * @param {any} event - The event data from the Touch event. * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated. */ updatePointer: function (event) { if (this.pointer1.active &amp;&amp; this.pointer1.identifier === event.identifier) { return this.pointer1.move(event); } if (this.pointer2.active &amp;&amp; this.pointer2.identifier === event.identifier) { return this.pointer2.move(event); } for (var i = 2; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (pointer.active &amp;&amp; pointer.identifier === event.identifier) { return pointer.move(event); } } return null; }, /** * Stops the matching Pointer object, passing in the event data. * * @method Phaser.Input#stopPointer * @protected * @param {any} event - The event data from the Touch event. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. */ stopPointer: function (event) { if (this.pointer1.active &amp;&amp; this.pointer1.identifier === event.identifier) { return this.pointer1.stop(event); } if (this.pointer2.active &amp;&amp; this.pointer2.identifier === event.identifier) { return this.pointer2.stop(event); } for (var i = 2; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (pointer.active &amp;&amp; pointer.identifier === event.identifier) { return pointer.stop(event); } } return null; }, /** * Returns the total number of active pointers, not exceeding the specified limit * * @name Phaser.Input#countActivePointers * @private * @property {integer} [limit=(max pointers)] - Stop counting after this. * @return {integer} The number of active pointers, or limit - whichever is less. */ countActivePointers: function (limit) { if (limit === undefined) { limit = this.pointers.length; } var count = limit; for (var i = 0; i &lt; this.pointers.length &amp;&amp; count > 0; i++) { var pointer = this.pointers[i]; if (pointer.active) { count--; } } return (limit - count); }, /** * Get the first Pointer with the given active state. * * @method Phaser.Input#getPointer * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive? * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. */ getPointer: function (isActive) { if (isActive === undefined) { isActive = false; } for (var i = 0; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (pointer.active === isActive) { return pointer; } } return null; }, /** * Get the Pointer object whos `identifier` property matches the given identifier value. * * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event. * Also it can change every time you press the pointer down, and is not fixed once set. * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead. * * @method Phaser.Input#getPointerFromIdentifier * @param {number} identifier - The Pointer.identifier value to search for. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. */ getPointerFromIdentifier: function (identifier) { for (var i = 0; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (pointer.identifier === identifier) { return pointer; } } return null; }, /** * Get the Pointer object whos `pointerId` property matches the given value. * * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event. * Also it can change every time you press the pointer down if the browser recycles it. * * @method Phaser.Input#getPointerFromId * @param {number} pointerId - The `pointerId` (not 'id') value to search for. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. */ getPointerFromId: function (pointerId) { for (var i = 0; i &lt; this.pointers.length; i++) { var pointer = this.pointers[i]; if (pointer.pointerId === pointerId) { return pointer; } } return null; }, /** * This will return the local coordinates of the specified displayObject based on the given Pointer. * * @method Phaser.Input#getLocalPosition * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for. * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject. * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject. */ getLocalPosition: function (displayObject, pointer, output) { if (output === undefined) { output = new Phaser.Point(); } var wt = displayObject.worldTransform; var id = 1 / (wt.a * wt.d + wt.c * -wt.b); return output.setTo( wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id, wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id ); }, /** * Tests if the pointer hits the given object. * * @method Phaser.Input#hitTest * @param {DisplayObject} displayObject - The displayObject to test for a hit. * @param {Phaser.Pointer} pointer - The pointer to use for the test. * @param {Phaser.Point} localPoint - The local translated point. */ hitTest: function (displayObject, pointer, localPoint) { if (!displayObject.worldVisible) { return false; } this.getLocalPosition(displayObject, pointer, this._localPoint); localPoint.copyFrom(this._localPoint); if (displayObject.hitArea &amp;&amp; displayObject.hitArea.contains) { return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y)); } else if (displayObject instanceof Phaser.TileSprite) { var width = displayObject.width; var height = displayObject.height; var x1 = -width * displayObject.anchor.x; if (this._localPoint.x >= x1 &amp;&amp; this._localPoint.x &lt; x1 + width) { var y1 = -height * displayObject.anchor.y; if (this._localPoint.y >= y1 &amp;&amp; this._localPoint.y &lt; y1 + height) { return true; } } } else if (displayObject instanceof PIXI.Sprite) { var width = displayObject.texture.frame.width; var height = displayObject.texture.frame.height; var x1 = -width * displayObject.anchor.x; if (this._localPoint.x >= x1 &amp;&amp; this._localPoint.x &lt; x1 + width) { var y1 = -height * displayObject.anchor.y; if (this._localPoint.y >= y1 &amp;&amp; this._localPoint.y &lt; y1 + height) { return true; } } } else if (displayObject instanceof Phaser.Graphics) { for (var i = 0; i &lt; displayObject.graphicsData.length; i++) { var data = displayObject.graphicsData[i]; if (!data.fill) { continue; } // Only deal with fills.. if (data.shape &amp;&amp; data.shape.contains(this._localPoint.x, this._localPoint.y)) { return true; } } } // Didn't hit the parent, does it have any children? for (var i = 0, len = displayObject.children.length; i &lt; len; i++) { if (this.hitTest(displayObject.children[i], pointer, localPoint)) { return true; } } return false; }, /** * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}. * * @method Phaser.Input#onClickTrampoline * @private */ onClickTrampoline: function () { // It might not always be the active pointer, but this does work on // Desktop browsers (read: IE) with Mouse or MSPointer input. this.activePointer.processClickTrampolines(); } }; Phaser.Input.prototype.constructor = Phaser.Input; /** * The X coordinate of the most recently active pointer. * This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. * @name Phaser.Input#x * @property {number} x */ Object.defineProperty(Phaser.Input.prototype, "x", { get: function () { return this._x; }, set: function (value) { this._x = Math.floor(value); } }); /** * The Y coordinate of the most recently active pointer. * This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. * @name Phaser.Input#y * @property {number} y */ Object.defineProperty(Phaser.Input.prototype, "y", { get: function () { return this._y; }, set: function (value) { this._y = Math.floor(value); } }); /** * True if the Input is currently poll rate locked. * @name Phaser.Input#pollLocked * @property {boolean} pollLocked * @readonly */ Object.defineProperty(Phaser.Input.prototype, "pollLocked", { get: function () { return (this.pollRate > 0 &amp;&amp; this._pollCounter &lt; this.pollRate); } }); /** * The total number of inactive Pointers. * @name Phaser.Input#totalInactivePointers * @property {number} totalInactivePointers * @readonly */ Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { get: function () { return this.pointers.length - this.countActivePointers(); } }); /** * The total number of active Pointers, not counting the mouse pointer. * @name Phaser.Input#totalActivePointers * @property {integers} totalActivePointers * @readonly */ Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { get: function () { return this.countActivePointers(); } }); /** * The world X coordinate of the most recently active pointer. * @name Phaser.Input#worldX * @property {number} worldX - The world X coordinate of the most recently active pointer. * @readonly */ Object.defineProperty(Phaser.Input.prototype, "worldX", { get: function () { return this.game.camera.view.x + this.x; } }); /** * The world Y coordinate of the most recently active pointer. * @name Phaser.Input#worldY * @property {number} worldY - The world Y coordinate of the most recently active pointer. * @readonly */ Object.defineProperty(Phaser.Input.prototype, "worldY", { get: function () { return this.game.camera.view.y + this.y; } }); </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2016 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.2</a> on Fri Apr 22 2016 15:11:45 GMT+0100 (GMT Daylight Time) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
pzyu/orbital-game
phaser/docs/src_input_Input.js.html
HTML
mit
66,187
<polymer-element name="the-panel" attributes="edge size handle open automatic" on-click="{{ handleClicked }}"> <template> <style> @host { :scope { position: fixed; overflow: hidden; } } </style> <content select="header"></content> <content select="main"></content> <content select="footer"></content> </template> <script> Polymer('the-panel', { edge: 'left', size: 200, handle: 0, automatic: true, open: false, toggleOpen: function (open) { this.open = open; this.updateVisibility(); }, enteredView: function () { this.cleanUpLocation(); this.automaticChanged(); this.updateVisibility(); }, leftView: function () { this.unobserve(); }, edgeChanged: function () { this.updateVisibility(); }, sizeChanged: function () { this.updateVisibility(); }, handleChanged: function () { this.updateVisibility(); }, openChanged: function () { this.updateVisibility(); }, automaticChanged: function () { if (this.automatic) { this.observeChanges(); } else { this.unobserve(); } }, getHeader: function () { return this.querySelector('header'); }, getMain: function () { return this.querySelector('main'); }, getFooter: function () { return this.querySelector('footer'); }, handleClicked: function (event) { if (this.automatic) { return; } if (event.target !== this) { return; } if (this.open) { this.open = false; return; } this.open = true; }, observeChanges: function () { this.observer = new MutationObserver(this.handleMutations.bind(this)); this.observer.observe(this.getMain(), { subtree: false, childList: true, attributes: false, characterData: false }); }, unobserve: function () { if (!this.observer) { return; } this.observer.disconnect(); this.observer = null; }, handleMutations: function () { if (this.getMain().childElementCount === 0) { this.open = false; } else { this.open = true; } }, getPositionDimension: function () { return this.edge; }, getSizeDimensions: function () { switch (this.edge) { case 'left': case 'right': return ['width', 'height']; case 'top': case 'bottom': return ['height', 'width']; } }, cleanUpLocation: function () { this.style.left = ''; this.style.right = ''; this.style.top = ''; this.style.bottom = ''; }, updateVisibility: function () { var sizeDimensions = this.getSizeDimensions(); this.style[sizeDimensions[1]] = '100%'; this.style[sizeDimensions[0]] = this.size + 'px'; var outside = 0; if (!this.open) { outside = (this.size - this.handle) * -1; } this.style[this.getPositionDimension()] = outside + 'px'; } }); </script> </polymer-element>
rasata/noflo-ui
elements/the-panel.html
HTML
mit
3,402
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Tests.Core.ComponentModel.Helpers { public interface IService { int Id { get; } } }
EPTamminga/Dnn.Platform
DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/IService.cs
C#
mit
335
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.mixin.core.block.state; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.trait.BlockTrait; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataQuery; import org.spongepowered.api.data.MemoryDataContainer; import org.spongepowered.api.data.Property; import org.spongepowered.api.data.Queries; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.manipulator.ImmutableDataManipulator; import org.spongepowered.api.data.merge.MergeFunction; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.util.Cycleable; import org.spongepowered.api.util.Direction; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.common.data.util.DataQueries; import org.spongepowered.common.data.util.DataVersions; import org.spongepowered.common.util.VecHelper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; @Mixin(IBlockState.class) public interface MixinIBlockState extends IBlockState, BlockState { @Override default BlockType getType() { return (BlockType) getBlock(); } @Override default BlockState withExtendedProperties(Location<World> location) { return (BlockState) getBlock().getActualState(this, (net.minecraft.world.World) location.getExtent(), VecHelper.toBlockPos(location)); } @Override default BlockState cycleValue(Key<? extends BaseValue<? extends Cycleable<?>>> key) { return this; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override default <T extends Comparable<T>> Optional<T> getTraitValue(BlockTrait<T> blockTrait) { for (Map.Entry<IProperty, Comparable> entry : getProperties().entrySet()) { if (entry.getKey() == blockTrait) { return Optional.of((T) entry.getValue()); } } return Optional.empty(); } @SuppressWarnings("rawtypes") @Override default Optional<BlockTrait<?>> getTrait(String blockTrait) { for (IProperty property : getProperties().keySet()) { if (property.getName().equalsIgnoreCase(blockTrait)) { return Optional.of((BlockTrait<?>) property); } } return Optional.empty(); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override default Optional<BlockState> withTrait(BlockTrait<?> trait, Object value) { if (value instanceof String) { Comparable foundValue = null; for (Comparable comparable : trait.getPossibleValues()) { if (comparable.toString().equals(value)) { foundValue = comparable; break; } } if (foundValue != null) { return Optional.of((BlockState) this.withProperty((IProperty) trait, foundValue)); } } if (value instanceof Comparable) { if (getProperties().containsKey(trait) && ((IProperty) trait).getAllowedValues().contains(value)) { return Optional.of((BlockState) this.withProperty((IProperty) trait, (Comparable) value)); } } return Optional.empty(); } @Override default Collection<BlockTrait<?>> getTraits() { return getTraitMap().keySet(); } @Override default Collection<?> getTraitValues() { return getTraitMap().values(); } @SuppressWarnings({"unchecked", "rawtypes"}) @Override default Map<BlockTrait<?>, ?> getTraitMap() { return (ImmutableMap) getProperties(); } @SuppressWarnings("unchecked") @Override default String getId() { StringBuilder builder = new StringBuilder(); builder.append(((BlockType) getBlock()).getId()); final ImmutableMap<IProperty<?>, Comparable<?>> properties = (ImmutableMap<IProperty<?>, Comparable<?>>) (ImmutableMap<?, ?>) this.getProperties(); if (!properties.isEmpty()) { builder.append('['); Joiner joiner = Joiner.on(','); List<String> propertyValues = new ArrayList<>(); for (Map.Entry<IProperty<?>, Comparable<?>> entry : properties.entrySet()) { propertyValues.add(entry.getKey().getName() + "=" + entry.getValue()); } builder.append(joiner.join(propertyValues)); builder.append(']'); } return builder.toString(); } @Override default String getName() { return getId(); } @Override default <T extends Property<?, ?>> Optional<T> getProperty(Direction direction, Class<T> clazz) { return Optional.empty(); } @Override default List<ImmutableDataManipulator<?, ?>> getManipulators() { return Collections.emptyList(); } @Override default int getContentVersion() { return DataVersions.BlockState.STATE_AS_CATALOG_ID; } @Override default DataContainer toContainer() { return new MemoryDataContainer() .set(Queries.CONTENT_VERSION, getContentVersion()) .set(DataQueries.BLOCK_STATE, getId()); } @Override default <T extends ImmutableDataManipulator<?, ?>> Optional<T> get(Class<T> containerClass) { return Optional.empty(); } @Override default <T extends ImmutableDataManipulator<?, ?>> Optional<T> getOrCreate(Class<T> containerClass) { return Optional.empty(); } @Override default boolean supports(Class<? extends ImmutableDataManipulator<?, ?>> containerClass) { return false; } @Override default <E> Optional<BlockState> transform(Key<? extends BaseValue<E>> key, Function<E, E> function) { return Optional.empty(); } @Override default <E> Optional<BlockState> with(Key<? extends BaseValue<E>> key, E value) { return Optional.empty(); } @Override default Optional<BlockState> with(BaseValue<?> value) { return Optional.empty(); } @Override default Optional<BlockState> with(ImmutableDataManipulator<?, ?> valueContainer) { return Optional.empty(); } @Override default Optional<BlockState> with(Iterable<ImmutableDataManipulator<?, ?>> valueContainers) { return Optional.empty(); } @Override default Optional<BlockState> without(Class<? extends ImmutableDataManipulator<?, ?>> containerClass) { return Optional.empty(); } @Override default BlockState merge(BlockState that) { return this; } @Override default BlockState merge(BlockState that, MergeFunction function) { return this; } @Override default List<ImmutableDataManipulator<?, ?>> getContainers() { return Collections.emptyList(); } @Override default <T extends Property<?, ?>> Optional<T> getProperty(Class<T> propertyClass) { return Optional.empty(); } @Override default Collection<Property<?, ?>> getApplicableProperties() { return Collections.emptyList(); } @Override default <E> Optional<E> get(Key<? extends BaseValue<E>> key) { return Optional.empty(); } @Override default <E, V extends BaseValue<E>> Optional<V> getValue(Key<V> key) { return Optional.empty(); } @Override default boolean supports(Key<?> key) { return false; } @Override default BlockState copy() { return this; } @Override default Set<Key<?>> getKeys() { return Collections.emptySet(); } @Override default Set<ImmutableValue<?>> getValues() { return Collections.emptySet(); } }
ryantheleach/SpongeCommon
src/main/java/org/spongepowered/common/mixin/core/block/state/MixinIBlockState.java
Java
mit
9,567
var assert = require('assert'); var Globals = require('../../lib/globals/expect.js'); var common = require('../../common.js'); var CommandQueue = common.require('core/queue.js'); module.exports = { 'test Queue' : { beforeEach: function (done) { CommandQueue.reset(); Globals.beforeEach.call(this, done); }, afterEach: function() { Globals.afterEach.call(this); }, 'Test commands queue' : function(done) { var client = this.client, urlCommand, endCommand; this.client.once('nightwatch:finished', function() { assert.equal(urlCommand.done, true); assert.equal(endCommand.children.length, 0); assert.equal(endCommand.done, true); assert.equal(CommandQueue.list().length, 0); done(); }); client.api.url('http://localhost').end(); assert.equal(CommandQueue.list().length, 2); urlCommand = CommandQueue.instance().rootNode.children[0]; endCommand = CommandQueue.instance().rootNode.children[1]; assert.equal(endCommand.done, false); assert.equal(urlCommand.done, false); assert.equal(endCommand.started, false); this.client.start(); assert.equal(urlCommand.started, true); } } };
PatrickCrawford/herdacity-e2e
tests/src/core/testQueue.js
JavaScript
mit
1,238
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Database; use Cake\Core\App; use Cake\Database\Exception\MissingConnectionException; use Cake\Database\Exception\MissingDriverException; use Cake\Database\Exception\MissingExtensionException; use Cake\Database\Log\LoggedQuery; use Cake\Database\Log\LoggingStatement; use Cake\Database\Log\QueryLogger; use Cake\Database\Schema\CachedCollection; use Cake\Database\Schema\Collection as SchemaCollection; use Cake\Datasource\ConnectionInterface; use Exception; /** * Represents a connection with a database server. */ class Connection implements ConnectionInterface { use TypeConverterTrait; /** * Contains the configuration params for this connection. * * @var array */ protected $_config; /** * Driver object, responsible for creating the real connection * and provide specific SQL dialect. * * @var \Cake\Database\Driver */ protected $_driver; /** * Contains how many nested transactions have been started. * * @var int */ protected $_transactionLevel = 0; /** * Whether a transaction is active in this connection. * * @var bool */ protected $_transactionStarted = false; /** * Whether this connection can and should use savepoints for nested * transactions. * * @var bool */ protected $_useSavePoints = false; /** * Whether to log queries generated during this connection. * * @var bool */ protected $_logQueries = false; /** * Logger object instance. * * @var \Cake\Database\Log\QueryLogger */ protected $_logger = null; /** * The schema collection object * * @var \Cake\Database\Schema\Collection */ protected $_schemaCollection; /** * Constructor. * * @param array $config configuration for connecting to database */ public function __construct($config) { $this->_config = $config; $driver = ''; if (!empty($config['driver'])) { $driver = $config['driver']; } $this->driver($driver, $config); if (!empty($config['log'])) { $this->logQueries($config['log']); } } /** * Destructor * * Disconnects the driver to release the connection. */ public function __destruct() { unset($this->_driver); } /** * {@inheritDoc} */ public function config() { return $this->_config; } /** * {@inheritDoc} */ public function configName() { if (empty($this->_config['name'])) { return ''; } return $this->_config['name']; } /** * Sets the driver instance. If a string is passed it will be treated * as a class name and will be instantiated. * * If no params are passed it will return the current driver instance. * * @param \Cake\Database\Driver|string|null $driver The driver instance to use. * @param array $config Either config for a new driver or null. * @throws \Cake\Database\Exception\MissingDriverException When a driver class is missing. * @throws \Cake\Database\Exception\MissingExtensionException When a driver's PHP extension is missing. * @return \Cake\Database\Driver */ public function driver($driver = null, $config = []) { if ($driver === null) { return $this->_driver; } if (is_string($driver)) { $className = App::className($driver, 'Database/Driver'); if (!$className || !class_exists($className)) { throw new MissingDriverException(['driver' => $driver]); } $driver = new $className($config); } if (!$driver->enabled()) { throw new MissingExtensionException(['driver' => get_class($driver)]); } return $this->_driver = $driver; } /** * Connects to the configured database. * * @throws \Cake\Database\Exception\MissingConnectionException if credentials are invalid * @return bool true on success or false if already connected. */ public function connect() { try { $this->_driver->connect(); return true; } catch (Exception $e) { throw new MissingConnectionException(['reason' => $e->getMessage()]); } } /** * Disconnects from database server. * * @return void */ public function disconnect() { $this->_driver->disconnect(); } /** * Returns whether connection to database server was already established. * * @return bool */ public function isConnected() { return $this->_driver->isConnected(); } /** * Prepares a SQL statement to be executed. * * @param string|\Cake\Database\Query $sql The SQL to convert into a prepared statement. * @return \Cake\Database\StatementInterface */ public function prepare($sql) { $statement = $this->_driver->prepare($sql); if ($this->_logQueries) { $statement = $this->_newLogger($statement); } return $statement; } /** * Executes a query using $params for interpolating values and $types as a hint for each * those params. * * @param string $query SQL to be executed and interpolated with $params * @param array $params list or associative array of params to be interpolated in $query as values * @param array $types list or associative array of types to be used for casting values in query * @return \Cake\Database\StatementInterface executed statement */ public function execute($query, array $params = [], array $types = []) { if (!empty($params)) { $statement = $this->prepare($query); $statement->bind($params, $types); $statement->execute(); } else { $statement = $this->query($query); } return $statement; } /** * Compiles a Query object into a SQL string according to the dialect for this * connection's driver * * @param \Cake\Database\Query $query The query to be compiled * @param \Cake\Database\ValueBinder $generator The placeholder generator to use * @return string */ public function compileQuery(Query $query, ValueBinder $generator) { return $this->driver()->compileQuery($query, $generator)[1]; } /** * Executes the provided query after compiling it for the specific driver * dialect and returns the executed Statement object. * * @param \Cake\Database\Query $query The query to be executed * @return \Cake\Database\StatementInterface executed statement */ public function run(Query $query) { $statement = $this->prepare($query); $query->valueBinder()->attachTo($statement); $statement->execute(); return $statement; } /** * Executes a SQL statement and returns the Statement object as result. * * @param string $sql The SQL query to execute. * @return \Cake\Database\StatementInterface */ public function query($sql) { $statement = $this->prepare($sql); $statement->execute(); return $statement; } /** * Create a new Query instance for this connection. * * @return \Cake\Database\Query */ public function newQuery() { return new Query($this); } /** * Gets or sets a Schema\Collection object for this connection. * * @param \Cake\Database\Schema\Collection|null $collection The schema collection object * @return \Cake\Database\Schema\Collection */ public function schemaCollection(SchemaCollection $collection = null) { if ($collection !== null) { return $this->_schemaCollection = $collection; } if ($this->_schemaCollection !== null) { return $this->_schemaCollection; } if (!empty($this->_config['cacheMetadata'])) { return $this->_schemaCollection = new CachedCollection($this, $this->_config['cacheMetadata']); } return $this->_schemaCollection = new SchemaCollection($this); } /** * Executes an INSERT query on the specified table. * * @param string $table the table to insert values in * @param array $data values to be inserted * @param array $types list of associative array containing the types to be used for casting * @return \Cake\Database\StatementInterface */ public function insert($table, array $data, array $types = []) { $columns = array_keys($data); return $this->newQuery()->insert($columns, $types) ->into($table) ->values($data) ->execute(); } /** * Executes an UPDATE statement on the specified table. * * @param string $table the table to update rows from * @param array $data values to be updated * @param array $conditions conditions to be set for update statement * @param array $types list of associative array containing the types to be used for casting * @return \Cake\Database\StatementInterface */ public function update($table, array $data, array $conditions = [], $types = []) { return $this->newQuery()->update($table) ->set($data, $types) ->where($conditions, $types) ->execute(); } /** * Executes a DELETE statement on the specified table. * * @param string $table the table to delete rows from * @param array $conditions conditions to be set for delete statement * @param array $types list of associative array containing the types to be used for casting * @return \Cake\Database\StatementInterface */ public function delete($table, $conditions = [], $types = []) { return $this->newQuery()->delete($table) ->where($conditions, $types) ->execute(); } /** * Starts a new transaction. * * @return void */ public function begin() { if (!$this->_transactionStarted) { if ($this->_logQueries) { $this->log('BEGIN'); } $this->_driver->beginTransaction(); $this->_transactionLevel = 0; $this->_transactionStarted = true; return; } $this->_transactionLevel++; if ($this->useSavePoints()) { $this->createSavePoint($this->_transactionLevel); } } /** * Commits current transaction. * * @return bool true on success, false otherwise */ public function commit() { if (!$this->_transactionStarted) { return false; } if ($this->_transactionLevel === 0) { $this->_transactionStarted = false; if ($this->_logQueries) { $this->log('COMMIT'); } return $this->_driver->commitTransaction(); } if ($this->useSavePoints()) { $this->releaseSavePoint($this->_transactionLevel); } $this->_transactionLevel--; return true; } /** * Rollback current transaction. * * @return bool */ public function rollback() { if (!$this->_transactionStarted) { return false; } $useSavePoint = $this->useSavePoints(); if ($this->_transactionLevel === 0 || !$useSavePoint) { $this->_transactionLevel = 0; $this->_transactionStarted = false; if ($this->_logQueries) { $this->log('ROLLBACK'); } $this->_driver->rollbackTransaction(); return true; } if ($useSavePoint) { $this->rollbackSavepoint($this->_transactionLevel--); } return true; } /** * Returns whether this connection is using savepoints for nested transactions * If a boolean is passed as argument it will enable/disable the usage of savepoints * only if driver the allows it. * * If you are trying to enable this feature, make sure you check the return value of this * function to verify it was enabled successfully. * * ### Example: * * `$connection->useSavePoints(true)` Returns true if drivers supports save points, false otherwise * `$connection->useSavePoints(false)` Disables usage of savepoints and returns false * `$connection->useSavePoints()` Returns current status * * @param bool|null $enable Whether or not save points should be used. * @return bool true if enabled, false otherwise */ public function useSavePoints($enable = null) { if ($enable === null) { return $this->_useSavePoints; } if ($enable === false) { return $this->_useSavePoints = false; } return $this->_useSavePoints = $this->_driver->supportsSavePoints(); } /** * Creates a new save point for nested transactions. * * @param string $name The save point name. * @return void */ public function createSavePoint($name) { $this->execute($this->_driver->savePointSQL($name))->closeCursor(); } /** * Releases a save point by its name. * * @param string $name The save point name. * @return void */ public function releaseSavePoint($name) { $this->execute($this->_driver->releaseSavePointSQL($name))->closeCursor(); } /** * Rollback a save point by its name. * * @param string $name The save point name. * @return void */ public function rollbackSavepoint($name) { $this->execute($this->_driver->rollbackSavePointSQL($name))->closeCursor(); } /** * Run driver specific SQL to disable foreign key checks. * * @return void */ public function disableForeignKeys() { $this->execute($this->_driver->disableForeignKeySql())->closeCursor(); } /** * Run driver specific SQL to enable foreign key checks. * * @return void */ public function enableForeignKeys() { $this->execute($this->_driver->enableForeignKeySql())->closeCursor(); } /** * Returns whether the driver supports adding or dropping constraints * to already created tables. * * @return bool true if driver supports dynamic constraints */ public function supportsDynamicConstraints() { return $this->_driver->supportsDynamicConstraints(); } /** * {@inheritDoc} * * ### Example: * * ``` * $connection->transactional(function ($connection) { * $connection->newQuery()->delete('users')->execute(); * }); * ``` */ public function transactional(callable $callback) { $this->begin(); try { $result = $callback($this); } catch (Exception $e) { $this->rollback(); throw $e; } if ($result === false) { $this->rollback(); return false; } $this->commit(); return $result; } /** * {@inheritDoc} * * ### Example: * * ``` * $connection->disableConstraints(function ($connection) { * $connection->newQuery()->delete('users')->execute(); * }); * ``` */ public function disableConstraints(callable $callback) { $this->disableForeignKeys(); try { $result = $callback($this); } catch (Exception $e) { $this->enableForeignKeys(); throw $e; } $this->enableForeignKeys(); return $result; } /** * Checks if a transaction is running. * * @return bool True if a transaction is running else false. */ public function inTransaction() { return $this->_transactionStarted; } /** * Quotes value to be used safely in database query. * * @param mixed $value The value to quote. * @param string|null $type Type to be used for determining kind of quoting to perform * @return string Quoted value */ public function quote($value, $type = null) { list($value, $type) = $this->cast($value, $type); return $this->_driver->quote($value, $type); } /** * Checks if the driver supports quoting. * * @return bool */ public function supportsQuoting() { return $this->_driver->supportsQuoting(); } /** * Quotes a database identifier (a column name, table name, etc..) to * be used safely in queries without the risk of using reserved words. * * @param string $identifier The identifier to quote. * @return string */ public function quoteIdentifier($identifier) { return $this->_driver->quoteIdentifier($identifier); } /** * Enables or disables metadata caching for this connection * * Changing this setting will not modify existing schema collections objects. * * @param bool|string $cache Either boolean false to disable meta dataing caching, or * true to use `_cake_model_` or the name of the cache config to use. * @return void */ public function cacheMetadata($cache) { $this->_schemaCollection = null; $this->_config['cacheMetadata'] = $cache; } /** * {@inheritDoc} */ public function logQueries($enable = null) { if ($enable === null) { return $this->_logQueries; } $this->_logQueries = $enable; } /** * {@inheritDoc} */ public function logger($instance = null) { if ($instance === null) { if ($this->_logger === null) { $this->_logger = new QueryLogger; } return $this->_logger; } $this->_logger = $instance; } /** * Logs a Query string using the configured logger object. * * @param string $sql string to be logged * @return void */ public function log($sql) { $query = new LoggedQuery; $query->query = $sql; $this->logger()->log($query); } /** * Returns a new statement object that will log the activity * for the passed original statement instance. * * @param \Cake\Database\StatementInterface $statement the instance to be decorated * @return \Cake\Database\Log\LoggingStatement */ protected function _newLogger(StatementInterface $statement) { $log = new LoggingStatement($statement, $this->driver()); $log->logger($this->logger()); return $log; } /** * Returns an array that can be used to describe the internal state of this * object. * * @return array */ public function __debugInfo() { $secrets = [ 'password' => '*****', 'username' => '*****', 'host' => '*****', 'database' => '*****', 'port' => '*****' ]; $replace = array_intersect_key($secrets, $this->_config); $config = $replace + $this->_config; return [ 'config' => $config, 'driver' => $this->_driver, 'transactionLevel' => $this->_transactionLevel, 'transactionStarted' => $this->_transactionStarted, 'useSavePoints' => $this->_useSavePoints, 'logQueries' => $this->_logQueries, 'logger' => $this->_logger ]; } }
xdxdVSxdxd/HumanEcosystemsv3
vendor/cakephp/cakephp/src/Database/Connection.php
PHP
mit
20,537
/*************************************************************************** file : xml.cpp created : Sat Mar 18 23:50:46 CET 2000 copyright : (C) 2000 by Eric Espie email : [email protected] version : $Id: xml.cpp,v 1.4.2.1 2008/11/09 17:50:22 berniw Exp $ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* * This set of function is used to store and retrieve * values in parameters files written in XML. */ #include <stdlib.h> #include <stdio.h> #include <cstring> #include <sys/stat.h> #include "xmlparse.h" #include <xml.h> #define BUFMAX 256 /* * NAME: * NewElt * * FUNCTION: * Creates a new element * * PARAMETERS: * name and attributes * * RETURNS: * new element created * */ static txmlElement * NewElt(const char *name, const char **atts) { int nAtts; const char **p; const char *s1, *s2; txmlElement *newElt; txmlAttribute *newAttr; /* Create a new element */ if ((newElt = (txmlElement*)malloc(sizeof(txmlElement))) == NULL) { return (txmlElement*)NULL; } newElt->name = strdup(name); newElt->pcdata = (char*)NULL; newElt->attr = (txmlAttribute*)NULL; newElt->sub = (txmlElement*)NULL; newElt->up = (txmlElement*)NULL; newElt->next = newElt; newElt->level = 0; /* attributes */ p = atts; while (*p) ++p; nAtts = (p - atts) >> 1; if (nAtts > 1) { qsort((void *)atts, nAtts, sizeof(char *) * 2, (int (*)(const void *, const void *))strcmp); } while (*atts) { s1 = *atts++; s2 = *atts++; if ((newAttr = (txmlAttribute*)malloc(sizeof(txmlAttribute))) == NULL) { return (txmlElement*)NULL; } newAttr->name = strdup(s1); newAttr->value = strdup(s2); /* insert in attributes ring */ if (newElt->attr == NULL) { newElt->attr = newAttr; newAttr->next = newAttr; } else { newAttr->next = newElt->attr->next; newElt->attr->next = newAttr; newElt->attr = newAttr; } } return newElt; } /* * NAME: * xmlInsertElt * * FUNCTION: * Create and Insert a new element in the sub-list of * the element given in parameter * * PARAMETERS: * curElt element * name name of the new element * atts attribute list of the new element * * RETURNS: * the new element created. * * NOTE: * Use NULL as current element to create a new tree */ txmlElement * xmlInsertElt(txmlElement *curElt, const char *name, const char **atts) { txmlElement *newElt; newElt = NewElt(name, atts); if (curElt) { if (curElt->sub == NULL) { curElt->sub = newElt; newElt->next = newElt; } else { newElt->next = curElt->sub->next; curElt->sub->next = newElt; curElt->sub = newElt; } newElt->up = curElt; newElt->level = curElt->level + 1; } return newElt; } /* * Function * startElement * * Description * * * Parameters * * * Return * */ static void startElement(void *userData, const char *name, const char **atts) { txmlElement **curElt = (txmlElement **)userData; *curElt = xmlInsertElt(*curElt, name, atts); } /* * Function * endElement * * Description * * * Parameters * * * Return * none */ static void endElement(void *userData, const char * /* name */) { txmlElement **curElt = (txmlElement **)userData; if ((*curElt)->up != NULL) { *curElt = (*curElt)->up; } } static void CharacterData(void *userData, const char *s, int len) { char *s1,*s2,*s3; txmlElement **curElt = (txmlElement **)userData; if ((s1 = (char*)malloc(len+1)) == NULL) { return; } strncpy(s1, s, len); /* remove spaces in front */ s2 = s1; while ((*s2 == ' ') || (*s2 == '\t') || (*s2 == '\n')) { s2++; } /* remove spaces at the end */ s3 = s1+len-1; while (((*s3 == ' ') || (*s3 == '\t') || (*s3 == '\n')) && (s3 > s2)) { s3--; } if (s3 > s2) { *(s3+1) = 0; (*curElt)->pcdata = strdup(s2); } free(s1); } /* * Function * xmlReadFile * * Description * Read a config file * * Parameters * file name of the config file * * Return * root of the tree * NULL error. * * Remarks * */ txmlElement * xmlReadFile(const char *file) { FILE *in; char buf[BUFSIZ]; XML_Parser parser; int done; txmlElement *retElt; if ((in = fopen(file, "r")) == NULL) { fprintf(stderr, "xmlReadFile: file %s has pb (access rights ?)\n", file); return (txmlElement*)NULL; } parser = XML_ParserCreate((XML_Char*)NULL); XML_SetUserData(parser, &retElt); XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, CharacterData); do { size_t len = fread(buf, 1, sizeof(buf), in); done = len < sizeof(buf); if (!XML_Parse(parser, buf, len, done)) { fprintf(stderr, "file: %s -> %s at line %d\n", file, XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); return (txmlElement*)NULL; } } while (!done); XML_ParserFree(parser); return retElt; } static void wr(int indent, char *buf, FILE *out) { char blank[BUFMAX]; int i; for(i = 0; i < indent*2; i++) blank[i] = ' '; blank[i] = 0; fprintf(out, "%s%s", blank, buf); } static void wrrec(txmlElement *startElt, FILE *out) { txmlElement *curElt; txmlAttribute *curAttr; char buf[BUFMAX]; curElt = startElt; if (curElt) { wr(0, "\n", out); do { curElt = curElt->next; sprintf(buf, "<%s", curElt->name); wr(curElt->level, buf, out); curAttr = curElt->attr; if (curAttr) { do { curAttr = curAttr->next; sprintf(buf, " %s=\"%s\"", curAttr->name, curAttr->value); wr(0, buf, out); } while (curAttr != curElt->attr); } sprintf(buf, ">"); wr(0, buf, out); if (curElt->pcdata) { sprintf(buf, "%s", curElt->pcdata); wr(0, buf, out); } /* recurse the nested elements */ wrrec(curElt->sub, out); sprintf(buf, "</%s>\n", curElt->name); wr(0, buf, out); } while (curElt != startElt); wr(curElt->level-1, "", out); } } /* * Function * xmlWriteFile * * Description * Write a parameter file * * Parameters * file name of the config file * startElt root of the tree to write * * Return * 0 ok * -1 failed * * Remarks * the file is created if necessary */ int xmlWriteFile(const char *file, txmlElement *startElt, char *dtd) { char buf[BUFMAX]; FILE *out; if ((out = fopen(file, "w")) == NULL) { fprintf(stderr, "xmlWriteFile: file %s has pb (access rights ?)\n", file); return -1; } sprintf(buf, "<?xml version=\"1.0\" ?>\n"); wr(0, buf, out); sprintf(buf, "\n<!DOCTYPE params SYSTEM \"%s\">\n\n", dtd); wr(0, buf, out); wrrec(startElt, out); wr(0, "\n", out); fclose(out); return 0; } /* * NAME: * xmlGetAttr * * FUNCTION: * Get the attribute value of an element * * PARAMETERS: * curElt element to consider * attrname name of the attribute * * RETURNS: * the attribute value or NULL if attribute is not present * */ char * xmlGetAttr(txmlElement *curElt, char *attrname) { txmlAttribute *cutAttr; cutAttr = curElt->attr; if (cutAttr) { do { cutAttr = cutAttr->next; if (strcmp(cutAttr->name, attrname) == 0) { return strdup(cutAttr->value); } } while (cutAttr != curElt->attr); } return (char*)NULL; } /* * NAME: * xmlNextElt * * FUNCTION: * Get the next element (same level) * * PARAMETERS: * startElt element to start with * * RETURNS: * the next element or NULL if no more element * at the same level * */ txmlElement * xmlNextElt(txmlElement *startElt) { txmlElement *curElt; curElt = startElt->next; if (curElt->up != NULL) { if (curElt->up->sub->next == curElt) { return (txmlElement*)NULL; } return curElt; } return (txmlElement*)NULL; } /* * NAME: * xmlSubElt * * FUNCTION: * Get the first sub-element (nested level) * * PARAMETERS: * startElt element to start with * * RETURNS: * the first sub-element or NULL if no sub-element * */ txmlElement * xmlSubElt(txmlElement *startElt) { if (startElt->sub != NULL) { return startElt->sub->next; } return (txmlElement*)NULL; } /* * NAME: * xmlWalkElt * * FUNCTION: * Walk all the tree * * PARAMETERS: * startElt element to start with * * RETURNS: * the next element in the tree or NULL if all the tree * has been parsed. * */ txmlElement * xmlWalkElt(txmlElement *startElt) { txmlElement *curElt; curElt = startElt; /* in depth first */ if (curElt->sub != NULL) { return curElt->sub->next; } /* go to the next element */ if ((curElt->up != NULL) && (curElt != curElt->up->sub)) { return curElt->next; } /* end of the ring should go upward */ while (curElt->up != NULL) { curElt = curElt->up; if ((curElt->up != NULL) && (curElt != curElt->up->sub)) { return curElt->next; } } return (txmlElement*)NULL; } /* * NAME: * xmlWalkSubElt * * FUNCTION: * walk a sub-tree * * PARAMETERS: * startElt element to start with * topElt sub-tree root * * RETURNS: * next element in in-depth search or NULL if all sub-tree has been parsed * */ txmlElement * xmlWalkSubElt(txmlElement *startElt, txmlElement *topElt) { txmlElement *curElt; curElt = startElt; /* in depth first */ if (curElt->sub != NULL) { return curElt->sub->next; } /* go to the next element */ if ((curElt->up != NULL) && (curElt != curElt->up->sub) && (curElt != topElt)) { return curElt->next; } /* end of the ring should go upward */ while ((curElt->up != NULL) && (curElt != topElt)) { curElt = curElt->up; if ((curElt->up != NULL) && (curElt != curElt->up->sub)) { return curElt->next; } } return (txmlElement*)NULL; } /* * NAME: * xmlFindNextElt * * FUNCTION: * Find the next element corresponding to name * * PARAMETERS: * startElt element to start with * name name of the element to find * * RETURNS: * pointer on next element corresponding to name * or NULL if no more. * */ txmlElement * xmlFindNextElt(txmlElement *startElt, char *name) { txmlElement *curElt; curElt = startElt; curElt = xmlWalkElt(curElt); while (curElt) { if (strcmp(curElt->name, name) == 0) { return curElt; } curElt = xmlWalkElt(curElt); } return (txmlElement*)NULL; } /* * NAME: * xmlFindEltAttr * * FUNCTION: * Find an element with its name an an attribute value * * PARAMETERS: * startElt element to start with * name name of the element to search * attrname attribute name * attrvalue attribute value of the searched element * * RETURNS: * the corresponding element or NULL if not found * */ txmlElement * xmlFindEltAttr(txmlElement *startElt, char *name, char *attrname, char *attrvalue) { txmlElement *curElt; txmlAttribute *cutAttr; curElt = startElt; curElt = xmlWalkElt(curElt); while (curElt) { if (strcmp(curElt->name, name) == 0) { cutAttr = curElt->attr; if (cutAttr) { do { cutAttr = cutAttr->next; if (strcmp(cutAttr->name, attrname) == 0) { if (strcmp(cutAttr->value, attrvalue) == 0) { return curElt; } else { cutAttr = curElt->attr; } } } while (cutAttr != curElt->attr); } } curElt = xmlWalkElt(curElt); } return (txmlElement*)NULL; }
ugo-nama-kun/gym_torcs
vtorcs-RL-color/src/libs/txml/xml.cpp
C++
mit
12,278
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.data.item; import com.google.common.collect.ImmutableList; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import org.spongepowered.api.data.DataContainer; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.ImmutableFireworkEffectData; import org.spongepowered.api.data.manipulator.mutable.FireworkEffectData; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableValue; import org.spongepowered.api.data.value.mutable.ListValue; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.entity.EntityTypes; import org.spongepowered.api.item.FireworkEffect; import org.spongepowered.common.data.manipulator.mutable.SpongeFireworkEffectData; import org.spongepowered.common.data.processor.common.AbstractItemSingleDataProcessor; import org.spongepowered.common.data.processor.common.FireworkUtils; import org.spongepowered.common.data.util.DataUtil; import org.spongepowered.common.data.value.immutable.ImmutableSpongeListValue; import org.spongepowered.common.data.value.mutable.SpongeListValue; import java.util.List; import java.util.Optional; public class ItemFireworkEffectDataProcessor extends AbstractItemSingleDataProcessor<List<FireworkEffect>, ListValue<FireworkEffect>, FireworkEffectData, ImmutableFireworkEffectData> { public ItemFireworkEffectDataProcessor() { super(stack -> stack.getItem() == Items.FIREWORK_CHARGE || stack.getItem() == Items.FIREWORKS, Keys.FIREWORK_EFFECTS); } @Override protected FireworkEffectData createManipulator() { return new SpongeFireworkEffectData(); } @Override public boolean supports(EntityType entityType) { return entityType.equals(EntityTypes.FIREWORK); } @Override protected Optional<List<FireworkEffect>> getVal(ItemStack itemStack) { return FireworkUtils.getFireworkEffects(itemStack); } @Override public Optional<FireworkEffectData> fill(DataContainer container, FireworkEffectData fireworkEffectData) { DataUtil.checkDataExists(container, Keys.FIREWORK_EFFECTS.getQuery()); List<FireworkEffect> effects = container.getSerializableList(Keys.FIREWORK_EFFECTS.getQuery(), FireworkEffect.class).get(); return Optional.of(fireworkEffectData.set(Keys.FIREWORK_EFFECTS, effects)); } @Override protected boolean set(ItemStack itemStack, List<FireworkEffect> effects) { return FireworkUtils.setFireworkEffects(itemStack, effects); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { if (FireworkUtils.removeFireworkEffects(container)) { return DataTransactionResult.successNoData(); } return DataTransactionResult.failNoData(); } @Override protected ListValue<FireworkEffect> constructValue(List<FireworkEffect> value) { return new SpongeListValue<>(Keys.FIREWORK_EFFECTS, value); } @Override protected ImmutableValue<List<FireworkEffect>> constructImmutableValue(List<FireworkEffect> value) { return new ImmutableSpongeListValue<>(Keys.FIREWORK_EFFECTS, ImmutableList.copyOf(value)); } }
SpongePowered/SpongeCommon
src/main/java/org/spongepowered/common/data/processor/data/item/ItemFireworkEffectDataProcessor.java
Java
mit
4,628
$(function() { $widget = $('#calendar-widget') if ($widget.length) { $.get('/events/calendar.json', function(data){ $widget.fullCalendar({ editable: false, header: { left: 'title', firstDay: 1, center: '', aspectRatio: 1, right: 'today prev,next' }, events: data }); }); } });
yazug/rdo-website
source/javascripts/lib/cal-widget.js
JavaScript
mit
388
# - Config file for the glfw3 package # It defines the following variables # GLFW3_INCLUDE_DIR, the path where GLFW headers are located # GLFW3_LIBRARY_DIR, folder in which the GLFW library is located # GLFW3_LIBRARY, library to link against to use GLFW set(GLFW3_VERSION "3.1.1") ####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() ####### ####### Any changes to this file will be overwritten by the next CMake run #### ####### The input file was glfw3Config.cmake.in ######## get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE) macro(set_and_check _var _file) set(${_var} "${_file}") if(NOT EXISTS "${_file}") message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !") endif() endmacro() #################################################################################### set_and_check(GLFW3_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/include") set_and_check(GLFW3_LIBRARY_DIR "${PACKAGE_PREFIX_DIR}/lib") find_library(GLFW3_LIBRARY "glfw3" HINTS ${GLFW3_LIBRARY_DIR})
jazztext/VRRayTracing
src/pathtracer/CMU462/deps/glfw/src/glfw3Config.cmake
CMake
mit
1,113
// // $Id$ // // QKQueryStringAdditions.h // QueryKit // // Created by Stuart Connolly (stuconnolly.com) on July 12, 2012 // Copyright (c) 2012 Stuart Connolly. All rights reserved. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. @interface NSString (QKQueryStringAdditions) - (NSString *)quotedStringWithCharacter:(NSString *)character; @end
Shooter7119/sequel-pro
Frameworks/QueryKit/Source/QKQueryStringAdditions.h
C
mit
1,405
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WX.Model.ApiResponses; namespace WX.Model.ApiRequests { public class GetCurrentAutoreplyInfoRequest : ApiRequest<GetCurrentAutoreplyInfoResponse> { internal override string Method { get { return GETMETHOD; } } protected override string UrlFormat { get { return "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token={0}"; } } internal override string GetUrl() { return String.Format(UrlFormat, AccessToken); } protected override bool NeedToken { get { return true; } } public override string GetPostContent() { return String.Empty; } } }
JamesYing/JCWX
Business/Model/ApiRequests/GetCurrentAutoreplyInfoRequest.cs
C#
mit
850
/* Simple DirectMedia Layer Copyright (C) 1997-2014 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_THREAD_PSP /* PSP thread management routines for SDL */ #include <stdio.h> #include <stdlib.h> #include "SDL_error.h" #include "SDL_thread.h" #include "../SDL_systhread.h" #include "../SDL_thread_c.h" #include <pspkerneltypes.h> #include <pspthreadman.h> static int ThreadEntry(SceSize args, void *argp) { SDL_RunThread(*(void **) argp); return 0; } int SDL_SYS_CreateThread(SDL_Thread *thread, void *args) { SceKernelThreadInfo status; int priority = 32; /* Set priority of new thread to the same as the current thread */ status.size = sizeof(SceKernelThreadInfo); if (sceKernelReferThreadStatus(sceKernelGetThreadId(), &status) == 0) { priority = status.currentPriority; } thread->handle = sceKernelCreateThread("SDL thread", ThreadEntry, priority, 0x8000, PSP_THREAD_ATTR_VFPU, NULL); if (thread->handle < 0) { return SDL_SetError("sceKernelCreateThread() failed"); } sceKernelStartThread(thread->handle, 4, &args); return 0; } void SDL_SYS_SetupThread(const char *name) { /* Do nothing. */ } SDL_threadID SDL_ThreadID(void) { return (SDL_threadID) sceKernelGetThreadId(); } void SDL_SYS_WaitThread(SDL_Thread *thread) { sceKernelWaitThreadEnd(thread->handle, NULL); sceKernelDeleteThread(thread->handle); } void SDL_SYS_DetachThread(SDL_Thread *thread) { /* !!! FIXME: is this correct? */ sceKernelDeleteThread(thread->handle); } void SDL_SYS_KillThread(SDL_Thread *thread) { sceKernelTerminateDeleteThread(thread->handle); } int SDL_SYS_SetThreadPriority(SDL_ThreadPriority priority) { int value; if (priority == SDL_THREAD_PRIORITY_LOW) { value = 19; } else if (priority == SDL_THREAD_PRIORITY_HIGH) { value = -20; } else { value = 0; } return sceKernelChangeThreadPriority(sceKernelGetThreadId(),value); } #endif /* SDL_THREAD_PSP */ /* vim: ts=4 sw=4 */
eastcowboy2002/gles-study
glesstudy/jni/SDL/src/thread/psp/SDL_systhread.c
C
mit
2,961
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\ResourceBundle\Routing; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; final class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('routing'); $rootNode ->children() ->scalarNode('alias')->isRequired()->cannotBeEmpty()->end() ->scalarNode('path')->defaultValue(null)->end() ->scalarNode('identifier')->defaultValue('id')->end() ->arrayNode('criteria') ->useAttributeAsKey('identifier') ->prototype('scalar') ->end() ->end() ->booleanNode('filterable')->end() ->variableNode('form')->cannotBeEmpty()->end() ->scalarNode('serialization_version')->cannotBeEmpty()->end() ->scalarNode('section')->cannotBeEmpty()->end() ->scalarNode('redirect')->cannotBeEmpty()->end() ->scalarNode('templates')->cannotBeEmpty()->end() ->scalarNode('grid')->cannotBeEmpty()->end() ->booleanNode('permission')->defaultValue(false)->end() ->arrayNode('except') ->prototype('scalar')->end() ->end() ->arrayNode('only') ->prototype('scalar')->end() ->end() ->variableNode('vars')->cannotBeEmpty()->end() ->end() ; return $treeBuilder; } }
vihuvac/Sylius
src/Sylius/Bundle/ResourceBundle/Routing/Configuration.php
PHP
mit
1,988
/*! @header FrontiaACL.h @abstract Frontia权限控制类。 @version 1.00 2013/08/05 Creation @copyright (c) 2013 baidu. All rights reserved. */ #import <Foundation/Foundation.h> @class FrontiaAccount; @interface FrontiaACL : NSObject //@property (nonatomic, assign) int publicAccess; /*! @method initWithDictionary @abstract 初始化当前权限控制对象。 @param dic - 权限控制内容 */ -(id)initWithDictionary:(NSDictionary*)dic; /*! @method setPublicReadable @abstract 为所有用户设置读权限信息。 @param flag - 如果是TRUE则可读 */ -(void)setPublicReadable:(BOOL)flag; /*! @method setPublicReadable @abstract 获取所有用户设置读权限信息。 @return 可读则返回TRUE */ -(bool)isPublicReadable; /*! @method setPublicWritable @abstract 为所有用户设置写权限信息。 @param flag -如果为TRUE,则表示可写 */ -(void)setPublicWritable:(BOOL)flag; /*! @method isPublicWritable @abstract 获取所有用户设置写权限信息。 @return 可写则返回TRUE */ -(bool)isPublicWritable; /*! @method setAccountReadable @abstract 为用户设置读权限信息 @param account - 账户 @param canRead - 如果是TRUE则可读 */ -(void)setAccountReadable:(FrontiaAccount*)account canRead:(BOOL)canRead; /*! @method isAccountReadable @abstract 获取用户账户设置的读权限信息。 @param account - 账户 @return 可读则返回TRUE */ -(bool)isAccountReadable:(FrontiaAccount*)account; /*! @method setAccountWritable @abstract 为用户设置写权限信息。 @param account - 账户 @param canWrite - 如果是TRUE则可写 */ -(void)setAccountWritable:(FrontiaAccount*)account canWrite:(BOOL)canWrite; /*! @method isAccountWritable @abstract 获取用户账户设置的写权限信息。 @param account - 账户 @return 可写则返回TRUE */ -(bool)isAccountWritable:(FrontiaAccount*)account; /*! @method toJSONObject @abstract 获取当前acl权限设置。 @return 权限信息 */ -(NSDictionary*)toJSONObject; @end
AngerDragon/ADShop
DragonUperClouds/baidu/Frontia.framework/Versions/Current/Headers/FrontiaACL.h
C
mit
2,079
using UnityEngine; using System; public static class GoEaseAnimationCurve { public static Func<float, float, float, float, float> EaseCurve( GoTween tween ) { if (tween == null) { Debug.LogError("no tween to extract easeCurve from"); } if (tween.easeCurve == null) { Debug.LogError("no curve found for tween"); } return delegate (float t, float b, float c, float d) { return tween.easeCurve.Evaluate(t / d) * c + b; }; } }
bah-interactivemedia/ReInventNASA2014
Client/Assets/Plugins/GoKit/easing/GoEaseAnimationCurve.cs
C#
mit
461
/* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.core.command.impl; import org.kie.internal.command.Context; public interface GenericCommand<T> extends org.kie.api.command.Command<T> { T execute(Context context); }
rokn/Count_Words_2015
testing/drools-master/drools-core/src/main/java/org/drools/core/command/impl/GenericCommand.java
Java
mit
815
#pragma once /** * \file NETGeographicLib/SphericalHarmonic2.h * \brief Header for NETGeographicLib::SphericalHarmonic2 class * * NETGeographicLib is copyright (c) Scott Heiman (2013) * GeographicLib is Copyright (c) Charles Karney (2010-2012) * <[email protected]> and licensed under the MIT/X11 License. * For more information, see * http://geographiclib.sourceforge.net/ **********************************************************************/ namespace NETGeographicLib { ref class CircularEngine; ref class SphericalCoefficients; /** * \brief .NET wrapper for GeographicLib::SphericalHarmonic2. * * This class allows .NET applications to access GeographicLib::SphericalHarmonic2. * * This class is similar to SphericalHarmonic, except that the coefficients * \e C<sub>\e nm</sub> are replaced by \e C<sub>\e nm</sub> + \e tau' * C'<sub>\e nm</sub> + \e tau'' C''<sub>\e nm</sub> (and similarly for \e * S<sub>\e nm</sub>). * * C# Example: * \include example-SphericalHarmonic2.cs * Managed C++ Example: * \include example-SphericalHarmonic2.cpp * Visual Basic Example: * \include example-SphericalHarmonic2.vb * * <B>INTERFACE DIFFERENCES:</B><BR> * This class replaces the () operator with HarmonicSum(). * * Coefficients, Coefficients1, and Coefficients2 return a SphericalCoefficients * object. **********************************************************************/ public ref class SphericalHarmonic2 { private: // pointer to the unmanaged GeographicLib::SphericalHarmonic2 const GeographicLib::SphericalHarmonic2* m_pSphericalHarmonic2; // the finalizer destroys the unmanaged memory when the object is destroyed. !SphericalHarmonic2(void); // the number of coefficient vectors. static const int m_numCoeffVectors = 3; // local containers for the cosine and sine coefficients. The // GeographicLib::SphericalEngine::coeffs class uses a // std::vector::iterator to access these vectors. std::vector<double> **m_C, **m_S; public: /** * Supported normalizations for associate Legendre polynomials. **********************************************************************/ enum class Normalization { /** * Fully normalized associated Legendre polynomials. See * SphericalHarmonic::FULL for documentation. * * @hideinitializer **********************************************************************/ FULL = GeographicLib::SphericalEngine::FULL, /** * Schmidt semi-normalized associated Legendre polynomials. See * SphericalHarmonic::SCHMIDT for documentation. * * @hideinitializer **********************************************************************/ SCHMIDT = GeographicLib::SphericalEngine::SCHMIDT }; /** * Constructor with a full set of coefficients specified. * * @param[in] C the coefficients \e C<sub>\e nm</sub>. * @param[in] S the coefficients \e S<sub>\e nm</sub>. * @param[in] N the maximum degree and order of the sum * @param[in] C1 the coefficients \e C'<sub>\e nm</sub>. * @param[in] S1 the coefficients \e S'<sub>\e nm</sub>. * @param[in] N1 the maximum degree and order of the first correction * coefficients \e C'<sub>\e nm</sub> and \e S'<sub>\e nm</sub>. * @param[in] C2 the coefficients \e C''<sub>\e nm</sub>. * @param[in] S2 the coefficients \e S''<sub>\e nm</sub>. * @param[in] N2 the maximum degree and order of the second correction * coefficients \e C'<sub>\e nm</sub> and \e S'<sub>\e nm</sub>. * @param[in] a the reference radius appearing in the definition of the * sum. * @param[in] norm the normalization for the associated Legendre * polynomials, either SphericalHarmonic2::FULL (the default) or * SphericalHarmonic2::SCHMIDT. * @exception GeographicErr if \e N and \e N1 do not satisfy \e N &ge; * \e N1 &ge; &minus;1, and similarly for \e N2. * @exception GeographicErr if any of the vectors of coefficients is not * large enough. * * See SphericalHarmonic for the way the coefficients should be stored. \e * N1 and \e N2 should satisfy \e N1 &le; \e N and \e N2 &le; \e N. * * The class stores <i>pointers</i> to the first elements of \e C, \e S, \e * C', \e S', \e C'', and \e S''. These arrays should not be altered or * destroyed during the lifetime of a SphericalHarmonic object. **********************************************************************/ SphericalHarmonic2(array<double>^ C, array<double>^ S, int N, array<double>^ C1, array<double>^ S1, int N1, array<double>^ C2, array<double>^ S2, int N2, double a, Normalization norm ); /** * Constructor with a subset of coefficients specified. * * @param[in] C the coefficients \e C<sub>\e nm</sub>. * @param[in] S the coefficients \e S<sub>\e nm</sub>. * @param[in] N the degree used to determine the layout of \e C and \e S. * @param[in] nmx the maximum degree used in the sum. The sum over \e n is * from 0 thru \e nmx. * @param[in] mmx the maximum order used in the sum. The sum over \e m is * from 0 thru min(\e n, \e mmx). * @param[in] C1 the coefficients \e C'<sub>\e nm</sub>. * @param[in] S1 the coefficients \e S'<sub>\e nm</sub>. * @param[in] N1 the degree used to determine the layout of \e C' and \e * S'. * @param[in] nmx1 the maximum degree used for \e C' and \e S'. * @param[in] mmx1 the maximum order used for \e C' and \e S'. * @param[in] C2 the coefficients \e C''<sub>\e nm</sub>. * @param[in] S2 the coefficients \e S''<sub>\e nm</sub>. * @param[in] N2 the degree used to determine the layout of \e C'' and \e * S''. * @param[in] nmx2 the maximum degree used for \e C'' and \e S''. * @param[in] mmx2 the maximum order used for \e C'' and \e S''. * @param[in] a the reference radius appearing in the definition of the * sum. * @param[in] norm the normalization for the associated Legendre * polynomials, either SphericalHarmonic2::FULL (the default) or * SphericalHarmonic2::SCHMIDT. * @exception GeographicErr if the parameters do not satisfy \e N &ge; \e * nmx &ge; \e mmx &ge; &minus;1; \e N1 &ge; \e nmx1 &ge; \e mmx1 &ge; * &minus;1; \e N &ge; \e N1; \e nmx &ge; \e nmx1; \e mmx &ge; \e mmx1; * and similarly for \e N2, \e nmx2, and \e mmx2. * @exception GeographicErr if any of the vectors of coefficients is not * large enough. * * The class stores <i>pointers</i> to the first elements of \e C, \e S, \e * C', \e S', \e C'', and \e S''. These arrays should not be altered or * destroyed during the lifetime of a SphericalHarmonic object. **********************************************************************/ SphericalHarmonic2(array<double>^ C, array<double>^ S, int N, int nmx, int mmx, array<double>^ C1, array<double>^ S1, int N1, int nmx1, int mmx1, array<double>^ C2, array<double>^ S2, int N2, int nmx2, int mmx2, double a, Normalization norm ); /** * The destructor calls the finalizer. **********************************************************************/ ~SphericalHarmonic2() { this->!SphericalHarmonic2(); } /** * Compute a spherical harmonic sum with two correction terms. * * @param[in] tau1 multiplier for correction coefficients \e C' and \e S'. * @param[in] tau2 multiplier for correction coefficients \e C'' and \e S''. * @param[in] x cartesian coordinate. * @param[in] y cartesian coordinate. * @param[in] z cartesian coordinate. * @return \e V the spherical harmonic sum. * * This routine requires constant memory and thus never throws an * exception. **********************************************************************/ double HarmonicSum(double tau1, double tau2, double x, double y, double z); /** * Compute a spherical harmonic sum with two correction terms and its * gradient. * * @param[in] tau1 multiplier for correction coefficients \e C' and \e S'. * @param[in] tau2 multiplier for correction coefficients \e C'' and \e S''. * @param[in] x cartesian coordinate. * @param[in] y cartesian coordinate. * @param[in] z cartesian coordinate. * @param[out] gradx \e x component of the gradient * @param[out] grady \e y component of the gradient * @param[out] gradz \e z component of the gradient * @return \e V the spherical harmonic sum. * * This is the same as the previous function, except that the components of * the gradients of the sum in the \e x, \e y, and \e z directions are * computed. This routine requires constant memory and thus never throws * an exception. **********************************************************************/ double HarmonicSum(double tau1, double tau2, double x, double y, double z, [System::Runtime::InteropServices::Out] double% gradx, [System::Runtime::InteropServices::Out] double% grady, [System::Runtime::InteropServices::Out] double% gradz); /** * Create a CircularEngine to allow the efficient evaluation of several * points on a circle of latitude at fixed values of \e tau1 and \e tau2. * * @param[in] tau1 multiplier for correction coefficients \e C' and \e S'. * @param[in] tau2 multiplier for correction coefficients \e C'' and \e S''. * @param[in] p the radius of the circle. * @param[in] z the height of the circle above the equatorial plane. * @param[in] gradp if true the returned object will be able to compute the * gradient of the sum. * @exception std::bad_alloc if the memory for the CircularEngine can't be * allocated. * @return the CircularEngine object. * * SphericalHarmonic2::operator()() exchanges the order of the sums in the * definition, i.e., &sum;<sub>n = 0..N</sub> &sum;<sub>m = 0..n</sub> * becomes &sum;<sub>m = 0..N</sub> &sum;<sub>n = m..N</sub>.. * SphericalHarmonic2::Circle performs the inner sum over degree \e n * (which entails about <i>N</i><sup>2</sup> operations). Calling * CircularEngine::operator()() on the returned object performs the outer * sum over the order \e m (about \e N operations). * * See SphericalHarmonic::Circle for an example of its use. **********************************************************************/ CircularEngine^ Circle(double tau1, double tau2, double p, double z, bool gradp); /** * @return the zeroth SphericalCoefficients object. **********************************************************************/ SphericalCoefficients^ Coefficients(); /** * @return the first SphericalCoefficients object. **********************************************************************/ SphericalCoefficients^ Coefficients1(); /** * @return the second SphericalCoefficients object. **********************************************************************/ SphericalCoefficients^ Coefficients2(); }; } // namespace NETGeographicLib
JanEicken/MA
libs/GeographicLib-1.43/dotnet/NETGeographicLib/SphericalHarmonic2.h
C
mit
12,636
import map from './map'; export default map;
hoka-plus/p-01-web
tmp/babel-output_path-MNyU5yIO.tmp/modules/lodash/collection/collect.js
JavaScript
mit
44
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell { /// <summary> /// /// ProgressNode is an augmentation of the ProgressRecord type that adds extra fields for the purposes of tracking /// outstanding activities received by the host, and rendering them in the console. /// /// </summary> internal class ProgressNode : ProgressRecord { /// <summary> /// /// Indicates the various layouts for rendering a particular node. Each style is progressively less terse. /// /// </summary> internal enum RenderStyle { Invisible = 0, Minimal = 1, Compact = 2, /// <summary> /// Allocate only one line for displaying the StatusDescription or the CurrentOperation, /// truncate the rest if the StatusDescription or CurrentOperation doesn't fit in one line /// </summary> Full = 3, /// <summary> /// The node will be displayed the same as Full, plus, the whole StatusDescription and CurrentOperation will be displayed (in multiple lines if needed). /// </summary> FullPlus = 4, }; /// <summary> /// /// Constructs an instance from a ProgressRecord. /// /// </summary> internal ProgressNode(Int64 sourceId, ProgressRecord record) : base(record.ActivityId, record.Activity, record.StatusDescription) { Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records"); this.ParentActivityId = record.ParentActivityId; this.CurrentOperation = record.CurrentOperation; this.PercentComplete = Math.Min(record.PercentComplete, 100); this.SecondsRemaining = record.SecondsRemaining; this.RecordType = record.RecordType; this.Style = RenderStyle.FullPlus; this.SourceId = sourceId; } /// <summary> /// /// Renders a single progress node as strings of text according to that node's style. The text is appended to the /// supplied list of strings. /// /// </summary> /// <param name="strCollection"> /// /// List of strings to which the node's rendering will be appended. /// /// </param> /// <param name="indentation"> /// /// The indentation level (in BufferCells) at which the node should be rendered. /// /// </param> /// <param name="maxWidth"> /// /// The maximum number of BufferCells that the rendering is allowed to consume. /// /// </param> /// <param name="rawUI"> /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// /// </param> internal void Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { Dbg.Assert(strCollection != null, "strCollection should not be null"); Dbg.Assert(indentation >= 0, "indentation is negative"); Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records"); switch (Style) { case RenderStyle.FullPlus: RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: true); break; case RenderStyle.Full: RenderFull(strCollection, indentation, maxWidth, rawUI, isFullPlus: false); break; case RenderStyle.Compact: RenderCompact(strCollection, indentation, maxWidth, rawUI); break; case RenderStyle.Minimal: RenderMinimal(strCollection, indentation, maxWidth, rawUI); break; case RenderStyle.Invisible: // do nothing break; default: Dbg.Assert(false, "unrecognized RenderStyle value"); break; } } /// <summary> /// /// Renders a node in the "Full" style. /// /// </summary> /// <param name="strCollection"> /// /// List of strings to which the node's rendering will be appended. /// /// </param> /// <param name="indentation"> /// /// The indentation level (in BufferCells) at which the node should be rendered. /// /// </param> /// <param name="maxWidth"> /// /// The maximum number of BufferCells that the rendering is allowed to consume. /// /// </param> /// <param name="rawUI"> /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// /// </param> /// <param name="isFullPlus"> /// /// Indicate if the full StatusDescription and CurrentOperation should be displayed. /// /// </param> private void RenderFull(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI, bool isFullPlus) { string indent = new string(' ', indentation); // First line: the activity strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth)); indentation += 3; indent = new string(' ', indentation); // Second line: the status description RenderFullDescription(this.StatusDescription, indent, maxWidth, rawUI, strCollection, isFullPlus); // Third line: the percentage thermometer. The size of this is proportional to the width we're allowed // to consume. -2 for the whitespace, -2 again for the brackets around thermo, -5 to not be too big if (PercentComplete >= 0) { int thermoWidth = Math.Max(3, maxWidth - indentation - 2 - 2 - 5); int mercuryWidth = 0; mercuryWidth = PercentComplete * thermoWidth / 100; if (PercentComplete < 100 && mercuryWidth == thermoWidth) { // back off a tad unless we're totally complete to prevent the appearance of completion before // the fact. --mercuryWidth; } strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format( " {0}[{1}{2}] ", indent, new string('o', mercuryWidth), new string(' ', thermoWidth - mercuryWidth)), maxWidth)); } // Fourth line: the seconds remaining if (SecondsRemaining >= 0) { TimeSpan span = new TimeSpan(0, 0, this.SecondsRemaining); strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, " " + StringUtil.Format( ProgressNodeStrings.SecondsRemaining, indent, span) + " ", maxWidth)); } // Fifth and Sixth lines: The current operation if (!String.IsNullOrEmpty(CurrentOperation)) { strCollection.Add(" "); RenderFullDescription(this.CurrentOperation, indent, maxWidth, rawUI, strCollection, isFullPlus); } } private static void RenderFullDescription(string description, string indent, int maxWidth, PSHostRawUserInterface rawUi, ArrayList strCollection, bool isFullPlus) { string oldDescription = StringUtil.Format(" {0}{1} ", indent, description); string newDescription; do { newDescription = StringUtil.TruncateToBufferCellWidth(rawUi, oldDescription, maxWidth); strCollection.Add(newDescription); if (oldDescription.Length == newDescription.Length) { break; } else { oldDescription = StringUtil.Format(" {0}{1}", indent, oldDescription.Substring(newDescription.Length)); } } while (isFullPlus); } /// <summary> /// /// Renders a node in the "Compact" style. /// /// </summary> /// <param name="strCollection"> /// /// List of strings to which the node's rendering will be appended. /// /// </param> /// <param name="indentation"> /// /// The indentation level (in BufferCells) at which the node should be rendered. /// /// </param> /// <param name="maxWidth"> /// /// The maximum number of BufferCells that the rendering is allowed to consume. /// /// </param> /// <param name="rawUI"> /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// /// </param> private void RenderCompact(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { string indent = new string(' ', indentation); // First line: the activity strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format(" {0}{1} ", indent, this.Activity), maxWidth)); indentation += 3; indent = new string(' ', indentation); // Second line: the status description with percentage and time remaining, if applicable. string percent = ""; if (PercentComplete >= 0) { percent = StringUtil.Format("{0}% ", PercentComplete); } string secRemain = ""; if (SecondsRemaining >= 0) { TimeSpan span = new TimeSpan(0, 0, SecondsRemaining); secRemain = span.ToString() + " "; } strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format( " {0}{1}{2}{3} ", indent, percent, secRemain, StatusDescription), maxWidth)); // Third line: The current operation if (!String.IsNullOrEmpty(CurrentOperation)) { strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format(" {0}{1} ", indent, this.CurrentOperation), maxWidth)); } } /// <summary> /// /// Renders a node in the "Minimal" style. /// /// </summary> /// <param name="strCollection"> /// /// List of strings to which the node's rendering will be appended. /// /// </param> /// <param name="indentation"> /// /// The indentation level (in BufferCells) at which the node should be rendered. /// /// </param> /// <param name="maxWidth"> /// /// The maximum number of BufferCells that the rendering is allowed to consume. /// /// </param> /// <param name="rawUI"> /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// /// </param> private void RenderMinimal(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { string indent = new string(' ', indentation); // First line: Everything mushed into one line string percent = ""; if (PercentComplete >= 0) { percent = StringUtil.Format("{0}% ", PercentComplete); } string secRemain = ""; if (SecondsRemaining >= 0) { TimeSpan span = new TimeSpan(0, 0, SecondsRemaining); secRemain = span.ToString() + " "; } strCollection.Add( StringUtil.TruncateToBufferCellWidth( rawUI, StringUtil.Format( " {0}{1} {2}{3}{4} ", indent, Activity, percent, secRemain, StatusDescription), maxWidth)); } /// <summary> /// /// The nodes that have this node as their parent. /// /// </summary> internal ArrayList Children; /// <summary> /// /// The "age" of the node. A node's age is incremented by PendingProgress.Update each time a new ProgressRecord is /// received by the host. A node's age is reset when a corresponding ProgressRecord is received. Thus, the age of /// a node reflects the number of ProgressRecord that have been received since the node was last updated. /// /// The age is used by PendingProgress.Render to determine which nodes should be rendered on the display, and how. As the /// display has finite size, it may be possible to have many more outstanding progress activities than will fit in that /// space. The rendering of nodes can be progressively "compressed" into a more terse format, or not rendered at all in /// order to fit as many nodes as possible in the available space. The oldest nodes are compressed or skipped first. /// /// </summary> internal int Age; /// <summary> /// /// The style in which this node should be rendered. /// /// </summary> internal RenderStyle Style = RenderStyle.FullPlus; /// <summary> /// /// Identifies the source of the progress record. /// /// </summary> internal Int64 SourceId; /// <summary> /// /// The number of vertical BufferCells that are required to render the node in its current style. /// /// </summary> /// <value></value> internal int LinesRequiredMethod(PSHostRawUserInterface rawUi, int maxWidth) { Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records"); switch (Style) { case RenderStyle.FullPlus: return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: true); case RenderStyle.Full: return LinesRequiredInFullStyleMethod(rawUi, maxWidth, isFullPlus: false); case RenderStyle.Compact: return LinesRequiredInCompactStyle; case RenderStyle.Minimal: return 1; case RenderStyle.Invisible: return 0; default: Dbg.Assert(false, "Unknown RenderStyle value"); break; } return 0; } /// <summary> /// /// The number of vertical BufferCells that are required to render the node in the Full style. /// /// </summary> /// <value></value> private int LinesRequiredInFullStyleMethod(PSHostRawUserInterface rawUi, int maxWidth, bool isFullPlus) { // Since the fields of this instance could have been changed, we compute this on-the-fly. // NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to // word-wrap text fields, then this calculation will need updating. // Start with 1 for the Activity int lines = 1; // Use 5 spaces as the heuristic indent. 5 spaces stand for the indent for the CurrentOperation of the first-level child node var indent = new string(' ', 5); var temp = new ArrayList(); if (isFullPlus) { temp.Clear(); RenderFullDescription(StatusDescription, indent, maxWidth, rawUi, temp, isFullPlus: true); lines += temp.Count; } else { // 1 for the Status lines++; } if (PercentComplete >= 0) { ++lines; } if (SecondsRemaining >= 0) { ++lines; } if (!String.IsNullOrEmpty(CurrentOperation)) { if (isFullPlus) { lines += 1; temp.Clear(); RenderFullDescription(CurrentOperation, indent, maxWidth, rawUi, temp, isFullPlus: true); lines += temp.Count; } else { lines += 2; } } return lines; } /// <summary> /// /// The number of vertical BufferCells that are required to render the node in the Compact style. /// /// </summary> /// <value></value> private int LinesRequiredInCompactStyle { get { // Since the fields of this instance could have been changed, we compute this on-the-fly. // NTRAID#Windows OS Bugs-1062104-2004/12/15-sburns we assume 1 line for each field. If we ever need to // word-wrap text fields, then this calculation will need updating. // Start with 1 for the Activity, and 1 for the Status. int lines = 2; if (!String.IsNullOrEmpty(CurrentOperation)) { ++lines; } return lines; } } } } // namespace
bingbing8/PowerShell
src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs
C#
mit
19,385
/** * @author Richard Davey <[email protected]> * @author Mat Groves (@Doormat23) * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * New version of PIXI.ComplexPrimitiveShader * * @class Phaser.Renderer.Canvas * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. */ Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics = function (renderer) { this.renderer = renderer; // WebGLContext this.gl = renderer.gl; /** * @property _UID * @type Number * @private */ this._UID = renderer.getShaderID(this); /** * The WebGL program. * @property program * @type Any */ this.program = null; /** * The vertex shader. * @property vertexSrc * @type Array */ this.fragmentSrc = []; this.vertexSrc = []; this.attributes = []; // @type {WebGLUniformLocation } this.projectionVector; // @type {WebGLUniformLocation } this.offsetVector; // @type {WebGLUniformLocation } this.tintColor; // @type {WebGLUniformLocation } this.color; // @type {WebGLUniformLocation } this.flipY; // @type {GLint} this.aVertexPosition; // @type {GLint} this.colorAttribute; // @type {WebGLUniformLocation } this.translationMatrix; // @type {WebGLUniformLocation } this.alpha; this.init(); }; Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics.prototype.constructor = Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics; Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics.prototype = { init: function () { this.fragmentSrc = [ 'precision mediump float;', 'varying vec4 vColor;', 'void main(void) {', ' gl_FragColor = vColor;', '}' ]; this.vertexSrc = [ 'attribute vec2 aVertexPosition;', 'uniform mat3 translationMatrix;', 'uniform vec2 projectionVector;', 'uniform vec2 offsetVector;', 'uniform vec3 tint;', 'uniform float alpha;', 'uniform vec3 color;', 'uniform float flipY;', 'varying vec4 vColor;', 'void main(void) {', ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);', ' v -= offsetVector.xyx;', ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);', ' vColor = vec4(color * alpha * tint, alpha);', '}' ]; var program = this.renderer.compileProgram(this.vertexSrc, this.fragmentSrc); var gl = this.gl; gl.useProgram(program); // get and store the uniforms for the shader this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); this.tintColor = gl.getUniformLocation(program, 'tint'); this.flipY = gl.getUniformLocation(program, 'flipY'); this.color = gl.getUniformLocation(program, 'color'); // get and store the attributes this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); this.colorAttribute = gl.getAttribLocation(program, 'aColor'); // this.attributes = [ this.aVertexPosition, this.colorAttribute ]; this.attributes = [ this.aVertexPosition ]; this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); this.alpha = gl.getUniformLocation(program, 'alpha'); this.program = program; }, destroy: function () { this.gl.deleteProgram(this.program); this.gl = null; this.renderer = null; this.attributes = null; } };
clark-stevenson/phaser
v3/merge/renderer/webgl/shaders/ComplexPrimitiveGraphics.js
JavaScript
mit
3,947
/* reset styling (prevent conflicts with bootstrap, materialize.css, etc.) */ div.jsoneditor .jsoneditor-search input { height: auto; border: inherit; } div.jsoneditor .jsoneditor-search input:focus { border: none !important; box-shadow: none !important; } div.jsoneditor table { border-collapse: collapse; width: auto; } div.jsoneditor td, div.jsoneditor th { padding: 0; display: table-cell; text-align: left; vertical-align: inherit; border-radius: inherit; } div.jsoneditor-field, div.jsoneditor-value, div.jsoneditor-readonly { border: 1px solid transparent; min-height: 16px; min-width: 32px; padding: 2px; margin: 1px; word-wrap: break-word; float: left; } /* adjust margin of p elements inside editable divs, needed for Opera, IE */ div.jsoneditor-field p, div.jsoneditor-value p { margin: 0; } div.jsoneditor-value { word-break: break-word; } div.jsoneditor-readonly { min-width: 16px; color: #808080; } div.jsoneditor-empty { border-color: #d3d3d3; border-style: dashed; border-radius: 2px; } div.jsoneditor-field.jsoneditor-empty::after, div.jsoneditor-value.jsoneditor-empty::after { pointer-events: none; color: #d3d3d3; font-size: 8pt; } div.jsoneditor-field.jsoneditor-empty::after { content: "field"; } div.jsoneditor-value.jsoneditor-empty::after { content: "value"; } div.jsoneditor-value.jsoneditor-url, a.jsoneditor-value.jsoneditor-url { color: green; text-decoration: underline; } a.jsoneditor-value.jsoneditor-url { display: inline-block; padding: 2px; margin: 2px; } a.jsoneditor-value.jsoneditor-url:hover, a.jsoneditor-value.jsoneditor-url:focus { color: #ee422e; } div.jsoneditor td.jsoneditor-separator { padding: 3px 0; vertical-align: top; color: #808080; } div.jsoneditor-field[contenteditable=true]:focus, div.jsoneditor-field[contenteditable=true]:hover, div.jsoneditor-value[contenteditable=true]:focus, div.jsoneditor-value[contenteditable=true]:hover, div.jsoneditor-field.jsoneditor-highlight, div.jsoneditor-value.jsoneditor-highlight { background-color: #FFFFAB; border: 1px solid yellow; border-radius: 2px; } div.jsoneditor-field.jsoneditor-highlight-active, div.jsoneditor-field.jsoneditor-highlight-active:focus, div.jsoneditor-field.jsoneditor-highlight-active:hover, div.jsoneditor-value.jsoneditor-highlight-active, div.jsoneditor-value.jsoneditor-highlight-active:focus, div.jsoneditor-value.jsoneditor-highlight-active:hover { background-color: #ffee00; border: 1px solid #ffc700; border-radius: 2px; } div.jsoneditor-value.jsoneditor-string { color: #008000; } div.jsoneditor-value.jsoneditor-object, div.jsoneditor-value.jsoneditor-array { min-width: 16px; color: #808080; } div.jsoneditor-value.jsoneditor-number { color: #ee422e; } div.jsoneditor-value.jsoneditor-boolean { color: #ff8c00; } div.jsoneditor-value.jsoneditor-null { color: #004ED0; } div.jsoneditor-value.jsoneditor-invalid { color: #000000; } div.jsoneditor-tree button.jsoneditor-button { width: 24px; height: 24px; padding: 0; margin: 0; border: none; cursor: pointer; background: transparent url("img/jsoneditor-icons.svg"); } div.jsoneditor-mode-view tr.jsoneditor-expandable td.jsoneditor-tree, div.jsoneditor-mode-form tr.jsoneditor-expandable td.jsoneditor-tree { cursor: pointer; } div.jsoneditor-tree button.jsoneditor-collapsed { background-position: 0 -48px; } div.jsoneditor-tree button.jsoneditor-expanded { background-position: 0 -72px; } div.jsoneditor-tree button.jsoneditor-contextmenu { background-position: -48px -72px; } div.jsoneditor-tree button.jsoneditor-contextmenu:hover, div.jsoneditor-tree button.jsoneditor-contextmenu:focus, div.jsoneditor-tree button.jsoneditor-contextmenu.jsoneditor-selected, tr.jsoneditor-selected.jsoneditor-first button.jsoneditor-contextmenu { background-position: -48px -48px; } div.jsoneditor-tree *:focus { outline: none; } div.jsoneditor-tree button.jsoneditor-button:focus { /* TODO: nice outline for buttons with focus outline: #97B0F8 solid 2px; box-shadow: 0 0 8px #97B0F8; */ background-color: #f5f5f5; outline: #e5e5e5 solid 1px; } div.jsoneditor-tree button.jsoneditor-invisible { visibility: hidden; background: none; } div.jsoneditor-tree div.jsoneditor-show-more { display: inline-block; padding: 3px 4px; margin: 2px 0; background-color: #e5e5e5; border-radius: 3px; color: #808080; font-family: arial, sans-serif; font-size: 10pt; } div.jsoneditor-tree div.jsoneditor-show-more a { display: inline-block; color: #808080; } div.jsoneditor-tree div.jsoneditor-show-more a:hover, div.jsoneditor-tree div.jsoneditor-show-more a:focus { color: #ee422e; } div.jsoneditor-tree div.jsoneditor-color { display: inline-block; width: 12px; height: 12px; margin: 4px; border: 1px solid #808080; cursor: pointer; } div.jsoneditor-tree div.jsoneditor-color .picker_wrapper.popup.popup_bottom { top: 28px; left: -10px; } div.jsoneditor-tree div.jsoneditor-date { background: #a1a1a1; color: white; font-family: arial, sans-serif; border-radius: 3px; display: inline-block; padding: 3px; margin: 0 3px; } div.jsoneditor { color: #1A1A1A; border: 1px solid #3883fa; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; width: 100%; height: 100%; position: relative; padding: 0; line-height: 100%; } div.jsoneditor-tree table.jsoneditor-tree { border-collapse: collapse; border-spacing: 0; width: 100%; } div.jsoneditor-tree div.jsoneditor-tree-inner { padding-bottom: 300px; } div.jsoneditor-outer { position: static; width: 100%; height: 100%; margin: -35px 0 0 0; padding: 35px 0 0 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } div.jsoneditor-outer.has-nav-bar { margin: -61px 0 0 0; padding: 61px 0 0 0; } div.jsoneditor-outer.has-status-bar { margin: -35px 0 -26px 0; padding: 35px 0 26px 0; } textarea.jsoneditor-text, .ace-jsoneditor { min-height: 150px; } div.jsoneditor-tree { width: 100%; height: 100%; position: relative; overflow: auto; } textarea.jsoneditor-text { width: 100%; height: 100%; margin: 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; outline-width: 0; border: none; background-color: white; resize: none; } tr.jsoneditor-highlight, tr.jsoneditor-selected { background-color: #d3d3d3; } tr.jsoneditor-selected button.jsoneditor-dragarea, tr.jsoneditor-selected button.jsoneditor-contextmenu { visibility: hidden; } tr.jsoneditor-selected.jsoneditor-first button.jsoneditor-dragarea, tr.jsoneditor-selected.jsoneditor-first button.jsoneditor-contextmenu { visibility: visible; } div.jsoneditor-tree button.jsoneditor-dragarea { background: url("img/jsoneditor-icons.svg") -72px -72px; cursor: move; } div.jsoneditor-tree button.jsoneditor-dragarea:hover, div.jsoneditor-tree button.jsoneditor-dragarea:focus, tr.jsoneditor-selected.jsoneditor-first button.jsoneditor-dragarea { background-position: -72px -48px; } div.jsoneditor tr, div.jsoneditor th, div.jsoneditor td { padding: 0; margin: 0; } div.jsoneditor td { vertical-align: top; } div.jsoneditor td.jsoneditor-tree { vertical-align: top; } div.jsoneditor-field, div.jsoneditor-value, div.jsoneditor td, div.jsoneditor th, div.jsoneditor textarea, .jsoneditor-schema-error { font-family: "dejavu sans mono", "droid sans mono", consolas, monaco, "lucida console", "courier new", courier, monospace, sans-serif; font-size: 10pt; color: #1A1A1A; } /* popover */ .jsoneditor-schema-error { cursor: default; display: inline-block; /*font-family: arial, sans-serif;*/ height: 24px; line-height: 24px; position: relative; text-align: center; width: 24px; } div.jsoneditor-tree .jsoneditor-button.jsoneditor-schema-error { width: 24px; height: 24px; padding: 0; margin: 0 4px 0 0; background: url("img/jsoneditor-icons.svg") -168px -48px; } .jsoneditor-schema-error .jsoneditor-popover { background-color: #4c4c4c; border-radius: 3px; box-shadow: 0 0 5px rgba(0,0,0,0.4); color: #fff; display: none; padding: 7px 10px; position: absolute; width: 200px; z-index: 4; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-above { bottom: 32px; left: -98px; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-below { top: 32px; left: -98px; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-left { top: -7px; right: 32px; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-right { top: -7px; left: 32px; } .jsoneditor-schema-error .jsoneditor-popover:before { border-right: 7px solid transparent; border-left: 7px solid transparent; content: ''; display: block; left: 50%; margin-left: -7px; position: absolute; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-above:before { border-top: 7px solid #4c4c4c; bottom: -7px; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-below:before { border-bottom: 7px solid #4c4c4c; top: -7px; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-left:before { border-left: 7px solid #4c4c4c; border-top: 7px solid transparent; border-bottom: 7px solid transparent; content: ''; top: 19px; right: -14px; left: inherit; margin-left: inherit; margin-top: -7px; position: absolute; } .jsoneditor-schema-error .jsoneditor-popover.jsoneditor-right:before { border-right: 7px solid #4c4c4c; border-top: 7px solid transparent; border-bottom: 7px solid transparent; content: ''; top: 19px; left: -14px; margin-left: inherit; margin-top: -7px; position: absolute; } .jsoneditor-schema-error:hover .jsoneditor-popover, .jsoneditor-schema-error:focus .jsoneditor-popover { display: block; -webkit-animation: fade-in .3s linear 1, move-up .3s linear 1; -moz-animation: fade-in .3s linear 1, move-up .3s linear 1; -ms-animation: fade-in .3s linear 1, move-up .3s linear 1; } @-webkit-keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @-moz-keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @-ms-keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } /*@-webkit-keyframes move-up {*/ /*from { bottom: 24px; }*/ /*to { bottom: 32px; }*/ /*}*/ /*@-moz-keyframes move-up {*/ /*from { bottom: 24px; }*/ /*to { bottom: 32px; }*/ /*}*/ /*@-ms-keyframes move-up {*/ /*from { bottom: 24px; }*/ /*to { bottom: 32px; }*/ /*}*/ /* JSON schema errors displayed at the bottom of the editor in mode text and code */ .jsoneditor .jsoneditor-validation-errors-container { max-height: 130px; overflow-y: auto; } .jsoneditor .jsoneditor-additional-errors { position: absolute; margin: auto; bottom: 31px; left: calc(50% - 92px); color: #808080; background-color: #ebebeb; padding: 7px 15px; border-radius: 8px; } .jsoneditor .jsoneditor-additional-errors.visible { visibility: visible; opacity: 1; transition: opacity 2s linear; } .jsoneditor .jsoneditor-additional-errors.hidden { visibility: hidden; opacity: 0; transition: visibility 0s 2s, opacity 2s linear; } .jsoneditor .jsoneditor-text-errors { width: 100%; border-collapse: collapse; background-color: #ffef8b; border-top: 1px solid #ffd700; } .jsoneditor .jsoneditor-text-errors td { padding: 3px 6px; vertical-align: middle; } .jsoneditor-text-errors .jsoneditor-schema-error { border: none; width: 24px; height: 24px; padding: 0; margin: 0 4px 0 0; background: url("img/jsoneditor-icons.svg") -168px -48px; } .fadein { -webkit-animation: fadein .3s; animation: fadein .3s; -moz-animation: fadein .3s; -o-animation: fadein .3s; } @-webkit-keyframes fadein { 0% { opacity: 0; } 100% { opacity: 1; } } @-moz-keyframes fadein { 0% { opacity: 0; } 100% { opacity: 1; } } @keyframes fadein { 0% { opacity: 0; } 100% { opacity: 1; } } @-o-keyframes fadein { 0% { opacity: 0; } 100% { opacity: 1; } } /* ContextMenu - main menu */ div.jsoneditor-contextmenu-root { position: relative; width: 0; height: 0; } div.jsoneditor-contextmenu { position: absolute; box-sizing: content-box; z-index: 99999; } div.jsoneditor-contextmenu ul, div.jsoneditor-contextmenu li { box-sizing: content-box; position: relative; } div.jsoneditor-contextmenu ul { position: relative; left: 0; top: 0; width: 128px; background: white; border: 1px solid #d3d3d3; box-shadow: 2px 2px 12px rgba(128, 128, 128, 0.3); list-style: none; margin: 0; padding: 0; } div.jsoneditor-contextmenu ul li button { position: relative; padding: 0 4px 0 0; margin: 0; width: 128px; height: auto; border: none; cursor: pointer; color: #4d4d4d; background: transparent; font-size: 10pt; font-family: arial, sans-serif; box-sizing: border-box; text-align: left; } /* Fix button padding in firefox */ div.jsoneditor-contextmenu ul li button::-moz-focus-inner { padding: 0; border: 0; } div.jsoneditor-contextmenu ul li button:hover, div.jsoneditor-contextmenu ul li button:focus { color: #1a1a1a; background-color: #f5f5f5; outline: none; } div.jsoneditor-contextmenu ul li button.jsoneditor-default { width: 96px; /* 128px - 32px */ } div.jsoneditor-contextmenu ul li button.jsoneditor-expand { float: right; width: 32px; height: 24px; border-left: 1px solid #e5e5e5; } div.jsoneditor-contextmenu div.jsoneditor-icon { position: absolute; top: 0; left: 0; width: 24px; height: 24px; border: none; padding: 0; margin: 0; background-image: url("img/jsoneditor-icons.svg"); } div.jsoneditor-contextmenu ul li ul div.jsoneditor-icon { margin-left: 24px; } div.jsoneditor-contextmenu div.jsoneditor-text { padding: 4px 0 4px 24px; word-wrap: break-word; } div.jsoneditor-contextmenu div.jsoneditor-text.jsoneditor-right-margin { padding-right: 24px; } div.jsoneditor-contextmenu ul li button div.jsoneditor-expand { position: absolute; top: 0; right: 0; width: 24px; height: 24px; padding: 0; margin: 0 4px 0 0; background: url("img/jsoneditor-icons.svg") 0 -72px; } div.jsoneditor-contextmenu div.jsoneditor-separator { height: 0; border-top: 1px solid #e5e5e5; padding-top: 5px; margin-top: 5px; } div.jsoneditor-contextmenu button.jsoneditor-remove > div.jsoneditor-icon { background-position: -24px 0; } div.jsoneditor-contextmenu button.jsoneditor-append > div.jsoneditor-icon { background-position: 0 0; } div.jsoneditor-contextmenu button.jsoneditor-insert > div.jsoneditor-icon { background-position: 0 0; } div.jsoneditor-contextmenu button.jsoneditor-duplicate > div.jsoneditor-icon { background-position: -48px 0; } div.jsoneditor-contextmenu button.jsoneditor-sort-asc > div.jsoneditor-icon { background-position: -168px 0; } div.jsoneditor-contextmenu button.jsoneditor-sort-desc > div.jsoneditor-icon { background-position: -192px 0; } div.jsoneditor-contextmenu button.jsoneditor-transform > div.jsoneditor-icon { background-position: -216px 0; } /* ContextMenu - sub menu */ div.jsoneditor-contextmenu ul li button.jsoneditor-selected, div.jsoneditor-contextmenu ul li button.jsoneditor-selected:hover, div.jsoneditor-contextmenu ul li button.jsoneditor-selected:focus { color: white; background-color: #ee422e; } div.jsoneditor-contextmenu ul li { overflow: hidden; } div.jsoneditor-contextmenu ul li ul { display: none; position: relative; left: -10px; top: 0; border: none; box-shadow: inset 0 0 10px rgba(128, 128, 128, 0.5); padding: 0 10px; /* TODO: transition is not supported on IE8-9 */ -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; -o-transition: all 0.3s ease-out; transition: all 0.3s ease-out; } div.jsoneditor-contextmenu ul li ul li button { padding-left: 24px; animation: all ease-in-out 1s; } div.jsoneditor-contextmenu ul li ul li button:hover, div.jsoneditor-contextmenu ul li ul li button:focus { background-color: #f5f5f5; } div.jsoneditor-contextmenu button.jsoneditor-type-string > div.jsoneditor-icon { background-position: -144px 0; } div.jsoneditor-contextmenu button.jsoneditor-type-auto > div.jsoneditor-icon { background-position: -120px 0; } div.jsoneditor-contextmenu button.jsoneditor-type-object > div.jsoneditor-icon { background-position: -72px 0; } div.jsoneditor-contextmenu button.jsoneditor-type-array > div.jsoneditor-icon { background-position: -96px 0; } div.jsoneditor-contextmenu button.jsoneditor-type-modes > div.jsoneditor-icon { background-image: none; width: 6px; } /* pico modal styling */ .jsoneditor-modal-overlay { position: absolute !important; background: rgb(1,1,1) !important; opacity: 0.3 !important; } .jsoneditor-modal { position: absolute !important; max-width: 95% !important; width: auto !important; border-radius: 2px !important; padding: 45px 15px 15px 15px !important; box-shadow: 2px 2px 12px rgba(128, 128, 128, 0.3) !important; color: #4d4d4d; line-height: 1.3em; } .jsoneditor-modal.jsoneditor-modal-transform { width: 600px !important; } .jsoneditor-modal .pico-modal-header { position: absolute; box-sizing: border-box; top: 0; left: 0; width: 100%; padding: 0 10px; height: 30px; line-height: 30px; font-family: arial, sans-serif; font-size: 11pt; background: #3883fa; color: white; } .jsoneditor-modal table { width: 100%; } .jsoneditor-modal table th, .jsoneditor-modal table td { padding: 5px 20px 5px 0; text-align: left; vertical-align: top; font-weight: normal; color: #4d4d4d; line-height: 32px; } .jsoneditor-modal p:first-child { margin-top: 0; } .jsoneditor-modal a { color: #3883fa; } .jsoneditor-modal table td.jsoneditor-modal-input { text-align: right; padding-right: 0; white-space: nowrap; } .jsoneditor-modal table td.jsoneditor-modal-actions { padding-top: 15px; } .jsoneditor-modal .pico-close { background: none !important; font-size: 24px !important; top: 7px !important; right: 7px !important; color: white; } .jsoneditor-modal select, .jsoneditor-modal textarea, .jsoneditor-modal input, .jsoneditor-modal #query { background: #ffffff; border: 1px solid #d3d3d3; color: #4d4d4d; border-radius: 3px; padding: 4px; } .jsoneditor-modal, .jsoneditor-modal table td, .jsoneditor-modal table th, .jsoneditor-modal select, .jsoneditor-modal option, .jsoneditor-modal textarea, .jsoneditor-modal input, .jsoneditor-modal #query { font-size: 10.5pt; font-family: arial, sans-serif; } .jsoneditor-modal #query, .jsoneditor-modal .jsoneditor-transform-preview { font-family: "dejavu sans mono", "droid sans mono", consolas, monaco, "lucida console", "courier new", courier, monospace, sans-serif; font-size: 10pt; } .jsoneditor-modal input[type="button"], .jsoneditor-modal input[type="submit"] { background: #f5f5f5; padding: 4px 20px; } .jsoneditor-modal select, .jsoneditor-modal input { cursor: pointer; } .jsoneditor-modal input { padding: 4px; } .jsoneditor-modal input[type="text"] { cursor: inherit; } .jsoneditor-modal input[disabled] { background: #d3d3d3; color: #808080; } .jsoneditor-modal .jsoneditor-select-wrapper { position: relative; display: inline-block; } .jsoneditor-modal .jsoneditor-select-wrapper:after { content: ""; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 6px solid #666; position: absolute; right: 8px; top: 14px; pointer-events: none; } .jsoneditor-modal select { padding: 3px 24px 3px 10px; min-width: 180px; max-width: 350px; -webkit-appearance: none; -moz-appearance: none; appearance: none; text-indent: 0; text-overflow: ""; font-size: 10pt; line-height: 1.5em; } .jsoneditor-modal select::-ms-expand { display: none; } .jsoneditor-modal .jsoneditor-button-group input { padding: 4px 10px; margin: 0; border-radius: 0; border-left-style: none; } .jsoneditor-modal .jsoneditor-button-group input.jsoneditor-button-first { border-top-left-radius: 3px; border-bottom-left-radius: 3px; border-left-style: solid; } .jsoneditor-modal .jsoneditor-button-group input.jsoneditor-button-last { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } .jsoneditor-modal .jsoneditor-button-group.jsoneditor-button-group-value-asc input.jsoneditor-button-asc, .jsoneditor-modal .jsoneditor-button-group.jsoneditor-button-group-value-desc input.jsoneditor-button-desc { background: #3883fa; border-color: #3883fa; color: white; } .jsoneditor-modal #query, .jsoneditor-modal .jsoneditor-transform-preview { width: 100%; box-sizing: border-box; } .jsoneditor-modal .jsoneditor-transform-preview { background: #f5f5f5; height: 200px; } .jsoneditor-modal .jsoneditor-transform-preview.jsoneditor-error { color: #ee422e; } .jsoneditor-modal .jsoneditor-jmespath-wizard { line-height: 1.2em; width: 100%; background: #ffffe0; border: 1px solid #ffe99a; padding: 0 10px 10px; border-radius: 3px; } .jsoneditor-modal .jsoneditor-jmespath-wizard-label { font-style: italic; margin: 4px 0 2px 0; } .jsoneditor-modal .jsoneditor-inline { position: relative; display: inline-block; width: 100%; padding: 2px; } .jsoneditor-modal .jsoneditor-jmespath-filter { display: flex; flex-wrap: wrap; } .jsoneditor-modal .jsoneditor-jmespath-filter-field { width: 170px; } .jsoneditor-modal .jsoneditor-jmespath-filter-relation { width: 100px; } .jsoneditor-modal .jsoneditor-jmespath-filter-value { min-width: 100px; flex: 1; } .jsoneditor-modal .jsoneditor-jmespath-sort-field { width: 170px; } .jsoneditor-modal .jsoneditor-jmespath-sort-order { width: 150px; } .jsoneditor-modal .jsoneditor-jmespath-select-fields { width: 100%; } .jsoneditor-modal .selectr-selected { border-color: #d3d3d3; padding: 4px 28px 4px 8px; } .jsoneditor-modal .selectr-selected .selectr-tag { background-color: #3883fa; border-radius: 5px; } div.jsoneditor-menu { width: 100%; height: 35px; padding: 2px; margin: 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; color: white; background-color: #3883fa; border-bottom: 1px solid #3883fa; } div.jsoneditor-menu > button, div.jsoneditor-menu > div.jsoneditor-modes > button { width: 26px; height: 26px; margin: 2px; padding: 0; border-radius: 2px; border: 1px solid transparent; background: transparent url("img/jsoneditor-icons.svg"); color: white; opacity: 0.8; font-family: arial, sans-serif; font-size: 10pt; float: left; } div.jsoneditor-menu > button:hover, div.jsoneditor-menu > div.jsoneditor-modes > button:hover { background-color: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.4); } div.jsoneditor-menu > button:focus, div.jsoneditor-menu > button:active, div.jsoneditor-menu > div.jsoneditor-modes > button:focus, div.jsoneditor-menu > div.jsoneditor-modes > button:active { background-color: rgba(255,255,255,0.3); } div.jsoneditor-menu > button:disabled, div.jsoneditor-menu > div.jsoneditor-modes > button:disabled { opacity: 0.5; } div.jsoneditor-menu > button.jsoneditor-collapse-all { background-position: 0 -96px; } div.jsoneditor-menu > button.jsoneditor-expand-all { background-position: 0 -120px; } div.jsoneditor-menu > button.jsoneditor-sort { background-position: -120px -96px; } div.jsoneditor-menu > button.jsoneditor-transform { background-position: -144px -96px; } div.jsoneditor.jsoneditor-mode-view > div.jsoneditor-menu > button.jsoneditor-sort, div.jsoneditor.jsoneditor-mode-form > div.jsoneditor-menu > button.jsoneditor-sort, div.jsoneditor.jsoneditor-mode-view > div.jsoneditor-menu > button.jsoneditor-transform, div.jsoneditor.jsoneditor-mode-form > div.jsoneditor-menu > button.jsoneditor-transform { display: none; } div.jsoneditor-menu > button.jsoneditor-undo { background-position: -24px -96px; } div.jsoneditor-menu > button.jsoneditor-undo:disabled { background-position: -24px -120px; } div.jsoneditor-menu > button.jsoneditor-redo { background-position: -48px -96px; } div.jsoneditor-menu > button.jsoneditor-redo:disabled { background-position: -48px -120px; } div.jsoneditor-menu > button.jsoneditor-compact { background-position: -72px -96px; } div.jsoneditor-menu > button.jsoneditor-format { background-position: -72px -120px; } div.jsoneditor-menu > button.jsoneditor-repair { background-position: -96px -96px; } div.jsoneditor-menu > div.jsoneditor-modes { display: inline-block; float: left; } div.jsoneditor-menu > div.jsoneditor-modes > button { background-image: none; width: auto; padding-left: 6px; padding-right: 6px; } div.jsoneditor-menu > button.jsoneditor-separator, div.jsoneditor-menu > div.jsoneditor-modes > button.jsoneditor-separator { margin-left: 10px; } div.jsoneditor-menu a { font-family: arial, sans-serif; font-size: 10pt; color: white; opacity: 0.8; vertical-align: middle; } div.jsoneditor-menu a:hover { opacity: 1; } div.jsoneditor-menu a.jsoneditor-poweredBy { font-size: 8pt; position: absolute; right: 0; top: 0; padding: 10px; } table.jsoneditor-search input, table.jsoneditor-search div.jsoneditor-results { font-family: arial, sans-serif; font-size: 10pt; color: #1A1A1A; background: transparent; /* For Firefox */ } table.jsoneditor-search div.jsoneditor-results { color: white; padding-right: 5px; line-height: 24px; padding-top: 2px; } table.jsoneditor-search { position: absolute; right: 4px; top: 4px; border-collapse: collapse; border-spacing: 0; } table.jsoneditor-search div.jsoneditor-frame { border: 1px solid transparent; background-color: white; padding: 0 2px; margin: 0; } table.jsoneditor-search div.jsoneditor-frame table { border-collapse: collapse; } table.jsoneditor-search input { width: 120px; border: none; outline: none; margin: 1px; line-height: 20px; } table.jsoneditor-search button { width: 16px; height: 24px; padding: 0; margin: 0; border: none; background: url("img/jsoneditor-icons.svg"); vertical-align: top; } table.jsoneditor-search button:hover { background-color: transparent; } table.jsoneditor-search button.jsoneditor-refresh { width: 18px; background-position: -99px -73px; } table.jsoneditor-search button.jsoneditor-next { cursor: pointer; background-position: -124px -73px; } table.jsoneditor-search button.jsoneditor-next:hover { background-position: -124px -49px; } table.jsoneditor-search button.jsoneditor-previous { cursor: pointer; background-position: -148px -73px; margin-right: 2px; } table.jsoneditor-search button.jsoneditor-previous:hover { background-position: -148px -49px; } div.jsoneditor div.autocomplete.dropdown { position: absolute; background: white; box-shadow: 2px 2px 12px rgba(128, 128, 128, 0.3); border: 1px solid #d3d3d3; z-index: 100; overflow-x: hidden; overflow-y: auto; cursor: default; margin: 0; padding-left: 2pt; padding-right: 5pt; text-align: left; outline: 0; font-family: "dejavu sans mono", "droid sans mono", consolas, monaco, "lucida console", "courier new", courier, monospace, sans-serif; font-size: 10pt; } div.jsoneditor div.autocomplete.dropdown .item { color: #333; } div.jsoneditor div.autocomplete.dropdown .item.hover { background-color: #ddd; } div.jsoneditor div.autocomplete.hint { color: #aaa; top: 4px; left: 4px; } div.jsoneditor-treepath { padding: 0 5px; overflow: hidden; } div.jsoneditor-treepath div.jsoneditor-contextmenu-root { position: absolute; left: 0; } div.jsoneditor-treepath span.jsoneditor-treepath-element { margin: 1px; font-family: arial, sans-serif; font-size: 10pt; } div.jsoneditor-treepath span.jsoneditor-treepath-seperator { margin: 2px; font-size: 9pt; font-family: arial, sans-serif; } div.jsoneditor-treepath span.jsoneditor-treepath-element:hover, div.jsoneditor-treepath span.jsoneditor-treepath-seperator:hover { cursor: pointer; text-decoration: underline; } div.jsoneditor-statusbar { line-height: 26px; height: 26px; margin-top: -1px; color: #808080; background-color: #ebebeb; border-top: 1px solid #d3d3d3; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; font-size: 10pt; } div.jsoneditor-statusbar > .jsoneditor-curserinfo-label { margin: 0 2px 0 4px; } div.jsoneditor-statusbar > .jsoneditor-curserinfo-val { margin-right: 12px; } div.jsoneditor-statusbar > .jsoneditor-curserinfo-count { margin-left: 4px; } div.jsoneditor-statusbar > .jsoneditor-validation-error-icon { float: right; width: 24px; height: 24px; padding: 0; margin-top: 1px; background: url("img/jsoneditor-icons.svg") -168px -48px; } div.jsoneditor-statusbar > .jsoneditor-validation-error-count { float: right; margin: 0 4px 0 0; } div.jsoneditor-navigation-bar { width: 100%; height: 26px; line-height: 26px; padding: 0; margin: 0; border-bottom: 1px solid #d3d3d3; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; color: #808080; background-color: #ebebeb; overflow: hidden; font-family: arial, sans-serif; font-size: 10pt; } /*! * Selectr 2.4.0 * https://github.com/Mobius1/Selectr * * Released under the MIT license */ .selectr-container { position: relative; } .selectr-container li { list-style: none; } .selectr-hidden { position: absolute; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); width: 1px; height: 1px; margin: -1px; padding: 0; border: 0 none; } .selectr-visible { position: absolute; left: 0; top: 0; width: 100%; height: 100%; opacity: 0; z-index: 11; } .selectr-desktop.multiple .selectr-visible { display: none; } .selectr-desktop.multiple.native-open .selectr-visible { top: 100%; min-height: 200px !important; height: auto; opacity: 1; display: block; } .selectr-container.multiple.selectr-mobile .selectr-selected { z-index: 0; } .selectr-selected { position: relative; z-index: 1; box-sizing: border-box; width: 100%; padding: 7px 28px 7px 14px; cursor: pointer; border: 1px solid #999; border-radius: 3px; background-color: #fff; } .selectr-selected::before { position: absolute; top: 50%; right: 10px; width: 0; height: 0; content: ''; -o-transform: rotate(0deg) translate3d(0px, -50%, 0px); -ms-transform: rotate(0deg) translate3d(0px, -50%, 0px); -moz-transform: rotate(0deg) translate3d(0px, -50%, 0px); -webkit-transform: rotate(0deg) translate3d(0px, -50%, 0px); transform: rotate(0deg) translate3d(0px, -50%, 0px); border-width: 4px 4px 0 4px; border-style: solid; border-color: #6c7a86 transparent transparent; } .selectr-container.open .selectr-selected::before, .selectr-container.native-open .selectr-selected::before { border-width: 0 4px 4px 4px; border-style: solid; border-color: transparent transparent #6c7a86; } .selectr-label { display: none; overflow: hidden; width: 100%; white-space: nowrap; text-overflow: ellipsis; } .selectr-placeholder { color: #6c7a86; } .selectr-tags { margin: 0; padding: 0; white-space: normal; } .has-selected .selectr-tags { margin: 0 0 -2px; } .selectr-tag { list-style: none; position: relative; float: left; padding: 2px 25px 2px 8px; margin: 0 2px 2px 0; cursor: default; color: #fff; border: medium none; border-radius: 10px; background: #acb7bf none repeat scroll 0 0; } .selectr-container.multiple.has-selected .selectr-selected { padding: 5px 28px 5px 5px; } .selectr-options-container { position: absolute; z-index: 10000; top: calc(100% - 1px); left: 0; display: none; box-sizing: border-box; width: 100%; border-width: 0 1px 1px; border-style: solid; border-color: transparent #999 #999; border-radius: 0 0 3px 3px; background-color: #fff; } .selectr-container.open .selectr-options-container { display: block; } .selectr-input-container { position: relative; display: none; } .selectr-clear, .selectr-input-clear, .selectr-tag-remove { position: absolute; top: 50%; right: 22px; width: 20px; height: 20px; padding: 0; cursor: pointer; -o-transform: translate3d(0px, -50%, 0px); -ms-transform: translate3d(0px, -50%, 0px); -moz-transform: translate3d(0px, -50%, 0px); -webkit-transform: translate3d(0px, -50%, 0px); transform: translate3d(0px, -50%, 0px); border: medium none; background-color: transparent; z-index: 11; } .selectr-clear, .selectr-input-clear { display: none; } .selectr-container.has-selected .selectr-clear, .selectr-input-container.active .selectr-input-clear { display: block; } .selectr-selected .selectr-tag-remove { right: 2px; } .selectr-clear::before, .selectr-clear::after, .selectr-input-clear::before, .selectr-input-clear::after, .selectr-tag-remove::before, .selectr-tag-remove::after { position: absolute; top: 5px; left: 9px; width: 2px; height: 10px; content: ' '; background-color: #6c7a86; } .selectr-tag-remove::before, .selectr-tag-remove::after { top: 4px; width: 3px; height: 12px; background-color: #fff; } .selectr-clear:before, .selectr-input-clear::before, .selectr-tag-remove::before { -o-transform: rotate(45deg); -ms-transform: rotate(45deg); -moz-transform: rotate(45deg); -webkit-transform: rotate(45deg); transform: rotate(45deg); } .selectr-clear:after, .selectr-input-clear::after, .selectr-tag-remove::after { -o-transform: rotate(-45deg); -ms-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -webkit-transform: rotate(-45deg); transform: rotate(-45deg); } .selectr-input-container.active, .selectr-input-container.active .selectr-clear { display: block; } .selectr-input { top: 5px; left: 5px; box-sizing: border-box; width: calc(100% - 30px); margin: 10px 15px; padding: 7px 30px 7px 9px; border: 1px solid #999; border-radius: 3px; } .selectr-notice { display: none; box-sizing: border-box; width: 100%; padding: 8px 16px; border-top: 1px solid #999; border-radius: 0 0 3px 3px; background-color: #fff; } .selectr-container.notice .selectr-notice { display: block; } .selectr-container.notice .selectr-selected { border-radius: 3px 3px 0 0; } .selectr-options { position: relative; top: calc(100% + 2px); display: none; overflow-x: auto; overflow-y: scroll; max-height: 200px; margin: 0; padding: 0; } .selectr-container.open .selectr-options, .selectr-container.open .selectr-input-container, .selectr-container.notice .selectr-options-container { display: block; } .selectr-option { position: relative; display: block; padding: 5px 20px; list-style: outside none none; cursor: pointer; font-weight: normal; } .selectr-options.optgroups > .selectr-option { padding-left: 25px; } .selectr-optgroup { font-weight: bold; padding: 0; } .selectr-optgroup--label { font-weight: bold; margin-top: 10px; padding: 5px 15px; } .selectr-match { text-decoration: underline; } .selectr-option.selected { background-color: #ddd; } .selectr-option.active { color: #fff; background-color: #5897fb; } .selectr-option.disabled { opacity: 0.4; } .selectr-option.excluded { display: none; } .selectr-container.open .selectr-selected { border-color: #999 #999 transparent #999; border-radius: 3px 3px 0 0; } .selectr-container.open .selectr-selected::after { -o-transform: rotate(180deg) translate3d(0px, 50%, 0px); -ms-transform: rotate(180deg) translate3d(0px, 50%, 0px); -moz-transform: rotate(180deg) translate3d(0px, 50%, 0px); -webkit-transform: rotate(180deg) translate3d(0px, 50%, 0px); transform: rotate(180deg) translate3d(0px, 50%, 0px); } .selectr-disabled { opacity: .6; } .selectr-empty, .has-selected .selectr-placeholder { display: none; } .has-selected .selectr-label { display: block; } /* TAGGABLE */ .taggable .selectr-selected { padding: 4px 28px 4px 4px; } .taggable .selectr-selected::after { display: table; content: " "; clear: both; } .taggable .selectr-label { width: auto; } .taggable .selectr-tags { float: left; display: block; } .taggable .selectr-placeholder { display: none; } .input-tag { float: left; min-width: 90px; width: auto; } .selectr-tag-input { border: medium none; padding: 3px 10px; width: 100%; font-family: inherit; font-weight: inherit; font-size: inherit; } .selectr-input-container.loading::after { position: absolute; top: 50%; right: 20px; width: 20px; height: 20px; content: ''; -o-transform: translate3d(0px, -50%, 0px); -ms-transform: translate3d(0px, -50%, 0px); -moz-transform: translate3d(0px, -50%, 0px); -webkit-transform: translate3d(0px, -50%, 0px); transform: translate3d(0px, -50%, 0px); -o-transform-origin: 50% 0 0; -ms-transform-origin: 50% 0 0; -moz-transform-origin: 50% 0 0; -webkit-transform-origin: 50% 0 0; transform-origin: 50% 0 0; -moz-animation: 500ms linear 0s normal forwards infinite running spin; -webkit-animation: 500ms linear 0s normal forwards infinite running spin; animation: 500ms linear 0s normal forwards infinite running spin; border-width: 3px; border-style: solid; border-color: #aaa #ddd #ddd; border-radius: 50%; } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg) translate3d(0px, -50%, 0px); transform: rotate(0deg) translate3d(0px, -50%, 0px); } 100% { -webkit-transform: rotate(360deg) translate3d(0px, -50%, 0px); transform: rotate(360deg) translate3d(0px, -50%, 0px); } } @keyframes spin { 0% { -webkit-transform: rotate(0deg) translate3d(0px, -50%, 0px); transform: rotate(0deg) translate3d(0px, -50%, 0px); } 100% { -webkit-transform: rotate(360deg) translate3d(0px, -50%, 0px); transform: rotate(360deg) translate3d(0px, -50%, 0px); } } .selectr-container.open.inverted .selectr-selected { border-color: transparent #999 #999; border-radius: 0 0 3px 3px; } .selectr-container.inverted .selectr-options-container { border-width: 1px 1px 0; border-color: #999 #999 transparent; border-radius: 3px 3px 0 0; background-color: #fff; } .selectr-container.inverted .selectr-options-container { top: auto; bottom: calc(100% - 1px); } .selectr-container ::-webkit-input-placeholder { color: #6c7a86; opacity: 1; } .selectr-container ::-moz-placeholder { color: #6c7a86; opacity: 1; } .selectr-container :-ms-input-placeholder { color: #6c7a86; opacity: 1; } .selectr-container ::placeholder { color: #6c7a86; opacity: 1; }
extend1994/cdnjs
ajax/libs/jsoneditor/5.24.0/jsoneditor.css
CSS
mit
39,083
<?php /* SVN FILE: $Id$ */ /** * JavascriptHelperTest file * * Long description for file * * PHP versions 4 and 5 * * CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite> * Copyright 2006-2008, Cake Software Foundation, Inc. * * Licensed under The Open Group Test Suite License * Redistributions of files must retain the above copyright notice. * * @filesource * @copyright Copyright 2006-2008, Cake Software Foundation, Inc. * @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests * @package cake * @subpackage cake.tests.cases.libs.view.helpers * @since CakePHP(tm) v 1.2.0.4206 * @version $Revision$ * @modifiedby $LastChangedBy$ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ App::import('Core', array('Controller', 'View', 'ClassRegistry', 'View')); App::import('Helper', array('Javascript', 'Html', 'Form')); /** * TheJsTestController class * * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ class TheJsTestController extends Controller { /** * name property * * @var string 'TheTest' * @access public */ var $name = 'TheTest'; /** * uses property * * @var mixed null * @access public */ var $uses = null; } /** * TheView class * * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ class TheView extends View { /** * scripts method * * @access public * @return void */ function scripts() { return $this->__scripts; } } /** * TestJavascriptObject class * * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ class TestJavascriptObject { /** * property1 property * * @var string 'value1' * @access public */ var $property1 = 'value1'; /** * property2 property * * @var int 2 * @access public */ var $property2 = 2; } /** * JavascriptTest class * * @package test_suite * @subpackage test_suite.cases.libs * @since CakePHP Test Suite v 1.0.0.0 */ class JavascriptTest extends CakeTestCase { /** * Regexp for CDATA start block * * @var string */ var $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/'; /** * Regexp for CDATA end block * * @var string */ var $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/'; /** * setUp method * * @access public * @return void */ function startTest() { $this->Javascript =& new JavascriptHelper(); $this->Javascript->Html =& new HtmlHelper(); $this->Javascript->Form =& new FormHelper(); $this->View =& new TheView(new TheJsTestController()); ClassRegistry::addObject('view', $this->View); } /** * tearDown method * * @access public * @return void */ function endTest() { unset($this->Javascript->Html); unset($this->Javascript->Form); unset($this->Javascript); ClassRegistry::removeObject('view'); unset($this->View); } /** * testConstruct method * * @access public * @return void */ function testConstruct() { $Javascript =& new JavascriptHelper(array('safe')); $this->assertTrue($Javascript->safe); $Javascript =& new JavascriptHelper(array('safe' => false)); $this->assertFalse($Javascript->safe); } /** * testLink method * * @access public * @return void */ function testLink() { Configure::write('Asset.timestamp', false); $result = $this->Javascript->link('script.js'); $expected = '<script type="text/javascript" src="js/script.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('script'); $expected = '<script type="text/javascript" src="js/script.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('scriptaculous.js?load=effects'); $expected = '<script type="text/javascript" src="js/scriptaculous.js?load=effects"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('jquery-1.1.2'); $expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('jquery-1.1.2'); $expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('/plugin/js/jquery-1.1.2'); $expected = '<script type="text/javascript" src="/plugin/js/jquery-1.1.2.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('/some_other_path/myfile.1.2.2.min.js'); $expected = '<script type="text/javascript" src="/some_other_path/myfile.1.2.2.min.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('some_other_path/myfile.1.2.2.min.js'); $expected = '<script type="text/javascript" src="js/some_other_path/myfile.1.2.2.min.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('some_other_path/myfile.1.2.2.min'); $expected = '<script type="text/javascript" src="js/some_other_path/myfile.1.2.2.min.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link('http://example.com/jquery.js'); $expected = '<script type="text/javascript" src="http://example.com/jquery.js"></script>'; $this->assertEqual($result, $expected); $result = $this->Javascript->link(array('prototype.js', 'scriptaculous.js')); $this->assertPattern('/^\s*<script\s+type="text\/javascript"\s+src=".*js\/prototype\.js"[^<>]*><\/script>/', $result); $this->assertPattern('/<\/script>\s*<script[^<>]+>/', $result); $this->assertPattern('/<script\s+type="text\/javascript"\s+src=".*js\/scriptaculous\.js"[^<>]*><\/script>\s*$/', $result); $result = $this->Javascript->link('jquery-1.1.2', false); $resultScripts = $this->View->scripts(); reset($resultScripts); $expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>'; $this->assertNull($result); $this->assertEqual(count($resultScripts), 1); $this->assertEqual(current($resultScripts), $expected); } /** * testFilteringAndTimestamping method * * @access public * @return void */ function testFilteringAndTimestamping() { if (!is_writable(JS)) { echo "<br />JavaScript directory not writable, skipping JS asset timestamp tests<br />"; return; } cache(str_replace(WWW_ROOT, '', JS) . '__cake_js_test.js', 'alert("test")', '+999 days', 'public'); $timestamp = substr(strtotime('now'), 0, 8); Configure::write('Asset.timestamp', true); $result = $this->Javascript->link('__cake_js_test'); $this->assertPattern('/^<script[^<>]+src=".*js\/__cake_js_test\.js\?' . $timestamp . '[0-9]{2}"[^<>]*>/', $result); $debug = Configure::read('debug'); Configure::write('debug', 0); $result = $this->Javascript->link('__cake_js_test'); $expected = '<script type="text/javascript" src="js/__cake_js_test.js"></script>'; $this->assertEqual($result, $expected); Configure::write('Asset.timestamp', 'force'); $result = $this->Javascript->link('__cake_js_test'); $this->assertPattern('/^<script[^<>]+src=".*js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"[^<>]*>/', $result); Configure::write('debug', $debug); Configure::write('Asset.timestamp', false); $old = Configure::read('Asset.filter.js'); Configure::write('Asset.filter.js', 'js.php'); $result = $this->Javascript->link('__cake_js_test'); $this->assertPattern('/^<script[^<>]+src=".*cjs\/__cake_js_test\.js"[^<>]*>/', $result); Configure::write('Asset.filter.js', true); $result = $this->Javascript->link('jquery-1.1.2'); $expected = '<script type="text/javascript" src="cjs/jquery-1.1.2.js"></script>'; $this->assertEqual($result, $expected); if ($old === null) { Configure::delete('Asset.filter.js'); } $debug = Configure::read('debug'); $webroot = $this->Javascript->webroot; Configure::write('debug', 0); Configure::write('Asset.timestamp', 'force'); $this->Javascript->webroot = '/testing/'; $result = $this->Javascript->link('__cake_js_test'); $this->assertPattern('/^<script[^<>]+src="\/testing\/js\/__cake_js_test\.js\?"[^<>]*>/', $result); $this->Javascript->webroot = '/testing/longer/'; $result = $this->Javascript->link('__cake_js_test'); $this->assertPattern('/^<script[^<>]+src="\/testing\/longer\/js\/__cake_js_test\.js\?"[^<>]*>/', $result); $this->Javascript->webroot = $webroot; Configure::write('debug', $debug); unlink(JS . '__cake_js_test.js'); } /** * testValue method * * @access public * @return void */ function testValue() { $result = $this->Javascript->value(array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8))); $expected = '{"title":"New thing","indexes":[5,6,7,8]}'; $this->assertEqual($result, $expected); $result = $this->Javascript->value(null); $this->assertEqual($result, 'null'); $result = $this->Javascript->value(true); $this->assertEqual($result, 'true'); $result = $this->Javascript->value(false); $this->assertEqual($result, 'false'); $result = $this->Javascript->value(5); $this->assertEqual($result, '5'); $result = $this->Javascript->value(floatval(5.3)); $this->assertPattern('/^5.3[0]+$/', $result); $result = $this->Javascript->value(''); $expected = '""'; $this->assertEqual($result, $expected); $result = $this->Javascript->value('CakePHP' . "\n" . 'Rapid Development Framework'); $expected = '"CakePHP\\nRapid Development Framework"'; $this->assertEqual($result, $expected); $result = $this->Javascript->value('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP'); $expected = '"CakePHP\\nRapid Development Framework\\nFor PHP"'; $this->assertEqual($result, $expected); $result = $this->Javascript->value('CakePHP: "Rapid Development Framework"'); $expected = '"CakePHP: \\"Rapid Development Framework\\""'; $this->assertEqual($result, $expected); $result = $this->Javascript->value('CakePHP: \'Rapid Development Framework\''); $expected = '"CakePHP: \\\'Rapid Development Framework\\\'"'; $this->assertEqual($result, $expected); } /** * testObjectGeneration method * * @access public * @return void */ function testObjectGeneration() { $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8)); $result = $this->Javascript->object($object); $expected = '{"title":"New thing","indexes":[5,6,7,8]}'; $this->assertEqual($result, $expected); $result = $this->Javascript->object(array('default' => 0)); $expected = '{"default":0}'; $this->assertEqual($result, $expected); $result = $this->Javascript->object(array( '2007' => array( 'Spring' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')), 'Fall' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')) ), '2006' => array( 'Spring' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')), 'Fall' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky') )) )); $expected = '{"2007":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}},"2006":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}}}'; $this->assertEqual($result, $expected); if (ini_get('precision') >= 12) { $number = 3.141592653589; if (!$this->Javascript->useNative) { $number = sprintf("%.11f", $number); } $result = $this->Javascript->object(array('Object' => array(true, false, 1, '02101', 0, -1, 3.141592653589, "1"))); $expected = '{"Object":[true,false,1,"02101",0,-1,' . $number . ',"1"]}'; $this->assertEqual($result, $expected); $result = $this->Javascript->object(array('Object' => array(true => true, false, -3.141592653589, -10))); $expected = '{"Object":{"1":true,"2":false,"3":' . (-1 * $number) . ',"4":-10}}'; $this->assertEqual($result, $expected); } $result = $this->Javascript->object(new TestJavascriptObject()); $expected = '{"property1":"value1","property2":2}'; $this->assertEqual($result, $expected); $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8)); $result = $this->Javascript->object($object, array('block' => true)); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, '{"title":"New thing","indexes":[5,6,7,8]}', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1))); $result = $this->Javascript->object($object); $expected = '{"title":"New thing","indexes":[5,6,7,8],"object":{"inner":{"value":1}}}'; $this->assertEqual($result, $expected); foreach (array('true' => true, 'false' => false, 'null' => null) as $expected => $data) { $result = $this->Javascript->object($data); $this->assertEqual($result, $expected); } if ($this->Javascript->useNative) { $this->Javascript->useNative = false; $this->testObjectGeneration(); $this->Javascript->useNative = true; } } /** * testObjectNonNative method * * @access public * @return void */ function testObjectNonNative() { $oldNative = $this->Javascript->useNative; $this->Javascript->useNative = false; $object = array( 'Object' => array( 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ) ); $expected = '{"Object":{"key1":val1,"key2":"val2","key3":val3}}'; $result = $this->Javascript->object($object, array('quoteKeys' => false, 'stringKeys' => array('key1', 'key3'))); $this->assertEqual($result, $expected); $this->Javascript->useNative = $oldNative; } /** * testScriptBlock method * * @access public * @return void */ function testScriptBlock() { $result = $this->Javascript->codeBlock('something'); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, 'something', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', array('allowCache' => true, 'safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), 'something', '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', array('allowCache' => false, 'safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), 'something', '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', true); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, 'something', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', false); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, 'something', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', array('safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), 'something', '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock('something', array('safe' => true)); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, 'something', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock(null, array('safe' => true, 'allowCache' => false)); $this->assertNull($result); echo 'this is some javascript'; $result = $this->Javascript->blockEnd(); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, 'this is some javascript', $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->codeBlock(); $this->assertNull($result); echo "alert('hey');"; $result = $this->Javascript->blockEnd(); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "alert('hey');", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $this->Javascript->cacheEvents(false, true); $this->assertFalse($this->Javascript->inBlock); $result = $this->Javascript->codeBlock(); $this->assertIdentical($result, null); $this->assertTrue($this->Javascript->inBlock); echo 'alert("this is a buffered script");'; $result = $this->Javascript->blockEnd(); $this->assertIdentical($result, null); $this->assertFalse($this->Javascript->inBlock); $result = $this->Javascript->getCache(); $this->assertEqual('alert("this is a buffered script");', $result); } /** * testOutOfLineScriptWriting method * * @access public * @return void */ function testOutOfLineScriptWriting() { echo $this->Javascript->codeBlock('$(document).ready(function() { });', array('inline' => false)); $this->Javascript->codeBlock(null, array('inline' => false)); echo '$(function(){ });'; $this->Javascript->blockEnd(); $script = $this->View->scripts(); $this->assertEqual(count($script), 2); $this->assertPattern('/' . preg_quote('$(document).ready(function() { });', '/') . '/', $script[0]); $this->assertPattern('/' . preg_quote('$(function(){ });', '/') . '/', $script[1]); } /** * testEvent method * * @access public * @return void */ function testEvent() { $result = $this->Javascript->event('myId', 'click', 'something();'); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('myId', 'click', 'something();', array('safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), "Event.observe($('myId'), 'click', function(event) { something(); }, false);", '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('myId', 'click'); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('myId', 'click', 'something();', false); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('myId', 'click', 'something();', array('useCapture' => true)); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, true);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('document', 'load'); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe(document, 'load', function(event) { }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('$(\'myId\')', 'click', 'something();', array('safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), "Event.observe($('myId'), 'click', function(event) { something(); }, false);", '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->event('\'document\'', 'load', 'something();', array('safe' => false)); $expected = array( 'script' => array('type' => 'text/javascript'), "Event.observe('document', 'load', function(event) { something(); }, false);", '/script' ); $this->assertTags($result, $expected); $this->Javascript->cacheEvents(); $result = $this->Javascript->event('myId', 'click', 'something();'); $this->assertNull($result); $result = $this->Javascript->getCache(); $this->assertPattern('/^' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '$/s', $result); $result = $this->Javascript->event('#myId', 'alert(event);'); $this->assertNull($result); $result = $this->Javascript->getCache(); $this->assertPattern('/^\s*var Rules = {\s*\'#myId\': function\(element, event\)\s*{\s*alert\(event\);\s*}\s*}\s*EventSelectors\.start\(Rules\);\s*$/s', $result); } /** * testWriteEvents method * * @access public * @return void */ function testWriteEvents() { $this->Javascript->cacheEvents(); $result = $this->Javascript->event('myId', 'click', 'something();'); $this->assertNull($result); $result = $this->Javascript->writeEvents(); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->getCache(); $this->assertTrue(empty($result)); $this->Javascript->cacheEvents(); $result = $this->Javascript->event('myId', 'click', 'something();'); $this->assertNull($result); $result = $this->Javascript->writeEvents(false); $resultScripts = $this->View->scripts(); reset($resultScripts); $this->assertNull($result); $this->assertEqual(count($resultScripts), 1); $result = current($resultScripts); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->getCache(); $this->assertTrue(empty($result)); } /** * testEscapeScript method * * @access public * @return void */ function testEscapeScript() { $result = $this->Javascript->escapeScript(''); $expected = ''; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeScript('CakePHP' . "\n" . 'Rapid Development Framework'); $expected = 'CakePHP\\nRapid Development Framework'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeScript('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP'); $expected = 'CakePHP\\nRapid Development Framework\\nFor PHP'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeScript('CakePHP: "Rapid Development Framework"'); $expected = 'CakePHP: \\"Rapid Development Framework\\"'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeScript('CakePHP: \'Rapid Development Framework\''); $expected = 'CakePHP: \\\'Rapid Development Framework\\\''; $this->assertEqual($result, $expected); } /** * testEscapeString method * * @access public * @return void */ function testEscapeString() { $result = $this->Javascript->escapeString(''); $expected = ''; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('CakePHP' . "\n" . 'Rapid Development Framework'); $expected = 'CakePHP\\nRapid Development Framework'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP'); $expected = 'CakePHP\\nRapid Development Framework\\nFor PHP'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('CakePHP: "Rapid Development Framework"'); $expected = 'CakePHP: \\"Rapid Development Framework\\"'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('CakePHP: \'Rapid Development Framework\''); $expected = "CakePHP: \\'Rapid Development Framework\\'"; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('my \\"string\\"'); $expected = 'my \\\\\\"string\\\\\\"'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('my string\nanother line'); $expected = 'my string\\\nanother line'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('String with \n string that looks like newline'); $expected = 'String with \\\n string that looks like newline'; $this->assertEqual($result, $expected); $result = $this->Javascript->escapeString('String with \n string that looks like newline'); $expected = 'String with \\\n string that looks like newline'; $this->assertEqual($result, $expected); } /** * test string escaping and compare to json_encode() * * @return void **/ function testStringJsonEncodeCompliance() { if (!function_exists('json_encode')) { return; } $this->Javascript->useNative = false; $data = array(); $data['mystring'] = "simple string"; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); $data['mystring'] = "strïng with spécial chârs"; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); $data['mystring'] = "a two lines\nstring"; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); $data['mystring'] = "a \t tabbed \t string"; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); $data['mystring'] = "a \"double-quoted\" string"; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); $data['mystring'] = 'a \\"double-quoted\\" string'; $this->assertEqual(json_encode($data), $this->Javascript->object($data)); } /** * test that text encoded with Javascript::object decodes properly * * @return void **/ function testObjectDecodeCompatibility() { if (!function_exists('json_decode')) { return; } $this->Javascript->useNative = false; $data = array("simple string"); $result = $this->Javascript->object($data); $this->assertEqual(json_decode($result), $data); $data = array('my \"string\"'); $result = $this->Javascript->object($data); $this->assertEqual(json_decode($result), $data); $data = array('my \\"string\\"'); $result = $this->Javascript->object($data); $this->assertEqual(json_decode($result), $data); } /** * testAfterRender method * * @access public * @return void */ function testAfterRender() { $this->Javascript->cacheEvents(); $result = $this->Javascript->event('myId', 'click', 'something();'); $this->assertNull($result); ob_start(); $this->Javascript->afterRender(); $result = ob_get_clean(); $expected = array( 'script' => array('type' => 'text/javascript'), $this->cDataStart, "Event.observe($('myId'), 'click', function(event) { something(); }, false);", $this->cDataEnd, '/script' ); $this->assertTags($result, $expected); $result = $this->Javascript->getCache(); $this->assertTrue(empty($result)); $old = $this->Javascript->enabled; $this->Javascript->enabled = false; $this->Javascript->cacheEvents(); $result = $this->Javascript->event('myId', 'click', 'something();'); $this->assertNull($result); ob_start(); $this->Javascript->afterRender(); $result = ob_get_clean(); $this->assertTrue(empty($result)); $result = $this->Javascript->getCache(); $this->assertPattern('/^' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '$/s', $result); $this->Javascript->enabled = $old; } } ?>
kamil-bluechip/cake-1.2.5
tests/cases/libs/view/helpers/javascript.test.php
PHP
mit
27,847
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.HealthcareApis { using Microsoft.Rest.Azure; using Models; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// PrivateLinkResourcesOperations operations. /// </summary> public partial interface IPrivateLinkResourcesOperations { /// <summary> /// Gets the private link resources that need to be created for a /// service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the service instance. /// </param> /// <param name='resourceName'> /// The name of the service instance. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorDetailsException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PrivateLinkResourceListResult>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a private link resource that need to be created for a service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the service instance. /// </param> /// <param name='resourceName'> /// The name of the service instance. /// </param> /// <param name='groupName'> /// The name of the private link resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorDetailsException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PrivateLinkResource>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, string groupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
jackmagic313/azure-sdk-for-net
sdk/healthcareapis/Microsoft.Azure.Management.HealthcareApis/src/Generated/IPrivateLinkResourcesOperations.cs
C#
mit
3,475
<?php namespace Backend\Modules\FormBuilder\Actions; use Backend\Core\Engine\Base\Action as BackendBaseAction; use Backend\Core\Language\Language as BL; use Backend\Core\Engine\Model as BackendModel; use Backend\Core\Engine\Csv as BackendCSV; use Backend\Modules\FormBuilder\Engine\Model as BackendFormBuilderModel; /** * This action is used to export submissions of a form. */ class ExportData extends BackendBaseAction { /** * CSV column headers. * * @var array */ private $columnHeaders = []; /** * The filter. * * @var array */ private $filter; /** * Form id. * * @var int */ private $id; /** * CSV rows. * * @var array */ private $rows = []; /** * Builds the query for this datagrid. * * @return array An array with two arguments containing the query and its parameters. */ private function buildQuery(): array { // init var $parameters = [$this->id]; /* * Start query, as you can see this query is build in the wrong place, because of the filter * it is a special case wherein we allow the query to be in the actionfile itself */ $query = 'SELECT i.*, UNIX_TIMESTAMP(i.sent_on) AS sent_on, d.* FROM forms_data AS i INNER JOIN forms_data_fields AS d ON i.id = d.data_id WHERE i.form_id = ?'; // add start date if ($this->filter['start_date'] !== '') { // explode date parts $chunks = explode('/', $this->filter['start_date']); // add condition $query .= ' AND i.sent_on >= ?'; $parameters[] = BackendModel::getUTCDate(null, gmmktime(23, 59, 59, $chunks[1], $chunks[0], $chunks[2])); } // add end date if ($this->filter['end_date'] !== '') { // explode date parts $chunks = explode('/', $this->filter['end_date']); // add condition $query .= ' AND i.sent_on <= ?'; $parameters[] = BackendModel::getUTCDate(null, gmmktime(23, 59, 59, $chunks[1], $chunks[0], $chunks[2])); } return [$query, $parameters]; } public function execute(): void { $this->id = $this->getRequest()->query->getInt('id'); // does the item exist if ($this->id !== 0 && BackendFormBuilderModel::exists($this->id)) { parent::execute(); $this->setFilter(); $this->setItems(); BackendCSV::outputCSV(date('Ymd_His') . '.csv', $this->rows, $this->columnHeaders); } else { // no item found, redirect to index, because somebody is fucking with our url $this->redirect(BackendModel::createUrlForAction('Index') . '&error=non-existing'); } } /** * Sets the filter based on the $_GET array. */ private function setFilter(): void { // start date is set if ($this->getRequest()->query->has('start_date') && $this->getRequest()->query->get('start_date', '') !== '') { // redefine $startDate = $this->getRequest()->query->get('start_date', ''); // explode date parts $chunks = explode('/', $startDate); // valid date if (count($chunks) == 3 && checkdate((int) $chunks[1], (int) $chunks[0], (int) $chunks[2])) { $this->filter['start_date'] = $startDate; } else { // invalid date $this->filter['start_date'] = ''; } } else { // not set $this->filter['start_date'] = ''; } // end date is set if ($this->getRequest()->query->has('end_date') && $this->getRequest()->query->get('end_date', '') !== '') { // redefine $endDate = $this->getRequest()->query->get('end_date', ''); // explode date parts $chunks = explode('/', $endDate); // valid date if (count($chunks) == 3 && checkdate((int) $chunks[1], (int) $chunks[0], (int) $chunks[2])) { $this->filter['end_date'] = $endDate; } else { // invalid date $this->filter['end_date'] = ''; } } else { // not set $this->filter['end_date'] = ''; } } /** * Fetch data for this form from the database and reformat to csv rows. */ private function setItems(): void { // init header labels $lblSessionId = \SpoonFilter::ucfirst(BL::lbl('SessionId')); $lblSentOn = \SpoonFilter::ucfirst(BL::lbl('SentOn')); $this->columnHeaders = [$lblSessionId, $lblSentOn]; // fetch query and parameters list($query, $parameters) = $this->buildQuery(); // get the data $records = (array) $this->get('database')->getRecords($query, $parameters); $data = []; // reformat data foreach ($records as $row) { // first row of a submission if (!isset($data[$row['data_id']])) { $data[$row['data_id']][$lblSessionId] = $row['session_id']; $data[$row['data_id']][$lblSentOn] = \SpoonDate::getDate( 'Y-m-d H:i:s', $row['sent_on'], BL::getWorkingLanguage() ); } // value is serialized $value = unserialize($row['value']); // flatten arrays if (is_array($value)) { $value = implode(', ', $value); } // group submissions $data[$row['data_id']][$row['label']] = \SpoonFilter::htmlentitiesDecode($value, null, ENT_QUOTES); // add into headers if not yet added if (!in_array($row['label'], $this->columnHeaders)) { $this->columnHeaders[] = $row['label']; } } // reorder data so they are in the correct column foreach ($data as $id => $row) { foreach ($this->columnHeaders as $header) { // submission has this field so add it if (isset($row[$header])) { $this->rows[$id][] = $row[$header]; } else { // submission does not have this field so add a placeholder $this->rows[$id][] = ''; } } } // remove the keys $this->rows = array_values($this->rows); } }
mathiashelin/forkcms
src/Backend/Modules/FormBuilder/Actions/ExportData.php
PHP
mit
6,635
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using NadekoBot.Modules.Administration.Common; using NadekoBot.Services; using NadekoBot.Services.Database.Models; using NLog; namespace NadekoBot.Modules.Administration.Services { public class ProtectionService : INService { public readonly ConcurrentDictionary<ulong, AntiRaidStats> AntiRaidGuilds = new ConcurrentDictionary<ulong, AntiRaidStats>(); // guildId | (userId|messages) public readonly ConcurrentDictionary<ulong, AntiSpamStats> AntiSpamGuilds = new ConcurrentDictionary<ulong, AntiSpamStats>(); public event Func<PunishmentAction, ProtectionType, IGuildUser[], Task> OnAntiProtectionTriggered = delegate { return Task.CompletedTask; }; private readonly Logger _log; private readonly DiscordSocketClient _client; private readonly MuteService _mute; public ProtectionService(DiscordSocketClient client, IEnumerable<GuildConfig> gcs, MuteService mute) { _log = LogManager.GetCurrentClassLogger(); _client = client; _mute = mute; foreach (var gc in gcs) { var raid = gc.AntiRaidSetting; var spam = gc.AntiSpamSetting; if (raid != null) { var raidStats = new AntiRaidStats() { AntiRaidSettings = raid }; AntiRaidGuilds.TryAdd(gc.GuildId, raidStats); } if (spam != null) AntiSpamGuilds.TryAdd(gc.GuildId, new AntiSpamStats() { AntiSpamSettings = spam }); } _client.MessageReceived += (imsg) => { var msg = imsg as IUserMessage; if (msg == null || msg.Author.IsBot) return Task.CompletedTask; var channel = msg.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; var _ = Task.Run(async () => { try { if (!AntiSpamGuilds.TryGetValue(channel.Guild.Id, out var spamSettings) || spamSettings.AntiSpamSettings.IgnoredChannels.Contains(new AntiSpamIgnore() { ChannelId = channel.Id })) return; var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, (id) => new UserSpamStats(msg), (id, old) => { old.ApplyNextMessage(msg); return old; }); if (stats.Count >= spamSettings.AntiSpamSettings.MessageThreshold) { if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats)) { stats.Dispose(); await PunishUsers(spamSettings.AntiSpamSettings.Action, ProtectionType.Spamming, spamSettings.AntiSpamSettings.MuteTime, (IGuildUser)msg.Author) .ConfigureAwait(false); } } } catch { // ignored } }); return Task.CompletedTask; }; _client.UserJoined += (usr) => { if (usr.IsBot) return Task.CompletedTask; if (!AntiRaidGuilds.TryGetValue(usr.Guild.Id, out var settings)) return Task.CompletedTask; if (!settings.RaidUsers.Add(usr)) return Task.CompletedTask; var _ = Task.Run(async () => { try { ++settings.UsersCount; if (settings.UsersCount >= settings.AntiRaidSettings.UserThreshold) { var users = settings.RaidUsers.ToArray(); settings.RaidUsers.Clear(); await PunishUsers(settings.AntiRaidSettings.Action, ProtectionType.Raiding, 0, users).ConfigureAwait(false); } await Task.Delay(1000 * settings.AntiRaidSettings.Seconds).ConfigureAwait(false); settings.RaidUsers.TryRemove(usr); --settings.UsersCount; } catch { // ignored } }); return Task.CompletedTask; }; } private async Task PunishUsers(PunishmentAction action, ProtectionType pt, int muteTime, params IGuildUser[] gus) { _log.Info($"[{pt}] - Punishing [{gus.Length}] users with [{action}] in {gus[0].Guild.Name} guild"); foreach (var gu in gus) { switch (action) { case PunishmentAction.Mute: try { if (muteTime <= 0) await _mute.MuteUser(gu).ConfigureAwait(false); else await _mute.TimedMute(gu, TimeSpan.FromSeconds(muteTime)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex, "I can't apply punishement"); } break; case PunishmentAction.Kick: try { await gu.KickAsync().ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex, "I can't apply punishement"); } break; case PunishmentAction.Softban: try { await gu.Guild.AddBanAsync(gu, 7).ConfigureAwait(false); try { await gu.Guild.RemoveBanAsync(gu).ConfigureAwait(false); } catch { await gu.Guild.RemoveBanAsync(gu).ConfigureAwait(false); // try it twice, really don't want to ban user if // only kick has been specified as the punishement } } catch (Exception ex) { _log.Warn(ex, "I can't apply punishment"); } break; case PunishmentAction.Ban: try { await gu.Guild.AddBanAsync(gu, 7).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex, "I can't apply punishment"); } break; } } await OnAntiProtectionTriggered(action, pt, gus).ConfigureAwait(false); } } }
Blacnova/NadekoBot
src/NadekoBot/Modules/Administration/Services/ProtectionService.cs
C#
mit
7,587
'''Package for Banded Min Hash based Similarity Calculations''' from min_hash import *
ClickSecurity/data_hacking
data_hacking/min_hash/__init__.py
Python
mit
87
/** * A promise-based Q-JSGI server and client API. * @module */ /*whatsupdoc*/ var HTTP = require("http"); // node var HTTPS = require("https"); // node var URL = require("url2"); // node var Q = require("q"); var Reader = require("./reader"); /** * @param {respond(request Request)} respond a JSGI responder function that * receives a Request object as its argument. The JSGI responder promises to * return an object of the form `{status, headers, body}`. The status and * headers must be fully resolved, but the body may be a promise for an object * with a `forEach(write(chunk String))` method, albeit an array of strings. * The `forEach` method may promise to resolve when all chunks have been * written. * @returns a Node Server object. */ exports.Server = function (respond) { var self = Object.create(exports.Server.prototype); var server = HTTP.createServer(function (_request, _response) { var request = exports.ServerRequest(_request); var response = exports.ServerResponse(_response); var closed = Q.defer(); _request.on("end", function (error, value) { if (error) { closed.reject(error); } else { closed.resolve(value); } }); Q.when(request, function (request) { return Q.when(respond(request, response), function (response) { if (!response) return; _response.writeHead(response.status, response.headers); if (response.onclose || response.onClose) Q.when(closed, response.onclose || response.onClose); return Q.when(response.body, function (body) { var length; if ( Array.isArray(body) && (length = body.length) && body.every(function (chunk) { return typeof chunk === "string" }) ) { body.forEach(function (chunk, i) { if (i < length - 1) { _response.write(chunk, response.charset); } else { _response.end(chunk, response.charset); } }); } else if (body) { var end; var done = body.forEach(function (chunk) { end = Q.when(end, function () { return Q.when(chunk, function (chunk) { _response.write(chunk, response.charset); }); }); }); return Q.when(done, function () { return Q.when(end, function () { _response.end(); }); }); } else { _response.end(); } }); }) }) .done(); // should be .fail(self.emitter("error")) }); var stopped = Q.defer(); server.on("close", function (err) { if (err) { stopped.reject(err); } else { stopped.resolve(); } }); /*** * Stops the server. * @returns {Promise * Undefined} a promise that will * resolve when the server is stopped. */ self.stop = function () { server.close(); listening = undefined; return stopped.promise; }; var listening = Q.defer(); server.on("listening", function (err) { if (err) { listening.reject(err); } else { listening.resolve(self); } }); /*** * Starts the server, listening on the given port * @param {Number} port * @returns {Promise * Undefined} a promise that will * resolve when the server is ready to receive * connections */ self.listen = function (/*...args*/) { if (typeof server.port !== "undefined") return Q.reject(new Error("A server cannot be restarted or " + "started on a new port")); server.listen.apply(server, arguments); return listening.promise; }; self.stopped = stopped.promise; self.node = server; self.nodeServer = server; // Deprecated self.address = server.address.bind(server); return self; }; Object.defineProperties(exports.Server, { port: { get: function () { return this.node.port; } }, host: { get: function () { return this.node.host; } } }); /** * A wrapper for a Node HTTP Request, as received by * the Q HTTP Server, suitable for use by the Q HTTP Client. */ exports.ServerRequest = function (_request, ssl) { var request = Object.create(_request); /*** {Array} HTTP version. (JSGI) */ request.version = _request.httpVersion.split(".").map(Math.floor); /*** {String} HTTP method, e.g., `"GET"` (JSGI) */ request.method = _request.method; /*** {String} path, starting with `"/"` */ request.path = _request.url; /*** {String} pathInfo, starting with `"/"`, the * portion of the path that has not yet * been routed (JSGI) */ request.pathInfo = URL.parse(_request.url).pathname; /*** {String} scriptName, the portion of the path that * has already been routed (JSGI) */ request.scriptName = ""; /*** {String} (JSGI) */ request.scheme = "http"; var address = _request.connection.address(); /*** {String} hostname */ if (_request.headers.host) { request.hostname = _request.headers.host.split(":")[0]; } else { request.hostname = address.address; } /*** {String} host */ request.host = request.hostname + ":" + address.port; request.port = address.port; var socket = _request.socket; /*** {String} */ request.remoteHost = socket.remoteAddress; /*** {Number} */ request.remotePort = socket.remotePort; /*** {String} url */ request.url = URL.format({ protocol: request.scheme, host: _request.headers.host, port: request.port === (ssl ? 443 : 80) ? null : request.port, path: request.path }); /*** A Q IO asynchronous text reader */ request.body = Reader(_request); /*** {Object} HTTP headers (JSGI)*/ request.headers = _request.headers; /*** The underlying Node request */ request.node = _request; request.nodeRequest = _request; // Deprecated /*** The underlying Node TCP connection */ request.nodeConnection = _request.connection; return Q.when(request.body, function (body) { request.body = body; return request; }); }; exports.ServerResponse = function (_response, ssl) { var response = Object.create(_response); response.ssl = ssl; response.node = _response; response.nodeResponse = _response; // Deprecated return response; }; exports.normalizeRequest = function (request) { if (typeof request === "string") { request = { url: request }; } if (request.url) { var url = URL.parse(request.url); request.host = url.hostname; request.port = url.port; request.ssl = url.protocol === "https:"; request.method = request.method || "GET"; request.path = (url.pathname || "") + (url.search || ""); request.headers = request.headers || {}; request.headers.host = url.hostname; // FIXME name consistency } return request; }; exports.normalizeResponse = function (response) { if (response === void 0) { return; } if (typeof response == "string") { response = [response]; } if (response.forEach) { response = { status: 200, headers: {}, body: response } } return response; }; /** * Issues an HTTP request. * * @param {Request {host, port, method, path, headers, * body}} request (may be a promise) * @returns {Promise * Response} promise for a response */ exports.request = function (request) { return Q.when(request, function (request) { request = exports.normalizeRequest(request); var deferred = Q.defer(); var ssl = request.ssl; var http = ssl ? HTTPS : HTTP; var headers = request.headers || {}; headers.host = headers.host || request.host; var _request = http.request({ "host": request.host, "port": request.port || (ssl ? 443 : 80), "path": request.path || "/", "method": request.method || "GET", "headers": headers, "agent": request.agent }, function (_response) { deferred.resolve(exports.ClientResponse(_response, request.charset)); _response.on("error", function (error) { // TODO find a better way to channel // this into the response console.warn(error && error.stack || error); deferred.reject(error); }); }); _request.on("error", function (error) { deferred.reject(error); }); Q.when(request.body, function (body) { var end, done; if (body) { done = body.forEach(function (chunk) { end = Q.when(end, function () { return Q.when(chunk, function (chunk) { _request.write(chunk, request.charset); }); }); }); } return Q.when(end, function () { return Q.when(done, function () { _request.end(); }); }); }).done(); return deferred.promise; }); }; /** * Issues a GET request to the given URL and returns * a promise for a `String` containing the entirety * of the response. * * @param {String} url * @returns {Promise * String} or a rejection if the * status code is not exactly 200. The reason for the * rejection is the full response object. */ exports.read = function (request, qualifier) { qualifier = qualifier || function (response) { return response.status === 200; }; return Q.when(exports.request(request), function (response) { if (!qualifier(response)){ var error = new Error("HTTP request failed with code " + response.status); error.response = response; throw error; } return Q.post(response.body, 'read', []); }); }; /** * A wrapper for the Node HTTP Response as provided * by the Q HTTP Client API, suitable for use by the * Q HTTP Server API. */ exports.ClientResponse = function (_response, charset) { var response = Object.create(exports.ClientResponse.prototype); /*** {Number} HTTP status code */ response.status = _response.statusCode; /*** HTTP version */ response.version = _response.httpVersion; /*** {Object} HTTP headers */ response.headers = _response.headers; /*** * A Q IO asynchronous text reader. */ response.node = _response; response.nodeResponse = _response; // Deprecated response.nodeConnection = _response.connection; // Deprecated return Q.when(Reader(_response, charset), function (body) { response.body = body; return response; }); };
uistyleguide/uistyleguide.github.io
node_modules/dgeni-packages/node_modules/q-io/http.js
JavaScript
mit
11,726
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. require 'uuidtools' module AWS class SimpleWorkflow # ## Registering a WorkflowType # # To register a workflow type you should use the #workflow_types method # on the domain: # # domain.workflow_types.register('name', 'version', { ... }) # # See {WorkflowTypeCollection#register} for a complete list of options. # # ## Deprecating a workflow type # # WorkflowType inherits from the generic {Type} base class. Defined in # {Type} are a few useful methods including: # # * {Type#deprecate} # * {Type#deprecated?} # # You can use these to deprecate a workflow type: # # domain.workflow_types['name','version'].deprecate # # @attr_reader [Time] creation_date When the workflow type was registered. # # @attr_reader [Time,nil] deprecation_date When the workflow type # was deprecated, or nil if the workflow type has not been deprecated. # # @attr_reader [String,nil] description The description of this workflow # type, or nil if was not set when it was registered. # # @attr_reader [Symbol] status The status of this workflow type. The # status will either be `:registered` or `:deprecated`. # # @attr_reader [Symbol,nil] default_child_policy Specifies the default # policy to use for the child workflow executions when a workflow # execution of this type is terminated. Values may be one of the # following (or nil): # # * `:terminate` - the child executions will be terminated. # # * `:request_cancel` - a request to cancel will be attempted for each # child execution by recording a WorkflowExecutionCancelRequested # event in its history. It is up to the decider to take appropriate # actions when it receives an execution history with this event. # # * `:abandon` - no action will be taken. The child executions will # continue to run. # # @attr_reader [Integer,:none,nil] default_execution_start_to_close_timeout # The default maximum duration for executions of this workflow type. # # The return value may be an integer (number of seconds), the # symbol `:none` (implying no timeout) or `nil` (not specified). # # @attr_reader [String,nil] default_task_list Specifies # the default task list to use for scheduling decision tasks for # executions of this workflow type. # # @attr_reader [Integer,:none,nil] default_task_start_to_close_timeout # The default maximum duration of decision tasks for this workflow type. # # The return value may be an integer (number of seconds), the # symbol `:none` (implying no timeout) or `nil` (not specified). # class WorkflowType < Type include OptionFormatters type_attribute :creation_date, :timestamp => true type_attribute :deprecation_date, :timestamp => true, :static => false type_attribute :description type_attribute :status, :to_sym => true, :static => false config_attribute :default_child_policy, :to_sym => true config_attribute :default_execution_start_to_close_timeout, :duration => true config_attribute :default_task_list do translates_output {|v| v['name'] } end config_attribute :default_task_start_to_close_timeout, :duration => true # @param [Hash] options # # @option (see DecisionTask#continue_as_new_workflow_execution) # # @option options [String] :workflow_id # A user defined identifier associated with the workflow execution. # You can use this to associate a custom identifier with the # workflow execution. You may specify the same identifier if a # workflow execution is logically a restart of a previous execution. # You cannot have two open workflow executions with the same # :workflow_id at the same time. # # If you do not provide `:workflow_id` a random UUID will be generated. # # @return [WorkflowExecution] Returns the new workflow execution. # def start_execution options = {} options[:domain] = domain.name start_execution_opts(options, self) response = client.start_workflow_execution(options) workflow_id = options[:workflow_id] run_id = response.data['runId'] domain.workflow_executions[workflow_id, run_id] end # Returns a count of workflow executions of this workflow type. # # @example # # domain.workflow_types['name','version'].count # # @note (see WorkflowExecution#count_executions) # @param (see WorkflowExecution#count_executions) # @option (see WorkflowExecution#count_executions) # @return [Integer] Returns the count of workflow execution of this type. def count_executions options = {} options[:workflow_type] = self domain.workflow_executions.count(options) end # @return [WorkflowExecutionCollection] Returns a collection that # enumerates only workflow executions of this type. def workflow_executions WorkflowExecutionCollection.new(domain).with_workflow_type(self) end # list workflow type only provides type attributes provider(:list_workflow_types) do |provider| provider.provides *type_attributes.keys provider.find do |resp| desc = resp.data['typeInfos'].find do |info| info[self.class.type_key] == { 'name' => name, 'version' => version } end end end # describe workflow type provides type and config attributes provider(:describe_workflow_type) do |provider| provider.provides *type_attributes.keys provider.provides *config_attributes.keys provider.find do |resp| type = { 'name' => name, 'version' => version } resp.data['typeInfo'][self.class.type_key] == type ? resp.data['typeInfo'].merge(resp.data['configuration']) : nil end end end end end
HelainSchoonjans/LogstashRabbitMQExample
logstash-producer/vendor/bundle/jruby/1.9/gems/aws-sdk-1.35.0/lib/aws/simple_workflow/workflow_type.rb
Ruby
mit
6,707
// // Copyright (c) 2014 VK.com // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // package com.vk.sdk.api.httpClient; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Looper; import com.vk.sdk.api.VKError; import org.apache.http.client.methods.HttpGet; public class VKImageOperation extends VKHttpOperation { public float imageDensity; /** * Create new operation for loading prepared Http request. * * @param imageUrl URL for image */ public VKImageOperation(String imageUrl) { super(new HttpGet(imageUrl)); } /** * Set listener for current operation * @param listener Listener subclasses VKHTTPOperationCompleteListener */ public void setImageOperationListener(final VKImageOperationListener listener) { this.setCompleteListener(new VKOperationCompleteListener() { @Override public void onComplete() { if (VKImageOperation.this.state() != VKOperationState.Finished || mLastException != null) { listener.onError(VKImageOperation.this, generateError(mLastException)); } else { byte[] response = getResponseData(); Bitmap captchaImage = BitmapFactory.decodeByteArray(response, 0, response.length); if (imageDensity > 0) { captchaImage = Bitmap.createScaledBitmap(captchaImage, (int) (captchaImage.getWidth() * imageDensity), (int) (captchaImage.getHeight() * imageDensity), true); } final Bitmap result = captchaImage; new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { listener.onComplete(VKImageOperation.this, result); } }); } } }); } /** * Class representing operation listener for VKHttpOperation */ public static abstract class VKImageOperationListener extends VKHTTPOperationCompleteListener { public void onComplete(VKImageOperation operation, Bitmap image) { } public void onError(VKImageOperation operation, VKError error) { } } }
shustreek/vk-android-sdk-master
vksdk_library/src/main/java/com/vk/sdk/api/httpClient/VKImageOperation.java
Java
mit
3,403
/** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); };
ldcvia/ldcvia-teamroom
node_modules/bower/node_modules/insight/node_modules/inquirer/node_modules/rx/src/core/linq/observable/some.js
JavaScript
mit
1,118
using System; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Repositories; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Persistence.Querying { [TestFixture] public class PetaPocoSqlTests : BaseUsingSqlCeSyntax { [Test] public void Can_Select_From_With_Type() { var expected = new Sql(); expected.Select("*").From("[cmsContent]"); var sql = new Sql(); sql.Select("*").From<ContentDto>(); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } [Test] public void Can_InnerJoin_With_Types() { var expected = new Sql(); expected.Select("*") .From("[cmsDocument]") .InnerJoin("[cmsContentVersion]") .On("[cmsDocument].[versionId] = [cmsContentVersion].[VersionId]"); var sql = new Sql(); sql.Select("*").From<DocumentDto>() .InnerJoin<ContentVersionDto>() .On<DocumentDto, ContentVersionDto>(left => left.VersionId, right => right.VersionId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } [Test] public void Can_OrderBy_With_Type() { var expected = new Sql(); expected.Select("*").From("[cmsContent]").OrderBy("([cmsContent].[contentType])"); var sql = new Sql(); sql.Select("*").From<ContentDto>().OrderBy<ContentDto>(x => x.ContentTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } [Test] public void Can_GroupBy_With_Type() { var expected = new Sql(); expected.Select("*").From("[cmsContent]").GroupBy("[contentType]"); var sql = new Sql(); sql.Select("*").From<ContentDto>().GroupBy<ContentDto>(x => x.ContentTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } [Test] public void Can_Use_Where_Predicate() { var expected = new Sql(); expected.Select("*").From("[cmsContent]").Where("[cmsContent].[nodeId] = 1045"); var sql = new Sql(); sql.Select("*").From<ContentDto>().Where<ContentDto>(x => x.NodeId == 1045); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } [Test] public void Can_Use_Where_And_Predicate() { var expected = new Sql(); expected.Select("*") .From("[cmsContent]") .Where("[cmsContent].[nodeId] = 1045") .Where("[cmsContent].[contentType] = 1050"); var sql = new Sql(); sql.Select("*") .From<ContentDto>() .Where<ContentDto>(x => x.NodeId == 1045) .Where<ContentDto>(x => x.ContentTypeId == 1050); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Console.WriteLine(sql.SQL); } } }
bowserm/Umbraco-CMS
src/Umbraco.Tests/Persistence/Querying/PetaPocoSqlTests.cs
C#
mit
3,453
/** * The position and size of the Bitmap Text in global space, taking into account the Game Object's scale and world position. * * @typedef {object} Phaser.Types.GameObjects.BitmapText.GlobalBitmapTextSize * @since 3.0.0 * * @property {number} x - The x position of the BitmapText, taking into account the x position and scale of the Game Object. * @property {number} y - The y position of the BitmapText, taking into account the y position and scale of the Game Object. * @property {number} width - The width of the BitmapText, taking into account the x scale of the Game Object. * @property {number} height - The height of the BitmapText, taking into account the y scale of the Game Object. */
photonstorm/phaser
src/gameobjects/bitmaptext/typedefs/GlobalBitmapTextSize.js
JavaScript
mit
707
version https://git-lfs.github.com/spec/v1 oid sha256:0e7889c818b4129a08bc3843ba39b2e1118e6cfd3f186b1abf15037cd5599dd6 size 547
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.7.8/cldr/nls/fr/number.js
JavaScript
mit
128
import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', async(() => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); })); });
Toxicable/angular
aio/content/examples/interpolation/src/app/app.component.spec.ts
TypeScript
mit
475
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\DependencyInjection\Dumper; use Symfony\Component\DependencyInjection\Variable; use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Parameter; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; use Symfony\Component\DependencyInjection\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; /** * PhpDumper dumps a service container as a PHP class. * * @author Fabien Potencier <[email protected]> * @author Johannes M. Schmitt <[email protected]> */ class PhpDumper extends Dumper { /** * Characters that might appear in the generated variable name as first character. * * @var string */ const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz'; /** * Characters that might appear in the generated variable name as any but the first character. * * @var string */ const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_'; private $inlinedDefinitions; private $definitionVariables; private $referenceVariables; private $variableCount; private $reservedVariables = array('instance', 'class'); private $expressionLanguage; private $targetDirRegex; private $targetDirMaxMatches; /** * @var ExpressionFunctionProviderInterface[] */ private $expressionLanguageProviders = array(); /** * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface */ private $proxyDumper; /** * {@inheritdoc} */ public function __construct(ContainerBuilder $container) { parent::__construct($container); $this->inlinedDefinitions = new \SplObjectStorage(); } /** * Sets the dumper to be used when dumping proxies in the generated container. * * @param ProxyDumper $proxyDumper */ public function setProxyDumper(ProxyDumper $proxyDumper) { $this->proxyDumper = $proxyDumper; } /** * Dumps the service container as a PHP class. * * Available options: * * * class: The class name * * base_class: The base class name * * namespace: The class namespace * * @param array $options An array of options * * @return string A PHP class representing of the service container */ public function dump(array $options = array()) { $this->targetDirRegex = null; $options = array_merge(array( 'class' => 'ProjectServiceContainer', 'base_class' => 'Container', 'namespace' => '', ), $options); if (!empty($options['file']) && is_dir($dir = dirname($options['file']))) { // Build a regexp where the first root dirs are mandatory, // but every other sub-dir is optional up to the full path in $dir // Mandate at least 2 root dirs and not more that 5 optional dirs. $dir = explode(DIRECTORY_SEPARATOR, realpath($dir)); $i = count($dir); if (3 <= $i) { $regex = ''; $lastOptionalDir = $i > 8 ? $i - 5 : 3; $this->targetDirMaxMatches = $i - $lastOptionalDir; while (--$i >= $lastOptionalDir) { $regex = sprintf('(%s%s)?', preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex); } do { $regex = preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#').$regex; } while (0 < --$i); $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#'; } } $code = $this->startClass($options['class'], $options['base_class'], $options['namespace']); if ($this->container->isFrozen()) { $code .= $this->addFrozenConstructor(); $code .= $this->addFrozenCompile(); } else { $code .= $this->addConstructor(); } $code .= $this->addServices(). $this->addDefaultParametersMethod(). $this->endClass(). $this->addProxyClasses() ; $this->targetDirRegex = null; return $code; } /** * Retrieves the currently set proxy dumper or instantiates one. * * @return ProxyDumper */ private function getProxyDumper() { if (!$this->proxyDumper) { $this->proxyDumper = new NullDumper(); } return $this->proxyDumper; } /** * Generates Service local temp variables. * * @param string $cId * @param string $definition * * @return string */ private function addServiceLocalTempVariables($cId, $definition) { static $template = " \$%s = %s;\n"; $localDefinitions = array_merge( array($definition), $this->getInlinedDefinitions($definition) ); $calls = $behavior = array(); foreach ($localDefinitions as $iDefinition) { $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior); $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior); $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior); $this->getServiceCallsFromArguments(array($iDefinition->getConfigurator()), $calls, $behavior); $this->getServiceCallsFromArguments(array($iDefinition->getFactory()), $calls, $behavior); } $code = ''; foreach ($calls as $id => $callCount) { if ('service_container' === $id || $id === $cId) { continue; } if ($callCount > 1) { $name = $this->getNextVariableName(); $this->referenceVariables[$id] = new Variable($name); if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) { $code .= sprintf($template, $name, $this->getServiceCall($id)); } else { $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE))); } } } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Generates code for the proxies to be attached after the container class. * * @return string */ private function addProxyClasses() { /* @var $definitions Definition[] */ $definitions = array_filter( $this->container->getDefinitions(), array($this->getProxyDumper(), 'isProxyCandidate') ); $code = ''; foreach ($definitions as $definition) { $code .= "\n".$this->getProxyDumper()->getProxyCode($definition); } return $code; } /** * Generates the require_once statement for service includes. * * @param string $id The service id * @param Definition $definition * * @return string */ private function addServiceInclude($id, $definition) { $template = " require_once %s;\n"; $code = ''; if (null !== $file = $definition->getFile()) { $code .= sprintf($template, $this->dumpValue($file)); } foreach ($this->getInlinedDefinitions($definition) as $definition) { if (null !== $file = $definition->getFile()) { $code .= sprintf($template, $this->dumpValue($file)); } } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Generates the inline definition of a service. * * @param string $id * @param Definition $definition * * @return string * * @throws RuntimeException When the factory definition is incomplete * @throws ServiceCircularReferenceException When a circular reference is detected */ private function addServiceInlinedDefinitions($id, $definition) { $code = ''; $variableMap = $this->definitionVariables; $nbOccurrences = new \SplObjectStorage(); $processed = new \SplObjectStorage(); $inlinedDefinitions = $this->getInlinedDefinitions($definition); foreach ($inlinedDefinitions as $definition) { if (false === $nbOccurrences->contains($definition)) { $nbOccurrences->offsetSet($definition, 1); } else { $i = $nbOccurrences->offsetGet($definition); $nbOccurrences->offsetSet($definition, $i + 1); } } foreach ($inlinedDefinitions as $sDefinition) { if ($processed->contains($sDefinition)) { continue; } $processed->offsetSet($sDefinition); $class = $this->dumpValue($sDefinition->getClass()); if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) { $name = $this->getNextVariableName(); $variableMap->offsetSet($sDefinition, new Variable($name)); // a construct like: // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a); // this is an indication for a wrong implementation, you can circumvent this problem // by setting up your service structure like this: // $b = new ServiceB(); // $a = new ServiceA(ServiceB $b); // $b->setServiceA(ServiceA $a); if ($this->hasReference($id, $sDefinition->getArguments())) { throw new ServiceCircularReferenceException($id, array($id)); } $code .= $this->addNewInstance($id, $sDefinition, '$'.$name, ' = '); if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) { $code .= $this->addServiceMethodCalls(null, $sDefinition, $name); $code .= $this->addServiceProperties(null, $sDefinition, $name); $code .= $this->addServiceConfigurator(null, $sDefinition, $name); } $code .= "\n"; } } return $code; } /** * Adds the service return statement. * * @param string $id Service id * @param Definition $definition * * @return string */ private function addServiceReturn($id, $definition) { if ($this->isSimpleInstance($id, $definition)) { return " }\n"; } return "\n return \$instance;\n }\n"; } /** * Generates the service instance. * * @param string $id * @param Definition $definition * * @return string * * @throws InvalidArgumentException * @throws RuntimeException */ private function addServiceInstance($id, $definition) { $class = $definition->getClass(); if ('\\' === substr($class, 0, 1)) { $class = substr($class, 1); } $class = $this->dumpValue($class); if (0 === strpos($class, "'") && !preg_match('/^\'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) { throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id)); } $simple = $this->isSimpleInstance($id, $definition); $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $instantiation = ''; if (!$isProxyCandidate && ContainerInterface::SCOPE_CONTAINER === $definition->getScope()) { $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance'); } elseif (!$isProxyCandidate && ContainerInterface::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) { $instantiation = "\$this->services['$id'] = \$this->scopedServices['$scope']['$id'] = ".($simple ? '' : '$instance'); } elseif (!$simple) { $instantiation = '$instance'; } $return = ''; if ($simple) { $return = 'return '; } else { $instantiation .= ' = '; } $code = $this->addNewInstance($id, $definition, $return, $instantiation); if (!$simple) { $code .= "\n"; } return $code; } /** * Checks if the definition is a simple instance. * * @param string $id * @param Definition $definition * * @return bool */ private function isSimpleInstance($id, $definition) { foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) { if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) { continue; } if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) { return false; } } return true; } /** * Adds method calls to a service definition. * * @param string $id * @param Definition $definition * @param string $variableName * * @return string */ private function addServiceMethodCalls($id, $definition, $variableName = 'instance') { $calls = ''; foreach ($definition->getMethodCalls() as $call) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments))); } return $calls; } private function addServiceProperties($id, $definition, $variableName = 'instance') { $code = ''; foreach ($definition->getProperties() as $name => $value) { $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value)); } return $code; } /** * Generates the inline definition setup. * * @param string $id * @param Definition $definition * * @return string * * @throws ServiceCircularReferenceException when the container contains a circular reference */ private function addServiceInlinedDefinitionsSetup($id, $definition) { $this->referenceVariables[$id] = new Variable('instance'); $code = ''; $processed = new \SplObjectStorage(); foreach ($this->getInlinedDefinitions($definition) as $iDefinition) { if ($processed->contains($iDefinition)) { continue; } $processed->offsetSet($iDefinition); if (!$this->hasReference($id, $iDefinition->getMethodCalls(), true) && !$this->hasReference($id, $iDefinition->getProperties(), true)) { continue; } // if the instance is simple, the return statement has already been generated // so, the only possible way to get there is because of a circular reference if ($this->isSimpleInstance($id, $definition)) { throw new ServiceCircularReferenceException($id, array($id)); } $name = (string) $this->definitionVariables->offsetGet($iDefinition); $code .= $this->addServiceMethodCalls(null, $iDefinition, $name); $code .= $this->addServiceProperties(null, $iDefinition, $name); $code .= $this->addServiceConfigurator(null, $iDefinition, $name); } if ('' !== $code) { $code .= "\n"; } return $code; } /** * Adds configurator definition. * * @param string $id * @param Definition $definition * @param string $variableName * * @return string */ private function addServiceConfigurator($id, $definition, $variableName = 'instance') { if (!$callable = $definition->getConfigurator()) { return ''; } if (is_array($callable)) { if ($callable[0] instanceof Reference || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } $class = $this->dumpValue($callable[0]); // If the class is a string we can optimize call_user_func away if (strpos($class, "'") === 0) { return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName); } return sprintf(" call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName); } return sprintf(" %s(\$%s);\n", $callable, $variableName); } /** * Adds a service. * * @param string $id * @param Definition $definition * * @return string */ private function addService($id, $definition) { $this->definitionVariables = new \SplObjectStorage(); $this->referenceVariables = array(); $this->variableCount = 0; $return = array(); if ($definition->isSynthetic()) { $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically'; } elseif ($class = $definition->getClass()) { $return[] = sprintf('@return %s A %s instance.', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), ltrim($class, '\\')); } elseif ($definition->getFactory()) { $factory = $definition->getFactory(); if (is_string($factory)) { $return[] = sprintf('@return object An instance returned by %s().', $factory); } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) { if (is_string($factory[0]) || $factory[0] instanceof Reference) { $return[] = sprintf('@return object An instance returned by %s::%s().', (string) $factory[0], $factory[1]); } elseif ($factory[0] instanceof Definition) { $return[] = sprintf('@return object An instance returned by %s::%s().', $factory[0]->getClass(), $factory[1]); } } } elseif ($definition->getFactoryClass(false)) { $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryClass(false), $definition->getFactoryMethod(false)); } elseif ($definition->getFactoryService(false)) { $return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryService(false), $definition->getFactoryMethod(false)); } $scope = $definition->getScope(); if (!in_array($scope, array(ContainerInterface::SCOPE_CONTAINER, ContainerInterface::SCOPE_PROTOTYPE))) { if ($return && 0 === strpos($return[count($return) - 1], '@return')) { $return[] = ''; } $return[] = sprintf("@throws InactiveScopeException when the '%s' service is requested while the '%s' scope is not active", $id, $scope); } $return = implode("\n * ", $return); $doc = ''; if (ContainerInterface::SCOPE_PROTOTYPE !== $scope) { $doc .= <<<'EOF' * * This service is shared. * This method always returns the same instance of the service. EOF; } if (!$definition->isPublic()) { $doc .= <<<'EOF' * * This service is private. * If you want to be able to request this service from the container directly, * make it public, otherwise you might end up with broken code. EOF; } if ($definition->isLazy()) { $lazyInitialization = '$lazyLoad = true'; $lazyInitializationDoc = "\n * @param bool \$lazyLoad whether to try lazy-loading the service with a proxy\n *"; } else { $lazyInitialization = ''; $lazyInitializationDoc = ''; } // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition); $visibility = $isProxyCandidate ? 'public' : 'protected'; $code = <<<EOF /** * Gets the '$id' service.$doc *$lazyInitializationDoc * $return */ {$visibility} function get{$this->camelize($id)}Service($lazyInitialization) { EOF; $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id) : ''; if (!in_array($scope, array(ContainerInterface::SCOPE_CONTAINER, ContainerInterface::SCOPE_PROTOTYPE))) { $code .= <<<EOF if (!isset(\$this->scopedServices['$scope'])) { throw new InactiveScopeException('$id', '$scope'); } EOF; } if ($definition->isSynthetic()) { $code .= sprintf(" throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n }\n", $id); } else { $code .= $this->addServiceInclude($id, $definition). $this->addServiceLocalTempVariables($id, $definition). $this->addServiceInlinedDefinitions($id, $definition). $this->addServiceInstance($id, $definition). $this->addServiceInlinedDefinitionsSetup($id, $definition). $this->addServiceMethodCalls($id, $definition). $this->addServiceProperties($id, $definition). $this->addServiceConfigurator($id, $definition). $this->addServiceReturn($id, $definition) ; } $this->definitionVariables = null; $this->referenceVariables = null; return $code; } /** * Adds multiple services. * * @return string */ private function addServices() { $publicServices = $privateServices = $synchronizers = ''; $definitions = $this->container->getDefinitions(); ksort($definitions); foreach ($definitions as $id => $definition) { if ($definition->isPublic()) { $publicServices .= $this->addService($id, $definition); } else { $privateServices .= $this->addService($id, $definition); } $synchronizers .= $this->addServiceSynchronizer($id, $definition); } return $publicServices.$synchronizers.$privateServices; } /** * Adds synchronizer methods. * * @param string $id A service identifier * @param Definition $definition A Definition instance * * @return string|null * * @deprecated since version 2.7, will be removed in 3.0. */ private function addServiceSynchronizer($id, Definition $definition) { if (!$definition->isSynchronized(false)) { return; } if ('request' !== $id) { @trigger_error('Synchronized services were deprecated in version 2.7 and won\'t work anymore in 3.0.', E_USER_DEPRECATED); } $code = ''; foreach ($this->container->getDefinitions() as $definitionId => $definition) { foreach ($definition->getMethodCalls() as $call) { foreach ($call[1] as $argument) { if ($argument instanceof Reference && $id == (string) $argument) { $arguments = array(); foreach ($call[1] as $value) { $arguments[] = $this->dumpValue($value); } $call = $this->wrapServiceConditionals($call[1], sprintf("\$this->get('%s')->%s(%s);", $definitionId, $call[0], implode(', ', $arguments))); $code .= <<<EOF if (\$this->initialized('$definitionId')) { $call } EOF; } } } } if (!$code) { return; } return <<<EOF /** * Updates the '$id' service. */ protected function synchronize{$this->camelize($id)}Service() { $code } EOF; } private function addNewInstance($id, Definition $definition, $return, $instantiation) { $class = $this->dumpValue($definition->getClass()); $arguments = array(); foreach ($definition->getArguments() as $value) { $arguments[] = $this->dumpValue($value); } if (null !== $definition->getFactory()) { $callable = $definition->getFactory(); if (is_array($callable)) { if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) { throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a')); } if ($callable[0] instanceof Reference || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) { return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : ''); } $class = $this->dumpValue($callable[0]); // If the class is a string we can optimize call_user_func away if (strpos($class, "'") === 0) { return sprintf(" $return{$instantiation}%s::%s(%s);\n", $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : ''); } return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? ', '.implode(', ', $arguments) : ''); } return sprintf(" $return{$instantiation}\\%s(%s);\n", $callable, $arguments ? implode(', ', $arguments) : ''); } elseif (null !== $definition->getFactoryMethod(false)) { if (null !== $definition->getFactoryClass(false)) { $class = $this->dumpValue($definition->getFactoryClass(false)); // If the class is a string we can optimize call_user_func away if (strpos($class, "'") === 0) { return sprintf(" $return{$instantiation}%s::%s(%s);\n", $this->dumpLiteralClass($class), $definition->getFactoryMethod(false), $arguments ? implode(', ', $arguments) : ''); } return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($definition->getFactoryClass(false)), $definition->getFactoryMethod(false), $arguments ? ', '.implode(', ', $arguments) : ''); } if (null !== $definition->getFactoryService(false)) { return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->getServiceCall($definition->getFactoryService(false)), $definition->getFactoryMethod(false), implode(', ', $arguments)); } throw new RuntimeException(sprintf('Factory method requires a factory service or factory class in service definition for %s', $id)); } if (false !== strpos($class, '$')) { return sprintf(" \$class = %s;\n\n $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments)); } return sprintf(" $return{$instantiation}new %s(%s);\n", $this->dumpLiteralClass($class), implode(', ', $arguments)); } /** * Adds the class headers. * * @param string $class Class name * @param string $baseClass The name of the base class * @param string $namespace The class namespace * * @return string */ private function startClass($class, $baseClass, $namespace) { $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;'; $namespaceLine = $namespace ? "namespace $namespace;\n" : ''; return <<<EOF <?php $namespaceLine use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\Exception\InactiveScopeException; use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Exception\LogicException; use Symfony\Component\DependencyInjection\Exception\RuntimeException; $bagClass /** * $class. * * This class has been auto-generated * by the Symfony Dependency Injection Component. */ class $class extends $baseClass { private \$parameters; private \$targetDirs = array(); EOF; } /** * Adds the constructor. * * @return string */ private function addConstructor() { $targetDirs = $this->exportTargetDirs(); $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null; $code = <<<EOF /** * Constructor. */ public function __construct() {{$targetDirs} parent::__construct($arguments); EOF; if (count($scopes = $this->container->getScopes()) > 0) { $code .= "\n"; $code .= ' $this->scopes = '.$this->dumpValue($scopes).";\n"; $code .= ' $this->scopeChildren = '.$this->dumpValue($this->container->getScopeChildren()).";\n"; } $code .= $this->addMethodMap(); $code .= $this->addAliases(); $code .= <<<'EOF' } EOF; return $code; } /** * Adds the constructor for a frozen container. * * @return string */ private function addFrozenConstructor() { $targetDirs = $this->exportTargetDirs(); $code = <<<EOF /** * Constructor. */ public function __construct() {{$targetDirs} EOF; if ($this->container->getParameterBag()->all()) { $code .= "\n \$this->parameters = \$this->getDefaultParameters();\n"; } $code .= <<<'EOF' $this->services = $this->scopedServices = $this->scopeStacks = array(); EOF; $code .= "\n"; if (count($scopes = $this->container->getScopes()) > 0) { $code .= ' $this->scopes = '.$this->dumpValue($scopes).";\n"; $code .= ' $this->scopeChildren = '.$this->dumpValue($this->container->getScopeChildren()).";\n"; } else { $code .= " \$this->scopes = array();\n"; $code .= " \$this->scopeChildren = array();\n"; } $code .= $this->addMethodMap(); $code .= $this->addAliases(); $code .= <<<'EOF' } EOF; return $code; } /** * Adds the constructor for a frozen container. * * @return string */ private function addFrozenCompile() { return <<<EOF /** * {@inheritdoc} */ public function compile() { throw new LogicException('You cannot compile a dumped frozen container.'); } EOF; } /** * Adds the methodMap property definition. * * @return string */ private function addMethodMap() { if (!$definitions = $this->container->getDefinitions()) { return ''; } $code = " \$this->methodMap = array(\n"; ksort($definitions); foreach ($definitions as $id => $definition) { $code .= ' '.var_export($id, true).' => '.var_export('get'.$this->camelize($id).'Service', true).",\n"; } return $code." );\n"; } /** * Adds the aliases property definition. * * @return string */ private function addAliases() { if (!$aliases = $this->container->getAliases()) { if ($this->container->isFrozen()) { return "\n \$this->aliases = array();\n"; } else { return ''; } } $code = " \$this->aliases = array(\n"; ksort($aliases); foreach ($aliases as $alias => $id) { $id = (string) $id; while (isset($aliases[$id])) { $id = (string) $aliases[$id]; } $code .= ' '.var_export($alias, true).' => '.var_export($id, true).",\n"; } return $code." );\n"; } /** * Adds default parameters method. * * @return string */ private function addDefaultParametersMethod() { if (!$this->container->getParameterBag()->all()) { return ''; } $parameters = $this->exportParameters($this->container->getParameterBag()->all()); $code = ''; if ($this->container->isFrozen()) { $code .= <<<'EOF' /** * {@inheritdoc} */ public function getParameter($name) { $name = strtolower($name); if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) { throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name)); } return $this->parameters[$name]; } /** * {@inheritdoc} */ public function hasParameter($name) { $name = strtolower($name); return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters); } /** * {@inheritdoc} */ public function setParameter($name, $value) { throw new LogicException('Impossible to call set() on a frozen ParameterBag.'); } /** * {@inheritdoc} */ public function getParameterBag() { if (null === $this->parameterBag) { $this->parameterBag = new FrozenParameterBag($this->parameters); } return $this->parameterBag; } EOF; } $code .= <<<EOF /** * Gets the default parameters. * * @return array An array of the default parameters */ protected function getDefaultParameters() { return $parameters; } EOF; return $code; } /** * Exports parameters. * * @param array $parameters * @param string $path * @param int $indent * * @return string * * @throws InvalidArgumentException */ private function exportParameters($parameters, $path = '', $indent = 12) { $php = array(); foreach ($parameters as $key => $value) { if (is_array($value)) { $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4); } elseif ($value instanceof Variable) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key)); } elseif ($value instanceof Definition) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key)); } elseif ($value instanceof Reference) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key)); } elseif ($value instanceof Expression) { throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key)); } else { $value = $this->export($value); } $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), var_export($key, true), $value); } return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4)); } /** * Ends the class definition. * * @return string */ private function endClass() { return <<<'EOF' } EOF; } /** * Wraps the service conditionals. * * @param string $value * @param string $code * * @return string */ private function wrapServiceConditionals($value, $code) { if (!$services = ContainerBuilder::getServiceConditionals($value)) { return $code; } $conditions = array(); foreach ($services as $service) { $conditions[] = sprintf("\$this->has('%s')", $service); } // re-indent the wrapped code $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code))); return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code); } /** * Builds service calls from arguments. * * @param array $arguments * @param array &$calls By reference * @param array &$behavior By reference */ private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior) { foreach ($arguments as $argument) { if (is_array($argument)) { $this->getServiceCallsFromArguments($argument, $calls, $behavior); } elseif ($argument instanceof Reference) { $id = (string) $argument; if (!isset($calls[$id])) { $calls[$id] = 0; } if (!isset($behavior[$id])) { $behavior[$id] = $argument->getInvalidBehavior(); } elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) { $behavior[$id] = $argument->getInvalidBehavior(); } ++$calls[$id]; } } } /** * Returns the inline definition. * * @param Definition $definition * * @return array */ private function getInlinedDefinitions(Definition $definition) { if (false === $this->inlinedDefinitions->contains($definition)) { $definitions = array_merge( $this->getDefinitionsFromArguments($definition->getArguments()), $this->getDefinitionsFromArguments($definition->getMethodCalls()), $this->getDefinitionsFromArguments($definition->getProperties()), $this->getDefinitionsFromArguments(array($definition->getConfigurator())), $this->getDefinitionsFromArguments(array($definition->getFactory())) ); $this->inlinedDefinitions->offsetSet($definition, $definitions); return $definitions; } return $this->inlinedDefinitions->offsetGet($definition); } /** * Gets the definition from arguments. * * @param array $arguments * * @return array */ private function getDefinitionsFromArguments(array $arguments) { $definitions = array(); foreach ($arguments as $argument) { if (is_array($argument)) { $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument)); } elseif ($argument instanceof Definition) { $definitions = array_merge( $definitions, $this->getInlinedDefinitions($argument), array($argument) ); } } return $definitions; } /** * Checks if a service id has a reference. * * @param string $id * @param array $arguments * @param bool $deep * @param array $visited * * @return bool */ private function hasReference($id, array $arguments, $deep = false, array &$visited = array()) { foreach ($arguments as $argument) { if (is_array($argument)) { if ($this->hasReference($id, $argument, $deep, $visited)) { return true; } } elseif ($argument instanceof Reference) { $argumentId = (string) $argument; if ($id === $argumentId) { return true; } if ($deep && !isset($visited[$argumentId])) { $visited[$argumentId] = true; $service = $this->container->getDefinition($argumentId); $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties()); if ($this->hasReference($id, $arguments, $deep, $visited)) { return true; } } } } return false; } /** * Dumps values. * * @param mixed $value * @param bool $interpolate * * @return string * * @throws RuntimeException */ private function dumpValue($value, $interpolate = true) { if (is_array($value)) { $code = array(); foreach ($value as $k => $v) { $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)); } return sprintf('array(%s)', implode(', ', $code)); } elseif ($value instanceof Definition) { if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) { return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate); } if (count($value->getMethodCalls()) > 0) { throw new RuntimeException('Cannot dump definitions which have method calls.'); } if (null !== $value->getConfigurator()) { throw new RuntimeException('Cannot dump definitions which have a configurator.'); } $arguments = array(); foreach ($value->getArguments() as $argument) { $arguments[] = $this->dumpValue($argument); } if (null !== $value->getFactory()) { $factory = $value->getFactory(); if (is_string($factory)) { return sprintf('\\%s(%s)', $factory, implode(', ', $arguments)); } if (is_array($factory)) { if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) { throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a')); } if (is_string($factory[0])) { return sprintf('%s::%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory[0])), $factory[1], implode(', ', $arguments)); } if ($factory[0] instanceof Definition) { return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($factory[0]), $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : ''); } if ($factory[0] instanceof Reference) { return sprintf('%s->%s(%s)', $this->dumpValue($factory[0]), $factory[1], implode(', ', $arguments)); } } throw new RuntimeException('Cannot dump definition because of invalid factory'); } if (null !== $value->getFactoryMethod(false)) { if (null !== $value->getFactoryClass(false)) { return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($value->getFactoryClass(false)), $value->getFactoryMethod(false), count($arguments) > 0 ? ', '.implode(', ', $arguments) : ''); } elseif (null !== $value->getFactoryService(false)) { $service = $this->dumpValue($value->getFactoryService(false)); return sprintf('%s->%s(%s)', 0 === strpos($service, '$') ? sprintf('$this->get(%s)', $service) : $this->getServiceCall($value->getFactoryService(false)), $value->getFactoryMethod(false), implode(', ', $arguments)); } else { throw new RuntimeException('Cannot dump definitions which have factory method without factory service or factory class.'); } } $class = $value->getClass(); if (null === $class) { throw new RuntimeException('Cannot dump definitions which have no class nor factory.'); } return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments)); } elseif ($value instanceof Variable) { return '$'.$value; } elseif ($value instanceof Reference) { if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) { return $this->dumpValue($this->referenceVariables[$id], $interpolate); } return $this->getServiceCall((string) $value, $value); } elseif ($value instanceof Expression) { return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container')); } elseif ($value instanceof Parameter) { return $this->dumpParameter($value); } elseif (true === $interpolate && is_string($value)) { if (preg_match('/^%([^%]+)%$/', $value, $match)) { // we do this to deal with non string values (Boolean, integer, ...) // the preg_replace_callback converts them to strings return $this->dumpParameter(strtolower($match[1])); } else { $that = $this; $replaceParameters = function ($match) use ($that) { return "'.".$that->dumpParameter(strtolower($match[2])).".'"; }; $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value))); return $code; } } elseif (is_object($value) || is_resource($value)) { throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.'); } else { return $this->export($value); } } /** * Dumps a string to a literal (aka PHP Code) class value. * * @param string $class * * @return string * * @throws RuntimeException */ private function dumpLiteralClass($class) { if (false !== strpos($class, '$')) { throw new RuntimeException('Cannot dump definitions which have a variable class name.'); } if (0 !== strpos($class, "'") || !preg_match('/^\'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) { throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s)', $class ?: 'n/a')); } return '\\'.substr(str_replace('\\\\', '\\', $class), 1, -1); } /** * Dumps a parameter. * * @param string $name * * @return string */ public function dumpParameter($name) { if ($this->container->isFrozen() && $this->container->hasParameter($name)) { return $this->dumpValue($this->container->getParameter($name), false); } return sprintf("\$this->getParameter('%s')", strtolower($name)); } /** * @deprecated since version 2.6.2, to be removed in 3.0. * Use \Symfony\Component\DependencyInjection\ContainerBuilder::addExpressionLanguageProvider instead. * * @param ExpressionFunctionProviderInterface $provider */ public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) { @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6.2 and will be removed in 3.0. Use the Symfony\Component\DependencyInjection\ContainerBuilder::addExpressionLanguageProvider method instead.', E_USER_DEPRECATED); $this->expressionLanguageProviders[] = $provider; } /** * Gets a service call. * * @param string $id * @param Reference $reference * * @return string */ private function getServiceCall($id, Reference $reference = null) { if ('service_container' === $id) { return '$this'; } if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) { return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id); } else { if ($this->container->hasAlias($id)) { $id = (string) $this->container->getAlias($id); } return sprintf('$this->get(\'%s\')', $id); } } /** * Convert a service id to a valid PHP method name. * * @param string $id * * @return string * * @throws InvalidArgumentException */ private function camelize($id) { $name = Container::camelize($id); if (!preg_match('/^[a-zA-Z0-9_\x7f-\xff]+$/', $name)) { throw new InvalidArgumentException(sprintf('Service id "%s" cannot be converted to a valid PHP method name.', $id)); } return $name; } /** * Returns the next name to use. * * @return string */ private function getNextVariableName() { $firstChars = self::FIRST_CHARS; $firstCharsLength = strlen($firstChars); $nonFirstChars = self::NON_FIRST_CHARS; $nonFirstCharsLength = strlen($nonFirstChars); while (true) { $name = ''; $i = $this->variableCount; if ('' === $name) { $name .= $firstChars[$i % $firstCharsLength]; $i = (int) ($i / $firstCharsLength); } while ($i > 0) { --$i; $name .= $nonFirstChars[$i % $nonFirstCharsLength]; $i = (int) ($i / $nonFirstCharsLength); } ++$this->variableCount; // check that the name is not reserved if (in_array($name, $this->reservedVariables, true)) { continue; } return $name; } } private function getExpressionLanguage() { if (null === $this->expressionLanguage) { if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); } $providers = array_merge($this->container->getExpressionLanguageProviders(), $this->expressionLanguageProviders); $this->expressionLanguage = new ExpressionLanguage(null, $providers); if ($this->container->isTrackingResources()) { foreach ($providers as $provider) { $this->container->addObjectResource($provider); } } } return $this->expressionLanguage; } private function exportTargetDirs() { return null === $this->targetDirRegex ? '' : <<<EOF \$dir = __DIR__; for (\$i = 1; \$i <= {$this->targetDirMaxMatches}; ++\$i) { \$this->targetDirs[\$i] = \$dir = dirname(\$dir); } EOF; } private function export($value) { if (null !== $this->targetDirRegex && is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) { $prefix = $matches[0][1] ? var_export(substr($value, 0, $matches[0][1]), true).'.' : ''; $suffix = $matches[0][1] + strlen($matches[0][0]); $suffix = isset($value[$suffix]) ? '.'.var_export(substr($value, $suffix), true) : ''; $dirname = '__DIR__'; if (0 < $offset = 1 + $this->targetDirMaxMatches - count($matches)) { $dirname = sprintf('$this->targetDirs[%d]', $offset); } if ($prefix || $suffix) { return sprintf('(%s%s%s)', $prefix, $dirname, $suffix); } return $dirname; } return var_export($value, true); } }
Milkyway2605/EasyStage_Symfony
vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
PHP
mit
54,466
--- layout: default --- {% include JB/setup %} {% include themes/Snail/archive.html %}
gameindie/gameindie.github.io
_layouts/archive.html
HTML
mit
87
#!/usr/bin/php <?php /** * demo_user_dict.php * * PHP version 5 * * @category PHP * @package /src/cmd/ * @author Fukuball Lin <[email protected]> * @license MIT Licence * @version GIT: <fukuball/jieba-php> * @link https://github.com/fukuball/jieba-php */ ini_set('memory_limit', '600M'); require_once dirname(dirname(__FILE__))."/vendor/multi-array/MultiArray.php"; require_once dirname(dirname(__FILE__))."/vendor/multi-array/Factory/MultiArrayFactory.php"; require_once dirname(dirname(__FILE__))."/class/Jieba.php"; require_once dirname(dirname(__FILE__))."/class/Finalseg.php"; use Fukuball\Jieba; use Fukuball\Finalseg; Jieba::init(array('mode'=>'test','dict'=>'samll')); Finalseg::init(); $seg_list = Jieba::cut("李小福是创新办主任也是云计算方面的专家"); var_dump($seg_list); Jieba::loadUserDict(dirname(dirname(__FILE__)).'/dict/user_dict.txt'); $seg_list = Jieba::cut("李小福是创新办主任也是云计算方面的专家"); var_dump($seg_list); ?>
MeicaiRose/jieba-php
src/cmd/demo_user_dict.php
PHP
mit
1,005
// Copyright (c) 2017-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <index/txindex.h> #include <script/standard.h> #include <test/setup_common.h> #include <util/system.h> #include <util/time.h> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(txindex_tests) BOOST_FIXTURE_TEST_CASE(txindex_initial_sync, TestChain100Setup) { TxIndex txindex(1 << 20, true); CTransactionRef tx_disk; uint256 block_hash; // Transaction should not be found in the index before it is started. for (const auto& txn : m_coinbase_txns) { BOOST_CHECK(!txindex.FindTx(txn->GetHash(), block_hash, tx_disk)); } // BlockUntilSyncedToCurrentChain should return false before txindex is started. BOOST_CHECK(!txindex.BlockUntilSyncedToCurrentChain()); txindex.Start(); // Allow tx index to catch up with the block index. constexpr int64_t timeout_ms = 10 * 1000; int64_t time_start = GetTimeMillis(); while (!txindex.BlockUntilSyncedToCurrentChain()) { BOOST_REQUIRE(time_start + timeout_ms > GetTimeMillis()); MilliSleep(100); } // Check that txindex excludes genesis block transactions. const CBlock& genesis_block = Params().GenesisBlock(); for (const auto& txn : genesis_block.vtx) { BOOST_CHECK(!txindex.FindTx(txn->GetHash(), block_hash, tx_disk)); } // Check that txindex has all txs that were in the chain before it started. for (const auto& txn : m_coinbase_txns) { if (!txindex.FindTx(txn->GetHash(), block_hash, tx_disk)) { BOOST_ERROR("FindTx failed"); } else if (tx_disk->GetHash() != txn->GetHash()) { BOOST_ERROR("Read incorrect tx"); } } // Check that new transactions in new blocks make it into the index. for (int i = 0; i < 10; i++) { CScript coinbase_script_pub_key = GetScriptForDestination(PKHash(coinbaseKey.GetPubKey())); std::vector<CMutableTransaction> no_txns; const CBlock& block = CreateAndProcessBlock(no_txns, coinbase_script_pub_key); const CTransaction& txn = *block.vtx[0]; BOOST_CHECK(txindex.BlockUntilSyncedToCurrentChain()); if (!txindex.FindTx(txn.GetHash(), block_hash, tx_disk)) { BOOST_ERROR("FindTx failed"); } else if (tx_disk->GetHash() != txn.GetHash()) { BOOST_ERROR("Read incorrect tx"); } } // shutdown sequence (c.f. Shutdown() in init.cpp) txindex.Stop(); threadGroup.interrupt_all(); threadGroup.join_all(); // Rest of shutdown sequence and destructors happen in ~TestingSetup() } BOOST_AUTO_TEST_SUITE_END()
CryptArc/bitcoin
src/test/txindex_tests.cpp
C++
mit
2,799
var traceur = require('traceur'); var traceurGet = require('../lib/utils').traceurGet; var ParseTreeTransformer = traceurGet('codegeneration/ParseTreeTransformer.js').ParseTreeTransformer; var ModuleSpecifier = traceurGet('syntax/trees/ParseTrees.js').ModuleSpecifier; var createStringLiteralToken = traceurGet('codegeneration/ParseTreeFactory.js').createStringLiteralToken; var InstantiateModuleTransformer = traceurGet('codegeneration/InstantiateModuleTransformer.js').InstantiateModuleTransformer; var extend = require('../lib/utils').extend; // patch pending https://github.com/google/traceur-compiler/pull/2053 var createUseStrictDirective = traceurGet('codegeneration/ParseTreeFactory.js').createUseStrictDirective; InstantiateModuleTransformer.prototype.__proto__.moduleProlog = function() { return [createUseStrictDirective()]; }; var CollectingErrorReporter = traceurGet('util/CollectingErrorReporter.js').CollectingErrorReporter; var UniqueIdentifierGenerator = traceurGet('codegeneration/UniqueIdentifierGenerator.js').UniqueIdentifierGenerator; function TraceurImportNormalizeTransformer(map) { this.map = map; return ParseTreeTransformer.apply(this, arguments); } TraceurImportNormalizeTransformer.prototype = Object.create(ParseTreeTransformer.prototype); TraceurImportNormalizeTransformer.prototype.transformModuleSpecifier = function(tree) { var depName = this.map(tree.token.processedValue) || tree.token.processedValue; return new ModuleSpecifier(tree.location, createStringLiteralToken(depName)); }; exports.TraceurImportNormalizeTransformer = TraceurImportNormalizeTransformer; function remap(source, map, fileName) { var compiler = new traceur.Compiler(); var tree = compiler.parse(source, fileName); tree = new TraceurImportNormalizeTransformer(map).transformAny(tree); return Promise.resolve({ source: compiler.write(tree) }); } exports.remap = remap; // override System instantiate to handle esm tracing exports.attach = function(loader) { var systemInstantiate = loader.instantiate; loader.instantiate = function(load) { // skip plugin loader attachment || non es modules || es modules handled by internal transpilation layer if (!loader.builder || load.metadata.format != 'esm' || load.metadata.originalSource) return systemInstantiate.call(this, load); var depsList = load.metadata.deps.concat([]); var babel = require('babel-core'); var output = babel.transform(load.source, { babelrc: false, compact: false, filename: load.path, //sourceFileName: load.path, inputSourceMap: load.metadata.sourceMap, ast: true, resolveModuleSource: function(dep) { if (depsList.indexOf(dep) == -1) depsList.push(dep); return dep; } }); // turn back on comments (for some reason!) output.ast.comments.forEach(function(comment) { comment.ignore = false; }); load.metadata.ast = output.ast; return Promise.resolve({ deps: depsList, execute: null }); }; }; var versionCheck = true; exports.compile = function(load, opts, loader) { if (!load.metadata.originalSource || load.metadata.loader && load.metadata.format == 'esm') { var babel = require('babel-core'); var babelOptions = { babelrc: false, compact: false, plugins: [[require('babel-plugin-transform-es2015-modules-systemjs'), { systemGlobal: opts.systemGlobal }]], filename: load.path, //sourceFileName: load.path, sourceMaps: opts.sourceMaps, inputSourceMap: load.metadata.sourceMap, moduleIds: !opts.anonymous, moduleId: !opts.anonymous && load.name, code: true, resolveModuleSource: function(dep) { if (opts.normalize) return load.depMap[dep]; else return dep; } }; var source = load.metadata.originalSource || load.source; var output; if (load.metadata.ast) output = babel.transformFromAst(load.metadata.ast, source, babelOptions); else output = babel.transform(source, babelOptions); // NB this can be removed with merging of () if (opts.systemGlobal != 'System') output.code = output.code.replace(/(\s|^)System\.register\(/, '$1' + opts.systemGlobal + '.register('); // for some reason Babel isn't respecting sourceFileName... if (output.map && !load.metadata.sourceMap) output.map.sources[0] = load.path; return Promise.resolve({ source: output.code, sourceMap: output.map }); } // ... legacy transpilation, to be deprecated with internal transpilation layer return Promise.resolve(global[loader.transpiler == 'typescript' ? 'ts' : loader.transpiler] || loader.pluginLoader.import(loader.transpiler)) .then(function(transpiler) { if (transpiler.__useDefault) transpiler = transpiler['default']; if (transpiler.Compiler) { var options = loader.traceurOptions || {}; options.modules = 'instantiate'; options.script = false; options.sourceRoot = true; options.moduleName = !opts.anonymous; if (opts.sourceMaps) options.sourceMaps = 'memory'; if (opts.lowResSourceMaps) options.lowResolutionSourceMap = true; if (load.metadata.sourceMap) options.inputSourceMap = load.metadata.sourceMap; var compiler = new transpiler.Compiler(options); var tree = compiler.parse(load.source, load.path); var transformer = new TraceurImportNormalizeTransformer(function(dep) { return opts.normalize ? load.depMap[dep] : dep; }); tree = transformer.transformAny(tree); tree = compiler.transform(tree, load.name); var outputSource = compiler.write(tree, load.path); if (outputSource.match(/\$traceurRuntime/)) load.metadata.usesTraceurRuntimeGlobal = true; return Promise.resolve({ source: outputSource, sourceMap: compiler.getSourceMap() }); } else if (transpiler.createLanguageService) { var options = loader.typescriptOptions || {}; if (options.target === undefined) options.target = transpiler.ScriptTarget.ES5; options.module = transpiler.ModuleKind.System; var transpileOptions = { compilerOptions: options, renamedDependencies: load.depMap, fileName: load.path, moduleName: !opts.anonymous && load.name }; var transpiled = transpiler.transpileModule(load.source, transpileOptions); return Promise.resolve({ source: transpiled.outputText, sourceMap: transpiled.sourceMapText }); } else { if (versionCheck) { var babelVersion = transpiler.version; if (babelVersion.split('.')[0] > 5) console.log('Warning - using Babel ' + babelVersion + '. This version of SystemJS builder is designed to run against Babel 5.'); versionCheck = false; } var options = extend({}, loader.babelOptions || {}); options.modules = 'system'; if (opts.sourceMaps) options.sourceMap = true; if (load.metadata.sourceMap) options.inputSourceMap = load.metadata.sourceMap; options.filename = load.path; options.filenameRelative = load.name; options.sourceFileName = load.path; options.keepModuleIdExtensions = true; options.code = true; options.ast = false; options.moduleIds = !opts.anonymous; options.externalHelpers = true; if (transpiler.version.match(/^4/)) options.returnUsedHelpers = true; else if (transpiler.version.match(/^5\.[01234]\./)) options.metadataUsedHelpers = true; if (opts.normalize) options.resolveModuleSource = function(dep) { return load.depMap[dep] || dep; }; var output = transpiler.transform(load.source, options); var usedHelpers = output.usedHelpers || output.metadata && output.metadata.usedHelpers; if ((!options.optional || options.optional.indexOf('runtime') == -1) && usedHelpers.length) load.metadata.usesBabelHelpersGlobal = true; // pending Babel v5, we need to manually map the helpers if (options.optional && options.optional.indexOf('runtime') != -1) load.deps.forEach(function(dep) { if (dep.match(/^babel-runtime/)) output.code = output.code.replace(dep, load.depMap[dep]); }); // clear options for reuse delete options.filenameRelative; delete options.sourceFileName; return Promise.resolve({ source: output.code, sourceMap: output.map }); } }) .then(function(output) { if (opts.systemGlobal != 'System') output.source = output.source.replace(/System\.register\(/, opts.systemGlobal + '.register('); return output; }); };
CharlesSanford/personal-site
node_modules/systemjs-builder/compilers/esm.js
JavaScript
mit
8,859
#Get-SPOAzureADManifestKeyCredentials Creates the JSON snippet that is required for the manifest json file for Azure WebApplication / WebAPI apps ##Syntax ```powershell Get-SPOAzureADManifestKeyCredentials -CertPath <String> ``` ##Parameters Parameter|Type|Required|Description ---------|----|--------|----------- |CertPath|String|True|| ##Examples ###Example 1 ```powershell PS:> Get-SPOAzureADManifestKeyCredentials -CertPath .\mycert.cer ``` Output the JSON snippet which needs to be replaced in the application manifest file ###Example 2 ```powershell PS:> Get-SPOAzureADManifestKeyCredentials -CertPath .\mycert.cer | Set-Clipboard ``` Output the JSON snippet which needs to be replaced in the application manifest file and copies it to the clipboard
pschaeflein/PnP-PowerShell
Documentation/GetSPOAzureADManifestKeyCredentials.md
Markdown
mit
760
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.editor.orion.client.incremental.find; import elemental.dom.Text; import elemental.html.DivElement; import com.google.gwt.dom.client.Element; import com.google.inject.Inject; import org.eclipse.che.ide.api.editor.texteditor.EditorWidget; import org.eclipse.che.ide.editor.orion.client.OrionEditorWidget; import org.eclipse.che.ide.editor.orion.client.OrionResource; import org.eclipse.che.ide.status.message.StatusMessage; import org.eclipse.che.ide.status.message.StatusMessageObserver; import org.eclipse.che.ide.util.dom.Elements; import static org.eclipse.che.ide.util.StringUtils.isNullOrEmpty; /** * IncrementalFindReportStatusObserver listens editor status messages and filter messages * which contains information about incremental find state. It creates simple UI * for user notification about incremental find operation progress. * Note: incremental find can be straight or reverse. * * @author Alexander Andrienko */ public class IncrementalFindReportStatusObserver implements StatusMessageObserver { private final OrionResource orionResource; private EditorWidget editorWidget; private DivElement findDiv; @Inject public IncrementalFindReportStatusObserver(OrionResource orionResource) { this.orionResource = orionResource; } /** * Sets editor widget which contains text source to incremental search. * * @param editorWidget * editor widget with content to search. */ public void setEditorWidget(OrionEditorWidget editorWidget) { this.editorWidget = editorWidget; } /** * * Checks if {@code statusMessage} is incremental find message. * In case if this is true than create or update simple UI to display * message content, otherwise skip this message. * * @param statusMessage * editor status message. */ @Override public void update(StatusMessage statusMessage) { String message = statusMessage.getMessage(); boolean isIncrementalFindMessage = message.startsWith("Incremental find:") | message.startsWith("Reverse Incremental find:"); if (!message.isEmpty() && !isIncrementalFindMessage) { return; } Element editorElem = editorWidget.asWidget().getElement(); Element findDiv = createFindDiv(message); setStyle(message, findDiv); editorElem.appendChild(findDiv); if (isNullOrEmpty(message) && findDiv != null) { editorElem.removeChild(findDiv); this.findDiv = null; } } private Element createFindDiv(String message) { if (findDiv == null) { findDiv = Elements.createDivElement(); Text messageNode = Elements.createTextNode(message); findDiv.appendChild(messageNode); } findDiv.getFirstChild().setTextContent(message); return (Element)findDiv; } private void setStyle(String message, Element element) { if (message.endsWith("(not found)")) { element.addClassName(orionResource.getIncrementalFindStyle().incrementalFindContainer()); element.addClassName(orionResource.getIncrementalFindStyle().incrementalFindError()); } else { element.setClassName(orionResource.getIncrementalFindStyle().incrementalFindContainer()); } } }
cdietrich/che
plugins/plugin-orion/che-plugin-orion-editor/src/main/java/org/eclipse/che/ide/editor/orion/client/incremental/find/IncrementalFindReportStatusObserver.java
Java
epl-1.0
3,917
package fitnesse.testsystems.slim; import org.junit.Assert; import org.junit.Test; public class CustomComparatorRegistryTest { @Test public void useConverterFromCustomizing() { CustomComparatorRegistry customComparatorRegistry = new CustomComparatorRegistry(); customComparatorRegistry.addCustomComparator("prefix", new Comparator()); CustomComparator comparator = customComparatorRegistry.getCustomComparatorForPrefix("prefix"); Assert.assertTrue(comparator.matches("SAME", "same")); } static class Comparator implements CustomComparator { @Override public boolean matches(String actual, String expected) { return expected.equalsIgnoreCase(actual); } } }
rbevers/fitnesse
test/fitnesse/testsystems/slim/CustomComparatorRegistryTest.java
Java
epl-1.0
706
package fitnesse.wikitext.parser; import fitnesse.html.HtmlUtil; import java.util.Calendar; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FormattedExpression { public static final Pattern formatParser = Pattern.compile("^[ \\t]*((%[-#+ 0,(]*[0-9.]*([a-zA-Z])[^: \\t]*)[ \\t]*:)?[ \\t]*(.*)$"); private String input; private String format; private char conversion = '?'; private String expression; private Maybe<String> formatLocale; private Locale locale; public FormattedExpression(String input, Maybe<String> formatLocale) { this.input = input; this.formatLocale = formatLocale; } public Maybe<String> evaluate() { parseFormat(); selectLocale(); return !expression.isEmpty() ? evaluateAndFormat() : new Maybe<>(""); } private void selectLocale() { if(formatLocale.isNothing() || formatLocale.getValue().isEmpty()) { locale = Locale.getDefault(); } else { locale = Locale.forLanguageTag(formatLocale.getValue()); } } private void parseFormat() { Matcher match = formatParser.matcher(input); if (match.find()) { //match.group(1) is an outer group. format = (match.group(2) == null) ? null : match.group(2).trim(); conversion = (match.group(3) == null) ? '?' : match.group(3).trim().charAt(0); expression = (match.group(4) == null) ? "" : match.group(4).trim(); } else { format = null; expression = input.trim(); } } private Maybe<String> evaluateAndFormat() { Maybe<Double> evaluation = (new Expression(expression)).evaluate(); if (evaluation.isNothing()) { return Maybe.nothingBecause("invalid expression: " + expression); } Double result = evaluation.getValue(); Long iResult = Math.round(result); if (format == null) return new Maybe<>(result.equals(iResult.doubleValue()) ? iResult.toString() : result.toString()); if ("aAdhHoOxX".indexOf(conversion) >= 0) //...use the integer return new Maybe<>(String.format(locale, format, iResult)); if ("bB".indexOf(conversion) >= 0) //...use boolean return new Maybe<>(result == 0.0 ? "false" : "true"); if ("sScC".indexOf(conversion) >= 0) { //...string & character formatting; use the double String sString; boolean isInt = result.equals(iResult.doubleValue()); if (isInt) sString = String.format(locale, format, iResult.toString()); else sString = String.format(locale, format, result.toString()); return new Maybe<>(sString.replaceAll(" ", HtmlUtil.NBSP.html())); } if ("tT".indexOf(conversion) >= 0) { //...date Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(iResult); return new Maybe<>(String.format(locale, format, cal.getTime())); } if ("eEfgG".indexOf(conversion) >= 0) //...use the double return new Maybe<>(String.format(locale, format, result)); return Maybe.nothingBecause("invalid format: " + format); } }
jdufner/fitnesse
src/fitnesse/wikitext/parser/FormattedExpression.java
Java
epl-1.0
3,301
/* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "vmhdr.h" /* Clear out all allocated space. ** ** Written by Kiem-Phong Vo, [email protected], 01/16/94. */ int vmclear(Vmalloc_t * vm) { reg Seg_t *seg; reg Seg_t *next; reg Block_t *tp; reg size_t size, s; reg Vmdata_t *vd = vm->data; if (!(vd->mode & VM_TRUST)) { if (ISLOCK(vd, 0)) return -1; SETLOCK(vd, 0); } vd->free = vd->wild = NIL(Block_t *); vd->pool = 0; if (vd->mode & (VM_MTBEST | VM_MTDEBUG | VM_MTPROFILE)) { vd->root = NIL(Block_t *); for (s = 0; s < S_TINY; ++s) TINY(vd)[s] = NIL(Block_t *); for (s = 0; s <= S_CACHE; ++s) CACHE(vd)[s] = NIL(Block_t *); } for (seg = vd->seg; seg; seg = next) { next = seg->next; tp = SEGBLOCK(seg); size = seg->baddr - ((Vmuchar_t *) tp) - 2 * sizeof(Head_t); SEG(tp) = seg; SIZE(tp) = size; if ((vd->mode & (VM_MTLAST | VM_MTPOOL))) seg->free = tp; else { SIZE(tp) |= BUSY | JUNK; LINK(tp) = CACHE(vd)[C_INDEX(SIZE(tp))]; CACHE(vd)[C_INDEX(SIZE(tp))] = tp; } tp = BLOCK(seg->baddr); SEG(tp) = seg; SIZE(tp) = BUSY; } CLRLOCK(vd, 0); return 0; }
ellson/graphviz
lib/vmalloc/vmclear.c
C
epl-1.0
1,705
package net.minecraft.server; public class ItemSeedFood extends ItemFood { private int b; private int c; public ItemSeedFood(int i, int j, float f, int k, int l) { super(i, j, f, false); this.b = k; this.c = l; } public boolean interactWith(ItemStack itemstack, EntityHuman entityhuman, World world, int i, int j, int k, int l, float f, float f1, float f2) { final int clickedX = i, clickedY = j, clickedZ = k; // CraftBukkit if (l != 1) { return false; } else if (entityhuman.a(i, j, k, l, itemstack) && entityhuman.a(i, j + 1, k, l, itemstack)) { int i1 = world.getTypeId(i, j, k); if (i1 == this.c && world.isEmpty(i, j + 1, k)) { // CraftBukkit start // world.setTypeIdUpdate(i, j + 1, k, this.b); if (!ItemBlock.processBlockPlace(world, entityhuman, null, i, j + 1, k, this.b, 0, clickedX, clickedY, clickedZ)) { return false; } // CraftBukkit end --itemstack.count; return true; } else { return false; } } else { return false; } } }
JashGaming/JashCraft
src/main/java/net/minecraft/server/ItemSeedFood.java
Java
gpl-2.0
1,253
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "fullpipe/fullpipe.h" #include "fullpipe/objectnames.h" #include "fullpipe/constants.h" #include "fullpipe/gameloader.h" #include "fullpipe/motion.h" #include "fullpipe/scenes.h" #include "fullpipe/statics.h" #include "fullpipe/behavior.h" #include "fullpipe/interaction.h" namespace Fullpipe { void scene10_initScene(Scene *sc) { g_vars->scene10_gum = sc->getStaticANIObject1ById(ANI_GUM, -1); g_vars->scene10_packet = sc->getStaticANIObject1ById(ANI_PACHKA, -1); g_vars->scene10_packet2 = sc->getStaticANIObject1ById(ANI_PACHKA2, -1); g_vars->scene10_inflater = sc->getStaticANIObject1ById(ANI_NADUVATEL, -1); g_vars->scene10_ladder = sc->getPictureObjectById(PIC_SC10_LADDER, 0); g_fp->lift_setButton(sO_Level1, ST_LBN_1N); g_fp->lift_init(sc, QU_SC10_ENTERLIFT, QU_SC10_EXITLIFT); if (g_fp->getObjectState(sO_Inflater) == g_fp->getObjectEnumState(sO_Inflater, sO_WithGum)) { g_vars->scene10_hasGum = 1; } else { g_vars->scene10_hasGum = 0; g_vars->scene10_gum->hide(); } } bool sceneHandler10_inflaterIsBlind() { return g_vars->scene10_inflater->_movement && g_vars->scene10_inflater->_movement->_id == MV_NDV_BLOW2 && g_vars->scene10_inflater->_movement->_currDynamicPhaseIndex < 42; } int scene10_updateCursor() { g_fp->updateCursorCommon(); if (g_fp->_objectIdAtCursor == ANI_PACHKA || g_fp->_objectIdAtCursor == ANI_GUM) { if (g_fp->_cursorId == PIC_CSR_ITN) { if (g_vars->scene10_hasGum) g_fp->_cursorId = (sceneHandler10_inflaterIsBlind() != 0) ? PIC_CSR_ITN_RED : PIC_CSR_ITN_GREEN; else g_fp->_cursorId = PIC_CSR_DEFAULT; } } return g_fp->_cursorId; } void sceneHandler10_clickGum() { if (g_vars->scene10_hasGum) { if (sceneHandler10_inflaterIsBlind()) { if (g_vars->scene10_hasGum) { int x = g_vars->scene10_gum->_ox - 139; int y = g_vars->scene10_gum->_oy - 48; if (abs(x - g_fp->_aniMan->_ox) > 1 || abs(y - g_fp->_aniMan->_oy) > 1) { MessageQueue *mq = getCurrSceneSc2MotionController()->startMove(g_fp->_aniMan, x, y, 1, ST_MAN_RIGHT); if (mq) { ExCommand *ex = new ExCommand(0, 17, MSG_SC10_CLICKGUM, 0, 0, 0, 1, 0, 0, 0); ex->_excFlags = 2; mq->addExCommandToEnd(ex); postExCommand(g_fp->_aniMan->_id, 2, x, y, 0, -1); } } else { g_vars->scene10_hasGum = 0; chainQueue(QU_SC10_TAKEGUM, 1); } } } else { g_vars->scene10_inflater->changeStatics2(ST_NDV_SIT); if (g_fp->getObjectState(sO_Inflater) == g_fp->getObjectEnumState(sO_Inflater, sO_WithGum)) g_vars->scene10_inflater->startAnim(MV_NDV_DENIES, 0, -1); else g_vars->scene10_inflater->startAnim(MV_NDV_DENY_NOGUM, 0, -1); } } } void sceneHandler10_hideGum() { g_vars->scene10_gum->hide(); g_vars->scene10_packet->hide(); g_vars->scene10_packet2->hide(); } void sceneHandler10_showGum() { if (g_vars->scene10_hasGum) g_vars->scene10_gum->show1(-1, -1, -1, 0); g_vars->scene10_packet->show1(-1, -1, -1, 0); g_vars->scene10_packet2->show1(-1, -1, -1, 0); } int sceneHandler10(ExCommand *ex) { if (ex->_messageKind != 17) return 0; switch(ex->_messageNum) { case MSG_LIFT_CLOSEDOOR: g_fp->lift_closedoorSeq(); break; case MSG_LIFT_EXITLIFT: g_fp->lift_exitSeq(ex); break; case MSG_LIFT_STARTEXITQUEUE: g_fp->lift_startExitQueue(); break; case MSG_LIFT_CLICKBUTTON: g_fp->lift_clickButton(); break; case MSG_SC10_LADDERTOBACK: g_vars->scene10_ladder->_priority = 49; break; case MSG_SC10_LADDERTOFORE: g_vars->scene10_ladder->_priority = 0; break; case MSG_LIFT_GO: g_fp->lift_goAnimation(); break; case MSG_SC10_CLICKGUM: sceneHandler10_clickGum(); ex->_messageKind = 0; break; case MSG_SC10_HIDEGUM: sceneHandler10_hideGum(); break; case MSG_SC10_SHOWGUM: sceneHandler10_showGum(); break; case 64: g_fp->lift_hoverButton(ex); break; case 29: { if (g_fp->_currentScene->getPictureObjectIdAtPos(ex->_sceneClickX, ex->_sceneClickY) == PIC_SC10_LADDER) { handleObjectInteraction(g_fp->_aniMan, g_fp->_currentScene->getPictureObjectById(PIC_SC10_DTRUBA, 0), ex->_keyCode); ex->_messageKind = 0; return 0; } StaticANIObject *ani = g_fp->_currentScene->getStaticANIObjectAtPos(ex->_sceneClickX, ex->_sceneClickY); if (ani && ani->_id == ANI_LIFTBUTTON) { g_fp->lift_animateButton(ani); ex->_messageKind = 0; return 0; } } break; case 33: { int res = 0; if (g_fp->_aniMan2) { if (g_fp->_aniMan2->_ox < g_fp->_sceneRect.left + 200) g_fp->_currentScene->_x = g_fp->_aniMan2->_ox - g_fp->_sceneRect.left - 300; if (g_fp->_aniMan2->_ox > g_fp->_sceneRect.right - 200) g_fp->_currentScene->_x = g_fp->_aniMan2->_ox - g_fp->_sceneRect.right + 300; res = 1; } g_fp->_behaviorManager->updateBehaviors(); g_fp->startSceneTrack(); return res; } } return 0; } } // End of namespace Fullpipe
blorente/scummvm
engines/fullpipe/scenes/scene10.cpp
C++
gpl-2.0
5,863
/* * Copyright (C) 2010 Samsung Electronics * Minkyu Kang <[email protected]> * * Configuation settings for the SAMSUNG Universal (EXYNOS4210) board. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef __CONFIG_H #define __CONFIG_H /* * High Level Configuration Options * (easy to change) */ #define CONFIG_SAMSUNG 1 /* in a SAMSUNG core */ #define CONFIG_S5P 1 /* which is in a S5P Family */ #define CONFIG_EXYNOS4210 1 /* which is in a EXYNOS4210 */ #define CONFIG_UNIVERSAL 1 /* working with Universal */ #include <asm/arch/cpu.h> /* get chip and board defs */ #define CONFIG_ARCH_CPU_INIT #define CONFIG_DISPLAY_CPUINFO #define CONFIG_DISPLAY_BOARDINFO /* Keep L2 Cache Disabled */ #define CONFIG_SYS_L2CACHE_OFF 1 #define CONFIG_SYS_SDRAM_BASE 0x40000000 #define CONFIG_SYS_TEXT_BASE 0x44800000 /* input clock of PLL: Universal has 24MHz input clock at EXYNOS4210 */ #define CONFIG_SYS_CLK_FREQ_C210 24000000 #define CONFIG_SYS_CLK_FREQ CONFIG_SYS_CLK_FREQ_C210 #define CONFIG_SETUP_MEMORY_TAGS #define CONFIG_CMDLINE_TAG #define CONFIG_INITRD_TAG #define CONFIG_REVISION_TAG #define CONFIG_CMDLINE_EDITING /* Size of malloc() pool */ #define CONFIG_SYS_MALLOC_LEN (CONFIG_ENV_SIZE + (1 << 20)) /* select serial console configuration */ #define CONFIG_SERIAL_MULTI 1 #define CONFIG_SERIAL2 1 /* use SERIAL 2 */ #define CONFIG_BAUDRATE 115200 /* MMC */ #define CONFIG_GENERIC_MMC #define CONFIG_MMC #define CONFIG_SDHCI #define CONFIG_S5P_SDHCI /* PWM */ #define CONFIG_PWM 1 /* It should define before config_cmd_default.h */ #define CONFIG_SYS_NO_FLASH 1 /* Command definition */ #include <config_cmd_default.h> #undef CONFIG_CMD_FPGA #undef CONFIG_CMD_MISC #undef CONFIG_CMD_NET #undef CONFIG_CMD_NFS #undef CONFIG_CMD_XIMG #define CONFIG_CMD_CACHE #define CONFIG_CMD_ONENAND #define CONFIG_CMD_MTDPARTS #define CONFIG_CMD_MMC #define CONFIG_CMD_FAT #define CONFIG_BOOTDELAY 1 #define CONFIG_ZERO_BOOTDELAY_CHECK #define CONFIG_MTD_DEVICE #define CONFIG_MTD_PARTITIONS /* Actual modem binary size is 16MiB. Add 2MiB for bad block handling */ #define MTDIDS_DEFAULT "onenand0=samsung-onenand" #define MTDPARTS_DEFAULT "mtdparts=samsung-onenand:"\ "128k(s-boot)"\ ",896k(bootloader)"\ ",256k(params)"\ ",2816k(config)"\ ",8m(csa)"\ ",7m(kernel)"\ ",1m(log)"\ ",12m(modem)"\ ",60m(qboot)"\ ",-(UBI)\0" #define NORMAL_MTDPARTS_DEFAULT MTDPARTS_DEFAULT #define MBRPARTS_DEFAULT "20M(permanent)"\ ",20M(boot)"\ ",1G(system)"\ ",100M(swap)"\ ",-(UMS)\0" #define CONFIG_BOOTARGS "Please use defined boot" #define CONFIG_BOOTCOMMAND "run mmcboot" #define CONFIG_DEFAULT_CONSOLE "console=ttySAC2,115200n8\0" #define CONFIG_ENV_UBI_MTD " ubi.mtd=${ubiblock} ubi.mtd=4 ubi.mtd=7" #define CONFIG_BOOTBLOCK "10" #define CONFIG_UBIBLOCK "9" #define CONFIG_ENV_UBIFS_OPTION " rootflags=bulk_read,no_chk_data_crc " #define CONFIG_ENV_FLASHBOOT CONFIG_ENV_UBI_MTD CONFIG_ENV_UBIFS_OPTION \ "${mtdparts}" #define CONFIG_ENV_COMMON_BOOT "${console} ${meminfo}" #define CONFIG_ENV_OVERWRITE #define CONFIG_SYS_CONSOLE_INFO_QUIET #define CONFIG_SYS_CONSOLE_IS_IN_ENV #define CONFIG_EXTRA_ENV_SETTINGS \ "updateb=" \ "onenand erase 0x0 0x100000;" \ "onenand write 0x42008000 0x0 0x100000\0" \ "updatek=" \ "onenand erase 0xc00000 0x500000;" \ "onenand write 0x41008000 0xc00000 0x500000\0" \ "bootk=" \ "run loaduimage; bootm 0x40007FC0\0" \ "updatemmc=" \ "mmc boot 0 1 1 1; mmc write 0 0x42008000 0 0x200;" \ "mmc boot 0 1 1 0\0" \ "updatebackup=" \ "mmc boot 0 1 1 2; mmc write 0 0x42100000 0 0x200;" \ "mmc boot 0 1 1 0\0" \ "updatebootb=" \ "mmc read 0 0x42100000 0x80 0x200; run updatebackup\0" \ "lpj=lpj=3981312\0" \ "ubifsboot=" \ "set bootargs root=ubi0!rootfs rootfstype=ubifs ${lpj} " \ CONFIG_ENV_FLASHBOOT " ${opts} ${lcdinfo} " \ CONFIG_ENV_COMMON_BOOT "; run bootk\0" \ "tftpboot=" \ "set bootargs root=ubi0!rootfs rootfstype=ubifs " \ CONFIG_ENV_FLASHBOOT " ${opts} ${lcdinfo} " \ CONFIG_ENV_COMMON_BOOT \ "; tftp 0x40007FC0 uImage; bootm 0x40007FC0\0" \ "nfsboot=" \ "set bootargs root=/dev/nfs rw " \ "nfsroot=${nfsroot},nolock,tcp " \ "ip=${ipaddr}:${serverip}:${gatewayip}:" \ "${netmask}:generic:usb0:off " CONFIG_ENV_COMMON_BOOT \ "; run bootk\0" \ "ramfsboot=" \ "set bootargs root=/dev/ram0 rw rootfstype=ext2 " \ "${console} ${meminfo} " \ "initrd=0x43000000,8M ramdisk=8192\0" \ "mmcboot=" \ "set bootargs root=/dev/mmcblk${mmcdev}p${mmcrootpart} " \ "${lpj} rootwait ${console} ${meminfo} ${opts} ${lcdinfo}; " \ "run loaduimage; bootm 0x40007FC0\0" \ "bootchart=set opts init=/sbin/bootchartd; run bootcmd\0" \ "boottrace=setenv opts initcall_debug; run bootcmd\0" \ "mmcoops=mmc read 0 0x40000000 0x40 8; md 0x40000000 0x400\0" \ "verify=n\0" \ "rootfstype=ext4\0" \ "console=" CONFIG_DEFAULT_CONSOLE \ "mtdparts=" MTDPARTS_DEFAULT \ "mbrparts=" MBRPARTS_DEFAULT \ "meminfo=crashkernel=32M@0x50000000\0" \ "nfsroot=/nfsroot/arm\0" \ "bootblock=" CONFIG_BOOTBLOCK "\0" \ "ubiblock=" CONFIG_UBIBLOCK" \0" \ "ubi=enabled\0" \ "loaduimage=fatload mmc ${mmcdev}:${mmcbootpart} 0x40007FC0 uImage\0" \ "mmcdev=0\0" \ "mmcbootpart=2\0" \ "mmcrootpart=3\0" \ "opts=always_resume=1" /* Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP /* undef to save memory */ #define CONFIG_SYS_HUSH_PARSER /* use "hush" command parser */ #define CONFIG_SYS_PROMPT "Universal # " #define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */ #define CONFIG_SYS_PBSIZE 384 /* Print Buffer Size */ #define CONFIG_SYS_MAXARGS 16 /* max number of command args */ /* Boot Argument Buffer Size */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* memtest works on */ #define CONFIG_SYS_MEMTEST_START CONFIG_SYS_SDRAM_BASE #define CONFIG_SYS_MEMTEST_END (CONFIG_SYS_SDRAM_BASE + 0x5000000) #define CONFIG_SYS_LOAD_ADDR (CONFIG_SYS_SDRAM_BASE + 0x4800000) #define CONFIG_SYS_HZ 1000 /* Stack sizes */ #define CONFIG_STACKSIZE (256 << 10) /* regular stack 256KB */ /* Universal has 2 banks of DRAM */ #define CONFIG_NR_DRAM_BANKS 2 #define PHYS_SDRAM_1 CONFIG_SYS_SDRAM_BASE /* LDDDR2 DMC 0 */ #define PHYS_SDRAM_1_SIZE (256 << 20) /* 256 MB in CS 0 */ #define PHYS_SDRAM_2 0x50000000 /* LPDDR2 DMC 1 */ #define PHYS_SDRAM_2_SIZE (256 << 20) /* 256 MB in CS 0 */ #define CONFIG_SYS_MEM_TOP_HIDE (1 << 20) /* ram console */ #define CONFIG_SYS_MONITOR_BASE 0x00000000 #define CONFIG_SYS_MONITOR_LEN (256 << 10) /* Reserve 2 sectors */ #define CONFIG_USE_ONENAND_BOARD_INIT #define CONFIG_SAMSUNG_ONENAND #define CONFIG_SYS_ONENAND_BASE 0x0C000000 #define CONFIG_ENV_IS_IN_MMC 1 #define CONFIG_SYS_MMC_ENV_DEV 0 #define CONFIG_ENV_SIZE 4096 #define CONFIG_ENV_OFFSET ((32 - 4) << 10)/* 32KiB - 4KiB */ #define CONFIG_DOS_PARTITION 1 #define CONFIG_SYS_INIT_SP_ADDR (CONFIG_SYS_LOAD_ADDR - GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_CACHELINE_SIZE 32 #include <asm/arch/gpio.h> /* * I2C Settings */ #define CONFIG_SOFT_I2C_GPIO_SCL exynos4_gpio_part1_get_nr(b, 7) #define CONFIG_SOFT_I2C_GPIO_SDA exynos4_gpio_part1_get_nr(b, 6) #define CONFIG_SOFT_I2C #define CONFIG_SOFT_I2C_READ_REPEATED_START #define CONFIG_SYS_I2C_SPEED 50000 #define CONFIG_I2C_MULTI_BUS #define CONFIG_SYS_MAX_I2C_BUS 7 #define CONFIG_PMIC #define CONFIG_PMIC_I2C #define CONFIG_PMIC_MAX8998 #define CONFIG_USB_GADGET #define CONFIG_USB_GADGET_S3C_UDC_OTG #define CONFIG_USB_GADGET_DUALSPEED #endif /* __CONFIG_H */
itgb/opCloudRouter
qca/src/u-boot/include/configs/s5pc210_universal.h
C
gpl-2.0
8,287
//@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact H. Carter Edwards ([email protected]) // // ************************************************************************ //@HEADER #ifndef KOKKOS_GLOBAL_TO_LOCAL_IDS_HPP #define KOKKOS_GLOBAL_TO_LOCAL_IDS_HPP #include <Kokkos_Core.hpp> #include <Kokkos_UnorderedMap.hpp> #include <vector> #include <algorithm> #include <iomanip> #include <impl/Kokkos_Timer.hpp> // This test will simulate global ids namespace G2L { static const unsigned begin_id_size = 256u; static const unsigned end_id_size = 1u << 25; static const unsigned id_step = 2u; //use to help generate global ids union helper { uint32_t word; uint8_t byte[4]; }; //generate a unique global id from the local id template <typename Device> struct generate_ids { typedef Device execution_space; typedef typename execution_space::size_type size_type; typedef Kokkos::View<uint32_t*,execution_space> local_id_view; local_id_view local_2_global; generate_ids( local_id_view & ids) : local_2_global(ids) { Kokkos::parallel_for(local_2_global.size(), *this); } KOKKOS_INLINE_FUNCTION void operator()(size_type i) const { helper x = {static_cast<uint32_t>(i)}; // shuffle the bytes of i to create a unique, semi-random global_id x.word = ~x.word; uint8_t tmp = x.byte[3]; x.byte[3] = x.byte[1]; x.byte[1] = tmp; tmp = x.byte[2]; x.byte[2] = x.byte[0]; x.byte[0] = tmp; local_2_global[i] = x.word; } }; // fill a map of global_id -> local_id template <typename Device> struct fill_map { typedef Device execution_space; typedef typename execution_space::size_type size_type; typedef Kokkos::View<const uint32_t*,execution_space, Kokkos::MemoryRandomAccess> local_id_view; typedef Kokkos::UnorderedMap<uint32_t,size_type,execution_space> global_id_view; global_id_view global_2_local; local_id_view local_2_global; fill_map( global_id_view gIds, local_id_view lIds) : global_2_local(gIds) , local_2_global(lIds) { Kokkos::parallel_for(local_2_global.size(), *this); } KOKKOS_INLINE_FUNCTION void operator()(size_type i) const { global_2_local.insert( local_2_global[i], i); } }; // check that the global id is found and that it maps to the local id template <typename Device> struct find_test { typedef Device execution_space; typedef typename execution_space::size_type size_type; typedef Kokkos::View<const uint32_t*,execution_space, Kokkos::MemoryRandomAccess> local_id_view; typedef Kokkos::UnorderedMap<const uint32_t, const size_type,execution_space> global_id_view; global_id_view global_2_local; local_id_view local_2_global; typedef size_t value_type; find_test( global_id_view gIds, local_id_view lIds, value_type & num_errors) : global_2_local(gIds) , local_2_global(lIds) { Kokkos::parallel_reduce(local_2_global.size(), *this, num_errors); } KOKKOS_INLINE_FUNCTION void init(value_type & v) const { v = 0; } KOKKOS_INLINE_FUNCTION void join(volatile value_type & dst, volatile value_type const & src) const { dst += src; } KOKKOS_INLINE_FUNCTION void operator()(size_type i, value_type & num_errors) const { uint32_t index = global_2_local.find( local_2_global[i] ); if ( !global_2_local.valid_at(index) || global_2_local.key_at(index) != local_2_global[i] || global_2_local.value_at(index) != i) ++num_errors; } }; // run test template <typename Device> size_t test_global_to_local_ids(unsigned num_ids, unsigned capacity, unsigned num_find_iterations) { typedef Device execution_space; typedef typename execution_space::size_type size_type; typedef Kokkos::View<uint32_t*,execution_space> local_id_view; typedef Kokkos::UnorderedMap<uint32_t,size_type,execution_space> global_id_view; double elasped_time = 0; Kokkos::Impl::Timer timer; local_id_view local_2_global("local_ids", num_ids); global_id_view global_2_local(capacity); int shiftw = 15; //create elasped_time = timer.seconds(); std::cout << std::setw(shiftw) << "allocate: " << elasped_time << std::endl; timer.reset(); // generate unique ids { generate_ids<Device> gen(local_2_global); } // generate elasped_time = timer.seconds(); std::cout << std::setw(shiftw) << "generate: " << elasped_time << std::endl; timer.reset(); { fill_map<Device> fill(global_2_local, local_2_global); } // fill elasped_time = timer.seconds(); std::cout << std::setw(shiftw) << "fill: " << elasped_time << std::endl; timer.reset(); size_t num_errors = global_2_local.failed_insert(); if (num_errors == 0u) { for (unsigned i=0; i<num_find_iterations; ++i) { find_test<Device> find(global_2_local, local_2_global,num_errors); } // find elasped_time = timer.seconds(); std::cout << std::setw(shiftw) << "lookup: " << elasped_time << std::endl; } else { std::cout << " !!! Fill Failed !!!" << std::endl; } return num_errors; } template <typename Device> size_t run_test(unsigned num_ids, unsigned num_find_iterations) { // expect to fail unsigned capacity = (num_ids*2u)/3u; std::cout << " 66% of needed capacity (should fail)" << std::endl; test_global_to_local_ids<Device>(num_ids, capacity, num_find_iterations); //should not fail std::cout << " 100% of needed capacity" << std::endl; capacity = num_ids; size_t num_errors = test_global_to_local_ids<Device>(num_ids, capacity, num_find_iterations); //should not fail std::cout << " 150% of needed capacity" << std::endl; capacity = (num_ids*3u)/2u; num_errors += test_global_to_local_ids<Device>(num_ids, capacity, num_find_iterations); return num_errors; } } // namespace G2L #endif //KOKKOS_GLOBAL_TO_LOCAL_IDS_HPP
crtrott/lammps
lib/kokkos/example/global_2_local_ids/G2L.hpp
C++
gpl-2.0
7,594
/* Copyright (c) 2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _WCNSS_WLAN_H_ #define _WCNSS_WLAN_H_ #include <linux/device.h> enum wcnss_opcode { WCNSS_WLAN_SWITCH_OFF = 0, WCNSS_WLAN_SWITCH_ON, }; struct wcnss_wlan_config { int use_48mhz_xo; }; #define WCNSS_WLAN_IRQ_INVALID -1 struct device *wcnss_wlan_get_device(void); struct resource *wcnss_wlan_get_memory_map(struct device *dev); int wcnss_wlan_get_dxe_tx_irq(struct device *dev); int wcnss_wlan_get_dxe_rx_irq(struct device *dev); void wcnss_wlan_register_pm_ops(struct device *dev, const struct dev_pm_ops *pm_ops); void wcnss_wlan_unregister_pm_ops(struct device *dev, const struct dev_pm_ops *pm_ops); struct platform_device *wcnss_get_platform_device(void); struct wcnss_wlan_config *wcnss_get_wlan_config(void); int wcnss_wlan_power(struct device *dev, struct wcnss_wlan_config *cfg, enum wcnss_opcode opcode); #define wcnss_wlan_get_drvdata(dev) dev_get_drvdata(dev) #define wcnss_wlan_set_drvdata(dev, data) dev_set_drvdata((dev), (data)) #endif /* _WCNSS_WLAN_H_ */
jomeister15/ICS-SGH-I727-kernel
include/linux/wcnss_wlan.h
C
gpl-2.0
1,535
/* ---------------------------------------------------------------------- LIGGGHTS - LAMMPS Improved for General Granular and Granular Heat Transfer Simulations LIGGGHTS is part of the CFDEMproject www.liggghts.com | www.cfdem.com Christoph Kloss, [email protected] Copyright 2009-2012 JKU Linz Copyright 2012- DCS Computing GmbH, Linz LIGGGHTS is based on LAMMPS LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] This software is distributed under the GNU General Public License. See the README file in the top-level directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author for SPH: Andreas Aigner (CD Lab Particulate Flow Modelling, JKU) [email protected] ------------------------------------------------------------------------- */ #include "math.h" #include "mpi.h" #include "string.h" #include "stdlib.h" #include "fix_sph_density_summation.h" #include "update.h" #include "respa.h" #include "atom.h" #include "force.h" #include "modify.h" #include "pair.h" #include "comm.h" #include "neighbor.h" #include "neigh_list.h" #include "neigh_request.h" #include "memory.h" #include "error.h" #include "sph_kernels.h" #include "fix_property_atom.h" #include "timer.h" using namespace LAMMPS_NS; using namespace FixConst; /* ---------------------------------------------------------------------- */ FixSPHDensitySum::FixSPHDensitySum(LAMMPS *lmp, int narg, char **arg) : FixSph(lmp, narg, arg) { int iarg = 0; if (iarg+3 > narg) error->fix_error(FLERR,this,"Not enough input arguments"); iarg += 3; while (iarg < narg) { // kernel style if (strcmp(arg[iarg],"sphkernel") == 0) { if (iarg+2 > narg) error->fix_error(FLERR,this,"Illegal use of keyword 'sphkernel'. Not enough input arguments"); if(kernel_style) delete []kernel_style; kernel_style = new char[strlen(arg[iarg+1])+1]; strcpy(kernel_style,arg[iarg+1]); // check uniqueness of kernel IDs int flag = SPH_KERNEL_NS::sph_kernels_unique_id(); if(flag < 0) error->fix_error(FLERR,this,"Cannot proceed, sph kernels need unique IDs, check all sph_kernel_* files"); // get kernel id kernel_id = SPH_KERNEL_NS::sph_kernel_id(kernel_style); if(kernel_id < 0) error->fix_error(FLERR,this,"Unknown sph kernel"); iarg += 2; } else error->fix_error(FLERR,this,"Wrong keyword."); } } /* ---------------------------------------------------------------------- */ FixSPHDensitySum::~FixSPHDensitySum() { } /* ---------------------------------------------------------------------- */ int FixSPHDensitySum::setmask() { int mask = 0; mask |= POST_INTEGRATE; mask |= POST_INTEGRATE_RESPA; return mask; } /* ---------------------------------------------------------------------- */ void FixSPHDensitySum::init() { FixSph::init(); // check if there is an sph/pressure fix present // must come before me, because // a - it needs the rho for the pressure calculation // b - i have to do the forward comm to have updated ghost properties int pres = -1; int me = -1; for(int i = 0; i < modify->nfix; i++) { if(strcmp("sph/density/summation",modify->fix[i]->style)) { me = i; } if(strncmp("sph/pressure",modify->fix[i]->style,12) == 0) { pres = i; break; } } if(me == -1 && pres >= 0) error->fix_error(FLERR,this,"Fix sph/pressure has to be defined after sph/density/summation \n"); if(pres == -1) error->fix_error(FLERR,this,"Requires to define a fix sph/pressure also \n"); } /* ---------------------------------------------------------------------- */ void FixSPHDensitySum::post_integrate() { //template function for using per atom or per atomtype smoothing length if (mass_type) post_integrate_eval<1>(); else post_integrate_eval<0>(); } /* ---------------------------------------------------------------------- */ template <int MASSFLAG> void FixSPHDensitySum::post_integrate_eval() { int i,j,ii,jj,inum,jnum,itype,jtype; double xtmp,ytmp,ztmp,delx,dely,delz,rsq,r,s,W; double sli,sliInv,slj,slCom,slComInv,cut,imass,jmass; int *ilist,*jlist,*numneigh,**firstneigh; double **x = atom->x; int *mask = atom->mask; double *rho = atom->rho; int newton_pair = force->newton_pair; int *type = atom->type; double *mass = atom->mass; double *rmass = atom->rmass; updatePtrs(); // get sl // reset and add rho contribution of self int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) { if (MASSFLAG) { itype = type[i]; sli = sl[itype-1]; imass = mass[itype]; } else { sli = sl[i]; imass = rmass[i]; } sliInv = 1./sli; // this gets a value for W at self, perform error check W = SPH_KERNEL_NS::sph_kernel(kernel_id,0.,sli,sliInv); if (W < 0.) { fprintf(screen,"s = %f, W = %f\n",s,W); error->one(FLERR,"Illegal kernel used, W < 0"); } // add contribution of self rho[i] = W * imass; } // need updated ghost positions and self contributions timer->stamp(); comm->forward_comm(); timer->stamp(TIME_COMM); // loop over neighbors of my atoms inum = list->inum; ilist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; for (ii = 0; ii < inum; ii++) { i = ilist[ii]; if (!(mask[i] & groupbit)) continue; xtmp = x[i][0]; ytmp = x[i][1]; ztmp = x[i][2]; jlist = firstneigh[i]; jnum = numneigh[i]; if (MASSFLAG) { itype = type[i]; imass = mass[itype]; } else { imass = rmass[i]; sli = sl[i]; } for (jj = 0; jj < jnum; jj++) { j = jlist[jj]; if (!(mask[j] & groupbit)) continue; if (MASSFLAG) { jtype = type[j]; jmass = mass[jtype]; slCom = slComType[itype][jtype]; } else { jmass = rmass[j]; slj = sl[j]; slCom = interpDist(sli,slj); } slComInv = 1./slCom; cut = slCom*kernel_cut; delx = xtmp - x[j][0]; dely = ytmp - x[j][1]; delz = ztmp - x[j][2]; rsq = delx*delx + dely*dely + delz*delz; if (rsq >= cut*cut) continue; // calculate distance and normalized distance r = sqrt(rsq); slComInv = 1./slCom; s = r*slComInv; // this gets a value for W at self, perform error check W = SPH_KERNEL_NS::sph_kernel(kernel_id,s,slCom,slComInv); if (W < 0.) { fprintf(screen,"s = %f, W = %f\n",s,W); error->one(FLERR,"Illegal kernel used, W < 0"); } // add contribution of neighbor // have a half neigh list, so do it for both if necessary rho[i] += W * jmass; if (newton_pair || j < nlocal) rho[j] += W * imass; } } // rho is now correct, send to ghosts timer->stamp(); comm->forward_comm(); timer->stamp(TIME_COMM); }
tm1249wk/WASHLIGGGHTS-2.3.7
src/fix_sph_density_summation.cpp
C++
gpl-2.0
7,151
### GIVEN Given /^I have no tags$/ do # Tag.delete_all if Tag.count > 1 # silence_warnings {load "#{Rails.root}/app/models/fandom.rb"} end Given /^basic tags$/ do step %{the default ratings exist} step %{the basic warnings exist} Fandom.where(name: "No Fandom", canonical: true).first_or_create step %{the basic categories exist} step %{all indexing jobs have been run} end Given /^the default ratings exist$/ do # TODO: "Not Rated" should be adult, to match the behavior in production, but # there are many tests that rely on being able to view a "Not Rated" work # without clicking through the adult content warning. So until those tests # are fixed, we leave "Not Rated" as a non-adult rating. [ ArchiveConfig.RATING_DEFAULT_TAG_NAME, ArchiveConfig.RATING_GENERAL_TAG_NAME, ArchiveConfig.RATING_TEEN_TAG_NAME ].each do |rating| Rating.find_or_create_by!(name: rating, canonical: true) end [ ArchiveConfig.RATING_MATURE_TAG_NAME, ArchiveConfig.RATING_EXPLICIT_TAG_NAME ].each do |rating| Rating.find_or_create_by!(name: rating, canonical: true, adult: true) end end Given /^the basic warnings exist$/ do warnings = [ArchiveConfig.WARNING_DEFAULT_TAG_NAME, ArchiveConfig.WARNING_NONE_TAG_NAME] warnings.each do |warning| ArchiveWarning.find_or_create_by!(name: warning, canonical: true) end end Given /^all warnings exist$/ do step %{the basic warnings exist} warnings = [ArchiveConfig.WARNING_VIOLENCE_TAG_NAME, ArchiveConfig.WARNING_DEATH_TAG_NAME, ArchiveConfig.WARNING_NONCON_TAG_NAME, ArchiveConfig.WARNING_CHAN_TAG_NAME] warnings.each do |warning| ArchiveWarning.find_or_create_by!(name: warning, canonical: true) end end Given /^the basic categories exist$/ do %w(Gen Other F/F Multi F/M M/M).each do |category| Category.find_or_create_by!(name: category, canonical: true) end end Given /^I have a canonical "([^\"]*)" fandom tag named "([^\"]*)"$/ do |media, fandom| fandom = Fandom.find_or_create_by_name(fandom) fandom.update(canonical: true) media = Media.find_or_create_by_name(media) media.update(canonical: true) fandom.add_association media end Given /^I add the fandom "([^\"]*)" to the character "([^\"]*)"$/ do |fandom, character| char = Character.find_or_create_by(name: character) fand = Fandom.find_or_create_by_name(fandom) char.add_association(fand) end Given /^a canonical character "([^\"]*)" in fandom "([^\"]*)"$/ do |character, fandom| char = Character.where(name: character, canonical: true).first_or_create fand = Fandom.where(name: fandom, canonical: true).first_or_create char.add_association(fand) end Given /^a canonical relationship "([^\"]*)" in fandom "([^\"]*)"$/ do |relationship, fandom| rel = Relationship.where(name: relationship, canonical: true).first_or_create fand = Fandom.where(name: fandom, canonical: true).first_or_create rel.add_association(fand) end Given /^a (non-?canonical|canonical) (\w+) "([^\"]*)"$/ do |canonical_status, tag_type, tag_name| t = tag_type.classify.constantize.find_or_create_by_name(tag_name) t.canonical = canonical_status == "canonical" t.save end Given /^a synonym "([^\"]*)" of the tag "([^\"]*)"$/ do |synonym, merger| merger = Tag.find_by_name(merger) merger_type = merger.type synonym = merger_type.classify.constantize.find_or_create_by(name: synonym) synonym.reload.merger = merger synonym.save end Given /^"([^\"]*)" is a metatag of the (\w+) "([^\"]*)"$/ do |metatag, tag_type, tag| tag = tag_type.classify.constantize.find_or_create_by_name(tag) metatag = tag_type.classify.constantize.find_or_create_by_name(metatag) tag.meta_tags << metatag tag.save end Given /^I am logged in as a tag wrangler$/ do step "I start a new session" username = "wrangler" step %{I am logged in as "#{username}"} user = User.find_by(login: username) role = Role.find_or_create_by(name: "tag_wrangler") user.roles = [role] end Given /^the tag wrangler "([^\"]*)" with password "([^\"]*)" is wrangler of "([^\"]*)"$/ do |user, password, fandomname| tw = User.find_by(login: user) if tw.blank? tw = FactoryBot.create(:user, login: user, password: password) else tw.password = password tw.password_confirmation = password tw.save end role = Role.find_or_create_by(name: "tag_wrangler") tw.roles = [role] step %{I am logged in as "#{user}" with password "#{password}"} fandom = Fandom.where(name: fandomname, canonical: true).first_or_create visit tag_wranglers_url fill_in "tag_fandom_string", with: fandomname click_button "Assign" end Given /^a tag "([^\"]*)" with(?: (\d+))? comments$/ do |tagname, n_comments| tag = Fandom.find_or_create_by_name(tagname) step "I start a new session" n_comments = 3 if n_comments.blank? || n_comments.zero? FactoryBot.create_list(:comment, n_comments.to_i, :on_tag, commentable: tag) end Given /^(?:a|the) canonical(?: "([^"]*)")? fandom "([^"]*)" with (\d+) works$/ do |media, tag_name, number_of_works| fandom = FactoryBot.create(:fandom, name: tag_name, canonical: true) fandom.add_association(Media.find_by(name: media)) if media.present? number_of_works.to_i.times do FactoryBot.create(:work, fandom_string: tag_name) end step %(the periodic filter count task is run) end Given /^a period-containing tag "([^\"]*)" with(?: (\d+))? comments$/ do |tagname, n_comments| tag = Fandom.find_or_create_by_name(tagname) step "I start a new session" n_comments = 3 if n_comments.blank? || n_comments.zero? FactoryBot.create_list(:comment, n_comments.to_i, :on_tag, commentable: tag) end Given /^the unsorted tags setup$/ do 30.times do |i| UnsortedTag.find_or_create_by_name("unsorted tag #{i}") end end Given /^the tag wrangling setup$/ do step %{basic tags} step %{a media exists with name: "TV Shows", canonical: true} step %{I am logged in as a random user} step %{I post the work "Revenge of the Sith 2" with fandom "Star Wars, Stargate SG-1" with character "Daniel Jackson" with second character "Jack O'Neil" with rating "Not Rated" with relationship "JackDaniel"} step %{The periodic tag count task is run} step %{I flush the wrangling sidebar caches} end Given /^I have posted a Wrangling Guideline?(?: titled "([^\"]*)")?$/ do |title| step %{I am logged in as an admin} visit new_wrangling_guideline_path if title fill_in("Guideline text", with: "This is a page about how we wrangle things.") fill_in("Title", with: title) click_button("Post") else step %{I make a 1st Wrangling Guideline} end end Given(/^the following typed tags exists$/) do |table| table.hashes.each do |hash| type = hash["type"].downcase.to_sym hash.delete("type") FactoryBot.create(type, hash) end end Given /^the tag "([^"]*)" does not exist$/ do |tag_name| tag = Tag.find_by_name(tag_name) tag.destroy if tag.present? end ### WHEN When /^the periodic tag count task is run$/i do Tag.write_redis_to_database end When /^the periodic filter count task is run$/i do FilterCount.update_counts_for_small_queue FilterCount.update_counts_for_large_queue end When /^I check the canonical option for the tag "([^"]*)"$/ do |tagname| tag = Tag.find_by(name: tagname) check("canonicals_#{tag.id}") end When /^I select "([^"]*)" for the unsorted tag "([^"]*)"$/ do |type, tagname| tag = Tag.find_by(name: tagname) select(type, from: "tags[#{tag.id}]") end When /^I check the (?:mass )?wrangling option for "([^"]*)"$/ do |tagname| tag = Tag.find_by(name: tagname) check("selected_tags_#{tag.id}") end When "I edit the tag {string}" do |tag| tag = Tag.find_by!(name: tag) visit tag_path(tag) within(".header") do click_link("Edit") end end When /^I view the tag "([^\"]*)"$/ do |tag| tag = Tag.find_by!(name: tag) visit tag_path(tag) end When /^I create the fandom "([^\"]*)" with id (\d+)$/ do |name, id| tag = Fandom.new(name: name) tag.id = id.to_i tag.canonical = true tag.save end When /^I set up the comment "([^"]*)" on the tag "([^"]*)"$/ do |comment_text, tag| tag = Tag.find_by!(name: tag) visit tag_url(tag) click_link(" comment") fill_in("Comment", with: comment_text) end When /^I post the comment "([^"]*)" on the tag "([^"]*)"$/ do |comment_text, tag| step "I set up the comment \"#{comment_text}\" on the tag \"#{tag}\"" click_button("Comment") end When /^I post the comment "([^"]*)" on the period-containing tag "([^"]*)"$/ do |comment_text, tag| step "I am on the search tags page" fill_in("tag_search", with: tag) click_button "Search tags" click_link(tag) click_link(" comment") fill_in("Comment", with: comment_text) click_button("Comment") end When /^I post the comment "([^"]*)" on the tag "([^"]*)" via web$/ do |comment_text, tag| step %{I view the tag "#{tag}"} step %{I follow " comments"} step %{I fill in "Comment" with "#{comment_text}"} step %{I press "Comment"} step %{I should see "Comment created!"} end When /^I view tag wrangling discussions$/ do step %{I follow "Tag Wrangling"} step %{I follow "Discussion"} end When /^I add "([^\"]*)" to my favorite tags$/ do |tag| step %{I view the "#{tag}" works index} step %{I press "Favorite Tag"} end When /^I remove "([^\"]*)" from my favorite tags$/ do |tag| step %{I view the "#{tag}" works index} step %{I press "Unfavorite Tag"} end When /^the tag "([^\"]*)" is decanonized$/ do |tag| tag = Tag.find_by!(name: tag) tag.canonical = false tag.save end When /^the tag "([^"]*)" is canonized$/ do |tag| tag = Tag.find_by!(name: tag) tag.canonical = true tag.save end When /^I make a(?: (\d+)(?:st|nd|rd|th)?)? Wrangling Guideline$/ do |n| n = 1 if n.zero? visit new_wrangling_guideline_path fill_in("Guideline text", with: "Number #{n} posted Wrangling Guideline, this is.") fill_in("Title", with: "Number #{n} Wrangling Guideline") click_button("Post") end When /^(\d+) Wrangling Guidelines? exists?$/ do |n| (1..n).each do |i| FactoryBot.create(:wrangling_guideline, id: i) end end When /^I flush the wrangling sidebar caches$/ do [Fandom, Character, Relationship, Freeform].each do |klass| Rails.cache.delete("/wrangler/counts/sidebar/#{klass}") end end When /^I syn the tag "([^"]*)" to "([^"]*)"$/ do |syn, merger| syn = Tag.find_by(name: syn) visit edit_tag_path(syn) fill_in("Synonym of", with: merger) click_button("Save changes") end When /^I de-syn the tag "([^"]*)" from "([^"]*)"$/ do |syn, merger| merger = Tag.find_by(name: merger) syn_id = Tag.find_by(name: syn).id visit edit_tag_path(merger) check("child_Merger_associations_to_remove_#{syn_id}") click_button("Save changes") end When /^I subtag the tag "([^"]*)" to "([^"]*)"$/ do |subtag, metatag| subtag = Tag.find_by(name: subtag) visit edit_tag_path(subtag) fill_in("Add MetaTags:", with: metatag) click_button("Save changes") end When /^I remove the metatag "([^"]*)" from "([^"]*)"$/ do |metatag, subtag| subtag = Tag.find_by(name: subtag) metatag_id = Tag.find_by(name: metatag).id visit edit_tag_path(subtag) check("parent_MetaTag_associations_to_remove_#{metatag_id}") click_button("Save changes") end When /^I view the (canonical|synonymous|unfilterable|unwrangled|unwrangleable) (character|relationship|freeform) bin for "(.*?)"$/ do |status, type, tag| visit wrangle_tag_path(Tag.find_by(name: tag), show: type.pluralize, status: status) end ### THEN Then /^I should see the tag wrangler listed as an editor of the tag$/ do step %{I should see "wrangler" within "fieldset dl"} end Then /^I should see the tag search result "([^\"]*)"(?: within "([^"]*)")?$/ do |result, selector| with_scope(selector) do page.has_text?(result) end end Then /^I should not see the tag search result "([^\"]*)"(?: within "([^"]*)")?$/ do |result, selector| with_scope(selector) do page.has_no_text?(result) end end Then /^"([^\"]*)" should not be a tag wrangler$/ do |username| user = User.find_by(login: username) user.tag_wrangler.should be_falsey end Then /^"([^\"]*)" should be assigned to the wrangler "([^\"]*)"$/ do |fandom, username| user = User.find_by(login: username) fandom = Fandom.find_by(name: fandom) assignment = WranglingAssignment.where(user_id: user.id, fandom_id: fandom.id ).first assignment.should_not be_nil end Then /^"([^\"]*)" should not be assigned to the wrangler "([^\"]*)"$/ do |fandom, username| user = User.find_by(login: username) fandom = Fandom.find_by(name: fandom) assignment = WranglingAssignment.where(user_id: user.id, fandom_id: fandom.id ).first assignment.should be_nil end Then(/^the "([^"]*)" tag should be a "([^"]*)" tag$/) do |tagname, tag_type| tag = Tag.find_by(name: tagname) assert tag.type == tag_type end Then(/^the "([^"]*)" tag should (be|not be) canonical$/) do |tagname, canonical| tag = Tag.find_by(name: tagname) expected = canonical == "be" assert tag.canonical == expected end Then(/^the "([^"]*)" tag should (be|not be) unwrangleable$/) do |tagname, unwrangleable| tag = Tag.find_by(name: tagname) expected = unwrangleable == "be" assert tag.unwrangleable == expected end Then(/^the "([^"]*)" tag should be in the "([^"]*)" fandom$/) do |tagname, fandom_name| tag = Tag.find_by(name: tagname) fandom = Fandom.find_by(name: fandom_name) assert tag.has_parent?(fandom) end Then(/^show me what the tag "([^"]*)" is like$/) do |tagname| tag = Tag.find_by(name: tagname) puts tag.inspect end
elzj/otwarchive
features/step_definitions/tag_steps.rb
Ruby
gpl-2.0
13,617
<?php namespace Drupal\Tests\field\Kernel\Migrate\d6; use Drupal\Core\Entity\Entity\EntityViewDisplay; use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase; /** * Upgrade field formatter settings to entity.display.*.*.yml. * * @group migrate_drupal_6 */ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase { /** * {@inheritdoc} */ public static $modules = ['menu_ui']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->migrateFields(); } /** * Asserts that a particular component is NOT included in a display. * * @param string $display_id * The display ID. * @param string $component_id * The component ID. */ protected function assertComponentNotExists($display_id, $component_id) { $component = EntityViewDisplay::load($display_id)->getComponent($component_id); $this->assertNull($component); } /** * Test that migrated entity display settings can be loaded using D8 API's. */ public function testEntityDisplaySettings() { // Run tests. $field_name = "field_test"; $expected = [ 'label' => 'above', 'weight' => 1, 'type' => 'text_trimmed', 'settings' => ['trim_length' => 600], 'third_party_settings' => [], 'region' => 'content', ]; // Can we load any entity display. $display = EntityViewDisplay::load('node.story.teaser'); $this->assertIdentical($expected, $display->getComponent($field_name)); // Test migrate worked with multiple bundles. $display = EntityViewDisplay::load('node.test_page.teaser'); $expected['weight'] = 35; $this->assertIdentical($expected, $display->getComponent($field_name)); // Test RSS because that has been converted from 4 to rss. $display = EntityViewDisplay::load('node.story.rss'); $expected['weight'] = 1; $this->assertIdentical($expected, $display->getComponent($field_name)); // Test the default format with text_default which comes from a static map. $expected['type'] = 'text_default'; $expected['settings'] = []; $display = EntityViewDisplay::load('node.story.default'); $this->assertIdentical($expected, $display->getComponent($field_name)); // Check that we can migrate multiple fields. $content = $display->get('content'); $this->assertTrue(isset($content['field_test']), 'Settings for field_test exist.'); $this->assertTrue(isset($content['field_test_two']), "Settings for field_test_two exist."); // Check that we can migrate a field where exclude is not set. $this->assertTrue(isset($content['field_test_exclude_unset']), "Settings for field_test_exclude_unset exist."); // Test the number field formatter settings are correct. $expected['weight'] = 1; $expected['type'] = 'number_integer'; $expected['settings'] = [ 'thousand_separator' => ',', 'prefix_suffix' => TRUE, ]; $component = $display->getComponent('field_test_two'); $this->assertIdentical($expected, $component); $expected['weight'] = 2; $expected['type'] = 'number_decimal'; $expected['settings'] = [ 'scale' => 2, 'decimal_separator' => '.', 'thousand_separator' => ',', 'prefix_suffix' => TRUE, ]; $component = $display->getComponent('field_test_three'); $this->assertIdentical($expected, $component); // Test the email field formatter settings are correct. $expected['weight'] = 6; $expected['type'] = 'email_mailto'; $expected['settings'] = []; $component = $display->getComponent('field_test_email'); $this->assertIdentical($expected, $component); // Test the link field formatter settings. $expected['weight'] = 7; $expected['type'] = 'link'; $expected['settings'] = [ 'trim_length' => 80, 'url_only' => TRUE, 'url_plain' => TRUE, 'rel' => '0', 'target' => '0', ]; $component = $display->getComponent('field_test_link'); $this->assertIdentical($expected, $component); $expected['settings']['url_only'] = FALSE; $expected['settings']['url_plain'] = FALSE; $display = EntityViewDisplay::load('node.story.teaser'); $component = $display->getComponent('field_test_link'); $this->assertIdentical($expected, $component); // Test the file field formatter settings. $expected['weight'] = 8; $expected['type'] = 'file_default'; $expected['settings'] = [ 'use_description_as_link_text' => TRUE, ]; $component = $display->getComponent('field_test_filefield'); $this->assertIdentical($expected, $component); $display = EntityViewDisplay::load('node.story.default'); $expected['type'] = 'file_url_plain'; $expected['settings'] = []; $component = $display->getComponent('field_test_filefield'); $this->assertIdentical($expected, $component); // Test the image field formatter settings. $expected['weight'] = 9; $expected['type'] = 'image'; $expected['settings'] = ['image_style' => '', 'image_link' => '']; $component = $display->getComponent('field_test_imagefield'); $this->assertIdentical($expected, $component); $display = EntityViewDisplay::load('node.story.teaser'); $expected['settings']['image_link'] = 'file'; $component = $display->getComponent('field_test_imagefield'); $this->assertIdentical($expected, $component); // Test phone field. $expected['weight'] = 13; $expected['type'] = 'basic_string'; $expected['settings'] = []; $component = $display->getComponent('field_test_phone'); $this->assertIdentical($expected, $component); // Test date field. $defaults = ['format_type' => 'fallback', 'timezone_override' => '']; $expected['weight'] = 10; $expected['type'] = 'datetime_default'; $expected['settings'] = ['format_type' => 'fallback'] + $defaults; $component = $display->getComponent('field_test_date'); $this->assertIdentical($expected, $component); $display = EntityViewDisplay::load('node.story.default'); $expected['settings']['format_type'] = 'long'; $component = $display->getComponent('field_test_date'); $this->assertIdentical($expected, $component); // Test date stamp field. $expected['weight'] = 11; $expected['settings']['format_type'] = 'fallback'; $component = $display->getComponent('field_test_datestamp'); $this->assertIdentical($expected, $component); $display = EntityViewDisplay::load('node.story.teaser'); $expected['settings'] = ['format_type' => 'medium'] + $defaults; $component = $display->getComponent('field_test_datestamp'); $this->assertIdentical($expected, $component); // Test datetime field. $expected['weight'] = 12; $expected['settings'] = ['format_type' => 'short'] + $defaults; $component = $display->getComponent('field_test_datetime'); $this->assertIdentical($expected, $component); $display = EntityViewDisplay::load('node.story.default'); $expected['settings']['format_type'] = 'fallback'; $component = $display->getComponent('field_test_datetime'); $this->assertIdentical($expected, $component); // Test a date field with a random format which should be mapped // to datetime_default. $display = EntityViewDisplay::load('node.story.rss'); $expected['settings']['format_type'] = 'fallback'; $component = $display->getComponent('field_test_datetime'); $this->assertIdentical($expected, $component); // Test that our Id map has the correct data. $this->assertIdentical(['node', 'story', 'teaser', 'field_test'], $this->getMigration('d6_field_formatter_settings')->getIdMap()->lookupDestinationId(['story', 'teaser', 'node', 'field_test'])); // Test hidden field. $this->assertComponentNotExists('node.test_planet.teaser', 'field_test_text_single_checkbox'); // Test a node reference field, which should be migrated to an entity // reference field. $display = EntityViewDisplay::load('node.employee.default'); $component = $display->getComponent('field_company'); $this->assertInternalType('array', $component); $this->assertSame('entity_reference_label', $component['type']); // The default node reference formatter shows the referenced node's title // as a link. $this->assertTrue($component['settings']['link']); $display = EntityViewDisplay::load('node.employee.teaser'); $component = $display->getComponent('field_company'); $this->assertInternalType('array', $component); $this->assertSame('entity_reference_label', $component['type']); // The plain node reference formatter shows the referenced node's title, // unlinked. $this->assertFalse($component['settings']['link']); $component = $display->getComponent('field_commander'); $this->assertInternalType('array', $component); $this->assertSame('entity_reference_label', $component['type']); // The default user reference formatter links to the referenced user. $this->assertTrue($component['settings']['link']); } }
morethanthemes/magazine-lite
site/core/modules/field/tests/src/Kernel/Migrate/d6/MigrateFieldFormatterSettingsTest.php
PHP
gpl-2.0
9,097
<?php if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"])) exit("Do not access this file directly."); ?> <optgroup label="<?php echo esc_attr (_x ("Authorize.Net (Buy Now)", "s2member-admin", "s2member")); ?>"> <option value="1-L-BN" selected="selected"><?php echo esc_html (_x ("One Time (for lifetime access, non-recurring)", "s2member-admin", "s2member")); ?></option> </optgroup>
qyom/pipstation
wp-content/plugins/s2member-pro/includes/templates/options/authnet-membership-ccap-terms.php
PHP
gpl-2.0
400
// Noise++ Library // Copyright (c) 2008, Urs C. Hanselmann // 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. // // 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 "NoiseEndianUtils.h" namespace noisepp { namespace utils { void EndianUtils::flipEndian (void *data, size_t size) { #if NOISEPP_BIG_ENDIAN if (size < 2) return; assert (size % 2 == 0); char byte; for(size_t i=0;i<size/2;++i) { byte = *(char*)((long)data+i); *(char*)((long)data+i) = *(char*)((long)data+(size-i-1)); *(char*)((long)data+(size-i-1)) = byte; } #endif } }; };
egor200021/Minecraft-LCMod-J16-woolio
3libs/noisepp/NoiseEndianUtils.cpp
C++
gpl-2.0
1,798
/**************************************************************************************** * Copyright (c) 2008 Seb Ruiz <[email protected]> * * Copyright (c) 2008 Leo Franchi <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 2 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ #ifndef AMAROK_ITUNES_IMPORTER_CONFIG_H #define AMAROK_ITUNES_IMPORTER_CONFIG_H #include "databaseimporter/DatabaseImporter.h" #include <QCheckBox> #include <QLineEdit> class QComboBox; class QLabel; class ITunesImporterConfig : public DatabaseImporterConfig { Q_OBJECT public: ITunesImporterConfig( QWidget *parent = 0 ); virtual ~ITunesImporterConfig() { }; QString databaseLocation() const { return m_databaseLocationInput->text(); } private: QLabel *m_databaseLocationLabel; QLineEdit *m_databaseLocationInput; }; #endif
orangejulius/amarok
src/databaseimporter/itunes/ITunesImporterConfig.h
C
gpl-2.0
2,040
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.stat.regression; /** * An interface for regression models allowing for dynamic updating of the data. * That is, the entire data set need not be loaded into memory. As observations * become available, they can be added to the regression model and an updated * estimate regression statistics can be calculated. * * @version $Id$ * @since 3.0 */ public interface UpdatingMultipleLinearRegression { /** * Returns true if a constant has been included false otherwise. * * @return true if constant exists, false otherwise */ boolean hasIntercept(); /** * Returns the number of observations added to the regression model. * * @return Number of observations */ long getN(); /** * Adds one observation to the regression model. * * @param x the independent variables which form the design matrix * @param y the dependent or response variable * @throws ModelSpecificationException if the length of {@code x} does not equal * the number of independent variables in the model */ void addObservation(double[] x, double y) throws ModelSpecificationException; /** * Adds a series of observations to the regression model. The lengths of * x and y must be the same and x must be rectangular. * * @param x a series of observations on the independent variables * @param y a series of observations on the dependent variable * The length of x and y must be the same * @throws ModelSpecificationException if {@code x} is not rectangular, does not match * the length of {@code y} or does not contain sufficient data to estimate the model */ void addObservations(double[][] x, double[] y) throws ModelSpecificationException; /** * Clears internal buffers and resets the regression model. This means all * data and derived values are initialized */ void clear(); /** * Performs a regression on data present in buffers and outputs a RegressionResults object * @return RegressionResults acts as a container of regression output * @throws ModelSpecificationException if the model is not correctly specified */ RegressionResults regress() throws ModelSpecificationException; /** * Performs a regression on data present in buffers including only regressors * indexed in variablesToInclude and outputs a RegressionResults object * @param variablesToInclude an array of indices of regressors to include * @return RegressionResults acts as a container of regression output * @throws ModelSpecificationException if the model is not correctly specified */ RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException; }
SpoonLabs/astor
examples/math_32/src/main/java/org/apache/commons/math3/stat/regression/UpdatingMultipleLinearRegression.java
Java
gpl-2.0
3,605
#include "IRA.hpp" #include <limits> #include <algorithm> #include <cmath> #include <iostream> #include <cassert> // References: // 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in // a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), // pp 357-385. // 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly // Restarted Arnoldi Iteration", Rice University Technical Report // TR95-13, Department of Computational and Applied Mathematics. // 3. B.N. Parlett & Y. Saad, "Complex Shift and Invert Strategies for // real_type precision Matrices", Linear Algebra and its Applications, // vol 88/89, pp 575-595, (1987). // 4. B. Nour-Omid, B. N. Parlett, T. Ericsson and P. S. Jensen, // "How to Implement the Spectral Transformation", Math Comp., // Vol. 48, No. 178, April, 1987 pp. 664-673. // // Authors // Danny Sorensen Phuong Vu // Richard Lehoucq CRPC / Rice University // Chao Yang Houston, Texas // Dept. of Computational & // Applied Mathematics // Rice University // Houston, Texas // // Victor Liu // Stanford University // Stanford, CA namespace IRA{ static inline real_type _abs1(const complex_type &z){ return fabs(z.real()) + fabs(z.imag()); } static real_type frand(){ static const real_type nrm(real_type(1) / real_type(RAND_MAX)); real_type a = rand(); real_type b = rand(); return ((a * nrm) + b) * real_type(2) - real_type(1); } static real_type HessenbergNorm1(size_t n, const complex_type *a, size_t lda){ real_type result = 0; for(size_t j = 0; j < n; ++j){ size_t ilimit = (n < j+2 ? n : j+2); real_type sum = 0; for(size_t i = 0; i < ilimit; ++i){ sum += std::abs(a[i+j*lda]); } if(sum > result){ result = sum; } } return result; } template <typename TS, typename T> static void RescaleMatrix(const TS &cfrom, const TS &cto, size_t m, size_t n, T *a, size_t lda){ if(n == 0 || m == 0){ return; } const TS smlnum = std::numeric_limits<TS>::min(); const TS bignum = TS(1) / smlnum; TS cfromc = cfrom; TS ctoc = cto; bool done = true; do{ const TS cfrom1 = cfromc * smlnum; TS mul; if(cfrom1 == cfromc){ // CFROMC is an inf. Multiply by a correctly signed zero for // finite CTOC, or a NaN if CTOC is infinite. mul = ctoc / cfromc; done = true; //cto1 = ctoc; }else{ const TS cto1 = ctoc / bignum; if(cto1 == ctoc){ // CTOC is either 0 or an inf. In both cases, CTOC itself // serves as the correct multiplication factor. mul = ctoc; done = true; //cfromc = 1.; }else if(std::abs(cfrom1) > std::abs(ctoc) && ctoc != TS(0)){ mul = smlnum; done = false; cfromc = cfrom1; }else if(std::abs(cto1) > std::abs(cfromc)){ mul = bignum; done = false; ctoc = cto1; }else{ mul = ctoc / cfromc; done = true; } } for(size_t j = 0; j < n; ++j){ for(size_t i = 0; i < m; ++i){ a[i+j*lda] *= mul; } } }while(!done); } #ifdef IRA_STANDALONE # include "IRA_deps.cpp" #else // External Lapack routines namespace Lapack{ typedef int integer; typedef int logical; extern "C" void zlartg_( const complex_type &f, const complex_type &g, real_type *cs, complex_type *sn, complex_type *r ); void RotationGenerate( const complex_type &f, const complex_type &g, real_type *cs, complex_type *sn, complex_type *r ){ zlartg_(f, g, cs, sn, r); } extern "C" void ztrexc_( const char *compq, const integer &n, complex_type *t, const integer &ldt, complex_type *q, const integer &ldq, const integer &ifst, const integer &ilst, integer *info ); // Reorders the Schur factorization of a complex matrix // A = Q*T*Q**H, so that the diagonal element of T with row index ifst // is moved to row ilst. void SchurReorder( const char *compq, size_t n, complex_type *t, size_t ldt, complex_type *q, size_t ldq, size_t ifst, size_t ilst ){ integer info; ztrexc_(compq, n, t, ldt, q, ldq, ifst+1, ilst+1, &info); } extern "C" void zlahqr_( const logical &wantt, const logical &wantz, const integer &n, const integer &ilo, const integer &ihi, complex_type *h, const integer &ldh, complex_type *w, const integer &iloz, const integer &ihiz, complex_type *z, const integer &ldz, integer *info ); // We assume that H is already upper triangular in columns indices // ihi to n-1, inclusive, and that h[ilo+(ilo-1)*ldh] == 0. // iloz and ihiz specify the rows of Z to which transformations // should be applied if wantz == true. iloz is the lower index (inclusive), // and ihi is the upper index (exclusive). int HessenbergQRIteration( bool wantt, bool wantz, size_t n, size_t ilo, size_t ihi, complex_type *h, int ldh, complex_type *w, size_t iloz, size_t ihiz, complex_type *z, size_t ldz ){ integer info; zlahqr_( wantt ? 1 : 0, wantz ? 1 : 0, n, ilo+1, ihi, h, ldh, w, iloz+1, ihiz, z, ldz, &info ); return info; } extern "C" void ztrevc_( const char *side, const char *howmny, const logical *select, const integer &n, complex_type *t, const integer &ldt, complex_type *vl, const integer &ldvl, complex_type *vr, const integer &ldvr, const integer &mm, integer *m, complex_type *work, real_type *rwork, integer *info ); int TriangularEigenvectors( const char *howmny, const bool *select, size_t n, complex_type *t, size_t ldt, complex_type *vr, size_t ldvr, size_t mm, complex_type *work, real_type *rwork ){ integer im, info; logical *bsel = NULL; if(NULL != select){ bsel = new logical[n]; for(size_t i = 0; i < n; ++i){ bsel[i] = (select[i] ? 1 : 0); } } ztrevc_( "R", howmny, bsel, n, t, ldt, NULL, n, vr, ldvr, mm, &im, work, rwork, &info ); if(NULL != select){ delete [] bsel; } return info; } extern "C" void zgeqr2_( const integer &m, const integer &n, complex_type *a, const integer &lda, complex_type *tau, complex_type *work, integer *info ); void QRFactorization( size_t m, size_t n, complex_type *a, size_t lda, complex_type *tau, complex_type *work ){ integer info; zgeqr2_(m, n, a, lda, tau, work, &info); } extern "C" void zunm2r_( const char *side, const char *trans, const integer &m, const integer &n, const integer &k, complex_type *a, const integer &lda, const complex_type *tau, complex_type *c, const integer &ldc, complex_type *work, integer *info ); void QRMultQ_RN( size_t m, size_t n, size_t k, complex_type *a, size_t lda, const complex_type *tau, complex_type *c, size_t ldc, complex_type *work ){ integer info; zunm2r_("R", "N", m, n, k, a, lda, tau, c, ldc, work, &info); } } // namespace Lapack namespace BLAS{ typedef int integer; extern "C" void zgemv_( const char *trans, const integer &m, const integer &n, const complex_type &alpha, const complex_type *a, const integer &lda, const complex_type *x, const integer &incx, const complex_type &beta, complex_type *y, const integer &incy ); void MultMV(const char *trans, size_t m, size_t n, const complex_type &alpha, const complex_type *a, size_t lda, const complex_type *x, size_t incx, const complex_type &beta, complex_type *y, size_t incy ){ zgemv_(trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } extern "C" void ztrmm_( const char *side, const char *uplo, const char *transa, const char *diag, const integer &m, const integer &n, const complex_type &alpha, const complex_type *a, const integer &lda, complex_type *b, const integer &ldb ); void MultTrM_RUNN1( size_t m, size_t n, const complex_type *a, size_t lda, complex_type *b, size_t ldb ){ ztrmm_("R","U","N","N", m, n, complex_type(1), a, lda, b, ldb); } } // namespace BLAS #endif // IRA_STANDALONE class ComplexEigensystemImpl{ friend class ComplexEigensystem; protected: ComplexEigensystem *parent; size_t nn, n_wanted, n_arnoldi; complex_type *workd; // length 2*n complex_type *workl; // length (3*n_arnoldi + 5)*n_arnoldi. complex_type *workev; // length 2*n_arnoldi; complex_type *resid; // length n complex_type *v; // length n*n_arnoldi complex_type *w; // length n_arnoldi real_type *rwork; // length n_arnoldi bool *bwork; // length n_arnoldi // Pointers into workspaces size_t ldh, ldq; complex_type *h; complex_type *ritz, *bounds; complex_type *q; complex_type *subwork; bool shift_invert; complex_type shift; size_t maxiter; real_type tol; bool bsubspace; bool resid0_provided; bool solved; size_t nconv; // number of converged pairs real_type rnorm; static const size_t nb = 1; // block size public: ComplexEigensystemImpl(ComplexEigensystem *sup, size_t n, size_t nwanted, size_t narnoldi, // n_wanted+1 <= n_arnoldi <= n bool shift_invert_mode, const complex_type &shift_value, const ComplexEigensystem::Params &params, complex_type *resid0 ):parent(sup), nn(n), n_wanted(nwanted), n_arnoldi(narnoldi), shift_invert(shift_invert_mode), shift(shift_value), maxiter(params.max_iterations), tol(params.tol), bsubspace(params.invariant_subspace), solved(false), nconv(0) { if(n_arnoldi > n){ n_arnoldi = n; } const size_t ncv = n_arnoldi; ldh = ncv; ldq = ncv; w = new complex_type[n_arnoldi]; v = new complex_type[n*n_arnoldi]; workd = new complex_type[2*n]; workl = new complex_type[(3*n_arnoldi+5)*n_arnoldi]; workev = new complex_type[2*n_arnoldi]; rwork = new real_type[n_arnoldi]; bwork = new bool[n_arnoldi]; if(NULL != resid0){ resid0_provided = true; resid = resid0; }else{ resid0_provided = false; resid = new complex_type[n]; } if(tol <= real_type(0)){ tol = std::numeric_limits<real_type>::epsilon(); } h = workl; ritz = h + ldh*ncv; bounds = ritz + ncv; q = bounds + ncv; subwork = q + ldq*ncv; } ~ComplexEigensystemImpl(){ delete [] v; delete [] w; delete [] bwork; delete [] rwork; delete [] workev; delete [] workl; delete [] workd; if(!resid0_provided){ delete [] resid; } } protected: int RunArnoldi(){ // the old znaupd const size_t ncv = n_arnoldi; const size_t nev = n_wanted; memset(workl, 0, sizeof(complex_type) * (ncv * ncv * 3 + ncv * 5)); nconv = nev; int info = Phase1( ncv - nev, &maxiter, subwork ); info = ComputeEigenvectors( !bsubspace, 'A', bwork, workev, n_wanted, n_arnoldi, workd, workl ); return info; } int Phase1( // the old znaup2 size_t np, size_t *mxiter, complex_type *workl ){ const size_t n = nn; int info; static const real_type eps23 = pow(std::numeric_limits<real_type>::epsilon(), (real_type)2/(real_type)3); size_t nev = n_wanted; // Save initial values const size_t nev0 = n_wanted; const size_t np0 = np; // kplusp is the bound on the largest Lanczos factorization built. // nconv is the current number of "converged" eigenvalues. const size_t kplusp = nev + np; nconv = 0; // Get a possibly random starting vector and // force it into the range of the operator OP. info = GetInitialVector(resid0_provided, 0, &rnorm); if(real_type(0) == rnorm){ // The initial vector is zero. Error exit. *mxiter = 0; return -9; } // Compute the first nev steps of the Arnoldi factorization info = Iterate(0, nev, &rnorm, workd); if(info > 0){ nconv = info; *mxiter = 0; return -9999; } // MAIN ARNOLDI ITERATION LOOP // Each iteration implicitly restarts the Arnoldi factorization in place. size_t iter = 0; do{ ++iter; // Compute NP additional steps of the Arnoldi factorization. // Adjust NP since NEV might have been updated by last call // to the shift application routine znapps . np = kplusp - nev; // Compute np additional steps of the Arnoldi factorization. info = Iterate(nev, np, &rnorm, workd); if(info > 0){ nconv = info; *mxiter = iter; return -9999; } // Compute the eigenvalues and corresponding error bounds // of the current upper Hessenberg matrix. if(0 != ComputeHessenbergEigenvalues(rnorm, kplusp, workl, rwork)){ nconv = np; return -8; } // Select the wanted Ritz values and their bounds // to be used in the convergence test. // The wanted part of the spectrum and corresponding // error bounds are in the last NEV loc. of RITZ, // and BOUNDS respectively. nev = nev0; np = np0; // Make a copy of Ritz values and the corresponding // Ritz estimates obtained from zneigh . BLAS::Copy(kplusp, ritz , 1, &workl[kplusp * kplusp], 1); BLAS::Copy(kplusp, bounds, 1, &workl[kplusp * kplusp + kplusp], 1); // Select the wanted Ritz values and their bounds // to be used in the convergence test. // The wanted part of the spectrum and corresponding // bounds are in the last NEV loc. of RITZ // BOUNDS respectively. SortRitz(!parent->CanSupplyShifts(), nev, np, ritz, bounds); // Convergence test: currently we use the following criteria. // The relative accuracy of a Ritz value is considered // acceptable if: // // error_bounds(i) < tol*max(eps23, magnitude_of_ritz(i)). nconv = 0; for(size_t i = 0; i < nev; ++i){ real_type rtemp = std::abs(ritz[np + i]); if(eps23 > rtemp){ rtemp = eps23; } if(std::abs(bounds[np + i]) <= tol * rtemp){ ++nconv; }else{ } } // Count the number of unwanted Ritz values that have zero // Ritz estimates. If any Ritz estimates are equal to zero // then a leading block of H of order equal to at least // the number of Ritz values with zero Ritz estimates has // split off. None of these Ritz values may be removed by // shifting. Decrease NP the number of shifts to apply. If // no shifts may be applied, then prepare to exit { size_t nptemp = np; for(size_t j = 0; j < nptemp; ++j){ if(real_type(0) == bounds[j]){ --np; ++nev; } } } if(nconv >= nev0 || iter > *mxiter || np == 0){ // Prepare to exit. Put the converged Ritz values // and corresponding bounds in RITZ(1:NCONV) and // BOUNDS(1:NCONV) respectively. Then sort. // Be careful when NCONV > NP // Use h( 3,1 ) as storage to communicate // rnorm to zneupd if needed h[2] = rnorm; // Sort Ritz values so that converged Ritz // values appear within the first NEV locations // of ritz and bounds, and the most desired one // appears at the front. SortUtil(kplusp, ritz, bounds, true, false); // Scale the Ritz estimate of each Ritz value // by 1 / max(eps23, magnitude of the Ritz value). for(size_t j = 0; j < nev0; ++j){ real_type rtemp = std::abs(ritz[j]); if(eps23 > rtemp){ rtemp = eps23; } bounds[j] /= rtemp; } // Sort the Ritz values according to the scaled Ritz // estimates. This will push all the converged ones // towards the front of ritz, bounds (in the case // when NCONV < NEV.) SortUtil(nev0, bounds, ritz, true, true); // Scale the Ritz estimate back to its original // value. for(size_t j = 0; j < nev0; ++j){ real_type rtemp = std::abs(ritz[j]); if(eps23 > rtemp){ rtemp = eps23; } bounds[j] *= rtemp; } // Sort the converged Ritz values again so that // the "threshold" value appears at the front of // ritz and bound. SortUtil(nconv, ritz, bounds, false, false); // Max iterations have been exceeded. if(iter > *mxiter && nconv < nev0){ info = 1; } // No shifts to apply. if(0 == np && nconv < nev0){ info = 2; } np = nconv; break; // Exit main loop }else if(nconv < nev0 && !parent->CanSupplyShifts()){ // Do not have all the requested eigenvalues yet. // To prevent possible stagnation, adjust the size // of NEV. size_t nevbef = nev; nev += (nconv < np/2 ? nconv : np/2); if(nev == 1 && kplusp >= 6){ nev = kplusp / 2; } else if(nev == 1 && kplusp > 3){ nev = 2; } np = kplusp - nev; // If the size of NEV was just increased, // resort the eigenvalues. if(nevbef < nev){ SortRitz(!parent->CanSupplyShifts(), nev, np, ritz, bounds); } } if(parent->CanSupplyShifts()){ // User specified shifts: pop back out to get the shifts // and return them in the first 2*NP locations of WORKL. parent->GetShifts(np, ritz, subwork); // Move the NP shifts from WORKL to RITZ, to free up WORKL BLAS::Copy(np, subwork, 1, ritz, 1); } // Apply the NP implicit shifts by QR bulge chasing. // Each shift is applied to the whole upper Hessenberg matrix H. // The first 2*N locations of WORKD are used as workspace. ApplyShifts(&nev, np, ritz, workl); // Compute the B-norm of the updated residual. // Keep B*RESID in WORKD(1:N) to be used in // the first step of the next call to znaitr . // WORKD(1:N) := B*RESID if(!parent->IsBIdentity()){ if(parent->IsBInPlace()){ BLAS::Copy(n, resid, 1, workd, 1); parent->ApplyB(n, NULL, workd); }else{ parent->ApplyB(n, resid, workd); } complex_type cmpnorm = BLAS::ConjugateDot(n, resid, 1, workd, 1); rnorm = sqrt(std::abs(cmpnorm)); }else{ BLAS::Copy(n, resid, 1, workd, 1); rnorm = BLAS::Norm2(n, resid, 1); } }while(1); *mxiter = iter; return info; } // (the old zsortc) // Sort the arrays x and y of length n according to the comparison function. // The comparison function indicates when two elements needs to be swapped. // If reverse is true, then the sort order is reversed. // If sm is true, then the sort order is to place smallest magnitude values // at the beginning of the arrays and the comparison function is not called. void SortUtil(size_t n, complex_type *x, complex_type *y, bool reverse, bool sm){ size_t igap = n / 2; while(igap != 0){ for(size_t i = igap; i < n; ++i){ int j = i - igap; while(j >= 0){ if(j < 0){ break; } bool cmpres; if(sm){ cmpres = (std::abs(x[j]) < std::abs(x[j+igap])); }else{ cmpres = parent->EigenvalueCompare(x[j], x[j+igap]); } if(reverse == cmpres){ std::swap(x[j], x[j+igap]); if(NULL != y){ std::swap(y[j], y[j+igap]); } }else{ break; } j -= igap; } } igap /= 2; } } // (the old zngets) // Given the eigenvalues of the upper Hessenberg matrix H, // computes the NP shifts AMU that are zeros of the polynomial of // degree NP which filters out components of the unwanted eigenvectors // corresponding to the AMU's based on some given criteria. // // NOTE: call this even in the case of user specified shifts in order // to sort the eigenvalues, and error bounds of H for later use. void SortRitz(bool srtunwanted, size_t kev, size_t np, complex_type *r, complex_type *b){ SortUtil(kev + np, r, b, false, false); if(srtunwanted){ // Sort the unwanted Ritz values used as shifts so that // the ones with largest Ritz estimates are first // This will tend to minimize the effects of the // forward instability of the iteration when the shifts // are applied in subroutine znapps. // Be careful and use 'SM' since we want to sort BOUNDS! SortUtil(np, b, r, false, true); } } // (the old zneigh) // Compute the eigenvalues of the current upper Hessenberg matrix // and the corresponding Ritz estimates given the current residual norm. int ComputeHessenbergEigenvalues( const real_type &rnorm, size_t n, complex_type *workl, real_type *rwork ){ int ierr; // 1. Compute the eigenvalues, the last components of the // corresponding Schur vectors and the full Schur form T // of the current upper Hessenberg matrix H. // zlahqr returns the full Schur form of H // in WORKL(1:N**2), and the Schur vectors in q. BLAS::Copy(n, n, h, ldh, workl, n); BLAS::Set(n, n, 0.0, 1.0, q, ldq); ierr = Lapack::HessenbergQRIteration(true, true, n, 0, n, workl, ldh, ritz, 0, n, q, ldq); if(ierr != 0){ return ierr; } BLAS::Copy(n, &q[n-2+0*ldq], ldq, bounds, 1); // 2. Compute the eigenvectors of the full Schur form T and // apply the Schur vectors to get the corresponding // eigenvectors. ierr = Lapack::TriangularEigenvectors("B", NULL, n, workl, n, q, ldq, n, &workl[n*n], rwork); if(0 == ierr){ // Scale the returning eigenvectors so that their // Euclidean norms are all one. LAPACK subroutine // ztrevc returns each eigenvector normalized so // that the element of largest magnitude has // magnitude 1; here the magnitude of a complex // number (x,y) is taken to be |x| + |y|. for(size_t j = 0; j < n; ++j){ real_type temp = BLAS::Norm2(n, &q[0+j*ldq], 1); BLAS::Scale(n, real_type(1) / temp, &q[0+j*ldq], 1); } // Compute the Ritz estimates BLAS::Copy(n, &q[n-1+0*ldq], n, bounds, 1); BLAS::Scale(n, rnorm, bounds, 1); } return ierr; } // (the old znapps) // Given the Arnoldi factorization // A*V_{k} - V_{k}*H_{k} = r_{k+p}*e_{k+p}^T, // apply NP implicit shifts resulting in // A*(V_{k}*Q) - (V_{k}*Q)*(Q^T* H_{k}*Q) = r_{k+p}*e_{k+p}^T * Q // where Q is an orthogonal matrix which is the product of rotations // and reflections resulting from the NP bulge change sweeps. // The updated Arnoldi factorization becomes: // A*Vnew_{k} - Vnew_{k}*Hnew_{k} = rnew_{k}*e_{k}^T. void ApplyShifts(size_t *kev, size_t np, complex_type *shift, complex_type *workl){ const size_t n = nn; real_type c; complex_type f, g; complex_type r, s, t; complex_type h11, h21; size_t iend; complex_type sigma; size_t istart, kplusp; // Set machine-dependent constants for the // stopping criterion. If norm(H) <= sqrt(OVFL), // overflow should not occur. // REFERENCE: LAPACK subroutine zlahqr const real_type unfl = std::numeric_limits<real_type>::min(); //const real_type ovfl = 1. / unfl; const real_type ulp = 2.0*std::numeric_limits<real_type>::epsilon(); const real_type smlnum = unfl * (n / ulp); kplusp = *kev + np; // Initialize Q to the identity to accumulate // the rotations and reflections BLAS::Set(kplusp, kplusp, 0.0, 1.0, q, ldq); // Quick return if there are no shifts to apply if(np == 0){ return; } // Chase the bulge with the application of each // implicit shift. Each shift is applied to the // whole matrix including each block. for(size_t jj = 0; jj < np; ++jj){ sigma = shift[jj]; istart = 0; do{ iend = kplusp-1; for(size_t i = istart; i < iend; ++i){ // Check for splitting and deflation. Use // a standard test as in the QR algorithm // REFERENCE: LAPACK subroutine zlahqr real_type tst1 = _abs1(h[i+i*ldh]) + _abs1(h[(i+1)+(i+1)*ldh]); if(tst1 == 0.){ tst1 = HessenbergNorm1(kplusp - jj, h, ldh); } if(std::abs(h[(i+1)+i*ldh].real()) <= (ulp*tst1 > smlnum ? ulp*tst1 : smlnum)){ iend = i; h[(i+1)+i*ldh] = 0; break; } } // No reason to apply a shift to block of order 1 // or if the current block starts after the point // of compression since we'll discard this stuff if(!(istart == iend || istart >= *kev)){ h11 = h[istart+istart*ldh]; h21 = h[(istart+1)+istart*ldh]; f = h11 - sigma; g = h21; for(size_t i = istart; i < iend; ++i){ // Construct the plane rotation G to zero out the bulge Lapack::RotationGenerate(f, g, &c, &s, &r); if(i > istart){ h[i+(i-1)*ldh] = r; h[(i+1)+(i-1)*ldh] = 0; } // Apply rotation to the left of H; H <- G'*H for(size_t j = i; j < kplusp; ++j){ t = c*h[i+j*ldh] + s*h[(i+1)+j*ldh]; h[(i+1)+j*ldh] = -std::conj(s)*h[i+j*ldh] + c * h[(i+1)+j*ldh]; h[i+j*ldh] = t; } // Apply rotation to the right of H; H <- H*G { size_t jend = (i+2 < iend ? i+2 : iend); for(size_t j = 0; j <= jend; ++j){ t = c*h[j+i*ldh] + std::conj(s)*h[j+(i+1)*ldh]; h[j+(i+1)*ldh] = -s*h[j+i*ldh] + c*h[j+(i+1)*ldh]; h[j+i*ldh] = t; } } // Accumulate the rotation in the matrix Q; Q <- Q*G' { size_t jend = (i+jj+2 < kplusp ? i+jj+2 : kplusp); for(size_t j = 0; j < jend; ++j){ t = c*q[j+i*ldq] + std::conj(s)*q[j+(i+1)*ldq]; q[j+(i+1)*ldq] = -s*q[j+i*ldq] + c*q[j+(i+1)*ldq]; q[j+i*ldq] = t; } } // Prepare for next rotation if(i+1 < iend){ f = h[(i+1)+i*ldh]; g = h[(i+2)+i*ldh]; } } } // Finished applying the shift. // Apply the same shift to the next block if there is any. istart = iend + 1; // Loop back to the top to get the next shift. }while(iend+1 < kplusp); } // Perform a similarity transformation that makes // sure that the compressed H will have non-negative // real subdiagonal elements. for(size_t j = 0; j < *kev; ++j){ if(h[(j+1)+j*ldh].real() < 0. || h[(j+1)+j*ldh].imag() != 0.){ t = h[(j+1)+j*ldh] / std::abs(h[(j+1)+j*ldh]); BLAS::Scale(kplusp - j, std::conj(t), &h[(j+1)+j*ldh], ldh); /* Computing MIN */ size_t sublen = (j+3 < kplusp ? j+3 : kplusp); BLAS::Scale(sublen, t, &h[0+(j+1)*ldh], 1); sublen = (j+1+np+1 < kplusp ? j+1+np+1 : kplusp); BLAS::Scale(sublen, t, &q[0+(j+1)*ldq], 1); h[(j+1)+j*ldh] = h[(j+1)+j*ldh].real(); } } for(size_t i = 0; i < *kev; ++i){ // Final check for splitting and deflation. // Use a standard test as in the QR algorithm // REFERENCE: LAPACK subroutine zlahqr. // Note: Since the subdiagonals of the // compressed H are nonnegative real numbers, // we take advantage of this. real_type tst1 = _abs1(h[i+i*ldh]) + _abs1(h[(i+1)+(i+1)*ldh]); if(tst1 == 0.){ tst1 = HessenbergNorm1(*kev, h, ldh); } if(h[(i+1)+i*ldh].real() <= (ulp*tst1 > smlnum ? ulp*tst1 : smlnum)){ h[(i+1)+i*ldh] = 0; } } // Compute the (kev+1)-st column of (V*Q) and // temporarily store the result in WORKD(N+1:2*N). // This is needed in the residual update since we // cannot GUARANTEE that the corresponding entry // of H would be zero as in exact arithmetic. if(h[*kev+(*kev-1)*ldh].real() > 0.){ BLAS::MultMV("N", n, kplusp, 1.0, v, n, &q[0+(*kev)*ldq], 1, 0.0, &workd[n], 1); } // Compute column 1 to kev of (V*Q) in backward order // taking advantage of the upper Hessenberg structure of Q. for(size_t i = 0; i < *kev; ++i){ BLAS::MultMV("N", n, kplusp - i, 1.0, v, n, &q[0+(*kev - i-1)*ldq], 1, 0.0, workd, 1); BLAS::Copy(n, workd, 1, &v[0+(kplusp - i-1)*n], 1); } // Move v(:,kplusp-kev+1:kplusp) into v(:,1:kev). for(size_t i = 0; i < *kev; ++i){ BLAS::Copy(n, &v[0+(kplusp - *kev+i)*n], 1, &v[i*n], 1); } // Can't use this due to potential column overlap //BLAS::Copy(n, *kev, &v[0+(kplusp - *kev)*n], n, v, n); // Copy the (kev+1)-st column of (V*Q) in the appropriate place if(h[*kev+(*kev-1)*ldh].real() > 0.){ BLAS::Copy(n, &workd[n], 1, &v[0+(*kev)*n], 1); } // Update the residual vector: // r <- sigmak*r + betak*v(:,kev+1) // where // sigmak = (e_{kev+p}'*Q)*e_{kev} // betak = e_{kev+1}'*H*e_{kev} BLAS::Scale(n, q[(kplusp-1)+(*kev-1)*ldq], resid, 1); if(h[*kev+(*kev-1)*ldh].real() > 0.){ for(size_t i = 0; i < n; ++i){ resid[i] += h[*kev+(*kev-1)*ldh] * v[i+(*kev)*n]; } } } // the old zgetv0 int GetInitialVector(bool initv, size_t j, real_type *rnorm){ const size_t n = nn; // State data size_t iter; real_type rnorm0; iter = 0; // Possibly generate a random starting vector in RESID // Use a LAPACK random number generator used by the // matrix generation routines. // idist = 1: uniform (0,1) distribution; // idist = 2: uniform (-1,1) distribution; // idist = 3: normal (0,1) distribution; if(!initv){ for(size_t i = 0; i < n; ++i){ resid[i] = complex_type(frand(), frand()); } } if(!parent->IsBIdentity()){ // Force the starting vector into the range of Op to handle // the generalized problem when B is possibly (singular). // So we perform: // resid <- Op*B*resid (shift-invert) // resid <- Op*resid (non-shift-invert) if(shift_invert){ if(parent->IsOpInPlace()){ if(parent->IsBInPlace()){ parent->ApplyB(n, NULL, resid); parent->ApplyOp(n, NULL, resid); }else{ parent->ApplyB(n, resid, workd); BLAS::Copy(n, workd, 1, resid, 1); parent->ApplyOp(n, NULL, resid); } }else{ if(parent->IsBInPlace()){ parent->ApplyB(n, NULL, resid); parent->ApplyOp(n, resid, workd); BLAS::Copy(n, workd, 1, resid, 1); }else{ parent->ApplyB(n, resid, workd); parent->ApplyOp(n, workd, resid); } } }else{ if(parent->IsOpInPlace()){ parent->ApplyOp(n, NULL, resid); }else{ parent->ApplyOp(n, resid, workd); BLAS::Copy(n, workd, 1, resid, 1); } } // we need to end up with the result in resid // Starting vector is now in the range of OP; r = OP*r; // Compute B-norm of starting vector. parent->ApplyB(n, resid, workd); complex_type cnorm = BLAS::ConjugateDot(n, resid, 1, workd, 1); rnorm0 = sqrt(std::abs(cnorm)); }else{ BLAS::Copy(n, resid, 1, workd, 1); rnorm0 = BLAS::Norm2(n, resid, 1); } *rnorm = rnorm0; // At this point, we need resid to be valid, and // workd[0..n] contains B*resid // Exit if this is the very first Arnoldi step if(j > 0){ // Otherwise need to B-orthogonalize the starting vector against // the current Arnoldi basis using Gram-Schmidt with iter. ref. // This is the case where an invariant subspace is encountered // in the middle of the Arnoldi factorization. // // s = V^{T}*B*r; r = r - V*s; // // Stopping criteria used for iter. ref. is discussed in // Parlett's book, page 107 and in Gragg & Reichel TOMS paper. do{ assert(j <= n); BLAS::MultMV("C", n, j, 1.0, v, n, workd, 1, 0.0, &workd[n], 1); BLAS::MultMV("N", n, j, -1.0, v, n, &workd[n], 1, 1.0, resid, 1); // Compute the B-norm of the orthogonalized starting vector if(!parent->IsBIdentity()){ if(parent->IsBInPlace()){ BLAS::Copy(n, resid, 1, workd, 1); parent->ApplyB(n, NULL, workd); }else{ parent->ApplyB(n, resid, workd); } complex_type cnorm = BLAS::ConjugateDot(n, resid, 1, workd, 1); *rnorm = sqrt(std::abs(cnorm)); }else{ BLAS::Copy(n, resid, 1, workd, 1); *rnorm = BLAS::Norm2(n, resid, 1); } // Check for further orthogonalization. if(*rnorm > rnorm0 * .717f){ break; } ++iter; if(iter > 1){ // Iterative refinement step "failed" for(size_t jj = 0; jj < n; ++jj){ resid[jj] = 0; } *rnorm = 0.; return -1; } // Perform iterative refinement step rnorm0 = *rnorm; }while(1); } return 0; } // (the old znaitr) int Iterate(size_t k, size_t np, real_type *rnorm, complex_type *workd){ const size_t n = nn; const size_t ldv = nn; using namespace std; // Set machine-dependent constants for the // the splitting and deflation criterion. // If norm(H) <= sqrt(OVFL), // overflow should not occur. // REFERENCE: LAPACK subroutine zlahqr static const real_type unfl = std::numeric_limits<real_type>::min(); //const real_type ovfl = 1. / unfl; static const real_type ulp = 2.*std::numeric_limits<real_type>::epsilon(); const real_type smlnum = unfl * (n / ulp); // Initial call to this routine size_t j = k; complex_type *work_pj = &workd[0]; complex_type *work_rj = &workd[n]; // Note: B*r_{j-1} is already in workd[0..n] = work_pj do{ // STEP 1: Check if the B norm of j-th residual // vector is zero. Equivalent to determine whether // an exact j-step Arnoldi factorization is present. real_type betaj = *rnorm; if(!(*rnorm > 0.)){ // Invariant subspace found, generate a new starting // vector which is orthogonal to the current Arnoldi // basis and continue the iteration. betaj = 0.; // ITRY is the loop variable that controls the // maximum amount of times that a restart is // attempted. NRSTRT is used by stat.h size_t itry = 0; int ierr; do{ ierr = GetInitialVector(false, j, rnorm); ++itry; }while(ierr < 0 && itry <= 3); if(ierr < 0){ // Give up after several restart attempts. // Set INFO to the size of the invariant subspace // which spans OP and exit. return j; } } // STEP 2: v_{j} = r_{j-1}/rnorm and p_{j} = p_{j}/rnorm // Note that p_{j} = B*r_{j-1}. In order to avoid overflow // when reciprocating a small RNORM, test against lower // machine bound. BLAS::Copy(n, resid, 1, &v[0+j*ldv], 1); if(*rnorm >= unfl){ real_type temp1 = 1. / *rnorm; BLAS::Scale(n, temp1, &v[0+j*ldv], 1); BLAS::Scale(n, temp1, work_pj, 1); } else { // To scale both v_{j} and p_{j} carefully // use LAPACK routine zlascl RescaleMatrix(*rnorm, 1.0, n, 1, &v[0+j*ldv], n); RescaleMatrix(*rnorm, 1.0, n, 1, work_pj, n); } // STEP 3: r_{j} = OP*v_{j}; Note that p_{j} = B*v_{j} // Note that this is not quite yet r_{j}. See STEP 4 if(shift_invert){ // Compute inv(A - s B) * B * x // workd[ipj] already contains B*x if(parent->IsOpInPlace()){ BLAS::Copy(n, work_pj, 1, work_rj, 1); parent->ApplyOp(n, NULL, work_rj); }else{ parent->ApplyOp(n, work_pj, work_rj); } }else{ // Compute (inv(B)*A) * x if(parent->IsOpInPlace()){ BLAS::Copy(n, &v[0+j*ldv], 1, work_rj, 1); parent->ApplyOp(n, NULL, work_rj); }else{ parent->ApplyOp(n, &v[0+j*ldv], work_rj); } } // Put another copy of OP*v_{j} into RESID. BLAS::Copy(n, work_rj, 1, resid, 1); // STEP 4: Finish extending the Arnoldi // factorization to length j. // work_pj contains B*Op*v_{j} // The following is needed for STEP 5. // Compute the B-norm of OP*v_{j}. real_type wnorm; if(!parent->IsBIdentity()){ if(parent->IsBInPlace()){ BLAS::Copy(n, work_rj, 1, work_pj, 1); parent->ApplyB(n, NULL, work_pj); }else{ parent->ApplyB(n, work_rj, work_pj); } complex_type cnorm = BLAS::ConjugateDot(n, resid, 1, work_pj, 1); wnorm = sqrt(std::abs(cnorm)); }else{ BLAS::Copy(n, resid, 1, work_pj, 1); wnorm = BLAS::Norm2(n, resid, 1); } // Compute the j-th residual corresponding // to the j step factorization. // Use Classical Gram Schmidt and compute: // w_{j} <- V_{j}^T * B * OP * v_{j} // r_{j} <- OP*v_{j} - V_{j} * w_{j} // Compute the j Fourier coefficients w_{j} // work_pj contains B*Op*v_{j}. BLAS::MultMV("C", n, j+1, 1.0, v, ldv, work_pj, 1, 0.0, &h[0+j*ldh], 1); // Orthogonalize r_{j} against V_{j}. // resid contains Op*v_{j}. See STEP 3. BLAS::MultMV("N", n, j+1, -1.0, v, ldv, &h[0+j*ldh], 1, 1.0, resid, 1); if(j > 0){ h[j+(j-1)*ldh] = betaj; } // work_pj contains B*r_{j}. // Compute the B-norm of r_{j}. if(!parent->IsBIdentity()){ if(parent->IsBInPlace()){ BLAS::Copy(n, resid, 1, work_pj, 1); parent->ApplyB(n, NULL, work_pj); }else{ parent->ApplyB(n, resid, work_pj); } complex_type cnorm = BLAS::ConjugateDot(n, resid, 1, work_pj, 1); *rnorm = sqrt(std::abs(cnorm)); }else{ BLAS::Copy(n, resid, 1, work_pj, 1); *rnorm = BLAS::Norm2(n, resid, 1); } // STEP 5: Re-orthogonalization / Iterative refinement phase // Maximum NITER_ITREF tries. // // s = V_{j}^T * B * r_{j} // r_{j} = r_{j} - V_{j}*s // alphaj = alphaj + s_{j} // // The stopping criteria used for iterative refinement is // discussed in Parlett's book SEP, page 107 and in Gragg & // Reichel ACM TOMS paper; Algorithm 686, Dec. 1990. // Determine if we need to correct the residual. The goal is // to enforce ||v(:,1:j)^T * r_{j}|| .le. eps * || r_{j} || // The following test determines whether the sine of the // angle between OP*x and the computed residual is less // than or equal to 0.717. if(*rnorm <= wnorm * .717f){ size_t iter = 0; // Enter the Iterative refinement phase. If further // refinement is necessary, loop back here. The loop // variable is ITER. Perform a step of Classical // Gram-Schmidt using all the Arnoldi vectors V_{j} do{ // Compute V_{j}^T * B * r_{j}. // WORKD(IRJ:IRJ+J-1) = v(:,1:J)'*WORKD(IPJ:IPJ+N-1). BLAS::MultMV("C", n, j+1, 1.0, v, ldv, work_pj, 1, 0.0, work_rj, 1); // Compute the correction to the residual: // r_{j} = r_{j} - V_{j} * WORKD(IRJ:IRJ+J-1). // The correction to H is v(:,1:J)*H(1:J,1:J) // + v(:,1:J)*WORKD(IRJ:IRJ+J-1)*e'_j. BLAS::MultMV("N", n, j+1, -1.0, v, ldv, work_rj, 1, 1.0, resid, 1); for(size_t i = 0; i < j; ++i){ h[i+j*ldh] += work_rj[i]; } // Compute the B-norm of the corrected residual r_{j}. real_type rnorm1; if(!parent->IsBIdentity()){ if(parent->IsBInPlace()){ BLAS::Copy(n, resid, 1, work_pj, 1); parent->ApplyB(n, NULL, work_pj); }else{ parent->ApplyB(n, resid, work_pj); } complex_type cnorm = BLAS::ConjugateDot(n, resid, 1, work_pj, 1); rnorm1 = sqrt(std::abs(cnorm)); }else{ BLAS::Copy(n, resid, 1, work_pj, 1); rnorm1 = BLAS::Norm2(n, resid, 1); } // Determine if we need to perform another // step of re-orthogonalization. if(rnorm1 > *rnorm * .717f){ // No need for further refinement. // The cosine of the angle between the // corrected residual vector and the old // residual vector is greater than 0.717 // In other words the corrected residual // and the old residual vector share an // angle of less than arcCOS(0.717) *rnorm = rnorm1; } else { // Another step of iterative refinement step // is required. NITREF is used by stat.h *rnorm = rnorm1; ++iter; if(iter <= 1){ continue; } // Otherwise RESID is numerically in the span of V for(size_t jj = 0; jj < n; ++jj){ resid[jj] = 0; } *rnorm = 0.; } }while(0); } // STEP 6: Update j = j+1; Continue ++j; if(j >= k + np){ size_t istart = (k > 1 ? k : 1); for(size_t i = istart; i < k+np; ++i){ // Check for splitting and deflation. // Use a standard test as in the QR algorithm // REFERENCE: LAPACK subroutine zlahqr real_type tst1 = std::abs(h[(i-1)+(i-1)*ldh]) + std::abs(h[i+i*ldh]); if(tst1 == 0.){ tst1 = HessenbergNorm1(k + np, h, ldh); } /* Computing MAX */ if(std::abs(h[i+i*ldh]) <= max(ulp * tst1,smlnum)){ h[i+(i-1)*ldh] = 0; } } return 0; } }while(1); return 0; } // (the old zneupd) // We assume that rnorm and nconv are set from a previous call to // Phase1. Furthermore, we assume that the work arrays have not // been modified. // // rvec: false if only Ritz values are desired, true if Ritz // vectors or Schur vectors are also desired. // howmny: 'A' for NEV Ritz vectors // 'P' for NEV Schur vectors // 'S' for some Ritz vectors, selected by select // select: bool array of length ncv // // Ritz values returned in w, vectors in v. // // Notes: // 1. Currently only HOWMNY = 'A' and 'P' are implemented. // // 2. Schur vectors are an orthogonal representation for the basis of // Ritz vectors. Thus, their numerical properties are often superior. // If RVEC = .true. then the relationship // A * V(:,1:IPARAM(5)) = V(:,1:IPARAM(5)) * T, and // transpose( V(:,1:IPARAM(5)) ) * V(:,1:IPARAM(5)) = I // are approximately satisfied. // Here T is the leading submatrix of order IPARAM(5) of the // upper triangular matrix stored workl(ipntr(12)). // int ComputeEigenvectors( bool rvec, char howmny, bool *select, complex_type *workev, size_t nev, size_t ncv, complex_type *workd, complex_type *workl ){ const size_t n = nn; const size_t ldv = nn; complex_type *z = v; const size_t ldz = nn; using namespace std; complex_type temp; bool reord; real_type rtemp; size_t numcnv; // Get machine dependent constant. const real_type eps23 = pow(std::numeric_limits<real_type>::epsilon(), (real_type)2/(real_type)3); //const size_t bounds = ncv*ncv+3*ncv; const size_t ldh = ncv; const size_t ldq = ncv; // Input pointers from Phase 1 complex_type *work_h = h; complex_type *work_ritz = ritz; complex_type *work_bounds = bounds; complex_type *work_heig = q; // Output pointers complex_type *work_hbds = q + ldh; complex_type *work_uptri = work_hbds + ldh; complex_type *work_invsub = work_uptri + ldh*ncv; // rz points to ritz values computed by zneigh before exiting znaup2. // bd points to bounds estimates computed by zneigh before exiting znaup2. complex_type *work_rz = &workl[2*ncv*ncv+2*ncv + ncv * ncv]; complex_type *work_bd = &workl[2*ncv*ncv+2*ncv + ncv * ncv + ncv]; if(rvec){ reord = false; // Use the temporary bounds array to store indices // These will be used to mark the select array later for(size_t j = 0; j < ncv; ++j){ work_bounds[j] = (real_type)j; select[j] = false; } // Select the wanted Ritz values. // Sort the Ritz values so that the // wanted ones appear at the tailing // NEV positions of workl(irr) and // workl(iri). Move the corresponding // error estimates in workl(ibd) // accordingly. SortRitz(false, nev, ncv - nev, work_rz, work_bounds); // Record indices of the converged wanted Ritz values // Mark the select array for possible reordering numcnv = 0; for(size_t j = 0; j < ncv; ++j){ /* Computing MAX */ rtemp = std::abs(work_rz[ncv - j-1]); if(eps23 > rtemp){ rtemp = eps23; } size_t jj = (int)work_bounds[ncv - j-1].real(); if(numcnv < nconv && std::abs(work_bd[jj]) <= tol * rtemp){ select[jj] = true; ++numcnv; if(jj >= nev){ reord = true; } } } // Check the count (numcnv) of converged Ritz values with // the number (nconv) reported by dnaupd. If these two // are different then there has probably been an error // caused by incorrect passing of the dnaupd data. if(numcnv != nconv){ return -15; } // Call LAPACK routine zlahqr to compute the Schur form // of the upper Hessenberg matrix returned by ZNAUPD. // Make a copy of the upper Hessenberg matrix. // Initialize the Schur vector matrix Q to the identity. BLAS::Copy(ldh * ncv, work_h, 1, work_uptri, 1); BLAS::Set(ncv, ncv, 0.0, 1.0, work_invsub, ldq); int ierr = Lapack::HessenbergQRIteration(true, true, ncv, 0, ncv, work_uptri, ldh, work_heig, 0, ncv, work_invsub, ldq); BLAS::Copy(ncv, &work_invsub[ncv - 1], ldq, work_hbds, 1); if(ierr != 0){ return -8; } if(reord){ // Reorder the computed upper triangular matrix. //ztrsen_(&select[1], ncv, &workl[iuptri], ldh, &workl[invsub], ldq, &workl[iheig], &nconv, NULL, NULL); { nconv = 0; for(size_t k = 0; k < ncv; ++k){ if(select[k]){ ++nconv; } } if(!(nconv == ncv || nconv == 0)){ // Collect the selected eigenvalues at the top left corner of T. size_t ks = 0; for(size_t k = 0; k < ncv; ++k){ if(select[k]){ // Swap the K-th eigenvalue to position KS. if(k != ks){ Lapack::SchurReorder("V", ncv, work_uptri, ldh, work_invsub, ldq, k, ks); } ++ks; } } } // Copy reordered eigenvalues to W. for(size_t k = 0; k < ncv; ++k){ work_heig[k] = work_uptri[k+k*ldh]; } } if(ierr == 1){ return 1; } } // Copy the last row of the Schur basis matrix // to workl(ihbds). This vector will be used // to compute the Ritz estimates of converged // Ritz values. BLAS::Copy(ncv, &work_invsub[ncv-1], ldq, work_hbds, 1); // Place the computed eigenvalues of H into D // if a spectral transformation was not used. if(!shift_invert){ BLAS::Copy(nconv, work_heig, 1, w, 1); } // Compute the QR factorization of the matrix representing // the wanted invariant subspace located in the first NCONV // columns of workl(invsub,ldq). Lapack::QRFactorization(ncv, nconv, work_invsub, ldq, workev, &workev[ncv]); // * Postmultiply V by Q using zunm2r. // * Copy the first NCONV columns of VQ into Z. // * Postmultiply Z by R. // The N by NCONV matrix Z is now a matrix representation // of the approximate invariant subspace associated with // the Ritz values in workl(iheig). The first NCONV // columns of V are now approximate Schur vectors // associated with the upper triangular matrix of order // NCONV in workl(iuptri). Lapack::QRMultQ_RN(n, ncv, nconv, work_invsub, ldq, workev, v, ldv, &workd[n]); //BLAS::Copy(n, nconv, v, ldv, z, ldz); // this is a Nop for(size_t j = 0; j < nconv; ++j){ // Perform both a column and row scaling if the // diagonal element of workl(invsub,ldq) is negative // I'm lazy and don't take advantage of the upper // triangular form of workl(iuptri,ldq). // Note that since Q is orthogonal, R is a diagonal // matrix consisting of plus or minus ones. if(work_invsub[j+j*ldq].real() < 0.){ BLAS::Scale(nconv, -1.0, &work_uptri[j], ldq); BLAS::Scale(nconv, -1.0, &work_uptri[j*ldq], 1); } } if(howmny == 'A'){ // Compute the NCONV wanted eigenvectors of T // located in workl(iuptri,ldq). for(size_t j = 0; j < ncv; ++j){ if(j < nconv){ select[j] = true; } else { select[j] = false; } } ierr = Lapack::TriangularEigenvectors("S", select, ncv, work_uptri, ldq, work_invsub, ldq, ncv, workev, rwork); if(ierr != 0){ return -9; } // Scale the returning eigenvectors so that their // Euclidean norms are all one. LAPACK subroutine // ztrevc returns each eigenvector normalized so // that the element of largest magnitude has // magnitude 1. for(size_t j = 0; j < nconv; ++j){ rtemp = BLAS::Norm2(ncv, &work_invsub[j*ldq], 1); BLAS::Scale(ncv, 1. / rtemp, &work_invsub[j*ldq], 1); // Ritz estimates can be obtained by taking // the inner product of the last row of the // Schur basis of H with eigenvectors of T. // Note that the eigenvector matrix of T is // upper triangular, thus the length of the // inner product can be set to j. workev[j] = BLAS::ConjugateDot(j+1, work_hbds, 1, &work_invsub[j*ldq], 1); } // Copy Ritz estimates into workl(ihbds) BLAS::Copy(nconv, workev, 1, work_hbds, 1); // The eigenvector matrix Q of T is triangular. // Form Z*Q. BLAS::MultTrM_RUNN1(n, nconv, work_invsub, ldq, z, ldz); } }else{ // An approximate invariant subspace is not needed. // Place the Ritz values computed ZNAUPD into D. BLAS::Copy(nconv, work_ritz, 1, w, 1); BLAS::Copy(nconv, work_ritz, 1, work_heig, 1); BLAS::Copy(nconv, work_bounds, 1, work_hbds, 1); } // Transform the Ritz values and possibly vectors // and corresponding error bounds of OP to those // of A*x = lambda*B*x. if(!shift_invert){ if(rvec){ BLAS::Scale(ncv, rnorm, work_hbds, 1); } }else{ // A spectral transformation was used. // Determine the Ritz estimates of the // Ritz values in the original system. if(rvec){ BLAS::Scale(ncv, rnorm, work_hbds, 1); } for(size_t k = 0; k < ncv; ++k){ complex_type temp = work_heig[k]; work_hbds[k] /= temp; work_hbds[k] /= temp; } } // Transform the Ritz values back to the original system. // For shift-invert the transformation is // lambda = 1/theta + sigma // Note the Ritz vectors are not affected by the transformation. if(shift_invert){ for(size_t k = 0; k < nconv; ++k){ w[k] = 1.0/work_heig[k] + shift; } } // Eigenvector Purification step. Formally perform // one of inverse subspace iteration. Only used // for shift-invert. See references. if(rvec && howmny == 'A' && shift_invert){ // Purify the computed Ritz vectors by adding a // little bit of the residual vector: // T // resid(:)*( e s ) / theta // NCV // where H s = s theta. for(size_t j = 0; j < nconv; ++j){ if(work_heig[j] != 0.){ workev[j] = work_invsub[j*ldq + ncv-1] / work_heig[j]; } } // Perform a rank one update to Z and // purify all the Ritz vectors together. for(size_t j = 0; j < nconv; ++j){ if(complex_type(0) != workev[j]){ for(size_t i = 0; i < n; ++i){ z[i+j*ldz] += resid[i]*workev[j]; } } } } return 0; } }; ComplexEigensystem::ComplexEigensystem( size_t n, size_t n_wanted, size_t n_arnoldi, // n_wanted+1 <= n_arnoldi <= n bool shift_invert, const complex_type &shift, const Params &params, complex_type *resid0 ){ impl = new ComplexEigensystemImpl(this, n, n_wanted, n_arnoldi, shift_invert, shift, params, resid0 ); } ComplexEigensystem::~ComplexEigensystem(){ delete impl; } size_t ComplexEigensystem::GetConvergedCount(){ if(!impl->solved){ impl->RunArnoldi(); impl->solved = true; } return impl->nconv; } const complex_type *ComplexEigensystem::GetEigenvalues(){ size_t n = GetConvergedCount(); return (n > 0 ? impl->w : NULL); } const complex_type *ComplexEigensystem::GetEigenvectors(){ size_t n = GetConvergedCount(); return (n > 0 ? impl->v : NULL); } } // namespace IRA
gevero/S4
S4r/IRA.cpp
C++
gpl-2.0
51,407
<?php /** * An AbstractScopeTest allows for tests that extend from this class to * listen for tokens within a particluar scope. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version CVS: $Id: AbstractScopeSniff.php 270198 2008-12-01 05:41:28Z squiz $ * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * An AbstractScopeTest allows for tests that extend from this class to * listen for tokens within a particluar scope. * * Below is a test that listens to methods that exist only within classes: * <code> * class ClassScopeTest extends PHP_CodeSniffer_Standards_AbstractScopeSniff * { * public function __construct() * { * parent::__construct(array(T_CLASS), array(T_FUNCTION)); * } * * protected function processTokenWithinScope(PHP_CodeSniffer_File $phpcsFile, $) * { * $className = $phpcsFile->getDeclarationName($currScope); * echo 'encountered a method within class '.$className; * } * } * </code> * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version Release: 1.3.0RC1 * @link http://pear.php.net/package/PHP_CodeSniffer */ abstract class PHP_CodeSniffer_Standards_AbstractScopeSniff implements PHP_CodeSniffer_Sniff { /** * The token types that this test wishes to listen to within the scope. * * @var array() */ private $_tokens = array(); /** * The type of scope opener tokens that this test wishes to listen to. * * @var string */ private $_scopeTokens = array(); /** * The position in the tokens array that opened the current scope. * * @var array() */ protected $currScope = null; /** * The current file being checked. * * @var string */ protected $currFile = ''; /** * True if this test should fire on tokens outside of the scope. * * @var boolean */ private $_listenOutside = false; /** * Constructs a new AbstractScopeTest. * * @param array $scopeTokens The type of scope the test wishes to listen to. * @param array $tokens The tokens that the test wishes to listen to * within the scope. * @param boolean $listenOutside If true this test will also alert the * extending class when a token is found outside * the scope, by calling the * processTokenOutideScope method. * * @see PHP_CodeSniffer.getValidScopeTokeners() * @throws PHP_CodeSniffer_Test_Exception If the specified tokens array is empty. */ public function __construct( array $scopeTokens, array $tokens, $listenOutside=false ) { if (empty($scopeTokens) === true) { $error = 'The scope tokens list cannot be empty'; throw new PHP_CodeSniffer_Test_Exception($error); } if (empty($tokens) === true) { $error = 'The tokens list cannot be empty'; throw new PHP_CodeSniffer_Test_Exception($error); } $invalidScopeTokens = array_intersect($scopeTokens, $tokens); if (empty($invalidScopeTokens) === false) { $invalid = implode(', ', $invalidScopeTokens); $error = "Scope tokens [$invalid] cant be in the tokens array"; throw new PHP_CodeSniffer_Test_Exception($error); } $this->_listenOutside = $listenOutside; $this->_scopeTokens = $scopeTokens; $this->_tokens = $tokens; }//end __construct() /** * The method that is called to register the tokens this test wishes to * listen to. * * DO NOT OVERRIDE THIS METHOD. Use the constructor of this class to register * for the desired tokens and scope. * * @return array(int) * @see __constructor() */ public final function register() { if ($this->_listenOutside === false) { return $this->_scopeTokens; } else { return array_merge($this->_scopeTokens, $this->_tokens); } }//end register() /** * Processes the tokens that this test is listening for. * * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found. * @param int $stackPtr The position in the stack where this * token was found. * * @return void * @see processTokenWithinScope() */ public final function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $file = $phpcsFile->getFilename(); if ($this->currFile !== $file) { // We have changed files, so clean up. $this->currScope = null; $this->currFile = $file; } $tokens = $phpcsFile->getTokens(); if (in_array($tokens[$stackPtr]['code'], $this->_scopeTokens) === true) { $this->currScope = $stackPtr; $phpcsFile->addTokenListener($this, $this->_tokens); } else if ($this->currScope !== null && isset($tokens[$this->currScope]['scope_closer']) === true && $stackPtr > $tokens[$this->currScope]['scope_closer'] ) { $this->currScope = null; if ($this->_listenOutside === true) { // This is a token outside the current scope, so notify the // extender as they wish to know about this. $this->processTokenOutsideScope($phpcsFile, $stackPtr); } else { // Don't remove the listener if the extender wants to know about // tokens that live outside the current scope. $phpcsFile->removeTokenListener($this, $this->_tokens); } } else if ($this->currScope !== null) { $this->processTokenWithinScope($phpcsFile, $stackPtr, $this->currScope); } else { $this->processTokenOutsideScope($phpcsFile, $stackPtr); } }//end process() /** * Processes a token that is found within the scope that this test is * listening to. * * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found. * @param int $stackPtr The position in the stack where this * token was found. * @param int $currScope The position in the tokens array that * opened the scope that this test is * listening for. * * @return void */ protected abstract function processTokenWithinScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $currScope ); /** * Processes a token that is found within the scope that this test is * listening to. * * @param PHP_CodeSniffer_File $phpcsFile The file where this token was found. * @param int $stackPtr The position in the stack where this * token was found. * * @return void */ protected function processTokenOutsideScope( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { return; }//end processTokenOutsideScope() }//end class ?>
mlti/learning-repository-system-
profiles/syntiro/modules/custom/curriculum/phpdocx/lib/php_codesniffer/CodeSniffer/Standards/AbstractScopeSniff.php
PHP
gpl-2.0
7,909
/************************************************************************* * * file : RecycledEntityId.cs * copyright : (C) The WCell Team * email : [email protected] * last changed : $LastChangedDate: 2008-01-31 12:35:36 +0100 (to, 31 jan 2008) $ * last author : $LastChangedBy: tobz $ * revision : $Rev: 87 $ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * *************************************************************************/ using Cell.Core; using System; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using WCell.Core; using WCell.RealmServer.Database; using NLog; using WCell.RealmServer.Localization; namespace WCell.RealmServer.Database { /// <summary> /// Represents a recycled entity ID. /// </summary> public partial class RecycledEntityId { #region Compiled Queries public static Func<RealmServerDataContext, int, IQueryable<RecycledEntityId>> RecycledIdsByType = CompiledQuery.Compile( (RealmServerDataContext rdb, int id) => from rid in rdb.RecycledEntityIds where rid.EntityType == id select rid ); public static Func<RealmServerDataContext, int, int, IQueryable<RecycledEntityId>> RecycledIdByLowerAndType = CompiledQuery.Compile( (RealmServerDataContext rdb, int lowerId, int idType) => from rid in rdb.RecycledEntityIds where rid.EntityType == idType && rid.EntityId == lowerId select rid ); #endregion #region Fields private static SpinWaitLock m_idLock = new SpinWaitLock(); private static Logger s_log = LogManager.GetCurrentClassLogger(); #endregion #region Methods /// <summary> /// Tries to get the first available recycled ID. /// </summary> /// <param name="entityIdType">the type of the entity id</param> /// <returns>a non-zero ID if one was available; 0 otheriwse</returns> /// <remarks>If an available ID is found, it'll be removed from the database.</remarks> public static uint TryGetLowerEntityId(EntityIdType entityIdType) { // Lock so someone else doesn't grab the same row m_idLock.Enter(); try { RecycledEntityId eid = GetFirstRecycledId(entityIdType); if (eid == null) { return 0; } else { RemoveRecycledId(eid); return (uint)eid.EntityId; } } finally { m_idLock.Exit(); } } /// <summary> /// Recycles an entity ID of the given type. /// </summary> /// <param name="lowerEntityId">the lower entity id</param> /// <param name="entityIdType">the type of the entity id</param> public static bool RecycleLowerEntityId(uint lowerEntityId, EntityIdType idType) { if (DoesIdExist(lowerEntityId, idType)) { // TODO: What should we do if it already exists? This is are a serious bug. s_log.Debug(Resources.AlreadyRecycledEntityId, lowerEntityId, idType.ToString()); return false; } RecycledEntityId eid = new RecycledEntityId(); eid.RecycledEntityIdGuid = Guid.NewGuid(); eid.EntityId = (long)lowerEntityId; eid.EntityType = (int)idType; AddRecycledId(eid); return true; } /// <summary> /// Gets the first available ID of the given type. /// </summary> /// <param name="type">the type of entity ID to get</param> /// <returns>a <see cref="RecycledEntityId" /> object representing the ID; null if no ID was available</returns> public static RecycledEntityId GetFirstRecycledId(EntityIdType type) { using (var db = RealmServerDataContext.GetContext()) { IQueryable<RecycledEntityId> ids = RecycledIdsByType(db, (int)type); return ids.FirstOrDefault(); } } /// <summary> /// Checks if the recycled ID already exists in the database. /// </summary> /// <param name="lowerId">the ID to check for</param> /// <param name="type">the entity ID type to check for</param> /// <returns>true if the ID has already been recycled; false if not</returns> public static bool DoesIdExist(uint lowerId, EntityIdType type) { using (var db = RealmServerDataContext.GetContext()) { return RecycledIdByLowerAndType(db, (int)lowerId, (int)type).Count() > 0; } } /// <summary> /// Adds a new recycled ID to the database. /// </summary> /// <param name="id">the ID to add</param> public static void AddRecycledId(RecycledEntityId id) { using (var db = RealmServerDataContext.GetContext()) { db.RecycledEntityIds.InsertOnSubmit(id); db.SubmitChanges(); } } /// <summary> /// Removes a recycled ID from the database. /// </summary> /// <param name="id">the ID to remove</param> public static void RemoveRecycledId(RecycledEntityId id) { using (var db = RealmServerDataContext.GetContext()) { db.RecycledEntityIds.Attach(id); db.RecycledEntityIds.DeleteOnSubmit(id); db.SubmitChanges(); } } #endregion } }
WCell/WCell
Services/WCell.RealmServer/Misc/RecycledEntityId.cs
C#
gpl-2.0
5,490
// $Id: OS_NS_Thread.cpp 91523 2010-08-27 14:18:02Z johnnyw $ #include "ace/OS_NS_Thread.h" #if !defined (ACE_HAS_INLINED_OSCALLS) # include "ace/OS_NS_Thread.inl" #endif /* ACE_HAS_INLINED_OSCALLS */ #include "ace/OS_NS_stdio.h" #include "ace/Sched_Params.h" #include "ace/OS_Memory.h" #include "ace/OS_Thread_Adapter.h" #include "ace/Min_Max.h" #include "ace/Object_Manager_Base.h" #include "ace/OS_NS_errno.h" #include "ace/OS_NS_ctype.h" #include "ace/Log_Msg.h" // for ACE_ASSERT // This is necessary to work around nasty problems with MVS C++. #include "ace/Auto_Ptr.h" #include "ace/Thread_Mutex.h" #include "ace/Condition_T.h" #include "ace/Guard_T.h" extern "C" void ACE_MUTEX_LOCK_CLEANUP_ADAPTER_NAME (void *args) { ACE_VERSIONED_NAMESPACE_NAME::ACE_OS::mutex_lock_cleanup (args); } #if !defined(ACE_WIN32) && defined (__IBMCPP__) && (__IBMCPP__ >= 400) # define ACE_BEGINTHREADEX(STACK, STACKSIZE, ENTRY_POINT, ARGS, FLAGS, THR_ID) \ (*THR_ID = ::_beginthreadex ((void(_Optlink*)(void*))ENTRY_POINT, STACK, STACKSIZE, ARGS), *THR_ID) #elif defined (ACE_HAS_WINCE) # define ACE_BEGINTHREADEX(STACK, STACKSIZE, ENTRY_POINT, ARGS, FLAGS, THR_ID) \ CreateThread (0, STACKSIZE, (unsigned long (__stdcall *) (void *)) ENTRY_POINT, ARGS, (FLAGS) & (CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION), (unsigned long *) THR_ID) #elif defined(ACE_HAS_WTHREADS) // Green Hills compiler gets confused when __stdcall is imbedded in // parameter list, so we define the type ACE_WIN32THRFUNC_T and use it // instead. typedef unsigned (__stdcall *ACE_WIN32THRFUNC_T)(void*); # define ACE_BEGINTHREADEX(STACK, STACKSIZE, ENTRY_POINT, ARGS, FLAGS, THR_ID) \ ::_beginthreadex (STACK, STACKSIZE, (ACE_WIN32THRFUNC_T) ENTRY_POINT, ARGS, FLAGS, (unsigned int *) THR_ID) #endif /* defined (__IBMCPP__) && (__IBMCPP__ >= 400) */ /*****************************************************************************/ ACE_BEGIN_VERSIONED_NAMESPACE_DECL void ACE_Thread_ID::to_string (char *thr_string) const { char format[128]; // Converted format string char *fp = 0; // Current format pointer fp = format; *fp++ = '%'; // Copy in the % #if defined (ACE_WIN32) ACE_OS::strcpy (fp, "u"); ACE_OS::sprintf (thr_string, format, static_cast <unsigned> (thread_id_)); #elif defined (DIGITAL_UNIX) ACE_OS::strcpy (fp, "u"); ACE_OS::sprintf (thr_string, format, # if defined (ACE_HAS_THREADS) thread_id_ # else thread_id_ # endif /* ACE_HAS_THREADS */ ); #else # if defined (ACE_MVS) || defined (ACE_TANDEM_T1248_PTHREADS) // MVS's pthread_t is a struct... yuck. So use the ACE 5.0 // code for it. ACE_OS::strcpy (fp, "u"); ACE_OS::sprintf (thr_string, format, thread_handle_); # else // Yes, this is an ugly C-style cast, but the // correct C++ cast is different depending on // whether the t_id is an integral type or a pointer // type. FreeBSD uses a pointer type, but doesn't // have a _np function to get an integral type, like // the OSes above. ACE_OS::strcpy (fp, "lu"); ACE_OS::sprintf (thr_string, format, (unsigned long) thread_handle_); # endif /* ACE_MVS || ACE_TANDEM_T1248_PTHREADS */ #endif /* ACE_WIN32 */ } /*****************************************************************************/ #if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) #if defined (ACE_HAS_TSS_EMULATION) u_int ACE_TSS_Emulation::total_keys_ = 0; ACE_TSS_Keys* ACE_TSS_Emulation::tss_keys_used_ = 0; ACE_TSS_Emulation::ACE_TSS_DESTRUCTOR ACE_TSS_Emulation::tss_destructor_[ACE_TSS_Emulation::ACE_TSS_THREAD_KEYS_MAX] = { 0 }; # if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) bool ACE_TSS_Emulation::key_created_ = false; ACE_OS_thread_key_t ACE_TSS_Emulation::native_tss_key_; /* static */ # if defined (ACE_HAS_THR_C_FUNC) extern "C" void ACE_TSS_Emulation_cleanup (void *) { // Really this must be used for ACE_TSS_Emulation code to make the TSS // cleanup } # else void ACE_TSS_Emulation_cleanup (void *) { // Really this must be used for ACE_TSS_Emulation code to make the TSS // cleanup } # endif /* ACE_HAS_THR_C_FUNC */ void ** ACE_TSS_Emulation::tss_base (void* ts_storage[], u_int *ts_created) { // TSS Singleton implementation. // Create the one native TSS key, if necessary. if (!key_created_) { // Double-checked lock . . . ACE_TSS_BASE_GUARD if (!key_created_) { ACE_NO_HEAP_CHECK; if (ACE_OS::thr_keycreate_native (&native_tss_key_, &ACE_TSS_Emulation_cleanup) != 0) { ACE_ASSERT (0); return 0; // Major problems, this should *never* happen! } key_created_ = true; } } void **old_ts_storage = 0; // Get the tss_storage from thread-OS specific storage. if (ACE_OS::thr_getspecific_native (native_tss_key_, (void **) &old_ts_storage) == -1) { ACE_ASSERT (false); return 0; // This should not happen! } // Check to see if this is the first time in for this thread. // This block can also be entered after a fork () in the child process. if (old_ts_storage == 0) { if (ts_created) *ts_created = 1u; // Use the ts_storage passed as argument, if non-zero. It is // possible that this has been implemented in the stack. At the // moment, this is unknown. The cleanup must not do nothing. // If ts_storage is zero, allocate (and eventually leak) the // storage array. if (ts_storage == 0) { ACE_NO_HEAP_CHECK; ACE_NEW_RETURN (ts_storage, void*[ACE_TSS_THREAD_KEYS_MAX], 0); // Zero the entire TSS array. Do it manually instead of // using memset, for optimum speed. Though, memset may be // faster :-) void **tss_base_p = ts_storage; for (u_int i = 0; i < ACE_TSS_THREAD_KEYS_MAX; ++i) *tss_base_p++ = 0; } // Store the pointer in thread-specific storage. It gets // deleted via the ACE_TSS_Emulation_cleanup function when the // thread terminates. if (ACE_OS::thr_setspecific_native (native_tss_key_, (void *) ts_storage) != 0) { ACE_ASSERT (false); return 0; // This should not happen! } } else if (ts_created) ts_created = 0; return ts_storage ? ts_storage : old_ts_storage; } # endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ u_int ACE_TSS_Emulation::total_keys () { ACE_OS_Recursive_Thread_Mutex_Guard ( *static_cast <ACE_recursive_thread_mutex_t *> (ACE_OS_Object_Manager::preallocated_object[ ACE_OS_Object_Manager::ACE_TSS_KEY_LOCK])); return total_keys_; } int ACE_TSS_Emulation::next_key (ACE_thread_key_t &key) { ACE_OS_Recursive_Thread_Mutex_Guard ( *static_cast <ACE_recursive_thread_mutex_t *> (ACE_OS_Object_Manager::preallocated_object[ ACE_OS_Object_Manager::ACE_TSS_KEY_LOCK])); // Initialize the tss_keys_used_ pointer on first use. if (tss_keys_used_ == 0) { ACE_NEW_RETURN (tss_keys_used_, ACE_TSS_Keys, -1); } if (total_keys_ < ACE_TSS_THREAD_KEYS_MAX) { u_int counter = 0; // Loop through all possible keys and check whether a key is free for ( ;counter < ACE_TSS_THREAD_KEYS_MAX; counter++) { ACE_thread_key_t localkey; # if defined (ACE_HAS_NONSCALAR_THREAD_KEY_T) ACE_OS::memset (&localkey, 0, sizeof (ACE_thread_key_t)); ACE_OS::memcpy (&localkey, &counter_, sizeof (u_int)); # else localkey = counter; # endif /* ACE_HAS_NONSCALAR_THREAD_KEY_T */ // If the key is not set as used, we can give out this key, if not // we have to search further if (tss_keys_used_->is_set(localkey) == 0) { tss_keys_used_->test_and_set(localkey); key = localkey; break; } } ++total_keys_; return 0; } else { key = ACE_OS::NULL_key; return -1; } } int ACE_TSS_Emulation::release_key (ACE_thread_key_t key) { ACE_OS_Recursive_Thread_Mutex_Guard ( *static_cast <ACE_recursive_thread_mutex_t *> (ACE_OS_Object_Manager::preallocated_object[ ACE_OS_Object_Manager::ACE_TSS_KEY_LOCK])); if (tss_keys_used_ != 0 && tss_keys_used_->test_and_clear (key) == 0) { --total_keys_; return 0; } return 1; } int ACE_TSS_Emulation::is_key (ACE_thread_key_t key) { ACE_OS_Recursive_Thread_Mutex_Guard ( *static_cast <ACE_recursive_thread_mutex_t *> (ACE_OS_Object_Manager::preallocated_object[ ACE_OS_Object_Manager::ACE_TSS_KEY_LOCK])); if (tss_keys_used_ != 0 && tss_keys_used_->is_set (key) == 1) { return 1; } return 0; } void * ACE_TSS_Emulation::tss_open (void *ts_storage[ACE_TSS_THREAD_KEYS_MAX]) { # if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) // On VxWorks, in particular, don't check to see if the field // is 0. It isn't always, specifically, when a program is run // directly by the shell (without spawning a new task) after // another program has been run. u_int ts_created = 0; tss_base (ts_storage, &ts_created); if (ts_created) { # else /* ! ACE_HAS_THREAD_SPECIFIC_STORAGE */ tss_base () = ts_storage; # endif // Zero the entire TSS array. Do it manually instead of using // memset, for optimum speed. Though, memset may be faster :-) void **tss_base_p = tss_base (); for (u_int i = 0; i < ACE_TSS_THREAD_KEYS_MAX; ++i, ++tss_base_p) { *tss_base_p = 0; } return tss_base (); # if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) } else { return 0; } # endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ } void ACE_TSS_Emulation::tss_close () { #if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) ACE_OS::thr_keyfree_native (native_tss_key_); #endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ } #endif /* ACE_HAS_TSS_EMULATION */ #endif /* WIN32 || ACE_HAS_TSS_EMULATION */ /*****************************************************************************/ #if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) // Moved class ACE_TSS_Ref declaration to OS.h so it can be visible to // the single file of template instantiations. ACE_TSS_Ref::ACE_TSS_Ref (ACE_thread_t id) : tid_(id) { ACE_OS_TRACE ("ACE_TSS_Ref::ACE_TSS_Ref"); } ACE_TSS_Ref::ACE_TSS_Ref (void) { ACE_OS_TRACE ("ACE_TSS_Ref::ACE_TSS_Ref"); } // Check for equality. bool ACE_TSS_Ref::operator== (const ACE_TSS_Ref &info) const { ACE_OS_TRACE ("ACE_TSS_Ref::operator=="); return this->tid_ == info.tid_; } // Check for inequality. ACE_SPECIAL_INLINE bool ACE_TSS_Ref::operator != (const ACE_TSS_Ref &tss_ref) const { ACE_OS_TRACE ("ACE_TSS_Ref::operator !="); return !(*this == tss_ref); } // moved class ACE_TSS_Info declaration // to OS.h so it can be visible to the // single file of template instantiations ACE_TSS_Info::ACE_TSS_Info (ACE_thread_key_t key, ACE_TSS_Info::Destructor dest) : key_ (key), destructor_ (dest), thread_count_ (-1) { ACE_OS_TRACE ("ACE_TSS_Info::ACE_TSS_Info"); } ACE_TSS_Info::ACE_TSS_Info (void) : key_ (ACE_OS::NULL_key), destructor_ (0), thread_count_ (-1) { ACE_OS_TRACE ("ACE_TSS_Info::ACE_TSS_Info"); } # if defined (ACE_HAS_NONSCALAR_THREAD_KEY_T) static inline bool operator== (const ACE_thread_key_t &lhs, const ACE_thread_key_t &rhs) { return ! ACE_OS::memcmp (&lhs, &rhs, sizeof (ACE_thread_key_t)); } static inline bool operator!= (const ACE_thread_key_t &lhs, const ACE_thread_key_t &rhs) { return ! (lhs == rhs); } # endif /* ACE_HAS_NONSCALAR_THREAD_KEY_T */ // Check for equality. bool ACE_TSS_Info::operator== (const ACE_TSS_Info &info) const { ACE_OS_TRACE ("ACE_TSS_Info::operator=="); return this->key_ == info.key_; } // Check for inequality. bool ACE_TSS_Info::operator != (const ACE_TSS_Info &info) const { ACE_OS_TRACE ("ACE_TSS_Info::operator !="); return !(*this == info); } void ACE_TSS_Info::dump (void) { # if defined (ACE_HAS_DUMP) // ACE_OS_TRACE ("ACE_TSS_Info::dump"); # if 0 ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("key_ = %u\n"), this->key_)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("destructor_ = %u\n"), this->destructor_)); ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP)); # endif /* 0 */ # endif /* ACE_HAS_DUMP */ } // Moved class ACE_TSS_Keys declaration to OS.h so it can be visible // to the single file of template instantiations. ACE_TSS_Keys::ACE_TSS_Keys (void) { for (u_int i = 0; i < ACE_WORDS; ++i) { key_bit_words_[i] = 0; } } ACE_SPECIAL_INLINE void ACE_TSS_Keys::find (const u_int key, u_int &word, u_int &bit) { word = key / ACE_BITS_PER_WORD; bit = key % ACE_BITS_PER_WORD; } int ACE_TSS_Keys::test_and_set (const ACE_thread_key_t key) { ACE_KEY_INDEX (key_index, key); u_int word, bit; find (key_index, word, bit); if (ACE_BIT_ENABLED (key_bit_words_[word], 1 << bit)) { return 1; } else { ACE_SET_BITS (key_bit_words_[word], 1 << bit); return 0; } } int ACE_TSS_Keys::test_and_clear (const ACE_thread_key_t key) { ACE_KEY_INDEX (key_index, key); u_int word, bit; find (key_index, word, bit); if (word < ACE_WORDS && ACE_BIT_ENABLED (key_bit_words_[word], 1 << bit)) { ACE_CLR_BITS (key_bit_words_[word], 1 << bit); return 0; } else { return 1; } } int ACE_TSS_Keys::is_set (const ACE_thread_key_t key) const { ACE_KEY_INDEX (key_index, key); u_int word, bit; find (key_index, word, bit); return word < ACE_WORDS ? ACE_BIT_ENABLED (key_bit_words_[word], 1 << bit) : 0; } /** * @class ACE_TSS_Cleanup * @brief Singleton that helps to manage the lifetime of TSS objects and keys. */ class ACE_TSS_Cleanup { public: /// Register a newly-allocated key /// @param key the key to be monitored /// @param destructor the function to call to delete objects stored via this key int insert (ACE_thread_key_t key, void (*destructor)(void *)); /// Mark a key as being used by this thread. void thread_use_key (ACE_thread_key_t key); /// This thread is no longer using this key /// call destructor if appropriate int thread_detach_key (ACE_thread_key_t key); /// This key is no longer used /// Release key if use count == 0 /// fail if use_count != 0; /// @param key the key to be released int free_key (ACE_thread_key_t key); /// Cleanup the thread-specific objects. Does _NOT_ exit the thread. /// For each used key perform the same actions as free_key. void thread_exit (void); private: void dump (void); /// Release a key used by this thread /// @param info reference to the info for this key /// @param destructor out arg to receive destructor function ptr /// @param tss_obj out arg to receive pointer to deletable object void thread_release ( ACE_TSS_Info &info, ACE_TSS_Info::Destructor & destructor, void *& tss_obj); /// remove key if it's unused (thread_count == 0) /// @param info reference to the info for this key int remove_key (ACE_TSS_Info &info); /// Find the TSS keys (if any) for this thread. /// @param thread_keys reference to pointer to be filled in by this function. /// @return false if keys don't exist. bool find_tss_keys (ACE_TSS_Keys *& thread_keys) const; /// Accessor for this threads ACE_TSS_Keys instance. /// Creates the keys if necessary. ACE_TSS_Keys *tss_keys (); /// Ensure singleton. ACE_TSS_Cleanup (void); ~ACE_TSS_Cleanup (void); /// ACE_TSS_Cleanup access only via TSS_Cleanup_Instance friend class TSS_Cleanup_Instance; private: // Array of <ACE_TSS_Info> objects. typedef ACE_TSS_Info ACE_TSS_TABLE[ACE_DEFAULT_THREAD_KEYS]; typedef ACE_TSS_Info *ACE_TSS_TABLE_ITERATOR; /// Table of <ACE_TSS_Info>'s. ACE_TSS_TABLE table_; /// Key for the thread-specific ACE_TSS_Keys /// Used by find_tss_keys() or tss_keys() to find the /// bit array that records whether each TSS key is in /// use by this thread. ACE_thread_key_t in_use_; }; /*****************************************************************************/ /** * @class TSS_Cleanup_Instance * @A class to manage an instance pointer to ACE_TSS_Cleanup. * Note: that the double checked locking pattern doesn't allow * safe deletion. * Callers who wish to access the singleton ACE_TSS_Cleanup must * do so by instantiating a TSS_Cleanup_Instance, calling the valid * method to be sure the ACE_TSS_Cleanup is available, then using * the TSS_Cleanup_Instance as a pointer to the instance. * Construction argument to the TSS_Cleanup_Instance determines how * it is to be used: * CREATE means allow this call to create an ACE_TSS_Cleanup if necessary. * USE means use the existing ACE_TSS_Cleanup, but do not create a new one. * DESTROY means provide exclusive access to the ACE_TSS_Cleanup, then * delete it when the TSS_Cleanup_Instance goes out of scope. */ class TSS_Cleanup_Instance { public: enum Purpose { CREATE, USE, DESTROY }; TSS_Cleanup_Instance (Purpose purpose = USE); ~TSS_Cleanup_Instance(); bool valid(); ACE_TSS_Cleanup * operator ->(); private: ACE_TSS_Cleanup * operator *(); private: static unsigned int reference_count_; static ACE_TSS_Cleanup * instance_; static ACE_Thread_Mutex* mutex_; static ACE_Thread_Condition<ACE_Thread_Mutex>* condition_; private: ACE_TSS_Cleanup * ptr_; unsigned short flags_; enum { FLAG_DELETING = 1, FLAG_VALID_CHECKED = 2 }; }; TSS_Cleanup_Instance::TSS_Cleanup_Instance (Purpose purpose) : ptr_(0) , flags_(0) { // During static construction or construction of the ACE_Object_Manager, // there can be only one thread in this constructor at any one time, so // it's safe to check for a zero mutex_. If it's zero, we create a new // mutex and condition variable. if (mutex_ == 0) { ACE_NEW (mutex_, ACE_Thread_Mutex ()); ACE_NEW (condition_, ACE_Thread_Condition<ACE_Thread_Mutex> (*mutex_)); } ACE_Guard<ACE_Thread_Mutex> guard(*mutex_); if (purpose == CREATE) { if (instance_ == 0) { instance_ = new ACE_TSS_Cleanup(); } ptr_ = instance_; ++reference_count_; } else if(purpose == DESTROY) { if (instance_ != 0) { ptr_ = instance_; instance_ = 0; ACE_SET_BITS(flags_, FLAG_DELETING); while (reference_count_ > 0) { condition_->wait(); } } } else // must be normal use { ACE_ASSERT(purpose == USE); if (instance_ != 0) { ptr_ = instance_; ++reference_count_; } } } TSS_Cleanup_Instance::~TSS_Cleanup_Instance (void) { // Variable to hold the mutex_ to delete outside the scope of the // guard. ACE_Thread_Mutex *del_mutex = 0; // scope the guard { ACE_GUARD (ACE_Thread_Mutex, guard, *mutex_); if (ptr_ != 0) { if (ACE_BIT_ENABLED (flags_, FLAG_DELETING)) { ACE_ASSERT(instance_ == 0); ACE_ASSERT(reference_count_ == 0); delete ptr_; del_mutex = mutex_ ; mutex_ = 0; } else { ACE_ASSERT (reference_count_ > 0); --reference_count_; if (reference_count_ == 0 && instance_ == 0) condition_->signal (); } } }// end of guard scope if (del_mutex != 0) { delete condition_; condition_ = 0; delete del_mutex; } } bool TSS_Cleanup_Instance::valid() { ACE_SET_BITS(flags_, FLAG_VALID_CHECKED); return (this->instance_ != 0); } ACE_TSS_Cleanup * TSS_Cleanup_Instance::operator *() { ACE_ASSERT(ACE_BIT_ENABLED(flags_, FLAG_VALID_CHECKED)); return instance_; } ACE_TSS_Cleanup * TSS_Cleanup_Instance::operator ->() { ACE_ASSERT(ACE_BIT_ENABLED(flags_, FLAG_VALID_CHECKED)); return instance_; } // = Static object initialization. unsigned int TSS_Cleanup_Instance::reference_count_ = 0; ACE_TSS_Cleanup * TSS_Cleanup_Instance::instance_ = 0; ACE_Thread_Mutex* TSS_Cleanup_Instance::mutex_ = 0; ACE_Thread_Condition<ACE_Thread_Mutex>* TSS_Cleanup_Instance::condition_ = 0; ACE_TSS_Cleanup::~ACE_TSS_Cleanup (void) { } void ACE_TSS_Cleanup::thread_exit (void) { ACE_OS_TRACE ("ACE_TSS_Cleanup::thread_exit"); // variables to hold the destructors, keys // and pointers to the object to be destructed // the actual destruction is deferred until the guard is released ACE_TSS_Info::Destructor destructor[ACE_DEFAULT_THREAD_KEYS]; void * tss_obj[ACE_DEFAULT_THREAD_KEYS]; ACE_thread_key_t keys[ACE_DEFAULT_THREAD_KEYS]; // count of items to be destroyed unsigned int d_count = 0; // scope the guard { ACE_TSS_CLEANUP_GUARD // if not initialized or already cleaned up ACE_TSS_Keys *this_thread_keys = 0; if (! find_tss_keys (this_thread_keys) ) { return; } // Minor hack: Iterating in reverse order means the LOG buffer which is // accidentally allocated first will be accidentally deallocated (almost) // last -- in case someone logs something from the other destructors. // applications should not count on this behavior because platforms which // do not use ACE_TSS_Cleanup may delete objects in other orders. unsigned int key_index = ACE_DEFAULT_THREAD_KEYS; while( key_index > 0) { --key_index; ACE_TSS_Info & info = this->table_[key_index]; // if this key is in use by this thread if (info.key_in_use () && this_thread_keys->is_set(info.key_)) { // defer deleting the in-use key until all others have been deleted if(info.key_ != this->in_use_) { destructor[d_count] = 0; tss_obj[d_count] = 0; keys[d_count] = 0; this->thread_release (info, destructor[d_count], tss_obj[d_count]); if (destructor[d_count] != 0 && tss_obj[d_count] != 0) { keys[d_count] = info.key_; ++d_count; } } } } // remove the in_use bit vector last ACE_KEY_INDEX (use_index, this->in_use_); ACE_TSS_Info & info = this->table_[use_index]; destructor[d_count] = 0; tss_obj[d_count] = 0; keys[d_count] = 0; this->thread_release (info, destructor[d_count], tss_obj[d_count]); if (destructor[d_count] != 0 && tss_obj[d_count] != 0) { keys[d_count] = info.key_; ++d_count; } } // end of guard scope for (unsigned int d_index = 0; d_index < d_count; ++d_index) { (*destructor[d_index])(tss_obj[d_index]); #if defined (ACE_HAS_TSS_EMULATION) ACE_TSS_Emulation::ts_object (keys[d_index]) = 0; #else // defined (ACE_HAS_TSS_EMULATION) ACE_OS::thr_setspecific_native (keys[d_index], 0); #endif // defined (ACE_HAS_TSS_EMULATION) } } extern "C" void ACE_TSS_Cleanup_keys_destroyer (void *tss_keys) { delete static_cast <ACE_TSS_Keys *> (tss_keys); } ACE_TSS_Cleanup::ACE_TSS_Cleanup (void) : in_use_ (ACE_OS::NULL_key) { ACE_OS_TRACE ("ACE_TSS_Cleanup::ACE_TSS_Cleanup"); } int ACE_TSS_Cleanup::insert (ACE_thread_key_t key, void (*destructor)(void *)) { ACE_OS_TRACE ("ACE_TSS_Cleanup::insert"); ACE_TSS_CLEANUP_GUARD ACE_KEY_INDEX (key_index, key); ACE_ASSERT (key_index < ACE_DEFAULT_THREAD_KEYS); if (key_index < ACE_DEFAULT_THREAD_KEYS) { ACE_ASSERT (table_[key_index].thread_count_ == -1); table_[key_index] = ACE_TSS_Info (key, destructor); table_[key_index].thread_count_ = 0; // inserting it does not use it // but it does "allocate" it return 0; } else { return -1; } } int ACE_TSS_Cleanup::free_key (ACE_thread_key_t key) { ACE_OS_TRACE ("ACE_TSS_Cleanup::free_key"); ACE_TSS_CLEANUP_GUARD ACE_KEY_INDEX (key_index, key); if (key_index < ACE_DEFAULT_THREAD_KEYS) { return remove_key (this->table_ [key_index]); } return -1; } int ACE_TSS_Cleanup::remove_key (ACE_TSS_Info &info) { // assume CLEANUP_GUARD is held by caller ACE_OS_TRACE ("ACE_TSS_Cleanup::remove_key"); #if 0 // This was a good idea, but POSIX says it's legal to delete used keys. // When this is done, any existing TSS objects controlled by this key are leaked // There is no "right thing" to do in this case // only remove it if all threads are done with it if (info.thread_count_ != 0) { return -1; } #endif // 0 #if !defined (ACE_HAS_TSS_EMULATION) ACE_OS_thread_key_t temp_key = info.key_; ACE_OS::thr_keyfree_native (temp_key); #endif /* !ACE_HAS_TSS_EMULATION */ if (info.key_ == this->in_use_) { this->in_use_ = ACE_OS::NULL_key; } info.key_in_use (0); info.destructor_ = 0; return 0; } int ACE_TSS_Cleanup::thread_detach_key (ACE_thread_key_t key) { // variables to hold the destructor and the object to be destructed // the actual call is deferred until the guard is released ACE_TSS_Info::Destructor destructor = 0; void * tss_obj = 0; // scope the guard { ACE_TSS_CLEANUP_GUARD ACE_KEY_INDEX (key_index, key); ACE_ASSERT (key_index < sizeof(this->table_)/sizeof(this->table_[0]) && this->table_[key_index].key_ == key); ACE_TSS_Info &info = this->table_ [key_index]; // sanity check if (!info.key_in_use ()) { return -1; } this->thread_release (info, destructor, tss_obj); } // end of scope for the Guard // if there's a destructor and an object to be destroyed if (destructor != 0 && tss_obj != 0) { (*destructor) (tss_obj); } return 0; } void ACE_TSS_Cleanup::thread_release ( ACE_TSS_Info &info, ACE_TSS_Info::Destructor & destructor, void *& tss_obj) { // assume guard is held by caller // Find the TSS keys (if any) for this thread // do not create them if they don't exist ACE_TSS_Keys * thread_keys = 0; if (find_tss_keys (thread_keys)) { // if this key is in use by this thread if (thread_keys->test_and_clear(info.key_) == 0) { // save destructor & pointer to tss object // until after the guard is released destructor = info.destructor_; ACE_OS::thr_getspecific (info.key_, &tss_obj); ACE_ASSERT (info.thread_count_ > 0); --info.thread_count_; } } } void ACE_TSS_Cleanup::thread_use_key (ACE_thread_key_t key) { // If the key's ACE_TSS_Info in-use bit for this thread is not set, // set it and increment the key's thread_count_. if (! tss_keys ()->test_and_set (key)) { ACE_TSS_CLEANUP_GUARD // Retrieve the key's ACE_TSS_Info and increment its thread_count_. ACE_KEY_INDEX (key_index, key); ACE_TSS_Info &key_info = this->table_ [key_index]; ACE_ASSERT (key_info.key_in_use ()); ++key_info.thread_count_; } } void ACE_TSS_Cleanup::dump (void) { # if defined (ACE_HAS_DUMP) // Iterate through all the thread-specific items and dump them all. ACE_TSS_TABLE_ITERATOR key_info = table_; for (unsigned int i = 0; i < ACE_DEFAULT_THREAD_KEYS; ++key_info, ++i) key_info->dump (); # endif /* ACE_HAS_DUMP */ } bool ACE_TSS_Cleanup::find_tss_keys (ACE_TSS_Keys *& tss_keys) const { if (this->in_use_ == ACE_OS::NULL_key) return false; if (ACE_OS::thr_getspecific (in_use_, reinterpret_cast<void **> (&tss_keys)) == -1) { ACE_ASSERT (false); return false; // This should not happen! } return tss_keys != 0; } ACE_TSS_Keys * ACE_TSS_Cleanup::tss_keys () { if (this->in_use_ == ACE_OS::NULL_key) { ACE_TSS_CLEANUP_GUARD // Double-check; if (in_use_ == ACE_OS::NULL_key) { // Initialize in_use_ with a new key. if (ACE_OS::thr_keycreate (&in_use_, &ACE_TSS_Cleanup_keys_destroyer)) { ACE_ASSERT (false); return 0; // Major problems, this should *never* happen! } } } void *ts_keys = 0; if (ACE_OS::thr_getspecific (in_use_, &ts_keys) == -1) { ACE_ASSERT (false); return 0; // This should not happen! } if (ts_keys == 0) { ACE_NEW_RETURN (ts_keys, ACE_TSS_Keys, 0); // Store the dynamically allocated pointer in thread-specific // storage. if (ACE_OS::thr_setspecific (in_use_, ts_keys) == -1) { ACE_ASSERT (false); delete reinterpret_cast <ACE_TSS_Keys*> (ts_keys); return 0; // Major problems, this should *never* happen! } } return reinterpret_cast <ACE_TSS_Keys*>(ts_keys); } #endif /* ACE_WIN32 || ACE_HAS_TSS_EMULATION */ /*****************************************************************************/ // = Static initialization. // This is necessary to deal with POSIX pthreads insanity. This // guarantees that we've got a "zero'd" thread id even when // ACE_thread_t, ACE_hthread_t, and ACE_thread_key_t are implemented // as structures... Under no circumstances should these be given // initial values. // Note: these three objects require static construction. ACE_thread_t ACE_OS::NULL_thread; ACE_hthread_t ACE_OS::NULL_hthread; #if defined (ACE_HAS_TSS_EMULATION) ACE_thread_key_t ACE_OS::NULL_key = static_cast <ACE_thread_key_t> (-1); #else /* ! ACE_HAS_TSS_EMULATION */ ACE_thread_key_t ACE_OS::NULL_key; #endif /* ! ACE_HAS_TSS_EMULATION */ /*****************************************************************************/ void ACE_OS::cleanup_tss (const u_int main_thread) { #if defined (ACE_HAS_TSS_EMULATION) || defined (ACE_WIN32) { // scope the cleanup instance // Call TSS destructors for current thread. TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { cleanup->thread_exit (); } } #endif /* ACE_HAS_TSS_EMULATION || ACE_WIN32 */ if (main_thread) { #if !defined (ACE_HAS_TSS_EMULATION) && !defined (ACE_HAS_MINIMAL_ACE_OS) // Just close the ACE_Log_Msg for the current (which should be // main) thread. We don't have TSS emulation; if there's native // TSS, it should call its destructors when the main thread // exits. ACE_Base_Thread_Adapter::close_log_msg (); #endif /* ! ACE_HAS_TSS_EMULATION && ! ACE_HAS_MINIMAL_ACE_OS */ #if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) // Finally, free up the ACE_TSS_Cleanup instance. This method gets // called by the ACE_Object_Manager. TSS_Cleanup_Instance cleanup(TSS_Cleanup_Instance::DESTROY); if (cleanup.valid ()) { ; // the pointer deletes the Cleanup when it goes out of scope } #endif /* WIN32 || ACE_HAS_TSS_EMULATION */ #if defined (ACE_HAS_TSS_EMULATION) ACE_TSS_Emulation::tss_close (); #endif /* ACE_HAS_TSS_EMULATION */ } } /*****************************************************************************/ // CONDITIONS BEGIN /*****************************************************************************/ #if defined (ACE_LACKS_COND_T) int ACE_OS::cond_broadcast (ACE_cond_t *cv) { ACE_OS_TRACE ("ACE_OS::cond_broadcast"); # if defined (ACE_HAS_THREADS) // The <external_mutex> must be locked before this call is made. // This is needed to ensure that <waiters_> and <was_broadcast_> are // consistent relative to each other. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) { return -1; } bool have_waiters = false; if (cv->waiters_ > 0) { // We are broadcasting, even if there is just one waiter... // Record the fact that we are broadcasting. This helps the // cond_wait() method know how to optimize itself. Be sure to // set this with the <waiters_lock_> held. cv->was_broadcast_ = 1; have_waiters = true; } if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) { // This is really bad, we have the lock but can't release it anymore return -1; } int result = 0; if (have_waiters) { // Wake up all the waiters. if (ACE_OS::sema_post (&cv->sema_, cv->waiters_) == -1) result = -1; // Wait for all the awakened threads to acquire their part of // the counting semaphore. # if defined (ACE_VXWORKS) else if (ACE_OS::sema_wait (&cv->waiters_done_) == -1) # else else if (ACE_OS::event_wait (&cv->waiters_done_) == -1) # endif /* ACE_VXWORKS */ result = -1; // This is okay, even without the <waiters_lock_> held because // no other waiter threads can wake up to access it. cv->was_broadcast_ = 0; } return result; # else ACE_UNUSED_ARG (cv); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } int ACE_OS::cond_destroy (ACE_cond_t *cv) { ACE_OS_TRACE ("ACE_OS::cond_destroy"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_WTHREADS) ACE_OS::event_destroy (&cv->waiters_done_); # elif defined (ACE_VXWORKS) ACE_OS::sema_destroy (&cv->waiters_done_); # endif /* ACE_VXWORKS */ int result = 0; if (ACE_OS::thread_mutex_destroy (&cv->waiters_lock_) != 0) result = -1; if (ACE_OS::sema_destroy (&cv->sema_) != 0) result = -1; return result; # else ACE_UNUSED_ARG (cv); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } int ACE_OS::cond_init (ACE_cond_t *cv, ACE_condattr_t &attributes, const char *name, void *arg) { return ACE_OS::cond_init (cv, static_cast<short> (attributes.type), name, arg); } # if defined (ACE_HAS_WCHAR) int ACE_OS::cond_init (ACE_cond_t *cv, ACE_condattr_t &attributes, const wchar_t *name, void *arg) { return ACE_OS::cond_init (cv, static_cast<short> (attributes.type), name, arg); } # endif /* ACE_HAS_WCHAR */ int ACE_OS::cond_init (ACE_cond_t *cv, short type, const char *name, void *arg) { ACE_OS_TRACE ("ACE_OS::cond_init"); # if defined (ACE_HAS_THREADS) cv->waiters_ = 0; cv->was_broadcast_ = 0; int result = 0; if (ACE_OS::sema_init (&cv->sema_, 0, type, name, arg) == -1) result = -1; else if (ACE_OS::thread_mutex_init (&cv->waiters_lock_) == -1) result = -1; # if defined (ACE_VXWORKS) else if (ACE_OS::sema_init (&cv->waiters_done_, 0, type) == -1) # else else if (ACE_OS::event_init (&cv->waiters_done_) == -1) # endif /* ACE_VXWORKS */ result = -1; return result; # else ACE_UNUSED_ARG (cv); ACE_UNUSED_ARG (type); ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (arg); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } # if defined (ACE_HAS_WCHAR) int ACE_OS::cond_init (ACE_cond_t *cv, short type, const wchar_t *name, void *arg) { ACE_OS_TRACE ("ACE_OS::cond_init"); # if defined (ACE_HAS_THREADS) cv->waiters_ = 0; cv->was_broadcast_ = 0; int result = 0; if (ACE_OS::sema_init (&cv->sema_, 0, type, name, arg) == -1) result = -1; else if (ACE_OS::thread_mutex_init (&cv->waiters_lock_) == -1) result = -1; # if defined (ACE_VXWORKS) else if (ACE_OS::sema_init (&cv->waiters_done_, 0, type) == -1) # else else if (ACE_OS::event_init (&cv->waiters_done_) == -1) # endif /* ACE_VXWORKS */ result = -1; return result; # else ACE_UNUSED_ARG (cv); ACE_UNUSED_ARG (type); ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (arg); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } # endif /* ACE_HAS_WCHAR */ int ACE_OS::cond_signal (ACE_cond_t *cv) { ACE_OS_TRACE ("ACE_OS::cond_signal"); # if defined (ACE_HAS_THREADS) // If there aren't any waiters, then this is a no-op. Note that // this function *must* be called with the <external_mutex> held // since other wise there is a race condition that can lead to the // lost wakeup bug... This is needed to ensure that the <waiters_> // value is not in an inconsistent internal state while being // updated by another thread. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; bool const have_waiters = cv->waiters_ > 0; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; if (have_waiters) return ACE_OS::sema_post (&cv->sema_); else return 0; // No-op # else ACE_UNUSED_ARG (cv); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } int ACE_OS::cond_wait (ACE_cond_t *cv, ACE_mutex_t *external_mutex) { ACE_OS_TRACE ("ACE_OS::cond_wait"); # if defined (ACE_HAS_THREADS) // Prevent race conditions on the <waiters_> count. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; ++cv->waiters_; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; int result = 0; # if defined (ACE_HAS_SIGNAL_OBJECT_AND_WAIT) if (external_mutex->type_ == USYNC_PROCESS) { // This call will automatically release the mutex and wait on the semaphore. ACE_WIN32CALL (ACE_ADAPT_RETVAL (::SignalObjectAndWait (external_mutex->proc_mutex_, cv->sema_, INFINITE, FALSE), result), int, -1, result); if (result == -1) return result; } else # endif /* ACE_HAS_SIGNAL_OBJECT_AND_WAIT */ { // We keep the lock held just long enough to increment the count of // waiters by one. Note that we can't keep it held across the call // to ACE_OS::sema_wait() since that will deadlock other calls to // ACE_OS::cond_signal(). if (ACE_OS::mutex_unlock (external_mutex) != 0) return -1; // Wait to be awakened by a ACE_OS::cond_signal() or // ACE_OS::cond_broadcast(). result = ACE_OS::sema_wait (&cv->sema_); } // Reacquire lock to avoid race conditions on the <waiters_> count. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; // We're ready to return, so there's one less waiter. --cv->waiters_; bool const last_waiter = cv->was_broadcast_ && cv->waiters_ == 0; // Release the lock so that other collaborating threads can make // progress. if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; if (result == -1) // Bad things happened, so let's just return below. /* NOOP */; # if defined (ACE_HAS_SIGNAL_OBJECT_AND_WAIT) else if (external_mutex->type_ == USYNC_PROCESS) { if (last_waiter) // This call atomically signals the <waiters_done_> event and // waits until it can acquire the mutex. This is important to // prevent unfairness. ACE_WIN32CALL (ACE_ADAPT_RETVAL (::SignalObjectAndWait (cv->waiters_done_, external_mutex->proc_mutex_, INFINITE, FALSE), result), int, -1, result); else // We must always regain the <external_mutex>, even when // errors occur because that's the guarantee that we give to // our callers. if (ACE_OS::mutex_lock (external_mutex) != 0) return -1; return result; /* NOTREACHED */ } # endif /* ACE_HAS_SIGNAL_OBJECT_AND_WAIT */ // If we're the last waiter thread during this particular broadcast // then let all the other threads proceed. else if (last_waiter) # if defined (ACE_VXWORKS) ACE_OS::sema_post (&cv->waiters_done_); # else ACE_OS::event_signal (&cv->waiters_done_); # endif /* ACE_VXWORKS */ // We must always regain the <external_mutex>, even when errors // occur because that's the guarantee that we give to our callers. ACE_OS::mutex_lock (external_mutex); return result; # else ACE_UNUSED_ARG (cv); ACE_UNUSED_ARG (external_mutex); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } int ACE_OS::cond_timedwait (ACE_cond_t *cv, ACE_mutex_t *external_mutex, ACE_Time_Value *timeout) { ACE_OS_TRACE ("ACE_OS::cond_timedwait"); # if defined (ACE_HAS_THREADS) // Handle the easy case first. if (timeout == 0) return ACE_OS::cond_wait (cv, external_mutex); # if defined (ACE_HAS_WTHREADS) || defined (ACE_VXWORKS) // Prevent race conditions on the <waiters_> count. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; ++cv->waiters_; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; int result = 0; ACE_Errno_Guard error (errno, 0); int msec_timeout = 0; if (timeout != 0 && *timeout != ACE_Time_Value::zero) { // Note that we must convert between absolute time (which is // passed as a parameter) and relative time (which is what // WaitForSingleObjects() expects). ACE_Time_Value relative_time (*timeout - ACE_OS::gettimeofday ()); // Watchout for situations where a context switch has caused the // current time to be > the timeout. if (relative_time > ACE_Time_Value::zero) msec_timeout = relative_time.msec (); } # if defined (ACE_HAS_SIGNAL_OBJECT_AND_WAIT) if (external_mutex->type_ == USYNC_PROCESS) // This call will automatically release the mutex and wait on the // semaphore. result = ::SignalObjectAndWait (external_mutex->proc_mutex_, cv->sema_, msec_timeout, FALSE); else # endif /* ACE_HAS_SIGNAL_OBJECT_AND_WAIT */ { // We keep the lock held just long enough to increment the count // of waiters by one. Note that we can't keep it held across // the call to WaitForSingleObject since that will deadlock // other calls to ACE_OS::cond_signal(). if (ACE_OS::mutex_unlock (external_mutex) != 0) return -1; // Wait to be awakened by a ACE_OS::signal() or // ACE_OS::broadcast(). # if defined (ACE_WIN32) # if !defined (ACE_USES_WINCE_SEMA_SIMULATION) result = ::WaitForSingleObject (cv->sema_, msec_timeout); # else /* ACE_USES_WINCE_SEMA_SIMULATION */ // Can't use Win32 API on our simulated semaphores. result = ACE_OS::sema_wait (&cv->sema_, timeout); # endif /* ACE_USES_WINCE_SEMA_SIMULATION */ # elif defined (ACE_VXWORKS) // Inline the call to ACE_OS::sema_wait () because it takes an // ACE_Time_Value argument. Avoid the cost of that conversion . . . int const ticks_per_sec = ::sysClkRateGet (); int const ticks = msec_timeout * ticks_per_sec / ACE_ONE_SECOND_IN_MSECS; result = ::semTake (cv->sema_.sema_, ticks); # endif /* ACE_WIN32 || VXWORKS */ } // Reacquire lock to avoid race conditions. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; --cv->waiters_; bool const last_waiter = cv->was_broadcast_ && cv->waiters_ == 0; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; # if defined (ACE_WIN32) if (result != WAIT_OBJECT_0) { switch (result) { case WAIT_TIMEOUT: error = ETIME; break; default: error = ::GetLastError (); break; } result = -1; } # elif defined (ACE_VXWORKS) if (result == ERROR) { switch (errno) { case S_objLib_OBJ_TIMEOUT: error = ETIME; break; case S_objLib_OBJ_UNAVAILABLE: if (msec_timeout == 0) error = ETIME; break; default: error = errno; break; } result = -1; } # endif /* ACE_WIN32 || VXWORKS */ # if defined (ACE_HAS_SIGNAL_OBJECT_AND_WAIT) if (external_mutex->type_ == USYNC_PROCESS) { if (last_waiter) // This call atomically signals the <waiters_done_> event and // waits until it can acquire the mutex. This is important to // prevent unfairness. ACE_WIN32CALL (ACE_ADAPT_RETVAL (::SignalObjectAndWait (cv->waiters_done_, external_mutex->proc_mutex_, INFINITE, FALSE), result), int, -1, result); else { // We must always regain the <external_Mutex>, even when // errors occur because that's the guarantee that we give to // our callers. if (ACE_OS::mutex_lock (external_mutex) != 0) return -1; } return result; /* NOTREACHED */ } # endif /* ACE_HAS_SIGNAL_OBJECT_AND_WAIT */ // Note that this *must* be an "if" statement rather than an "else // if" statement since the caller may have timed out and hence the // result would have been -1 above. if (last_waiter) { // Release the signaler/broadcaster if we're the last waiter. # if defined (ACE_WIN32) if (ACE_OS::event_signal (&cv->waiters_done_) != 0) # else if (ACE_OS::sema_post (&cv->waiters_done_) != 0) # endif /* ACE_WIN32 */ return -1; } // We must always regain the <external_mutex>, even when errors // occur because that's the guarantee that we give to our callers. if (ACE_OS::mutex_lock (external_mutex) != 0) return -1; return result; # endif /* ACE_HAS_WTHREADS || ACE_HAS_VXWORKS */ # else ACE_UNUSED_ARG (cv); ACE_UNUSED_ARG (external_mutex); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } #else int ACE_OS::cond_init (ACE_cond_t *cv, short type, const char *name, void *arg) { ACE_condattr_t attributes; if (ACE_OS::condattr_init (attributes, type) == 0 && ACE_OS::cond_init (cv, attributes, name, arg) == 0) { (void) ACE_OS::condattr_destroy (attributes); return 0; } return -1; } #endif /* ACE_LACKS_COND_T */ #if defined (ACE_WIN32) && defined (ACE_HAS_WTHREADS) int ACE_OS::cond_timedwait (ACE_cond_t *cv, ACE_thread_mutex_t *external_mutex, ACE_Time_Value *timeout) { ACE_OS_TRACE ("ACE_OS::cond_timedwait"); # if defined (ACE_HAS_THREADS) // Handle the easy case first. if (timeout == 0) return ACE_OS::cond_wait (cv, external_mutex); # if defined (ACE_HAS_WTHREADS_CONDITION_VARIABLE) int msec_timeout = 0; int result = 0; ACE_Time_Value relative_time (*timeout - ACE_OS::gettimeofday ()); // Watchout for situations where a context switch has caused the // current time to be > the timeout. if (relative_time > ACE_Time_Value::zero) msec_timeout = relative_time.msec (); ACE_OSCALL (ACE_ADAPT_RETVAL (::SleepConditionVariableCS (cv, external_mutex, msec_timeout), result), int, -1, result); return result; #else // Prevent race conditions on the <waiters_> count. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; ++cv->waiters_; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; int result = 0; int error = 0; int msec_timeout = 0; if (timeout != 0 && *timeout != ACE_Time_Value::zero) { // Note that we must convert between absolute time (which is // passed as a parameter) and relative time (which is what // WaitForSingleObjects() expects). ACE_Time_Value relative_time (*timeout - ACE_OS::gettimeofday ()); // Watchout for situations where a context switch has caused the // current time to be > the timeout. if (relative_time > ACE_Time_Value::zero) msec_timeout = relative_time.msec (); } // We keep the lock held just long enough to increment the count of // waiters by one. Note that we can't keep it held across the call // to WaitForSingleObject since that will deadlock other calls to // ACE_OS::cond_signal(). if (ACE_OS::thread_mutex_unlock (external_mutex) != 0) return -1; // Wait to be awakened by a ACE_OS::signal() or ACE_OS::broadcast(). # if defined (ACE_USES_WINCE_SEMA_SIMULATION) // Can't use Win32 API on simulated semaphores. result = ACE_OS::sema_wait (&cv->sema_, timeout); if (result == -1 && errno == ETIME) result = WAIT_TIMEOUT; # else result = ::WaitForSingleObject (cv->sema_, msec_timeout); # endif /* ACE_USES_WINCE_SEMA_SIMULATION */ // Reacquire lock to avoid race conditions. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; --cv->waiters_; bool const last_waiter = cv->was_broadcast_ && cv->waiters_ == 0; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; if (result != WAIT_OBJECT_0) { switch (result) { case WAIT_TIMEOUT: error = ETIME; break; default: error = ::GetLastError (); break; } result = -1; } if (last_waiter) { // Release the signaler/broadcaster if we're the last waiter. if (ACE_OS::event_signal (&cv->waiters_done_) != 0) return -1; } // We must always regain the <external_mutex>, even when errors // occur because that's the guarantee that we give to our callers. if (ACE_OS::thread_mutex_lock (external_mutex) != 0) result = -1; if (error != 0) { /* This assignment must only be done if error != 0, * since writing 0 to errno violates the POSIX specification. */ errno = error; } return result; # endif # else ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } int ACE_OS::cond_wait (ACE_cond_t *cv, ACE_thread_mutex_t *external_mutex) { ACE_OS_TRACE ("ACE_OS::cond_wait"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_WTHREADS_CONDITION_VARIABLE) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::SleepConditionVariableCS (cv, external_mutex, INFINITE), result), int, -1); #else if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; ++cv->waiters_; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; int result = 0; int error = 0; // We keep the lock held just long enough to increment the count of // waiters by one. Note that we can't keep it held across the call // to ACE_OS::sema_wait() since that will deadlock other calls to // ACE_OS::cond_signal(). if (ACE_OS::thread_mutex_unlock (external_mutex) != 0) return -1; // Wait to be awakened by a ACE_OS::cond_signal() or // ACE_OS::cond_broadcast(). # if !defined (ACE_USES_WINCE_SEMA_SIMULATION) result = ::WaitForSingleObject (cv->sema_, INFINITE); # else // Can't use Win32 API on simulated semaphores. result = ACE_OS::sema_wait (&cv->sema_); if (result != WAIT_OBJECT_0 && errno == ETIME) result = WAIT_TIMEOUT; # endif /* ACE_USES_WINCE_SEMA_SIMULATION */ // Reacquire lock to avoid race conditions. if (ACE_OS::thread_mutex_lock (&cv->waiters_lock_) != 0) return -1; cv->waiters_--; bool const last_waiter = cv->was_broadcast_ && cv->waiters_ == 0; if (ACE_OS::thread_mutex_unlock (&cv->waiters_lock_) != 0) return -1; if (result != WAIT_OBJECT_0) { switch (result) { case WAIT_TIMEOUT: error = ETIME; break; default: error = ::GetLastError (); break; } } else if (last_waiter) { // Release the signaler/broadcaster if we're the last waiter. if (ACE_OS::event_signal (&cv->waiters_done_) != 0) return -1; } // We must always regain the <external_mutex>, even when errors // occur because that's the guarantee that we give to our callers. if (ACE_OS::thread_mutex_lock (external_mutex) != 0) result = -1; // Reset errno in case mutex_lock() also fails... if (error != 0) { /* This assignment must only be done if error != 0, * since writing 0 to errno violates the POSIX specification. */ errno = error; } return result; #endif # else ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } # endif /* ACE_HAS_WTHREADS */ /*****************************************************************************/ // CONDITIONS END /*****************************************************************************/ /*****************************************************************************/ // MUTEXES BEGIN /*****************************************************************************/ int ACE_OS::mutex_init (ACE_mutex_t *m, int lock_scope, const char *name, ACE_mutexattr_t *attributes, LPSECURITY_ATTRIBUTES sa, int lock_type) { // ACE_OS_TRACE ("ACE_OS::mutex_init"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (sa); # if defined (ACE_PTHREAD_MUTEXATTR_T_INITIALIZE) /* Tests show that VxWorks 6.x pthread lib does not only * require zeroing of mutex/condition objects to function correctly * but also of the attribute objects. */ pthread_mutexattr_t l_attributes = {0}; # else pthread_mutexattr_t l_attributes; # endif if (attributes == 0) attributes = &l_attributes; int result = 0; int attr_init = 0; // have we initialized the local attributes. // Only do these initializations if the <attributes> parameter // wasn't originally set. if (attributes == &l_attributes) { if (ACE_ADAPT_RETVAL (::pthread_mutexattr_init (attributes), result) == 0) { result = 0; attr_init = 1; // we have initialized these attributes } else { result = -1; // ACE_ADAPT_RETVAL used it for intermediate status } } if (result == 0 && lock_scope != 0) { # if defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_MUTEXATTR_PSHARED) (void) ACE_ADAPT_RETVAL (::pthread_mutexattr_setpshared (attributes, lock_scope), result); # endif /* _POSIX_THREAD_PROCESS_SHARED && !ACE_LACKS_MUTEXATTR_PSHARED */ } if (result == 0 && lock_type != 0) { # if defined (ACE_HAS_RECURSIVE_MUTEXES) (void) ACE_ADAPT_RETVAL (::pthread_mutexattr_settype (attributes, lock_type), result); # endif /* ACE_HAS_RECURSIVE_MUTEXES */ } if (result == 0) { # if defined (ACE_PTHREAD_MUTEX_T_INITIALIZE) /* VxWorks 6.x API reference states: * If the memory for the mutex variable object has been allocated * dynamically, it is a good policy to always zero out the * block of memory so as to avoid spurious EBUSY return code * when calling this routine. * Tests shows this to be necessary. */ ACE_OS::memset (m, 0, sizeof (*m)); # endif if (ACE_ADAPT_RETVAL (::pthread_mutex_init (m, attributes), result) == 0) result = 0; else result = -1; // ACE_ADAPT_RETVAL used it for intermediate status } // Only do the deletions if the <attributes> parameter wasn't // originally set. if (attributes == &l_attributes && attr_init) ::pthread_mutexattr_destroy (&l_attributes); return result; # elif defined (ACE_HAS_STHREADS) ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (sa); ACE_UNUSED_ARG (lock_type); int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::mutex_init (m, lock_scope, attributes), result), int, -1); # elif defined (ACE_HAS_WTHREADS) m->type_ = lock_scope; SECURITY_ATTRIBUTES sa_buffer; SECURITY_DESCRIPTOR sd_buffer; switch (lock_scope) { case USYNC_PROCESS: # if defined (ACE_HAS_WINCE) // @@todo (brunsch) This idea should be moved into ACE_OS_Win32. m->proc_mutex_ = ::CreateMutexW (ACE_OS::default_win32_security_attributes_r (sa, &sa_buffer, &sd_buffer), FALSE, ACE_Ascii_To_Wide (name).wchar_rep ()); # else /* ACE_HAS_WINCE */ m->proc_mutex_ = ::CreateMutexA (ACE_OS::default_win32_security_attributes_r (sa, &sa_buffer, &sd_buffer), FALSE, name); # endif /* ACE_HAS_WINCE */ if (m->proc_mutex_ == 0) ACE_FAIL_RETURN (-1); else { // Make sure to set errno to ERROR_ALREADY_EXISTS if necessary. ACE_OS::set_errno_to_last_error (); return 0; } case USYNC_THREAD: return ACE_OS::thread_mutex_init (&m->thr_mutex_, lock_type, name, attributes); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (attributes); ACE_UNUSED_ARG (sa); ACE_UNUSED_ARG (lock_type); return (*m = ::semMCreate (lock_scope)) == 0 ? -1 : 0; # endif /* ACE_HAS_PTHREADS */ #else ACE_UNUSED_ARG (m); ACE_UNUSED_ARG (lock_scope); ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (attributes); ACE_UNUSED_ARG (sa); ACE_UNUSED_ARG (lock_type); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } int ACE_OS::mutex_destroy (ACE_mutex_t *m) { ACE_OS_TRACE ("ACE_OS::mutex_destroy"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::pthread_mutex_destroy (m), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::mutex_destroy (m), result), int, -1); # elif defined (ACE_HAS_WTHREADS) switch (m->type_) { case USYNC_PROCESS: ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::CloseHandle (m->proc_mutex_), ace_result_), int, -1); case USYNC_THREAD: return ACE_OS::thread_mutex_destroy (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) return ::semDelete (*m) == OK ? 0 : -1; # endif /* Threads variety case */ #else ACE_UNUSED_ARG (m); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } #if defined (ACE_HAS_WCHAR) int ACE_OS::mutex_init (ACE_mutex_t *m, int lock_scope, const wchar_t *name, ACE_mutexattr_t *attributes, LPSECURITY_ATTRIBUTES sa, int lock_type) { #if defined (ACE_HAS_THREADS) && defined (ACE_HAS_WTHREADS) m->type_ = lock_scope; SECURITY_ATTRIBUTES sa_buffer; SECURITY_DESCRIPTOR sd_buffer; switch (lock_scope) { case USYNC_PROCESS: m->proc_mutex_ = ::CreateMutexW (ACE_OS::default_win32_security_attributes_r (sa, &sa_buffer, &sd_buffer), FALSE, name); if (m->proc_mutex_ == 0) ACE_FAIL_RETURN (-1); else { // Make sure to set errno to ERROR_ALREADY_EXISTS if necessary. ACE_OS::set_errno_to_last_error (); return 0; } case USYNC_THREAD: return ACE_OS::thread_mutex_init (&m->thr_mutex_, lock_type, name, attributes); } errno = EINVAL; return -1; #else /* ACE_HAS_THREADS && ACE_HAS_WTHREADS */ return ACE_OS::mutex_init (m, lock_scope, ACE_Wide_To_Ascii (name).char_rep (), attributes, sa, lock_type); #endif /* ACE_HAS_THREADS && ACE_HAS_WTHREADS */ } #endif /* ACE_HAS_WCHAR */ int ACE_OS::mutex_lock (ACE_mutex_t *m) { // ACE_OS_TRACE ("ACE_OS::mutex_lock"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) // Note, don't use "::" here since the following call is often a macro. int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (pthread_mutex_lock (m), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::mutex_lock (m), result), int, -1); # elif defined (ACE_HAS_WTHREADS) switch (m->type_) { case USYNC_PROCESS: switch (::WaitForSingleObject (m->proc_mutex_, INFINITE)) { // // Timeout can't occur, so don't bother checking... // case WAIT_OBJECT_0: case WAIT_ABANDONED: // We will ignore abandonments in this method // Note that we still hold the lock return 0; default: // This is a hack, we need to find an appropriate mapping... ACE_OS::set_errno_to_last_error (); return -1; } case USYNC_THREAD: return ACE_OS::thread_mutex_lock (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) return ::semTake (*m, WAIT_FOREVER) == OK ? 0 : -1; # endif /* Threads variety case */ #else ACE_UNUSED_ARG (m); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } int ACE_OS::mutex_lock (ACE_mutex_t *m, int &abandoned) { ACE_OS_TRACE ("ACE_OS::mutex_lock"); #if defined (ACE_HAS_THREADS) && defined (ACE_HAS_WTHREADS) abandoned = 0; switch (m->type_) { case USYNC_PROCESS: switch (::WaitForSingleObject (m->proc_mutex_, INFINITE)) { // // Timeout can't occur, so don't bother checking... // case WAIT_OBJECT_0: return 0; case WAIT_ABANDONED: abandoned = 1; return 0; // something goofed, but we hold the lock ... default: // This is a hack, we need to find an appropriate mapping... ACE_OS::set_errno_to_last_error (); return -1; } case USYNC_THREAD: return ACE_OS::thread_mutex_lock (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ #else ACE_UNUSED_ARG (m); ACE_UNUSED_ARG (abandoned); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS and ACE_HAS_WTHREADS */ } int ACE_OS::mutex_lock (ACE_mutex_t *m, const ACE_Time_Value &timeout) { #if defined (ACE_HAS_THREADS) && defined (ACE_HAS_MUTEX_TIMEOUTS) # if defined (ACE_HAS_PTHREADS) int result; // "timeout" should be an absolute time. timespec_t ts = timeout; // Calls ACE_Time_Value::operator timespec_t(). // Note that the mutex should not be a recursive one, i.e., it // should only be a standard mutex or an error checking mutex. ACE_OSCALL (ACE_ADAPT_RETVAL (::pthread_mutex_timedlock (m, &ts), result), int, -1, result); // We need to adjust this to make the errno values consistent. if (result == -1 && errno == ETIMEDOUT) errno = ETIME; return result; # elif defined (ACE_HAS_WTHREADS) // Note that we must convert between absolute time (which is passed // as a parameter) and relative time (which is what the system call // expects). ACE_Time_Value relative_time (timeout - ACE_OS::gettimeofday ()); switch (m->type_) { case USYNC_PROCESS: switch (::WaitForSingleObject (m->proc_mutex_, relative_time.msec ())) { case WAIT_OBJECT_0: case WAIT_ABANDONED: // We will ignore abandonments in this method // Note that we still hold the lock return 0; case WAIT_TIMEOUT: errno = ETIME; return -1; default: // This is a hack, we need to find an appropriate mapping... ACE_OS::set_errno_to_last_error (); return -1; } case USYNC_THREAD: ACE_NOTSUP_RETURN (-1); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) // Note that we must convert between absolute time (which is passed // as a parameter) and relative time (which is what the system call // expects). ACE_Time_Value relative_time (timeout - ACE_OS::gettimeofday ()); int ticks_per_sec = ::sysClkRateGet (); int ticks = relative_time.sec() * ticks_per_sec + relative_time.usec () * ticks_per_sec / ACE_ONE_SECOND_IN_USECS; if (::semTake (*m, ticks) == ERROR) { if (errno == S_objLib_OBJ_TIMEOUT) // Convert the VxWorks errno to one that's common for to ACE // platforms. errno = ETIME; else if (errno == S_objLib_OBJ_UNAVAILABLE) errno = EBUSY; return -1; } else return 0; # endif /* ACE_HAS_PTHREADS */ #else ACE_UNUSED_ARG (m); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS && ACE_HAS_MUTEX_TIMEOUTS */ } int ACE_OS::mutex_trylock (ACE_mutex_t *m) { ACE_OS_TRACE ("ACE_OS::mutex_trylock"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) // Note, don't use "::" here since the following call is often a macro. int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (pthread_mutex_trylock (m), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::mutex_trylock (m), result), int, -1); # elif defined (ACE_HAS_WTHREADS) switch (m->type_) { case USYNC_PROCESS: { // Try for 0 milliseconds - i.e. nonblocking. switch (::WaitForSingleObject (m->proc_mutex_, 0)) { case WAIT_OBJECT_0: return 0; case WAIT_ABANDONED: // We will ignore abandonments in this method. Note that // we still hold the lock. return 0; case WAIT_TIMEOUT: errno = EBUSY; return -1; default: ACE_OS::set_errno_to_last_error (); return -1; } } case USYNC_THREAD: return ACE_OS::thread_mutex_trylock (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) if (::semTake (*m, NO_WAIT) == ERROR) if (errno == S_objLib_OBJ_UNAVAILABLE) { // couldn't get the semaphore errno = EBUSY; return -1; } else // error return -1; else // got the semaphore return 0; # endif /* Threads variety case */ #else ACE_UNUSED_ARG (m); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } int ACE_OS::mutex_trylock (ACE_mutex_t *m, int &abandoned) { #if defined (ACE_HAS_THREADS) && defined (ACE_HAS_WTHREADS) abandoned = 0; switch (m->type_) { case USYNC_PROCESS: { // Try for 0 milliseconds - i.e. nonblocking. switch (::WaitForSingleObject (m->proc_mutex_, 0)) { case WAIT_OBJECT_0: return 0; case WAIT_ABANDONED: abandoned = 1; return 0; // something goofed, but we hold the lock ... case WAIT_TIMEOUT: errno = EBUSY; return -1; default: ACE_OS::set_errno_to_last_error (); return -1; } } case USYNC_THREAD: return ACE_OS::thread_mutex_trylock (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ #else ACE_UNUSED_ARG (m); ACE_UNUSED_ARG (abandoned); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS and ACE_HAS_WTHREADS */ } int ACE_OS::mutex_unlock (ACE_mutex_t *m) { ACE_OS_TRACE ("ACE_OS::mutex_unlock"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) // Note, don't use "::" here since the following call is often a macro. int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (pthread_mutex_unlock (m), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::mutex_unlock (m), result), int, -1); # elif defined (ACE_HAS_WTHREADS) switch (m->type_) { case USYNC_PROCESS: ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::ReleaseMutex (m->proc_mutex_), ace_result_), int, -1); case USYNC_THREAD: return ACE_OS::thread_mutex_unlock (&m->thr_mutex_); default: errno = EINVAL; return -1; } /* NOTREACHED */ # elif defined (ACE_VXWORKS) return ::semGive (*m) == OK ? 0 : -1; # endif /* Threads variety case */ #else ACE_UNUSED_ARG (m); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } void ACE_OS::mutex_lock_cleanup (void *mutex) { ACE_OS_TRACE ("ACE_OS::mutex_lock_cleanup"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) ACE_mutex_t *p_lock = (ACE_mutex_t *) mutex; ACE_OS::mutex_unlock (p_lock); # else ACE_UNUSED_ARG (mutex); # endif /* ACE_HAS_PTHREADS */ #else ACE_UNUSED_ARG (mutex); #endif /* ACE_HAS_THREADS */ } /*****************************************************************************/ // MUTEXES END /*****************************************************************************/ /*****************************************************************************/ // EVENTS BEGIN /*****************************************************************************/ int ACE_OS::event_destroy (ACE_event_t *event) { #if defined (ACE_WIN32) ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::CloseHandle (*event), ace_result_), int, -1); #elif defined (ACE_HAS_THREADS) if (event->eventdata_) { // mutex_destroy()/cond_destroy() are called in a loop if the object // is BUSY. This avoids conditions where we fail to destroy these // objects because at time of destroy they were just being used in // another thread possibly causing deadlocks later on if they keep // being used after we're gone. if (event->eventdata_->type_ == USYNC_PROCESS) { if (event->name_) { // Only destroy the event data if we're the ones who initialized // it. int r1, r2; # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) // First destroy the mutex so locking after this will return // errors. while ((r1 = ACE_OS::mutex_destroy (&event->eventdata_->lock_)) == -1 && errno == EBUSY) { ACE_OS::thr_yield (); } # else r1 = ACE_OS::sema_destroy(&event->lock_); # endif # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) // Now fix event to manual reset, raise signal and broadcast // until is's possible to destroy the condition. event->eventdata_->manual_reset_ = 1; while ((r2 = ACE_OS::cond_destroy (&event->eventdata_->condition_)) == -1 && errno == EBUSY) { event->eventdata_->is_signaled_ = 1; if (ACE_OS::cond_broadcast (&event->eventdata_->condition_) != 0) return -1; ACE_OS::thr_yield (); } # else r2 = ACE_OS::sema_destroy(&event->semaphore_); # endif ACE_OS::munmap (event->eventdata_, sizeof (ACE_eventdata_t)); ACE_OS::shm_unlink (ACE_TEXT_CHAR_TO_TCHAR(event->name_)); ACE_OS::free (event->name_); return r1 != 0 || r2 != 0 ? -1 : 0; } else { ACE_OS::munmap (event->eventdata_, sizeof (ACE_eventdata_t)); # if (!defined (ACE_HAS_PTHREADS) || !defined (_POSIX_THREAD_PROCESS_SHARED) || \ (defined (ACE_LACKS_MUTEXATTR_PSHARED) && defined (ACE_LACKS_CONDATTR_PSHARED))) && \ (defined (ACE_USES_FIFO_SEM) || \ (defined (ACE_HAS_POSIX_SEM) && defined (ACE_HAS_POSIX_SEM_TIMEOUT) && defined (ACE_LACKS_NAMED_POSIX_SEM))) ACE_OS::sema_destroy(&event->lock_); # endif # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) return 0; # else return ACE_OS::sema_destroy(&event->semaphore_); # endif } } else { int r1, r2; // First destroy the mutex so locking after this will return errors. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) // first destroy the mutex so locking after this will return errors while ((r1 = ACE_OS::mutex_destroy (&event->eventdata_->lock_)) == -1 && errno == EBUSY) { ACE_OS::thr_yield (); } # else r1 = ACE_OS::sema_destroy(&event->lock_); # endif # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) // Now fix event to manual reset, raise signal and broadcast until // it's possible to destroy the condition. event->eventdata_->manual_reset_ = 1; while ((r2 = ACE_OS::cond_destroy (&event->eventdata_->condition_)) == -1 && errno == EBUSY) { event->eventdata_->is_signaled_ = 1; if (ACE_OS::cond_broadcast (&event->eventdata_->condition_) != 0) return -1; ACE_OS::thr_yield (); } # else r2 = ACE_OS::sema_destroy(&event->semaphore_); # endif delete event->eventdata_; return r1 != 0 || r2 != 0 ? -1 : 0; } } return 0; #else ACE_UNUSED_ARG (event); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_init (ACE_event_t *event, int manual_reset, int initial_state, int type, const char *name, void *arg, LPSECURITY_ATTRIBUTES sa) { #if defined (ACE_WIN32) ACE_UNUSED_ARG (type); ACE_UNUSED_ARG (arg); SECURITY_ATTRIBUTES sa_buffer; SECURITY_DESCRIPTOR sd_buffer; # if defined (ACE_HAS_WINCE) // @@todo (brunsch) This idea should be moved into ACE_OS_Win32. *event = ::CreateEventW (ACE_OS::default_win32_security_attributes_r (sa, &sa_buffer, &sd_buffer), manual_reset, initial_state, ACE_Ascii_To_Wide (name).wchar_rep ()); # else /* ACE_HAS_WINCE */ *event = ::CreateEventA (ACE_OS::default_win32_security_attributes_r (sa, &sa_buffer, &sd_buffer), manual_reset, initial_state, name); # endif /* ACE_HAS_WINCE */ if (*event == 0) ACE_FAIL_RETURN (-1); else { // Make sure to set errno to ERROR_ALREADY_EXISTS if necessary. ACE_OS::set_errno_to_last_error (); return 0; } #elif defined (ACE_HAS_THREADS) ACE_UNUSED_ARG (sa); event->eventdata_ = 0; ACE_eventdata_t* evtdata; if (type == USYNC_PROCESS) { const char *name_p = 0; # if defined (ACE_SHM_OPEN_REQUIRES_ONE_SLASH) char adj_name[MAXPATHLEN]; if (name[0] != '/') { adj_name[0] = '/'; ACE_OS::strsncpy (&adj_name[1], name, MAXPATHLEN-1); name_p = adj_name; } else { name_p = name; } # else name_p = name; # endif /* ACE_SHM_OPEN_REQUIRES_ONE_SLASH */ int owner = 0; // Let's see if the shared memory entity already exists. ACE_HANDLE fd = ACE_OS::shm_open (ACE_TEXT_CHAR_TO_TCHAR (name_p), O_RDWR | O_CREAT | O_EXCL, ACE_DEFAULT_FILE_PERMS); if (fd == ACE_INVALID_HANDLE) { if (errno == EEXIST) fd = ACE_OS::shm_open (ACE_TEXT_CHAR_TO_TCHAR (name_p), O_RDWR | O_CREAT, ACE_DEFAULT_FILE_PERMS); if (fd == ACE_INVALID_HANDLE) // Still can't get it. return -1; } else { // We own this shared memory object! Let's set its size. if (ACE_OS::ftruncate (fd, sizeof (ACE_eventdata_t)) == -1) { ACE_OS::close (fd); return -1; } owner = 1; } evtdata = (ACE_eventdata_t *) ACE_OS::mmap (0, sizeof (ACE_eventdata_t), PROT_RDWR, MAP_SHARED, fd, 0); ACE_OS::close (fd); if (evtdata == MAP_FAILED) { if (owner) ACE_OS::shm_unlink (ACE_TEXT_CHAR_TO_TCHAR (name_p)); return -1; } if (owner) { event->name_ = ACE_OS::strdup (name_p); if (event->name_ == 0) { ACE_OS::shm_unlink (ACE_TEXT_CHAR_TO_TCHAR (name_p)); return -1; } event->eventdata_ = evtdata; event->eventdata_->type_ = type; event->eventdata_->manual_reset_ = manual_reset; event->eventdata_->is_signaled_ = initial_state; event->eventdata_->auto_event_signaled_ = false; event->eventdata_->waiting_threads_ = 0; event->eventdata_->signal_count_ = 0; # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) int result = ACE_OS::cond_init (&event->eventdata_->condition_, static_cast<short> (type), name, arg); # else char sem_name[128]; ACE_OS::strncpy (sem_name, name, sizeof (sem_name) - (1 + sizeof ("._ACE_EVTSEM_"))); ACE_OS::strcat (sem_name, "._ACE_EVTSEM_"); int result = ACE_OS::sema_init (&event->semaphore_, 0, type, sem_name, arg); # endif if (result == 0) # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) result = ACE_OS::mutex_init (&event->eventdata_->lock_, type, name, (ACE_mutexattr_t *) arg); # else { char lck_name[128]; ACE_OS::strncpy (lck_name, name, sizeof (lck_name) - (1 + sizeof ("._ACE_EVTLCK_"))); ACE_OS::strcat (lck_name, "._ACE_EVTLCK_"); result = ACE_OS::sema_init (&event->lock_, 0, type, lck_name, arg); if (result == 0) result = ACE_OS::sema_post (&event->lock_); /* Initially unlock */ } # endif return result; } else { int result = 0; event->name_ = 0; event->eventdata_ = evtdata; #if (!defined (ACE_HAS_PTHREADS) || !defined (_POSIX_THREAD_PROCESS_SHARED) || defined (ACE_LACKS_CONDATTR_PSHARED)) && \ (defined (ACE_USES_FIFO_SEM) || \ (defined (ACE_HAS_POSIX_SEM) && defined (ACE_HAS_POSIX_SEM_TIMEOUT) && !defined (ACE_LACKS_NAMED_POSIX_SEM))) char sem_name[128]; ACE_OS::strncpy (sem_name, name, sizeof (sem_name) - (1 + sizeof ("._ACE_EVTSEM_"))); ACE_OS::strcat (sem_name, "._ACE_EVTSEM_"); result = ACE_OS::sema_init(&event->semaphore_, 0, type, sem_name, arg); # endif # if (!defined (ACE_HAS_PTHREADS) || !defined (_POSIX_THREAD_PROCESS_SHARED) || \ (defined (ACE_LACKS_MUTEXATTR_PSHARED) && defined (ACE_LACKS_CONDATTR_PSHARED))) && \ (defined (ACE_USES_FIFO_SEM) || \ (defined (ACE_HAS_POSIX_SEM) && defined (ACE_HAS_POSIX_SEM_TIMEOUT) && defined (ACE_LACKS_NAMED_POSIX_SEM))) if (result == 0) { char lck_name[128]; ACE_OS::strncpy (lck_name, name, sizeof (lck_name) - (1 + sizeof ("._ACE_EVTLCK_"))); ACE_OS::strcat (lck_name, "._ACE_EVTLCK_"); result = ACE_OS::sema_init (&event->lock_, 0, type, lck_name, arg); } # endif return result; } } else { ACE_NEW_RETURN (evtdata, ACE_eventdata_t, -1); event->name_ = 0; event->eventdata_ = evtdata; event->eventdata_->type_ = type; event->eventdata_->manual_reset_ = manual_reset; event->eventdata_->is_signaled_ = initial_state; event->eventdata_->auto_event_signaled_ = false; event->eventdata_->waiting_threads_ = 0; event->eventdata_->signal_count_ = 0; # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) int result = ACE_OS::cond_init (&event->eventdata_->condition_, static_cast<short> (type), name, arg); # else int result = ACE_OS::sema_init (&event->semaphore_, 0, type, name, arg); # endif if (result == 0) # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) result = ACE_OS::mutex_init (&event->eventdata_->lock_, type, name, (ACE_mutexattr_t *) arg); # else result = ACE_OS::sema_init (&event->lock_, 0, type, name, arg); if (result == 0) result = ACE_OS::sema_post(&event->lock_); /* initially unlock */ # endif return result; } #else ACE_UNUSED_ARG (event); ACE_UNUSED_ARG (manual_reset); ACE_UNUSED_ARG (initial_state); ACE_UNUSED_ARG (type); ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (arg); ACE_UNUSED_ARG (sa); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_pulse (ACE_event_t *event) { #if defined (ACE_WIN32) ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::PulseEvent (*event), ace_result_), int, -1); #elif defined (ACE_HAS_THREADS) int result = 0; int error = 0; // grab the lock first # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) == 0) # else if (ACE_OS::sema_wait (&event->lock_) == 0) # endif { if (event->eventdata_->waiting_threads_ > 0) { // Manual-reset event. if (event->eventdata_->manual_reset_ == 1) { // Wakeup all waiters. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::cond_broadcast (&event->eventdata_->condition_) != 0) { result = -1; error = errno; } if (result == 0) event->eventdata_->signal_count_ = event->eventdata_->waiting_threads_; # else event->eventdata_->signal_count_ = event->eventdata_->waiting_threads_; for (unsigned long i=0; i<event->eventdata_->signal_count_ ;++i) if (ACE_OS::sema_post(&event->semaphore_) != 0) { event->eventdata_->signal_count_ = 0; result = -1; error = errno; } if (result == 0) while(event->eventdata_->signal_count_!=0 && event->eventdata_->waiting_threads_!=0) ACE_OS::thr_yield (); # endif } // Auto-reset event: wakeup one waiter. else { # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::cond_signal (&event->eventdata_->condition_) != 0) # else if (ACE_OS::sema_post(&event->semaphore_) != 0) # endif { result = -1; error = errno; } event->eventdata_->auto_event_signaled_ = true; } } // Reset event. event->eventdata_->is_signaled_ = 0; // Now we can let go of the lock. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) return -1; # else if (ACE_OS::sema_post (&event->lock_) != 0) return -1; # endif if (result == -1) // Reset errno in case mutex_unlock() also fails... errno = error; } else result = -1; return result; #else ACE_UNUSED_ARG (event); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_reset (ACE_event_t *event) { #if defined (ACE_WIN32) ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::ResetEvent (*event), ace_result_), int, -1); #elif defined (ACE_HAS_THREADS) int result = 0; // Grab the lock first. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) == 0) # else if (ACE_OS::sema_wait (&event->lock_) == 0) # endif { // Reset event. event->eventdata_->is_signaled_ = 0; event->eventdata_->auto_event_signaled_ = false; // Now we can let go of the lock. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) return -1; # else if (ACE_OS::sema_post (&event->lock_) != 0) return -1; # endif } else result = -1; return result; #else ACE_UNUSED_ARG (event); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_signal (ACE_event_t *event) { #if defined (ACE_WIN32) ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::SetEvent (*event), ace_result_), int, -1); #elif defined (ACE_HAS_THREADS) int result = 0; int error = 0; // grab the lock first # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) == 0) # else if (ACE_OS::sema_wait (&event->lock_) == 0) # endif { // Manual-reset event. if (event->eventdata_->manual_reset_ == 1) { // wakeup all # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::cond_broadcast (&event->eventdata_->condition_) != 0) { result = -1; error = errno; } # else if (ACE_OS::sema_post(&event->semaphore_) != 0) { result = -1; error = errno; } # endif if (result == 0) // signal event event->eventdata_->is_signaled_ = 1; } // Auto-reset event else { if (event->eventdata_->waiting_threads_ == 0) // No waiters: signal event. event->eventdata_->is_signaled_ = 1; // Waiters: wakeup one waiter. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) else if (ACE_OS::cond_signal (&event->eventdata_->condition_) != 0) # else else if (ACE_OS::sema_post(&event->semaphore_) != 0) # endif { result = -1; error = errno; } event->eventdata_->auto_event_signaled_ = true; } // Now we can let go of the lock. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) return -1; # else if (ACE_OS::sema_post (&event->lock_) != 0) return -1; # endif if (result == -1) // Reset errno in case mutex_unlock() also fails... errno = error; } else result = -1; return result; #else ACE_UNUSED_ARG (event); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_timedwait (ACE_event_t *event, ACE_Time_Value *timeout, int use_absolute_time) { if (timeout == 0) // Wait indefinitely. return ACE_OS::event_wait (event); #if defined (ACE_WIN32) DWORD result; if (*timeout == ACE_Time_Value::zero) // Do a "poll". result = ::WaitForSingleObject (*event, 0); else { // Wait for upto <relative_time> number of milliseconds. Note // that we must convert between absolute time (which is passed // as a parameter) and relative time (which is what // WaitForSingleObjects() expects). // <timeout> parameter is given in absolute or relative value // depending on parameter <use_absolute_time>. int msec_timeout = 0; if (use_absolute_time) { // Time is given in absolute time, we should use // gettimeofday() to calculate relative time ACE_Time_Value relative_time (*timeout - ACE_OS::gettimeofday ()); // Watchout for situations where a context switch has caused // the current time to be > the timeout. Thanks to Norbert // Rapp <[email protected]> for pointing this. if (relative_time > ACE_Time_Value::zero) msec_timeout = relative_time.msec (); } else // time is given in relative time, just convert it into // milliseconds and use it msec_timeout = timeout->msec (); result = ::WaitForSingleObject (*event, msec_timeout); } switch (result) { case WAIT_OBJECT_0: return 0; case WAIT_TIMEOUT: errno = ETIME; return -1; default: // This is a hack, we need to find an appropriate mapping... ACE_OS::set_errno_to_last_error (); return -1; } #elif defined (ACE_HAS_THREADS) int result = 0; int error = 0; // grab the lock first # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) == 0) # else if (ACE_OS::sema_wait (&event->lock_) == 0) # endif { if (event->eventdata_->is_signaled_ == 1) // event is currently signaled { if (event->eventdata_->manual_reset_ == 0) { // AUTO: reset state event->eventdata_->is_signaled_ = 0; event->eventdata_->auto_event_signaled_ = false; } } else // event is currently not signaled { event->eventdata_->waiting_threads_++; ACE_Time_Value absolute_timeout = *timeout; // cond_timewait() expects absolute time, check // <use_absolute_time> flag. if (use_absolute_time == 0) absolute_timeout += ACE_OS::gettimeofday (); while (event->eventdata_->is_signaled_ == 0 && event->eventdata_->auto_event_signaled_ == false) { # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::cond_timedwait (&event->eventdata_->condition_, &event->eventdata_->lock_, &absolute_timeout) != 0) { result = -1; error = errno; break; } if (event->eventdata_->signal_count_ > 0) { event->eventdata_->signal_count_--; break; } # else # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_MUTEXATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && (!defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) # else if (ACE_OS::sema_post (&event->lock_) != 0) # endif { event->eventdata_->waiting_threads_--; return -1; } if (ACE_OS::sema_wait(&event->semaphore_, absolute_timeout) !=0) { result = -1; if (errno == ETIMEDOUT) // Semaphores time out with ETIMEDOUT (POSIX) error = ETIME; else error = errno; } bool signalled = false; if (result == 0 && event->eventdata_->signal_count_ > 0) { event->eventdata_->signal_count_--; signalled = true; } # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_MUTEXATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && (!defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) != 0) # else if (ACE_OS::sema_wait (&event->lock_) != 0) # endif { event->eventdata_->waiting_threads_--; // yes, I know it's not save return -1; } if (result) break; if (event->eventdata_->manual_reset_ == 1 && event->eventdata_->is_signaled_ == 1) if (ACE_OS::sema_post(&event->semaphore_) != 0) { result = -1; error = errno; break; } if (signalled) break; # endif } // Reset the auto_event_signaled_ to false now that we have // woken up. if (event->eventdata_->auto_event_signaled_ == true) event->eventdata_->auto_event_signaled_ = false; event->eventdata_->waiting_threads_--; } // Now we can let go of the lock. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) return -1; # else if (ACE_OS::sema_post (&event->lock_) != 0) return -1; # endif if (result == -1) // Reset errno in case mutex_unlock() also fails... errno = error; } else result = -1; return result; #else ACE_UNUSED_ARG (event); ACE_UNUSED_ARG (timeout); ACE_UNUSED_ARG (use_absolute_time); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } int ACE_OS::event_wait (ACE_event_t *event) { #if defined (ACE_WIN32) switch (::WaitForSingleObject (*event, INFINITE)) { case WAIT_OBJECT_0: return 0; default: { ACE_OS::set_errno_to_last_error (); return -1; } } #elif defined (ACE_HAS_THREADS) int result = 0; int error = 0; // grab the lock first # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) == 0) # else if (ACE_OS::sema_wait (&event->lock_) == 0) # endif { if (event->eventdata_->is_signaled_ == 1) // Event is currently signaled. { if (event->eventdata_->manual_reset_ == 0) // AUTO: reset state event->eventdata_->is_signaled_ = 0; } else // event is currently not signaled { event->eventdata_->waiting_threads_++; while (event->eventdata_->is_signaled_ == 0 && event->eventdata_->auto_event_signaled_ == false) { # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_CONDATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::cond_wait (&event->eventdata_->condition_, &event->eventdata_->lock_) != 0) { result = -1; error = errno; // Something went wrong... break; } if (event->eventdata_->signal_count_ > 0) { event->eventdata_->signal_count_--; break; } # else # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_MUTEXATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && (!defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) # else if (ACE_OS::sema_post (&event->lock_) != 0) # endif { event->eventdata_->waiting_threads_--; return -1; } if (ACE_OS::sema_wait (&event->semaphore_) !=0) { result = -1; error = errno; } bool signalled = false; if (result == 0 && event->eventdata_->signal_count_ > 0) { event->eventdata_->signal_count_--; signalled = true; } # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && !defined (ACE_LACKS_MUTEXATTR_PSHARED)) || \ (!defined (ACE_USES_FIFO_SEM) && (!defined (ACE_HAS_POSIX_SEM) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_lock (&event->eventdata_->lock_) != 0) # else if (ACE_OS::sema_wait (&event->lock_) != 0) # endif { event->eventdata_->waiting_threads_--; return -1; } if (result) break; if (event->eventdata_->manual_reset_ == 1 && event->eventdata_->is_signaled_ == 1) if (ACE_OS::sema_post(&event->semaphore_) != 0) { result = -1; error = errno; break; } if (signalled) break; # endif } // Reset it since we have woken up. if (event->eventdata_->auto_event_signaled_ == true) event->eventdata_->auto_event_signaled_ = false; event->eventdata_->waiting_threads_--; } // Now we can let go of the lock. # if (defined (ACE_HAS_PTHREADS) && defined (_POSIX_THREAD_PROCESS_SHARED) && \ (!defined (ACE_LACKS_MUTEXATTR_PSHARED) || !defined (ACE_LACKS_CONDATTR_PSHARED))) || \ (!defined (ACE_USES_FIFO_SEM) && \ (!defined (ACE_HAS_POSIX_SEM) || !defined (ACE_HAS_POSIX_SEM_TIMEOUT) || defined (ACE_LACKS_NAMED_POSIX_SEM))) if (ACE_OS::mutex_unlock (&event->eventdata_->lock_) != 0) return -1; # else if (ACE_OS::sema_post (&event->lock_) != 0) return -1; # endif if (result == -1) // Reset errno in case mutex_unlock() also fails... errno = error; } else result = -1; return result; #else ACE_UNUSED_ARG (event); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 */ } /*****************************************************************************/ // EVENTS END /*****************************************************************************/ int ACE_OS::lwp_getparams (ACE_Sched_Params &sched_params) { #if defined (ACE_HAS_STHREADS) || defined (sun) // Get the class TS and RT class IDs. ACE_id_t rt_id; ACE_id_t ts_id; if (ACE_OS::scheduling_class ("RT", rt_id) == -1 || ACE_OS::scheduling_class ("TS", ts_id) == -1) return -1; // Get this LWP's scheduling parameters. pcparms_t pcparms; // The following is just to avoid Purify warnings about unitialized // memory reads. ACE_OS::memset (&pcparms, 0, sizeof pcparms); pcparms.pc_cid = PC_CLNULL; if (ACE_OS::priority_control (P_LWPID, P_MYID, PC_GETPARMS, (char *) &pcparms) == -1) return -1; else if (pcparms.pc_cid == rt_id) { // RT class. rtparms_t rtparms; ACE_OS::memcpy (&rtparms, pcparms.pc_clparms, sizeof rtparms); sched_params.policy (ACE_SCHED_FIFO); sched_params.priority (rtparms.rt_pri); sched_params.scope (ACE_SCOPE_THREAD); ACE_Time_Value quantum (rtparms.rt_tqsecs, rtparms.rt_tqnsecs == RT_TQINF ? 0 : rtparms.rt_tqnsecs * 1000); sched_params.quantum (quantum); return 0; } else if (pcparms.pc_cid == ts_id) { /* TS class */ tsparms_t tsparms; ACE_OS::memcpy (&tsparms, pcparms.pc_clparms, sizeof tsparms); sched_params.policy (ACE_SCHED_OTHER); sched_params.priority (tsparms.ts_upri); sched_params.scope (ACE_SCOPE_THREAD); return 0; } else return -1; #else /* ! ACE_HAS_STHREADS && ! sun */ ACE_UNUSED_ARG (sched_params); ACE_NOTSUP_RETURN (-1); #endif /* ! ACE_HAS_STHREADS && ! sun */ } int ACE_OS::lwp_setparams (const ACE_Sched_Params &sched_params) { #if defined (ACE_HAS_STHREADS) || defined (sun) ACE_Sched_Params lwp_params (sched_params); lwp_params.scope (ACE_SCOPE_LWP); return ACE_OS::sched_params (lwp_params); #else /* ! ACE_HAS_STHREADS && ! sun */ ACE_UNUSED_ARG (sched_params); ACE_NOTSUP_RETURN (-1); #endif /* ! ACE_HAS_STHREADS && ! sun */ } #if !defined (ACE_HAS_THREADS) || (defined (ACE_LACKS_RWLOCK_T) && \ !defined (ACE_HAS_PTHREADS_UNIX98_EXT)) int ACE_OS::rwlock_init (ACE_rwlock_t *rw, int type, const ACE_TCHAR *name, void *arg) { // ACE_OS_TRACE ("ACE_OS::rwlock_init"); # if defined (ACE_HAS_THREADS) && defined (ACE_LACKS_RWLOCK_T) // NT, POSIX, and VxWorks don't support this natively. ACE_UNUSED_ARG (name); int result = -1; // Since we cannot use the user specified name for all three // objects, we will create three completely new names. ACE_TCHAR name1[ACE_UNIQUE_NAME_LEN]; ACE_TCHAR name2[ACE_UNIQUE_NAME_LEN]; ACE_TCHAR name3[ACE_UNIQUE_NAME_LEN]; ACE_TCHAR name4[ACE_UNIQUE_NAME_LEN]; ACE_OS::unique_name ((const void *) &rw->lock_, name1, ACE_UNIQUE_NAME_LEN); ACE_OS::unique_name ((const void *) &rw->waiting_readers_, name2, ACE_UNIQUE_NAME_LEN); ACE_OS::unique_name ((const void *) &rw->waiting_writers_, name3, ACE_UNIQUE_NAME_LEN); ACE_OS::unique_name ((const void *) &rw->waiting_important_writer_, name4, ACE_UNIQUE_NAME_LEN); ACE_condattr_t attributes; if (ACE_OS::condattr_init (attributes, type) == 0) { if (ACE_OS::mutex_init (&rw->lock_, type, name1, (ACE_mutexattr_t *) arg) == 0 && ACE_OS::cond_init (&rw->waiting_readers_, attributes, name2, arg) == 0 && ACE_OS::cond_init (&rw->waiting_writers_, attributes, name3, arg) == 0 && ACE_OS::cond_init (&rw->waiting_important_writer_, attributes, name4, arg) == 0) { // Success! rw->ref_count_ = 0; rw->num_waiting_writers_ = 0; rw->num_waiting_readers_ = 0; rw->important_writer_ = false; result = 0; } ACE_OS::condattr_destroy (attributes); } if (result == -1) { // Save/restore errno. ACE_Errno_Guard error (errno); /* We're about to return -1 anyway, so * no need to check return values of these clean-up calls: */ (void)ACE_OS::mutex_destroy (&rw->lock_); (void)ACE_OS::cond_destroy (&rw->waiting_readers_); (void)ACE_OS::cond_destroy (&rw->waiting_writers_); (void)ACE_OS::cond_destroy (&rw->waiting_important_writer_); } return result; # else ACE_UNUSED_ARG (rw); ACE_UNUSED_ARG (type); ACE_UNUSED_ARG (name); ACE_UNUSED_ARG (arg); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } #endif /* ! ACE_HAS_THREADS || ACE_LACKS_RWLOCK_T */ int ACE_OS::sched_params (const ACE_Sched_Params &sched_params, ACE_id_t id) { ACE_OS_TRACE ("ACE_OS::sched_params"); #if defined (ACE_HAS_STHREADS) return ACE_OS::set_scheduling_params (sched_params, id); #elif defined (ACE_HAS_PTHREADS) && \ (!defined (ACE_LACKS_SETSCHED) || defined (ACE_TANDEM_T1248_PTHREADS) || \ defined (ACE_HAS_PTHREAD_SCHEDPARAM)) if (sched_params.quantum () != ACE_Time_Value::zero) { // quantums not supported errno = EINVAL; return -1; } // Thanks to Thilo Kielmann <[email protected]> for // providing this code for 1003.1c PThreads. Please note that this // has only been tested for POSIX 1003.1c threads, and may cause // problems with other PThreads flavors! struct sched_param param; param.sched_priority = sched_params.priority (); if (sched_params.scope () == ACE_SCOPE_PROCESS) { # if defined(ACE_TANDEM_T1248_PTHREADS) || defined (ACE_HAS_PTHREAD_SCHEDPARAM) ACE_UNUSED_ARG (id); ACE_NOTSUP_RETURN (-1); # else /* ! ACE_TANDEM_T1248_PTHREADS */ int result = ::sched_setscheduler (id == ACE_SELF ? 0 : id, sched_params.policy (), &param) == -1 ? -1 : 0; # if defined (DIGITAL_UNIX) return result == 0 ? // Use priocntl (2) to set the process in the RT class, // if using an RT policy. ACE_OS::set_scheduling_params (sched_params) : result; # else /* ! DIGITAL_UNIX */ return result; # endif /* ! DIGITAL_UNIX */ # endif /* ! ACE_TANDEM_T1248_PTHREADS */ } else if (sched_params.scope () == ACE_SCOPE_THREAD) { ACE_thread_t thr_id = ACE_OS::thr_self (); int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::pthread_setschedparam (thr_id, sched_params.policy (), &param), result), int, -1); } # if defined (sun) // We need to be able to set LWP priorities on Suns, even without // ACE_HAS_STHREADS, to obtain preemption. else if (sched_params.scope () == ACE_SCOPE_LWP) return ACE_OS::set_scheduling_params (sched_params, id); # endif /* sun */ else // sched_params.scope () == ACE_SCOPE_LWP, which isn't POSIX { errno = EINVAL; return -1; } #elif defined (ACE_WIN32) && !defined (ACE_HAS_WINCE) // PharLap ETS can act on the current thread - it can set the // quantum also, unlike Win32. All this only works on the RT // version. # if defined (ACE_HAS_PHARLAP_RT) if (id != ACE_SELF) ACE_NOTSUP_RETURN (-1); # if !defined (ACE_PHARLAP_LABVIEW_RT) if (sched_params.quantum() != ACE_Time_Value::zero) EtsSetTimeSlice (sched_params.quantum().msec()); # endif # else if (sched_params.quantum () != ACE_Time_Value::zero) { // I don't know of a way to set the quantum on Win32. errno = EINVAL; return -1; } # endif /* ACE_HAS_PHARLAP_RT */ if (sched_params.scope () == ACE_SCOPE_THREAD) { // Setting the REALTIME_PRIORITY_CLASS on Windows is almost always // a VERY BAD THING. This include guard will allow people // to easily disable this feature in ACE. // It won't work at all for Pharlap since there's no SetPriorityClass. #if !defined (ACE_HAS_PHARLAP) && \ !defined (ACE_DISABLE_WIN32_INCREASE_PRIORITY) // Set the priority class of this process to the REALTIME process class // _if_ the policy is ACE_SCHED_FIFO. Otherwise, set to NORMAL. if (!::SetPriorityClass (::GetCurrentProcess (), (sched_params.policy () == ACE_SCHED_FIFO || sched_params.policy () == ACE_SCHED_RR) ? REALTIME_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS)) { ACE_OS::set_errno_to_last_error (); return -1; } #endif /* ACE_DISABLE_WIN32_INCREASE_PRIORITY */ // Now that we have set the priority class of the process, set the // priority of the current thread to the desired value. return ACE_OS::thr_setprio (sched_params.priority ()); } else if (sched_params.scope () == ACE_SCOPE_PROCESS) { # if defined (ACE_HAS_PHARLAP_RT) ACE_NOTSUP_RETURN (-1); # else HANDLE hProcess = ::OpenProcess (PROCESS_SET_INFORMATION, FALSE, id == ACE_SELF ? ::GetCurrentProcessId() : id); if (!hProcess) { ACE_OS::set_errno_to_last_error(); return -1; } // There is no way for us to set the priority of the thread when we // are setting the priority of a different process. So just ignore // the priority argument when ACE_SCOPE_PROCESS is specified. // Setting the priority class will automatically increase the base // priority of all the threads within a process while maintaining the // relative priorities of the threads within it. if (!::SetPriorityClass (hProcess, (sched_params.policy () == ACE_SCHED_FIFO || sched_params.policy () == ACE_SCHED_RR) ? REALTIME_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS)) { ACE_OS::set_errno_to_last_error (); ::CloseHandle (hProcess); return -1; } ::CloseHandle (hProcess); return 0; #endif /* ACE_HAS_PHARLAP_RT */ } else { errno = EINVAL; return -1; } #elif defined (ACE_VXWORKS) ACE_UNUSED_ARG (id); // There is only one class of priorities on VxWorks, and no time // quanta. So, just set the current thread's priority. if (sched_params.policy () != ACE_SCHED_FIFO || sched_params.scope () != ACE_SCOPE_PROCESS || sched_params.quantum () != ACE_Time_Value::zero) { errno = EINVAL; return -1; } // Set the thread priority on the current thread. return ACE_OS::thr_setprio (sched_params.priority ()); #else ACE_UNUSED_ARG (sched_params); ACE_UNUSED_ARG (id); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_STHREADS */ } int ACE_OS::scheduling_class (const char *class_name, ACE_id_t &id) { #if defined (ACE_HAS_PRIOCNTL) // Get the priority class ID. pcinfo_t pcinfo; // The following is just to avoid Purify warnings about unitialized // memory reads. ACE_OS::memset (&pcinfo, 0, sizeof pcinfo); ACE_OS::strcpy (pcinfo.pc_clname, class_name); if (ACE_OS::priority_control (P_ALL /* ignored */, P_MYID /* ignored */, PC_GETCID, (char *) &pcinfo) == -1) { return -1; } else { id = pcinfo.pc_cid; return 0; } #else /* ! ACE_HAS_PRIOCNTL */ ACE_UNUSED_ARG (class_name); ACE_UNUSED_ARG (id); ACE_NOTSUP_RETURN (-1); #endif /* ! ACE_HAS_PRIOCNTL */ } int ACE_OS::set_scheduling_params (const ACE_Sched_Params &sched_params, ACE_id_t id) { #if defined (ACE_HAS_PRIOCNTL) // Set priority class, priority, and quantum of this LWP or process as // specified in sched_params. // Get the priority class ID. ACE_id_t class_id; if (ACE_OS::scheduling_class (sched_params.policy() == ACE_SCHED_OTHER ? "TS" : "RT", class_id) == -1) { return -1; } pcparms_t pcparms; // The following is just to avoid Purify warnings about unitialized // memory reads. ACE_OS::memset (&pcparms, 0, sizeof pcparms); pcparms.pc_cid = class_id; if (sched_params.policy () == ACE_SCHED_OTHER && sched_params.quantum () == ACE_Time_Value::zero) // SunOS doesn't support non-zero quantums in time-sharing class: use // real-time class instead. { tsparms_t tsparms; // The following is just to avoid Purify warnings about unitialized // memory reads. ACE_OS::memset (&tsparms, 0, sizeof tsparms); // Don't change ts_uprilim (user priority limit) tsparms.ts_uprilim = TS_NOCHANGE; tsparms.ts_upri = sched_params.priority (); // Package up the TS class ID and parameters for the // priority_control () call. ACE_OS::memcpy (pcparms.pc_clparms, &tsparms, sizeof tsparms); } else if (sched_params.policy () == ACE_SCHED_FIFO || (sched_params.policy () == ACE_SCHED_RR && sched_params.quantum () != ACE_Time_Value::zero)) // must have non-zero quantum for RR, to make it meaningful // A zero quantum with FIFO has special significance: it actually // means infinite time quantum, i.e., run-to-completion. { rtparms_t rtparms; // The following is just to avoid Purify warnings about unitialized // memory reads. ACE_OS::memset (&rtparms, 0, sizeof rtparms); rtparms.rt_pri = sched_params.priority (); if (sched_params.quantum () == ACE_Time_Value::zero) { // rtparms.rt_tqsecs is ignored with RT_TQINF rtparms.rt_tqnsecs = RT_TQINF; } else { rtparms.rt_tqsecs = (ulong) sched_params.quantum ().sec (); rtparms.rt_tqnsecs = sched_params.quantum ().usec () * 1000; } // Package up the RT class ID and parameters for the // priority_control () call. ACE_OS::memcpy (pcparms.pc_clparms, &rtparms, sizeof rtparms); } else { errno = EINVAL; return -1; } if (ACE_OS::priority_control ((idtype_t) (sched_params.scope () == ACE_SCOPE_THREAD ? ACE_SCOPE_PROCESS : sched_params.scope ()), id, PC_SETPARMS, (char *) &pcparms) < 0) { return ACE_OS::last_error (); } return 0; #else /* ! ACE_HAS_PRIOCNTL */ ACE_UNUSED_ARG (sched_params); ACE_UNUSED_ARG (id); ACE_NOTSUP_RETURN (-1); #endif /* ! ACE_HAS_PRIOCNTL */ } int ACE_OS::thr_create (ACE_THR_FUNC func, void *args, long flags, ACE_thread_t *thr_id, ACE_hthread_t *thr_handle, long priority, void *stack, size_t stacksize, ACE_Base_Thread_Adapter *thread_adapter, const char** thr_name) { ACE_OS_TRACE ("ACE_OS::thr_create"); if (ACE_BIT_DISABLED (flags, THR_DETACHED) && ACE_BIT_DISABLED (flags, THR_JOINABLE)) ACE_SET_BITS (flags, THR_JOINABLE); #if defined (ACE_NO_THREAD_ADAPTER) # define ACE_THREAD_FUNCTION func # define ACE_THREAD_ARGUMENT args #else /* ! defined (ACE_NO_THREAD_ADAPTER) */ # define ACE_THREAD_FUNCTION thread_args->entry_point () # define ACE_THREAD_ARGUMENT thread_args #endif /* ! defined (ACE_NO_THREAD_ADAPTER) */ ACE_Base_Thread_Adapter *thread_args = 0; if (thread_adapter == 0) #if defined (ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS) ACE_NEW_RETURN (thread_args, ACE_OS_Thread_Adapter (func, args, (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME, ACE_OS_Object_Manager::seh_except_selector(), ACE_OS_Object_Manager::seh_except_handler()), -1); #else ACE_NEW_RETURN (thread_args, ACE_OS_Thread_Adapter (func, args, (ACE_THR_C_FUNC) ACE_THREAD_ADAPTER_NAME), -1); #endif /* ACE_HAS_WIN32_STRUCTURAL_EXCEPTIONS */ else thread_args = thread_adapter; auto_ptr <ACE_Base_Thread_Adapter> auto_thread_args; if (thread_adapter == 0) ACE_AUTO_PTR_RESET (auto_thread_args, thread_args, ACE_Base_Thread_Adapter); #if defined (ACE_HAS_THREADS) // *** Set Stack Size # if defined (ACE_NEEDS_HUGE_THREAD_STACKSIZE) if (stacksize < ACE_NEEDS_HUGE_THREAD_STACKSIZE) stacksize = ACE_NEEDS_HUGE_THREAD_STACKSIZE; # endif /* ACE_NEEDS_HUGE_THREAD_STACKSIZE */ ACE_thread_t tmp_thr; if (thr_id == 0) thr_id = &tmp_thr; ACE_hthread_t tmp_handle; if (thr_handle == 0) thr_handle = &tmp_handle; # if defined (ACE_HAS_PTHREADS) int result; # if defined (ACE_PTHREAD_ATTR_T_INITIALIZE) /* Tests show that VxWorks 6.x pthread lib does not only * require zeroing of mutex/condition objects to function correctly * but also of the attribute objects. */ pthread_attr_t attr = {0}; # else pthread_attr_t attr; # endif if (ACE_ADAPT_RETVAL(::pthread_attr_init(&attr), result) != 0) return -1; if (stacksize != 0) { size_t size = stacksize; # if defined (PTHREAD_STACK_MIN) if (size < static_cast <size_t> (PTHREAD_STACK_MIN)) size = PTHREAD_STACK_MIN; # endif /* PTHREAD_STACK_MIN */ # if !defined (ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE) # if !defined (ACE_LACKS_PTHREAD_ATTR_SETSTACK) int result; if (stack != 0) result = ACE_ADAPT_RETVAL (pthread_attr_setstack (&attr, stack, size), result); else result = ACE_ADAPT_RETVAL (pthread_attr_setstacksize (&attr, size), result); if (result == -1) # else if (ACE_ADAPT_RETVAL (pthread_attr_setstacksize (&attr, size), result) == -1) # endif /* !ACE_LACKS_PTHREAD_ATTR_SETSTACK */ { ::pthread_attr_destroy (&attr); return -1; } # else ACE_UNUSED_ARG (size); # endif /* !ACE_LACKS_PTHREAD_ATTR_SETSTACKSIZE */ } // *** Set Stack Address # if defined (ACE_LACKS_PTHREAD_ATTR_SETSTACK) # if !defined (ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR) if (stack != 0) { if (ACE_ADAPT_RETVAL(::pthread_attr_setstackaddr (&attr, stack), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } # else ACE_UNUSED_ARG (stack); # endif /* !ACE_LACKS_PTHREAD_ATTR_SETSTACKADDR */ # endif /* ACE_LACKS_PTHREAD_ATTR_SETSTACK */ // *** Deal with various attributes if (flags != 0) { // *** Set Detach state # if !defined (ACE_LACKS_SETDETACH) if (ACE_BIT_ENABLED (flags, THR_DETACHED) || ACE_BIT_ENABLED (flags, THR_JOINABLE)) { int dstate = PTHREAD_CREATE_JOINABLE; if (ACE_BIT_ENABLED (flags, THR_DETACHED)) dstate = PTHREAD_CREATE_DETACHED; if (ACE_ADAPT_RETVAL(::pthread_attr_setdetachstate (&attr, dstate), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } // Note: if ACE_LACKS_SETDETACH and THR_DETACHED is enabled, we // call ::pthread_detach () below. If THR_DETACHED is not // enabled, we call ::pthread_detach () in the Thread_Manager, // after joining with the thread. # endif /* ACE_LACKS_SETDETACH */ // *** Set Policy # if !defined (ACE_LACKS_SETSCHED) || defined (ACE_HAS_PTHREAD_SCHEDPARAM) // If we wish to set the priority explicitly, we have to enable // explicit scheduling, and a policy, too. if (priority != ACE_DEFAULT_THREAD_PRIORITY) { ACE_SET_BITS (flags, THR_EXPLICIT_SCHED); if (ACE_BIT_DISABLED (flags, THR_SCHED_FIFO) && ACE_BIT_DISABLED (flags, THR_SCHED_RR) && ACE_BIT_DISABLED (flags, THR_SCHED_DEFAULT)) ACE_SET_BITS (flags, THR_SCHED_DEFAULT); } if (ACE_BIT_ENABLED (flags, THR_SCHED_FIFO) || ACE_BIT_ENABLED (flags, THR_SCHED_RR) || ACE_BIT_ENABLED (flags, THR_SCHED_DEFAULT)) { int spolicy; # if defined (ACE_HAS_ONLY_SCHED_OTHER) // SunOS, thru version 5.6, only supports SCHED_OTHER. spolicy = SCHED_OTHER; # elif defined (ACE_HAS_ONLY_SCHED_FIFO) // NonStop OSS standard pthread supports only SCHED_FIFO. spolicy = SCHED_FIFO; # else // Make sure to enable explicit scheduling, in case we didn't // enable it above (for non-default priority). ACE_SET_BITS (flags, THR_EXPLICIT_SCHED); if (ACE_BIT_ENABLED (flags, THR_SCHED_DEFAULT)) spolicy = SCHED_OTHER; else if (ACE_BIT_ENABLED (flags, THR_SCHED_FIFO)) spolicy = SCHED_FIFO; # if defined (SCHED_IO) else if (ACE_BIT_ENABLED (flags, THR_SCHED_IO)) spolicy = SCHED_IO; # else else if (ACE_BIT_ENABLED (flags, THR_SCHED_IO)) { errno = ENOSYS; return -1; } # endif /* SCHED_IO */ else spolicy = SCHED_RR; # endif /* ACE_HAS_ONLY_SCHED_OTHER */ (void) ACE_ADAPT_RETVAL(::pthread_attr_setschedpolicy (&attr, spolicy), result); if (result != 0) { ::pthread_attr_destroy (&attr); return -1; } } // *** Set Priority (use reasonable default priorities) # if defined(ACE_HAS_PTHREADS) // If we wish to explicitly set a scheduling policy, we also // have to specify a priority. We choose a "middle" priority as // default. Maybe this is also necessary on other POSIX'ish // implementations? if ((ACE_BIT_ENABLED (flags, THR_SCHED_FIFO) || ACE_BIT_ENABLED (flags, THR_SCHED_RR) || ACE_BIT_ENABLED (flags, THR_SCHED_DEFAULT)) && priority == ACE_DEFAULT_THREAD_PRIORITY) { if (ACE_BIT_ENABLED (flags, THR_SCHED_FIFO)) priority = ACE_THR_PRI_FIFO_DEF; else if (ACE_BIT_ENABLED (flags, THR_SCHED_RR)) priority = ACE_THR_PRI_RR_DEF; else // THR_SCHED_DEFAULT priority = ACE_THR_PRI_OTHER_DEF; } # endif /* ACE_HAS_PTHREADS */ if (priority != ACE_DEFAULT_THREAD_PRIORITY) { struct sched_param sparam; ACE_OS::memset ((void *) &sparam, 0, sizeof sparam); # if defined (ACE_HAS_IRIX62_THREADS) sparam.sched_priority = ACE_MIN (priority, (long) PTHREAD_MAX_PRIORITY); # elif defined (PTHREAD_MAX_PRIORITY) && !defined(ACE_HAS_PTHREADS) /* For MIT pthreads... */ sparam.prio = ACE_MIN (priority, PTHREAD_MAX_PRIORITY); # elif defined(ACE_HAS_PTHREADS) && !defined (ACE_HAS_STHREADS) // The following code forces priority into range. if (ACE_BIT_ENABLED (flags, THR_SCHED_FIFO)) sparam.sched_priority = ACE_MIN (ACE_THR_PRI_FIFO_MAX, ACE_MAX (ACE_THR_PRI_FIFO_MIN, priority)); else if (ACE_BIT_ENABLED(flags, THR_SCHED_RR)) sparam.sched_priority = ACE_MIN (ACE_THR_PRI_RR_MAX, ACE_MAX (ACE_THR_PRI_RR_MIN, priority)); else // Default policy, whether set or not sparam.sched_priority = ACE_MIN (ACE_THR_PRI_OTHER_MAX, ACE_MAX (ACE_THR_PRI_OTHER_MIN, priority)); # elif defined (PRIORITY_MAX) sparam.sched_priority = ACE_MIN (priority, (long) PRIORITY_MAX); # else sparam.sched_priority = priority; # endif /* ACE_HAS_IRIX62_THREADS */ { # if defined (sun) && defined (ACE_HAS_ONLY_SCHED_OTHER) // SunOS, through 5.6, POSIX only allows priorities > 0 to // ::pthread_attr_setschedparam. If a priority of 0 was // requested, set the thread priority after creating it, below. if (priority > 0) # endif /* sun && ACE_HAS_ONLY_SCHED_OTHER */ { (void) ACE_ADAPT_RETVAL(::pthread_attr_setschedparam (&attr, &sparam), result); if (result != 0) { ::pthread_attr_destroy (&attr); return -1; } } } } // *** Set scheduling explicit or inherited if (ACE_BIT_ENABLED (flags, THR_INHERIT_SCHED) || ACE_BIT_ENABLED (flags, THR_EXPLICIT_SCHED)) { int sched = PTHREAD_EXPLICIT_SCHED; if (ACE_BIT_ENABLED (flags, THR_INHERIT_SCHED)) sched = PTHREAD_INHERIT_SCHED; if (ACE_ADAPT_RETVAL(::pthread_attr_setinheritsched (&attr, sched), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } # else /* ACE_LACKS_SETSCHED */ ACE_UNUSED_ARG (priority); # endif /* ACE_LACKS_SETSCHED */ // *** Set pthread name # if defined (ACE_HAS_PTHREAD_ATTR_SETNAME) if (thr_name && *thr_name) { if (ACE_ADAPT_RETVAL(::pthread_attr_setname (&attr, const_cast<char*>(*thr_name)), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } #else ACE_UNUSED_ARG (thr_name); # endif // *** Set Scope # if !defined (ACE_LACKS_THREAD_PROCESS_SCOPING) if (ACE_BIT_ENABLED (flags, THR_SCOPE_SYSTEM) || ACE_BIT_ENABLED (flags, THR_SCOPE_PROCESS)) { # if defined (ACE_CONFIG_LINUX_H) || defined (HPUX) || defined (ACE_VXWORKS) // LinuxThreads do not have support for PTHREAD_SCOPE_PROCESS. // Neither does HPUX (up to HP-UX 11.00, as far as I know). // Also VxWorks only delivers scope system int scope = PTHREAD_SCOPE_SYSTEM; # else /* ACE_CONFIG_LINUX_H */ int scope = PTHREAD_SCOPE_PROCESS; # endif /* ACE_CONFIG_LINUX_H */ if (ACE_BIT_ENABLED (flags, THR_SCOPE_SYSTEM)) scope = PTHREAD_SCOPE_SYSTEM; if (ACE_ADAPT_RETVAL(::pthread_attr_setscope (&attr, scope), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } # endif /* !ACE_LACKS_THREAD_PROCESS_SCOPING */ # ifdef ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP if (ACE_BIT_ENABLED (flags, THR_SUSPENDED)) { if (ACE_ADAPT_RETVAL(::pthread_attr_setcreatesuspend_np(&attr), result) != 0) { ::pthread_attr_destroy (&attr); return -1; } } # endif /* !ACE_HAS_PTHREAD_ATTR_SETCREATESUSPEND_NP */ # if ! defined(ACE_LACKS_THR_CONCURRENCY_FUNCS) if (ACE_BIT_ENABLED (flags, THR_NEW_LWP)) { // Increment the number of LWPs by one to emulate the // SunOS semantics. int lwps = ACE_OS::thr_getconcurrency (); if (lwps == -1) { if (errno == ENOTSUP) // Suppress the ENOTSUP because it's harmless. errno = 0; else // This should never happen on SunOS: // ::thr_getconcurrency () should always succeed. return -1; } else if (ACE_OS::thr_setconcurrency (lwps + 1) == -1) { if (errno == ENOTSUP) { // Unlikely: ::thr_getconcurrency () is supported // but ::thr_setconcurrency () is not? } else return -1; } } # endif /* ! ACE_LACKS_THR_CONCURRENCY_FUNCS */ } ACE_OSCALL (ACE_ADAPT_RETVAL (::pthread_create (thr_id, &attr, thread_args->entry_point (), thread_args), result), int, -1, result); ::pthread_attr_destroy (&attr); // This is a SunOS or POSIX implementation of pthreads, where we // assume that ACE_thread_t and ACE_hthread_t are the same. If this // *isn't* correct on some platform, please let us know. if (result != -1) *thr_handle = *thr_id; # if defined (sun) && defined (ACE_HAS_ONLY_SCHED_OTHER) // SunOS prior to 5.7: // If the priority is 0, then we might have to set it now because we // couldn't set it with ::pthread_attr_setschedparam, as noted // above. This doesn't provide strictly correct behavior, because // the thread was created (above) with the priority of its parent. // (That applies regardless of the inherit_sched attribute: if it // was PTHREAD_INHERIT_SCHED, then it certainly inherited its // parent's priority. If it was PTHREAD_EXPLICIT_SCHED, then "attr" // was initialized by the SunOS ::pthread_attr_init () to contain // NULL for the priority, which indicated to SunOS ::pthread_create // () to inherit the parent priority.) if (priority == 0) { // Check the priority of this thread, which is the parent // of the newly created thread. If it is 0, then the // newly created thread will have inherited the priority // of 0, so there's no need to explicitly set it. struct sched_param sparam; int policy = 0; ACE_OSCALL (ACE_ADAPT_RETVAL (::pthread_getschedparam (thr_self (), &policy, &sparam), result), int, -1, result); // The only policy supported by by SunOS, thru version 5.6, // is SCHED_OTHER, so that's hard-coded here. policy = ACE_SCHED_OTHER; if (sparam.sched_priority != 0) { ACE_OS::memset ((void *) &sparam, 0, sizeof sparam); // The memset to 0 sets the priority to 0, so we don't need // to explicitly set sparam.sched_priority. ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::pthread_setschedparam (*thr_id, policy, &sparam), result), int, -1); } } # if defined (ACE_NEEDS_LWP_PRIO_SET) # if 0 // It would be useful if we could make this work. But, it requires // a mechanism for determining the ID of an LWP to which another // thread is bound. Is there a way to do that? Instead, just rely // on the code in ACE_Thread_Adapter::invoke () to set the LWP // priority. // If the thread is bound, then set the priority on its LWP. if (ACE_BIT_ENABLED (flags, THR_BOUND)) { ACE_Sched_Params sched_params (ACE_BIT_ENABLED (flags, THR_SCHED_FIFO) || ACE_BIT_ENABLED (flags, THR_SCHED_RR) ? ACE_SCHED_FIFO : ACE_SCHED_OTHER, priority); result = ACE_OS::lwp_setparams (sched_params, /* ? How do we find the ID of the LWP to which *thr_id is bound? */); } # endif /* 0 */ # endif /* ACE_NEEDS_LWP_PRIO_SET */ # endif /* sun && ACE_HAS_ONLY_SCHED_OTHER */ auto_thread_args.release (); return result; # elif defined (ACE_HAS_STHREADS) int result; int start_suspended = ACE_BIT_ENABLED (flags, THR_SUSPENDED); if (priority != ACE_DEFAULT_THREAD_PRIORITY) // If we need to set the priority, then we need to start the // thread in a suspended mode. ACE_SET_BITS (flags, THR_SUSPENDED); ACE_OSCALL (ACE_ADAPT_RETVAL (::thr_create (stack, stacksize, thread_args->entry_point (), thread_args, flags, thr_id), result), int, -1, result); if (result != -1) { // With SunOS threads, ACE_thread_t and ACE_hthread_t are the same. *thr_handle = *thr_id; if (priority != ACE_DEFAULT_THREAD_PRIORITY) { // Set the priority of the new thread and then let it // continue, but only if the user didn't start it suspended // in the first place! result = ACE_OS::thr_setprio (*thr_id, priority); if (result != 0) { errno = result; return -1; } if (start_suspended == 0) { result = ACE_OS::thr_continue (*thr_id); if (result != 0) { errno = result; return -1; } } } } auto_thread_args.release (); return result; # elif defined (ACE_HAS_WTHREADS) ACE_UNUSED_ARG (thr_name); ACE_UNUSED_ARG (stack); # if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) if (ACE_BIT_ENABLED (flags, THR_USE_AFX)) { CWinThread *cwin_thread = ::AfxBeginThread ((AFX_THREADPROC) thread_args->entry_point (), thread_args, priority, 0, flags | THR_SUSPENDED); // Have to duplicate the handle because // CWinThread::~CWinThread() closes the original handle. # if !defined (ACE_HAS_WINCE) (void) ::DuplicateHandle (::GetCurrentProcess (), cwin_thread->m_hThread, ::GetCurrentProcess (), thr_handle, 0, TRUE, DUPLICATE_SAME_ACCESS); # endif /* ! ACE_HAS_WINCE */ *thr_id = cwin_thread->m_nThreadID; if (ACE_BIT_ENABLED (flags, THR_SUSPENDED) == 0) cwin_thread->ResumeThread (); // cwin_thread will be deleted in AfxThreadExit() // Warning: If AfxThreadExit() is called from within the // thread, ACE_TSS_Cleanup->thread_exit() never gets called ! } else # endif /* ACE_HAS_MFC */ { int start_suspended = ACE_BIT_ENABLED (flags, THR_SUSPENDED); if (priority != ACE_DEFAULT_THREAD_PRIORITY) // If we need to set the priority, then we need to start the // thread in a suspended mode. ACE_SET_BITS (flags, THR_SUSPENDED); *thr_handle = (void *) ACE_BEGINTHREADEX (0, static_cast <u_int> (stacksize), thread_args->entry_point (), thread_args, flags, thr_id); if (priority != ACE_DEFAULT_THREAD_PRIORITY && *thr_handle != 0) { // Set the priority of the new thread and then let it // continue, but only if the user didn't start it suspended // in the first place! if (ACE_OS::thr_setprio (*thr_handle, priority) != 0) { return -1; } if (start_suspended == 0) { ACE_OS::thr_continue (*thr_handle); } } } # if 0 *thr_handle = ::CreateThread (0, stacksize, LPTHREAD_START_ROUTINE (thread_args->entry_point ()), thread_args, flags, thr_id); # endif /* 0 */ // Close down the handle if no one wants to use it. if (thr_handle == &tmp_handle && tmp_handle != 0) ::CloseHandle (tmp_handle); if (*thr_handle != 0) { auto_thread_args.release (); return 0; } else ACE_FAIL_RETURN (-1); /* NOTREACHED */ # elif defined (ACE_VXWORKS) // The hard-coded values below are what ::sp () would use. (::sp () // hardcodes priority to 100, flags to VX_FP_TASK, and stacksize to // 20,000.) stacksize should be an even integer. If a stack is not // specified, ::taskSpawn () is used so that we can set the // priority, flags, and stacksize. If a stack is specified, // ::taskInit ()/::taskActivate() are used. // If called with thr_create() defaults, use same default values as ::sp (): if (priority == ACE_DEFAULT_THREAD_PRIORITY) priority = 100; // Assumes that there is a floating point coprocessor. As noted // above, ::sp () hardcodes this, so we should be safe with it. if (flags == 0) flags = VX_FP_TASK; if (stacksize == 0) stacksize = 20000; ACE_thread_t tid; # if 0 /* Don't support setting of stack, because it doesn't seem to work. */ if (stack == 0) { # else ACE_UNUSED_ARG (stack); # endif /* 0 */ // The call below to ::taskSpawn () causes VxWorks to assign a // unique task name of the form: "t" + an integer, because the // first argument is 0. tid = ::taskSpawn (thr_name && *thr_name ? const_cast <char*> (*thr_name) : 0, priority, (int) flags, (int) stacksize, thread_args->entry_point (), (int) thread_args, 0, 0, 0, 0, 0, 0, 0, 0, 0); # if 0 /* Don't support setting of stack, because it doesn't seem to work. */ } else { // If a task name (thr_id) was not supplied, then the task will // not have a unique name. That's VxWorks' behavior. // Carve out a TCB at the beginning of the stack space. The TCB // occupies 400 bytes with VxWorks 5.3.1/I386. WIND_TCB *tcb = (WIND_TCB *) stack; // The TID is defined to be the address of the TCB. int status = ::taskInit (tcb, thr_name && *thr_name ? const_cast <char*>(*thr_name) : 0, priority, (int) flags, (char *) stack + sizeof (WIND_TCB), (int) (stacksize - sizeof (WIND_TCB)), thread_args->entry_point (), (int) thread_args, 0, 0, 0, 0, 0, 0, 0, 0, 0); if (status == OK) { // The task was successfully initialized, now activate it. status = ::taskActivate ((ACE_hthread_t) tcb); } tid = status == OK ? (ACE_thread_t) tcb : ERROR; } # endif /* 0 */ if (tid == ERROR) return -1; else { if (thr_id) *thr_id = tid; if (thr_handle) *thr_handle = tid; if (thr_name && !(*thr_name)) *thr_name = ::taskName (tid); auto_thread_args.release (); return 0; } # endif /* ACE_HAS_STHREADS */ #else ACE_UNUSED_ARG (func); ACE_UNUSED_ARG (args); ACE_UNUSED_ARG (flags); ACE_UNUSED_ARG (thr_id); ACE_UNUSED_ARG (thr_handle); ACE_UNUSED_ARG (priority); ACE_UNUSED_ARG (stack); ACE_UNUSED_ARG (stacksize); ACE_UNUSED_ARG (thr_name); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_THREADS */ } void ACE_OS::thr_exit (ACE_THR_FUNC_RETURN status) { ACE_OS_TRACE ("ACE_OS::thr_exit"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) ::pthread_exit (status); # elif defined (ACE_HAS_STHREADS) ::thr_exit (status); # elif defined (ACE_HAS_WTHREADS) // Can't call it here because on NT, the thread is exited // directly by ACE_Thread_Adapter::invoke (). // ACE_TSS_Cleanup::instance ()->thread_exit (status); # if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) int using_afx = -1; // An ACE_Thread_Descriptor really is an ACE_OS_Thread_Descriptor. // But without #including ace/Thread_Manager.h, we don't know that. ACE_OS_Thread_Descriptor *td = ACE_Base_Thread_Adapter::thr_desc_log_msg (); if (td) using_afx = ACE_BIT_ENABLED (td->flags (), THR_USE_AFX); # endif /* ACE_HAS_MFC && (ACE_HAS_MFC != 0) */ // Call TSS destructors. ACE_OS::cleanup_tss (0 /* not main thread */); // Exit the thread. // Allow CWinThread-destructor to be invoked from AfxEndThread. // _endthreadex will be called from AfxEndThread so don't exit the // thread now if we are running an MFC thread. # if defined (ACE_HAS_MFC) && (ACE_HAS_MFC != 0) if (using_afx != -1) { if (using_afx) ::AfxEndThread (status); else ACE_ENDTHREADEX (status); } else { // Not spawned by ACE_Thread_Manager, use the old buggy // version. You should seriously consider using // ACE_Thread_Manager to spawn threads. The following code is // know to cause some problem. CWinThread *pThread = ::AfxGetThread (); if (!pThread || pThread->m_nThreadID != ACE_OS::thr_self ()) ACE_ENDTHREADEX (status); else ::AfxEndThread (status); } # else ACE_ENDTHREADEX (status); # endif /* ACE_HAS_MFC && ACE_HAS_MFS != 0*/ # elif defined (ACE_HAS_VXTHREADS) ACE_thread_t tid = ACE_OS::thr_self (); *((int *) status) = ::taskDelete (tid); # endif /* ACE_HAS_PTHREADS */ #else ACE_UNUSED_ARG (status); #endif /* ACE_HAS_THREADS */ } #if defined (ACE_HAS_VXTHREADS) // Leave this in the global scope to allow // users to adjust the delay value. int ACE_THR_JOIN_DELAY = 5; int ACE_OS::thr_join (ACE_hthread_t thr_handle, ACE_THR_FUNC_RETURN *status) { // We can't get the status of the thread if (status != 0) { *status = 0; } // This method can not support joining all threads if (ACE_OS::thr_cmp (thr_handle, ACE_OS::NULL_hthread)) { ACE_NOTSUP_RETURN (-1); } int retval = ESRCH; ACE_thread_t current = ACE_OS::thr_self (); // Make sure we are not joining ourself if (ACE_OS::thr_cmp (thr_handle, current)) { retval = EDEADLK; } else { // Whether the task exists or not // we will return a successful value retval = 0; // Verify that the task id still exists while (taskIdVerify (thr_handle) == OK) { // Wait a bit to see if the task is still active. ACE_OS::sleep (ACE_THR_JOIN_DELAY); } } // Adapt the return value into errno and return value. // The ACE_ADAPT_RETVAL macro doesn't exactly do what // we need to do here, so we do it manually. if (retval != 0) { errno = retval; retval = -1; } return retval; } int ACE_OS::thr_join (ACE_thread_t waiter_id, ACE_thread_t *thr_id, ACE_THR_FUNC_RETURN *status) { thr_id = 0; return ACE_OS::thr_join (waiter_id, status); } #endif /* ACE_HAS_VXTHREADS */ int ACE_OS::thr_key_detach (ACE_thread_key_t key, void *) { #if defined (ACE_HAS_WTHREADS) || defined (ACE_HAS_TSS_EMULATION) TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { return cleanup->thread_detach_key (key); } else { return -1; } #else ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); #endif /* ACE_HAS_WTHREADS || ACE_HAS_TSS_EMULATION */ } int ACE_OS::thr_get_affinity (ACE_hthread_t thr_id, size_t cpu_set_size, cpu_set_t * cpu_mask) { #if defined (ACE_HAS_PTHREAD_GETAFFINITY_NP) // Handle of the thread, which is NPTL thread-id, normally a big number if (::pthread_getaffinity_np (thr_id, cpu_set_size, cpu_mask) != 0) { return -1; } return 0; #elif defined (ACE_HAS_2_PARAM_SCHED_GETAFFINITY) // The process-id is expected as <thr_id>, which can be a thread-id of // linux-thread, thus making binding to cpu of that particular thread only. // If you are using this flag for NPTL-threads, however, please pass as a // thr_id process id obtained by ACE_OS::getpid () ACE_UNUSED_ARG (cpu_set_size); if (::sched_getaffinity(thr_id, cpu_mask) == -1) { return -1; } return 0; #elif defined (ACE_HAS_SCHED_GETAFFINITY) // The process-id is expected as <thr_id>, which can be a thread-id of // linux-thread, thus making binding to cpu of that particular thread only. // If you are using this flag for NPTL-threads, however, please pass as a // thr_id process id obtained by ACE_OS::getpid () if (::sched_getaffinity(thr_id, cpu_set_size, cpu_mask) == -1) { return -1; } return 0; #elif defined (ACE_HAS_TASKCPUAFFINITYSET) ACE_UNUSED_ARG (cpu_set_size); int result = 0; if (ACE_ADAPT_RETVAL (::taskCpuAffinitySet (thr_id, *cpu_mask), result) == -1) { return -1; } return 0; #else ACE_UNUSED_ARG (thr_id); ACE_UNUSED_ARG (cpu_set_size); ACE_UNUSED_ARG (cpu_mask); ACE_NOTSUP_RETURN (-1); #endif } int ACE_OS::thr_set_affinity (ACE_hthread_t thr_id, size_t cpu_set_size, const cpu_set_t * cpu_mask) { #if defined (ACE_HAS_PTHREAD_SETAFFINITY_NP) if (::pthread_setaffinity_np (thr_id, cpu_set_size, cpu_mask) != 0) { return -1; } return 0; #elif defined (ACE_HAS_2_PARAM_SCHED_SETAFFINITY) // The process-id is expected as <thr_id>, which can be a thread-id of // linux-thread, thus making binding to cpu of that particular thread only. // If you are using this flag for NPTL-threads, however, please pass as a // thr_id process id obtained by ACE_OS::getpid (), but whole process will bind your CPUs // ACE_UNUSED_ARG (cpu_set_size); if (::sched_setaffinity (thr_id, cpu_mask) == -1) { return -1; } return 0; #elif defined (ACE_HAS_SCHED_SETAFFINITY) // The process-id is expected as <thr_id>, which can be a thread-id of // linux-thread, thus making binding to cpu of that particular thread only. // If you are using this flag for NPTL-threads, however, please pass as a // thr_id process id obtained by ACE_OS::getpid (), but whole process will bind your CPUs // if (::sched_setaffinity (thr_id, cpu_set_size, cpu_mask) == -1) { return -1; } return 0; #elif defined (ACE_HAS_TASKCPUAFFINITYSET) int result = 0; if (ACE_ADAPT_RETVAL (::taskCpuAffinitySet (thr_id, *cpu_mask), result) == -1) { return -1; } return 0; #else ACE_UNUSED_ARG (thr_id); ACE_UNUSED_ARG (cpu_set_size); ACE_UNUSED_ARG (cpu_mask); ACE_NOTSUP_RETURN (-1); #endif } int ACE_OS::thr_key_used (ACE_thread_key_t key) { #if defined (ACE_WIN32) || defined (ACE_HAS_TSS_EMULATION) TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { cleanup->thread_use_key (key); return 0; } return -1; #else ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); #endif /* ACE_WIN32 || ACE_HAS_TSS_EMULATION */ } #if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) int ACE_OS::thr_keycreate_native (ACE_OS_thread_key_t *key, # if defined (ACE_HAS_THR_C_DEST) ACE_THR_C_DEST dest # else ACE_THR_DEST dest # endif /* ACE_HAS_THR_C_DEST */ ) { // can't trace here. Trace uses TSS // ACE_OS_TRACE ("ACE_OS::thr_keycreate_native"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::pthread_key_create (key, dest), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::thr_keycreate (key, dest), result), int, -1); # elif defined (ACE_HAS_WTHREADS) ACE_UNUSED_ARG (dest); *key = ::TlsAlloc (); if (*key == ACE_SYSCALL_FAILED) ACE_FAIL_RETURN (-1); return 0; # endif /* ACE_HAS_STHREADS */ # else ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (dest); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } #endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ int ACE_OS::thr_keycreate (ACE_thread_key_t *key, # if defined (ACE_HAS_THR_C_DEST) ACE_THR_C_DEST dest, # else ACE_THR_DEST dest, # endif /* ACE_HAS_THR_C_DEST */ void *) { // ACE_OS_TRACE ("ACE_OS::thr_keycreate"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_TSS_EMULATION) if (ACE_TSS_Emulation::next_key (*key) == 0) { ACE_TSS_Emulation::tss_destructor (*key, dest); // Extract out the thread-specific table instance and stash away // the key and destructor so that we can free it up later on... TSS_Cleanup_Instance cleanup (TSS_Cleanup_Instance::CREATE); if (cleanup.valid ()) { return cleanup->insert (*key, dest); } else { return -1; } } else return -1; # elif defined (ACE_HAS_WTHREADS) if (ACE_OS::thr_keycreate_native (key, dest) == 0) { // Extract out the thread-specific table instance and stash away // the key and destructor so that we can free it up later on... TSS_Cleanup_Instance cleanup (TSS_Cleanup_Instance::CREATE); if (cleanup.valid ()) { return cleanup->insert (*key, dest); } else { return -1; } } else return -1; /* NOTREACHED */ # elif defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) return ACE_OS::thr_keycreate_native (key, dest); # else ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (dest); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_TSS_EMULATION */ # else /* ACE_HAS_THREADS */ ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (dest); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } #if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) int ACE_OS::thr_keyfree_native (ACE_OS_thread_key_t key) { ACE_OS_TRACE ("ACE_OS::thr_keyfree_native"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_BROKEN_THREAD_KEYFREE) || defined (ACE_HAS_THR_KEYDELETE) // For some systems, e.g. LynxOS, we need to ensure that // any registered thread destructor action for this slot // is now disabled. Otherwise in the event of a dynamic library // unload of libACE, by a program not linked with libACE, // ACE_TSS_cleanup will be invoked again at the thread exit // after libACE has been actually been unmapped from memory. (void) ACE_OS::thr_setspecific (key, 0); # endif /* ACE_HAS_BROKEN_THREAD_KEYFREE */ # if defined (ACE_HAS_PTHREADS) return ::pthread_key_delete (key); # elif defined (ACE_HAS_THR_KEYDELETE) return ::thr_keydelete (key); # elif defined (ACE_HAS_STHREADS) ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); # elif defined (ACE_HAS_WTHREADS) ACE_WIN32CALL_RETURN (ACE_ADAPT_RETVAL (::TlsFree (key), ace_result_), int, -1); # else ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_PTHREADS */ # else ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } #endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ int ACE_OS::thr_keyfree (ACE_thread_key_t key) { ACE_OS_TRACE ("ACE_OS::thr_keyfree"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_TSS_EMULATION) // Release the key in the TSS_Emulation administration ACE_TSS_Emulation::release_key (key); TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { return cleanup->free_key (key); } return -1; # elif defined (ACE_HAS_WTHREADS) // Extract out the thread-specific table instance and free up // the key and destructor. TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { return cleanup->free_key (key); } return -1; # elif defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) return ACE_OS::thr_keyfree_native (key); # else ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_TSS_EMULATION */ # else /* ACE_HAS_THREADS */ ACE_UNUSED_ARG (key); ACE_NOTSUP_RETURN (-1); return 0; # endif /* ACE_HAS_THREADS */ } int ACE_OS::thr_setprio (const ACE_Sched_Priority prio) { // Set the thread priority on the current thread. ACE_hthread_t my_thread_id; ACE_OS::thr_self (my_thread_id); int const status = ACE_OS::thr_setprio (my_thread_id, prio); #if defined (ACE_NEEDS_LWP_PRIO_SET) // If the thread is in the RT class, then set the priority on its // LWP. (Instead of doing this if the thread is in the RT class, it // should be done for all bound threads. But, there doesn't appear // to be an easy way to determine if the thread is bound.) if (status == 0) { // Find what scheduling class the thread's LWP is in. ACE_Sched_Params sched_params (ACE_SCHED_OTHER, 0); if (ACE_OS::lwp_getparams (sched_params) == -1) { return -1; } else if (sched_params.policy () == ACE_SCHED_FIFO || sched_params.policy () == ACE_SCHED_RR) { // This thread's LWP is in the RT class, so we need to set // its priority. sched_params.priority (prio); return ACE_OS::lwp_setparams (sched_params); } // else this is not an RT thread. Nothing more needs to be // done. } #endif /* ACE_NEEDS_LWP_PRIO_SET */ return status; } # if defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) int ACE_OS::thr_setspecific_native (ACE_OS_thread_key_t key, void *data) { // ACE_OS_TRACE ("ACE_OS::thr_setspecific_native"); # if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_PTHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (pthread_setspecific (key, data), result), int, -1); # elif defined (ACE_HAS_STHREADS) int result; ACE_OSCALL_RETURN (ACE_ADAPT_RETVAL (::thr_setspecific (key, data), result), int, -1); # elif defined (ACE_HAS_WTHREADS) ::TlsSetValue (key, data); return 0; # else /* ACE_HAS_STHREADS */ ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (data); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_STHREADS */ # else ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (data); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } # endif /* ACE_HAS_THREAD_SPECIFIC_STORAGE */ int ACE_OS::thr_setspecific (ACE_thread_key_t key, void *data) { // ACE_OS_TRACE ("ACE_OS::thr_setspecific"); #if defined (ACE_HAS_THREADS) # if defined (ACE_HAS_TSS_EMULATION) if (ACE_TSS_Emulation::is_key (key) == 0) { errno = EINVAL; data = 0; return -1; } else { ACE_TSS_Emulation::ts_object (key) = data; TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { cleanup->thread_use_key (key); // for TSS_Cleanup purposes treat stetting data to zero // like detaching. This is a consequence of POSIX allowing // deletion of a "used" key. if (data == 0) { cleanup->thread_detach_key (key); } return 0; } else { return -1; } } # elif defined (ACE_HAS_WTHREADS) if (ACE_OS::thr_setspecific_native (key, data) == 0) { TSS_Cleanup_Instance cleanup; if (cleanup.valid ()) { cleanup->thread_use_key (key); // for TSS_Cleanup purposes treat stetting data to zero // like detaching. This is a consequence of POSIX allowing // deletion of a "used" key. if (data == 0) { cleanup->thread_detach_key (key); } return 0; } return -1; } return -1; # elif defined (ACE_HAS_THREAD_SPECIFIC_STORAGE) return ACE_OS::thr_setspecific_native (key, data); # else /* ACE_HAS_TSS_EMULATION */ ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (data); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_TSS_EMULATION */ # else /* ACE_HAS_THREADS */ ACE_UNUSED_ARG (key); ACE_UNUSED_ARG (data); ACE_NOTSUP_RETURN (-1); # endif /* ACE_HAS_THREADS */ } void ACE_OS::unique_name (const void *object, char *name, size_t length) { // The process ID will provide uniqueness between processes on the // same machine. The "this" pointer of the <object> will provide // uniqueness between other "live" objects in the same process. The // uniqueness of this name is therefore only valid for the life of // <object>. char temp_name[ACE_UNIQUE_NAME_LEN]; ACE_OS::sprintf (temp_name, "%p%d", object, static_cast <int> (ACE_OS::getpid ())); ACE_OS::strsncpy (name, temp_name, length); } #if defined (ACE_USES_WCHAR) void ACE_OS::unique_name (const void *object, wchar_t *name, size_t length) { // The process ID will provide uniqueness between processes on the // same machine. The "this" pointer of the <object> will provide // uniqueness between other "live" objects in the same process. The // uniqueness of this name is therefore only valid for the life of // <object>. wchar_t temp_name[ACE_UNIQUE_NAME_LEN]; ACE_OS::sprintf (temp_name, ACE_TEXT ("%p%d"), object, static_cast <int> (ACE_OS::getpid ())); ACE_OS::strsncpy (name, temp_name, length); } #endif ACE_END_VERSIONED_NAMESPACE_DECL #if defined (ACE_VXWORKS) && !defined (__RTP__) # include /**/ <usrLib.h> /* for ::sp() */ # include /**/ <sysLib.h> /* for ::sysClkRateGet() */ # include "ace/Service_Config.h" // This global function can be used from the VxWorks shell to pass // arguments to a C main () function. // // usage: -> spa main, "arg1", "arg2" // // All arguments must be quoted, even numbers. int spa (FUNCPTR entry, ...) { static const unsigned int ACE_MAX_ARGS = 10; static char *argv[ACE_MAX_ARGS]; va_list pvar; unsigned int argc; // Hardcode a program name because the real one isn't available // through the VxWorks shell. argv[0] = "ace_main"; // Peel off arguments to spa () and put into argv. va_arg () isn't // necessarily supposed to return 0 when done, though since the // VxWorks shell uses a fixed number (10) of arguments, it might 0 // the unused ones. This function could be used to increase that // limit, but then it couldn't depend on the trailing 0. So, the // number of arguments would have to be passed. va_start (pvar, entry); for (argc = 1; argc <= ACE_MAX_ARGS; ++argc) { argv[argc] = va_arg (pvar, char *); if (argv[argc] == 0) break; } if (argc > ACE_MAX_ARGS && argv[argc-1] != 0) { // try to read another arg, and warn user if the limit was exceeded if (va_arg (pvar, char *) != 0) ACE_OS::fprintf (stderr, "spa(): number of arguments limited to %d\n", ACE_MAX_ARGS); } else { // fill unused argv slots with 0 to get rid of leftovers // from previous invocations for (unsigned int i = argc; i <= ACE_MAX_ARGS; ++i) argv[i] = 0; } // The hard-coded options are what ::sp () uses, except for the // larger stack size (instead of ::sp ()'s 20000). int const ret = ::taskSpawn (argv[0], // task name 100, // task priority VX_FP_TASK, // task options ACE_NEEDS_HUGE_THREAD_STACKSIZE, // stack size entry, // entry point argc, // first argument to main () (int) argv, // second argument to main () 0, 0, 0, 0, 0, 0, 0, 0); va_end (pvar); // ::taskSpawn () returns the taskID on success: return 0 instead if // successful return ret > 0 ? 0 : ret; } // A helper function for the extended spa functions static void add_to_argv (int& argc, char** argv, int max_args, char* string) { char indouble = 0; size_t previous = 0; size_t length = ACE_OS::strlen (string); if (length > 0) { // We use <= to make sure that we get the last argument for (size_t i = 0; i <= length; i++) { // Is it a double quote that hasn't been escaped? if (string[i] == '\"' && (i == 0 || string[i - 1] != '\\')) { indouble ^= 1; if (indouble) { // We have just entered a double quoted string, so // save the starting position of the contents. previous = i + 1; } else { // We have just left a double quoted string, so // zero out the ending double quote. string[i] = '\0'; } } else if (string[i] == '\\') // Escape the next character { // The next character is automatically skipped because // of the memmove(). ACE_OS::memmove (string + i, string + i + 1, length); --length; } else if (!indouble && (ACE_OS::ace_isspace (string[i]) || string[i] == '\0')) { string[i] = '\0'; if (argc < max_args) { argv[argc] = string + previous; ++argc; } else { ACE_OS::fprintf (stderr, "spae(): number of arguments " "limited to %d\n", max_args); } // Skip over whitespace in between arguments for(++i; i < length && ACE_OS::ace_isspace (string[i]); ++i) { } // Save the starting point for the next time around previous = i; // Make sure we don't skip over a character due // to the above loop to skip over whitespace --i; } } } } // This global function can be used from the VxWorks shell to pass // arguments to a C main () function. // // usage: -> spae main, "arg1 arg2 \"arg3 with spaces\"" // // All arguments must be within double quotes, even numbers. int spae (FUNCPTR entry, ...) { static int const WINDSH_ARGS = 10; static int const ACE_MAX_ARGS = 128; static char* argv[ACE_MAX_ARGS] = { "ace_main", 0 }; va_list pvar; int argc = 1; // Peel off arguments to spa () and put into argv. va_arg () isn't // necessarily supposed to return 0 when done, though since the // VxWorks shell uses a fixed number (10) of arguments, it might 0 // the unused ones. va_start (pvar, entry); int i = 0; for (char* str = va_arg (pvar, char*); str != 0 && i < WINDSH_ARGS; str = va_arg (pvar, char*), ++i) { add_to_argv(argc, argv, ACE_MAX_ARGS, str); } // fill unused argv slots with 0 to get rid of leftovers // from previous invocations for (i = argc; i < ACE_MAX_ARGS; ++i) argv[i] = 0; // The hard-coded options are what ::sp () uses, except for the // larger stack size (instead of ::sp ()'s 20000). int const ret = ::taskSpawn (argv[0], // task name 100, // task priority VX_FP_TASK, // task options ACE_NEEDS_HUGE_THREAD_STACKSIZE, // stack size entry, // entry point argc, // first argument to main () (int) argv, // second argument to main () 0, 0, 0, 0, 0, 0, 0, 0); va_end (pvar); // ::taskSpawn () returns the taskID on success: return 0 instead if // successful return ret > 0 ? 0 : ret; } // This global function can be used from the VxWorks shell to pass // arguments to a C main () function. The function will be run // within the shells task. // // usage: -> spaef main, "arg1 arg2 \"arg3 with spaces\"" // // All arguments must be within double quotes, even numbers. // Unlike the spae function, this fuction executes the supplied // routine in the foreground, rather than spawning it in a separate // task. int spaef (FUNCPTR entry, ...) { static int const WINDSH_ARGS = 10; static int const ACE_MAX_ARGS = 128; static char* argv[ACE_MAX_ARGS] = { "ace_main", 0 }; va_list pvar; int argc = 1; // Peel off arguments to spa () and put into argv. va_arg () isn't // necessarily supposed to return 0 when done, though since the // VxWorks shell uses a fixed number (10) of arguments, it might 0 // the unused ones. va_start (pvar, entry); int i = 0; for (char* str = va_arg (pvar, char*); str != 0 && i < WINDSH_ARGS; str = va_arg (pvar, char*), ++i) { add_to_argv(argc, argv, ACE_MAX_ARGS, str); } // fill unused argv slots with 0 to get rid of leftovers // from previous invocations for (i = argc; i < ACE_MAX_ARGS; ++i) argv[i] = 0; int ret = entry (argc, argv); va_end (pvar); // Return the return value of the invoked ace_main routine. return ret; } // This global function can be used from the VxWorks shell to pass // arguments to and run a main () function (i.e. ace_main). // // usage: -> vx_execae ace_main, "arg1 arg2 \"arg3 with spaces\"", [prio, [opt, [stacksz]]] // // All arguments must be within double quotes, even numbers. // This routine spawns the main () function in a separate task and waits till the // task has finished. static int _vx_call_rc = 0; static int _vx_call_entry(FUNCPTR entry, int argc, char* argv[]) { ACE_Service_Config::current (ACE_Service_Config::global()); _vx_call_rc = entry (argc, argv); return _vx_call_rc; } int vx_execae (FUNCPTR entry, char* arg, int prio, int opt, int stacksz, ...) { static int const ACE_MAX_ARGS = 128; static char* argv[ACE_MAX_ARGS] = { "ace_main", 0 }; int argc = 1; // Peel off arguments to run_main () and put into argv. if (arg) { add_to_argv(argc, argv, ACE_MAX_ARGS, arg); } // fill unused argv slots with 0 to get rid of leftovers // from previous invocations for (int i = argc; i < ACE_MAX_ARGS; ++i) argv[i] = 0; // The hard-coded options are what ::sp () uses, except for the // larger stack size (instead of ::sp ()'s 20000). int const ret = ::taskSpawn (argv[0], // task name prio==0 ? 100 : prio, // task priority opt==0 ? VX_FP_TASK : opt, // task options stacksz==0 ? ACE_NEEDS_HUGE_THREAD_STACKSIZE : stacksz, // stack size (FUNCPTR)_vx_call_entry, // entrypoint caller (int)entry, // entry point argc, // first argument to main () (int) argv, // second argument to main () 0, 0, 0, 0, 0, 0, 0); if (ret == ERROR) return 255; while( ret > 0 && ::taskIdVerify (ret) != ERROR ) ::taskDelay (3 * ::sysClkRateGet ()); // ::taskSpawn () returns the taskID on success: return _vx_call_rc instead if // successful return ret > 0 ? _vx_call_rc : 255; } #if defined(ACE_AS_STATIC_LIBS) && defined (ACE_VXWORKS_DEBUGGING_HELPER) /** Wind River workbench allows the user to spawn a kernel task as a "Debug Configuration". Use this function as the entrypoint so that the arguments are translated into the form that ace_main() requires. */ int ace_wb_exec (int arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9) { return spaef ((FUNCPTR) ace_main, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } #endif /* ACE_AS_STATIC_LIBS && ... */ #endif /* ACE_VXWORKS && !__RTP__ */
Khira/La-Confrerie
dep/ACE_wrappers/ace/OS_NS_Thread.cpp
C++
gpl-2.0
175,634
/* * Copyright (C) 2015 AChep@xda <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.achep.acdisplay.services.switches; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.SystemClock; import android.support.annotation.NonNull; import android.util.Log; import com.achep.acdisplay.services.Switch; /** * Prevents {@link com.achep.acdisplay.services.SwitchService} from working * while an alarm app is alarming. * * @author Artem Chepurnoy */ public final class AlarmSwitch extends Switch { private static final String TAG = "AlarmSwitch"; public static final String ALARM_ALERT = "ALARM_ALERT"; public static final String ALARM_DISMISS = "ALARM_DISMISS"; public static final String ALARM_SNOOZE = "ALARM_SNOOZE"; public static final String ALARM_DONE = "ALARM_DONE"; private boolean mActive; private long mAlarmingTimestamp; @NonNull private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.contains(ALARM_ALERT)) { // Hide the keyguard mActive = false; mAlarmingTimestamp = SystemClock.elapsedRealtime(); requestInactive(); } else if (action.contains(ALARM_DISMISS) || action.contains(ALARM_SNOOZE) || action.contains(ALARM_DONE)) { // Show the keyguard mActive = true; requestActive(); } else if (mActive) { // Get mad Log.w(TAG, "Received an unknown intent=" + intent.getAction() + " re-enabling the switch."); // Show the keyguard mActive = true; requestActive(); } } }; public AlarmSwitch(@NonNull Context context, @NonNull Callback callback) { super(context, callback); } /** * {@inheritDoc} */ @Override public void onCreate() { mActive = true; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Alarms.STANDARD_ALARM_ALERT_ACTION); intentFilter.addAction(Alarms.STANDARD_ALARM_DISMISS_ACTION); intentFilter.addAction(Alarms.STANDARD_ALARM_SNOOZE_ACTION); intentFilter.addAction(Alarms.STANDARD_ALARM_DONE_ACTION); for (String alarm : Alarms.ALARMS) { intentFilter.addAction(alarm + "." + ALARM_ALERT); intentFilter.addAction(alarm + "." + ALARM_DISMISS); intentFilter.addAction(alarm + "." + ALARM_SNOOZE); intentFilter.addAction(alarm + "." + ALARM_DONE); } intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1); getContext().registerReceiver(mReceiver, intentFilter); } /** * {@inheritDoc} */ @Override public void onDestroy() { getContext().unregisterReceiver(mReceiver); } /** * {@inheritDoc} */ @Override public boolean isActive() { // Check how old the alarm intent is. This is needed because // we can't be sure that alarm app will broadcast any of // DISMISS, SNOOZE, DONE intents. final long now = SystemClock.elapsedRealtime(); final boolean timedOut = now - mAlarmingTimestamp > 1000 * 60 * 5; Log.i(TAG, "Checking if AlarmSwitch is active: " + "active=" + mActive + ", " + "timed_out=" + timedOut + ", "); return mActive || timedOut; } /** * @author Artem Chepurnoy */ private static class Alarms { // Modern Android app public static final String STANDARD_ALARM_PACKAGE = "com.android.deskclock"; public static final String STANDARD_ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT"; public static final String STANDARD_ALARM_SNOOZE_ACTION = "com.android.deskclock.ALARM_SNOOZE"; public static final String STANDARD_ALARM_DISMISS_ACTION = "com.android.deskclock.ALARM_DISMISS"; public static final String STANDARD_ALARM_DONE_ACTION = "com.android.deskclock.ALARM_DONE"; // Deprecated Android app public static final String STANDARD_OLD_ALARM_PACKAGE = "com.android.alarmclock"; //-- MANUFACTURERS -------------------------------------------------------- // Samsung public static final String SAMSUNG_ALARM_PACKAGE = "com.samsung.sec.android.clockpackage.alarm"; public static final String SAMSUNG_ALARM_PACKAGE_2 = "com.sec.android.app.clockpackage.alarm"; // HTC public static final String HTC_ALARM_ALERT_PACKAGE = "com.htc.android.worldclock"; public static final String HTC_ONE_ALARM_ALERT_PACKAGE = "com.htc.android"; // Sony public static final String SONY_ALARM_PACKAGE = "com.sonyericsson.alarm"; // ZTE public static final String ZTE_ALARM_PACKAGE = "zte.com.cn.alarmclock"; // Motorola public static final String MOTO_ALARM_PACKAGE = "com.motorola.blur.alarmclock"; // LG public static final String LG_ALARM_PACKAGE = "com.lge.alarm.alarmclocknew"; //-- THIRD PARTY ---------------------------------------------------------- // Gentle Alarm public static final String GENTLE_ALARM_PACKAGE = "com.mobitobi.android.gentlealarm"; // Sleep As Android public static final String SLEEPASDROID_ALARM_PACKAGE = "com.urbandroid.sleep.alarmclock"; // Alarmdroid (1.13.2) public static final String ALARMDROID_ALARM_PACKAGE = "com.splunchy.android.alarmclock"; // Timely public static final String TIMELY_ALARM_PACKAGE = "ch.bitspin.timely"; //-- ALL-IN-ONE ----------------------------------------------------------- @NonNull public static final String ALARMS[] = { STANDARD_ALARM_PACKAGE, STANDARD_OLD_ALARM_PACKAGE, SAMSUNG_ALARM_PACKAGE, SAMSUNG_ALARM_PACKAGE_2, HTC_ALARM_ALERT_PACKAGE, HTC_ONE_ALARM_ALERT_PACKAGE, SONY_ALARM_PACKAGE, ZTE_ALARM_PACKAGE, MOTO_ALARM_PACKAGE, LG_ALARM_PACKAGE, GENTLE_ALARM_PACKAGE, SLEEPASDROID_ALARM_PACKAGE, ALARMDROID_ALARM_PACKAGE, TIMELY_ALARM_PACKAGE }; } }
hgl888/AcDisplay
project/app/src/main/java/com/achep/acdisplay/services/switches/AlarmSwitch.java
Java
gpl-2.0
7,436
<?php /** * Relais: Check if logged-in patron can order an item. * * PHP version 7 * * Copyright (C) Villanova University 2018. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package AJAX * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ namespace VuFind\AjaxHandler; use Zend\Mvc\Controller\Plugin\Params; /** * Relais: Check if logged-in patron can order an item. * * @category VuFind * @package AJAX * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ class RelaisInfo extends AbstractRelaisAction { /** * Handle a request. * * @param Params $params Parameter helper from controller * * @return array [response data, HTTP status code] */ public function handleRequest(Params $params) { $this->disableSessionWrites(); // avoid session write timing bug $oclcNumber = $params->fromQuery('oclcNumber'); $lin = $this->user['cat_username'] ?? null; // Authenticate $authResponse = $this->relais->authenticatePatron($lin, true); $authorizationId = $authResponse->AuthorizationId ?? null; if ($authorizationId === null) { return $this->formatResponse( $this->translate('Failed'), self::STATUS_HTTP_FORBIDDEN ); } $allowLoan = $authResponse->AllowLoanAddRequest ?? false; if ($allowLoan == false) { return $this->formatResponse( 'AllowLoan was false', self::STATUS_HTTP_ERROR ); } $result = $this->relais->search($oclcNumber, $authorizationId, $lin); return $this->formatResponse(compact('result')); } }
arto70/NDL-VuFind2
module/VuFind/src/VuFind/AjaxHandler/RelaisInfo.php
PHP
gpl-2.0
2,568
/* SPDX-License-Identifier: GPL-2.0 */ #include <stdio.h> #include <linux/netlink.h> #include <linux/wwan.h> #include "utils.h" #include "ip_common.h" static void print_explain(FILE *f) { fprintf(f, "Usage: ... wwan linkid LINKID\n" "\n" "Where: LINKID := 0-4294967295\n" ); } static void explain(void) { print_explain(stderr); } static int wwan_parse_opt(struct link_util *lu, int argc, char **argv, struct nlmsghdr *n) { while (argc > 0) { if (matches(*argv, "linkid") == 0) { __u32 linkid; NEXT_ARG(); if (get_u32(&linkid, *argv, 0)) invarg("linkid", *argv); addattr32(n, 1024, IFLA_WWAN_LINK_ID, linkid); } else if (matches(*argv, "help") == 0) { explain(); return -1; } else { fprintf(stderr, "wwan: unknown command \"%s\"?\n", *argv); explain(); return -1; } argc--, argv++; } return 0; } static void wwan_print_opt(struct link_util *lu, FILE *f, struct rtattr *tb[]) { if (!tb) return; if (tb[IFLA_WWAN_LINK_ID]) print_uint(PRINT_ANY, "linkid", "linkid %u ", rta_getattr_u32(tb[IFLA_WWAN_LINK_ID])); } static void wwan_print_help(struct link_util *lu, int argc, char **argv, FILE *f) { print_explain(f); } struct link_util wwan_link_util = { .id = "wwan", .maxattr = IFLA_WWAN_MAX, .parse_opt = wwan_parse_opt, .print_opt = wwan_print_opt, .print_help = wwan_print_help, };
jpirko/iproute2_mlxsw
ip/iplink_wwan.c
C
gpl-2.0
1,380
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Copyright (C) 2013 - ARM Ltd * Author: Marc Zyngier <[email protected]> */ #ifndef __ASM_ESR_H #define __ASM_ESR_H #include <asm/memory.h> #include <asm/sysreg.h> #define ESR_ELx_EC_UNKNOWN (0x00) #define ESR_ELx_EC_WFx (0x01) /* Unallocated EC: 0x02 */ #define ESR_ELx_EC_CP15_32 (0x03) #define ESR_ELx_EC_CP15_64 (0x04) #define ESR_ELx_EC_CP14_MR (0x05) #define ESR_ELx_EC_CP14_LS (0x06) #define ESR_ELx_EC_FP_ASIMD (0x07) #define ESR_ELx_EC_CP10_ID (0x08) /* EL2 only */ #define ESR_ELx_EC_PAC (0x09) /* EL2 and above */ /* Unallocated EC: 0x0A - 0x0B */ #define ESR_ELx_EC_CP14_64 (0x0C) #define ESR_ELx_EC_BTI (0x0D) #define ESR_ELx_EC_ILL (0x0E) /* Unallocated EC: 0x0F - 0x10 */ #define ESR_ELx_EC_SVC32 (0x11) #define ESR_ELx_EC_HVC32 (0x12) /* EL2 only */ #define ESR_ELx_EC_SMC32 (0x13) /* EL2 and above */ /* Unallocated EC: 0x14 */ #define ESR_ELx_EC_SVC64 (0x15) #define ESR_ELx_EC_HVC64 (0x16) /* EL2 and above */ #define ESR_ELx_EC_SMC64 (0x17) /* EL2 and above */ #define ESR_ELx_EC_SYS64 (0x18) #define ESR_ELx_EC_SVE (0x19) #define ESR_ELx_EC_ERET (0x1a) /* EL2 only */ /* Unallocated EC: 0x1B */ #define ESR_ELx_EC_FPAC (0x1C) /* EL1 and above */ /* Unallocated EC: 0x1D - 0x1E */ #define ESR_ELx_EC_IMP_DEF (0x1f) /* EL3 only */ #define ESR_ELx_EC_IABT_LOW (0x20) #define ESR_ELx_EC_IABT_CUR (0x21) #define ESR_ELx_EC_PC_ALIGN (0x22) /* Unallocated EC: 0x23 */ #define ESR_ELx_EC_DABT_LOW (0x24) #define ESR_ELx_EC_DABT_CUR (0x25) #define ESR_ELx_EC_SP_ALIGN (0x26) /* Unallocated EC: 0x27 */ #define ESR_ELx_EC_FP_EXC32 (0x28) /* Unallocated EC: 0x29 - 0x2B */ #define ESR_ELx_EC_FP_EXC64 (0x2C) /* Unallocated EC: 0x2D - 0x2E */ #define ESR_ELx_EC_SERROR (0x2F) #define ESR_ELx_EC_BREAKPT_LOW (0x30) #define ESR_ELx_EC_BREAKPT_CUR (0x31) #define ESR_ELx_EC_SOFTSTP_LOW (0x32) #define ESR_ELx_EC_SOFTSTP_CUR (0x33) #define ESR_ELx_EC_WATCHPT_LOW (0x34) #define ESR_ELx_EC_WATCHPT_CUR (0x35) /* Unallocated EC: 0x36 - 0x37 */ #define ESR_ELx_EC_BKPT32 (0x38) /* Unallocated EC: 0x39 */ #define ESR_ELx_EC_VECTOR32 (0x3A) /* EL2 only */ /* Unallocated EC: 0x3B */ #define ESR_ELx_EC_BRK64 (0x3C) /* Unallocated EC: 0x3D - 0x3F */ #define ESR_ELx_EC_MAX (0x3F) #define ESR_ELx_EC_SHIFT (26) #define ESR_ELx_EC_MASK (UL(0x3F) << ESR_ELx_EC_SHIFT) #define ESR_ELx_EC(esr) (((esr) & ESR_ELx_EC_MASK) >> ESR_ELx_EC_SHIFT) #define ESR_ELx_IL_SHIFT (25) #define ESR_ELx_IL (UL(1) << ESR_ELx_IL_SHIFT) #define ESR_ELx_ISS_MASK (ESR_ELx_IL - 1) /* ISS field definitions shared by different classes */ #define ESR_ELx_WNR_SHIFT (6) #define ESR_ELx_WNR (UL(1) << ESR_ELx_WNR_SHIFT) /* Asynchronous Error Type */ #define ESR_ELx_IDS_SHIFT (24) #define ESR_ELx_IDS (UL(1) << ESR_ELx_IDS_SHIFT) #define ESR_ELx_AET_SHIFT (10) #define ESR_ELx_AET (UL(0x7) << ESR_ELx_AET_SHIFT) #define ESR_ELx_AET_UC (UL(0) << ESR_ELx_AET_SHIFT) #define ESR_ELx_AET_UEU (UL(1) << ESR_ELx_AET_SHIFT) #define ESR_ELx_AET_UEO (UL(2) << ESR_ELx_AET_SHIFT) #define ESR_ELx_AET_UER (UL(3) << ESR_ELx_AET_SHIFT) #define ESR_ELx_AET_CE (UL(6) << ESR_ELx_AET_SHIFT) /* Shared ISS field definitions for Data/Instruction aborts */ #define ESR_ELx_SET_SHIFT (11) #define ESR_ELx_SET_MASK (UL(3) << ESR_ELx_SET_SHIFT) #define ESR_ELx_FnV_SHIFT (10) #define ESR_ELx_FnV (UL(1) << ESR_ELx_FnV_SHIFT) #define ESR_ELx_EA_SHIFT (9) #define ESR_ELx_EA (UL(1) << ESR_ELx_EA_SHIFT) #define ESR_ELx_S1PTW_SHIFT (7) #define ESR_ELx_S1PTW (UL(1) << ESR_ELx_S1PTW_SHIFT) /* Shared ISS fault status code(IFSC/DFSC) for Data/Instruction aborts */ #define ESR_ELx_FSC (0x3F) #define ESR_ELx_FSC_TYPE (0x3C) #define ESR_ELx_FSC_LEVEL (0x03) #define ESR_ELx_FSC_EXTABT (0x10) #define ESR_ELx_FSC_MTE (0x11) #define ESR_ELx_FSC_SERROR (0x11) #define ESR_ELx_FSC_ACCESS (0x08) #define ESR_ELx_FSC_FAULT (0x04) #define ESR_ELx_FSC_PERM (0x0C) /* ISS field definitions for Data Aborts */ #define ESR_ELx_ISV_SHIFT (24) #define ESR_ELx_ISV (UL(1) << ESR_ELx_ISV_SHIFT) #define ESR_ELx_SAS_SHIFT (22) #define ESR_ELx_SAS (UL(3) << ESR_ELx_SAS_SHIFT) #define ESR_ELx_SSE_SHIFT (21) #define ESR_ELx_SSE (UL(1) << ESR_ELx_SSE_SHIFT) #define ESR_ELx_SRT_SHIFT (16) #define ESR_ELx_SRT_MASK (UL(0x1F) << ESR_ELx_SRT_SHIFT) #define ESR_ELx_SF_SHIFT (15) #define ESR_ELx_SF (UL(1) << ESR_ELx_SF_SHIFT) #define ESR_ELx_AR_SHIFT (14) #define ESR_ELx_AR (UL(1) << ESR_ELx_AR_SHIFT) #define ESR_ELx_CM_SHIFT (8) #define ESR_ELx_CM (UL(1) << ESR_ELx_CM_SHIFT) /* ISS field definitions for exceptions taken in to Hyp */ #define ESR_ELx_CV (UL(1) << 24) #define ESR_ELx_COND_SHIFT (20) #define ESR_ELx_COND_MASK (UL(0xF) << ESR_ELx_COND_SHIFT) #define ESR_ELx_WFx_ISS_TI (UL(1) << 0) #define ESR_ELx_WFx_ISS_WFI (UL(0) << 0) #define ESR_ELx_WFx_ISS_WFE (UL(1) << 0) #define ESR_ELx_xVC_IMM_MASK ((1UL << 16) - 1) #define DISR_EL1_IDS (UL(1) << 24) /* * DISR_EL1 and ESR_ELx share the bottom 13 bits, but the RES0 bits may mean * different things in the future... */ #define DISR_EL1_ESR_MASK (ESR_ELx_AET | ESR_ELx_EA | ESR_ELx_FSC) /* ESR value templates for specific events */ #define ESR_ELx_WFx_MASK (ESR_ELx_EC_MASK | ESR_ELx_WFx_ISS_TI) #define ESR_ELx_WFx_WFI_VAL ((ESR_ELx_EC_WFx << ESR_ELx_EC_SHIFT) | \ ESR_ELx_WFx_ISS_WFI) /* BRK instruction trap from AArch64 state */ #define ESR_ELx_BRK64_ISS_COMMENT_MASK 0xffff /* ISS field definitions for System instruction traps */ #define ESR_ELx_SYS64_ISS_RES0_SHIFT 22 #define ESR_ELx_SYS64_ISS_RES0_MASK (UL(0x7) << ESR_ELx_SYS64_ISS_RES0_SHIFT) #define ESR_ELx_SYS64_ISS_DIR_MASK 0x1 #define ESR_ELx_SYS64_ISS_DIR_READ 0x1 #define ESR_ELx_SYS64_ISS_DIR_WRITE 0x0 #define ESR_ELx_SYS64_ISS_RT_SHIFT 5 #define ESR_ELx_SYS64_ISS_RT_MASK (UL(0x1f) << ESR_ELx_SYS64_ISS_RT_SHIFT) #define ESR_ELx_SYS64_ISS_CRM_SHIFT 1 #define ESR_ELx_SYS64_ISS_CRM_MASK (UL(0xf) << ESR_ELx_SYS64_ISS_CRM_SHIFT) #define ESR_ELx_SYS64_ISS_CRN_SHIFT 10 #define ESR_ELx_SYS64_ISS_CRN_MASK (UL(0xf) << ESR_ELx_SYS64_ISS_CRN_SHIFT) #define ESR_ELx_SYS64_ISS_OP1_SHIFT 14 #define ESR_ELx_SYS64_ISS_OP1_MASK (UL(0x7) << ESR_ELx_SYS64_ISS_OP1_SHIFT) #define ESR_ELx_SYS64_ISS_OP2_SHIFT 17 #define ESR_ELx_SYS64_ISS_OP2_MASK (UL(0x7) << ESR_ELx_SYS64_ISS_OP2_SHIFT) #define ESR_ELx_SYS64_ISS_OP0_SHIFT 20 #define ESR_ELx_SYS64_ISS_OP0_MASK (UL(0x3) << ESR_ELx_SYS64_ISS_OP0_SHIFT) #define ESR_ELx_SYS64_ISS_SYS_MASK (ESR_ELx_SYS64_ISS_OP0_MASK | \ ESR_ELx_SYS64_ISS_OP1_MASK | \ ESR_ELx_SYS64_ISS_OP2_MASK | \ ESR_ELx_SYS64_ISS_CRN_MASK | \ ESR_ELx_SYS64_ISS_CRM_MASK) #define ESR_ELx_SYS64_ISS_SYS_VAL(op0, op1, op2, crn, crm) \ (((op0) << ESR_ELx_SYS64_ISS_OP0_SHIFT) | \ ((op1) << ESR_ELx_SYS64_ISS_OP1_SHIFT) | \ ((op2) << ESR_ELx_SYS64_ISS_OP2_SHIFT) | \ ((crn) << ESR_ELx_SYS64_ISS_CRN_SHIFT) | \ ((crm) << ESR_ELx_SYS64_ISS_CRM_SHIFT)) #define ESR_ELx_SYS64_ISS_SYS_OP_MASK (ESR_ELx_SYS64_ISS_SYS_MASK | \ ESR_ELx_SYS64_ISS_DIR_MASK) #define ESR_ELx_SYS64_ISS_RT(esr) \ (((esr) & ESR_ELx_SYS64_ISS_RT_MASK) >> ESR_ELx_SYS64_ISS_RT_SHIFT) /* * User space cache operations have the following sysreg encoding * in System instructions. * op0=1, op1=3, op2=1, crn=7, crm={ 5, 10, 11, 12, 13, 14 }, WRITE (L=0) */ #define ESR_ELx_SYS64_ISS_CRM_DC_CIVAC 14 #define ESR_ELx_SYS64_ISS_CRM_DC_CVADP 13 #define ESR_ELx_SYS64_ISS_CRM_DC_CVAP 12 #define ESR_ELx_SYS64_ISS_CRM_DC_CVAU 11 #define ESR_ELx_SYS64_ISS_CRM_DC_CVAC 10 #define ESR_ELx_SYS64_ISS_CRM_IC_IVAU 5 #define ESR_ELx_SYS64_ISS_EL0_CACHE_OP_MASK (ESR_ELx_SYS64_ISS_OP0_MASK | \ ESR_ELx_SYS64_ISS_OP1_MASK | \ ESR_ELx_SYS64_ISS_OP2_MASK | \ ESR_ELx_SYS64_ISS_CRN_MASK | \ ESR_ELx_SYS64_ISS_DIR_MASK) #define ESR_ELx_SYS64_ISS_EL0_CACHE_OP_VAL \ (ESR_ELx_SYS64_ISS_SYS_VAL(1, 3, 1, 7, 0) | \ ESR_ELx_SYS64_ISS_DIR_WRITE) /* * User space MRS operations which are supported for emulation * have the following sysreg encoding in System instructions. * op0 = 3, op1= 0, crn = 0, {crm = 0, 4-7}, READ (L = 1) */ #define ESR_ELx_SYS64_ISS_SYS_MRS_OP_MASK (ESR_ELx_SYS64_ISS_OP0_MASK | \ ESR_ELx_SYS64_ISS_OP1_MASK | \ ESR_ELx_SYS64_ISS_CRN_MASK | \ ESR_ELx_SYS64_ISS_DIR_MASK) #define ESR_ELx_SYS64_ISS_SYS_MRS_OP_VAL \ (ESR_ELx_SYS64_ISS_SYS_VAL(3, 0, 0, 0, 0) | \ ESR_ELx_SYS64_ISS_DIR_READ) #define ESR_ELx_SYS64_ISS_SYS_CTR ESR_ELx_SYS64_ISS_SYS_VAL(3, 3, 1, 0, 0) #define ESR_ELx_SYS64_ISS_SYS_CTR_READ (ESR_ELx_SYS64_ISS_SYS_CTR | \ ESR_ELx_SYS64_ISS_DIR_READ) #define ESR_ELx_SYS64_ISS_SYS_CNTVCT (ESR_ELx_SYS64_ISS_SYS_VAL(3, 3, 2, 14, 0) | \ ESR_ELx_SYS64_ISS_DIR_READ) #define ESR_ELx_SYS64_ISS_SYS_CNTVCTSS (ESR_ELx_SYS64_ISS_SYS_VAL(3, 3, 6, 14, 0) | \ ESR_ELx_SYS64_ISS_DIR_READ) #define ESR_ELx_SYS64_ISS_SYS_CNTFRQ (ESR_ELx_SYS64_ISS_SYS_VAL(3, 3, 0, 14, 0) | \ ESR_ELx_SYS64_ISS_DIR_READ) #define esr_sys64_to_sysreg(e) \ sys_reg((((e) & ESR_ELx_SYS64_ISS_OP0_MASK) >> \ ESR_ELx_SYS64_ISS_OP0_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_OP1_MASK) >> \ ESR_ELx_SYS64_ISS_OP1_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_CRN_MASK) >> \ ESR_ELx_SYS64_ISS_CRN_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_CRM_MASK) >> \ ESR_ELx_SYS64_ISS_CRM_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_OP2_MASK) >> \ ESR_ELx_SYS64_ISS_OP2_SHIFT)) #define esr_cp15_to_sysreg(e) \ sys_reg(3, \ (((e) & ESR_ELx_SYS64_ISS_OP1_MASK) >> \ ESR_ELx_SYS64_ISS_OP1_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_CRN_MASK) >> \ ESR_ELx_SYS64_ISS_CRN_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_CRM_MASK) >> \ ESR_ELx_SYS64_ISS_CRM_SHIFT), \ (((e) & ESR_ELx_SYS64_ISS_OP2_MASK) >> \ ESR_ELx_SYS64_ISS_OP2_SHIFT)) /* * ISS field definitions for floating-point exception traps * (FP_EXC_32/FP_EXC_64). * * (The FPEXC_* constants are used instead for common bits.) */ #define ESR_ELx_FP_EXC_TFV (UL(1) << 23) /* * ISS field definitions for CP15 accesses */ #define ESR_ELx_CP15_32_ISS_DIR_MASK 0x1 #define ESR_ELx_CP15_32_ISS_DIR_READ 0x1 #define ESR_ELx_CP15_32_ISS_DIR_WRITE 0x0 #define ESR_ELx_CP15_32_ISS_RT_SHIFT 5 #define ESR_ELx_CP15_32_ISS_RT_MASK (UL(0x1f) << ESR_ELx_CP15_32_ISS_RT_SHIFT) #define ESR_ELx_CP15_32_ISS_CRM_SHIFT 1 #define ESR_ELx_CP15_32_ISS_CRM_MASK (UL(0xf) << ESR_ELx_CP15_32_ISS_CRM_SHIFT) #define ESR_ELx_CP15_32_ISS_CRN_SHIFT 10 #define ESR_ELx_CP15_32_ISS_CRN_MASK (UL(0xf) << ESR_ELx_CP15_32_ISS_CRN_SHIFT) #define ESR_ELx_CP15_32_ISS_OP1_SHIFT 14 #define ESR_ELx_CP15_32_ISS_OP1_MASK (UL(0x7) << ESR_ELx_CP15_32_ISS_OP1_SHIFT) #define ESR_ELx_CP15_32_ISS_OP2_SHIFT 17 #define ESR_ELx_CP15_32_ISS_OP2_MASK (UL(0x7) << ESR_ELx_CP15_32_ISS_OP2_SHIFT) #define ESR_ELx_CP15_32_ISS_SYS_MASK (ESR_ELx_CP15_32_ISS_OP1_MASK | \ ESR_ELx_CP15_32_ISS_OP2_MASK | \ ESR_ELx_CP15_32_ISS_CRN_MASK | \ ESR_ELx_CP15_32_ISS_CRM_MASK | \ ESR_ELx_CP15_32_ISS_DIR_MASK) #define ESR_ELx_CP15_32_ISS_SYS_VAL(op1, op2, crn, crm) \ (((op1) << ESR_ELx_CP15_32_ISS_OP1_SHIFT) | \ ((op2) << ESR_ELx_CP15_32_ISS_OP2_SHIFT) | \ ((crn) << ESR_ELx_CP15_32_ISS_CRN_SHIFT) | \ ((crm) << ESR_ELx_CP15_32_ISS_CRM_SHIFT)) #define ESR_ELx_CP15_64_ISS_DIR_MASK 0x1 #define ESR_ELx_CP15_64_ISS_DIR_READ 0x1 #define ESR_ELx_CP15_64_ISS_DIR_WRITE 0x0 #define ESR_ELx_CP15_64_ISS_RT_SHIFT 5 #define ESR_ELx_CP15_64_ISS_RT_MASK (UL(0x1f) << ESR_ELx_CP15_64_ISS_RT_SHIFT) #define ESR_ELx_CP15_64_ISS_RT2_SHIFT 10 #define ESR_ELx_CP15_64_ISS_RT2_MASK (UL(0x1f) << ESR_ELx_CP15_64_ISS_RT2_SHIFT) #define ESR_ELx_CP15_64_ISS_OP1_SHIFT 16 #define ESR_ELx_CP15_64_ISS_OP1_MASK (UL(0xf) << ESR_ELx_CP15_64_ISS_OP1_SHIFT) #define ESR_ELx_CP15_64_ISS_CRM_SHIFT 1 #define ESR_ELx_CP15_64_ISS_CRM_MASK (UL(0xf) << ESR_ELx_CP15_64_ISS_CRM_SHIFT) #define ESR_ELx_CP15_64_ISS_SYS_VAL(op1, crm) \ (((op1) << ESR_ELx_CP15_64_ISS_OP1_SHIFT) | \ ((crm) << ESR_ELx_CP15_64_ISS_CRM_SHIFT)) #define ESR_ELx_CP15_64_ISS_SYS_MASK (ESR_ELx_CP15_64_ISS_OP1_MASK | \ ESR_ELx_CP15_64_ISS_CRM_MASK | \ ESR_ELx_CP15_64_ISS_DIR_MASK) #define ESR_ELx_CP15_64_ISS_SYS_CNTVCT (ESR_ELx_CP15_64_ISS_SYS_VAL(1, 14) | \ ESR_ELx_CP15_64_ISS_DIR_READ) #define ESR_ELx_CP15_64_ISS_SYS_CNTVCTSS (ESR_ELx_CP15_64_ISS_SYS_VAL(9, 14) | \ ESR_ELx_CP15_64_ISS_DIR_READ) #define ESR_ELx_CP15_32_ISS_SYS_CNTFRQ (ESR_ELx_CP15_32_ISS_SYS_VAL(0, 0, 14, 0) |\ ESR_ELx_CP15_32_ISS_DIR_READ) #ifndef __ASSEMBLY__ #include <asm/types.h> static inline bool esr_is_data_abort(u32 esr) { const u32 ec = ESR_ELx_EC(esr); return ec == ESR_ELx_EC_DABT_LOW || ec == ESR_ELx_EC_DABT_CUR; } const char *esr_get_class_string(u32 esr); #endif /* __ASSEMBLY */ #endif /* __ASM_ESR_H */
rperier/linux
arch/arm64/include/asm/esr.h
C
gpl-2.0
12,729
/* * Copyright 2009-2011 Freescale Semiconductor, Inc. * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 #include <hwconfig.h> #endif #include <asm/fsl_serdes.h> #include <asm/immap_85xx.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/fsl_law.h> #include <asm/errno.h> #include "fsl_corenet_serdes.h" /* * The work-arounds for erratum SERDES8 and SERDES-A001 are linked together. * The code is already very complicated as it is, and separating the two * completely would just make things worse. We try to keep them as separate * as possible, but for now we require SERDES8 if SERDES_A001 is defined. */ #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A001 #ifndef CONFIG_SYS_P4080_ERRATUM_SERDES8 #error "CONFIG_SYS_P4080_ERRATUM_SERDES_A001 requires CONFIG_SYS_P4080_ERRATUM_SERDES8" #endif #endif static u32 serdes_prtcl_map; #ifdef DEBUG static const char *serdes_prtcl_str[] = { [NONE] = "NA", [PCIE1] = "PCIE1", [PCIE2] = "PCIE2", [PCIE3] = "PCIE3", [PCIE4] = "PCIE4", [SATA1] = "SATA1", [SATA2] = "SATA2", [SRIO1] = "SRIO1", [SRIO2] = "SRIO2", [SGMII_FM1_DTSEC1] = "SGMII_FM1_DTSEC1", [SGMII_FM1_DTSEC2] = "SGMII_FM1_DTSEC2", [SGMII_FM1_DTSEC3] = "SGMII_FM1_DTSEC3", [SGMII_FM1_DTSEC4] = "SGMII_FM1_DTSEC4", [SGMII_FM1_DTSEC5] = "SGMII_FM1_DTSEC5", [SGMII_FM2_DTSEC1] = "SGMII_FM2_DTSEC1", [SGMII_FM2_DTSEC2] = "SGMII_FM2_DTSEC2", [SGMII_FM2_DTSEC3] = "SGMII_FM2_DTSEC3", [SGMII_FM2_DTSEC4] = "SGMII_FM2_DTSEC4", [SGMII_FM2_DTSEC5] = "SGMII_FM2_DTSEC5", [XAUI_FM1] = "XAUI_FM1", [XAUI_FM2] = "XAUI_FM2", [AURORA] = "DEBUG", }; #endif static const struct { int idx; unsigned int lpd; /* RCW lane powerdown bit */ int bank; } lanes[SRDS_MAX_LANES] = { { 0, 152, FSL_SRDS_BANK_1 }, { 1, 153, FSL_SRDS_BANK_1 }, { 2, 154, FSL_SRDS_BANK_1 }, { 3, 155, FSL_SRDS_BANK_1 }, { 4, 156, FSL_SRDS_BANK_1 }, { 5, 157, FSL_SRDS_BANK_1 }, { 6, 158, FSL_SRDS_BANK_1 }, { 7, 159, FSL_SRDS_BANK_1 }, { 8, 160, FSL_SRDS_BANK_1 }, { 9, 161, FSL_SRDS_BANK_1 }, { 16, 162, FSL_SRDS_BANK_2 }, { 17, 163, FSL_SRDS_BANK_2 }, { 18, 164, FSL_SRDS_BANK_2 }, { 19, 165, FSL_SRDS_BANK_2 }, #ifdef CONFIG_PPC_P4080 { 20, 170, FSL_SRDS_BANK_3 }, { 21, 171, FSL_SRDS_BANK_3 }, { 22, 172, FSL_SRDS_BANK_3 }, { 23, 173, FSL_SRDS_BANK_3 }, #else { 20, 166, FSL_SRDS_BANK_3 }, { 21, 167, FSL_SRDS_BANK_3 }, { 22, 168, FSL_SRDS_BANK_3 }, { 23, 169, FSL_SRDS_BANK_3 }, #endif #if SRDS_MAX_BANK > 3 { 24, 175, FSL_SRDS_BANK_4 }, { 25, 176, FSL_SRDS_BANK_4 }, #endif }; int serdes_get_lane_idx(int lane) { return lanes[lane].idx; } int serdes_get_bank_by_lane(int lane) { return lanes[lane].bank; } int serdes_lane_enabled(int lane) { ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); serdes_corenet_t *regs = (void *)CONFIG_SYS_FSL_CORENET_SERDES_ADDR; int bank = lanes[lane].bank; int word = lanes[lane].lpd / 32; int bit = lanes[lane].lpd % 32; if (in_be32(&regs->bank[bank].rstctl) & SRDS_RSTCTL_SDPD) return 0; #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 /* * For banks two and three, use the srds_lpd_b[] array instead of the * RCW, because this array contains the real values of SRDS_LPD_B2 and * SRDS_LPD_B3. */ if (bank > 0) return !(srds_lpd_b[bank] & (8 >> (lane - (6 + 4 * bank)))); #endif return !(in_be32(&gur->rcwsr[word]) & (0x80000000 >> bit)); } int is_serdes_configured(enum srds_prtcl device) { ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); /* Is serdes enabled at all? */ if (!(in_be32(&gur->rcwsr[5]) & FSL_CORENET_RCWSR5_SRDS_EN)) return 0; return (1 << device) & serdes_prtcl_map; } static int __serdes_get_first_lane(uint32_t prtcl, enum srds_prtcl device) { int i; for (i = 0; i < SRDS_MAX_LANES; i++) { if (serdes_get_prtcl(prtcl, i) == device) return i; } return -ENODEV; } /* * Returns the SERDES lane (0..SRDS_MAX_LANES-1) that routes to the given * device. This depends on the current SERDES protocol, as defined in the RCW. * * Returns a negative error code if SERDES is disabled or the given device is * not supported in the current SERDES protocol. */ int serdes_get_first_lane(enum srds_prtcl device) { u32 prtcl; const ccsr_gur_t *gur; gur = (typeof(gur))CONFIG_SYS_MPC85xx_GUTS_ADDR; /* Is serdes enabled at all? */ if (unlikely((in_be32(&gur->rcwsr[5]) & 0x2000) == 0)) return -ENODEV; prtcl = (in_be32(&gur->rcwsr[4]) & FSL_CORENET_RCWSR4_SRDS_PRTCL) >> 26; return __serdes_get_first_lane(prtcl, device); } #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES9 /* * Returns the SERDES bank (1, 2, or 3) that a given device is on for a given * SERDES protocol. * * Returns a negative error code if the given device is not supported for the * given SERDES protocol. */ static int serdes_get_bank_by_device(uint32_t prtcl, enum srds_prtcl device) { int lane; lane = __serdes_get_first_lane(prtcl, device); if (unlikely(lane < 0)) return lane; return serdes_get_bank_by_lane(lane); } static uint32_t __serdes_get_lane_count(uint32_t prtcl, enum srds_prtcl device, int first) { int lane; for (lane = first; lane < SRDS_MAX_LANES; lane++) { if (serdes_get_prtcl(prtcl, lane) != device) break; } return lane - first; } static void __serdes_reset_rx(serdes_corenet_t *regs, uint32_t prtcl, enum srds_prtcl device) { int lane, idx, first, last; lane = __serdes_get_first_lane(prtcl, device); if (unlikely(lane < 0)) return; first = serdes_get_lane_idx(lane); last = first + __serdes_get_lane_count(prtcl, device, lane); /* * Set BnGCRy0[RRST] = 0 for each lane in the each bank that is * selected as XAUI to place the lane into reset. */ for (idx = first; idx < last; idx++) clrbits_be32(&regs->lane[idx].gcr0, SRDS_GCR0_RRST); /* Wait at least 250 ns */ udelay(1); /* * Set BnGCRy0[RRST] = 1 for each lane in the each bank that is * selected as XAUI to bring the lane out of reset. */ for (idx = first; idx < last; idx++) setbits_be32(&regs->lane[idx].gcr0, SRDS_GCR0_RRST); } void serdes_reset_rx(enum srds_prtcl device) { u32 prtcl; const ccsr_gur_t *gur; serdes_corenet_t *regs; if (unlikely(device == NONE)) return; gur = (typeof(gur))CONFIG_SYS_MPC85xx_GUTS_ADDR; /* Is serdes enabled at all? */ if (unlikely((in_be32(&gur->rcwsr[5]) & 0x2000) == 0)) return; regs = (typeof(regs))CONFIG_SYS_FSL_CORENET_SERDES_ADDR; prtcl = (in_be32(&gur->rcwsr[4]) & FSL_CORENET_RCWSR4_SRDS_PRTCL) >> 26; __serdes_reset_rx(regs, prtcl, device); } #endif #ifndef CONFIG_SYS_DCSRBAR_PHYS #define CONFIG_SYS_DCSRBAR_PHYS 0x80000000 /* Must be 1GB-aligned for rev1.0 */ #define CONFIG_SYS_DCSRBAR 0x80000000 #define __DCSR_NOT_DEFINED_BY_CONFIG #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 /* * Enable a SERDES bank that was disabled via the RCW * * We only call this function for SERDES8 and SERDES-A001 in cases we really * want to enable the bank, whether we actually want to use the lanes or not, * so make sure at least one lane is enabled. We're only enabling this one * lane to satisfy errata requirements that the bank be enabled. * * We use a local variable instead of srds_lpd_b[] because we want drivers to * think that the lanes actually are disabled. */ static void enable_bank(ccsr_gur_t *gur, int bank) { u32 rcw5; u32 temp_lpd_b = srds_lpd_b[bank]; /* * If we're asked to disable all lanes, just pretend we're doing * that. */ if (temp_lpd_b == 0xF) temp_lpd_b = 0xE; /* * Enable the lanes SRDS_LPD_Bn. The RCW bits are read-only in * CCSR, and read/write in DSCR. */ rcw5 = in_be32(gur->rcwsr + 5); if (bank == FSL_SRDS_BANK_2) { rcw5 &= ~FSL_CORENET_RCWSRn_SRDS_LPD_B2; rcw5 |= temp_lpd_b << 26; } else if (bank == FSL_SRDS_BANK_3) { rcw5 &= ~FSL_CORENET_RCWSRn_SRDS_LPD_B3; rcw5 |= temp_lpd_b << 18; } else { printf("SERDES: enable_bank: bad bank %d\n", bank + 1); return; } /* See similar code in cpu/mpc85xx/cpu_init.c for an explanation * of the DCSR mapping. */ { #ifdef __DCSR_NOT_DEFINED_BY_CONFIG struct law_entry law = find_law(CONFIG_SYS_DCSRBAR_PHYS); int law_index; if (law.index == -1) law_index = set_next_law(CONFIG_SYS_DCSRBAR_PHYS, LAW_SIZE_1M, LAW_TRGT_IF_DCSR); else set_law(law.index, CONFIG_SYS_DCSRBAR_PHYS, LAW_SIZE_1M, LAW_TRGT_IF_DCSR); #endif u32 *p = (void *)CONFIG_SYS_DCSRBAR + 0x20114; out_be32(p, rcw5); #ifdef __DCSR_NOT_DEFINED_BY_CONFIG if (law.index == -1) disable_law(law_index); else set_law(law.index, law.addr, law.size, law.trgt_id); #endif } } /* * To avoid problems with clock jitter, rev 2 p4080 uses the pll from * bank 3 to clock banks 2 and 3, as well as a limited selection of * protocol configurations. This requires that banks 2 and 3's lanes be * disabled in the RCW, and enabled with some fixup here to re-enable * them, and to configure bank 2's clock parameters in bank 3's pll in * cases where they differ. */ static void p4080_erratum_serdes8(serdes_corenet_t *regs, ccsr_gur_t *gur, u32 devdisr, u32 devdisr2, int cfg) { int srds_ratio_b2; int rfck_sel; /* * The disabled lanes of bank 2 will cause the associated * logic blocks to be disabled in DEVDISR. We reverse that here. * * Note that normally it is not permitted to clear DEVDISR bits * once the device has been disabled, but the hardware people * say that this special case is OK. */ clrbits_be32(&gur->devdisr, devdisr); clrbits_be32(&gur->devdisr2, devdisr2); /* * Some protocols require special handling. There are a few * additional protocol configurations that can be used, which are * not listed here. See app note 4065 for supported protocol * configurations. */ switch (cfg) { case 0x19: /* * Bank 2 has PCIe which wants BWSEL -- tell bank 3's PLL. * SGMII on bank 3 should still be usable. */ setbits_be32(&regs->bank[FSL_SRDS_BANK_3].pllcr1, SRDS_PLLCR1_PLL_BWSEL); break; case 0x0f: case 0x10: /* * Banks 2 (XAUI) and 3 (SGMII) have different clocking * requirements in these configurations. Bank 3 cannot * be used and should have its lanes (but not the bank * itself) disabled in the RCW. We set up bank 3's pll * for bank 2's needs here. */ srds_ratio_b2 = (in_be32(&gur->rcwsr[4]) >> 13) & 7; /* Determine refclock from XAUI ratio */ switch (srds_ratio_b2) { case 1: /* 20:1 */ rfck_sel = SRDS_PLLCR0_RFCK_SEL_156_25; break; case 2: /* 25:1 */ rfck_sel = SRDS_PLLCR0_RFCK_SEL_125; break; default: printf("SERDES: bad SRDS_RATIO_B2 %d\n", srds_ratio_b2); return; } clrsetbits_be32(&regs->bank[FSL_SRDS_BANK_3].pllcr0, SRDS_PLLCR0_RFCK_SEL_MASK, rfck_sel); clrsetbits_be32(&regs->bank[FSL_SRDS_BANK_3].pllcr0, SRDS_PLLCR0_FRATE_SEL_MASK, SRDS_PLLCR0_FRATE_SEL_6_25); break; } enable_bank(gur, FSL_SRDS_BANK_3); } #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A005 /* * If PCIe is not selected as a protocol for any lanes driven by a given PLL, * that PLL should have SRDSBnPLLCR1[PLLBW_SEL] = 0. */ static void p4080_erratum_serdes_a005(serdes_corenet_t *regs, unsigned int cfg) { enum srds_prtcl device; switch (cfg) { case 0x13: case 0x16: /* * If SRDS_PRTCL = 0x13 or 0x16, set SRDSB1PLLCR1[PLLBW_SEL] * to 0. */ clrbits_be32(&regs->bank[FSL_SRDS_BANK_1].pllcr1, SRDS_PLLCR1_PLL_BWSEL); break; case 0x19: /* * If SRDS_PRTCL = 0x19, set SRDSB1PLLCR1[PLLBW_SEL] to 0 and * SRDSB3PLLCR1[PLLBW_SEL] to 1. */ clrbits_be32(&regs->bank[FSL_SRDS_BANK_1].pllcr1, SRDS_PLLCR1_PLL_BWSEL); setbits_be32(&regs->bank[FSL_SRDS_BANK_3].pllcr1, SRDS_PLLCR1_PLL_BWSEL); break; } /* * Set SRDSBnPLLCR1[PLLBW_SEL] to 0 for each bank that selects XAUI * before XAUI is initialized. */ for (device = XAUI_FM1; device <= XAUI_FM2; device++) { if (is_serdes_configured(device)) { int bank = serdes_get_bank_by_device(cfg, device); clrbits_be32(&regs->bank[bank].pllcr1, SRDS_PLLCR1_PLL_BWSEL); } } } #endif /* * Wait for the RSTDONE bit to get set, or a one-second timeout. */ static void wait_for_rstdone(unsigned int bank) { serdes_corenet_t *srds_regs = (void *)CONFIG_SYS_FSL_CORENET_SERDES_ADDR; unsigned long long end_tick; u32 rstctl; /* wait for reset complete or 1-second timeout */ end_tick = usec2ticks(1000000) + get_ticks(); do { rstctl = in_be32(&srds_regs->bank[bank].rstctl); if (rstctl & SRDS_RSTCTL_RSTDONE) break; } while (end_tick > get_ticks()); if (!(rstctl & SRDS_RSTCTL_RSTDONE)) printf("SERDES: timeout resetting bank %u\n", bank + 1); } static void __soc_serdes_init(void) { /* Allow for SoC-specific initialization in <SOC>_serdes.c */ }; void soc_serdes_init(void) __attribute__((weak, alias("__soc_serdes_init"))); void fsl_serdes_init(void) { ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); int cfg; serdes_corenet_t *srds_regs; #ifdef CONFIG_PPC_P5040 serdes_corenet_t *srds2_regs; #endif int lane, bank, idx; int have_bank[SRDS_MAX_BANK] = {}; #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 u32 serdes8_devdisr = 0; u32 serdes8_devdisr2 = 0; char srds_lpd_opt[16]; const char *srds_lpd_arg; size_t arglen; #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A001 int need_serdes_a001; /* true == need work-around for SERDES A001 */ #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 char buffer[HWCONFIG_BUFFER_SIZE]; char *buf = NULL; /* * Extract hwconfig from environment since we have not properly setup * the environment but need it for ddr config params */ if (getenv_f("hwconfig", buffer, sizeof(buffer)) > 0) buf = buffer; #endif /* Is serdes enabled at all? */ if (!(in_be32(&gur->rcwsr[5]) & FSL_CORENET_RCWSR5_SRDS_EN)) return; srds_regs = (void *)(CONFIG_SYS_FSL_CORENET_SERDES_ADDR); cfg = (in_be32(&gur->rcwsr[4]) & FSL_CORENET_RCWSR4_SRDS_PRTCL) >> 26; debug("Using SERDES configuration 0x%x, lane settings:\n", cfg); if (!is_serdes_prtcl_valid(cfg)) { printf("SERDES[PRTCL] = 0x%x is not valid\n", cfg); return; } #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 /* * Display a warning if banks two and three are not disabled in the RCW, * since our work-around for SERDES8 depends on these banks being * disabled at power-on. */ #define B2_B3 (FSL_CORENET_RCWSRn_SRDS_LPD_B2 | FSL_CORENET_RCWSRn_SRDS_LPD_B3) if ((in_be32(&gur->rcwsr[5]) & B2_B3) != B2_B3) { printf("Warning: SERDES8 requires banks two and " "three to be disabled in the RCW\n"); } /* * Store the values of the fsl_srds_lpd_b2 and fsl_srds_lpd_b3 * hwconfig options into the srds_lpd_b[] array. See README.p4080ds * for a description of these options. */ for (bank = 1; bank < ARRAY_SIZE(srds_lpd_b); bank++) { sprintf(srds_lpd_opt, "fsl_srds_lpd_b%u", bank + 1); srds_lpd_arg = hwconfig_subarg_f("serdes", srds_lpd_opt, &arglen, buf); if (srds_lpd_arg) srds_lpd_b[bank] = simple_strtoul(srds_lpd_arg, NULL, 0) & 0xf; } if ((cfg == 0xf) || (cfg == 0x10)) { /* * For SERDES protocols 0xF and 0x10, force bank 3 to be * disabled, because it is not supported. */ srds_lpd_b[FSL_SRDS_BANK_3] = 0xF; } #endif /* Look for banks with all lanes disabled, and power down the bank. */ for (lane = 0; lane < SRDS_MAX_LANES; lane++) { enum srds_prtcl lane_prtcl = serdes_get_prtcl(cfg, lane); if (serdes_lane_enabled(lane)) { have_bank[serdes_get_bank_by_lane(lane)] = 1; serdes_prtcl_map |= (1 << lane_prtcl); } } #ifdef CONFIG_PPC_P5040 /* * Lanes on bank 4 on P5040 are commented-out, but for some SERDES * protocols, these lanes are routed to SATA. We use serdes_prtcl_map * to decide whether a protocol is supported on a given lane, so SATA * will be identified as not supported, and therefore not initialized. * So for protocols which use SATA on bank4, we add SATA support in * serdes_prtcl_map. */ switch (cfg) { case 0x0: case 0x1: case 0x2: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7: serdes_prtcl_map |= 1 << SATA1 | 1 << SATA2; break; default: srds2_regs = (void *)CONFIG_SYS_FSL_CORENET_SERDES2_ADDR; /* We don't need bank 4, so power it down */ setbits_be32(&srds2_regs->bank[0].rstctl, SRDS_RSTCTL_SDPD); } #endif soc_serdes_init(); #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 /* * Bank two uses the clock from bank three, so if bank two is enabled, * then bank three must also be enabled. */ if (have_bank[FSL_SRDS_BANK_2]) have_bank[FSL_SRDS_BANK_3] = 1; #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A001 /* * The work-aroud for erratum SERDES-A001 is needed only if bank two * is disabled and bank three is enabled. The converse is also true, * but SERDES8 ensures that bank 3 is always enabled if bank 2 is * enabled, so there's no point in complicating the code to handle * that situation. */ need_serdes_a001 = !have_bank[FSL_SRDS_BANK_2] && have_bank[FSL_SRDS_BANK_3]; #endif /* Power down the banks we're not interested in */ for (bank = 0; bank < SRDS_MAX_BANK; bank++) { if (!have_bank[bank]) { printf("SERDES: bank %d disabled\n", bank + 1); #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A001 /* * Erratum SERDES-A001 says bank two needs to be powered * down after bank three is powered up, so don't power * down bank two here. */ if (!need_serdes_a001 || (bank != FSL_SRDS_BANK_2)) setbits_be32(&srds_regs->bank[bank].rstctl, SRDS_RSTCTL_SDPD); #else setbits_be32(&srds_regs->bank[bank].rstctl, SRDS_RSTCTL_SDPD); #endif } } #ifdef CONFIG_SYS_FSL_ERRATUM_A004699 /* * To avoid the situation that resulted in the P4080 erratum * SERDES-8, a given SerDes bank will use the PLLs from the previous * bank if one of the PLL frequencies is a multiple of the other. For * instance, if bank 3 is running at 2.5GHz and bank 2 is at 1.25GHz, * then bank 3 will use bank 2's PLL. P5040 Erratum A-004699 says * that, in this situation, lane synchronization is not initiated. So * when we detect a bank with a "borrowed" PLL, we have to manually * initiate lane synchronization. */ for (bank = FSL_SRDS_BANK_2; bank <= FSL_SRDS_BANK_3; bank++) { /* Determine the first lane for this bank */ unsigned int lane; for (lane = 0; lane < SRDS_MAX_LANES; lane++) if (lanes[lane].bank == bank) break; idx = lanes[lane].idx; /* * Check if the PLL for the bank is borrowed. The UOTHL * bit of the first lane will tell us that. */ if (in_be32(&srds_regs->lane[idx].gcr0) & SRDS_GCR0_UOTHL) { /* Manually start lane synchronization */ setbits_be32(&srds_regs->bank[bank].pllcr0, SRDS_PLLCR0_PVCOCNT_EN); } } #endif #if defined(CONFIG_SYS_P4080_ERRATUM_SERDES8) || defined (CONFIG_SYS_P4080_ERRATUM_SERDES9) for (lane = 0; lane < SRDS_MAX_LANES; lane++) { enum srds_prtcl lane_prtcl; idx = serdes_get_lane_idx(lane); lane_prtcl = serdes_get_prtcl(cfg, lane); #ifdef DEBUG switch (lane) { case 0: puts("Bank1: "); break; case 10: puts("\nBank2: "); break; case 14: puts("\nBank3: "); break; default: break; } printf("%s ", serdes_prtcl_str[lane_prtcl]); #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES9 /* * Set BnTTLCRy0[FLT_SEL] = 011011 and set BnTTLCRy0[31] = 1 * for each of the SerDes lanes selected as SGMII, XAUI, SRIO, * or AURORA before the device is initialized. * * Note that this part of the SERDES-9 work-around is * redundant if the work-around for A-4580 has already been * applied via PBI. */ switch (lane_prtcl) { case SGMII_FM1_DTSEC1: case SGMII_FM1_DTSEC2: case SGMII_FM1_DTSEC3: case SGMII_FM1_DTSEC4: case SGMII_FM2_DTSEC1: case SGMII_FM2_DTSEC2: case SGMII_FM2_DTSEC3: case SGMII_FM2_DTSEC4: case SGMII_FM2_DTSEC5: case XAUI_FM1: case XAUI_FM2: case SRIO1: case SRIO2: case AURORA: out_be32(&srds_regs->lane[idx].ttlcr0, SRDS_TTLCR0_FLT_SEL_KFR_26 | SRDS_TTLCR0_FLT_SEL_KPH_28 | SRDS_TTLCR0_FLT_SEL_750PPM | SRDS_TTLCR0_FREQOVD_EN); break; default: break; } #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 switch (lane_prtcl) { case PCIE1: case PCIE2: case PCIE3: serdes8_devdisr |= FSL_CORENET_DEVDISR_PCIE1 >> (lane_prtcl - PCIE1); break; case SRIO1: case SRIO2: serdes8_devdisr |= FSL_CORENET_DEVDISR_SRIO1 >> (lane_prtcl - SRIO1); break; case SGMII_FM1_DTSEC1: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM1 | FSL_CORENET_DEVDISR2_DTSEC1_1; break; case SGMII_FM1_DTSEC2: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM1 | FSL_CORENET_DEVDISR2_DTSEC1_2; break; case SGMII_FM1_DTSEC3: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM1 | FSL_CORENET_DEVDISR2_DTSEC1_3; break; case SGMII_FM1_DTSEC4: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM1 | FSL_CORENET_DEVDISR2_DTSEC1_4; break; case SGMII_FM2_DTSEC1: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_DTSEC2_1; break; case SGMII_FM2_DTSEC2: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_DTSEC2_2; break; case SGMII_FM2_DTSEC3: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_DTSEC2_3; break; case SGMII_FM2_DTSEC4: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_DTSEC2_4; break; case SGMII_FM2_DTSEC5: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_DTSEC2_5; break; case XAUI_FM1: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM1 | FSL_CORENET_DEVDISR2_10GEC1; break; case XAUI_FM2: serdes8_devdisr2 |= FSL_CORENET_DEVDISR2_FM2 | FSL_CORENET_DEVDISR2_10GEC2; break; case AURORA: break; default: break; } #endif } #endif #ifdef DEBUG puts("\n"); #endif #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A005 p4080_erratum_serdes_a005(srds_regs, cfg); #endif for (idx = 0; idx < SRDS_MAX_BANK; idx++) { bank = idx; #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 /* * Change bank init order to 0, 2, 1, so that the third bank's * PLL is established before we start the second bank. The * second bank uses the third bank's PLL. */ if (idx == 1) bank = FSL_SRDS_BANK_3; else if (idx == 2) bank = FSL_SRDS_BANK_2; #endif /* Skip disabled banks */ if (!have_bank[bank]) continue; #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES8 if (idx == 1) { /* * Re-enable devices on banks two and three that were * disabled by the RCW, and then enable bank three. The * devices need to be enabled before either bank is * powered up. */ p4080_erratum_serdes8(srds_regs, gur, serdes8_devdisr, serdes8_devdisr2, cfg); } else if (idx == 2) { /* Enable bank two now that bank three is enabled. */ enable_bank(gur, FSL_SRDS_BANK_2); } #endif wait_for_rstdone(bank); } #ifdef CONFIG_SYS_P4080_ERRATUM_SERDES_A001 if (need_serdes_a001) { /* Bank 3 has been enabled, so now we can disable bank 2 */ setbits_be32(&srds_regs->bank[FSL_SRDS_BANK_2].rstctl, SRDS_RSTCTL_SDPD); } #endif }
luckyboy/uboot
u-boot-2013.10/arch/powerpc/cpu/mpc85xx/fsl_corenet_serdes.c
C
gpl-2.0
23,192
<?php /** * ILS driver test * * PHP version 5 * * Copyright (C) Villanova University 2011. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package Tests * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://www.vufind.org Main Page */ namespace VuFindTest\ILS\Driver; use VuFind\ILS\Driver\XCNCIP; /** * ILS driver test * * @category VuFind2 * @package Tests * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://www.vufind.org Main Page */ class XCNCIPTest extends \VuFindTest\Unit\ILSDriverTestCase { /** * Constructor */ public function __construct() { $this->driver = new XCNCIP(); } }
PetraZabickova/VuFind-2.x
module/VuFind/tests/unit-tests/src/VuFindTest/ILS/Driver/XCNCIPTest.php
PHP
gpl-2.0
1,475
/*MT* MediaTomb - http://www.mediatomb.cc/ subscription_request.cc - this file is part of MediaTomb. Copyright (C) 2005 Gena Batyan <[email protected]>, Sergey 'Jin' Bostandzhyan <[email protected]> Copyright (C) 2006-2010 Gena Batyan <[email protected]>, Sergey 'Jin' Bostandzhyan <[email protected]>, Leonhard Wimmer <[email protected]> MediaTomb is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. MediaTomb is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License version 2 along with MediaTomb; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. $Id$ */ /// \file subscription_request.cc #ifdef HAVE_CONFIG_H #include "autoconfig.h" #endif #include "mxml/mxml.h" #include "subscription_request.h" using namespace zmm; using namespace mxml; SubscriptionRequest::SubscriptionRequest(Upnp_Subscription_Request *upnp_request) : Object() { this->upnp_request = upnp_request; serviceID = upnp_request->ServiceId; UDN = upnp_request->UDN; sID = upnp_request->Sid; } String SubscriptionRequest::getServiceID() { return serviceID; } String SubscriptionRequest::getUDN() { return UDN; } String SubscriptionRequest::getSubscriptionID() { return sID; }
jonabbey/mediatomb
src/subscription_request.cc
C++
gpl-2.0
1,771
/* * Copyright (c) 2003, 2007-11 Matteo Frigo * Copyright (c) 2003, 2007-11 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sat Apr 28 11:04:22 EDT 2012 */ #include "codelet-rdft.h" #ifdef HAVE_FMA /* Generated by: ../../../genfft/gen_r2cb.native -fma -reorder-insns -schedule-for-pipeline -compact -variables 4 -pipeline-latency 4 -sign 1 -n 64 -name r2cbIII_64 -dft-III -include r2cbIII.h */ /* * This function contains 434 FP additions, 260 FP multiplications, * (or, 238 additions, 64 multiplications, 196 fused multiply/add), * 165 stack variables, 36 constants, and 128 memory accesses */ #include "r2cbIII.h" static void r2cbIII_64(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP357805721, +0.357805721314524104672487743774474392487532769); DK(KP1_883088130, +1.883088130366041556825018805199004714371179592); DK(KP472964775, +0.472964775891319928124438237972992463904131113); DK(KP1_807978586, +1.807978586246886663172400594461074097420264050); DK(KP049126849, +0.049126849769467254105343321271313617079695752); DK(KP1_997590912, +1.997590912410344785429543209518201388886407229); DK(KP906347169, +0.906347169019147157946142717268914412664134293); DK(KP1_481902250, +1.481902250709918182351233794990325459457910619); DK(KP980785280, +0.980785280403230449126182236134239036973933731); DK(KP250486960, +0.250486960191305461595702160124721208578685568); DK(KP1_940062506, +1.940062506389087985207968414572200502913731924); DK(KP599376933, +0.599376933681923766271389869014404232837890546); DK(KP1_715457220, +1.715457220000544139804539968569540274084981599); DK(KP148335987, +0.148335987538347428753676511486911367000625355); DK(KP1_978353019, +1.978353019929561946903347476032486127967379067); DK(KP741650546, +0.741650546272035369581266691172079863842265220); DK(KP1_606415062, +1.606415062961289819613353025926283847759138854); DK(KP831469612, +0.831469612302545237078788377617905756738560812); DK(KP303346683, +0.303346683607342391675883946941299872384187453); DK(KP1_913880671, +1.913880671464417729871595773960539938965698411); DK(KP534511135, +0.534511135950791641089685961295362908582039528); DK(KP1_763842528, +1.763842528696710059425513727320776699016885241); DK(KP098491403, +0.098491403357164253077197521291327432293052451); DK(KP1_990369453, +1.990369453344393772489673906218959843150949737); DK(KP820678790, +0.820678790828660330972281985331011598767386482); DK(KP1_546020906, +1.546020906725473921621813219516939601942082586); DK(KP923879532, +0.923879532511286756128183189396788286822416626); DK(KP198912367, +0.198912367379658006911597622644676228597850501); DK(KP1_961570560, +1.961570560806460898252364472268478073947867462); DK(KP668178637, +0.668178637919298919997757686523080761552472251); DK(KP1_662939224, +1.662939224605090474157576755235811513477121624); DK(KP1_847759065, +1.847759065022573512256366378793576573644833252); DK(KP1_414213562, +1.414213562373095048801688724209698078569671875); DK(KP2_000000000, +2.000000000000000000000000000000000000000000000); DK(KP707106781, +0.707106781186547524400844362104849039284835938); DK(KP414213562, +0.414213562373095048801688724209698078569671875); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(rs), MAKE_VOLATILE_STRIDE(csr), MAKE_VOLATILE_STRIDE(csi)) { E T43, T4b, T49, T4e, T3T, T46, T40, T4a; { E T3t, T15, T2E, T3U, T6b, Tf, T6Q, T6u, T5J, T4L, T3V, T1g, T5U, T5q, T3u; E T2H, T6v, Tu, T5r, T4V, T6R, T6e, T2K, T1s, T2J, T1D, T3X, T3B, T5s, T4Q; E T3Y, T3y, T6g, TK, T5M, T57, T6N, T6j, T35, T1W, T34, T25, T4i, T3J, T5N; E T52, T4j, T3G, T6l, TZ, T3L, T5P, T5i, T6M, T6o, T3M, T38, T2n, T37, T2w; E T4l, T3Q, T5Q, T5d; { E T3x, T3w, T3E, T3F; { E T5p, T5o, T2G, T2F; { E T11, T3, T5m, T2D, T2A, T6, T5n, T14, Tb, T16, Ta, T4I, T19, Tc, T1c; E T1d; { E T4, T5, T12, T13; { E T1, T2, T2B, T2C; T1 = Cr[0]; T2 = Cr[WS(csr, 31)]; T2B = Ci[0]; T2C = Ci[WS(csi, 31)]; T4 = Cr[WS(csr, 16)]; T11 = T1 - T2; T3 = T1 + T2; T5m = T2C - T2B; T2D = T2B + T2C; T5 = Cr[WS(csr, 15)]; T12 = Ci[WS(csi, 16)]; T13 = Ci[WS(csi, 15)]; } { E T8, T9, T17, T18; T8 = Cr[WS(csr, 8)]; T2A = T4 - T5; T6 = T4 + T5; T5n = T13 - T12; T14 = T12 + T13; T9 = Cr[WS(csr, 23)]; T17 = Ci[WS(csi, 8)]; T18 = Ci[WS(csi, 23)]; Tb = Cr[WS(csr, 7)]; T16 = T8 - T9; Ta = T8 + T9; T4I = T18 - T17; T19 = T17 + T18; Tc = Cr[WS(csr, 24)]; T1c = Ci[WS(csi, 7)]; T1d = Ci[WS(csi, 24)]; } } { E T1b, T4J, T1e, T4H, T7, Te, Td; T3t = T11 + T14; T15 = T11 - T14; T1b = Tb - Tc; Td = Tb + Tc; T4J = T1c - T1d; T1e = T1c + T1d; T2E = T2A + T2D; T3U = T2A - T2D; T4H = T3 - T6; T7 = T3 + T6; Te = Ta + Td; T5p = Ta - Td; { E T4K, T6s, T6t, T1a, T1f; T5o = T5m - T5n; T6s = T5n + T5m; T6t = T4I + T4J; T4K = T4I - T4J; T6b = T7 - Te; Tf = T7 + Te; T6Q = T6t + T6s; T6u = T6s - T6t; T2G = T16 + T19; T1a = T16 - T19; T1f = T1b - T1e; T2F = T1b + T1e; T5J = T4H - T4K; T4L = T4H + T4K; T3V = T1a - T1f; T1g = T1a + T1f; } } } { E T1i, Ti, T4O, T1q, T1n, Tl, T4N, T1l, Tq, T1t, Tp, T4T, T1A, Tr, T1u; E T1v; { E Tj, Tk, T1j, T1k; { E Tg, Th, T1o, T1p; Tg = Cr[WS(csr, 4)]; T5U = T5p + T5o; T5q = T5o - T5p; T3u = T2G + T2F; T2H = T2F - T2G; Th = Cr[WS(csr, 27)]; T1o = Ci[WS(csi, 4)]; T1p = Ci[WS(csi, 27)]; Tj = Cr[WS(csr, 20)]; T1i = Tg - Th; Ti = Tg + Th; T4O = T1p - T1o; T1q = T1o + T1p; Tk = Cr[WS(csr, 11)]; T1j = Ci[WS(csi, 20)]; T1k = Ci[WS(csi, 11)]; } { E Tn, To, T1y, T1z; Tn = Cr[WS(csr, 3)]; T1n = Tj - Tk; Tl = Tj + Tk; T4N = T1k - T1j; T1l = T1j + T1k; To = Cr[WS(csr, 28)]; T1y = Ci[WS(csi, 3)]; T1z = Ci[WS(csi, 28)]; Tq = Cr[WS(csr, 12)]; T1t = Tn - To; Tp = Tn + To; T4T = T1y - T1z; T1A = T1y + T1z; Tr = Cr[WS(csr, 19)]; T1u = Ci[WS(csi, 12)]; T1v = Ci[WS(csi, 19)]; } } { E T4M, T1B, T1w, T4P, T1m, T1r, Tm, Ts, T4S; T4M = Ti - Tl; Tm = Ti + Tl; T1B = Tq - Tr; Ts = Tq + Tr; T4S = T1v - T1u; T1w = T1u + T1v; { E T6c, Tt, T4R, T6d, T4U; T6c = T4N + T4O; T4P = T4N - T4O; Tt = Tp + Ts; T4R = Tp - Ts; T6d = T4S + T4T; T4U = T4S - T4T; T3x = T1i + T1l; T1m = T1i - T1l; T6v = Tm - Tt; Tu = Tm + Tt; T5r = T4R - T4U; T4V = T4R + T4U; T6R = T6c + T6d; T6e = T6c - T6d; T1r = T1n + T1q; T3w = T1n - T1q; } { E T3A, T3z, T1x, T1C; T3A = T1t + T1w; T1x = T1t - T1w; T1C = T1A - T1B; T3z = T1B + T1A; T2K = FMA(KP414213562, T1m, T1r); T1s = FNMS(KP414213562, T1r, T1m); T2J = FMA(KP414213562, T1x, T1C); T1D = FNMS(KP414213562, T1C, T1x); T3X = FMA(KP414213562, T3z, T3A); T3B = FNMS(KP414213562, T3A, T3z); T5s = T4M + T4P; T4Q = T4M - T4P; } } } } { E T1G, Ty, T54, T20, T1X, TB, T53, T1J, TI, T4Z, T1L, TF, T22, T1U, T50; E T1O; { E T1Y, T1Z, Tz, TA, Tw, Tx, T1H, T1I; Tw = Cr[WS(csr, 2)]; Tx = Cr[WS(csr, 29)]; T1Y = Ci[WS(csi, 2)]; T3Y = FNMS(KP414213562, T3w, T3x); T3y = FMA(KP414213562, T3x, T3w); T1G = Tw - Tx; Ty = Tw + Tx; T1Z = Ci[WS(csi, 29)]; Tz = Cr[WS(csr, 18)]; TA = Cr[WS(csr, 13)]; T1H = Ci[WS(csi, 18)]; T54 = T1Y - T1Z; T20 = T1Y + T1Z; T1X = Tz - TA; TB = Tz + TA; T1I = Ci[WS(csi, 13)]; { E T1R, T1Q, T1S, TG, TH; TG = Cr[WS(csr, 5)]; TH = Cr[WS(csr, 26)]; T1R = Ci[WS(csi, 5)]; T53 = T1H - T1I; T1J = T1H + T1I; T1Q = TG - TH; TI = TG + TH; T1S = Ci[WS(csi, 26)]; { E T1M, T1N, TD, TE, T1T; TD = Cr[WS(csr, 10)]; TE = Cr[WS(csr, 21)]; T1T = T1R + T1S; T4Z = T1S - T1R; T1M = Ci[WS(csi, 10)]; T1L = TD - TE; TF = TD + TE; T1N = Ci[WS(csi, 21)]; T22 = T1Q + T1T; T1U = T1Q - T1T; T50 = T1M - T1N; T1O = T1M + T1N; } } } { E T4Y, T23, T51, T1K, T1V, T3I, T3H, T21, T24; { E T56, T1P, T6h, T55, TC, TJ, T6i; T4Y = Ty - TB; TC = Ty + TB; TJ = TF + TI; T56 = TF - TI; T1P = T1L - T1O; T23 = T1L + T1O; T6h = T53 + T54; T55 = T53 - T54; T6g = TC - TJ; TK = TC + TJ; T6i = T50 + T4Z; T51 = T4Z - T50; T3E = T1G + T1J; T1K = T1G - T1J; T5M = T56 + T55; T57 = T55 - T56; T6N = T6i + T6h; T6j = T6h - T6i; T1V = T1P + T1U; T3I = T1P - T1U; } T3H = T1X - T20; T21 = T1X + T20; T24 = T22 - T23; T3F = T23 + T22; T35 = FNMS(KP707106781, T1V, T1K); T1W = FMA(KP707106781, T1V, T1K); T34 = FMA(KP707106781, T24, T21); T25 = FNMS(KP707106781, T24, T21); T4i = FMA(KP707106781, T3I, T3H); T3J = FNMS(KP707106781, T3I, T3H); T5N = T4Y - T51; T52 = T4Y + T51; } } { E T27, TN, T5f, T2q, T2r, TQ, T5e, T2a, TX, T5a, T2c, TU, T2t, T2l, T5b; E T2f; { E T2o, T2p, TO, TP, TL, TM, T28, T29; TL = Cr[WS(csr, 1)]; TM = Cr[WS(csr, 30)]; T2o = Ci[WS(csi, 1)]; T4j = FMA(KP707106781, T3F, T3E); T3G = FNMS(KP707106781, T3F, T3E); T27 = TL - TM; TN = TL + TM; T2p = Ci[WS(csi, 30)]; TO = Cr[WS(csr, 14)]; TP = Cr[WS(csr, 17)]; T28 = Ci[WS(csi, 14)]; T5f = T2p - T2o; T2q = T2o + T2p; T2r = TO - TP; TQ = TO + TP; T29 = Ci[WS(csi, 17)]; { E T2i, T2h, T2j, TV, TW; TV = Cr[WS(csr, 9)]; TW = Cr[WS(csr, 22)]; T2i = Ci[WS(csi, 9)]; T5e = T28 - T29; T2a = T28 + T29; T2h = TV - TW; TX = TV + TW; T2j = Ci[WS(csi, 22)]; { E T2d, T2e, TS, TT, T2k; TS = Cr[WS(csr, 6)]; TT = Cr[WS(csr, 25)]; T2k = T2i + T2j; T5a = T2j - T2i; T2d = Ci[WS(csi, 6)]; T2c = TS - TT; TU = TS + TT; T2e = Ci[WS(csi, 25)]; T2t = T2h + T2k; T2l = T2h - T2k; T5b = T2d - T2e; T2f = T2d + T2e; } } } { E T59, T2u, T5c, T2b, T2m, T3P, T3O, T2s, T2v; { E T5h, T2g, T6m, T5g, TR, TY, T6n; T59 = TN - TQ; TR = TN + TQ; TY = TU + TX; T5h = TU - TX; T2g = T2c - T2f; T2u = T2c + T2f; T6m = T5e + T5f; T5g = T5e - T5f; T6l = TR - TY; TZ = TR + TY; T6n = T5b + T5a; T5c = T5a - T5b; T3L = T27 + T2a; T2b = T27 - T2a; T5P = T5h + T5g; T5i = T5g - T5h; T6M = T6n + T6m; T6o = T6m - T6n; T2m = T2g + T2l; T3P = T2g - T2l; } T3O = T2r + T2q; T2s = T2q - T2r; T2v = T2t - T2u; T3M = T2u + T2t; T38 = FNMS(KP707106781, T2m, T2b); T2n = FMA(KP707106781, T2m, T2b); T37 = FNMS(KP707106781, T2v, T2s); T2w = FMA(KP707106781, T2v, T2s); T4l = FMA(KP707106781, T3P, T3O); T3Q = FNMS(KP707106781, T3P, T3O); T5Q = T59 - T5c; T5d = T59 + T5c; } } } { E T4m, T3N, T5t, T5L, T63, T4W, T5Y, T5X, T66, T5W, T67, T5S; { E T6T, T6S, T6W, T6P; { E T6L, T6O, T6Y, T6X, T6Z, Tv, T10, T70; T6L = Tf - Tu; Tv = Tf + Tu; T10 = TK + TZ; T6T = TK - TZ; T6O = T6M - T6N; T6Y = T6N + T6M; T4m = FMA(KP707106781, T3M, T3L); T3N = FNMS(KP707106781, T3M, T3L); T6X = Tv - T10; T6S = T6Q - T6R; T6Z = T6R + T6Q; R0[0] = KP2_000000000 * (Tv + T10); R0[WS(rs, 16)] = KP2_000000000 * (T6Z - T6Y); T70 = T6Y + T6Z; T6W = T6L - T6O; T6P = T6L + T6O; R0[WS(rs, 24)] = KP1_414213562 * (T70 - T6X); R0[WS(rs, 8)] = KP1_414213562 * (T6X + T70); } { E T6D, T6f, T6w, T6G, T6p, T6x, T6y, T6k, T6V, T6U; T6D = T6b - T6e; T6f = T6b + T6e; T6w = T6u - T6v; T6G = T6v + T6u; T6V = T6T + T6S; T6U = T6S - T6T; T6p = T6l + T6o; T6x = T6l - T6o; R0[WS(rs, 12)] = KP1_847759065 * (FMA(KP414213562, T6W, T6V)); R0[WS(rs, 28)] = -(KP1_847759065 * (FNMS(KP414213562, T6V, T6W))); R0[WS(rs, 20)] = KP1_847759065 * (FNMS(KP414213562, T6P, T6U)); R0[WS(rs, 4)] = KP1_847759065 * (FMA(KP414213562, T6U, T6P)); T6y = T6g + T6j; T6k = T6g - T6j; { E T5V, T5K, T5O, T5R; T5t = T5r - T5s; T5K = T5s + T5r; { E T6E, T6z, T6H, T6q; T6E = T6y + T6x; T6z = T6x - T6y; T6H = T6k - T6p; T6q = T6k + T6p; { E T6F, T6K, T6B, T6A; T6F = FNMS(KP707106781, T6E, T6D); T6K = FMA(KP707106781, T6E, T6D); T6B = FNMS(KP707106781, T6z, T6w); T6A = FMA(KP707106781, T6z, T6w); { E T6I, T6J, T6C, T6r; T6I = FNMS(KP707106781, T6H, T6G); T6J = FMA(KP707106781, T6H, T6G); T6C = FNMS(KP707106781, T6q, T6f); T6r = FMA(KP707106781, T6q, T6f); R0[WS(rs, 22)] = KP1_662939224 * (FNMS(KP668178637, T6F, T6I)); R0[WS(rs, 6)] = KP1_662939224 * (FMA(KP668178637, T6I, T6F)); R0[WS(rs, 30)] = -(KP1_961570560 * (FNMS(KP198912367, T6J, T6K))); R0[WS(rs, 14)] = KP1_961570560 * (FMA(KP198912367, T6K, T6J)); R0[WS(rs, 26)] = -(KP1_662939224 * (FNMS(KP668178637, T6B, T6C))); R0[WS(rs, 10)] = KP1_662939224 * (FMA(KP668178637, T6C, T6B)); R0[WS(rs, 18)] = KP1_961570560 * (FNMS(KP198912367, T6r, T6A)); R0[WS(rs, 2)] = KP1_961570560 * (FMA(KP198912367, T6A, T6r)); T5L = FNMS(KP707106781, T5K, T5J); T63 = FMA(KP707106781, T5K, T5J); } } } T5V = T4Q - T4V; T4W = T4Q + T4V; T5Y = FNMS(KP414213562, T5M, T5N); T5O = FMA(KP414213562, T5N, T5M); T5R = FNMS(KP414213562, T5Q, T5P); T5X = FMA(KP414213562, T5P, T5Q); T66 = FMA(KP707106781, T5V, T5U); T5W = FNMS(KP707106781, T5V, T5U); T67 = T5O + T5R; T5S = T5O - T5R; } } } { E T1h, T2L, T2I, T3h, T3p, T1E, T3n, T3s, T3b, T3k, T3e, T3o; { E T4X, T5B, T5v, T5w, T5E, T5u, T5F, T5k, T58, T5j; { E T68, T69, T62, T5T, T64, T5Z; T68 = FNMS(KP923879532, T67, T66); T69 = FMA(KP923879532, T67, T66); T62 = FNMS(KP923879532, T5S, T5L); T5T = FMA(KP923879532, T5S, T5L); T64 = T5Y + T5X; T5Z = T5X - T5Y; T4X = FMA(KP707106781, T4W, T4L); T5B = FNMS(KP707106781, T4W, T4L); { E T65, T6a, T61, T60; T65 = FNMS(KP923879532, T64, T63); T6a = FMA(KP923879532, T64, T63); T61 = FNMS(KP923879532, T5Z, T5W); T60 = FMA(KP923879532, T5Z, T5W); R0[WS(rs, 23)] = KP1_546020906 * (FNMS(KP820678790, T65, T68)); R0[WS(rs, 7)] = KP1_546020906 * (FMA(KP820678790, T68, T65)); R0[WS(rs, 31)] = -(KP1_990369453 * (FNMS(KP098491403, T69, T6a))); R0[WS(rs, 15)] = KP1_990369453 * (FMA(KP098491403, T6a, T69)); R0[WS(rs, 27)] = -(KP1_763842528 * (FNMS(KP534511135, T61, T62))); R0[WS(rs, 11)] = KP1_763842528 * (FMA(KP534511135, T62, T61)); R0[WS(rs, 19)] = KP1_913880671 * (FNMS(KP303346683, T5T, T60)); R0[WS(rs, 3)] = KP1_913880671 * (FMA(KP303346683, T60, T5T)); } } T5v = FNMS(KP414213562, T52, T57); T58 = FMA(KP414213562, T57, T52); T5j = FNMS(KP414213562, T5i, T5d); T5w = FMA(KP414213562, T5d, T5i); T5E = FNMS(KP707106781, T5t, T5q); T5u = FMA(KP707106781, T5t, T5q); T5F = T58 - T5j; T5k = T58 + T5j; { E T3l, T33, T3c, T3m, T3a, T3d; { E T39, T3f, T3g, T36; { E T31, T5G, T5H, T5A, T5l, T5C, T5x, T32; T1h = FMA(KP707106781, T1g, T15); T31 = FNMS(KP707106781, T1g, T15); T5G = FNMS(KP923879532, T5F, T5E); T5H = FMA(KP923879532, T5F, T5E); T5A = FNMS(KP923879532, T5k, T4X); T5l = FMA(KP923879532, T5k, T4X); T5C = T5w - T5v; T5x = T5v + T5w; T32 = T2K + T2J; T2L = T2J - T2K; T39 = FNMS(KP668178637, T38, T37); T3f = FMA(KP668178637, T37, T38); { E T5D, T5I, T5z, T5y; T5D = FNMS(KP923879532, T5C, T5B); T5I = FMA(KP923879532, T5C, T5B); T5z = FNMS(KP923879532, T5x, T5u); T5y = FMA(KP923879532, T5x, T5u); T3l = FMA(KP923879532, T32, T31); T33 = FNMS(KP923879532, T32, T31); R0[WS(rs, 21)] = KP1_763842528 * (FNMS(KP534511135, T5D, T5G)); R0[WS(rs, 5)] = KP1_763842528 * (FMA(KP534511135, T5G, T5D)); R0[WS(rs, 29)] = -(KP1_913880671 * (FNMS(KP303346683, T5H, T5I))); R0[WS(rs, 13)] = KP1_913880671 * (FMA(KP303346683, T5I, T5H)); R0[WS(rs, 25)] = -(KP1_546020906 * (FNMS(KP820678790, T5z, T5A))); R0[WS(rs, 9)] = KP1_546020906 * (FMA(KP820678790, T5A, T5z)); R0[WS(rs, 17)] = KP1_990369453 * (FNMS(KP098491403, T5l, T5y)); R0[WS(rs, 1)] = KP1_990369453 * (FMA(KP098491403, T5y, T5l)); T3g = FMA(KP668178637, T34, T35); T36 = FNMS(KP668178637, T35, T34); } } T2I = FNMS(KP707106781, T2H, T2E); T3c = FMA(KP707106781, T2H, T2E); T3m = T3g + T3f; T3h = T3f - T3g; T3p = T39 - T36; T3a = T36 + T39; T3d = T1s - T1D; T1E = T1s + T1D; } T3n = FNMS(KP831469612, T3m, T3l); T3s = FMA(KP831469612, T3m, T3l); T3b = FNMS(KP831469612, T3a, T33); T3k = FMA(KP831469612, T3a, T33); T3e = FMA(KP923879532, T3d, T3c); T3o = FNMS(KP923879532, T3d, T3c); } } { E T3v, T3Z, T3W, T4v, T4D, T3C, T4B, T4G, T4p, T4y, T4s, T4C; { E T4z, T4h, T4q, T4A, T4o, T4r; { E T4n, T4t, T4u, T4k, T4f, T4g; T3v = FNMS(KP707106781, T3u, T3t); T4f = FMA(KP707106781, T3u, T3t); T4g = T3Y + T3X; T3Z = T3X - T3Y; { E T3r, T3q, T3i, T3j; T3r = FNMS(KP831469612, T3p, T3o); T3q = FMA(KP831469612, T3p, T3o); T3i = FNMS(KP831469612, T3h, T3e); T3j = FMA(KP831469612, T3h, T3e); R1[WS(rs, 22)] = -(KP1_606415062 * (FMA(KP741650546, T3n, T3q))); R1[WS(rs, 6)] = KP1_606415062 * (FNMS(KP741650546, T3q, T3n)); R1[WS(rs, 30)] = -(KP1_978353019 * (FMA(KP148335987, T3r, T3s))); R1[WS(rs, 14)] = -(KP1_978353019 * (FNMS(KP148335987, T3s, T3r))); R1[WS(rs, 26)] = -(KP1_715457220 * (FMA(KP599376933, T3j, T3k))); R1[WS(rs, 10)] = -(KP1_715457220 * (FNMS(KP599376933, T3k, T3j))); R1[WS(rs, 18)] = -(KP1_940062506 * (FMA(KP250486960, T3b, T3i))); R1[WS(rs, 2)] = KP1_940062506 * (FNMS(KP250486960, T3i, T3b)); T4z = FMA(KP923879532, T4g, T4f); T4h = FNMS(KP923879532, T4g, T4f); } T4n = FNMS(KP198912367, T4m, T4l); T4t = FMA(KP198912367, T4l, T4m); T4u = FNMS(KP198912367, T4i, T4j); T4k = FMA(KP198912367, T4j, T4i); T3W = FNMS(KP707106781, T3V, T3U); T4q = FMA(KP707106781, T3V, T3U); T4A = T4u + T4t; T4v = T4t - T4u; T4D = T4k + T4n; T4o = T4k - T4n; T4r = T3y + T3B; T3C = T3y - T3B; } T4B = FNMS(KP980785280, T4A, T4z); T4G = FMA(KP980785280, T4A, T4z); T4p = FMA(KP980785280, T4o, T4h); T4y = FNMS(KP980785280, T4o, T4h); T4s = FNMS(KP923879532, T4r, T4q); T4C = FMA(KP923879532, T4r, T4q); } { E T2P, T2X, T2V, T30, T2z, T2S, T2M, T2W; { E T2T, T1F, T2U, T2y; { E T2x, T2N, T2O, T26; { E T4F, T4E, T4w, T4x; T4F = FMA(KP980785280, T4D, T4C); T4E = FNMS(KP980785280, T4D, T4C); T4w = FMA(KP980785280, T4v, T4s); T4x = FNMS(KP980785280, T4v, T4s); R1[WS(rs, 23)] = KP1_481902250 * (FNMS(KP906347169, T4B, T4E)); R1[WS(rs, 7)] = KP1_481902250 * (FMA(KP906347169, T4E, T4B)); R1[WS(rs, 31)] = -(KP1_997590912 * (FNMS(KP049126849, T4F, T4G))); R1[WS(rs, 15)] = KP1_997590912 * (FMA(KP049126849, T4G, T4F)); R1[WS(rs, 27)] = -(KP1_807978586 * (FNMS(KP472964775, T4x, T4y))); R1[WS(rs, 11)] = KP1_807978586 * (FMA(KP472964775, T4y, T4x)); R1[WS(rs, 19)] = KP1_883088130 * (FNMS(KP357805721, T4p, T4w)); R1[WS(rs, 3)] = KP1_883088130 * (FMA(KP357805721, T4w, T4p)); T2T = FNMS(KP923879532, T1E, T1h); T1F = FMA(KP923879532, T1E, T1h); } T2x = FNMS(KP198912367, T2w, T2n); T2N = FMA(KP198912367, T2n, T2w); T2O = FMA(KP198912367, T1W, T25); T26 = FNMS(KP198912367, T25, T1W); T2U = T2O + T2N; T2P = T2N - T2O; T2X = T26 - T2x; T2y = T26 + T2x; } T2V = FNMS(KP980785280, T2U, T2T); T30 = FMA(KP980785280, T2U, T2T); T2z = FMA(KP980785280, T2y, T1F); T2S = FNMS(KP980785280, T2y, T1F); T2M = FNMS(KP923879532, T2L, T2I); T2W = FMA(KP923879532, T2L, T2I); } { E T47, T3D, T48, T3S; { E T3K, T41, T42, T3R; { E T2Z, T2Y, T2Q, T2R; T2Z = FNMS(KP980785280, T2X, T2W); T2Y = FMA(KP980785280, T2X, T2W); T2Q = FNMS(KP980785280, T2P, T2M); T2R = FMA(KP980785280, T2P, T2M); R1[WS(rs, 20)] = -(KP1_807978586 * (FMA(KP472964775, T2V, T2Y))); R1[WS(rs, 4)] = KP1_807978586 * (FNMS(KP472964775, T2Y, T2V)); R1[WS(rs, 28)] = -(KP1_883088130 * (FMA(KP357805721, T2Z, T30))); R1[WS(rs, 12)] = -(KP1_883088130 * (FNMS(KP357805721, T30, T2Z))); R1[WS(rs, 24)] = -(KP1_481902250 * (FMA(KP906347169, T2R, T2S))); R1[WS(rs, 8)] = -(KP1_481902250 * (FNMS(KP906347169, T2S, T2R))); R1[WS(rs, 16)] = -(KP1_997590912 * (FMA(KP049126849, T2z, T2Q))); R1[0] = KP1_997590912 * (FNMS(KP049126849, T2Q, T2z)); T47 = FNMS(KP923879532, T3C, T3v); T3D = FMA(KP923879532, T3C, T3v); } T3K = FMA(KP668178637, T3J, T3G); T41 = FNMS(KP668178637, T3G, T3J); T42 = FMA(KP668178637, T3N, T3Q); T3R = FNMS(KP668178637, T3Q, T3N); T48 = T42 - T41; T43 = T41 + T42; T4b = T3K - T3R; T3S = T3K + T3R; } T49 = FNMS(KP831469612, T48, T47); T4e = FMA(KP831469612, T48, T47); T3T = FMA(KP831469612, T3S, T3D); T46 = FNMS(KP831469612, T3S, T3D); T40 = FMA(KP923879532, T3Z, T3W); T4a = FNMS(KP923879532, T3Z, T3W); } } } } } } { E T4d, T4c, T44, T45; T4d = FMA(KP831469612, T4b, T4a); T4c = FNMS(KP831469612, T4b, T4a); T44 = FMA(KP831469612, T43, T40); T45 = FNMS(KP831469612, T43, T40); R1[WS(rs, 21)] = KP1_715457220 * (FNMS(KP599376933, T49, T4c)); R1[WS(rs, 5)] = KP1_715457220 * (FMA(KP599376933, T4c, T49)); R1[WS(rs, 29)] = -(KP1_940062506 * (FNMS(KP250486960, T4d, T4e))); R1[WS(rs, 13)] = KP1_940062506 * (FMA(KP250486960, T4e, T4d)); R1[WS(rs, 25)] = -(KP1_606415062 * (FNMS(KP741650546, T45, T46))); R1[WS(rs, 9)] = KP1_606415062 * (FMA(KP741650546, T46, T45)); R1[WS(rs, 17)] = KP1_978353019 * (FNMS(KP148335987, T3T, T44)); R1[WS(rs, 1)] = KP1_978353019 * (FMA(KP148335987, T44, T3T)); } } } } static const kr2c_desc desc = { 64, "r2cbIII_64", {238, 64, 196, 0}, &GENUS }; void X(codelet_r2cbIII_64) (planner *p) { X(kr2c_register) (p, r2cbIII_64, &desc); } #else /* HAVE_FMA */ /* Generated by: ../../../genfft/gen_r2cb.native -compact -variables 4 -pipeline-latency 4 -sign 1 -n 64 -name r2cbIII_64 -dft-III -include r2cbIII.h */ /* * This function contains 434 FP additions, 208 FP multiplications, * (or, 342 additions, 116 multiplications, 92 fused multiply/add), * 130 stack variables, 39 constants, and 128 memory accesses */ #include "r2cbIII.h" static void r2cbIII_64(R *R0, R *R1, R *Cr, R *Ci, stride rs, stride csr, stride csi, INT v, INT ivs, INT ovs) { DK(KP1_343117909, +1.343117909694036801250753700854843606457501264); DK(KP1_481902250, +1.481902250709918182351233794990325459457910619); DK(KP1_807978586, +1.807978586246886663172400594461074097420264050); DK(KP855110186, +0.855110186860564188641933713777597068609157259); DK(KP1_997590912, +1.997590912410344785429543209518201388886407229); DK(KP098135348, +0.098135348654836028509909953885365316629490726); DK(KP673779706, +0.673779706784440101378506425238295140955533559); DK(KP1_883088130, +1.883088130366041556825018805199004714371179592); DK(KP195090322, +0.195090322016128267848284868477022240927691618); DK(KP980785280, +0.980785280403230449126182236134239036973933731); DK(KP1_191398608, +1.191398608984866686934073057659939779023852677); DK(KP1_606415062, +1.606415062961289819613353025926283847759138854); DK(KP1_715457220, +1.715457220000544139804539968569540274084981599); DK(KP1_028205488, +1.028205488386443453187387677937631545216098241); DK(KP1_978353019, +1.978353019929561946903347476032486127967379067); DK(KP293460948, +0.293460948910723503317700259293435639412430633); DK(KP485960359, +0.485960359806527779896548324154942236641981567); DK(KP1_940062506, +1.940062506389087985207968414572200502913731924); DK(KP555570233, +0.555570233019602224742830813948532874374937191); DK(KP831469612, +0.831469612302545237078788377617905756738560812); DK(KP1_268786568, +1.268786568327290996430343226450986741351374190); DK(KP1_546020906, +1.546020906725473921621813219516939601942082586); DK(KP1_763842528, +1.763842528696710059425513727320776699016885241); DK(KP942793473, +0.942793473651995297112775251810508755314920638); DK(KP1_990369453, +1.990369453344393772489673906218959843150949737); DK(KP196034280, +0.196034280659121203988391127777283691722273346); DK(KP580569354, +0.580569354508924735272384751634790549382952557); DK(KP1_913880671, +1.913880671464417729871595773960539938965698411); DK(KP1_662939224, +1.662939224605090474157576755235811513477121624); DK(KP1_111140466, +1.111140466039204449485661627897065748749874382); DK(KP390180644, +0.390180644032256535696569736954044481855383236); DK(KP1_961570560, +1.961570560806460898252364472268478073947867462); DK(KP765366864, +0.765366864730179543456919968060797733522689125); DK(KP1_847759065, +1.847759065022573512256366378793576573644833252); DK(KP1_414213562, +1.414213562373095048801688724209698078569671875); DK(KP2_000000000, +2.000000000000000000000000000000000000000000000); DK(KP382683432, +0.382683432365089771728459984030398866761344562); DK(KP923879532, +0.923879532511286756128183189396788286822416626); DK(KP707106781, +0.707106781186547524400844362104849039284835938); { INT i; for (i = v; i > 0; i = i - 1, R0 = R0 + ovs, R1 = R1 + ovs, Cr = Cr + ivs, Ci = Ci + ivs, MAKE_VOLATILE_STRIDE(rs), MAKE_VOLATILE_STRIDE(csr), MAKE_VOLATILE_STRIDE(csi)) { E T15, T3t, T3U, T2N, Tf, T6b, T6u, T6R, T4L, T5J, T1g, T3V, T5q, T5U, T2I; E T3u, Tu, T6v, T4V, T5s, T6e, T6Q, T1s, T2D, T1D, T2E, T3B, T3Y, T4Q, T5r; E T3y, T3X, TK, T6g, T57, T5N, T6j, T6N, T1W, T34, T25, T35, T3J, T4j, T52; E T5M, T3G, T4i, TZ, T6l, T5i, T5Q, T6o, T6M, T2n, T37, T2w, T38, T3Q, T4m; E T5d, T5P, T3N, T4l; { E T3, T11, T2M, T5n, T6, T2J, T14, T5m, Ta, T16, T19, T4J, Td, T1b, T1e; E T4I; { E T1, T2, T2K, T2L; T1 = Cr[0]; T2 = Cr[WS(csr, 31)]; T3 = T1 + T2; T11 = T1 - T2; T2K = Ci[0]; T2L = Ci[WS(csi, 31)]; T2M = T2K + T2L; T5n = T2L - T2K; } { E T4, T5, T12, T13; T4 = Cr[WS(csr, 16)]; T5 = Cr[WS(csr, 15)]; T6 = T4 + T5; T2J = T4 - T5; T12 = Ci[WS(csi, 16)]; T13 = Ci[WS(csi, 15)]; T14 = T12 + T13; T5m = T12 - T13; } { E T8, T9, T17, T18; T8 = Cr[WS(csr, 8)]; T9 = Cr[WS(csr, 23)]; Ta = T8 + T9; T16 = T8 - T9; T17 = Ci[WS(csi, 8)]; T18 = Ci[WS(csi, 23)]; T19 = T17 + T18; T4J = T17 - T18; } { E Tb, Tc, T1c, T1d; Tb = Cr[WS(csr, 7)]; Tc = Cr[WS(csr, 24)]; Td = Tb + Tc; T1b = Tb - Tc; T1c = Ci[WS(csi, 7)]; T1d = Ci[WS(csi, 24)]; T1e = T1c + T1d; T4I = T1d - T1c; } { E T7, Te, T1a, T1f; T15 = T11 - T14; T3t = T11 + T14; T3U = T2J - T2M; T2N = T2J + T2M; T7 = T3 + T6; Te = Ta + Td; Tf = T7 + Te; T6b = T7 - Te; { E T6s, T6t, T4H, T4K; T6s = T4J + T4I; T6t = T5n - T5m; T6u = T6s + T6t; T6R = T6t - T6s; T4H = T3 - T6; T4K = T4I - T4J; T4L = T4H + T4K; T5J = T4H - T4K; } T1a = T16 - T19; T1f = T1b - T1e; T1g = KP707106781 * (T1a + T1f); T3V = KP707106781 * (T1a - T1f); { E T5o, T5p, T2G, T2H; T5o = T5m + T5n; T5p = Ta - Td; T5q = T5o - T5p; T5U = T5p + T5o; T2G = T16 + T19; T2H = T1b + T1e; T2I = KP707106781 * (T2G - T2H); T3u = KP707106781 * (T2G + T2H); } } } { E Ti, T1i, T1q, T4N, Tl, T1n, T1l, T4O, Tp, T1t, T1B, T4S, Ts, T1y, T1w; E T4T; { E Tg, Th, T1o, T1p; Tg = Cr[WS(csr, 4)]; Th = Cr[WS(csr, 27)]; Ti = Tg + Th; T1i = Tg - Th; T1o = Ci[WS(csi, 4)]; T1p = Ci[WS(csi, 27)]; T1q = T1o + T1p; T4N = T1o - T1p; } { E Tj, Tk, T1j, T1k; Tj = Cr[WS(csr, 20)]; Tk = Cr[WS(csr, 11)]; Tl = Tj + Tk; T1n = Tj - Tk; T1j = Ci[WS(csi, 20)]; T1k = Ci[WS(csi, 11)]; T1l = T1j + T1k; T4O = T1j - T1k; } { E Tn, To, T1z, T1A; Tn = Cr[WS(csr, 3)]; To = Cr[WS(csr, 28)]; Tp = Tn + To; T1t = Tn - To; T1z = Ci[WS(csi, 3)]; T1A = Ci[WS(csi, 28)]; T1B = T1z + T1A; T4S = T1A - T1z; } { E Tq, Tr, T1u, T1v; Tq = Cr[WS(csr, 12)]; Tr = Cr[WS(csr, 19)]; Ts = Tq + Tr; T1y = Tq - Tr; T1u = Ci[WS(csi, 12)]; T1v = Ci[WS(csi, 19)]; T1w = T1u + T1v; T4T = T1u - T1v; } { E Tm, Tt, T4R, T4U; Tm = Ti + Tl; Tt = Tp + Ts; Tu = Tm + Tt; T6v = Tm - Tt; T4R = Tp - Ts; T4U = T4S - T4T; T4V = T4R + T4U; T5s = T4U - T4R; } { E T6c, T6d, T1m, T1r; T6c = T4T + T4S; T6d = T4O + T4N; T6e = T6c - T6d; T6Q = T6d + T6c; T1m = T1i - T1l; T1r = T1n + T1q; T1s = FNMS(KP382683432, T1r, KP923879532 * T1m); T2D = FMA(KP382683432, T1m, KP923879532 * T1r); } { E T1x, T1C, T3z, T3A; T1x = T1t - T1w; T1C = T1y - T1B; T1D = FMA(KP923879532, T1x, KP382683432 * T1C); T2E = FNMS(KP382683432, T1x, KP923879532 * T1C); T3z = T1t + T1w; T3A = T1y + T1B; T3B = FNMS(KP923879532, T3A, KP382683432 * T3z); T3Y = FMA(KP923879532, T3z, KP382683432 * T3A); } { E T4M, T4P, T3w, T3x; T4M = Ti - Tl; T4P = T4N - T4O; T4Q = T4M - T4P; T5r = T4M + T4P; T3w = T1i + T1l; T3x = T1q - T1n; T3y = FNMS(KP923879532, T3x, KP382683432 * T3w); T3X = FMA(KP923879532, T3w, KP382683432 * T3x); } } { E Ty, T1G, T23, T54, TB, T20, T1J, T55, TI, T4Z, T1U, T1Y, TF, T50, T1P; E T1X; { E Tw, Tx, T1H, T1I; Tw = Cr[WS(csr, 2)]; Tx = Cr[WS(csr, 29)]; Ty = Tw + Tx; T1G = Tw - Tx; { E T21, T22, Tz, TA; T21 = Ci[WS(csi, 2)]; T22 = Ci[WS(csi, 29)]; T23 = T21 + T22; T54 = T21 - T22; Tz = Cr[WS(csr, 18)]; TA = Cr[WS(csr, 13)]; TB = Tz + TA; T20 = Tz - TA; } T1H = Ci[WS(csi, 18)]; T1I = Ci[WS(csi, 13)]; T1J = T1H + T1I; T55 = T1H - T1I; { E TG, TH, T1Q, T1R, T1S, T1T; TG = Cr[WS(csr, 5)]; TH = Cr[WS(csr, 26)]; T1Q = TG - TH; T1R = Ci[WS(csi, 5)]; T1S = Ci[WS(csi, 26)]; T1T = T1R + T1S; TI = TG + TH; T4Z = T1S - T1R; T1U = T1Q - T1T; T1Y = T1Q + T1T; } { E TD, TE, T1L, T1M, T1N, T1O; TD = Cr[WS(csr, 10)]; TE = Cr[WS(csr, 21)]; T1L = TD - TE; T1M = Ci[WS(csi, 10)]; T1N = Ci[WS(csi, 21)]; T1O = T1M + T1N; TF = TD + TE; T50 = T1M - T1N; T1P = T1L - T1O; T1X = T1L + T1O; } } { E TC, TJ, T53, T56; TC = Ty + TB; TJ = TF + TI; TK = TC + TJ; T6g = TC - TJ; T53 = TF - TI; T56 = T54 - T55; T57 = T53 + T56; T5N = T56 - T53; } { E T6h, T6i, T1K, T1V; T6h = T55 + T54; T6i = T50 + T4Z; T6j = T6h - T6i; T6N = T6i + T6h; T1K = T1G - T1J; T1V = KP707106781 * (T1P + T1U); T1W = T1K + T1V; T34 = T1K - T1V; } { E T1Z, T24, T3H, T3I; T1Z = KP707106781 * (T1X - T1Y); T24 = T20 + T23; T25 = T1Z + T24; T35 = T24 - T1Z; T3H = KP707106781 * (T1P - T1U); T3I = T23 - T20; T3J = T3H + T3I; T4j = T3I - T3H; } { E T4Y, T51, T3E, T3F; T4Y = Ty - TB; T51 = T4Z - T50; T52 = T4Y + T51; T5M = T4Y - T51; T3E = T1G + T1J; T3F = KP707106781 * (T1X + T1Y); T3G = T3E - T3F; T4i = T3E + T3F; } } { E TN, T27, T2u, T5f, TQ, T2r, T2a, T5g, TX, T5a, T2l, T2p, TU, T5b, T2g; E T2o; { E TL, TM, T28, T29; TL = Cr[WS(csr, 1)]; TM = Cr[WS(csr, 30)]; TN = TL + TM; T27 = TL - TM; { E T2s, T2t, TO, TP; T2s = Ci[WS(csi, 1)]; T2t = Ci[WS(csi, 30)]; T2u = T2s + T2t; T5f = T2t - T2s; TO = Cr[WS(csr, 14)]; TP = Cr[WS(csr, 17)]; TQ = TO + TP; T2r = TO - TP; } T28 = Ci[WS(csi, 14)]; T29 = Ci[WS(csi, 17)]; T2a = T28 + T29; T5g = T28 - T29; { E TV, TW, T2h, T2i, T2j, T2k; TV = Cr[WS(csr, 9)]; TW = Cr[WS(csr, 22)]; T2h = TV - TW; T2i = Ci[WS(csi, 9)]; T2j = Ci[WS(csi, 22)]; T2k = T2i + T2j; TX = TV + TW; T5a = T2j - T2i; T2l = T2h - T2k; T2p = T2h + T2k; } { E TS, TT, T2c, T2d, T2e, T2f; TS = Cr[WS(csr, 6)]; TT = Cr[WS(csr, 25)]; T2c = TS - TT; T2d = Ci[WS(csi, 6)]; T2e = Ci[WS(csi, 25)]; T2f = T2d + T2e; TU = TS + TT; T5b = T2d - T2e; T2g = T2c - T2f; T2o = T2c + T2f; } } { E TR, TY, T5e, T5h; TR = TN + TQ; TY = TU + TX; TZ = TR + TY; T6l = TR - TY; T5e = TU - TX; T5h = T5f - T5g; T5i = T5e + T5h; T5Q = T5h - T5e; } { E T6m, T6n, T2b, T2m; T6m = T5g + T5f; T6n = T5b + T5a; T6o = T6m - T6n; T6M = T6n + T6m; T2b = T27 - T2a; T2m = KP707106781 * (T2g + T2l); T2n = T2b + T2m; T37 = T2b - T2m; } { E T2q, T2v, T3O, T3P; T2q = KP707106781 * (T2o - T2p); T2v = T2r - T2u; T2w = T2q + T2v; T38 = T2v - T2q; T3O = KP707106781 * (T2g - T2l); T3P = T2r + T2u; T3Q = T3O - T3P; T4m = T3O + T3P; } { E T59, T5c, T3L, T3M; T59 = TN - TQ; T5c = T5a - T5b; T5d = T59 + T5c; T5P = T59 - T5c; T3L = T27 + T2a; T3M = KP707106781 * (T2o + T2p); T3N = T3L - T3M; T4l = T3L + T3M; } } { E Tv, T10, T6X, T6Y, T6Z, T70; Tv = Tf + Tu; T10 = TK + TZ; T6X = Tv - T10; T6Y = T6N + T6M; T6Z = T6R - T6Q; T70 = T6Y + T6Z; R0[0] = KP2_000000000 * (Tv + T10); R0[WS(rs, 16)] = KP2_000000000 * (T6Z - T6Y); R0[WS(rs, 8)] = KP1_414213562 * (T6X + T70); R0[WS(rs, 24)] = KP1_414213562 * (T70 - T6X); } { E T6P, T6V, T6U, T6W; { E T6L, T6O, T6S, T6T; T6L = Tf - Tu; T6O = T6M - T6N; T6P = T6L + T6O; T6V = T6L - T6O; T6S = T6Q + T6R; T6T = TK - TZ; T6U = T6S - T6T; T6W = T6T + T6S; } R0[WS(rs, 4)] = FMA(KP1_847759065, T6P, KP765366864 * T6U); R0[WS(rs, 28)] = FNMS(KP1_847759065, T6V, KP765366864 * T6W); R0[WS(rs, 20)] = FNMS(KP765366864, T6P, KP1_847759065 * T6U); R0[WS(rs, 12)] = FMA(KP765366864, T6V, KP1_847759065 * T6W); } { E T6f, T6w, T6G, T6D, T6z, T6E, T6q, T6H; T6f = T6b + T6e; T6w = T6u - T6v; T6G = T6v + T6u; T6D = T6b - T6e; { E T6x, T6y, T6k, T6p; T6x = T6g + T6j; T6y = T6o - T6l; T6z = KP707106781 * (T6x + T6y); T6E = KP707106781 * (T6y - T6x); T6k = T6g - T6j; T6p = T6l + T6o; T6q = KP707106781 * (T6k + T6p); T6H = KP707106781 * (T6k - T6p); } { E T6r, T6A, T6J, T6K; T6r = T6f + T6q; T6A = T6w - T6z; R0[WS(rs, 2)] = FMA(KP1_961570560, T6r, KP390180644 * T6A); R0[WS(rs, 18)] = FNMS(KP390180644, T6r, KP1_961570560 * T6A); T6J = T6D - T6E; T6K = T6H + T6G; R0[WS(rs, 14)] = FMA(KP390180644, T6J, KP1_961570560 * T6K); R0[WS(rs, 30)] = FNMS(KP1_961570560, T6J, KP390180644 * T6K); } { E T6B, T6C, T6F, T6I; T6B = T6f - T6q; T6C = T6z + T6w; R0[WS(rs, 10)] = FMA(KP1_111140466, T6B, KP1_662939224 * T6C); R0[WS(rs, 26)] = FNMS(KP1_662939224, T6B, KP1_111140466 * T6C); T6F = T6D + T6E; T6I = T6G - T6H; R0[WS(rs, 6)] = FMA(KP1_662939224, T6F, KP1_111140466 * T6I); R0[WS(rs, 22)] = FNMS(KP1_111140466, T6F, KP1_662939224 * T6I); } } { E T5L, T63, T5W, T66, T5S, T67, T5Z, T64, T5K, T5V; T5K = KP707106781 * (T5s - T5r); T5L = T5J + T5K; T63 = T5J - T5K; T5V = KP707106781 * (T4Q - T4V); T5W = T5U - T5V; T66 = T5V + T5U; { E T5O, T5R, T5X, T5Y; T5O = FNMS(KP923879532, T5N, KP382683432 * T5M); T5R = FMA(KP382683432, T5P, KP923879532 * T5Q); T5S = T5O + T5R; T67 = T5O - T5R; T5X = FMA(KP923879532, T5M, KP382683432 * T5N); T5Y = FNMS(KP923879532, T5P, KP382683432 * T5Q); T5Z = T5X + T5Y; T64 = T5Y - T5X; } { E T5T, T60, T69, T6a; T5T = T5L + T5S; T60 = T5W - T5Z; R0[WS(rs, 3)] = FMA(KP1_913880671, T5T, KP580569354 * T60); R0[WS(rs, 19)] = FNMS(KP580569354, T5T, KP1_913880671 * T60); T69 = T63 - T64; T6a = T67 + T66; R0[WS(rs, 15)] = FMA(KP196034280, T69, KP1_990369453 * T6a); R0[WS(rs, 31)] = FNMS(KP1_990369453, T69, KP196034280 * T6a); } { E T61, T62, T65, T68; T61 = T5L - T5S; T62 = T5Z + T5W; R0[WS(rs, 11)] = FMA(KP942793473, T61, KP1_763842528 * T62); R0[WS(rs, 27)] = FNMS(KP1_763842528, T61, KP942793473 * T62); T65 = T63 + T64; T68 = T66 - T67; R0[WS(rs, 7)] = FMA(KP1_546020906, T65, KP1_268786568 * T68); R0[WS(rs, 23)] = FNMS(KP1_268786568, T65, KP1_546020906 * T68); } } { E T4X, T5B, T5u, T5E, T5k, T5F, T5x, T5C, T4W, T5t; T4W = KP707106781 * (T4Q + T4V); T4X = T4L + T4W; T5B = T4L - T4W; T5t = KP707106781 * (T5r + T5s); T5u = T5q - T5t; T5E = T5t + T5q; { E T58, T5j, T5v, T5w; T58 = FNMS(KP382683432, T57, KP923879532 * T52); T5j = FMA(KP923879532, T5d, KP382683432 * T5i); T5k = T58 + T5j; T5F = T58 - T5j; T5v = FMA(KP382683432, T52, KP923879532 * T57); T5w = FNMS(KP382683432, T5d, KP923879532 * T5i); T5x = T5v + T5w; T5C = T5w - T5v; } { E T5l, T5y, T5H, T5I; T5l = T4X + T5k; T5y = T5u - T5x; R0[WS(rs, 1)] = FMA(KP1_990369453, T5l, KP196034280 * T5y); R0[WS(rs, 17)] = FNMS(KP196034280, T5l, KP1_990369453 * T5y); T5H = T5B - T5C; T5I = T5F + T5E; R0[WS(rs, 13)] = FMA(KP580569354, T5H, KP1_913880671 * T5I); R0[WS(rs, 29)] = FNMS(KP1_913880671, T5H, KP580569354 * T5I); } { E T5z, T5A, T5D, T5G; T5z = T4X - T5k; T5A = T5x + T5u; R0[WS(rs, 9)] = FMA(KP1_268786568, T5z, KP1_546020906 * T5A); R0[WS(rs, 25)] = FNMS(KP1_546020906, T5z, KP1_268786568 * T5A); T5D = T5B + T5C; T5G = T5E - T5F; R0[WS(rs, 5)] = FMA(KP1_763842528, T5D, KP942793473 * T5G); R0[WS(rs, 21)] = FNMS(KP942793473, T5D, KP1_763842528 * T5G); } } { E T33, T3l, T3h, T3m, T3a, T3p, T3e, T3o; { E T31, T32, T3f, T3g; T31 = T15 - T1g; T32 = T2E - T2D; T33 = T31 + T32; T3l = T31 - T32; T3f = FMA(KP831469612, T34, KP555570233 * T35); T3g = FNMS(KP831469612, T37, KP555570233 * T38); T3h = T3f + T3g; T3m = T3g - T3f; } { E T36, T39, T3c, T3d; T36 = FNMS(KP831469612, T35, KP555570233 * T34); T39 = FMA(KP555570233, T37, KP831469612 * T38); T3a = T36 + T39; T3p = T36 - T39; T3c = T2I - T2N; T3d = T1s - T1D; T3e = T3c - T3d; T3o = T3d + T3c; } { E T3b, T3i, T3r, T3s; T3b = T33 + T3a; T3i = T3e - T3h; R1[WS(rs, 2)] = FMA(KP1_940062506, T3b, KP485960359 * T3i); R1[WS(rs, 18)] = FNMS(KP485960359, T3b, KP1_940062506 * T3i); T3r = T3l - T3m; T3s = T3p + T3o; R1[WS(rs, 14)] = FMA(KP293460948, T3r, KP1_978353019 * T3s); R1[WS(rs, 30)] = FNMS(KP1_978353019, T3r, KP293460948 * T3s); } { E T3j, T3k, T3n, T3q; T3j = T33 - T3a; T3k = T3h + T3e; R1[WS(rs, 10)] = FMA(KP1_028205488, T3j, KP1_715457220 * T3k); R1[WS(rs, 26)] = FNMS(KP1_715457220, T3j, KP1_028205488 * T3k); T3n = T3l + T3m; T3q = T3o - T3p; R1[WS(rs, 6)] = FMA(KP1_606415062, T3n, KP1_191398608 * T3q); R1[WS(rs, 22)] = FNMS(KP1_191398608, T3n, KP1_606415062 * T3q); } } { E T4h, T4z, T4v, T4A, T4o, T4D, T4s, T4C; { E T4f, T4g, T4t, T4u; T4f = T3t + T3u; T4g = T3X + T3Y; T4h = T4f - T4g; T4z = T4f + T4g; T4t = FMA(KP980785280, T4i, KP195090322 * T4j); T4u = FMA(KP980785280, T4l, KP195090322 * T4m); T4v = T4t - T4u; T4A = T4t + T4u; } { E T4k, T4n, T4q, T4r; T4k = FNMS(KP980785280, T4j, KP195090322 * T4i); T4n = FNMS(KP980785280, T4m, KP195090322 * T4l); T4o = T4k + T4n; T4D = T4k - T4n; T4q = T3V + T3U; T4r = T3y - T3B; T4s = T4q - T4r; T4C = T4r + T4q; } { E T4p, T4w, T4F, T4G; T4p = T4h + T4o; T4w = T4s - T4v; R1[WS(rs, 3)] = FMA(KP1_883088130, T4p, KP673779706 * T4w); R1[WS(rs, 19)] = FNMS(KP673779706, T4p, KP1_883088130 * T4w); T4F = T4z + T4A; T4G = T4D + T4C; R1[WS(rs, 15)] = FMA(KP098135348, T4F, KP1_997590912 * T4G); R1[WS(rs, 31)] = FNMS(KP1_997590912, T4F, KP098135348 * T4G); } { E T4x, T4y, T4B, T4E; T4x = T4h - T4o; T4y = T4v + T4s; R1[WS(rs, 11)] = FMA(KP855110186, T4x, KP1_807978586 * T4y); R1[WS(rs, 27)] = FNMS(KP1_807978586, T4x, KP855110186 * T4y); T4B = T4z - T4A; T4E = T4C - T4D; R1[WS(rs, 7)] = FMA(KP1_481902250, T4B, KP1_343117909 * T4E); R1[WS(rs, 23)] = FNMS(KP1_343117909, T4B, KP1_481902250 * T4E); } } { E T1F, T2T, T2P, T2W, T2y, T2X, T2C, T2U; { E T1h, T1E, T2F, T2O; T1h = T15 + T1g; T1E = T1s + T1D; T1F = T1h + T1E; T2T = T1h - T1E; T2F = T2D + T2E; T2O = T2I + T2N; T2P = T2F + T2O; T2W = T2F - T2O; } { E T26, T2x, T2A, T2B; T26 = FNMS(KP195090322, T25, KP980785280 * T1W); T2x = FMA(KP980785280, T2n, KP195090322 * T2w); T2y = T26 + T2x; T2X = T26 - T2x; T2A = FMA(KP195090322, T1W, KP980785280 * T25); T2B = FNMS(KP195090322, T2n, KP980785280 * T2w); T2C = T2A + T2B; T2U = T2B - T2A; } { E T2z, T2Q, T2Z, T30; T2z = T1F + T2y; T2Q = T2C + T2P; R1[0] = FNMS(KP098135348, T2Q, KP1_997590912 * T2z); R1[WS(rs, 16)] = -(FMA(KP098135348, T2z, KP1_997590912 * T2Q)); T2Z = T2T - T2U; T30 = T2X + T2W; R1[WS(rs, 12)] = FMA(KP673779706, T2Z, KP1_883088130 * T30); R1[WS(rs, 28)] = FNMS(KP1_883088130, T2Z, KP673779706 * T30); } { E T2R, T2S, T2V, T2Y; T2R = T1F - T2y; T2S = T2C - T2P; R1[WS(rs, 8)] = FMA(KP1_343117909, T2R, KP1_481902250 * T2S); R1[WS(rs, 24)] = FNMS(KP1_481902250, T2R, KP1_343117909 * T2S); T2V = T2T + T2U; T2Y = T2W - T2X; R1[WS(rs, 4)] = FMA(KP1_807978586, T2V, KP855110186 * T2Y); R1[WS(rs, 20)] = FNMS(KP855110186, T2V, KP1_807978586 * T2Y); } } { E T3D, T47, T43, T48, T3S, T4b, T40, T4a; { E T3v, T3C, T41, T42; T3v = T3t - T3u; T3C = T3y + T3B; T3D = T3v + T3C; T47 = T3v - T3C; T41 = FMA(KP555570233, T3G, KP831469612 * T3J); T42 = FNMS(KP555570233, T3N, KP831469612 * T3Q); T43 = T41 + T42; T48 = T42 - T41; } { E T3K, T3R, T3W, T3Z; T3K = FNMS(KP555570233, T3J, KP831469612 * T3G); T3R = FMA(KP831469612, T3N, KP555570233 * T3Q); T3S = T3K + T3R; T4b = T3K - T3R; T3W = T3U - T3V; T3Z = T3X - T3Y; T40 = T3W - T3Z; T4a = T3Z + T3W; } { E T3T, T44, T4d, T4e; T3T = T3D + T3S; T44 = T40 - T43; R1[WS(rs, 1)] = FMA(KP1_978353019, T3T, KP293460948 * T44); R1[WS(rs, 17)] = FNMS(KP293460948, T3T, KP1_978353019 * T44); T4d = T47 - T48; T4e = T4b + T4a; R1[WS(rs, 13)] = FMA(KP485960359, T4d, KP1_940062506 * T4e); R1[WS(rs, 29)] = FNMS(KP1_940062506, T4d, KP485960359 * T4e); } { E T45, T46, T49, T4c; T45 = T3D - T3S; T46 = T43 + T40; R1[WS(rs, 9)] = FMA(KP1_191398608, T45, KP1_606415062 * T46); R1[WS(rs, 25)] = FNMS(KP1_606415062, T45, KP1_191398608 * T46); T49 = T47 + T48; T4c = T4a - T4b; R1[WS(rs, 5)] = FMA(KP1_715457220, T49, KP1_028205488 * T4c); R1[WS(rs, 21)] = FNMS(KP1_028205488, T49, KP1_715457220 * T4c); } } } } } static const kr2c_desc desc = { 64, "r2cbIII_64", {342, 116, 92, 0}, &GENUS }; void X(codelet_r2cbIII_64) (planner *p) { X(kr2c_register) (p, r2cbIII_64, &desc); } #endif /* HAVE_FMA */
mesjetiu/grandorgue-es
src/fftw/src/rdft/scalar/r2cb/r2cbIII_64.c
C
gpl-2.0
49,177
#include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/spinlock.h> #include <linux/list.h> #include <linux/device.h> #include <linux/err.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <linux/gpio.h> #include <linux/of_gpio.h> #include <linux/idr.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/gpio/driver.h> #include <linux/gpio/machine.h> #include "gpiolib.h" #ifdef CONFIG_HTC_POWER_DEBUG #ifdef CONFIG_GPIO_QPNP_PIN_DEBUG #include <linux/qpnp/pin.h> #endif #endif #define CREATE_TRACE_POINTS #include <trace/events/gpio.h> /* Implementation infrastructure for GPIO interfaces. * * The GPIO programming interface allows for inlining speed-critical * get/set operations for common cases, so that access to SOC-integrated * GPIOs can sometimes cost only an instruction or two per bit. */ /* When debugging, extend minimal trust to callers and platform code. * Also emit diagnostic messages that may help initial bringup, when * board setup or driver bugs are most common. * * Otherwise, minimize overhead in what may be bitbanging codepaths. */ #ifdef DEBUG #define extra_checks 1 #else #define extra_checks 0 #endif /* gpio_lock prevents conflicts during gpio_desc[] table updates. * While any GPIO is requested, its gpio_chip is not removable; * each GPIO's "requested" flag serves as a lock and refcount. */ DEFINE_SPINLOCK(gpio_lock); static struct gpio_desc gpio_desc[ARCH_NR_GPIOS]; #define GPIO_OFFSET_VALID(chip, offset) (offset >= 0 && offset < chip->ngpio) static DEFINE_MUTEX(gpio_lookup_lock); static LIST_HEAD(gpio_lookup_list); LIST_HEAD(gpio_chips); static inline void desc_set_label(struct gpio_desc *d, const char *label) { d->label = label; } /** * Convert a GPIO number to its descriptor */ struct gpio_desc *gpio_to_desc(unsigned gpio) { if (WARN(!gpio_is_valid(gpio), "invalid GPIO %d\n", gpio)) return NULL; else return &gpio_desc[gpio]; } EXPORT_SYMBOL_GPL(gpio_to_desc); /** * Get the GPIO descriptor corresponding to the given hw number for this chip. */ struct gpio_desc *gpiochip_get_desc(struct gpio_chip *chip, u16 hwnum) { if (hwnum >= chip->ngpio) return ERR_PTR(-EINVAL); return &chip->desc[hwnum]; } /** * Convert a GPIO descriptor to the integer namespace. * This should disappear in the future but is needed since we still * use GPIO numbers for error messages and sysfs nodes */ int desc_to_gpio(const struct gpio_desc *desc) { return desc - &gpio_desc[0]; } EXPORT_SYMBOL_GPL(desc_to_gpio); /** * gpiod_to_chip - Return the GPIO chip to which a GPIO descriptor belongs * @desc: descriptor to return the chip of */ struct gpio_chip *gpiod_to_chip(const struct gpio_desc *desc) { return desc ? desc->chip : NULL; } EXPORT_SYMBOL_GPL(gpiod_to_chip); /* dynamic allocation of GPIOs, e.g. on a hotplugged device */ static int gpiochip_find_base(int ngpio) { struct gpio_chip *chip; int base = ARCH_NR_GPIOS - ngpio; list_for_each_entry_reverse(chip, &gpio_chips, list) { /* found a free space? */ if (chip->base + chip->ngpio <= base) break; else /* nope, check the space right before the chip */ base = chip->base - ngpio; } if (gpio_is_valid(base)) { pr_debug("%s: found new base at %d\n", __func__, base); return base; } else { pr_err("%s: cannot find free range\n", __func__); return -ENOSPC; } } /** * gpiod_get_direction - return the current direction of a GPIO * @desc: GPIO to get the direction of * * Return GPIOF_DIR_IN or GPIOF_DIR_OUT, or an error code in case of error. * * This function may sleep if gpiod_cansleep() is true. */ int gpiod_get_direction(const struct gpio_desc *desc) { struct gpio_chip *chip; unsigned offset; int status = -EINVAL; chip = gpiod_to_chip(desc); offset = gpio_chip_hwgpio(desc); if (!chip->get_direction) return status; status = chip->get_direction(chip, offset); if (status > 0) { /* GPIOF_DIR_IN, or other positive */ status = 1; /* FLAG_IS_OUT is just a cache of the result of get_direction(), * so it does not affect constness per se */ clear_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags); } if (status == 0) { /* GPIOF_DIR_OUT */ set_bit(FLAG_IS_OUT, &((struct gpio_desc *)desc)->flags); } return status; } EXPORT_SYMBOL_GPL(gpiod_get_direction); /* * Add a new chip to the global chips list, keeping the list of chips sorted * by base order. * * Return -EBUSY if the new chip overlaps with some other chip's integer * space. */ static int gpiochip_add_to_list(struct gpio_chip *chip) { struct list_head *pos = &gpio_chips; struct gpio_chip *_chip; int err = 0; /* find where to insert our chip */ list_for_each(pos, &gpio_chips) { _chip = list_entry(pos, struct gpio_chip, list); /* shall we insert before _chip? */ if (_chip->base >= chip->base + chip->ngpio) break; } /* are we stepping on the chip right before? */ if (pos != &gpio_chips && pos->prev != &gpio_chips) { _chip = list_entry(pos->prev, struct gpio_chip, list); if (_chip->base + _chip->ngpio > chip->base) { dev_err(chip->dev, "GPIO integer space overlap, cannot add chip\n"); err = -EBUSY; } } if (!err) list_add_tail(&chip->list, pos); return err; } /** * gpiochip_add() - register a gpio_chip * @chip: the chip to register, with chip->base initialized * Context: potentially before irqs or kmalloc will work * * Returns a negative errno if the chip can't be registered, such as * because the chip->base is invalid or already associated with a * different chip. Otherwise it returns zero as a success code. * * When gpiochip_add() is called very early during boot, so that GPIOs * can be freely used, the chip->dev device must be registered before * the gpio framework's arch_initcall(). Otherwise sysfs initialization * for GPIOs will fail rudely. * * If chip->base is negative, this requests dynamic assignment of * a range of valid GPIOs. */ int gpiochip_add(struct gpio_chip *chip) { unsigned long flags; int status = 0; unsigned id; int base = chip->base; if ((!gpio_is_valid(base) || !gpio_is_valid(base + chip->ngpio - 1)) && base >= 0) { status = -EINVAL; goto fail; } spin_lock_irqsave(&gpio_lock, flags); if (base < 0) { base = gpiochip_find_base(chip->ngpio); if (base < 0) { status = base; goto unlock; } chip->base = base; } status = gpiochip_add_to_list(chip); if (status == 0) { chip->desc = &gpio_desc[chip->base]; for (id = 0; id < chip->ngpio; id++) { struct gpio_desc *desc = &chip->desc[id]; desc->chip = chip; /* REVISIT: most hardware initializes GPIOs as * inputs (often with pullups enabled) so power * usage is minimized. Linux code should set the * gpio direction first thing; but until it does, * and in case chip->get_direction is not set, * we may expose the wrong direction in sysfs. */ desc->flags = !chip->direction_input ? (1 << FLAG_IS_OUT) : 0; } } spin_unlock_irqrestore(&gpio_lock, flags); if (status) goto fail; #ifdef CONFIG_PINCTRL INIT_LIST_HEAD(&chip->pin_ranges); #endif of_gpiochip_add(chip); acpi_gpiochip_add(chip); status = gpiochip_export(chip); if (status) { acpi_gpiochip_remove(chip); of_gpiochip_remove(chip); goto fail; } pr_debug("%s: registered GPIOs %d to %d on device: %s\n", __func__, chip->base, chip->base + chip->ngpio - 1, chip->label ? : "generic"); return 0; unlock: spin_unlock_irqrestore(&gpio_lock, flags); fail: /* failures here can mean systems won't boot... */ pr_err("%s: GPIOs %d..%d (%s) failed to register\n", __func__, chip->base, chip->base + chip->ngpio - 1, chip->label ? : "generic"); return status; } EXPORT_SYMBOL_GPL(gpiochip_add); /* Forward-declaration */ static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip); /** * gpiochip_remove() - unregister a gpio_chip * @chip: the chip to unregister * * A gpio_chip with any GPIOs still requested may not be removed. */ void gpiochip_remove(struct gpio_chip *chip) { unsigned long flags; unsigned id; gpiochip_irqchip_remove(chip); acpi_gpiochip_remove(chip); gpiochip_remove_pin_ranges(chip); of_gpiochip_remove(chip); spin_lock_irqsave(&gpio_lock, flags); for (id = 0; id < chip->ngpio; id++) { if (test_bit(FLAG_REQUESTED, &chip->desc[id].flags)) dev_crit(chip->dev, "REMOVING GPIOCHIP WITH GPIOS STILL REQUESTED\n"); } for (id = 0; id < chip->ngpio; id++) chip->desc[id].chip = NULL; list_del(&chip->list); spin_unlock_irqrestore(&gpio_lock, flags); gpiochip_unexport(chip); } EXPORT_SYMBOL_GPL(gpiochip_remove); /** * gpiochip_find() - iterator for locating a specific gpio_chip * @data: data to pass to match function * @callback: Callback function to check gpio_chip * * Similar to bus_find_device. It returns a reference to a gpio_chip as * determined by a user supplied @match callback. The callback should return * 0 if the device doesn't match and non-zero if it does. If the callback is * non-zero, this function will return to the caller and not iterate over any * more gpio_chips. */ struct gpio_chip *gpiochip_find(void *data, int (*match)(struct gpio_chip *chip, void *data)) { struct gpio_chip *chip; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); list_for_each_entry(chip, &gpio_chips, list) if (chip && match(chip, data)) break; /* No match? */ if (&chip->list == &gpio_chips) chip = NULL; spin_unlock_irqrestore(&gpio_lock, flags); return chip; } EXPORT_SYMBOL_GPL(gpiochip_find); static int gpiochip_match_name(struct gpio_chip *chip, void *data) { const char *name = data; return !strcmp(chip->label, name); } static struct gpio_chip *find_chip_by_name(const char *name) { return gpiochip_find((void *)name, gpiochip_match_name); } #ifdef CONFIG_GPIOLIB_IRQCHIP /* * The following is irqchip helper code for gpiochips. */ /** * gpiochip_set_chained_irqchip() - sets a chained irqchip to a gpiochip * @gpiochip: the gpiochip to set the irqchip chain to * @irqchip: the irqchip to chain to the gpiochip * @parent_irq: the irq number corresponding to the parent IRQ for this * chained irqchip * @parent_handler: the parent interrupt handler for the accumulated IRQ * coming out of the gpiochip. If the interrupt is nested rather than * cascaded, pass NULL in this handler argument */ void gpiochip_set_chained_irqchip(struct gpio_chip *gpiochip, struct irq_chip *irqchip, int parent_irq, irq_flow_handler_t parent_handler) { unsigned int offset; if (!gpiochip->irqdomain) { chip_err(gpiochip, "called %s before setting up irqchip\n", __func__); return; } if (parent_handler) { if (gpiochip->can_sleep) { chip_err(gpiochip, "you cannot have chained interrupts on a " "chip that may sleep\n"); return; } /* * The parent irqchip is already using the chip_data for this * irqchip, so our callbacks simply use the handler_data. */ irq_set_handler_data(parent_irq, gpiochip); irq_set_chained_handler(parent_irq, parent_handler); } /* Set the parent IRQ for all affected IRQs */ for (offset = 0; offset < gpiochip->ngpio; offset++) irq_set_parent(irq_find_mapping(gpiochip->irqdomain, offset), parent_irq); } EXPORT_SYMBOL_GPL(gpiochip_set_chained_irqchip); /* * This lock class tells lockdep that GPIO irqs are in a different * category than their parents, so it won't report false recursion. */ static struct lock_class_key gpiochip_irq_lock_class; /** * gpiochip_irq_map() - maps an IRQ into a GPIO irqchip * @d: the irqdomain used by this irqchip * @irq: the global irq number used by this GPIO irqchip irq * @hwirq: the local IRQ/GPIO line offset on this gpiochip * * This function will set up the mapping for a certain IRQ line on a * gpiochip by assigning the gpiochip as chip data, and using the irqchip * stored inside the gpiochip. */ static int gpiochip_irq_map(struct irq_domain *d, unsigned int irq, irq_hw_number_t hwirq) { struct gpio_chip *chip = d->host_data; irq_set_chip_data(irq, chip); irq_set_lockdep_class(irq, &gpiochip_irq_lock_class); irq_set_chip_and_handler(irq, chip->irqchip, chip->irq_handler); /* Chips that can sleep need nested thread handlers */ if (chip->can_sleep && !chip->irq_not_threaded) irq_set_nested_thread(irq, 1); #ifdef CONFIG_ARM set_irq_flags(irq, IRQF_VALID); #else irq_set_noprobe(irq); #endif /* * No set-up of the hardware will happen if IRQ_TYPE_NONE * is passed as default type. */ if (chip->irq_default_type != IRQ_TYPE_NONE) irq_set_irq_type(irq, chip->irq_default_type); return 0; } static void gpiochip_irq_unmap(struct irq_domain *d, unsigned int irq) { struct gpio_chip *chip = d->host_data; #ifdef CONFIG_ARM set_irq_flags(irq, 0); #endif if (chip->can_sleep) irq_set_nested_thread(irq, 0); irq_set_chip_and_handler(irq, NULL, NULL); irq_set_chip_data(irq, NULL); } static const struct irq_domain_ops gpiochip_domain_ops = { .map = gpiochip_irq_map, .unmap = gpiochip_irq_unmap, /* Virtually all GPIO irqchips are twocell:ed */ .xlate = irq_domain_xlate_twocell, }; static int gpiochip_irq_reqres(struct irq_data *d) { struct gpio_chip *chip = irq_data_get_irq_chip_data(d); if (gpio_lock_as_irq(chip, d->hwirq)) { chip_err(chip, "unable to lock HW IRQ %lu for IRQ\n", d->hwirq); return -EINVAL; } return 0; } static void gpiochip_irq_relres(struct irq_data *d) { struct gpio_chip *chip = irq_data_get_irq_chip_data(d); gpio_unlock_as_irq(chip, d->hwirq); } static int gpiochip_to_irq(struct gpio_chip *chip, unsigned offset) { return irq_find_mapping(chip->irqdomain, offset); } /** * gpiochip_irqchip_remove() - removes an irqchip added to a gpiochip * @gpiochip: the gpiochip to remove the irqchip from * * This is called only from gpiochip_remove() */ static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) { unsigned int offset; acpi_gpiochip_free_interrupts(gpiochip); /* Remove all IRQ mappings and delete the domain */ if (gpiochip->irqdomain) { for (offset = 0; offset < gpiochip->ngpio; offset++) irq_dispose_mapping( irq_find_mapping(gpiochip->irqdomain, offset)); irq_domain_remove(gpiochip->irqdomain); } if (gpiochip->irqchip) { gpiochip->irqchip->irq_request_resources = NULL; gpiochip->irqchip->irq_release_resources = NULL; gpiochip->irqchip = NULL; } } /** * gpiochip_irqchip_add() - adds an irqchip to a gpiochip * @gpiochip: the gpiochip to add the irqchip to * @irqchip: the irqchip to add to the gpiochip * @first_irq: if not dynamically assigned, the base (first) IRQ to * allocate gpiochip irqs from * @handler: the irq handler to use (often a predefined irq core function) * @type: the default type for IRQs on this irqchip, pass IRQ_TYPE_NONE * to have the core avoid setting up any default type in the hardware. * * This function closely associates a certain irqchip with a certain * gpiochip, providing an irq domain to translate the local IRQs to * global irqs in the gpiolib core, and making sure that the gpiochip * is passed as chip data to all related functions. Driver callbacks * need to use container_of() to get their local state containers back * from the gpiochip passed as chip data. An irqdomain will be stored * in the gpiochip that shall be used by the driver to handle IRQ number * translation. The gpiochip will need to be initialized and registered * before calling this function. * * This function will handle two cell:ed simple IRQs and assumes all * the pins on the gpiochip can generate a unique IRQ. Everything else * need to be open coded. */ int gpiochip_irqchip_add(struct gpio_chip *gpiochip, struct irq_chip *irqchip, unsigned int first_irq, irq_flow_handler_t handler, unsigned int type) { struct device_node *of_node; unsigned int offset; unsigned irq_base = 0; if (!gpiochip || !irqchip) return -EINVAL; if (!gpiochip->dev) { pr_err("missing gpiochip .dev parent pointer\n"); return -EINVAL; } of_node = gpiochip->dev->of_node; #ifdef CONFIG_OF_GPIO /* * If the gpiochip has an assigned OF node this takes precendence * FIXME: get rid of this and use gpiochip->dev->of_node everywhere */ if (gpiochip->of_node) of_node = gpiochip->of_node; #endif gpiochip->irqchip = irqchip; gpiochip->irq_handler = handler; gpiochip->irq_default_type = type; gpiochip->to_irq = gpiochip_to_irq; gpiochip->irqdomain = irq_domain_add_simple(of_node, gpiochip->ngpio, first_irq, &gpiochip_domain_ops, gpiochip); if (!gpiochip->irqdomain) { gpiochip->irqchip = NULL; return -EINVAL; } irqchip->irq_request_resources = gpiochip_irq_reqres; irqchip->irq_release_resources = gpiochip_irq_relres; /* * Prepare the mapping since the irqchip shall be orthogonal to * any gpiochip calls. If the first_irq was zero, this is * necessary to allocate descriptors for all IRQs. */ for (offset = 0; offset < gpiochip->ngpio; offset++) { irq_base = irq_create_mapping(gpiochip->irqdomain, offset); if (offset == 0) /* * Store the base into the gpiochip to be used when * unmapping the irqs. */ gpiochip->irq_base = irq_base; } acpi_gpiochip_request_interrupts(gpiochip); return 0; } EXPORT_SYMBOL_GPL(gpiochip_irqchip_add); #else /* CONFIG_GPIOLIB_IRQCHIP */ static void gpiochip_irqchip_remove(struct gpio_chip *gpiochip) {} #endif /* CONFIG_GPIOLIB_IRQCHIP */ #ifdef CONFIG_PINCTRL /** * gpiochip_add_pingroup_range() - add a range for GPIO <-> pin mapping * @chip: the gpiochip to add the range for * @pinctrl: the dev_name() of the pin controller to map to * @gpio_offset: the start offset in the current gpio_chip number space * @pin_group: name of the pin group inside the pin controller */ int gpiochip_add_pingroup_range(struct gpio_chip *chip, struct pinctrl_dev *pctldev, unsigned int gpio_offset, const char *pin_group) { struct gpio_pin_range *pin_range; int ret; pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL); if (!pin_range) { chip_err(chip, "failed to allocate pin ranges\n"); return -ENOMEM; } /* Use local offset as range ID */ pin_range->range.id = gpio_offset; pin_range->range.gc = chip; pin_range->range.name = chip->label; pin_range->range.base = chip->base + gpio_offset; pin_range->pctldev = pctldev; ret = pinctrl_get_group_pins(pctldev, pin_group, &pin_range->range.pins, &pin_range->range.npins); if (ret < 0) { kfree(pin_range); return ret; } pinctrl_add_gpio_range(pctldev, &pin_range->range); chip_dbg(chip, "created GPIO range %d->%d ==> %s PINGRP %s\n", gpio_offset, gpio_offset + pin_range->range.npins - 1, pinctrl_dev_get_devname(pctldev), pin_group); list_add_tail(&pin_range->node, &chip->pin_ranges); return 0; } EXPORT_SYMBOL_GPL(gpiochip_add_pingroup_range); /** * gpiochip_add_pin_range() - add a range for GPIO <-> pin mapping * @chip: the gpiochip to add the range for * @pinctrl_name: the dev_name() of the pin controller to map to * @gpio_offset: the start offset in the current gpio_chip number space * @pin_offset: the start offset in the pin controller number space * @npins: the number of pins from the offset of each pin space (GPIO and * pin controller) to accumulate in this range */ int gpiochip_add_pin_range(struct gpio_chip *chip, const char *pinctl_name, unsigned int gpio_offset, unsigned int pin_offset, unsigned int npins) { struct gpio_pin_range *pin_range; int ret; pin_range = kzalloc(sizeof(*pin_range), GFP_KERNEL); if (!pin_range) { chip_err(chip, "failed to allocate pin ranges\n"); return -ENOMEM; } /* Use local offset as range ID */ pin_range->range.id = gpio_offset; pin_range->range.gc = chip; pin_range->range.name = chip->label; pin_range->range.base = chip->base + gpio_offset; pin_range->range.pin_base = pin_offset; pin_range->range.npins = npins; pin_range->pctldev = pinctrl_find_and_add_gpio_range(pinctl_name, &pin_range->range); if (IS_ERR(pin_range->pctldev)) { ret = PTR_ERR(pin_range->pctldev); chip_err(chip, "could not create pin range\n"); kfree(pin_range); return ret; } chip_dbg(chip, "created GPIO range %d->%d ==> %s PIN %d->%d\n", gpio_offset, gpio_offset + npins - 1, pinctl_name, pin_offset, pin_offset + npins - 1); list_add_tail(&pin_range->node, &chip->pin_ranges); return 0; } EXPORT_SYMBOL_GPL(gpiochip_add_pin_range); /** * gpiochip_remove_pin_ranges() - remove all the GPIO <-> pin mappings * @chip: the chip to remove all the mappings for */ void gpiochip_remove_pin_ranges(struct gpio_chip *chip) { struct gpio_pin_range *pin_range, *tmp; list_for_each_entry_safe(pin_range, tmp, &chip->pin_ranges, node) { list_del(&pin_range->node); pinctrl_remove_gpio_range(pin_range->pctldev, &pin_range->range); kfree(pin_range); } } EXPORT_SYMBOL_GPL(gpiochip_remove_pin_ranges); #endif /* CONFIG_PINCTRL */ /* These "optional" allocation calls help prevent drivers from stomping * on each other, and help provide better diagnostics in debugfs. * They're called even less than the "set direction" calls. */ static int __gpiod_request(struct gpio_desc *desc, const char *label) { struct gpio_chip *chip = desc->chip; int status; unsigned long flags; spin_lock_irqsave(&gpio_lock, flags); /* NOTE: gpio_request() can be called in early boot, * before IRQs are enabled, for non-sleeping (SOC) GPIOs. */ if (test_and_set_bit(FLAG_REQUESTED, &desc->flags) == 0) { desc_set_label(desc, label ? : "?"); status = 0; } else { status = -EBUSY; goto done; } if (chip->request) { /* chip->request may sleep */ spin_unlock_irqrestore(&gpio_lock, flags); status = chip->request(chip, gpio_chip_hwgpio(desc)); spin_lock_irqsave(&gpio_lock, flags); if (status < 0) { desc_set_label(desc, NULL); clear_bit(FLAG_REQUESTED, &desc->flags); goto done; } } if (chip->get_direction) { /* chip->get_direction may sleep */ spin_unlock_irqrestore(&gpio_lock, flags); gpiod_get_direction(desc); spin_lock_irqsave(&gpio_lock, flags); } done: spin_unlock_irqrestore(&gpio_lock, flags); return status; } int gpiod_request(struct gpio_desc *desc, const char *label) { int status = -EPROBE_DEFER; struct gpio_chip *chip; if (!desc) { pr_warn("%s: invalid GPIO\n", __func__); return -EINVAL; } chip = desc->chip; if (!chip) goto done; if (try_module_get(chip->owner)) { status = __gpiod_request(desc, label); if (status < 0) module_put(chip->owner); } done: if (status) gpiod_dbg(desc, "%s: status %d\n", __func__, status); return status; } static bool __gpiod_free(struct gpio_desc *desc) { bool ret = false; unsigned long flags; struct gpio_chip *chip; might_sleep(); gpiod_unexport(desc); spin_lock_irqsave(&gpio_lock, flags); chip = desc->chip; if (chip && test_bit(FLAG_REQUESTED, &desc->flags)) { if (chip->free) { spin_unlock_irqrestore(&gpio_lock, flags); might_sleep_if(chip->can_sleep); chip->free(chip, gpio_chip_hwgpio(desc)); spin_lock_irqsave(&gpio_lock, flags); } desc_set_label(desc, NULL); clear_bit(FLAG_ACTIVE_LOW, &desc->flags); clear_bit(FLAG_REQUESTED, &desc->flags); clear_bit(FLAG_OPEN_DRAIN, &desc->flags); clear_bit(FLAG_OPEN_SOURCE, &desc->flags); ret = true; } spin_unlock_irqrestore(&gpio_lock, flags); return ret; } void gpiod_free(struct gpio_desc *desc) { if (desc && __gpiod_free(desc)) module_put(desc->chip->owner); else WARN_ON(extra_checks); } /** * gpiochip_is_requested - return string iff signal was requested * @chip: controller managing the signal * @offset: of signal within controller's 0..(ngpio - 1) range * * Returns NULL if the GPIO is not currently requested, else a string. * The string returned is the label passed to gpio_request(); if none has been * passed it is a meaningless, non-NULL constant. * * This function is for use by GPIO controller drivers. The label can * help with diagnostics, and knowing that the signal is used as a GPIO * can help avoid accidentally multiplexing it to another controller. */ const char *gpiochip_is_requested(struct gpio_chip *chip, unsigned offset) { struct gpio_desc *desc; if (!GPIO_OFFSET_VALID(chip, offset)) return NULL; desc = &chip->desc[offset]; if (test_bit(FLAG_REQUESTED, &desc->flags) == 0) return NULL; return desc->label; } EXPORT_SYMBOL_GPL(gpiochip_is_requested); /** * gpiochip_request_own_desc - Allow GPIO chip to request its own descriptor * @desc: GPIO descriptor to request * @label: label for the GPIO * * Function allows GPIO chip drivers to request and use their own GPIO * descriptors via gpiolib API. Difference to gpiod_request() is that this * function will not increase reference count of the GPIO chip module. This * allows the GPIO chip module to be unloaded as needed (we assume that the * GPIO chip driver handles freeing the GPIOs it has requested). */ struct gpio_desc *gpiochip_request_own_desc(struct gpio_chip *chip, u16 hwnum, const char *label) { struct gpio_desc *desc = gpiochip_get_desc(chip, hwnum); int err; if (IS_ERR(desc)) { chip_err(chip, "failed to get GPIO descriptor\n"); return desc; } err = __gpiod_request(desc, label); if (err < 0) return ERR_PTR(err); return desc; } EXPORT_SYMBOL_GPL(gpiochip_request_own_desc); /** * gpiochip_free_own_desc - Free GPIO requested by the chip driver * @desc: GPIO descriptor to free * * Function frees the given GPIO requested previously with * gpiochip_request_own_desc(). */ void gpiochip_free_own_desc(struct gpio_desc *desc) { if (desc) __gpiod_free(desc); } EXPORT_SYMBOL_GPL(gpiochip_free_own_desc); /* Drivers MUST set GPIO direction before making get/set calls. In * some cases this is done in early boot, before IRQs are enabled. * * As a rule these aren't called more than once (except for drivers * using the open-drain emulation idiom) so these are natural places * to accumulate extra debugging checks. Note that we can't (yet) * rely on gpio_request() having been called beforehand. */ /** * gpiod_direction_input - set the GPIO direction to input * @desc: GPIO to set to input * * Set the direction of the passed GPIO to input, such as gpiod_get_value() can * be called safely on it. * * Return 0 in case of success, else an error code. */ int gpiod_direction_input(struct gpio_desc *desc) { struct gpio_chip *chip; int status = -EINVAL; if (!desc || !desc->chip) { pr_warn("%s: invalid GPIO\n", __func__); return -EINVAL; } chip = desc->chip; if (!chip->get || !chip->direction_input) { gpiod_warn(desc, "%s: missing get() or direction_input() operations\n", __func__); return -EIO; } status = chip->direction_input(chip, gpio_chip_hwgpio(desc)); if (status == 0) clear_bit(FLAG_IS_OUT, &desc->flags); trace_gpio_direction(desc_to_gpio(desc), 1, status); return status; } EXPORT_SYMBOL_GPL(gpiod_direction_input); static int _gpiod_direction_output_raw(struct gpio_desc *desc, int value) { struct gpio_chip *chip; int status = -EINVAL; /* GPIOs used for IRQs shall not be set as output */ if (test_bit(FLAG_USED_AS_IRQ, &desc->flags)) { gpiod_err(desc, "%s: tried to set a GPIO tied to an IRQ as output\n", __func__); return -EIO; } /* Open drain pin should not be driven to 1 */ if (value && test_bit(FLAG_OPEN_DRAIN, &desc->flags)) return gpiod_direction_input(desc); /* Open source pin should not be driven to 0 */ if (!value && test_bit(FLAG_OPEN_SOURCE, &desc->flags)) return gpiod_direction_input(desc); chip = desc->chip; if (!chip->set || !chip->direction_output) { gpiod_warn(desc, "%s: missing set() or direction_output() operations\n", __func__); return -EIO; } status = chip->direction_output(chip, gpio_chip_hwgpio(desc), value); if (status == 0) set_bit(FLAG_IS_OUT, &desc->flags); trace_gpio_value(desc_to_gpio(desc), 0, value); trace_gpio_direction(desc_to_gpio(desc), 0, status); return status; } /** * gpiod_direction_output_raw - set the GPIO direction to output * @desc: GPIO to set to output * @value: initial output value of the GPIO * * Set the direction of the passed GPIO to output, such as gpiod_set_value() can * be called safely on it. The initial value of the output must be specified * as raw value on the physical line without regard for the ACTIVE_LOW status. * * Return 0 in case of success, else an error code. */ int gpiod_direction_output_raw(struct gpio_desc *desc, int value) { if (!desc || !desc->chip) { pr_warn("%s: invalid GPIO\n", __func__); return -EINVAL; } return _gpiod_direction_output_raw(desc, value); } EXPORT_SYMBOL_GPL(gpiod_direction_output_raw); /** * gpiod_direction_output - set the GPIO direction to output * @desc: GPIO to set to output * @value: initial output value of the GPIO * * Set the direction of the passed GPIO to output, such as gpiod_set_value() can * be called safely on it. The initial value of the output must be specified * as the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into * account. * * Return 0 in case of success, else an error code. */ int gpiod_direction_output(struct gpio_desc *desc, int value) { if (!desc || !desc->chip) { pr_warn("%s: invalid GPIO\n", __func__); return -EINVAL; } if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) value = !value; return _gpiod_direction_output_raw(desc, value); } EXPORT_SYMBOL_GPL(gpiod_direction_output); /** * gpiod_set_debounce - sets @debounce time for a @gpio * @gpio: the gpio to set debounce time * @debounce: debounce time is microseconds * * returns -ENOTSUPP if the controller does not support setting * debounce. */ int gpiod_set_debounce(struct gpio_desc *desc, unsigned debounce) { struct gpio_chip *chip; if (!desc || !desc->chip) { pr_warn("%s: invalid GPIO\n", __func__); return -EINVAL; } chip = desc->chip; if (!chip->set || !chip->set_debounce) { gpiod_dbg(desc, "%s: missing set() or set_debounce() operations\n", __func__); return -ENOTSUPP; } return chip->set_debounce(chip, gpio_chip_hwgpio(desc), debounce); } EXPORT_SYMBOL_GPL(gpiod_set_debounce); /** * gpiod_is_active_low - test whether a GPIO is active-low or not * @desc: the gpio descriptor to test * * Returns 1 if the GPIO is active-low, 0 otherwise. */ int gpiod_is_active_low(const struct gpio_desc *desc) { return test_bit(FLAG_ACTIVE_LOW, &desc->flags); } EXPORT_SYMBOL_GPL(gpiod_is_active_low); /* I/O calls are only valid after configuration completed; the relevant * "is this a valid GPIO" error checks should already have been done. * * "Get" operations are often inlinable as reading a pin value register, * and masking the relevant bit in that register. * * When "set" operations are inlinable, they involve writing that mask to * one register to set a low value, or a different register to set it high. * Otherwise locking is needed, so there may be little value to inlining. * *------------------------------------------------------------------------ * * IMPORTANT!!! The hot paths -- get/set value -- assume that callers * have requested the GPIO. That can include implicit requesting by * a direction setting call. Marking a gpio as requested locks its chip * in memory, guaranteeing that these table lookups need no more locking * and that gpiochip_remove() will fail. * * REVISIT when debugging, consider adding some instrumentation to ensure * that the GPIO was actually requested. */ static bool _gpiod_get_raw_value(const struct gpio_desc *desc) { struct gpio_chip *chip; bool value; int offset; chip = desc->chip; offset = gpio_chip_hwgpio(desc); value = chip->get ? chip->get(chip, offset) : false; trace_gpio_value(desc_to_gpio(desc), 1, value); return value; } /** * gpiod_get_raw_value() - return a gpio's raw value * @desc: gpio whose value will be returned * * Return the GPIO's raw value, i.e. the value of the physical line disregarding * its ACTIVE_LOW status. * * This function should be called from contexts where we cannot sleep, and will * complain if the GPIO chip functions potentially sleep. */ int gpiod_get_raw_value(const struct gpio_desc *desc) { if (!desc) return 0; /* Should be using gpio_get_value_cansleep() */ WARN_ON(desc->chip->can_sleep); return _gpiod_get_raw_value(desc); } EXPORT_SYMBOL_GPL(gpiod_get_raw_value); /** * gpiod_get_value() - return a gpio's value * @desc: gpio whose value will be returned * * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into * account. * * This function should be called from contexts where we cannot sleep, and will * complain if the GPIO chip functions potentially sleep. */ int gpiod_get_value(const struct gpio_desc *desc) { int value; if (!desc) return 0; /* Should be using gpio_get_value_cansleep() */ WARN_ON(desc->chip->can_sleep); value = _gpiod_get_raw_value(desc); if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) value = !value; return value; } EXPORT_SYMBOL_GPL(gpiod_get_value); /* * _gpio_set_open_drain_value() - Set the open drain gpio's value. * @desc: gpio descriptor whose state need to be set. * @value: Non-zero for setting it HIGH otherise it will set to LOW. */ static void _gpio_set_open_drain_value(struct gpio_desc *desc, bool value) { int err = 0; struct gpio_chip *chip = desc->chip; int offset = gpio_chip_hwgpio(desc); if (value) { err = chip->direction_input(chip, offset); if (!err) clear_bit(FLAG_IS_OUT, &desc->flags); } else { err = chip->direction_output(chip, offset, 0); if (!err) set_bit(FLAG_IS_OUT, &desc->flags); } trace_gpio_direction(desc_to_gpio(desc), value, err); if (err < 0) gpiod_err(desc, "%s: Error in set_value for open drain err %d\n", __func__, err); } /* * _gpio_set_open_source_value() - Set the open source gpio's value. * @desc: gpio descriptor whose state need to be set. * @value: Non-zero for setting it HIGH otherise it will set to LOW. */ static void _gpio_set_open_source_value(struct gpio_desc *desc, bool value) { int err = 0; struct gpio_chip *chip = desc->chip; int offset = gpio_chip_hwgpio(desc); if (value) { err = chip->direction_output(chip, offset, 1); if (!err) set_bit(FLAG_IS_OUT, &desc->flags); } else { err = chip->direction_input(chip, offset); if (!err) clear_bit(FLAG_IS_OUT, &desc->flags); } trace_gpio_direction(desc_to_gpio(desc), !value, err); if (err < 0) gpiod_err(desc, "%s: Error in set_value for open source err %d\n", __func__, err); } static void _gpiod_set_raw_value(struct gpio_desc *desc, bool value) { struct gpio_chip *chip; chip = desc->chip; trace_gpio_value(desc_to_gpio(desc), 0, value); if (test_bit(FLAG_OPEN_DRAIN, &desc->flags)) _gpio_set_open_drain_value(desc, value); else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags)) _gpio_set_open_source_value(desc, value); else chip->set(chip, gpio_chip_hwgpio(desc), value); } /** * gpiod_set_raw_value() - assign a gpio's raw value * @desc: gpio whose value will be assigned * @value: value to assign * * Set the raw value of the GPIO, i.e. the value of its physical line without * regard for its ACTIVE_LOW status. * * This function should be called from contexts where we cannot sleep, and will * complain if the GPIO chip functions potentially sleep. */ void gpiod_set_raw_value(struct gpio_desc *desc, int value) { if (!desc) return; /* Should be using gpio_set_value_cansleep() */ WARN_ON(desc->chip->can_sleep); _gpiod_set_raw_value(desc, value); } EXPORT_SYMBOL_GPL(gpiod_set_raw_value); /** * gpiod_set_value() - assign a gpio's value * @desc: gpio whose value will be assigned * @value: value to assign * * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into * account * * This function should be called from contexts where we cannot sleep, and will * complain if the GPIO chip functions potentially sleep. */ void gpiod_set_value(struct gpio_desc *desc, int value) { if (!desc) return; /* Should be using gpio_set_value_cansleep() */ WARN_ON(desc->chip->can_sleep); if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) value = !value; _gpiod_set_raw_value(desc, value); } EXPORT_SYMBOL_GPL(gpiod_set_value); /** * gpiod_cansleep() - report whether gpio value access may sleep * @desc: gpio to check * */ int gpiod_cansleep(const struct gpio_desc *desc) { if (!desc) return 0; return desc->chip->can_sleep; } EXPORT_SYMBOL_GPL(gpiod_cansleep); /** * gpiod_to_irq() - return the IRQ corresponding to a GPIO * @desc: gpio whose IRQ will be returned (already requested) * * Return the IRQ corresponding to the passed GPIO, or an error code in case of * error. */ int gpiod_to_irq(const struct gpio_desc *desc) { struct gpio_chip *chip; int offset; if (!desc) return -EINVAL; chip = desc->chip; offset = gpio_chip_hwgpio(desc); return chip->to_irq ? chip->to_irq(chip, offset) : -ENXIO; } EXPORT_SYMBOL_GPL(gpiod_to_irq); /** * gpio_lock_as_irq() - lock a GPIO to be used as IRQ * @chip: the chip the GPIO to lock belongs to * @offset: the offset of the GPIO to lock as IRQ * * This is used directly by GPIO drivers that want to lock down * a certain GPIO line to be used for IRQs. */ int gpio_lock_as_irq(struct gpio_chip *chip, unsigned int offset) { if (offset >= chip->ngpio) return -EINVAL; if (test_bit(FLAG_IS_OUT, &chip->desc[offset].flags)) { chip_err(chip, "%s: tried to flag a GPIO set as output for IRQ\n", __func__); return -EIO; } set_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags); return 0; } EXPORT_SYMBOL_GPL(gpio_lock_as_irq); /** * gpio_unlock_as_irq() - unlock a GPIO used as IRQ * @chip: the chip the GPIO to lock belongs to * @offset: the offset of the GPIO to lock as IRQ * * This is used directly by GPIO drivers that want to indicate * that a certain GPIO is no longer used exclusively for IRQ. */ void gpio_unlock_as_irq(struct gpio_chip *chip, unsigned int offset) { if (offset >= chip->ngpio) return; clear_bit(FLAG_USED_AS_IRQ, &chip->desc[offset].flags); } EXPORT_SYMBOL_GPL(gpio_unlock_as_irq); /** * gpiod_get_raw_value_cansleep() - return a gpio's raw value * @desc: gpio whose value will be returned * * Return the GPIO's raw value, i.e. the value of the physical line disregarding * its ACTIVE_LOW status. * * This function is to be called from contexts that can sleep. */ int gpiod_get_raw_value_cansleep(const struct gpio_desc *desc) { might_sleep_if(extra_checks); if (!desc) return 0; return _gpiod_get_raw_value(desc); } EXPORT_SYMBOL_GPL(gpiod_get_raw_value_cansleep); /** * gpiod_get_value_cansleep() - return a gpio's value * @desc: gpio whose value will be returned * * Return the GPIO's logical value, i.e. taking the ACTIVE_LOW status into * account. * * This function is to be called from contexts that can sleep. */ int gpiod_get_value_cansleep(const struct gpio_desc *desc) { int value; might_sleep_if(extra_checks); if (!desc) return 0; value = _gpiod_get_raw_value(desc); if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) value = !value; return value; } EXPORT_SYMBOL_GPL(gpiod_get_value_cansleep); /** * gpiod_set_raw_value_cansleep() - assign a gpio's raw value * @desc: gpio whose value will be assigned * @value: value to assign * * Set the raw value of the GPIO, i.e. the value of its physical line without * regard for its ACTIVE_LOW status. * * This function is to be called from contexts that can sleep. */ void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value) { might_sleep_if(extra_checks); if (!desc) return; _gpiod_set_raw_value(desc, value); } EXPORT_SYMBOL_GPL(gpiod_set_raw_value_cansleep); /** * gpiod_set_value_cansleep() - assign a gpio's value * @desc: gpio whose value will be assigned * @value: value to assign * * Set the logical value of the GPIO, i.e. taking its ACTIVE_LOW status into * account * * This function is to be called from contexts that can sleep. */ void gpiod_set_value_cansleep(struct gpio_desc *desc, int value) { might_sleep_if(extra_checks); if (!desc) return; if (test_bit(FLAG_ACTIVE_LOW, &desc->flags)) value = !value; _gpiod_set_raw_value(desc, value); } EXPORT_SYMBOL_GPL(gpiod_set_value_cansleep); /** * gpiod_add_lookup_table() - register GPIO device consumers * @table: table of consumers to register */ void gpiod_add_lookup_table(struct gpiod_lookup_table *table) { mutex_lock(&gpio_lookup_lock); list_add_tail(&table->list, &gpio_lookup_list); mutex_unlock(&gpio_lookup_lock); } static struct gpio_desc *of_find_gpio(struct device *dev, const char *con_id, unsigned int idx, enum gpio_lookup_flags *flags) { static const char *suffixes[] = { "gpios", "gpio" }; char prop_name[32]; /* 32 is max size of property name */ enum of_gpio_flags of_flags; struct gpio_desc *desc; unsigned int i; for (i = 0; i < ARRAY_SIZE(suffixes); i++) { if (con_id) snprintf(prop_name, 32, "%s-%s", con_id, suffixes[i]); else snprintf(prop_name, 32, "%s", suffixes[i]); desc = of_get_named_gpiod_flags(dev->of_node, prop_name, idx, &of_flags); if (!IS_ERR(desc) || (PTR_ERR(desc) == -EPROBE_DEFER)) break; } if (IS_ERR(desc)) return desc; if (of_flags & OF_GPIO_ACTIVE_LOW) *flags |= GPIO_ACTIVE_LOW; return desc; } static struct gpio_desc *acpi_find_gpio(struct device *dev, const char *con_id, unsigned int idx, enum gpio_lookup_flags *flags) { struct acpi_gpio_info info; struct gpio_desc *desc; desc = acpi_get_gpiod_by_index(dev, idx, &info); if (IS_ERR(desc)) return desc; if (info.gpioint && info.active_low) *flags |= GPIO_ACTIVE_LOW; return desc; } static struct gpiod_lookup_table *gpiod_find_lookup_table(struct device *dev) { const char *dev_id = dev ? dev_name(dev) : NULL; struct gpiod_lookup_table *table; mutex_lock(&gpio_lookup_lock); list_for_each_entry(table, &gpio_lookup_list, list) { if (table->dev_id && dev_id) { /* * Valid strings on both ends, must be identical to have * a match */ if (!strcmp(table->dev_id, dev_id)) goto found; } else { /* * One of the pointers is NULL, so both must be to have * a match */ if (dev_id == table->dev_id) goto found; } } table = NULL; found: mutex_unlock(&gpio_lookup_lock); return table; } static struct gpio_desc *gpiod_find(struct device *dev, const char *con_id, unsigned int idx, enum gpio_lookup_flags *flags) { struct gpio_desc *desc = ERR_PTR(-ENOENT); struct gpiod_lookup_table *table; struct gpiod_lookup *p; table = gpiod_find_lookup_table(dev); if (!table) return desc; for (p = &table->table[0]; p->chip_label; p++) { struct gpio_chip *chip; /* idx must always match exactly */ if (p->idx != idx) continue; /* If the lookup entry has a con_id, require exact match */ if (p->con_id && (!con_id || strcmp(p->con_id, con_id))) continue; chip = find_chip_by_name(p->chip_label); if (!chip) { dev_err(dev, "cannot find GPIO chip %s\n", p->chip_label); return ERR_PTR(-ENODEV); } if (chip->ngpio <= p->chip_hwnum) { dev_err(dev, "requested GPIO %d is out of range [0..%d] for chip %s\n", idx, chip->ngpio, chip->label); return ERR_PTR(-EINVAL); } desc = gpiochip_get_desc(chip, p->chip_hwnum); *flags = p->flags; return desc; } return desc; } /** * gpiod_get - obtain a GPIO for a given GPIO function * @dev: GPIO consumer, can be NULL for system-global GPIOs * @con_id: function within the GPIO consumer * @flags: optional GPIO initialization flags * * Return the GPIO descriptor corresponding to the function con_id of device * dev, -ENOENT if no GPIO has been assigned to the requested function, or * another IS_ERR() code if an error occured while trying to acquire the GPIO. */ struct gpio_desc *__must_check __gpiod_get(struct device *dev, const char *con_id, enum gpiod_flags flags) { return gpiod_get_index(dev, con_id, 0, flags); } EXPORT_SYMBOL_GPL(__gpiod_get); /** * gpiod_get_optional - obtain an optional GPIO for a given GPIO function * @dev: GPIO consumer, can be NULL for system-global GPIOs * @con_id: function within the GPIO consumer * @flags: optional GPIO initialization flags * * This is equivalent to gpiod_get(), except that when no GPIO was assigned to * the requested function it will return NULL. This is convenient for drivers * that need to handle optional GPIOs. */ struct gpio_desc *__must_check __gpiod_get_optional(struct device *dev, const char *con_id, enum gpiod_flags flags) { return gpiod_get_index_optional(dev, con_id, 0, flags); } EXPORT_SYMBOL_GPL(__gpiod_get_optional); /** * gpiod_get_index - obtain a GPIO from a multi-index GPIO function * @dev: GPIO consumer, can be NULL for system-global GPIOs * @con_id: function within the GPIO consumer * @idx: index of the GPIO to obtain in the consumer * @flags: optional GPIO initialization flags * * This variant of gpiod_get() allows to access GPIOs other than the first * defined one for functions that define several GPIOs. * * Return a valid GPIO descriptor, -ENOENT if no GPIO has been assigned to the * requested function and/or index, or another IS_ERR() code if an error * occured while trying to acquire the GPIO. */ struct gpio_desc *__must_check __gpiod_get_index(struct device *dev, const char *con_id, unsigned int idx, enum gpiod_flags flags) { struct gpio_desc *desc = NULL; int status; enum gpio_lookup_flags lookupflags = 0; dev_dbg(dev, "GPIO lookup for consumer %s\n", con_id); /* Using device tree? */ if (IS_ENABLED(CONFIG_OF) && dev && dev->of_node) { dev_dbg(dev, "using device tree for GPIO lookup\n"); desc = of_find_gpio(dev, con_id, idx, &lookupflags); } else if (IS_ENABLED(CONFIG_ACPI) && dev && ACPI_HANDLE(dev)) { dev_dbg(dev, "using ACPI for GPIO lookup\n"); desc = acpi_find_gpio(dev, con_id, idx, &lookupflags); } /* * Either we are not using DT or ACPI, or their lookup did not return * a result. In that case, use platform lookup as a fallback. */ if (!desc || desc == ERR_PTR(-ENOENT)) { dev_dbg(dev, "using lookup tables for GPIO lookup\n"); desc = gpiod_find(dev, con_id, idx, &lookupflags); } if (IS_ERR(desc)) { dev_dbg(dev, "lookup for GPIO %s failed\n", con_id); return desc; } status = gpiod_request(desc, con_id); if (status < 0) return ERR_PTR(status); if (lookupflags & GPIO_ACTIVE_LOW) set_bit(FLAG_ACTIVE_LOW, &desc->flags); if (lookupflags & GPIO_OPEN_DRAIN) set_bit(FLAG_OPEN_DRAIN, &desc->flags); if (lookupflags & GPIO_OPEN_SOURCE) set_bit(FLAG_OPEN_SOURCE, &desc->flags); /* No particular flag request, return here... */ if (!(flags & GPIOD_FLAGS_BIT_DIR_SET)) return desc; /* Process flags */ if (flags & GPIOD_FLAGS_BIT_DIR_OUT) status = gpiod_direction_output(desc, flags & GPIOD_FLAGS_BIT_DIR_VAL); else status = gpiod_direction_input(desc); if (status < 0) { dev_dbg(dev, "setup of GPIO %s failed\n", con_id); gpiod_put(desc); return ERR_PTR(status); } return desc; } EXPORT_SYMBOL_GPL(__gpiod_get_index); /** * gpiod_get_index_optional - obtain an optional GPIO from a multi-index GPIO * function * @dev: GPIO consumer, can be NULL for system-global GPIOs * @con_id: function within the GPIO consumer * @index: index of the GPIO to obtain in the consumer * @flags: optional GPIO initialization flags * * This is equivalent to gpiod_get_index(), except that when no GPIO with the * specified index was assigned to the requested function it will return NULL. * This is convenient for drivers that need to handle optional GPIOs. */ struct gpio_desc *__must_check __gpiod_get_index_optional(struct device *dev, const char *con_id, unsigned int index, enum gpiod_flags flags) { struct gpio_desc *desc; desc = gpiod_get_index(dev, con_id, index, flags); if (IS_ERR(desc)) { if (PTR_ERR(desc) == -ENOENT) return NULL; } return desc; } EXPORT_SYMBOL_GPL(__gpiod_get_index_optional); /** * gpiod_put - dispose of a GPIO descriptor * @desc: GPIO descriptor to dispose of * * No descriptor can be used after gpiod_put() has been called on it. */ void gpiod_put(struct gpio_desc *desc) { gpiod_free(desc); } EXPORT_SYMBOL_GPL(gpiod_put); #ifdef CONFIG_DEBUG_FS static void gpiolib_dbg_show(struct seq_file *s, struct gpio_chip *chip) { unsigned i; unsigned gpio = chip->base; struct gpio_desc *gdesc = &chip->desc[0]; int is_out; int is_irq; for (i = 0; i < chip->ngpio; i++, gpio++, gdesc++) { if (!test_bit(FLAG_REQUESTED, &gdesc->flags)) continue; gpiod_get_direction(gdesc); is_out = test_bit(FLAG_IS_OUT, &gdesc->flags); is_irq = test_bit(FLAG_USED_AS_IRQ, &gdesc->flags); seq_printf(s, " gpio-%-3d (%-20.20s) %s %s %s", gpio, gdesc->label, is_out ? "out" : "in ", chip->get ? (chip->get(chip, i) ? "hi" : "lo") : "? ", is_irq ? "IRQ" : " "); seq_printf(s, "\n"); } } static void *gpiolib_seq_start(struct seq_file *s, loff_t *pos) { unsigned long flags; struct gpio_chip *chip = NULL; loff_t index = *pos; s->private = ""; spin_lock_irqsave(&gpio_lock, flags); list_for_each_entry(chip, &gpio_chips, list) if (index-- == 0) { spin_unlock_irqrestore(&gpio_lock, flags); return chip; } spin_unlock_irqrestore(&gpio_lock, flags); return NULL; } static void *gpiolib_seq_next(struct seq_file *s, void *v, loff_t *pos) { unsigned long flags; struct gpio_chip *chip = v; void *ret = NULL; spin_lock_irqsave(&gpio_lock, flags); if (list_is_last(&chip->list, &gpio_chips)) ret = NULL; else ret = list_entry(chip->list.next, struct gpio_chip, list); spin_unlock_irqrestore(&gpio_lock, flags); s->private = "\n"; ++*pos; return ret; } static void gpiolib_seq_stop(struct seq_file *s, void *v) { } static int gpiolib_seq_show(struct seq_file *s, void *v) { struct gpio_chip *chip = v; struct device *dev; seq_printf(s, "%sGPIOs %d-%d", (char *)s->private, chip->base, chip->base + chip->ngpio - 1); dev = chip->dev; if (dev) seq_printf(s, ", %s/%s", dev->bus ? dev->bus->name : "no-bus", dev_name(dev)); if (chip->label) seq_printf(s, ", %s", chip->label); if (chip->can_sleep) seq_printf(s, ", can sleep"); seq_printf(s, ":\n"); if (chip->dbg_show) chip->dbg_show(s, chip); else gpiolib_dbg_show(s, chip); return 0; } static const struct seq_operations gpiolib_seq_ops = { .start = gpiolib_seq_start, .next = gpiolib_seq_next, .stop = gpiolib_seq_stop, .show = gpiolib_seq_show, }; static int gpiolib_open(struct inode *inode, struct file *file) { return seq_open(file, &gpiolib_seq_ops); } static const struct file_operations gpiolib_operations = { .owner = THIS_MODULE, .open = gpiolib_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_HTC_POWER_DEBUG #ifdef CONFIG_GPIO_QPNP_PIN_DEBUG static struct dentry *debugfs_base; static int list_gpios_show(struct seq_file *s, void *v) { struct gpio_chip *chip = v; if (chip->dbg_show) { msm_dump_gpios(s, 0, NULL); qpnp_pin_dump(s, 0, NULL); } return 0; } static const struct seq_operations htc_gpiolib_seq_ops = { .start = gpiolib_seq_start, .next = gpiolib_seq_next, .stop = gpiolib_seq_stop, .show = list_gpios_show, }; static int list_gpios_open(struct inode *inode, struct file *file) { return seq_open(file, &htc_gpiolib_seq_ops); } static const struct file_operations list_gpios_fops = { .open = list_gpios_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif #endif static int __init gpiolib_debugfs_init(void) { /* /sys/kernel/debug/gpio */ (void) debugfs_create_file("gpio", S_IFREG | S_IRUGO, NULL, NULL, &gpiolib_operations); #ifdef CONFIG_HTC_POWER_DEBUG #ifdef CONFIG_GPIO_QPNP_PIN_DEBUG debugfs_base = debugfs_create_dir("htc_gpio", NULL); if (!debugfs_base) return -ENOMEM; if (!debugfs_create_file("list_gpios", S_IRUGO, debugfs_base, NULL, &list_gpios_fops)) return -ENOMEM; #endif #endif return 0; } subsys_initcall(gpiolib_debugfs_init); #endif /* DEBUG_FS */
freak07/Kirisakura_Pixel
drivers/gpio/gpiolib.c
C
gpl-2.0
52,492
/** @file Provides services to print debug and assert messages to a debug output device. The Debug library supports debug print and asserts based on a combination of macros and code. The debug library can be turned on and off so that the debug code does not increase the size of an image. Note that a reserved macro named MDEPKG_NDEBUG is introduced for the intention of size reduction when compiler optimization is disabled. If MDEPKG_NDEBUG is defined, then debug and assert related macros wrapped by it are the NULL implementations. Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef __DEBUG_LIB_H__ #define __DEBUG_LIB_H__ // // Declare bits for PcdDebugPropertyMask // #define DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED 0x01 #define DEBUG_PROPERTY_DEBUG_PRINT_ENABLED 0x02 #define DEBUG_PROPERTY_DEBUG_CODE_ENABLED 0x04 #define DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED 0x08 #define DEBUG_PROPERTY_ASSERT_BREAKPOINT_ENABLED 0x10 #define DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED 0x20 // // Declare bits for PcdDebugPrintErrorLevel and the ErrorLevel parameter of DebugPrint() // #define DEBUG_INIT 0x00000001 // Initialization #define DEBUG_WARN 0x00000002 // Warnings #define DEBUG_LOAD 0x00000004 // Load events #define DEBUG_FS 0x00000008 // EFI File system #define DEBUG_POOL 0x00000010 // Alloc & Free (pool) #define DEBUG_PAGE 0x00000020 // Alloc & Free (page) #define DEBUG_INFO 0x00000040 // Informational debug messages #define DEBUG_DISPATCH 0x00000080 // PEI/DXE/SMM Dispatchers #define DEBUG_VARIABLE 0x00000100 // Variable #define DEBUG_BM 0x00000400 // Boot Manager #define DEBUG_BLKIO 0x00001000 // BlkIo Driver #define DEBUG_NET 0x00004000 // Network Io Driver #define DEBUG_UNDI 0x00010000 // UNDI Driver #define DEBUG_LOADFILE 0x00020000 // LoadFile #define DEBUG_EVENT 0x00080000 // Event messages #define DEBUG_GCD 0x00100000 // Global Coherency Database changes #define DEBUG_CACHE 0x00200000 // Memory range cachability changes #define DEBUG_VERBOSE 0x00400000 // Detailed debug messages that may // significantly impact boot performance #define DEBUG_ERROR 0x80000000 // Error // // Aliases of debug message mask bits // #define EFI_D_INIT DEBUG_INIT #define EFI_D_WARN DEBUG_WARN #define EFI_D_LOAD DEBUG_LOAD #define EFI_D_FS DEBUG_FS #define EFI_D_POOL DEBUG_POOL #define EFI_D_PAGE DEBUG_PAGE #define EFI_D_INFO DEBUG_INFO #define EFI_D_DISPATCH DEBUG_DISPATCH #define EFI_D_VARIABLE DEBUG_VARIABLE #define EFI_D_BM DEBUG_BM #define EFI_D_BLKIO DEBUG_BLKIO #define EFI_D_NET DEBUG_NET #define EFI_D_UNDI DEBUG_UNDI #define EFI_D_LOADFILE DEBUG_LOADFILE #define EFI_D_EVENT DEBUG_EVENT #define EFI_D_VERBOSE DEBUG_VERBOSE #define EFI_D_ERROR DEBUG_ERROR /** Prints a debug message to the debug output device if the specified error level is enabled. If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function GetDebugPrintErrorLevel (), then print the message specified by Format and the associated variable argument list to the debug output device. If Format is NULL, then ASSERT(). @param ErrorLevel The error level of the debug message. @param Format The format string for the debug message to print. @param ... The variable argument list whose contents are accessed based on the format string specified by Format. **/ VOID EFIAPI DebugPrint ( IN UINTN ErrorLevel, IN CONST CHAR8 *Format, ... ); /** Prints a debug message to the debug output device if the specified error level is enabled. If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function GetDebugPrintErrorLevel (), then print the message specified by Format and the associated variable argument list to the debug output device. If Format is NULL, then ASSERT(). @param ErrorLevel The error level of the debug message. @param Format Format string for the debug message to print. @param VaListMarker VA_LIST marker for the variable argument list. **/ VOID EFIAPI DebugVPrint ( IN UINTN ErrorLevel, IN CONST CHAR8 *Format, IN VA_LIST VaListMarker ); /** Prints a debug message to the debug output device if the specified error level is enabled. This function use BASE_LIST which would provide a more compatible service than VA_LIST. If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function GetDebugPrintErrorLevel (), then print the message specified by Format and the associated variable argument list to the debug output device. If Format is NULL, then ASSERT(). @param ErrorLevel The error level of the debug message. @param Format Format string for the debug message to print. @param BaseListMarker BASE_LIST marker for the variable argument list. **/ VOID EFIAPI DebugBPrint ( IN UINTN ErrorLevel, IN CONST CHAR8 *Format, IN BASE_LIST BaseListMarker ); /** Prints an assert message containing a filename, line number, and description. This may be followed by a breakpoint or a dead loop. Print a message of the form "ASSERT <FileName>(<LineNumber>): <Description>\n" to the debug output device. If DEBUG_PROPERTY_ASSERT_BREAKPOINT_ENABLED bit of PcdDebugProperyMask is set then CpuBreakpoint() is called. Otherwise, if DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED bit of PcdDebugProperyMask is set then CpuDeadLoop() is called. If neither of these bits are set, then this function returns immediately after the message is printed to the debug output device. DebugAssert() must actively prevent recursion. If DebugAssert() is called while processing another DebugAssert(), then DebugAssert() must return immediately. If FileName is NULL, then a <FileName> string of "(NULL) Filename" is printed. If Description is NULL, then a <Description> string of "(NULL) Description" is printed. @param FileName The pointer to the name of the source file that generated the assert condition. @param LineNumber The line number in the source file that generated the assert condition @param Description The pointer to the description of the assert condition. **/ VOID EFIAPI DebugAssert ( IN CONST CHAR8 *FileName, IN UINTN LineNumber, IN CONST CHAR8 *Description ); /** Fills a target buffer with PcdDebugClearMemoryValue, and returns the target buffer. This function fills Length bytes of Buffer with the value specified by PcdDebugClearMemoryValue, and returns Buffer. If Buffer is NULL, then ASSERT(). If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). @param Buffer The pointer to the target buffer to be filled with PcdDebugClearMemoryValue. @param Length The number of bytes in Buffer to fill with zeros PcdDebugClearMemoryValue. @return Buffer The pointer to the target buffer filled with PcdDebugClearMemoryValue. **/ VOID * EFIAPI DebugClearMemory ( OUT VOID *Buffer, IN UINTN Length ); /** Returns TRUE if ASSERT() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set. Otherwise, FALSE is returned. @retval TRUE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set. @retval FALSE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear. **/ BOOLEAN EFIAPI DebugAssertEnabled ( VOID ); /** Returns TRUE if DEBUG() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is set. Otherwise, FALSE is returned. @retval TRUE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is set. @retval FALSE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is clear. **/ BOOLEAN EFIAPI DebugPrintEnabled ( VOID ); /** Returns TRUE if DEBUG_CODE() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set. Otherwise, FALSE is returned. @retval TRUE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set. @retval FALSE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is clear. **/ BOOLEAN EFIAPI DebugCodeEnabled ( VOID ); /** Returns TRUE if DEBUG_CLEAR_MEMORY() macro is enabled. This function returns TRUE if the DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is set. Otherwise, FALSE is returned. @retval TRUE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is set. @retval FALSE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is clear. **/ BOOLEAN EFIAPI DebugClearMemoryEnabled ( VOID ); /** Returns TRUE if any one of the bit is set both in ErrorLevel and PcdFixedDebugPrintErrorLevel. This function compares the bit mask of ErrorLevel and PcdFixedDebugPrintErrorLevel. @retval TRUE Current ErrorLevel is supported. @retval FALSE Current ErrorLevel is not supported. **/ BOOLEAN EFIAPI DebugPrintLevelEnabled ( IN CONST UINTN ErrorLevel ); /** Internal worker macro that calls DebugAssert(). This macro calls DebugAssert(), passing in the filename, line number, and an expression that evaluated to FALSE. @param Expression Boolean expression that evaluated to FALSE **/ #if defined(__clang__) && defined(__FILE_NAME__) #define _ASSERT(Expression) DebugAssert (__FILE_NAME__, __LINE__, #Expression) #else #define _ASSERT(Expression) DebugAssert (__FILE__, __LINE__, #Expression) #endif /** Internal worker macro that calls DebugPrint(). This macro calls DebugPrint() passing in the debug error level, a format string, and a variable argument list. __VA_ARGS__ is not supported by EBC compiler, Microsoft Visual Studio .NET 2003 and Microsoft Windows Server 2003 Driver Development Kit (Microsoft WINDDK) version 3790.1830. @param Expression Expression containing an error level, a format string, and a variable argument list based on the format string. **/ #if !defined(MDE_CPU_EBC) && (!defined (_MSC_VER) || _MSC_VER > 1400) #define _DEBUG_PRINT(PrintLevel, ...) \ do { \ if (DebugPrintLevelEnabled (PrintLevel)) { \ DebugPrint (PrintLevel, ##__VA_ARGS__); \ } \ } while (FALSE) #define _DEBUG(Expression) _DEBUG_PRINT Expression #else #define _DEBUG(Expression) DebugPrint Expression #endif /** Macro that calls DebugAssert() if an expression evaluates to FALSE. If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set, then this macro evaluates the Boolean expression specified by Expression. If Expression evaluates to FALSE, then DebugAssert() is called passing in the source filename, source line number, and Expression. @param Expression Boolean expression. **/ #if !defined(MDEPKG_NDEBUG) #define ASSERT(Expression) \ do { \ if (DebugAssertEnabled ()) { \ if (!(Expression)) { \ _ASSERT (Expression); \ ANALYZER_UNREACHABLE (); \ } \ } \ } while (FALSE) #else #define ASSERT(Expression) #endif /** Macro that calls DebugPrint(). If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is set, then this macro passes Expression to DebugPrint(). @param Expression Expression containing an error level, a format string, and a variable argument list based on the format string. **/ #if !defined(MDEPKG_NDEBUG) #define DEBUG(Expression) \ do { \ if (DebugPrintEnabled ()) { \ _DEBUG (Expression); \ } \ } while (FALSE) #else #define DEBUG(Expression) #endif /** Macro that calls DebugAssert() if an EFI_STATUS evaluates to an error code. If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set, then this macro evaluates the EFI_STATUS value specified by StatusParameter. If StatusParameter is an error code, then DebugAssert() is called passing in the source filename, source line number, and StatusParameter. @param StatusParameter EFI_STATUS value to evaluate. **/ #if !defined(MDEPKG_NDEBUG) #define ASSERT_EFI_ERROR(StatusParameter) \ do { \ if (DebugAssertEnabled ()) { \ if (EFI_ERROR (StatusParameter)) { \ DEBUG ((EFI_D_ERROR, "\nASSERT_EFI_ERROR (Status = %r)\n", StatusParameter)); \ _ASSERT (!EFI_ERROR (StatusParameter)); \ } \ } \ } while (FALSE) #else #define ASSERT_EFI_ERROR(StatusParameter) #endif /** Macro that calls DebugAssert() if a RETURN_STATUS evaluates to an error code. If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set, then this macro evaluates the RETURN_STATUS value specified by StatusParameter. If StatusParameter is an error code, then DebugAssert() is called passing in the source filename, source line number, and StatusParameter. @param StatusParameter RETURN_STATUS value to evaluate. **/ #if !defined(MDEPKG_NDEBUG) #define ASSERT_RETURN_ERROR(StatusParameter) \ do { \ if (DebugAssertEnabled ()) { \ if (RETURN_ERROR (StatusParameter)) { \ DEBUG ((DEBUG_ERROR, "\nASSERT_RETURN_ERROR (Status = %r)\n", \ StatusParameter)); \ _ASSERT (!RETURN_ERROR (StatusParameter)); \ } \ } \ } while (FALSE) #else #define ASSERT_RETURN_ERROR(StatusParameter) #endif /** Macro that calls DebugAssert() if a protocol is already installed in the handle database. If MDEPKG_NDEBUG is defined or the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear, then return. If Handle is NULL, then a check is made to see if the protocol specified by Guid is present on any handle in the handle database. If Handle is not NULL, then a check is made to see if the protocol specified by Guid is present on the handle specified by Handle. If the check finds the protocol, then DebugAssert() is called passing in the source filename, source line number, and Guid. If Guid is NULL, then ASSERT(). @param Handle The handle to check for the protocol. This is an optional parameter that may be NULL. If it is NULL, then the entire handle database is searched. @param Guid The pointer to a protocol GUID. **/ #if !defined(MDEPKG_NDEBUG) #define ASSERT_PROTOCOL_ALREADY_INSTALLED(Handle, Guid) \ do { \ if (DebugAssertEnabled ()) { \ VOID *Instance; \ ASSERT (Guid != NULL); \ if (Handle == NULL) { \ if (!EFI_ERROR (gBS->LocateProtocol ((EFI_GUID *)Guid, NULL, &Instance))) { \ _ASSERT (Guid already installed in database); \ } \ } else { \ if (!EFI_ERROR (gBS->HandleProtocol (Handle, (EFI_GUID *)Guid, &Instance))) { \ _ASSERT (Guid already installed on Handle); \ } \ } \ } \ } while (FALSE) #else #define ASSERT_PROTOCOL_ALREADY_INSTALLED(Handle, Guid) #endif /** Macro that marks the beginning of debug source code. If the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set, then this macro marks the beginning of source code that is included in a module. Otherwise, the source lines between DEBUG_CODE_BEGIN() and DEBUG_CODE_END() are not included in a module. **/ #define DEBUG_CODE_BEGIN() do { if (DebugCodeEnabled ()) { UINT8 __DebugCodeLocal /** The macro that marks the end of debug source code. If the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set, then this macro marks the end of source code that is included in a module. Otherwise, the source lines between DEBUG_CODE_BEGIN() and DEBUG_CODE_END() are not included in a module. **/ #define DEBUG_CODE_END() __DebugCodeLocal = 0; __DebugCodeLocal++; } } while (FALSE) /** The macro that declares a section of debug source code. If the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set, then the source code specified by Expression is included in a module. Otherwise, the source specified by Expression is not included in a module. **/ #define DEBUG_CODE(Expression) \ DEBUG_CODE_BEGIN (); \ Expression \ DEBUG_CODE_END () /** The macro that calls DebugClearMemory() to clear a buffer to a default value. If the DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is set, then this macro calls DebugClearMemory() passing in Address and Length. @param Address The pointer to a buffer. @param Length The number of bytes in the buffer to set. **/ #define DEBUG_CLEAR_MEMORY(Address, Length) \ do { \ if (DebugClearMemoryEnabled ()) { \ DebugClearMemory (Address, Length); \ } \ } while (FALSE) /** Macro that calls DebugAssert() if the containing record does not have a matching signature. If the signatures matches, then a pointer to the data structure that contains a specified field of that data structure is returned. This is a lightweight method hide information by placing a public data structure inside a larger private data structure and using a pointer to the public data structure to retrieve a pointer to the private data structure. If MDEPKG_NDEBUG is defined or the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear, then this macro computes the offset, in bytes, of the field specified by Field from the beginning of the data structure specified by TYPE. This offset is subtracted from Record, and is used to return a pointer to a data structure of the type specified by TYPE. If MDEPKG_NDEBUG is not defined and the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set, then this macro computes the offset, in bytes, of field specified by Field from the beginning of the data structure specified by TYPE. This offset is subtracted from Record, and is used to compute a pointer to a data structure of the type specified by TYPE. The Signature field of the data structure specified by TYPE is compared to TestSignature. If the signatures match, then a pointer to the pointer to a data structure of the type specified by TYPE is returned. If the signatures do not match, then DebugAssert() is called with a description of "CR has a bad signature" and Record is returned. If the data type specified by TYPE does not contain the field specified by Field, then the module will not compile. If TYPE does not contain a field called Signature, then the module will not compile. @param Record The pointer to the field specified by Field within a data structure of type TYPE. @param TYPE The name of the data structure type to return This data structure must contain the field specified by Field. @param Field The name of the field in the data structure specified by TYPE to which Record points. @param TestSignature The 32-bit signature value to match. **/ #if !defined(MDEPKG_NDEBUG) #define CR(Record, TYPE, Field, TestSignature) \ (DebugAssertEnabled () && (BASE_CR (Record, TYPE, Field)->Signature != TestSignature)) ? \ (TYPE *) (_ASSERT (CR has Bad Signature), Record) : \ BASE_CR (Record, TYPE, Field) #else #define CR(Record, TYPE, Field, TestSignature) \ BASE_CR (Record, TYPE, Field) #endif #endif
felixsinger/coreboot
src/vendorcode/intel/edk2/edk2-stable202005/MdePkg/Include/Library/DebugLib.h
C
gpl-2.0
21,986
<?php $langues = array( 'langue' => 'Ελληνικά', 'locale' => 'hellenic', 'addVirtual' => 'Προσθήκη ενός VirtualHost', 'backHome' => 'Επιστροφή στην Αρχική σελίδα', 'VirtualSubMenuOn' => 'Το αντικείμενο <code>υπομενού VirtualHost</code> πρέπει να τεθεί σε (Ανοιχτό) στις <code>Ρυθμίσεις Wamp</code> Μενού Δεξιού Κλικ. Μετά επαναφορτώστε αυτή τη σελίδα', 'UncommentInclude' => 'Αποσχολιάστε <small>(Σβήστε τη δίεση #)</small> τη γραμμή <code>#Include conf/extra/httpd-vhosts.conf</code><br>στο αρχείο %s', 'FileNotExists' => 'Το αρχείο <code>%s</code> δεν υπάρχει', 'FileNotWritable' => 'Το αρχείο <code>%s</code> δεν είναι εγγράψιμο', 'DirNotExists' => 'Το <code>%s</code> δεν υπάρχει ή δεν είναι φάκελος', 'NotCleaned' => 'Το αρχείο <code>%s</code> δεν εκκαθαρίστηκε.<br>Εκεί παραμένουν παραδείγματα VirtualHost όπως: dummy-host.example.com', 'NoVirtualHost' => 'Δεν έχει οριστεί VirtualHost στο <code>%s</code><br>Πρέπει να υπάρχει τουλάχιστον το VirtualHost για το localhost.', 'NoFirst' => 'Το πρώτο VirtualHost πρέπει να είναι το <code>localhost</code> στο αρχείο <code>%s</code>', 'ServerNameInvalid' => 'Το όνομα διακομιστή ServerName <code>%s</code> δεν είναι έγκυρο.', 'VirtualHostName' => 'Το όνομα του <code>Virtual Host</code> Όχι διακριτικοί χαρακτήρες (ecen) - Όχι κενό - Όχι κάτω παύλα (_)', 'VirtualHostFolder' => 'Πλήρης απόλυτη <code>διαδρομή</code> του <code>φακέλου</code> του VirtualHost <i>Παραδείγματα: C:/wamp/www/projet/ ή E:/www/site1/</i>', 'VirtualAlreadyExist' => 'Το όνομα διακοιστή ServerName <code>%s</code> υπάρχει ήδη', 'VirtualHostExists' => 'Το VirtualHost έχει ήδη οριστεί:', 'Start' => 'Έναρξη της δημιουργίας του VirtualHost (Ίσως διαρκέσει λίγο...)', 'GreenErrors' => 'Τα σφάλματα σε πράσινο πλαίσιο μπορούν να διορθωθούν αυτόματα.', 'Correct' => 'Έναρξη της αυτόματης διόρθωσης των σφαλμάτων εντός των πράσινων πλαισίων', 'NoModify' => 'Αδύνατη η αλλαγή των αρχείων <code>httpd-vhosts.conf</code> ή <code>hosts</code>', 'VirtualCreated' => 'Τα αρχεία έχουν αλλάξει. Το Virtual host <code>%s</code> δημιουργήθηκε', 'CommandMessage' => 'Μηνύματα από τη γραμμή εντολών για ενημέρωση του DNS:', 'However' => 'Μπορείτε να προσθέσετε ένα άλλο VirtualHost επικυρώνοντας το «Προσθήκη ενός VirtualHost».<br>Ωστόσο, για αυτά τα νέα VirtualHost που λαμβάνονται υπόψη από τον Apache, πρέπει να εκτελέσετε το αντικείμενο <br><code>Επανεκκίνηση DNS</code><br>από το μενού Εργαλείων Δεξιού Κλικ του εικονιδίου Wampmanager. <i>(Αυτό δυστυχώς δεν μπορεί να γίνει αυτόματα)</i>', ); ?>
cchin013/uecsite2017
wamplangues/add_vhost_hellenic.php
PHP
gpl-2.0
3,577
/* * SROM format definition. * * Copyright (C) 1999-2014, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: bcmsrom_fmt.h 427005 2013-10-02 00:15:10Z $ */ #ifndef _bcmsrom_fmt_h_ #define _bcmsrom_fmt_h_ #define SROM_MAXREV 11 /* max revisiton supported by driver */ /* Maximum srom: 6 Kilobits == 768 bytes */ #define SROM_MAX 768 #define SROM_MAXW 384 #define VARS_MAX 4096 /* PCI fields */ #define PCI_F0DEVID 48 #define SROM_WORDS 64 #define SROM3_SWRGN_OFF 28 /* s/w region offset in words */ #define SROM_SSID 2 #define SROM_SVID 3 #define SROM_WL1LHMAXP 29 #define SROM_WL1LPAB0 30 #define SROM_WL1LPAB1 31 #define SROM_WL1LPAB2 32 #define SROM_WL1HPAB0 33 #define SROM_WL1HPAB1 34 #define SROM_WL1HPAB2 35 #define SROM_MACHI_IL0 36 #define SROM_MACMID_IL0 37 #define SROM_MACLO_IL0 38 #define SROM_MACHI_ET0 39 #define SROM_MACMID_ET0 40 #define SROM_MACLO_ET0 41 #define SROM_MACHI_ET1 42 #define SROM_MACMID_ET1 43 #define SROM_MACLO_ET1 44 #define SROM3_MACHI 37 #define SROM3_MACMID 38 #define SROM3_MACLO 39 #define SROM_BXARSSI2G 40 #define SROM_BXARSSI5G 41 #define SROM_TRI52G 42 #define SROM_TRI5GHL 43 #define SROM_RXPO52G 45 #define SROM2_ENETPHY 45 #define SROM_AABREV 46 /* Fields in AABREV */ #define SROM_BR_MASK 0x00ff #define SROM_CC_MASK 0x0f00 #define SROM_CC_SHIFT 8 #define SROM_AA0_MASK 0x3000 #define SROM_AA0_SHIFT 12 #define SROM_AA1_MASK 0xc000 #define SROM_AA1_SHIFT 14 #define SROM_WL0PAB0 47 #define SROM_WL0PAB1 48 #define SROM_WL0PAB2 49 #define SROM_LEDBH10 50 #define SROM_LEDBH32 51 #define SROM_WL10MAXP 52 #define SROM_WL1PAB0 53 #define SROM_WL1PAB1 54 #define SROM_WL1PAB2 55 #define SROM_ITT 56 #define SROM_BFL 57 #define SROM_BFL2 28 #define SROM3_BFL2 61 #define SROM_AG10 58 #define SROM_CCODE 59 #define SROM_OPO 60 #define SROM3_LEDDC 62 #define SROM_CRCREV 63 /* SROM Rev 4: Reallocate the software part of the srom to accomodate * MIMO features. It assumes up to two PCIE functions and 440 bytes * of useable srom i.e. the useable storage in chips with OTP that * implements hardware redundancy. */ #define SROM4_WORDS 220 #define SROM4_SIGN 32 #define SROM4_SIGNATURE 0x5372 #define SROM4_BREV 33 #define SROM4_BFL0 34 #define SROM4_BFL1 35 #define SROM4_BFL2 36 #define SROM4_BFL3 37 #define SROM5_BFL0 37 #define SROM5_BFL1 38 #define SROM5_BFL2 39 #define SROM5_BFL3 40 #define SROM4_MACHI 38 #define SROM4_MACMID 39 #define SROM4_MACLO 40 #define SROM5_MACHI 41 #define SROM5_MACMID 42 #define SROM5_MACLO 43 #define SROM4_CCODE 41 #define SROM4_REGREV 42 #define SROM5_CCODE 34 #define SROM5_REGREV 35 #define SROM4_LEDBH10 43 #define SROM4_LEDBH32 44 #define SROM5_LEDBH10 59 #define SROM5_LEDBH32 60 #define SROM4_LEDDC 45 #define SROM5_LEDDC 45 #define SROM4_AA 46 #define SROM4_AA2G_MASK 0x00ff #define SROM4_AA2G_SHIFT 0 #define SROM4_AA5G_MASK 0xff00 #define SROM4_AA5G_SHIFT 8 #define SROM4_AG10 47 #define SROM4_AG32 48 #define SROM4_TXPID2G 49 #define SROM4_TXPID5G 51 #define SROM4_TXPID5GL 53 #define SROM4_TXPID5GH 55 #define SROM4_TXRXC 61 #define SROM4_TXCHAIN_MASK 0x000f #define SROM4_TXCHAIN_SHIFT 0 #define SROM4_RXCHAIN_MASK 0x00f0 #define SROM4_RXCHAIN_SHIFT 4 #define SROM4_SWITCH_MASK 0xff00 #define SROM4_SWITCH_SHIFT 8 /* Per-path fields */ #define MAX_PATH_SROM 4 #define SROM4_PATH0 64 #define SROM4_PATH1 87 #define SROM4_PATH2 110 #define SROM4_PATH3 133 #define SROM4_2G_ITT_MAXP 0 #define SROM4_2G_PA 1 #define SROM4_5G_ITT_MAXP 5 #define SROM4_5GLH_MAXP 6 #define SROM4_5G_PA 7 #define SROM4_5GL_PA 11 #define SROM4_5GH_PA 15 /* Fields in the ITT_MAXP and 5GLH_MAXP words */ #define B2G_MAXP_MASK 0xff #define B2G_ITT_SHIFT 8 #define B5G_MAXP_MASK 0xff #define B5G_ITT_SHIFT 8 #define B5GH_MAXP_MASK 0xff #define B5GL_MAXP_SHIFT 8 /* All the miriad power offsets */ #define SROM4_2G_CCKPO 156 #define SROM4_2G_OFDMPO 157 #define SROM4_5G_OFDMPO 159 #define SROM4_5GL_OFDMPO 161 #define SROM4_5GH_OFDMPO 163 #define SROM4_2G_MCSPO 165 #define SROM4_5G_MCSPO 173 #define SROM4_5GL_MCSPO 181 #define SROM4_5GH_MCSPO 189 #define SROM4_CDDPO 197 #define SROM4_STBCPO 198 #define SROM4_BW40PO 199 #define SROM4_BWDUPPO 200 #define SROM4_CRCREV 219 /* SROM Rev 8: Make space for a 48word hardware header for PCIe rev >= 6. * This is acombined srom for both MIMO and SISO boards, usable in * the .130 4Kilobit OTP with hardware redundancy. */ #define SROM8_SIGN 64 #define SROM8_BREV 65 #define SROM8_BFL0 66 #define SROM8_BFL1 67 #define SROM8_BFL2 68 #define SROM8_BFL3 69 #define SROM8_MACHI 70 #define SROM8_MACMID 71 #define SROM8_MACLO 72 #define SROM8_CCODE 73 #define SROM8_REGREV 74 #define SROM8_LEDBH10 75 #define SROM8_LEDBH32 76 #define SROM8_LEDDC 77 #define SROM8_AA 78 #define SROM8_AG10 79 #define SROM8_AG32 80 #define SROM8_TXRXC 81 #define SROM8_BXARSSI2G 82 #define SROM8_BXARSSI5G 83 #define SROM8_TRI52G 84 #define SROM8_TRI5GHL 85 #define SROM8_RXPO52G 86 #define SROM8_FEM2G 87 #define SROM8_FEM5G 88 #define SROM8_FEM_ANTSWLUT_MASK 0xf800 #define SROM8_FEM_ANTSWLUT_SHIFT 11 #define SROM8_FEM_TR_ISO_MASK 0x0700 #define SROM8_FEM_TR_ISO_SHIFT 8 #define SROM8_FEM_PDET_RANGE_MASK 0x00f8 #define SROM8_FEM_PDET_RANGE_SHIFT 3 #define SROM8_FEM_EXTPA_GAIN_MASK 0x0006 #define SROM8_FEM_EXTPA_GAIN_SHIFT 1 #define SROM8_FEM_TSSIPOS_MASK 0x0001 #define SROM8_FEM_TSSIPOS_SHIFT 0 #define SROM8_THERMAL 89 /* Temp sense related entries */ #define SROM8_MPWR_RAWTS 90 #define SROM8_TS_SLP_OPT_CORRX 91 /* FOC: freiquency offset correction, HWIQ: H/W IOCAL enable, IQSWP: IQ CAL swap disable */ #define SROM8_FOC_HWIQ_IQSWP 92 #define SROM8_EXTLNAGAIN 93 /* Temperature delta for PHY calibration */ #define SROM8_PHYCAL_TEMPDELTA 94 /* Measured power 1 & 2, 0-13 bits at offset 95, MSB 2 bits are unused for now. */ #define SROM8_MPWR_1_AND_2 95 /* Per-path offsets & fields */ #define SROM8_PATH0 96 #define SROM8_PATH1 112 #define SROM8_PATH2 128 #define SROM8_PATH3 144 #define SROM8_2G_ITT_MAXP 0 #define SROM8_2G_PA 1 #define SROM8_5G_ITT_MAXP 4 #define SROM8_5GLH_MAXP 5 #define SROM8_5G_PA 6 #define SROM8_5GL_PA 9 #define SROM8_5GH_PA 12 /* All the miriad power offsets */ #define SROM8_2G_CCKPO 160 #define SROM8_2G_OFDMPO 161 #define SROM8_5G_OFDMPO 163 #define SROM8_5GL_OFDMPO 165 #define SROM8_5GH_OFDMPO 167 #define SROM8_2G_MCSPO 169 #define SROM8_5G_MCSPO 177 #define SROM8_5GL_MCSPO 185 #define SROM8_5GH_MCSPO 193 #define SROM8_CDDPO 201 #define SROM8_STBCPO 202 #define SROM8_BW40PO 203 #define SROM8_BWDUPPO 204 /* SISO PA parameters are in the path0 spaces */ #define SROM8_SISO 96 /* Legacy names for SISO PA paramters */ #define SROM8_W0_ITTMAXP (SROM8_SISO + SROM8_2G_ITT_MAXP) #define SROM8_W0_PAB0 (SROM8_SISO + SROM8_2G_PA) #define SROM8_W0_PAB1 (SROM8_SISO + SROM8_2G_PA + 1) #define SROM8_W0_PAB2 (SROM8_SISO + SROM8_2G_PA + 2) #define SROM8_W1_ITTMAXP (SROM8_SISO + SROM8_5G_ITT_MAXP) #define SROM8_W1_MAXP_LCHC (SROM8_SISO + SROM8_5GLH_MAXP) #define SROM8_W1_PAB0 (SROM8_SISO + SROM8_5G_PA) #define SROM8_W1_PAB1 (SROM8_SISO + SROM8_5G_PA + 1) #define SROM8_W1_PAB2 (SROM8_SISO + SROM8_5G_PA + 2) #define SROM8_W1_PAB0_LC (SROM8_SISO + SROM8_5GL_PA) #define SROM8_W1_PAB1_LC (SROM8_SISO + SROM8_5GL_PA + 1) #define SROM8_W1_PAB2_LC (SROM8_SISO + SROM8_5GL_PA + 2) #define SROM8_W1_PAB0_HC (SROM8_SISO + SROM8_5GH_PA) #define SROM8_W1_PAB1_HC (SROM8_SISO + SROM8_5GH_PA + 1) #define SROM8_W1_PAB2_HC (SROM8_SISO + SROM8_5GH_PA + 2) #define SROM8_CRCREV 219 /* SROM REV 9 */ #define SROM9_2GPO_CCKBW20 160 #define SROM9_2GPO_CCKBW20UL 161 #define SROM9_2GPO_LOFDMBW20 162 #define SROM9_2GPO_LOFDMBW20UL 164 #define SROM9_5GLPO_LOFDMBW20 166 #define SROM9_5GLPO_LOFDMBW20UL 168 #define SROM9_5GMPO_LOFDMBW20 170 #define SROM9_5GMPO_LOFDMBW20UL 172 #define SROM9_5GHPO_LOFDMBW20 174 #define SROM9_5GHPO_LOFDMBW20UL 176 #define SROM9_2GPO_MCSBW20 178 #define SROM9_2GPO_MCSBW20UL 180 #define SROM9_2GPO_MCSBW40 182 #define SROM9_5GLPO_MCSBW20 184 #define SROM9_5GLPO_MCSBW20UL 186 #define SROM9_5GLPO_MCSBW40 188 #define SROM9_5GMPO_MCSBW20 190 #define SROM9_5GMPO_MCSBW20UL 192 #define SROM9_5GMPO_MCSBW40 194 #define SROM9_5GHPO_MCSBW20 196 #define SROM9_5GHPO_MCSBW20UL 198 #define SROM9_5GHPO_MCSBW40 200 #define SROM9_PO_MCS32 202 #define SROM9_PO_LOFDM40DUP 203 #define SROM8_RXGAINERR_2G 205 #define SROM8_RXGAINERR_5GL 206 #define SROM8_RXGAINERR_5GM 207 #define SROM8_RXGAINERR_5GH 208 #define SROM8_RXGAINERR_5GU 209 #define SROM8_SUBBAND_PPR 210 #define SROM8_PCIEINGRESS_WAR 211 #define SROM9_SAR 212 #define SROM8_NOISELVL_2G 213 #define SROM8_NOISELVL_5GL 214 #define SROM8_NOISELVL_5GM 215 #define SROM8_NOISELVL_5GH 216 #define SROM8_NOISELVL_5GU 217 #define SROM8_NOISECALOFFSET 218 #define SROM9_REV_CRC 219 #define SROM10_CCKPWROFFSET 218 #define SROM10_SIGN 219 #define SROM10_SWCTRLMAP_2G 220 #define SROM10_CRCREV 229 #define SROM10_WORDS 230 #define SROM10_SIGNATURE SROM4_SIGNATURE /* SROM REV 11 */ #define SROM11_BREV 65 #define SROM11_BFL0 66 #define SROM11_BFL1 67 #define SROM11_BFL2 68 #define SROM11_BFL3 69 #define SROM11_BFL4 70 #define SROM11_BFL5 71 #define SROM11_MACHI 72 #define SROM11_MACMID 73 #define SROM11_MACLO 74 #define SROM11_CCODE 75 #define SROM11_REGREV 76 #define SROM11_LEDBH10 77 #define SROM11_LEDBH32 78 #define SROM11_LEDDC 79 #define SROM11_AA 80 #define SROM11_AGBG10 81 #define SROM11_AGBG2A0 82 #define SROM11_AGA21 83 #define SROM11_TXRXC 84 #define SROM11_FEM_CFG1 85 #define SROM11_FEM_CFG2 86 /* Masks and offsets for FEM_CFG */ #define SROM11_FEMCTRL_MASK 0xf800 #define SROM11_FEMCTRL_SHIFT 11 #define SROM11_PAPDCAP_MASK 0x0400 #define SROM11_PAPDCAP_SHIFT 10 #define SROM11_TWORANGETSSI_MASK 0x0200 #define SROM11_TWORANGETSSI_SHIFT 9 #define SROM11_PDGAIN_MASK 0x01f0 #define SROM11_PDGAIN_SHIFT 4 #define SROM11_EPAGAIN_MASK 0x000e #define SROM11_EPAGAIN_SHIFT 1 #define SROM11_TSSIPOSSLOPE_MASK 0x0001 #define SROM11_TSSIPOSSLOPE_SHIFT 0 #define SROM11_GAINCTRLSPH_MASK 0xf800 #define SROM11_GAINCTRLSPH_SHIFT 11 #define SROM11_THERMAL 87 #define SROM11_MPWR_RAWTS 88 #define SROM11_TS_SLP_OPT_CORRX 89 #define SROM11_XTAL_FREQ 90 #define SROM11_5GB0_4080_W0_A1 91 #define SROM11_PHYCAL_TEMPDELTA 92 #define SROM11_MPWR_1_AND_2 93 #define SROM11_5GB0_4080_W1_A1 94 #define SROM11_TSSIFLOOR_2G 95 #define SROM11_TSSIFLOOR_5GL 96 #define SROM11_TSSIFLOOR_5GM 97 #define SROM11_TSSIFLOOR_5GH 98 #define SROM11_TSSIFLOOR_5GU 99 /* Masks and offsets for Terrmal parameters */ #define SROM11_TEMPS_PERIOD_MASK 0xf0 #define SROM11_TEMPS_PERIOD_SHIFT 4 #define SROM11_TEMPS_HYSTERESIS_MASK 0x0f #define SROM11_TEMPS_HYSTERESIS_SHIFT 0 #define SROM11_TEMPCORRX_MASK 0xfc #define SROM11_TEMPCORRX_SHIFT 2 #define SROM11_TEMPSENSE_OPTION_MASK 0x3 #define SROM11_TEMPSENSE_OPTION_SHIFT 0 #define SROM11_PDOFF_2G_40M_A0_MASK 0x000f #define SROM11_PDOFF_2G_40M_A0_SHIFT 0 #define SROM11_PDOFF_2G_40M_A1_MASK 0x00f0 #define SROM11_PDOFF_2G_40M_A1_SHIFT 4 #define SROM11_PDOFF_2G_40M_A2_MASK 0x0f00 #define SROM11_PDOFF_2G_40M_A2_SHIFT 8 #define SROM11_PDOFF_2G_40M_VALID_MASK 0x8000 #define SROM11_PDOFF_2G_40M_VALID_SHIFT 15 #define SROM11_PDOFF_2G_40M 100 #define SROM11_PDOFF_40M_A0 101 #define SROM11_PDOFF_40M_A1 102 #define SROM11_PDOFF_40M_A2 103 #define SROM11_5GB0_4080_W2_A1 103 #define SROM11_PDOFF_80M_A0 104 #define SROM11_PDOFF_80M_A1 105 #define SROM11_PDOFF_80M_A2 106 #define SROM11_5GB1_4080_W0_A1 106 #define SROM11_SUBBAND5GVER 107 /* Per-path fields and offset */ #define MAX_PATH_SROM_11 3 #define SROM11_PATH0 108 #define SROM11_PATH1 128 #define SROM11_PATH2 148 #define SROM11_2G_MAXP 0 #define SROM11_5GB1_4080_PA 0 #define SROM11_2G_PA 1 #define SROM11_5GB2_4080_PA 2 #define SROM11_RXGAINS1 4 #define SROM11_RXGAINS 5 #define SROM11_5GB3_4080_PA 5 #define SROM11_5GB1B0_MAXP 6 #define SROM11_5GB3B2_MAXP 7 #define SROM11_5GB0_PA 8 #define SROM11_5GB1_PA 11 #define SROM11_5GB2_PA 14 #define SROM11_5GB3_PA 17 /* Masks and offsets for rxgains */ #define SROM11_RXGAINS5GTRELNABYPA_MASK 0x8000 #define SROM11_RXGAINS5GTRELNABYPA_SHIFT 15 #define SROM11_RXGAINS5GTRISOA_MASK 0x7800 #define SROM11_RXGAINS5GTRISOA_SHIFT 11 #define SROM11_RXGAINS5GELNAGAINA_MASK 0x0700 #define SROM11_RXGAINS5GELNAGAINA_SHIFT 8 #define SROM11_RXGAINS2GTRELNABYPA_MASK 0x0080 #define SROM11_RXGAINS2GTRELNABYPA_SHIFT 7 #define SROM11_RXGAINS2GTRISOA_MASK 0x0078 #define SROM11_RXGAINS2GTRISOA_SHIFT 3 #define SROM11_RXGAINS2GELNAGAINA_MASK 0x0007 #define SROM11_RXGAINS2GELNAGAINA_SHIFT 0 #define SROM11_RXGAINS5GHTRELNABYPA_MASK 0x8000 #define SROM11_RXGAINS5GHTRELNABYPA_SHIFT 15 #define SROM11_RXGAINS5GHTRISOA_MASK 0x7800 #define SROM11_RXGAINS5GHTRISOA_SHIFT 11 #define SROM11_RXGAINS5GHELNAGAINA_MASK 0x0700 #define SROM11_RXGAINS5GHELNAGAINA_SHIFT 8 #define SROM11_RXGAINS5GMTRELNABYPA_MASK 0x0080 #define SROM11_RXGAINS5GMTRELNABYPA_SHIFT 7 #define SROM11_RXGAINS5GMTRISOA_MASK 0x0078 #define SROM11_RXGAINS5GMTRISOA_SHIFT 3 #define SROM11_RXGAINS5GMELNAGAINA_MASK 0x0007 #define SROM11_RXGAINS5GMELNAGAINA_SHIFT 0 /* Power per rate */ #define SROM11_CCKBW202GPO 168 #define SROM11_CCKBW20UL2GPO 169 #define SROM11_MCSBW202GPO 170 #define SROM11_MCSBW202GPO_1 171 #define SROM11_MCSBW402GPO 172 #define SROM11_MCSBW402GPO_1 173 #define SROM11_DOT11AGOFDMHRBW202GPO 174 #define SROM11_OFDMLRBW202GPO 175 #define SROM11_MCSBW205GLPO 176 #define SROM11_MCSBW205GLPO_1 177 #define SROM11_MCSBW405GLPO 178 #define SROM11_MCSBW405GLPO_1 179 #define SROM11_MCSBW805GLPO 180 #define SROM11_MCSBW805GLPO_1 181 #define SROM11_RPCAL_2G 182 #define SROM11_RPCAL_5GL 183 #define SROM11_MCSBW205GMPO 184 #define SROM11_MCSBW205GMPO_1 185 #define SROM11_MCSBW405GMPO 186 #define SROM11_MCSBW405GMPO_1 187 #define SROM11_MCSBW805GMPO 188 #define SROM11_MCSBW805GMPO_1 189 #define SROM11_RPCAL_5GM 190 #define SROM11_RPCAL_5GH 191 #define SROM11_MCSBW205GHPO 192 #define SROM11_MCSBW205GHPO_1 193 #define SROM11_MCSBW405GHPO 194 #define SROM11_MCSBW405GHPO_1 195 #define SROM11_MCSBW805GHPO 196 #define SROM11_MCSBW805GHPO_1 197 #define SROM11_RPCAL_5GU 198 #define SROM11_PDOFF_2G_CCK 199 #define SROM11_MCSLR5GLPO 200 #define SROM11_MCSLR5GMPO 201 #define SROM11_MCSLR5GHPO 202 #define SROM11_SB20IN40HRPO 203 #define SROM11_SB20IN80AND160HR5GLPO 204 #define SROM11_SB40AND80HR5GLPO 205 #define SROM11_SB20IN80AND160HR5GMPO 206 #define SROM11_SB40AND80HR5GMPO 207 #define SROM11_SB20IN80AND160HR5GHPO 208 #define SROM11_SB40AND80HR5GHPO 209 #define SROM11_SB20IN40LRPO 210 #define SROM11_SB20IN80AND160LR5GLPO 211 #define SROM11_SB40AND80LR5GLPO 212 #define SROM11_TXIDXCAP2G 212 #define SROM11_SB20IN80AND160LR5GMPO 213 #define SROM11_SB40AND80LR5GMPO 214 #define SROM11_TXIDXCAP5G 214 #define SROM11_SB20IN80AND160LR5GHPO 215 #define SROM11_SB40AND80LR5GHPO 216 #define SROM11_DOT11AGDUPHRPO 217 #define SROM11_DOT11AGDUPLRPO 218 /* MISC */ #define SROM11_PCIEINGRESS_WAR 220 #define SROM11_SAR 221 #define SROM11_NOISELVL_2G 222 #define SROM11_NOISELVL_5GL 223 #define SROM11_NOISELVL_5GM 224 #define SROM11_NOISELVL_5GH 225 #define SROM11_NOISELVL_5GU 226 #define SROM11_RXGAINERR_2G 227 #define SROM11_RXGAINERR_5GL 228 #define SROM11_RXGAINERR_5GM 229 #define SROM11_RXGAINERR_5GH 230 #define SROM11_RXGAINERR_5GU 231 #define SROM11_SIGN 64 #define SROM11_CRCREV 233 #define SROM11_WORDS 234 #define SROM11_SIGNATURE 0x0634 typedef struct { uint8 tssipos; /* TSSI positive slope, 1: positive, 0: negative */ uint8 extpagain; /* Ext PA gain-type: full-gain: 0, pa-lite: 1, no_pa: 2 */ uint8 pdetrange; /* support 32 combinations of different Pdet dynamic ranges */ uint8 triso; /* TR switch isolation */ uint8 antswctrllut; /* antswctrl lookup table configuration: 32 possible choices */ } srom_fem_t; #endif /* _bcmsrom_fmt_h_ */
davidmueller13/arter97_bb
drivers/net/wireless/bcmdhd/include/bcmsrom_fmt.h
C
gpl-2.0
17,360
//# LELLattCoordBase.h: The base letter class for lattice coordinates in LEL //# Copyright (C) 1998,1999,2000,2001 //# Associated Universities, Inc. Washington DC, USA. //# //# This library is free software; you can redistribute it and/or modify it //# under the terms of the GNU Library General Public License as published by //# the Free Software Foundation; either version 2 of the License, or (at your //# option) any later version. //# //# This library is distributed in the hope that it will be useful, but WITHOUT //# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or //# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public //# License for more details. //# //# You should have received a copy of the GNU Library General Public License //# along with this library; if not, write to the Free Software Foundation, //# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. //# //# Correspondence concerning AIPS++ should be addressed as follows: //# Internet email: [email protected]. //# Postal address: AIPS++ Project Office //# National Radio Astronomy Observatory //# 520 Edgemont Road //# Charlottesville, VA 22903-2475 USA //# //# $Id$ #ifndef LATTICES_LELLATTCOORDBASE_H #define LATTICES_LELLATTCOORDBASE_H //# Includes #include <casacore/casa/aips.h> #include <casacore/casa/BasicSL/String.h> namespace casacore { //# NAMESPACE CASACORE - BEGIN //# Forward Declarations class LELImageCoord; class IPosition; template<class T> class Vector; // <summary> // The base letter class for lattice coordinates in LEL. // </summary> // <use visibility=local> // <reviewed reviewer="Bob Garwood" date="2000/01/25" tests="tLatticeExpr"> // </reviewed> // <prerequisite> // <li> <linkto class="Lattice"> Lattice</linkto> // <li> <linkto class="LELCoordinates"> LELCoordinates</linkto> // </prerequisite> // <synopsis> // This abstract base class is the basic letter for the envelope class // <linkto class=LELCoordinates>LELCoordinates</linkto>. // It does not do anything, but makes it possible that derived classes // (like <linkto class=LELLattCoord>LELLattCoord</linkto> and // <linkto class=LELImageCoord>LELImageCoord</linkto>) // implement their own behaviour. // </synopsis> // <motivation> // It must be possible to handle image coordinates in a lattice // expression. // </motivation> //# <todo asof="1998/01/31"> //# <li> //# </todo> class LELLattCoordBase { public: LELLattCoordBase() {}; // A virtual destructor is needed so that it will use the actual // destructor in the derived class. virtual ~LELLattCoordBase(); // Does the class have true coordinates? virtual Bool hasCoordinates() const = 0; // The name of the class. virtual String classname() const = 0; // Get the coordinates of the spectral axis for the given shape. // It returns the pixel axis number of the spectral coordinates. // -1 indicates that there is no pixel spectral axis. // An exception is thrown if there are no world spectral coordinates. virtual uInt getSpectralInfo (Vector<Double>& worldCoordinates, const IPosition& shape) const = 0; // Check how the coordinates of this and that compare. virtual Int compare (const LELLattCoordBase& other) const = 0; // Check how the coordinates of this and that image compare. // This function is used by <src>conform</src> to make a // double virtual dispatch possible. virtual Int doCompare (const LELImageCoord& other) const = 0; }; } //# NAMESPACE CASACORE - END #endif
bmerry/casacore
lattices/LEL/LELLattCoordBase.h
C
gpl-2.0
3,656
html, body{height:100%;} .mceContentBody{height:100%;min-width:90%;padding:5px;} body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; margin:8px;} body {background:#FFF;} body.mceContentReset {background: #FFFFFF none !important; color:#000000 !important; text-align:left !important;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table, img, hr, .mceItemAnchor {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important} *[contentEditable]:focus {outline:0} img::selection { background: #b4d4ff !important; } /** bookmark **/ span[data-mce-type="bookmark"] {font-size: 0;} pre.mcePreformatted {margin:0;padding:0;}
sdc/DevonStudioSchool
components/com_jce/editor/tiny_mce/themes/advanced/skins/default/content.css
CSS
gpl-2.0
1,395
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/system.h" #include "common/textconsole.h" #include "audio/audiostream.h" #include "audio/decoders/raw.h" #include "audio/decoders/wave.h" #include "graphics/palette.h" #include "graphics/surface.h" #include "tucker/tucker.h" #include "tucker/graphics.h" namespace Tucker { void TuckerEngine::handleIntroSequence() { const int firstSequence = (_gameFlags & kGameFlagDemo) != 0 ? kFirstAnimationSequenceDemo : kFirstAnimationSequenceGame; _player = new AnimationSequencePlayer(_system, _mixer, _eventMan, &_compressedSound, firstSequence); _player->mainLoop(); delete _player; _player = 0; } void TuckerEngine::handleCreditsSequence() { static const int _creditsSequenceTimecounts[] = { 200, 350, 650, 850, 1150, 1450, 12000 }; static const int _creditsSequenceSpriteCounts[] = { 1, 1, 5, 0, 6, 6, 0 }; int counter4 = 0; int counter3 = 0; int num = 0; int imgNum = 0; int prevLocationNum = _locationNum; int counter2 = 0; int counter1 = 0; loadCharset2(); stopSounds(); _locationNum = 74; _flagsTable[236] = 74; uint8 *imgBuf = (uint8 *)malloc(16 * 64000); loadSprC02_01(); clearSprites(); _spritesCount = _creditsSequenceSpriteCounts[num]; loadFile("credits.txt", _ptTextBuf); loadImage("loc74.pcx", _quadBackgroundGfxBuf, 1); startSpeechSound(9001, 120); _timerCounter2 = 0; _fadePaletteCounter = 0; do { if (_fadePaletteCounter < 16) { fadeOutPalette(); ++_fadePaletteCounter; } if (counter4 + 20 > _creditsSequenceTimecounts[num]) { fadeInPalette(); } ++imgNum; if (imgNum == 16) { imgNum = 0; } if (num < 6) { Graphics::copyRect(_locationBackgroundGfxBuf, 640, _quadBackgroundGfxBuf, 320, 320, 200); } else { Graphics::copyRect(_locationBackgroundGfxBuf, 640, imgBuf + imgNum * 64000, 320, 320, 200); static const int yPosTable[] = { 48, 60, 80, 92, 104, 116 }; for (int i = 0; i < 6; ++i) { drawCreditsString(5, yPosTable[i], counter2 * 6 + i); } ++counter1; if (counter1 < 20) { fadePaletteColor(191, kFadePaletteStep); } else if (counter1 > 106) { fadePaletteColor(191, -kFadePaletteStep); } if (counter1 > 116) { counter1 = 0; ++counter2; if (counter2 > 17) { counter2 = 0; } } } _fullRedraw = true; ++counter3; if (counter3 == 2) { counter3 = 0; updateSprites(); } for (int i = 0; i < _spritesCount; ++i) { drawSprite(i); } redrawScreen(0); waitForTimer(3); counter4 = _timerCounter2 / 3; if (counter4 == _creditsSequenceTimecounts[num]) { _fadePaletteCounter = 0; clearSprites(); ++num; Common::String filename; if (num == 6) { for (int i = 0; i < 16; ++i) { filename = Common::String::format("cogs%04d.pcx", i + 1); loadImage(filename.c_str(), imgBuf + i * 64000, 2); } } else { switch (num) { case 1: filename = "loc75.pcx"; break; case 2: filename = "loc76.pcx"; break; case 3: filename = "paper-3.pcx"; break; case 4: filename = "loc77.pcx"; break; case 5: filename = "loc78.pcx"; break; } loadImage(filename.c_str(), _quadBackgroundGfxBuf, 2); } _spritesCount = _creditsSequenceSpriteCounts[num]; ++_flagsTable[236]; } } while (!_quitGame && isSpeechSoundPlaying()); free(imgBuf); _locationNum = prevLocationNum; do { if (_fadePaletteCounter > 0) { fadeInPalette(); --_fadePaletteCounter; } redrawScreen(0); waitForTimer(2); } while (_fadePaletteCounter > 0); } void TuckerEngine::handleCongratulationsSequence() { _timerCounter2 = 0; _fadePaletteCounter = 0; stopSounds(); loadImage("congrat.pcx", _loadTempBuf, 1); Graphics::copyRect(_locationBackgroundGfxBuf, 640, _loadTempBuf, 320, 320, 200); _fullRedraw = true; redrawScreen(0); while (!_quitGame && _timerCounter2 < 450) { while (_fadePaletteCounter < 14) { ++_fadePaletteCounter; fadeOutPalette(); } waitForTimer(3); } } void TuckerEngine::handleNewPartSequence() { char filename[40]; stopSounds(); if (_flagsTable[219] == 1) { _flagsTable[219] = 0; for (int i = 0; i < 50; ++i) { _inventoryItemsState[i] = 0; } _inventoryObjectsOffset = 0; _inventoryObjectsCount = 0; addObjectToInventory(30); if (_partNum == 1 || _partNum == 3) { addObjectToInventory(1); addObjectToInventory(0); } _redrawPanelItemsCounter = 0; } _scrollOffset = 0; switch (_partNum) { case 1: strcpy(filename, "pt1bak.pcx"); break; case 2: strcpy(filename, "pt2bak.pcx"); break; default: strcpy(filename, "pt3bak.pcx"); break; } loadImage(filename, _quadBackgroundGfxBuf, 1); _spritesCount = 1; clearSprites(); int currentLocation = _locationNum; _locationNum = 98; unloadSprA02_01(); unloadSprC02_01(); switch (_partNum) { case 1: strcpy(filename, "sprites/partone.spr"); break; case 2: strcpy(filename, "sprites/parttwo.spr"); break; default: strcpy(filename, "sprites/partthr.spr"); break; } _sprC02Table[1] = loadFile(filename, 0); startSpeechSound(9000, 60); _fadePaletteCounter = 0; do { if (_fadePaletteCounter < 16) { fadeOutPalette(); ++_fadePaletteCounter; } Graphics::copyRect(_locationBackgroundGfxBuf, 640, _quadBackgroundGfxBuf, 320, 320, 200); _fullRedraw = true; updateSprites(); drawSprite(0); redrawScreen(0); waitForTimer(3); if (_inputKeys[kInputKeyEscape]) { _inputKeys[kInputKeyEscape] = false; break; } } while (isSpeechSoundPlaying()); stopSpeechSound(); do { if (_fadePaletteCounter > 0) { fadeInPalette(); --_fadePaletteCounter; } Graphics::copyRect(_locationBackgroundGfxBuf, 640, _quadBackgroundGfxBuf, 320, 320, 200); _fullRedraw = true; updateSprites(); drawSprite(0); redrawScreen(0); waitForTimer(3); } while (_fadePaletteCounter > 0); _locationNum = currentLocation; } void TuckerEngine::handleMeanwhileSequence() { char filename[40]; uint8 backupPalette[256 * 3]; memcpy(backupPalette, _currentPalette, 256 * 3); switch (_partNum) { case 1: strcpy(filename, "meanw01.pcx"); break; case 2: strcpy(filename, "meanw02.pcx"); break; default: strcpy(filename, "meanw03.pcx"); break; } if (_flagsTable[215] == 0 && _flagsTable[231] == 1) { strcpy(filename, "loc80.pcx"); } loadImage(filename, _quadBackgroundGfxBuf + 89600, 1); _fadePaletteCounter = 0; for (int i = 0; i < 60; ++i) { if (_fadePaletteCounter < 16) { fadeOutPalette(); ++_fadePaletteCounter; } Graphics::copyRect(_locationBackgroundGfxBuf, 640, _quadBackgroundGfxBuf + 89600, 320, 320, 200); _fullRedraw = true; redrawScreen(0); waitForTimer(3); ++i; } do { if (_fadePaletteCounter > 0) { fadeInPalette(); --_fadePaletteCounter; } Graphics::copyRect(_locationBackgroundGfxBuf, 640, _quadBackgroundGfxBuf + 89600, 320, 320, 200); _fullRedraw = true; redrawScreen(0); waitForTimer(3); } while (_fadePaletteCounter > 0); memcpy(_currentPalette, backupPalette, 256 * 3); _fullRedraw = true; } void TuckerEngine::handleMapSequence() { loadImage("map2.pcx", _quadBackgroundGfxBuf + 89600, 0); loadImage("map1.pcx", _loadTempBuf, 1); _selectedObject.locationObject_locationNum = 0; if (_flagsTable[7] > 0) { copyMapRect(0, 0, 140, 86); } if (_flagsTable[7] > 1) { copyMapRect(0, 60, 122, 120); } if (_flagsTable[7] > 2) { copyMapRect(122, 114, 97, 86); } if (_flagsTable[7] == 4) { copyMapRect(140, 0, 88, 125); } if (_flagsTable[120] == 1) { copyMapRect(220, 0, 100, 180); } _fadePaletteCounter = 0; int xPos = 0, yPos = 0, textNum = 0; while (!_quitGame) { waitForTimer(2); updateMouseState(); Graphics::copyRect(_locationBackgroundGfxBuf + _scrollOffset, 640, _quadBackgroundGfxBuf + 89600, 320, 320, 200); _fullRedraw = true; if (_flagsTable[7] > 0 && _mousePosX > 30 && _mousePosX < 86 && _mousePosY > 36 && _mousePosY < 86) { textNum = 13; _nextLocationNum = (_partNum == 1) ? 3 : 65; xPos = 620; yPos = 130; } else if (_flagsTable[7] > 1 && _mousePosX > 60 && _mousePosX < 120 && _mousePosY > 120 && _mousePosY < 170) { textNum = 14; _nextLocationNum = (_partNum == 1) ? 9 : 66; xPos = 344; yPos = 120; } else if (_flagsTable[7] > 2 && _mousePosX > 160 && _mousePosX < 210 && _mousePosY > 110 && _mousePosY < 160) { textNum = 15; _nextLocationNum = (_partNum == 1) ? 16 : 61; xPos = 590; yPos = 130; } else if ((_flagsTable[7] == 4 || _flagsTable[7] == 6) && _mousePosX > 150 && _mousePosX < 200 && _mousePosY > 20 && _mousePosY < 70) { textNum = 16; _nextLocationNum = (_partNum == 1) ? 20 : 68; xPos = 20; yPos = 130; } else if (_flagsTable[120] == 1 && _mousePosX > 240 && _mousePosX < 290 && _mousePosY > 35 && _mousePosY < 90) { textNum = 17; _nextLocationNum = (_partNum == 1) ? 19 : 62; xPos = 20; yPos = 124; } else if (_mousePosX > 135 && _mousePosX < 185 && _mousePosY > 170 && _mousePosY < 200) { textNum = 18; _nextLocationNum = _locationNum; if (!_noPositionChangeAfterMap) { xPos = _xPosCurrent; yPos = _yPosCurrent; } else if (_locationNum == 3 || _locationNum == 65) { xPos = 620; yPos = 130; } else if (_locationNum == 9 || _locationNum == 66) { xPos = 344; yPos = 120; } else if (_locationNum == 16 || _locationNum == 61) { xPos = 590; yPos = 130; } else if (_locationNum == 20 || _locationNum == 68) { xPos = 20; yPos = 130; } else { xPos = 20; yPos = 124; } } if (textNum > 0) { drawSpeechText(_scrollOffset + _mousePosX + 8, _mousePosY - 10, _infoBarBuf, textNum, 96); } redrawScreen(_scrollOffset); if (_fadePaletteCounter < 14) { fadeOutPalette(); ++_fadePaletteCounter; } if (_leftMouseButtonPressed && textNum != 0) { break; } } while (_fadePaletteCounter > 0) { fadeInPalette(); redrawScreen(_scrollOffset); --_fadePaletteCounter; } _mouseClick = 1; if (_nextLocationNum == 9 && _noPositionChangeAfterMap) { _backgroundSpriteCurrentAnimation = 2; _backgroundSpriteCurrentFrame = 0; setCursorType(2); } else if (_nextLocationNum == 66 && _noPositionChangeAfterMap) { _backgroundSpriteCurrentAnimation = 1; _backgroundSpriteCurrentFrame = 0; setCursorType(2); } _noPositionChangeAfterMap = false; _xPosCurrent = xPos; _yPosCurrent = yPos; } void TuckerEngine::copyMapRect(int x, int y, int w, int h) { const uint8 *src = _loadTempBuf + y * 320 + x; uint8 *dst = _quadBackgroundGfxBuf + 89600 + y * 320 + x; for (int i = 0; i < h; ++i) { memcpy(dst, src, w); src += 320; dst += 320; } } int TuckerEngine::handleSpecialObjectSelectionSequence() { char filename[40]; if (_partNum == 1 && _selectedObjectNum == 6) { strcpy(filename, "news1.pcx"); _flagsTable[7] = 4; } else if (_partNum == 3 && _selectedObjectNum == 45) { strcpy(filename, "profnote.pcx"); } else if (_partNum == 1 && _selectedObjectNum == 26) { strcpy(filename, "photo.pcx"); } else if (_partNum == 3 && _selectedObjectNum == 39) { strcpy(filename, "news2.pcx"); _flagsTable[135] = 1; } else if (_currentInfoString1SourceType == 0 && _currentActionObj1Num == 259) { strcpy(filename, "postit.pcx"); } else if (_currentInfoString1SourceType == 1 && _currentActionObj1Num == 91) { strcpy(filename, "memo.pcx"); } else { return 0; } while (_fadePaletteCounter > 0) { fadeInPalette(); redrawScreen(_scrollOffset); --_fadePaletteCounter; } _mouseClick = 1; loadImage(filename, _quadBackgroundGfxBuf, 1); _fadePaletteCounter = 0; while (!_quitGame) { waitForTimer(2); updateMouseState(); Graphics::copyRect(_locationBackgroundGfxBuf + _scrollOffset, 640, _quadBackgroundGfxBuf, 320, 320, 200); _fullRedraw = true; if (_fadePaletteCounter < 14) { fadeOutPalette(); ++_fadePaletteCounter; } if (!_leftMouseButtonPressed && _mouseClick == 1) { _mouseClick = 0; } if (_partNum == 3 && _selectedObjectNum == 45) { for (int i = 0; i < 13; ++i) { const int offset = _dataTable[204 + i].yDest * 640 + _dataTable[204 + i].xDest; static const int itemsTable[] = { 15, 44, 25, 19, 21, 24, 12, 27, 20, 29, 35, 23, 3 }; if (_inventoryItemsState[itemsTable[i]] > 1) { Graphics::decodeRLE(_locationBackgroundGfxBuf + _scrollOffset + offset, _data3GfxBuf + _dataTable[204 + i].sourceOffset, _dataTable[204 + i].xSize, _dataTable[204 + i].ySize); } } } redrawScreen(_scrollOffset); if (_leftMouseButtonPressed && _mouseClick != 1) { while (_fadePaletteCounter > 0) { fadeInPalette(); redrawScreen(_scrollOffset); --_fadePaletteCounter; } _mouseClick = 1; break; } } loadLoc(); return 1; } AnimationSequencePlayer::AnimationSequencePlayer(OSystem *system, Audio::Mixer *mixer, Common::EventManager *event, CompressedSound *sound, int num) : _system(system), _mixer(mixer), _event(event), _compressedSound(sound), _seqNum(num) { memset(_animationPalette, 0, sizeof(_animationPalette)); _soundSeqDataCount = 0; _soundSeqDataIndex = 0; _soundSeqData = 0; _offscreenBuffer = (uint8 *)malloc(kScreenWidth * kScreenHeight); _updateScreenWidth = 0; _updateScreenPicture = false; _picBufPtr = _pic2BufPtr = 0; } AnimationSequencePlayer::~AnimationSequencePlayer() { unloadAnimation(); free(_offscreenBuffer); } void AnimationSequencePlayer::mainLoop() { static const SequenceUpdateFunc _demoSeqUpdateFuncs[] = { { 13, 2, &AnimationSequencePlayer::loadIntroSeq13_14, &AnimationSequencePlayer::playIntroSeq13_14 }, { 15, 2, &AnimationSequencePlayer::loadIntroSeq15_16, &AnimationSequencePlayer::playIntroSeq15_16 }, { 27, 2, &AnimationSequencePlayer::loadIntroSeq27_28, &AnimationSequencePlayer::playIntroSeq27_28 }, { 1, 0, 0, 0 } }; static const SequenceUpdateFunc _gameSeqUpdateFuncs[] = { { 17, 1, &AnimationSequencePlayer::loadIntroSeq17_18, &AnimationSequencePlayer::playIntroSeq17_18 }, { 19, 1, &AnimationSequencePlayer::loadIntroSeq19_20, &AnimationSequencePlayer::playIntroSeq19_20 }, { 3, 2, &AnimationSequencePlayer::loadIntroSeq3_4, &AnimationSequencePlayer::playIntroSeq3_4 }, { 9, 2, &AnimationSequencePlayer::loadIntroSeq9_10, &AnimationSequencePlayer::playIntroSeq9_10 }, { 21, 2, &AnimationSequencePlayer::loadIntroSeq21_22, &AnimationSequencePlayer::playIntroSeq21_22 }, { 1, 0, 0, 0 } }; switch (_seqNum) { case kFirstAnimationSequenceDemo: _updateFunc = _demoSeqUpdateFuncs; break; case kFirstAnimationSequenceGame: _updateFunc = _gameSeqUpdateFuncs; break; } _updateFuncIndex = 0; _changeToNextSequence = true; do { if (_changeToNextSequence) { _changeToNextSequence = false; _frameCounter = 0; _lastFrameTime = _system->getMillis(); _frameTime = this->_updateFunc[_updateFuncIndex].frameTime; (this->*(_updateFunc[_updateFuncIndex].load))(); if (_seqNum == 1) { break; } // budttle2.flc is shorter in french version ; start the background music // earlier and skip any sounds effects if (_seqNum == 19 && _flicPlayer[0].getFrameCount() == 126) { _soundSeqDataIndex = 6; _frameCounter = 80; } } (this->*(_updateFunc[_updateFuncIndex].play))(); if (_changeToNextSequence) { unloadAnimation(); ++_updateFuncIndex; _seqNum = this->_updateFunc[_updateFuncIndex].num; } else { updateSounds(); } _system->copyRectToScreen(_offscreenBuffer, kScreenWidth, 0, 0, kScreenWidth, kScreenHeight); _system->getPaletteManager()->setPalette(_animationPalette, 0, 256); _system->updateScreen(); syncTime(); } while (_seqNum != 1); } void AnimationSequencePlayer::syncTime() { uint32 end = _lastFrameTime + kSequenceFrameTime * _frameTime; do { Common::Event ev; while (_event->pollEvent(ev)) { switch (ev.type) { case Common::EVENT_KEYDOWN: if (ev.kbd.keycode == Common::KEYCODE_ESCAPE) { _seqNum = 1; } break; case Common::EVENT_QUIT: case Common::EVENT_RTL: _seqNum = 1; break; default: break; } } _system->delayMillis(10); _lastFrameTime = _system->getMillis(); } while (_lastFrameTime <= end); } Audio::RewindableAudioStream *AnimationSequencePlayer::loadSound(int index, AnimationSoundType type) { Audio::RewindableAudioStream *stream = _compressedSound->load(kSoundTypeIntro, index); if (stream) return stream; Common::String fileName = Common::String::format("audio/%s", _audioFileNamesTable[index]); Common::File f; if (f.open(fileName)) { int size = 0, rate = 0; uint8 flags = 0; switch (type) { case kAnimationSoundType8BitsRAW: case kAnimationSoundType16BitsRAW: size = f.size(); rate = 22050; flags = Audio::FLAG_UNSIGNED; if (type == kAnimationSoundType16BitsRAW) flags = Audio::FLAG_LITTLE_ENDIAN | Audio::FLAG_16BITS; if (size != 0) { uint8 *sampleData = (uint8 *)malloc(size); if (sampleData) { f.read(sampleData, size); stream = Audio::makeRawStream(sampleData, size, rate, flags); } } break; case kAnimationSoundTypeWAV: stream = Audio::makeWAVStream(&f, DisposeAfterUse::NO); break; } } return stream; } void AnimationSequencePlayer::loadSounds(int num) { if (_soundSeqDataList[num].musicVolume != 0) { Audio::AudioStream *s; if ((s = loadSound(_soundSeqDataList[num].musicIndex, kAnimationSoundType8BitsRAW)) != 0) { _mixer->playStream(Audio::Mixer::kMusicSoundType, &_musicHandle, s, -1, scaleMixerVolume(_soundSeqDataList[num].musicVolume)); } } _soundSeqDataIndex = 0; _soundSeqDataCount = _soundSeqDataList[num].soundSeqDataCount; _soundSeqData = _soundSeqDataList[num].soundSeqData; } void AnimationSequencePlayer::updateSounds() { Audio::RewindableAudioStream *s = 0; const SoundSequenceData *p = &_soundSeqData[_soundSeqDataIndex]; while (_soundSeqDataIndex < _soundSeqDataCount && p->timestamp <= _frameCounter) { switch (p->opcode) { case 0: if ((s = loadSound(p->num, kAnimationSoundTypeWAV)) != 0) { _mixer->playStream(Audio::Mixer::kSFXSoundType, &_soundsHandle[p->index], s, -1, scaleMixerVolume(p->volume)); } break; case 1: if ((s = loadSound(p->num, kAnimationSoundTypeWAV)) != 0) { _mixer->playStream(Audio::Mixer::kSFXSoundType, &_soundsHandle[p->index], Audio::makeLoopingAudioStream(s, 0), -1, scaleMixerVolume(p->volume)); } break; case 2: _mixer->stopHandle(_soundsHandle[p->index]); break; case 3: _mixer->stopHandle(_musicHandle); break; case 4: _mixer->stopHandle(_musicHandle); if ((s = loadSound(p->num, kAnimationSoundType8BitsRAW)) != 0) { _mixer->playStream(Audio::Mixer::kMusicSoundType, &_musicHandle, s, -1, scaleMixerVolume(p->volume)); } break; case 5: if ((s = loadSound(p->num, kAnimationSoundTypeWAV)) != 0) { _mixer->playStream(Audio::Mixer::kSFXSoundType, &_sfxHandle, s, -1, scaleMixerVolume(p->volume)); } break; case 6: _mixer->stopHandle(_musicHandle); if ((s = loadSound(p->num, kAnimationSoundType16BitsRAW)) != 0) { _mixer->playStream(Audio::Mixer::kMusicSoundType, &_musicHandle, s, -1, scaleMixerVolume(p->volume)); } break; default: warning("Unhandled sound opcode %d (%d,%d)", p->opcode, _frameCounter, p->timestamp); break; } ++p; ++_soundSeqDataIndex; } } void AnimationSequencePlayer::fadeInPalette() { uint8 paletteBuffer[256 * 3]; memset(paletteBuffer, 0, sizeof(paletteBuffer)); bool fadeColors = true; for (int step = 0; step < 64; ++step) { if (fadeColors) { fadeColors = false; for (int i = 0; i < 3*256; ++i) { if (paletteBuffer[i] < _animationPalette[i]) { const int color = paletteBuffer[i] + 4; paletteBuffer[i] = MIN<int>(color, _animationPalette[i]); fadeColors = true; } } _system->getPaletteManager()->setPalette(paletteBuffer, 0, 256); _system->updateScreen(); } _system->delayMillis(1000 / 60); } } void AnimationSequencePlayer::fadeOutPalette() { uint8 paletteBuffer[256 * 3]; memcpy(paletteBuffer, _animationPalette, 3*256); bool fadeColors = true; for (int step = 0; step < 64; ++step) { if (fadeColors) { fadeColors = false; for (int i = 0; i < 3*256; ++i) { if (paletteBuffer[i] > 0) { const int color = paletteBuffer[i] - 4; paletteBuffer[i] = MAX<int>(0, color); fadeColors = true; } } _system->getPaletteManager()->setPalette(paletteBuffer, 0, 256); _system->updateScreen(); } _system->delayMillis(1000 / 60); } _system->fillScreen(0); } void AnimationSequencePlayer::unloadAnimation() { _mixer->stopAll(); free(_picBufPtr); _picBufPtr = 0; free(_pic2BufPtr); _pic2BufPtr = 0; } uint8 *AnimationSequencePlayer::loadPicture(const char *fileName) { uint8 *p = 0; Common::File f; if (f.open(fileName)) { const int sz = f.size(); p = (uint8 *)malloc(sz); if (p) { f.read(p, sz); } } return p; } void AnimationSequencePlayer::getRGBPalette(int index) { memcpy(_animationPalette, _flicPlayer[index].getPalette(), 3 * 256); } void AnimationSequencePlayer::openAnimation(int index, const char *fileName) { if (!_flicPlayer[index].loadFile(fileName)) { warning("Unable to open flc animation file '%s'", fileName); _seqNum = 1; return; } _flicPlayer[index].start(); _flicPlayer[index].decodeNextFrame(); if (index == 0) { getRGBPalette(index); _flicPlayer[index].copyDirtyRectsToBuffer(_offscreenBuffer, kScreenWidth); } } bool AnimationSequencePlayer::decodeNextAnimationFrame(int index, bool copyDirtyRects) { const ::Graphics::Surface *surface = _flicPlayer[index].decodeNextFrame(); if (!copyDirtyRects) { for (uint16 y = 0; (y < surface->h) && (y < kScreenHeight); y++) memcpy(_offscreenBuffer + y * kScreenWidth, (byte *)surface->pixels + y * surface->pitch, surface->w); } else { _flicPlayer[index].copyDirtyRectsToBuffer(_offscreenBuffer, kScreenWidth); } ++_frameCounter; if (index == 0 && _flicPlayer[index].hasDirtyPalette()) getRGBPalette(index); return !_flicPlayer[index].endOfVideo(); } void AnimationSequencePlayer::loadIntroSeq17_18() { loadSounds(kSoundsList_Seq17_18); openAnimation(0, "graphics/merit.flc"); } void AnimationSequencePlayer::playIntroSeq17_18() { if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } void AnimationSequencePlayer::loadIntroSeq19_20() { fadeOutPalette(); loadSounds(kSoundsList_Seq19_20); openAnimation(0, "graphics/budttle2.flc"); openAnimation(1, "graphics/machine.flc"); } void AnimationSequencePlayer::playIntroSeq19_20() { // The intro credits animation. This uses 2 animations: the foreground one, which // is the actual intro credits, and the background one, which is an animation of // cogs, and is being replayed when an intro credit appears const ::Graphics::Surface *surface = 0; if (_flicPlayer[0].getCurFrame() >= 115) { surface = _flicPlayer[1].decodeNextFrame(); if (_flicPlayer[1].endOfVideo()) _flicPlayer[1].rewind(); } bool framesLeft = decodeNextAnimationFrame(0, false); if (surface) for (int i = 0; i < kScreenWidth * kScreenHeight; ++i) if (_offscreenBuffer[i] == 0) _offscreenBuffer[i] = *((byte *)surface->pixels + i); if (!framesLeft) _changeToNextSequence = true; } void AnimationSequencePlayer::displayLoadingScreen() { Common::File f; if (f.open("graphics/loading.pic")) { fadeOutPalette(); f.seek(32); f.read(_animationPalette, 3 * 256); f.read(_offscreenBuffer, 64000); _system->copyRectToScreen(_offscreenBuffer, 320, 0, 0, kScreenWidth, kScreenHeight); fadeInPalette(); } } void AnimationSequencePlayer::initPicPart4() { _updateScreenWidth = 320; _updateScreenPicture = true; _updateScreenCounter = 0; _updateScreenIndex = -1; } void AnimationSequencePlayer::drawPicPart4() { static const uint8 offsets[] = { 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 }; if (_updateScreenIndex == -1) { memcpy(_animationPalette, _picBufPtr + 32, 3 * 256); } if (_updateScreenCounter == 0) { static const uint8 counter[] = { 1, 2, 3, 4, 5, 35, 5, 4, 3, 2, 1 }; ++_updateScreenIndex; assert(_updateScreenIndex < ARRAYSIZE(counter)); _updateScreenCounter = counter[_updateScreenIndex]; } --_updateScreenCounter; _updateScreenWidth -= offsets[_updateScreenIndex]; for (int y = 0; y < 200; ++y) { memcpy(_offscreenBuffer + y * 320, _picBufPtr + 800 + y * 640 + _updateScreenWidth, 320); } if (_updateScreenWidth == 0) { _updateScreenPicture = false; } } void AnimationSequencePlayer::loadIntroSeq3_4() { displayLoadingScreen(); loadSounds(kSoundsList_Seq3_4); _picBufPtr = loadPicture("graphics/house.pic"); openAnimation(0, "graphics/intro1.flc"); _system->copyRectToScreen(_offscreenBuffer, 320, 0, 0, kScreenWidth, kScreenHeight); fadeInPalette(); _updateScreenPicture = false; } void AnimationSequencePlayer::playIntroSeq3_4() { if (!_updateScreenPicture) { bool framesLeft = decodeNextAnimationFrame(0); if (_flicPlayer[0].getCurFrame() == 705) { initPicPart4(); } if (!framesLeft) { _changeToNextSequence = true; } } else { drawPicPart4(); } } void AnimationSequencePlayer::drawPic2Part10() { for (int y = 0; y < 16; ++y) { for (int x = 0; x < 64; ++x) { const uint8 color = _pic2BufPtr[y * 64 + x]; if (color != 0) { _picBufPtr[89417 + y * 640 + x] = color; } } } for (int y = 0; y < 80; ++y) { for (int x = 0; x < 48; ++x) { const uint8 color = _pic2BufPtr[1024 + y * 48 + x]; if (color != 0) { _picBufPtr[63939 + y * 640 + x] = color; } } } for (int y = 0; y < 32; ++y) { for (int x = 0; x < 80; ++x) { const uint8 color = _pic2BufPtr[7424 + y * 80 + x]; if (color != 0) { _picBufPtr[33067 + y * 640 + x] = color; } } } } void AnimationSequencePlayer::drawPic1Part10() { int offset = 0; for (int y = 0; y < kScreenHeight; ++y) { for (int x = 0; x < kScreenWidth; ++x) { byte color = _offscreenBuffer[offset]; if (color == 0) color = _picBufPtr[800 + y * 640 + _updateScreenWidth + x]; _offscreenBuffer[offset++] = color; } } } void AnimationSequencePlayer::loadIntroSeq9_10() { loadSounds(kSoundsList_Seq9_10); _pic2BufPtr = loadPicture("graphics/bits.pic"); _picBufPtr = loadPicture("graphics/lab.pic"); openAnimation(0, "graphics/intro2.flc"); _updateScreenWidth = 0; } void AnimationSequencePlayer::playIntroSeq9_10() { const int nextFrame = _flicPlayer[0].getCurFrame() + 1; if (nextFrame >= 263 && nextFrame <= 294) { decodeNextAnimationFrame(0, false); drawPic1Part10(); _updateScreenWidth += 6; } else if (nextFrame == 983) { decodeNextAnimationFrame(0); drawPic2Part10(); } else if (nextFrame >= 987 && nextFrame <= 995) { decodeNextAnimationFrame(0, false); drawPic1Part10(); _updateScreenWidth -= 25; if (_updateScreenWidth < 0) { _updateScreenWidth = 0; } } else if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } void AnimationSequencePlayer::loadIntroSeq21_22() { loadSounds(kSoundsList_Seq21_20); openAnimation(0, "graphics/intro3.flc"); } void AnimationSequencePlayer::playIntroSeq21_22() { if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } void AnimationSequencePlayer::loadIntroSeq13_14() { loadSounds(kSoundsList_Seq13_14); openAnimation(0, "graphics/allseg02.flc"); } void AnimationSequencePlayer::playIntroSeq13_14() { if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } void AnimationSequencePlayer::loadIntroSeq15_16() { loadSounds(kSoundsList_Seq15_16); openAnimation(0, "graphics/allseg03.flc"); } void AnimationSequencePlayer::playIntroSeq15_16() { if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } void AnimationSequencePlayer::loadIntroSeq27_28() { loadSounds(kSoundsList_Seq27_28); openAnimation(0, "graphics/allseg04.flc"); } void AnimationSequencePlayer::playIntroSeq27_28() { if (!decodeNextAnimationFrame(0)) { _changeToNextSequence = true; } } } // namespace Tucker
joeriedel/scummvm
engines/tucker/sequences.cpp
C++
gpl-2.0
28,796
/* Zebra mlag header. * Copyright (C) 2018 Cumulus Networks, Inc. * Donald Sharp * * This file is part of FRR. * * FRR is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * FRR is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FRR; see the file COPYING. If not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #ifndef __ZEBRA_MLAG_H__ #define __ZEBRA_MLAG_H__ #include "mlag.h" #include "zclient.h" #include "zebra/zserv.h" #ifdef __cplusplus extern "C" { #endif #define ZEBRA_MLAG_BUF_LIMIT 32768 #define ZEBRA_MLAG_LEN_SIZE 4 DECLARE_HOOK(zebra_mlag_private_write_data, (uint8_t *data, uint32_t len), (data, len)); DECLARE_HOOK(zebra_mlag_private_monitor_state, (), ()); DECLARE_HOOK(zebra_mlag_private_open_channel, (), ()); DECLARE_HOOK(zebra_mlag_private_close_channel, (), ()); DECLARE_HOOK(zebra_mlag_private_cleanup_data, (), ()); extern uint8_t mlag_wr_buffer[ZEBRA_MLAG_BUF_LIMIT]; extern uint8_t mlag_rd_buffer[ZEBRA_MLAG_BUF_LIMIT]; static inline void zebra_mlag_reset_read_buffer(void) { memset(mlag_wr_buffer, 0, ZEBRA_MLAG_BUF_LIMIT); } enum zebra_mlag_state { MLAG_UP = 1, MLAG_DOWN = 2, }; void zebra_mlag_init(void); void zebra_mlag_terminate(void); enum mlag_role zebra_mlag_get_role(void); void zebra_mlag_client_register(ZAPI_HANDLER_ARGS); void zebra_mlag_client_unregister(ZAPI_HANDLER_ARGS); void zebra_mlag_forward_client_msg(ZAPI_HANDLER_ARGS); void zebra_mlag_send_register(void); void zebra_mlag_send_deregister(void); void zebra_mlag_handle_process_state(enum zebra_mlag_state state); void zebra_mlag_process_mlag_data(uint8_t *data, uint32_t len); /* * ProtoBuffer Api's */ int zebra_mlag_protobuf_encode_client_data(struct stream *s, uint32_t *msg_type); int zebra_mlag_protobuf_decode_message(struct stream *s, uint8_t *data, uint32_t len); #ifdef __cplusplus } #endif #endif
freerangerouting/frr
zebra/zebra_mlag.h
C
gpl-2.0
2,377
using System; using Server.Targeting; namespace Server.Spells.Sixth { public class ExplosionSpell : MagerySpell { private static readonly SpellInfo m_Info = new SpellInfo( "Explosion", "Vas Ort Flam", 230, 9041, Reagent.Bloodmoss, Reagent.MandrakeRoot); public ExplosionSpell(Mobile caster, Item scroll) : base(caster, scroll, m_Info) { } public override SpellCircle Circle { get { return SpellCircle.Sixth; } } public override bool DelayedDamageStacking { get { return !Core.AOS; } } public override bool DelayedDamage { get { return false; } } public override void OnCast() { this.Caster.Target = new InternalTarget(this); } public void Target(IDamageable m) { Mobile defender = m as Mobile; if (!this.Caster.CanSee(m)) { this.Caster.SendLocalizedMessage(500237); // Target can not be seen. } else if (this.Caster.CanBeHarmful(m) && this.CheckSequence()) { Mobile attacker = this.Caster; SpellHelper.Turn(this.Caster, m); if(defender != null) SpellHelper.CheckReflect((int)this.Circle, this.Caster, ref defender); InternalTimer t = new InternalTimer(this, attacker, defender != null ? defender : m); t.Start(); } this.FinishSequence(); } private class InternalTimer : Timer { private readonly MagerySpell m_Spell; private readonly IDamageable m_Target; private readonly Mobile m_Attacker; public InternalTimer(MagerySpell spell, Mobile attacker, IDamageable target) : base(TimeSpan.FromSeconds(Core.AOS ? 3.0 : 2.5)) { m_Spell = spell; m_Attacker = attacker; m_Target = target; if (this.m_Spell != null) this.m_Spell.StartDelayedDamageContext(attacker, this); this.Priority = TimerPriority.FiftyMS; } protected override void OnTick() { Mobile defender = m_Target as Mobile; if (m_Attacker.HarmfulCheck(m_Target)) { double damage = 0; if (Core.AOS) { damage = this.m_Spell.GetNewAosDamage(40, 1, 5, m_Target); } else if (defender != null) { damage = Utility.Random(23, 22); if (this.m_Spell.CheckResisted(defender)) { damage *= 0.75; defender.SendLocalizedMessage(501783); // You feel yourself resisting magical energy. } damage *= this.m_Spell.GetDamageScalar(defender); } if (defender != null) { defender.FixedParticles(0x36BD, 20, 10, 5044, EffectLayer.Head); defender.PlaySound(0x307); } else { Effects.SendLocationParticles(m_Target, 0x36BD, 20, 10, 5044); Effects.PlaySound(m_Target.Location, m_Target.Map, 0x307); } if (damage > 0) { SpellHelper.Damage(this.m_Spell, this.m_Target, damage, 0, 100, 0, 0, 0); } if (this.m_Spell != null) this.m_Spell.RemoveDelayedDamageContext(this.m_Attacker); } } } private class InternalTarget : Target { private readonly ExplosionSpell m_Owner; public InternalTarget(ExplosionSpell owner) : base(Core.ML ? 10 : 12, false, TargetFlags.Harmful) { this.m_Owner = owner; } protected override void OnTarget(Mobile from, object o) { if (o is IDamageable) this.m_Owner.Target((IDamageable)o); } protected override void OnTargetFinish(Mobile from) { this.m_Owner.FinishSequence(); } } } }
SirGrizzlyBear/ServUOGrizzly
Scripts/Spells/Sixth/Explosion.cs
C#
gpl-2.0
4,788