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
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/file_system/entry_watcher_service_factory.h" #include "chrome/browser/extensions/api/file_system/entry_watcher_service.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "content/public/browser/browser_context.h" namespace extensions { EntryWatcherServiceFactory* EntryWatcherServiceFactory::GetInstance() { return Singleton<EntryWatcherServiceFactory>::get(); } EntryWatcherServiceFactory::EntryWatcherServiceFactory() : BrowserContextKeyedServiceFactory( "EntryWatcherService", BrowserContextDependencyManager::GetInstance()) { } EntryWatcherServiceFactory::~EntryWatcherServiceFactory() { } KeyedService* EntryWatcherServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new EntryWatcherService(Profile::FromBrowserContext(context)); } bool EntryWatcherServiceFactory::ServiceIsCreatedWithBrowserContext() const { // Required to restore persistent watchers as soon as the profile is loaded. return true; } } // namespace extensions
s20121035/rk3288_android5.1_repo
external/chromium_org/chrome/browser/extensions/api/file_system/entry_watcher_service_factory.cc
C++
gpl-3.0
1,309
<?php use LibreNMS\Exceptions\InvalidIpException; use LibreNMS\Util\IP; echo '<div class="container-fluid">'; echo "<div class='row'> <div class='col-md-12'> <div class='panel panel-default panel-condensed'> <div class='panel-heading'>"; if ($config['overview_show_sysDescr']) { echo '<i class="fa fa-id-card fa-lg icon-theme" aria-hidden="true"></i> <strong>'.$device['sysDescr'].'</strong>'; } echo '</div> <table class="table table-hover table-condensed table-striped">'; $uptime = formatUptime($device['uptime']); $uptime_text = 'Uptime'; if ($device['status'] == 0) { // Rewrite $uptime to be downtime if device is down $uptime = formatUptime(time() - strtotime($device['last_polled'])); $uptime_text = 'Downtime'; } if ($device['os'] == 'ios') { formatCiscoHardware($device); } if ($device['features']) { $device['features'] = '('.$device['features'].')'; } $device['os_text'] = $config['os'][$device['os']]['text']; echo '<tr> <td>System Name</td> <td>'.$device['sysName'].' </td> </tr>'; if (!empty($device['ip'])) { echo "<tr><td>Resolved IP</td><td>{$device['ip']}</td></tr>"; } elseif ($config['force_ip_to_sysname'] === true) { try { $ip = IP::parse($device['hostname']); echo "<tr><td>IP Address</td><td>$ip</td></tr>"; } catch (InvalidIpException $e) { // don't add an ip line } } if ($device['purpose']) { echo '<tr> <td>Description</td> <td>'.display($device['purpose']).'</td> </tr>'; } if ($device['hardware']) { echo '<tr> <td>Hardware</td> <td>'.$device['hardware'].'</td> </tr>'; } echo '<tr> <td>Operating System</td> <td>'.$device['os_text'].' '.$device['version'].' '.$device['features'].' </td> </tr>'; if ($device['serial']) { echo '<tr> <td>Serial</td> <td>'.$device['serial'].'</td> </tr>'; } if ($device['sysObjectID']) { echo '<tr> <td>Object ID</td> <td>'.$device['sysObjectID'].'</td> </tr>'; } if ($device['sysContact']) { echo '<tr> <td>Contact</td>'; if (get_dev_attrib($device, 'override_sysContact_bool')) { echo ' <td>'.htmlspecialchars(get_dev_attrib($device, 'override_sysContact_string')).'</td> </tr> <tr> <td>SNMP Contact</td>'; } echo ' <td>'.htmlspecialchars($device['sysContact']).'</td> </tr>'; } if ($device['location']) { echo '<tr> <td>Location</td> <td>'.$device['location'].'</td> </tr>'; if (get_dev_attrib($device, 'override_sysLocation_bool') && !empty($device['real_location'])) { echo '<tr> <td>SNMP Location</td> <td>'.$device['real_location'].'</td> </tr>'; } } $loc = parse_location($device['location']); if (!is_array($loc)) { $loc = dbFetchRow("SELECT `lat`,`lng` FROM `locations` WHERE `location`=? LIMIT 1", array($device['location'])); } if (is_array($loc)) { echo '<tr> <td>Lat / Lng</td> <td>['.$loc['lat'].','.$loc['lng'].'] <div class="pull-right"><a href="https://maps.google.com/?q='.$loc['lat'].'+'.$loc['lng'].'" target="_blank" class="btn btn-success btn-xs" role="button"><i class="fa fa-map-marker" style="color:white" aria-hidden="true"></i> Map</button></div></a></td> </tr>'; } if ($uptime) { echo "<tr> <td>$uptime_text</td> <td>".$uptime."</td> </tr>"; } echo '</table> </div> </div> </div> </div>';
wikimedia/operations-software-librenms
html/includes/dev-overview-data.inc.php
PHP
gpl-3.0
3,565
/* * Copyright (C) 2012 The Android Open Source Project * * 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. */ #ifndef ANDROID_AUDIO_NBAIO_H #define ANDROID_AUDIO_NBAIO_H // Non-blocking audio I/O interface // // This header file has the abstract interfaces only. Concrete implementation classes are declared // elsewhere. Implementations _should_ be non-blocking for all methods, especially read() and // write(), but this is not enforced. In general, implementations do not need to be multi-thread // safe, and any exceptions are noted in the particular implementation. #include <limits.h> #include <stdlib.h> #include <utils/Errors.h> #include <utils/RefBase.h> #include <media/AudioTimestamp.h> namespace android { // In addition to the usual status_t enum { NEGOTIATE = 0x80000010, // Must (re-)negotiate format. For negotiate() only, the offeree // doesn't accept offers, and proposes counter-offers OVERRUN = 0x80000011, // availableToRead(), read(), or readVia() detected lost input due // to overrun; an event is counted and the caller should re-try UNDERRUN = 0x80000012, // availableToWrite(), write(), or writeVia() detected a gap in // output due to underrun (not being called often enough, or with // enough data); an event is counted and the caller should re-try }; // Negotiation of format is based on the data provider and data sink, or the data consumer and // data source, exchanging prioritized arrays of offers and counter-offers until a single offer is // mutually agreed upon. Each offer is an NBAIO_Format. For simplicity and performance, // NBAIO_Format is a typedef that ties together the most important combinations of the various // attributes, rather than a struct with separate fields for format, sample rate, channel count, // interleave, packing, alignment, etc. The reason is that NBAIO_Format tries to abstract out only // the combinations that are actually needed within AudioFlinger. If the list of combinations grows // too large, then this decision should be re-visited. // Sample rate and channel count are explicit, PCM interleaved 16-bit is assumed. typedef unsigned NBAIO_Format; enum { Format_Invalid }; // Return the frame size of an NBAIO_Format in bytes size_t Format_frameSize(NBAIO_Format format); // Return the frame size of an NBAIO_Format as a bit shift size_t Format_frameBitShift(NBAIO_Format format); // Convert a sample rate in Hz and channel count to an NBAIO_Format NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount); // Return the sample rate in Hz of an NBAIO_Format unsigned Format_sampleRate(NBAIO_Format format); // Return the channel count of an NBAIO_Format unsigned Format_channelCount(NBAIO_Format format); // Callbacks used by NBAIO_Sink::writeVia() and NBAIO_Source::readVia() below. typedef ssize_t (*writeVia_t)(void *user, void *buffer, size_t count); typedef ssize_t (*readVia_t)(void *user, const void *buffer, size_t count, int64_t readPTS); // Abstract class (interface) representing a data port. class NBAIO_Port : public RefBase { public: // negotiate() must called first. The purpose of negotiate() is to check compatibility of // formats, not to automatically adapt if they are incompatible. It's the responsibility of // whoever sets up the graph connections to make sure formats are compatible, and this method // just verifies that. The edges are "dumb" and don't attempt to adapt to bad connections. // How it works: offerer proposes an array of formats, in descending order of preference from // offers[0] to offers[numOffers - 1]. If offeree accepts one of these formats, it returns // the index of that offer. Otherwise, offeree sets numCounterOffers to the number of // counter-offers (up to a maximumum of the entry value of numCounterOffers), fills in the // provided array counterOffers[] with its counter-offers, in descending order of preference // from counterOffers[0] to counterOffers[numCounterOffers - 1], and returns NEGOTIATE. // Note that since the offerer allocates space for counter-offers, but only the offeree knows // how many counter-offers it has, there may be insufficient space for all counter-offers. // In that case, the offeree sets numCounterOffers to the requested number of counter-offers // (which is greater than the entry value of numCounterOffers), fills in as many of the most // important counterOffers as will fit, and returns NEGOTIATE. As this implies a re-allocation, // it should be used as a last resort. It is preferable for the offerer to simply allocate a // larger space to begin with, and/or for the offeree to tolerate a smaller space than desired. // Alternatively, the offerer can pass NULL for offers and counterOffers, and zero for // numOffers. This indicates that it has not allocated space for any counter-offers yet. // In this case, the offerree should set numCounterOffers appropriately and return NEGOTIATE. // Then the offerer will allocate the correct amount of memory and retry. // Format_Invalid is not allowed as either an offer or counter-offer. // Returns: // >= 0 Offer accepted. // NEGOTIATE No offer accepted, and counter-offer(s) optionally made. See above for details. virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers, NBAIO_Format counterOffers[], size_t& numCounterOffers); // Return the current negotiated format, or Format_Invalid if negotiation has not been done, // or if re-negotiation is required. virtual NBAIO_Format format() const { return mNegotiated ? mFormat : Format_Invalid; } protected: NBAIO_Port(NBAIO_Format format) : mNegotiated(false), mFormat(format), mBitShift(Format_frameBitShift(format)) { } virtual ~NBAIO_Port() { } // Implementations are free to ignore these if they don't need them bool mNegotiated; // mNegotiated implies (mFormat != Format_Invalid) NBAIO_Format mFormat; // (mFormat != Format_Invalid) does not imply mNegotiated size_t mBitShift; // assign in parallel with any assignment to mFormat }; // Abstract class (interface) representing a non-blocking data sink, for use by a data provider. class NBAIO_Sink : public NBAIO_Port { public: // For the next two APIs: // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. // Return the number of frames written successfully since construction. virtual size_t framesWritten() const { return mFramesWritten; } // Number of frames lost due to underrun since construction. virtual size_t framesUnderrun() const { return 0; } // Number of underruns since construction, where a set of contiguous lost frames is one event. virtual size_t underruns() const { return 0; } // Estimate of number of frames that could be written successfully now without blocking. // When a write() is actually attempted, the implementation is permitted to return a smaller or // larger transfer count, however it will make a good faith effort to give an accurate estimate. // Errors: // NEGOTIATE (Re-)negotiation is needed. // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. // An underrun event is counted, and the caller should re-try this operation. // WOULD_BLOCK Determining how many frames can be written without blocking would itself block. virtual ssize_t availableToWrite() const { return SSIZE_MAX; } // Transfer data to sink from single input buffer. Implies a copy. // Inputs: // buffer Non-NULL buffer owned by provider. // count Maximum number of frames to transfer. // Return value: // > 0 Number of frames successfully transferred prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer. // Errors: // NEGOTIATE (Re-)negotiation is needed. // WOULD_BLOCK No frames can be transferred without blocking. // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. // An underrun event is counted, and the caller should re-try this operation. virtual ssize_t write(const void *buffer, size_t count) = 0; // Transfer data to sink using a series of callbacks. More suitable for zero-fill, synthesis, // and non-contiguous transfers (e.g. circular buffer or writev). // Inputs: // via Callback function that the sink will call as many times as needed to consume data. // total Estimate of the number of frames the provider has available. This is an estimate, // and it can provide a different number of frames during the series of callbacks. // user Arbitrary void * reserved for data provider. // block Number of frames per block, that is a suggested value for 'count' in each callback. // Zero means no preference. This parameter is a hint only, and may be ignored. // Return value: // > 0 Total number of frames successfully transferred prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer. // Errors: // NEGOTIATE (Re-)negotiation is needed. // WOULD_BLOCK No frames can be transferred without blocking. // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up. // An underrun event is counted, and the caller should re-try this operation. // // The 'via' callback is called by the data sink as follows: // Inputs: // user Arbitrary void * reserved for data provider. // buffer Non-NULL buffer owned by sink that callback should fill in with data, // up to a maximum of 'count' frames. // count Maximum number of frames to transfer during this callback. // Return value: // > 0 Number of frames successfully transferred during this callback prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer during this callback. virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block = 0); // Get the time (on the LocalTime timeline) at which the first frame of audio of the next write // operation to this sink will be eventually rendered by the HAL. // Inputs: // ts A pointer pointing to the int64_t which will hold the result. // Return value: // OK Everything went well, *ts holds the time at which the first audio frame of the next // write operation will be rendered, or AudioBufferProvider::kInvalidPTS if this sink // does not know the answer for some reason. Sinks which eventually lead to a HAL // which implements get_next_write_timestamp may return Invalid temporarily if the DMA // output of the audio driver has not started yet. Sinks which lead to a HAL which // does not implement get_next_write_timestamp, or which don't lead to a HAL at all, // will always return kInvalidPTS. // <other> Something unexpected happened internally. Check the logs and start debugging. virtual status_t getNextWriteTimestamp(int64_t *ts) { return INVALID_OPERATION; } // Returns NO_ERROR if a timestamp is available. The timestamp includes the total number // of frames presented to an external observer, together with the value of CLOCK_MONOTONIC // as of this presentation count. virtual status_t getTimestamp(AudioTimestamp& timestamp) { return INVALID_OPERATION; } protected: NBAIO_Sink(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesWritten(0) { } virtual ~NBAIO_Sink() { } // Implementations are free to ignore these if they don't need them size_t mFramesWritten; }; // Abstract class (interface) representing a non-blocking data source, for use by a data consumer. class NBAIO_Source : public NBAIO_Port { public: // For the next two APIs: // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically. // Number of frames read successfully since construction. virtual size_t framesRead() const { return mFramesRead; } // Number of frames lost due to overrun since construction. // Not const because implementations may need to do I/O. virtual size_t framesOverrun() /*const*/ { return 0; } // Number of overruns since construction, where a set of contiguous lost frames is one event. // Not const because implementations may need to do I/O. virtual size_t overruns() /*const*/ { return 0; } // Estimate of number of frames that could be read successfully now. // When a read() is actually attempted, the implementation is permitted to return a smaller or // larger transfer count, however it will make a good faith effort to give an accurate estimate. // Errors: // NEGOTIATE (Re-)negotiation is needed. // OVERRUN One or more frames were lost due to overrun, try again to read more recent data. // WOULD_BLOCK Determining how many frames can be read without blocking would itself block. virtual ssize_t availableToRead() { return SSIZE_MAX; } // Transfer data from source into single destination buffer. Implies a copy. // Inputs: // buffer Non-NULL destination buffer owned by consumer. // count Maximum number of frames to transfer. // readPTS The presentation time (on the LocalTime timeline) for which data // is being requested, or kInvalidPTS if not known. // Return value: // > 0 Number of frames successfully transferred prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer. // Errors: // NEGOTIATE (Re-)negotiation is needed. // WOULD_BLOCK No frames can be transferred without blocking. // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. // One or more frames were lost due to overrun, try again to read more recent data. virtual ssize_t read(void *buffer, size_t count, int64_t readPTS) = 0; // Transfer data from source using a series of callbacks. More suitable for zero-fill, // synthesis, and non-contiguous transfers (e.g. circular buffer or readv). // Inputs: // via Callback function that the source will call as many times as needed to provide data. // total Estimate of the number of frames the consumer desires. This is an estimate, // and it can consume a different number of frames during the series of callbacks. // user Arbitrary void * reserved for data consumer. // readPTS The presentation time (on the LocalTime timeline) for which data // is being requested, or kInvalidPTS if not known. // block Number of frames per block, that is a suggested value for 'count' in each callback. // Zero means no preference. This parameter is a hint only, and may be ignored. // Return value: // > 0 Total number of frames successfully transferred prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer. // Errors: // NEGOTIATE (Re-)negotiation is needed. // WOULD_BLOCK No frames can be transferred without blocking. // OVERRUN read() has not been called frequently enough, or with enough frames to keep up. // One or more frames were lost due to overrun, try again to read more recent data. // // The 'via' callback is called by the data source as follows: // Inputs: // user Arbitrary void * reserved for data consumer. // dest Non-NULL buffer owned by source that callback should consume data from, // up to a maximum of 'count' frames. // count Maximum number of frames to transfer during this callback. // Return value: // > 0 Number of frames successfully transferred during this callback prior to first error. // = 0 Count was zero. // < 0 status_t error occurred prior to the first frame transfer during this callback. virtual ssize_t readVia(readVia_t via, size_t total, void *user, int64_t readPTS, size_t block = 0); // Invoked asynchronously by corresponding sink when a new timestamp is available. // Default implementation ignores the timestamp. virtual void onTimestamp(const AudioTimestamp& timestamp) { } protected: NBAIO_Source(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesRead(0) { } virtual ~NBAIO_Source() { } // Implementations are free to ignore these if they don't need them size_t mFramesRead; }; } // namespace android #endif // ANDROID_AUDIO_NBAIO_H
sipXtapi/sipXtapi
sipXmediaLib/contrib/android/android_4_4_2_headers/frameworks/av/include/media/nbaio/NBAIO.h
C
lgpl-2.1
17,829
/* * Copyright (C) 2014 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser General * Public License v2.1. See the file LICENSE in the top level directory for more * details. */ /** * @ingroup tests * @{ * * @file * @brief Application for testing low-level SPI driver implementations * * This implementation covers both, master and slave configurations. * * @author Hauke Petersen <hauke.petersen@fu-berlin.de> * * @} */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "xtimer.h" #include "shell.h" #include "periph/spi.h" /** * @brief Some parameters used for benchmarking */ #define BENCH_REDOS (1000) #define BENCH_SMALL (2) #define BENCH_LARGE (100) #define BENCH_PAYLOAD ('b') #define BENCH_REGADDR (0x23) #define BUF_SIZE (512U) /** * @brief Benchmark buffers */ static uint8_t bench_wbuf[BENCH_LARGE]; static uint8_t bench_rbuf[BENCH_LARGE]; /** * @brief Generic buffer used for receiving */ static uint8_t buf[BUF_SIZE]; static struct { spi_t dev; spi_mode_t mode; spi_clk_t clk; spi_cs_t cs; } spiconf; void print_bytes(char* title, uint8_t* data, size_t len) { printf("%4s\n", title); for (size_t i = 0; i < len; i++) { printf(" %2i ", (int)i); } printf("\n "); for (size_t i = 0; i < len; i++) { printf(" 0x%02x", (int)data[i]); } printf("\n "); for (size_t i = 0; i < len; i++) { if (data[i] < ' ' || data[i] > '~') { printf(" ?? "); } else { printf(" %c ", (char)data[i]); } } printf("\n\n"); } int cmd_init(int argc, char **argv) { int dev, mode, clk, port, pin, tmp; if (argc < 5) { printf("usage: %s <dev> <mode> <clk> <cs port> <cs pin>\n", argv[0]); puts("\tdev:"); for (int i = 0; i < (int)SPI_NUMOF; i++) { printf("\t\t%i: SPI_DEV(%i)\n", i, i); } puts("\tmode:"); puts("\t\t0: POL:0, PHASE:0 - on first rising edge"); puts("\t\t1: POL:0, PHASE:1 - on second rising edge"); puts("\t\t2: POL:1, PHASE:0 - on first falling edge"); puts("\t\t3: POL:1, PHASE:1 - on second falling edge"); puts("\tclk:"); puts("\t\t0: 100 KHz"); puts("\t\t1: 400 KHz"); puts("\t\t2: 1 MHz"); puts("\t\t3: 5 MHz"); puts("\t\t4: 10 MHz"); puts("\tcs port:"); puts("\t\tPort of the CS pin, set to -1 for hardware chip select"); puts("\tcs pin:"); puts("\t\tPin used for chip select. If hardware chip select is enabled,\n" "\t\tthis value specifies the internal HWCS line"); return 1; } /* parse the given SPI device */ dev = atoi(argv[1]); if (dev < 0 || dev >= (int)SPI_NUMOF) { puts("error: invalid SPI device specified"); return 1; } spiconf.dev = SPI_DEV(dev); /* parse the SPI mode */ mode = atoi(argv[2]); switch (mode) { case 0: spiconf.mode = SPI_MODE_0; break; case 1: spiconf.mode = SPI_MODE_1; break; case 2: spiconf.mode = SPI_MODE_2; break; case 3: spiconf.mode = SPI_MODE_3; break; default: puts("error: invalid SPI mode specified"); return 1; } /* parse the targeted clock speed */ clk = atoi(argv[3]); switch (clk) { case 0: spiconf.clk = SPI_CLK_100KHZ; break; case 1: spiconf.clk = SPI_CLK_400KHZ; break; case 2: spiconf.clk = SPI_CLK_1MHZ; break; case 3: spiconf.clk = SPI_CLK_5MHZ; break; case 4: spiconf.clk = SPI_CLK_10MHZ; break; default: puts("error: invalid bus speed specified"); return 1; } /* parse chip select port and pin */ port = atoi(argv[4]); pin = atoi(argv[5]); if (pin < 0 || port < -1) { puts("error: invalid CS port/pin combination specified"); } if (port == -1) { /* hardware chip select line */ spiconf.cs = SPI_HWCS(pin); } else { spiconf.cs = (spi_cs_t)GPIO_PIN(port, pin); } /* test setup */ tmp = spi_init_cs(spiconf.dev, spiconf.cs); if (tmp != SPI_OK) { puts("error: unable to initialize the given chip select line"); return 1; } tmp = spi_acquire(spiconf.dev, spiconf.cs, spiconf.mode, spiconf.clk); if (tmp == SPI_NOMODE) { puts("error: given SPI mode is not supported"); return 1; } else if (tmp == SPI_NOCLK) { puts("error: targeted clock speed is not supported"); return 1; } else if (tmp != SPI_OK) { puts("error: unable to acquire bus with given parameters"); return 1; } spi_release(spiconf.dev); printf("SPI_DEV(%i) initialized: mode: %i, clk: %i, cs_port: %i, cs_pin: %i\n", dev, mode, clk, port, pin); return 0; } int cmd_transfer(int argc, char **argv) { size_t len; if (argc < 2) { printf("usage: %s <data>\n", argv[0]); return 1; } if (spiconf.dev == SPI_UNDEF) { puts("error: SPI is not initialized, please initialize bus first"); return 1; } /* get bus access */ if (spi_acquire(spiconf.dev, spiconf.cs, spiconf.mode, spiconf.clk) != SPI_OK) { puts("error: unable to acquire the SPI bus"); return 1; } /* transfer data */ len = strlen(argv[1]); memset(buf, 0, sizeof(buf)); spi_transfer_bytes(spiconf.dev, spiconf.cs, false, argv[1], buf, len); /* release the bus */ spi_release(spiconf.dev); /* print results */ print_bytes("Sent bytes", (uint8_t *)argv[1], len); print_bytes("Received bytes", buf, len); return 0; } int cmd_bench(int argc, char **argv) { (void)argc; (void)argv; uint32_t start, stop; uint32_t sum = 0; uint8_t in; uint8_t out = (uint8_t)BENCH_PAYLOAD; if (spiconf.dev == SPI_UNDEF) { puts("error: SPI is not initialized, please initialize bus first"); return 1; } /* prepare buffer */ memset(bench_wbuf, BENCH_PAYLOAD, BENCH_LARGE); /* get access to the bus */ if (spi_acquire(spiconf.dev, spiconf.cs, spiconf.mode, spiconf.clk) != SPI_OK) { puts("error: unable to acquire the SPI bus"); return 1; } puts("### Running some benchmarks, all values in [us] ###\n"); /* 1 - write 1000 times 1 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { in = spi_transfer_byte(spiconf.dev, spiconf.cs, false, out); (void)in; } stop = xtimer_now_usec(); printf(" 1 - write %i times %i byte:", BENCH_REDOS, 1); printf("\t\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 2 - write 1000 times 2 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, bench_wbuf, NULL, BENCH_SMALL); } stop = xtimer_now_usec(); printf(" 2 - write %i times %i byte:", BENCH_REDOS, BENCH_SMALL); printf("\t\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 3 - write 1000 times 100 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, bench_wbuf, NULL, BENCH_LARGE); } stop = xtimer_now_usec(); printf(" 3 - write %i times %i byte:", BENCH_REDOS, BENCH_LARGE); printf("\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 4 - write 1000 times 1 byte to register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { in = spi_transfer_reg(spiconf.dev, spiconf.cs, BENCH_REGADDR, out); (void)in; } stop = xtimer_now_usec(); printf(" 4 - write %i times %i byte to register:", BENCH_REDOS, 1); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 5 - write 1000 times 2 byte to register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, bench_wbuf, NULL, BENCH_SMALL); } stop = xtimer_now_usec(); printf(" 5 - write %i times %i byte to register:", BENCH_REDOS, BENCH_SMALL); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 6 - write 1000 times 100 byte to register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, bench_wbuf, NULL, BENCH_LARGE); } stop = xtimer_now_usec(); printf(" 6 - write %i times %i byte to register:", BENCH_REDOS, BENCH_LARGE); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 7 - read 1000 times 2 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, NULL, bench_rbuf, BENCH_SMALL); } stop = xtimer_now_usec(); printf(" 7 - read %i times %i byte:", BENCH_REDOS, BENCH_SMALL); printf("\t\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 8 - read 1000 times 100 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, NULL, bench_rbuf, BENCH_LARGE); } stop = xtimer_now_usec(); printf(" 8 - read %i times %i byte:", BENCH_REDOS, BENCH_LARGE); printf("\t\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 9 - read 1000 times 2 byte from register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, NULL, bench_rbuf, BENCH_SMALL); } stop = xtimer_now_usec(); printf(" 9 - read %i times %i byte from register:", BENCH_REDOS, BENCH_SMALL); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 10 - read 1000 times 100 byte from register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, NULL, bench_rbuf, BENCH_LARGE); } stop = xtimer_now_usec(); printf("10 - read %i times %i byte from register:", BENCH_REDOS, BENCH_LARGE); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 11 - transfer 1000 times 2 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, bench_wbuf, bench_rbuf, BENCH_SMALL); } stop = xtimer_now_usec(); printf("11 - transfer %i times %i byte:", BENCH_REDOS, BENCH_SMALL); printf("\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 12 - transfer 1000 times 100 byte */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_bytes(spiconf.dev, spiconf.cs, false, bench_wbuf, bench_rbuf, BENCH_LARGE); } stop = xtimer_now_usec(); printf("12 - transfer %i times %i byte:", BENCH_REDOS, BENCH_LARGE); printf("\t\t%i\n", (int)(stop - start)); sum += (stop - start); /* 13 - transfer 1000 times 2 byte from/to register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, bench_wbuf, bench_rbuf, BENCH_SMALL); } stop = xtimer_now_usec(); printf("13 - transfer %i times %i byte to register:", BENCH_REDOS, BENCH_SMALL); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); /* 14 - transfer 1000 times 100 byte from/to register */ start = xtimer_now_usec(); for (int i = 0; i < BENCH_REDOS; i++) { spi_transfer_regs(spiconf.dev, spiconf.cs, BENCH_REGADDR, bench_wbuf, bench_rbuf, BENCH_LARGE); } stop = xtimer_now_usec(); printf("14 - transfer %i times %i byte to register:", BENCH_REDOS, BENCH_LARGE); printf("\t%i\n", (int)(stop - start)); sum += (stop - start); printf("-- - SUM:\t\t\t\t\t%i\n", (int)sum); spi_release(spiconf.dev); puts("\n### All runs complete ###"); return 0; } static const shell_command_t shell_commands[] = { { "init", "Setup a particular SPI configuration", cmd_init }, { "send", "Transfer string to slave", cmd_transfer }, { "bench", "Runs some benchmarks", cmd_bench }, { NULL, NULL, NULL } }; int main(void) { puts("Manual SPI peripheral driver test"); puts("Refer to the README.md file for more information.\n"); printf("There are %i SPI devices configured for your platform.\n", (int)SPI_NUMOF); /* reset local SPI configuration */ spiconf.dev = SPI_UNDEF; /* run the shell */ char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
lazytech-org/RIOT
tests/periph_spi/main.c
C
lgpl-2.1
13,326
/* * GStreamer * Copyright (C) 2007-2009 Sebastian Dröge <sebastian.droege@collabora.co.uk> * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __GST_AUDIO_CHEB_LIMIT_H__ #define __GST_AUDIO_CHEB_LIMIT_H__ #include <gst/gst.h> #include <gst/base/gstbasetransform.h> #include <gst/audio/audio.h> #include <gst/audio/gstaudiofilter.h> #include "audiofxbaseiirfilter.h" G_BEGIN_DECLS #define GST_TYPE_AUDIO_CHEB_LIMIT (gst_audio_cheb_limit_get_type()) #define GST_AUDIO_CHEB_LIMIT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_CHEB_LIMIT,GstAudioChebLimit)) #define GST_IS_AUDIO_CHEB_LIMIT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_CHEB_LIMIT)) #define GST_AUDIO_CHEB_LIMIT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass) ,GST_TYPE_AUDIO_CHEB_LIMIT,GstAudioChebLimitClass)) #define GST_IS_AUDIO_CHEB_LIMIT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass) ,GST_TYPE_AUDIO_CHEB_LIMIT)) #define GST_AUDIO_CHEB_LIMIT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj) ,GST_TYPE_AUDIO_CHEB_LIMIT,GstAudioChebLimitClass)) typedef struct _GstAudioChebLimit GstAudioChebLimit; typedef struct _GstAudioChebLimitClass GstAudioChebLimitClass; struct _GstAudioChebLimit { GstAudioFXBaseIIRFilter parent; gint mode; gint type; gint poles; gfloat cutoff; gfloat ripple; /* < private > */ GMutex *lock; }; struct _GstAudioChebLimitClass { GstAudioFXBaseIIRFilterClass parent; }; GType gst_audio_cheb_limit_get_type (void); G_END_DECLS #endif /* __GST_AUDIO_CHEB_LIMIT_H__ */
cpopescu/whispermedialib
third-party/gstreamer/gst-plugins-good-0.10.23/gst/audiofx/audiocheblimit.h
C
lgpl-3.0
2,242
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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 com.jetbrains.python.codeInsight.stdlib; import com.intellij.psi.PsiElement; import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.resolve.PyCanonicalPathProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; /** * @author yole */ public class PyStdlibCanonicalPathProvider implements PyCanonicalPathProvider { @Nullable @Override public QualifiedName getCanonicalPath(@NotNull QualifiedName qName, PsiElement foothold) { return restoreStdlibCanonicalPath(qName); } public static QualifiedName restoreStdlibCanonicalPath(QualifiedName qName) { if (qName.getComponentCount() > 0) { final List<String> components = qName.getComponents(); final String head = components.get(0); if (head.equals("_abcoll") || head.equals("_collections")) { components.set(0, "collections"); return QualifiedName.fromComponents(components); } else if (head.equals("posix") || head.equals("nt")) { components.set(0, "os"); return QualifiedName.fromComponents(components); } else if (head.equals("_functools")) { components.set(0, "functools"); return QualifiedName.fromComponents(components); } else if (head.equals("_struct")) { components.set(0, "struct"); return QualifiedName.fromComponents(components); } else if (head.equals("_io") || head.equals("_pyio") || head.equals("_fileio")) { components.set(0, "io"); return QualifiedName.fromComponents(components); } else if (head.equals("_datetime")) { components.set(0, "datetime"); return QualifiedName.fromComponents(components); } else if (head.equals("ntpath") || head.equals("posixpath") || head.equals("path")) { final List<String> result = new ArrayList<String>(); result.add("os"); components.set(0, "path"); result.addAll(components); return QualifiedName.fromComponents(result); } else if (head.equals("_sqlite3")) { components.set(0, "sqlite3"); return QualifiedName.fromComponents(components); } else if (head.equals("_pickle")) { components.set(0, "pickle"); return QualifiedName.fromComponents(components); } } return null; } }
akosyakov/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibCanonicalPathProvider.java
Java
apache-2.0
3,015
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.script; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.script.ScriptService.ScriptType; import org.elasticsearch.script.groovy.GroovyScriptEngineService; import org.elasticsearch.test.ESIntegTestCase; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.scriptFunction; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; import static org.hamcrest.Matchers.equalTo; /** * Various tests for Groovy scripting */ public class GroovyScriptIT extends ESIntegTestCase { @Test public void testGroovyBigDecimalTransformation() { client().prepareIndex("test", "doc", "1").setSource("foo", 5).setRefresh(true).get(); // Test that something that would usually be a BigDecimal is transformed into a Double assertScript("def n = 1.23; assert n instanceof Double;"); assertScript("def n = 1.23G; assert n instanceof Double;"); assertScript("def n = BigDecimal.ONE; assert n instanceof BigDecimal;"); } public void assertScript(String script) { SearchResponse resp = client().prepareSearch("test") .setSource(new BytesArray("{\"query\": {\"match_all\": {}}," + "\"sort\":{\"_script\": {\"script\": \""+ script + "; 1\", \"type\": \"number\", \"lang\": \"groovy\"}}}")).get(); assertNoFailures(resp); } @Test public void testGroovyExceptionSerialization() throws Exception { List<IndexRequestBuilder> reqs = new ArrayList<>(); for (int i = 0; i < randomIntBetween(50, 500); i++) { reqs.add(client().prepareIndex("test", "doc", "" + i).setSource("foo", "bar")); } indexRandom(true, false, reqs); try { client().prepareSearch("test") .setQuery( constantScoreQuery(scriptQuery(new Script("1 == not_found", ScriptType.INLINE, GroovyScriptEngineService.NAME, null)))).get(); fail("should have thrown an exception"); } catch (SearchPhaseExecutionException e) { assertThat(e.toString()+ "should not contained NotSerializableTransportException", e.toString().contains("NotSerializableTransportException"), equalTo(false)); assertThat(e.toString()+ "should have contained GroovyScriptExecutionException", e.toString().contains("GroovyScriptExecutionException"), equalTo(true)); assertThat(e.toString()+ "should have contained not_found", e.toString().contains("No such property: not_found"), equalTo(true)); } try { client().prepareSearch("test") .setQuery(constantScoreQuery(scriptQuery(new Script("assert false", ScriptType.INLINE, "groovy", null)))).get(); fail("should have thrown an exception"); } catch (SearchPhaseExecutionException e) { assertThat(e.toString() + "should not contained NotSerializableTransportException", e.toString().contains("NotSerializableTransportException"), equalTo(false)); assertThat(e.toString() + "should have contained GroovyScriptExecutionException", e.toString().contains("GroovyScriptExecutionException"), equalTo(true)); assertThat(e.toString()+ "should have contained an assert error", e.toString().contains("AssertionError[assert false"), equalTo(true)); } } @Test public void testGroovyScriptAccess() { client().prepareIndex("test", "doc", "1").setSource("foo", "quick brow fox jumped over the lazy dog", "bar", 1).get(); client().prepareIndex("test", "doc", "2").setSource("foo", "fast jumping spiders", "bar", 2).get(); client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get(); refresh(); // doc[] access SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchAllQuery()) .add( scriptFunction(new Script("doc['bar'].value", ScriptType.INLINE, "groovy", null))) .boostMode(CombineFunction.REPLACE)).get(); assertNoFailures(resp); assertOrderedSearchHits(resp, "3", "2", "1"); } public void testScoreAccess() { client().prepareIndex("test", "doc", "1").setSource("foo", "quick brow fox jumped over the lazy dog", "bar", 1).get(); client().prepareIndex("test", "doc", "2").setSource("foo", "fast jumping spiders", "bar", 2).get(); client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get(); refresh(); // _score can be accessed SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchQuery("foo", "dog")) .add(scriptFunction(new Script("_score", ScriptType.INLINE, "groovy", null))) .boostMode(CombineFunction.REPLACE)).get(); assertNoFailures(resp); assertSearchHits(resp, "3", "1"); // _score is comparable // NOTE: it is important to use 0.0 instead of 0 instead Groovy will do an integer comparison // and if the score if between 0 and 1 it will be considered equal to 0 due to the cast resp = client() .prepareSearch("test") .setQuery( functionScoreQuery(matchQuery("foo", "dog")).add( scriptFunction(new Script("_score > 0.0 ? _score : 0", ScriptType.INLINE, "groovy", null))).boostMode( CombineFunction.REPLACE)).get(); assertNoFailures(resp); assertSearchHits(resp, "3", "1"); } }
wimvds/elasticsearch
core/src/test/java/org/elasticsearch/script/GroovyScriptIT.java
Java
apache-2.0
7,046
/* * 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.spark.deploy.rest import java.lang.Boolean import org.json4s.jackson.JsonMethods._ import org.apache.spark.{SparkConf, SparkFunSuite} import org.apache.spark.util.Utils /** * Tests for the REST application submission protocol. */ class SubmitRestProtocolSuite extends SparkFunSuite { test("validate") { val request = new DummyRequest intercept[SubmitRestProtocolException] { request.validate() } // missing everything request.clientSparkVersion = "1.2.3" intercept[SubmitRestProtocolException] { request.validate() } // missing name and age request.name = "something" intercept[SubmitRestProtocolException] { request.validate() } // missing only age request.age = 2 intercept[SubmitRestProtocolException] { request.validate() } // age too low request.age = 10 request.validate() // everything is set properly request.clientSparkVersion = null intercept[SubmitRestProtocolException] { request.validate() } // missing only Spark version request.clientSparkVersion = "1.2.3" request.name = null intercept[SubmitRestProtocolException] { request.validate() } // missing only name request.message = "not-setting-name" intercept[SubmitRestProtocolException] { request.validate() } // still missing name } test("request to and from JSON") { val request = new DummyRequest intercept[SubmitRestProtocolException] { request.toJson } // implicit validation request.clientSparkVersion = "1.2.3" request.active = true request.age = 25 request.name = "jung" val json = request.toJson assertJsonEquals(json, dummyRequestJson) val newRequest = SubmitRestProtocolMessage.fromJson(json, classOf[DummyRequest]) assert(newRequest.clientSparkVersion === "1.2.3") assert(newRequest.clientSparkVersion === "1.2.3") assert(newRequest.active) assert(newRequest.age === 25) assert(newRequest.name === "jung") assert(newRequest.message === null) } test("response to and from JSON") { val response = new DummyResponse response.serverSparkVersion = "3.3.4" response.success = true val json = response.toJson assertJsonEquals(json, dummyResponseJson) val newResponse = SubmitRestProtocolMessage.fromJson(json, classOf[DummyResponse]) assert(newResponse.serverSparkVersion === "3.3.4") assert(newResponse.serverSparkVersion === "3.3.4") assert(newResponse.success) assert(newResponse.message === null) } test("CreateSubmissionRequest") { val message = new CreateSubmissionRequest intercept[SubmitRestProtocolException] { message.validate() } message.clientSparkVersion = "1.2.3" message.appResource = "honey-walnut-cherry.jar" message.mainClass = "org.apache.spark.examples.SparkPie" message.appArgs = Array("two slices") message.environmentVariables = Map("PATH" -> "/dev/null") val conf = new SparkConf(false) conf.set("spark.app.name", "SparkPie") message.sparkProperties = conf.getAll.toMap message.validate() // optional fields conf.set("spark.jars", "mayonnaise.jar,ketchup.jar") conf.set("spark.files", "fireball.png") conf.set("spark.driver.memory", s"${Utils.DEFAULT_DRIVER_MEM_MB}m") conf.set("spark.driver.cores", "180") conf.set("spark.driver.extraJavaOptions", " -Dslices=5 -Dcolor=mostly_red") conf.set("spark.driver.extraClassPath", "food-coloring.jar") conf.set("spark.driver.extraLibraryPath", "pickle.jar") conf.set("spark.driver.supervise", "false") conf.set("spark.executor.memory", "256m") conf.set("spark.cores.max", "10000") message.sparkProperties = conf.getAll.toMap message.appArgs = Array("two slices", "a hint of cinnamon") message.environmentVariables = Map("PATH" -> "/dev/null") message.validate() // bad fields var badConf = conf.clone().set("spark.driver.cores", "one hundred feet") message.sparkProperties = badConf.getAll.toMap intercept[SubmitRestProtocolException] { message.validate() } badConf = conf.clone().set("spark.driver.supervise", "nope, never") message.sparkProperties = badConf.getAll.toMap intercept[SubmitRestProtocolException] { message.validate() } badConf = conf.clone().set("spark.cores.max", "two men") message.sparkProperties = badConf.getAll.toMap intercept[SubmitRestProtocolException] { message.validate() } message.sparkProperties = conf.getAll.toMap // test JSON val json = message.toJson assertJsonEquals(json, submitDriverRequestJson) val newMessage = SubmitRestProtocolMessage.fromJson(json, classOf[CreateSubmissionRequest]) assert(newMessage.clientSparkVersion === "1.2.3") assert(newMessage.appResource === "honey-walnut-cherry.jar") assert(newMessage.mainClass === "org.apache.spark.examples.SparkPie") assert(newMessage.sparkProperties("spark.app.name") === "SparkPie") assert(newMessage.sparkProperties("spark.jars") === "mayonnaise.jar,ketchup.jar") assert(newMessage.sparkProperties("spark.files") === "fireball.png") assert(newMessage.sparkProperties("spark.driver.memory") === s"${Utils.DEFAULT_DRIVER_MEM_MB}m") assert(newMessage.sparkProperties("spark.driver.cores") === "180") assert(newMessage.sparkProperties("spark.driver.extraJavaOptions") === " -Dslices=5 -Dcolor=mostly_red") assert(newMessage.sparkProperties("spark.driver.extraClassPath") === "food-coloring.jar") assert(newMessage.sparkProperties("spark.driver.extraLibraryPath") === "pickle.jar") assert(newMessage.sparkProperties("spark.driver.supervise") === "false") assert(newMessage.sparkProperties("spark.executor.memory") === "256m") assert(newMessage.sparkProperties("spark.cores.max") === "10000") assert(newMessage.appArgs === message.appArgs) assert(newMessage.sparkProperties === message.sparkProperties) assert(newMessage.environmentVariables === message.environmentVariables) } test("CreateSubmissionResponse") { val message = new CreateSubmissionResponse intercept[SubmitRestProtocolException] { message.validate() } message.serverSparkVersion = "1.2.3" message.submissionId = "driver_123" message.success = true message.validate() // test JSON val json = message.toJson assertJsonEquals(json, submitDriverResponseJson) val newMessage = SubmitRestProtocolMessage.fromJson(json, classOf[CreateSubmissionResponse]) assert(newMessage.serverSparkVersion === "1.2.3") assert(newMessage.submissionId === "driver_123") assert(newMessage.success) } test("KillSubmissionResponse") { val message = new KillSubmissionResponse intercept[SubmitRestProtocolException] { message.validate() } message.serverSparkVersion = "1.2.3" message.submissionId = "driver_123" message.success = true message.validate() // test JSON val json = message.toJson assertJsonEquals(json, killDriverResponseJson) val newMessage = SubmitRestProtocolMessage.fromJson(json, classOf[KillSubmissionResponse]) assert(newMessage.serverSparkVersion === "1.2.3") assert(newMessage.submissionId === "driver_123") assert(newMessage.success) } test("SubmissionStatusResponse") { val message = new SubmissionStatusResponse intercept[SubmitRestProtocolException] { message.validate() } message.serverSparkVersion = "1.2.3" message.submissionId = "driver_123" message.success = true message.validate() // optional fields message.driverState = "RUNNING" message.workerId = "worker_123" message.workerHostPort = "1.2.3.4:7780" // test JSON val json = message.toJson assertJsonEquals(json, driverStatusResponseJson) val newMessage = SubmitRestProtocolMessage.fromJson(json, classOf[SubmissionStatusResponse]) assert(newMessage.serverSparkVersion === "1.2.3") assert(newMessage.submissionId === "driver_123") assert(newMessage.driverState === "RUNNING") assert(newMessage.success) assert(newMessage.workerId === "worker_123") assert(newMessage.workerHostPort === "1.2.3.4:7780") } test("ErrorResponse") { val message = new ErrorResponse intercept[SubmitRestProtocolException] { message.validate() } message.serverSparkVersion = "1.2.3" message.message = "Field not found in submit request: X" message.validate() // test JSON val json = message.toJson assertJsonEquals(json, errorJson) val newMessage = SubmitRestProtocolMessage.fromJson(json, classOf[ErrorResponse]) assert(newMessage.serverSparkVersion === "1.2.3") assert(newMessage.message === "Field not found in submit request: X") } private val dummyRequestJson = """ |{ | "action" : "DummyRequest", | "active" : true, | "age" : 25, | "clientSparkVersion" : "1.2.3", | "name" : "jung" |} """.stripMargin private val dummyResponseJson = """ |{ | "action" : "DummyResponse", | "serverSparkVersion" : "3.3.4", | "success": true |} """.stripMargin private val submitDriverRequestJson = s""" |{ | "action" : "CreateSubmissionRequest", | "appArgs" : [ "two slices", "a hint of cinnamon" ], | "appResource" : "honey-walnut-cherry.jar", | "clientSparkVersion" : "1.2.3", | "environmentVariables" : { | "PATH" : "/dev/null" | }, | "mainClass" : "org.apache.spark.examples.SparkPie", | "sparkProperties" : { | "spark.driver.extraLibraryPath" : "pickle.jar", | "spark.jars" : "mayonnaise.jar,ketchup.jar", | "spark.driver.supervise" : "false", | "spark.app.name" : "SparkPie", | "spark.cores.max" : "10000", | "spark.driver.memory" : "${Utils.DEFAULT_DRIVER_MEM_MB}m", | "spark.files" : "fireball.png", | "spark.driver.cores" : "180", | "spark.driver.extraJavaOptions" : " -Dslices=5 -Dcolor=mostly_red", | "spark.executor.memory" : "256m", | "spark.driver.extraClassPath" : "food-coloring.jar" | } |} """.stripMargin private val submitDriverResponseJson = """ |{ | "action" : "CreateSubmissionResponse", | "serverSparkVersion" : "1.2.3", | "submissionId" : "driver_123", | "success" : true |} """.stripMargin private val killDriverResponseJson = """ |{ | "action" : "KillSubmissionResponse", | "serverSparkVersion" : "1.2.3", | "submissionId" : "driver_123", | "success" : true |} """.stripMargin private val driverStatusResponseJson = """ |{ | "action" : "SubmissionStatusResponse", | "driverState" : "RUNNING", | "serverSparkVersion" : "1.2.3", | "submissionId" : "driver_123", | "success" : true, | "workerHostPort" : "1.2.3.4:7780", | "workerId" : "worker_123" |} """.stripMargin private val errorJson = """ |{ | "action" : "ErrorResponse", | "message" : "Field not found in submit request: X", | "serverSparkVersion" : "1.2.3" |} """.stripMargin /** Assert that the contents in the two JSON strings are equal after ignoring whitespace. */ private def assertJsonEquals(jsonString1: String, jsonString2: String): Unit = { val trimmedJson1 = jsonString1.trim val trimmedJson2 = jsonString2.trim val json1 = compact(render(parse(trimmedJson1))) val json2 = compact(render(parse(trimmedJson2))) // Put this on a separate line to avoid printing comparison twice when test fails val equals = json1 == json2 assert(equals, "\"[%s]\" did not equal \"[%s]\"".format(trimmedJson1, trimmedJson2)) } } private class DummyResponse extends SubmitRestProtocolResponse private class DummyRequest extends SubmitRestProtocolRequest { var active: Boolean = null var age: Integer = null var name: String = null protected override def doValidate(): Unit = { super.doValidate() assertFieldIsSet(name, "name") assertFieldIsSet(age, "age") assert(age > 5, "Not old enough!") } }
esi-mineset/spark
core/src/test/scala/org/apache/spark/deploy/rest/SubmitRestProtocolSuite.scala
Scala
apache-2.0
12,949
/* * Copyright 2010-2015 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. */ package com.amazonaws.services.elasticfilesystem.model; import com.amazonaws.AmazonServiceException; /** * <p> * Returned if the specified <code>FileSystemId</code> does not exist in the * requester's AWS account. * </p> */ public class FileSystemNotFoundException extends AmazonServiceException { private static final long serialVersionUID = 1L; private String errorCode; /** * Constructs a new FileSystemNotFoundException with the specified error * message. * * @param message * Describes the error encountered. */ public FileSystemNotFoundException(String message) { super(message); } /** * Sets the value of the ErrorCode property for this object. * * @param errorCode * The new value for the ErrorCode property for this object. */ public void setErrorCode(String errorCode) { this.errorCode = errorCode; } /** * Returns the value of the ErrorCode property for this object. * * @return The value of the ErrorCode property for this object. */ public String getErrorCode() { return this.errorCode; } /** * Sets the value of the ErrorCode property for this object. * * @param errorCode * The new value for the ErrorCode property for this object. * @return Returns a reference to this object so that method calls can be * chained together. */ public FileSystemNotFoundException withErrorCode(String errorCode) { setErrorCode(errorCode); return this; } }
mahaliachante/aws-sdk-java
aws-java-sdk-efs/src/main/java/com/amazonaws/services/elasticfilesystem/model/FileSystemNotFoundException.java
Java
apache-2.0
2,190
/// <reference path='fourslash.ts' /> // @Filename: foo.ts //// export function /*Destination*/bar() { return "bar"; } //// import('./foo').then(({ [|ba/*1*/r|] }) => undefined); verify.goToDefinition("1", "Destination");
basarat/TypeScript
tests/cases/fourslash/goToDefinitionDynamicImport4.ts
TypeScript
apache-2.0
234
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.web.filter; import org.broadleafcommerce.common.web.BroadleafTimeZoneResolverImpl; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.TimeZone; /** * * @author Phillip Verheyden (phillipuniverse) */ @Component("blAdminTimeZoneResolver") public class BroadleafAdminTimeZoneResolver extends BroadleafTimeZoneResolverImpl { @Override public TimeZone resolveTimeZone(WebRequest request) { //TODO: eventually this should support a using a timezone from the currently logged in Admin user preferences return super.resolveTimeZone(request); } }
cloudbearings/BroadleafCommerce
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/filter/BroadleafAdminTimeZoneResolver.java
Java
apache-2.0
1,370
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that Cell is considered invariant with respect to its // type. use std::cell::Cell; struct Foo<'a> { x: Cell<Option<&'a int>>, } fn use_<'short,'long>(c: Foo<'short>, s: &'short int, l: &'long int, _where:Option<&'short &'long ()>) { let _: Foo<'long> = c; //~ ERROR mismatched types } fn main() { }
barosl/rust
src/test/compile-fail/variance-cell-is-invariant.rs
Rust
apache-2.0
853
/* * 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.ignite.visor.commands.alert import java.io.{File, FileNotFoundException} import java.util.UUID import java.util.concurrent.atomic._ import org.apache.ignite._ import org.apache.ignite.cluster.ClusterNode import org.apache.ignite.events.EventType._ import org.apache.ignite.events.{DiscoveryEvent, Event} import org.apache.ignite.internal.util.scala.impl import org.apache.ignite.internal.util.{IgniteUtils => U} import org.apache.ignite.lang.IgnitePredicate import org.apache.ignite.visor.VisorTag import org.apache.ignite.visor.commands.alert.VisorAlertCommand._ import org.apache.ignite.visor.commands.common.{VisorConsoleCommand, VisorTextTable} import org.apache.ignite.visor.visor._ import scala.collection.immutable.HashMap import scala.collection.mutable import scala.language.implicitConversions import scala.sys.process.{Process, ProcessLogger} import scala.util.control.Breaks._ /** * ==Overview== * Visor 'alert' command implementation. * * ==Help== * {{{ * +---------------------------------------------------------------------+ * | alert | Generates alerts for user-defined events. | * | | Node events and grid-wide events are defined via mnemonics. | * +---------------------------------------------------------------------+ * }}} * * ====Specification==== * {{{ * alert * alert "-u {-id=<alert-id>|-a}" * alert "-r {-t=<sec>} {-<metric>=<condition><value>} ... {-<metric>=<condition><value>}" * }}} * * ====Arguments==== * {{{ * -n * Alert name * -u * Unregisters alert(s). Either '-a' flag or '-id' parameter is required. * Note that only one of the '-u' or '-r' is allowed. * If neither '-u' or '-r' provided - all alerts will be printed. * -a * When provided with '-u' - all alerts will be unregistered. * -id=<alert-id> * When provided with '-u' - alert with matching ID will be unregistered. * -r * Register new alert with mnemonic predicate(s). * Note that only one of the '-u' or '-r' is allowed. * If neither '-u' or '-r' provided - all alerts will be printed. * -t * Defines notification frequency in seconds. Default is 60 seconds. * This parameter can only appear with '-r'. * -s * Define script for execution when alert triggered. * For configuration of throttle period see -i argument. * Script will receive following arguments: * 1) Alert name or alert ID when name is not defined. * 2) Alert condition as string. * 3, ...) Values of alert conditions ordered as in alert command. * -i * Configure alert notification minimal throttling interval in seconds. Default is 0 seconds. * * -<metric> * This defines a mnemonic for the metric that will be measured: * * Grid-wide metrics (not node specific): * cc - Total number of available CPUs in the grid. * nc - Total number of nodes in the grid. * hc - Total number of physical hosts in the grid. * cl - Current average CPU load (in %) in the grid. * * Per-node current metrics: * aj - Active jobs on the node. * cj - Cancelled jobs on the node. * tc - Thread count on the node. * ut - Up time on the node. * Note: <num> can have 's', 'm', or 'h' suffix indicating * seconds, minutes, and hours. By default (no suffix provided) * value is assumed to be in milliseconds. * je - Job execute time on the node. * jw - Job wait time on the node. * wj - Waiting jobs count on the node. * rj - Rejected jobs count on the node. * hu - Heap memory used (in MB) on the node. * cd - Current CPU load on the node. * hm - Heap memory maximum (in MB) on the node. * ), * <condition> * Comparison part of the mnemonic predicate: * eq - Equal '=' to '<value>' number. * neq - Not equal '!=' to '<value>' number. * gt - Greater than '>' to '<value>' number. * gte - Greater than or equal '>=' to '<value>' number. * lt - Less than '<' to 'NN' number. * lte - Less than or equal '<=' to '<value>' number. * }}} * * ====Examples==== * {{{ * alert * Prints all currently registered alerts. * alert "-u -a" * Unregisters all currently registered alerts. * alert "-u -id=12345678" * Unregisters alert with provided ID. * alert "-r -t=900 -cc=gte4 -cl=gt50" * Notify every 15 min if grid has >= 4 CPUs and > 50% CPU load. * alert "-r -n=Nodes -t=15 -nc=gte3 -s=/home/user/scripts/alert.sh -i=300" * Notify every 15 second if grid has >= 3 nodes and execute script "/home/user/scripts/alert.sh" with * repeat interval not less than 5 min. * }}} */ class VisorAlertCommand extends VisorConsoleCommand { @impl protected val name = "alert" /** Alerts. */ private var alerts = new HashMap[String, VisorAlert] /** Map of last sent notification per alert ID. */ private var sent = new HashMap[String, Long] /** Map of alert statistics. */ private var stats = new HashMap[String, VisorStats] /** Last 10 sent alerts. */ private var last10 = List.empty[VisorSentAlert] /** Subscribe guard. */ private val guard = new AtomicBoolean(false) /** Node metric update listener. */ private var lsnr: IgnitePredicate[Event] = _ /** * ===Command=== * Lists all registered alerts. * * ===Examples=== * <ex>alert</ex> * Prints all currently registered alerts. */ def alert() { alert("") } /** * ===Command=== * Registers, unregisters and list alerts. * * ===Examples=== * <ex>alert "-u -a"</ex> * Unregisters all currently registered alerts. * * <ex>alert "-i"</ex> * Starts command in interactive mode. * * <ex>alert "-u -id=12345678"</ex> * Unregisters alert with provided ID. * * <ex>alert "-r -t=900 -cc=gte4 -cl=gt50"</ex> * Notify every 15 min if grid has >= 4 CPUs and > 50% CPU load. * * @param args Command arguments. */ def alert(args: String) { assert(args != null) val argLst = parseArgs(args) if (hasArgFlag("u", argLst)) unregisterAlert(argLst) else if (hasArgFlag("r", argLst)) registerAlert(argLst) else if (args.length() > 0) scold("Invalid arguments: " + args) else printAlerts() } /** * Create function to check specific node condition. * * @param exprStr Expression string. * @param value Value generator. */ private def makeNodeFilter(exprStr: String, value: (ClusterNode) => Long): Option[(ClusterNode) => (Long, Boolean)] = { assert(exprStr != null) assert(value != null) val expr = makeExpression(exprStr) // Note that if 'f(n)' is false - 'value' won't be evaluated. expr match { case Some(f) => Some((n: ClusterNode) => { val v = value(n) (v, f.apply(v)) }) case _ => throw new IgniteException("Invalid expression: " + exprStr) } } /** * Create function to check specific grid condition. * * @param exprStr Expression string. * @param value Value generator. */ private def makeGridFilter(exprStr: String, value: () => Long): Option[() => (Long, Boolean)] = { assert(exprStr != null) assert(value != null) val expr = makeExpression(exprStr) // Note that if 'f' is false - 'value' won't be evaluated. expr match { case Some(f) => Some(() => { val v = value() (v, f.apply(v)) }) case _ => throw new IgniteException("Invalid expression: " + exprStr) } } /** * @param args Parsed argument list. */ private def registerAlert(args: ArgList) { breakable { assert(args != null) if (checkConnected()) { var name: Option[String] = None var script: Option[String] = None val conditions = mutable.ArrayBuffer.empty[VisorAlertCondition] var freq = DFLT_FREQ var interval = 0L try { args.foreach(arg => { val (n, v) = arg n match { case c if ALERT_DESCRIPTORS.contains(c) && v != null => val meta = ALERT_DESCRIPTORS(c) if (meta.byGrid) conditions += VisorAlertCondition(arg, gridFunc = makeGridFilter(v, meta.gridFunc)) else conditions += VisorAlertCondition(arg, nodeFunc = makeNodeFilter(v, meta.nodeFunc)) // Other tags. case "n" if v != null => name = Some(v) case "t" if v != null => freq = v.toLong case "s" if v != null => script = Option(v) case "i" if v != null => interval = v.toLong case "r" => () // Skipping. case _ => throw new IgniteException("Invalid argument: " + makeArg(arg)) } }) } catch { case e: NumberFormatException => scold("Number conversion error: " + e.getMessage) break() case e: Exception => scold(e) break() } if (conditions.isEmpty) { scold("No predicates have been provided in args: " + makeArgs(args)) break() } val alert = VisorAlert( id = id8, name = name, conditions = conditions, perGrid = conditions.exists(_.gridFunc.isDefined), perNode = conditions.exists(_.nodeFunc.isDefined), spec = makeArgs(args.filter((arg) => arg._1 != "r")), conditionSpec = makeArgs(conditions.map(_.arg)), freq = freq, createdOn = System.currentTimeMillis(), varName = setVar(id8, "a"), notification = VisorAlertNotification(script, interval * 1000) ) // Subscribe for node metric updates - if needed. registerListener() alerts = alerts + (alert.id -> alert) stats = stats + (alert.id -> VisorStats()) // Set visor var pointing to created alert. mset(alert.varName, alert.id) println("Alert '" + alert.id + "' (" + alert.varName + ") registered.") } } } /** * Registers node metrics update listener, if one wasn't registered already. */ private def registerListener() { if (guard.compareAndSet(false, true)) { assert(lsnr == null) lsnr = new IgnitePredicate[Event] { override def apply(evt: Event): Boolean = { val discoEvt = evt.asInstanceOf[DiscoveryEvent] val node = ignite.cluster.node(discoEvt.eventNode().id()) if (node != null && !node.isDaemon) alerts foreach (t => { val (id, alert) = t var check = (true, true) var printNid = false val values = mutable.ArrayBuffer.empty[String] var valuesView = mutable.ArrayBuffer.empty[String] try check = alert.conditions.foldLeft(check) { (res, cond) => { val gridRes = cond.gridFunc.forall(f => { val (value, check) = f() values += value.toString valuesView += cond.arg._1 + "=" + value.toString check }) val nodeRes = cond.nodeFunc.forall(f => { val (value, check) = f(node) values += value.toString valuesView += cond.arg._1 + "=" + value.toString printNid = true check }) (res._1 && gridRes) -> (res._2 && nodeRes) } } catch { // In case of exception (like an empty projection) - simply return. case _: Throwable => return true } if (check._1 && check._2) { val now = System.currentTimeMillis() var go: Boolean = false go = (now - sent.getOrElse(id, 0L)) / 1000 >= alert.freq if (go) { sent = sent + (id -> now) val stat: VisorStats = stats(id) assert(stat != null) // Update stats. if (stat.firstSnd == 0) stat.firstSnd = now stat.cnt += 1 stat.lastSnd = now stats = stats + (id -> stat) val nodeIdIp = nodeId8Addr(node.id()).split(", ") // Write to Visor log if it is started (see 'log' command). logText( "Alert [" + "id=" + alert.id + "(@" + alert.varName + "), " + (if (printNid) "nid8=" + nodeIdIp(0) + ", ip=" + nodeIdIp.lift(1).getOrElse(NA) + ", " else "") + "spec=[" + alert.spec + "], " + "values=[" + valuesView.mkString("; ") + "], " + "created on=" + formatDateTime(alert.createdOn) + "]" ) executeAlertScript(alert, node, values) last10 = VisorSentAlert( id = alert.id, name = alert.name.getOrElse("(Not set)"), spec = alert.spec, createdOn = alert.createdOn, sentTs = now ) +: last10 if (last10.size > 10) last10 = last10.take(10) } } else alert.notification.notified = false }) true } } ignite.events().localListen(lsnr, EVT_NODE_METRICS_UPDATED) } } /** * Unregisters previously registered node metric update listener. */ private def unregisterListener() { if (guard.compareAndSet(true, false)) { assert(lsnr != null) assert(ignite.events().stopLocalListen(lsnr)) lsnr = null } } /** * Resets command. */ private def reset() { unregisterAll() unregisterListener() } /** * Prints advise. */ private def advise() { println("\nType 'help alert' to see how to manage alerts.") } /** * Unregisters all alerts. */ private def unregisterAll() { mclear("-al") alerts = new HashMap[String, VisorAlert] } /** * * @param args Parsed argument list. */ private def unregisterAlert(args: ArgList) { breakable { assert(args != null) if (alerts.isEmpty) { scold("No alerts have been registered yet.") break() } // Unregister all alerts. if (hasArgFlag("a", args)) { unregisterAll() println("All alerts have been unregistered.") } // Unregister specific alert. else if (hasArgName("id", args)) { val idOpt = argValue("id", args) if (idOpt.isDefined) { val id = idOpt.get val a = alerts.get(id) if (a.isDefined) { alerts -= id // Clear variable host. mclear(a.get.varName) println("Alert '" + id + "' unregistered.") } else { scold("Failed to find alert with ID: " + id) break() } } else { scold("No value for '-id' parameter found.") break() } } else { scold("Failed to unregister alert.", "Either \"-a\" or \"-id\" parameter is required.") break() } if (alerts.isEmpty) unregisterListener() } } /** * Prints out all alerts. */ private def printAlerts() { if (alerts.isEmpty) println("No alerts are registered.") else { println("Summary:") val sum = new VisorTextTable() val firstSnd = (-1L /: stats.values)((b, a) => if (b == -1) a.firstSnd else math.min(b, a.firstSnd)) val lastSnd = (0L /: stats.values)((b, a) => math.max(b, a.lastSnd)) sum += ("Total alerts", alerts.size) sum += ("Total sends", (0 /: stats.values)((b, a) => b + a.cnt)) sum += ("First send", if (firstSnd == 0) NA else formatDateTime(firstSnd)) sum += ("Last send", if (lastSnd == 0) NA else formatDateTime(lastSnd)) sum.render() } if (last10.isEmpty) println("\nNo alerts have been sent.") else { val last10T = VisorTextTable() last10T #= ("ID(@)/Name", "Spec", "Sent", "Registered", "Count") last10.foreach((a: VisorSentAlert) => last10T += ( a.idVar + "/" + a.name, a.spec, formatDateTime(a.sentTs), formatDateTime(a.createdOn), stats(a.id).cnt )) println("\nLast 10 Triggered Alerts:") last10T.render() } if (alerts.nonEmpty) { val tbl = new VisorTextTable() tbl #= ("ID(@)/Name", "Spec", "Count", "Registered", "First Send", "Last Send") val sorted = alerts.values.toSeq.sortWith(_.varName < _.varName) sorted foreach (a => { val stat = stats(a.id) tbl += ( a.id + "(@" + a.varName + ')' + "/" + a.name.getOrElse("Not set"), a.spec, stat.cnt, formatDateTime(a.createdOn), if (stat.firstSnd == 0) NA else formatDateTime(stat.firstSnd), if (stat.lastSnd == 0) NA else formatDateTime(stat.lastSnd) ) }) println("\nAlerts: " + sorted.size) tbl.render() // Print advise. advise() } } /** * Gets unique ID8 id for the alert. * * @return 8-character locally unique alert ID. */ private def id8: String = { while (true) { val id = UUID.randomUUID().toString.substring(0, 8) // Have to check for guaranteed uniqueness. if (!alerts.contains(id)) return id } assert(false, "Should never happen.") "" } /** * Try to execute specified script on alert. * * @param alert Alarmed alert. * @param node Node where alert is alarmed. * @param values Values ith that alert is generated. */ private def executeAlertScript(alert: VisorAlert, node: ClusterNode, values: Seq[String]) { val n = alert.notification if (n.notified && System.currentTimeMillis() - n.notifiedTime < n.throttleInterval) return try { n.script.foreach(script => { val scriptFile = new File(script) if (!scriptFile.exists()) throw new FileNotFoundException("Script/executable not found: " + script) val scriptFolder = scriptFile.getParentFile val p = Process(Seq(script, alert.name.getOrElse(alert.id), alert.conditionSpec) ++ values, Some(scriptFolder)) p.run(ProcessLogger((fn: String) => {})) n.notifiedTime = System.currentTimeMillis() n.notified = true }) } catch { case e: Throwable => logText("Script execution failed [" + "id=" + alert.id + "(@" + alert.varName + "), " + "error=" + e.getMessage + ", " + "]") } } } /** * Visor alert. * * @param id Alert id. * @param name Alert name. * @param conditions List of alert condition metadata. * @param perGrid Condition per grid exists. * @param perNode Condition per node exists. * @param freq Freq of alert check. * @param spec Alert command specification. * @param conditionSpec Alert condition command specification. * @param varName Alert id short name. * @param createdOn Timestamp of alert creation. * @param notification Alert notification information. */ private case class VisorAlert( id: String, name: Option[String], conditions: Seq[VisorAlertCondition], perGrid: Boolean, perNode: Boolean, freq: Long, spec: String, conditionSpec: String, varName: String, createdOn: Long, notification: VisorAlertNotification ) { assert(id != null) assert(spec != null) assert(varName != null) } /** * Visor alert notification information. * * @param script Script to execute on alert firing. * @param throttleInterval Minimal interval between script execution. * @param notified `True` when on previous check of condition alert was fired or `false` otherwise. * @param notifiedTime Time of first alert notification in series of firings. */ private case class VisorAlertNotification( script: Option[String], throttleInterval: Long, var notified: Boolean = false, var notifiedTime: Long = -1L ) { assert(script != null) } /** * Visor alert condition information. * * @param arg Configuration argument. * @param gridFunc Function to check grid condition. * @param nodeFunc Function to check node condition. */ private case class VisorAlertCondition( arg: (String, String), gridFunc: Option[() => (Long, Boolean)] = None, nodeFunc: Option[(ClusterNode) => (Long, Boolean)] = None ) /** * Snapshot of the sent alert. */ private case class VisorSentAlert( id: String, name: String, sentTs: Long, createdOn: Long, spec: String ) { assert(id != null) assert(spec != null) def idVar: String = { val v = mfindHead(id) if (v.isDefined) id + "(@" + v.get._1 + ")" else id } } /** * Statistics holder for visor alert. */ private case class VisorStats( var cnt: Int = 0, var firstSnd: Long = 0, var lastSnd: Long = 0 ) /** * Metadata object for visor alert. * * @param byGrid If `true` then `gridFunc` should be used. * @param gridFunc Function to extract value to check in case of alert for grid metrics. * @param nodeFunc Function to extract value to check in case of alert for node metrics */ private case class VisorAlertMeta( byGrid: Boolean, gridFunc: () => Long, nodeFunc: (ClusterNode) => Long ) /** * Companion object that does initialization of the command. */ object VisorAlertCommand { /** Default alert frequency. */ val DFLT_FREQ = 60L private val dfltNodeValF = (_: ClusterNode) => 0L private val dfltGridValF = () => 0L private def cl(): IgniteCluster = ignite.cluster() private[this] val BY_GRID = true private[this] val BY_NODE = false private val ALERT_DESCRIPTORS = Map( "cc" -> VisorAlertMeta(BY_GRID, () => cl().metrics().getTotalCpus, dfltNodeValF), "nc" -> VisorAlertMeta(BY_GRID, () => cl().nodes().size, dfltNodeValF), "hc" -> VisorAlertMeta(BY_GRID, () => U.neighborhood(cl().nodes()).size, dfltNodeValF), "cl" -> VisorAlertMeta(BY_GRID, () => (cl().metrics().getAverageCpuLoad * 100).toLong, dfltNodeValF), "aj" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentActiveJobs), "cj" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentCancelledJobs), "tc" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentThreadCount), "ut" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getUpTime), "je" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentJobExecuteTime), "jw" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentJobWaitTime), "wj" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentWaitingJobs), "rj" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getCurrentRejectedJobs), "hu" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getHeapMemoryUsed), "cd" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => node.metrics().getHeapMemoryMaximum), "hm" -> VisorAlertMeta(BY_NODE, dfltGridValF, (node) => (node.metrics().getCurrentCpuLoad * 100).toLong)) /** Singleton command. */ private val cmd = new VisorAlertCommand addHelp( name = "alert", shortInfo = "Alerts for user-defined events.", longInfo = Seq( "Generates alerts for user-defined events.", "Node events and grid-wide events are defined via mnemonics." ), spec = Seq( "alert", "alert -u {-id=<alert-id>|-a}", "alert -r {-t=<sec>} {-<metric>=<condition><value>} ... {-<metric>=<condition><value>}" ), args = Seq( "-n" -> "Alert name", "-u" -> Seq( "Unregisters alert(s). Either '-a' flag or '-id' parameter is required.", "Note that only one of the '-u' or '-r' is allowed.", "If neither '-u' or '-r' provided - all alerts will be printed." ), "-a" -> "When provided with '-u' - all alerts will be unregistered.", ("-id=<alert-id>", "When provided with '-u' - alert with matching ID will be unregistered" + "Note you can also use '@a0' ... '@an' variables as shortcut to <alert-id>."), "-r" -> Seq( "Register new alert with mnemonic predicate(s).", "Note that only one of the '-u' or '-r' is allowed.", "If neither '-u' or '-r' provided - all alerts will be printed." ), "-t" -> Seq( "Defines notification frequency in seconds. Default is 60 seconds.", "This parameter can only appear with '-r'." ), "-s" -> Seq( "Define script for execution when alert triggered.", "For configuration of throttle period see -i argument.", "Script will receive following arguments:", " 1) Alert name or alert ID when name is not defined.", " 2) Alert condition as string.", " 3, ...) Values of alert conditions ordered as in alert command." ), "-i" -> "Configure alert notification minimal throttling interval in seconds. Default is 0 seconds.", "-<metric>" -> Seq( "This defines a mnemonic for the metric that will be measured:", "", "Grid-wide metrics (not node specific):", " cc - Total number of available CPUs in the grid.", " nc - Total number of nodes in the grid.", " hc - Total number of physical hosts in the grid.", " cl - Current average CPU load (in %) in the grid.", "", "Per-node current metrics:", " aj - Active jobs on the node.", " cj - Cancelled jobs on the node.", " tc - Thread count on the node.", " ut - Up time on the node.", " Note: <num> can have 's', 'm', or 'h' suffix indicating", " seconds, minutes, and hours. By default (no suffix provided)", " value is assumed to be in milliseconds.", " je - Job execute time on the node.", " jw - Job wait time on the node.", " wj - Waiting jobs count on the node.", " rj - Rejected jobs count on the node.", " hu - Heap memory used (in MB) on the node.", " cd - Current CPU load on the node.", " hm - Heap memory maximum (in MB) on the node." ), "<condition>" -> Seq( "Comparison part of the mnemonic predicate:", " eq - Equal '=' to '<value>' number.", " neq - Not equal '!=' to '<value>' number.", " gt - Greater than '>' to '<value>' number.", " gte - Greater than or equal '>=' to '<value>' number.", " lt - Less than '<' to 'NN' number.", " lte - Less than or equal '<=' to '<value>' number." ) ), examples = Seq( "alert" -> "Prints all currently registered alerts.", "alert -u -a" -> "Unregisters all currently registered alerts.", "alert -u -id=12345678" -> "Unregisters alert with provided ID.", "alert -u -id=@a0" -> "Unregisters alert with provided ID taken from '@a0' memory variable.", "alert -r -t=900 -cc=gte4 -cl=gt50" -> "Notify every 15 min if grid has >= 4 CPUs and > 50% CPU load.", "alert \"-r -n=Nodes -t=15 -nc=gte3 -s=/home/user/scripts/alert.sh -i=300" -> ("Notify every 15 second if grid has >= 3 nodes and execute script \"/home/user/scripts/alert.sh\" with " + "repeat interval not less than 5 min.") ), emptyArgs = cmd.alert, withArgs = cmd.alert ) addCloseCallback(() => { cmd.reset() }) /** * Singleton. */ def apply() = cmd /** * Implicit converter from visor to commands "pimp". * * @param vs Visor tagging trait. */ implicit def fromAlert2Visor(vs: VisorTag): VisorAlertCommand = cmd }
alexzaitzev/ignite
modules/visor-console/src/main/scala/org/apache/ignite/visor/commands/alert/VisorAlertCommand.scala
Scala
apache-2.0
33,630
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(intrinsics)] use std::ptr; struct Point { x: f32, y: f32, z: f32, } extern "rust-intrinsic" { fn return_address() -> *const u8; } fn f(result: &mut uint) -> Point { unsafe { *result = return_address() as uint; Point { x: 1.0, y: 2.0, z: 3.0, } } } fn main() { let mut intrinsic_reported_address = 0; let pt = f(&mut intrinsic_reported_address); let actual_address = &pt as *const Point as uint; assert_eq!(intrinsic_reported_address, actual_address); }
barosl/rust
src/test/run-pass/intrinsic-return-address.rs
Rust
apache-2.0
1,043
/* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2014 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.server.security.service; import java.util.List; /** * <p> * Provides row-level security to the various CRUD operations in the admin * * <p> * This security service can be extended by the use of {@link RowLevelSecurityProviders}, of which this service has a list. * To add additional providers, add this to an applicationContext merged into the admin application: * * {@code * <bean id="blCustomRowSecurityProviders" class="org.springframework.beans.factory.config.ListFactoryBean" > * <property name="sourceList"> * <list> * <ref bean="customProvider" /> * </list> * </property> * </bean> * <bean class="org.broadleafcommerce.common.extensibility.context.merge.LateStageMergeBeanPostProcessor"> * <property name="collectionRef" value="blCustomRowSecurityProviders" /> * <property name="targetRef" value="blRowLevelSecurityProviders" /> * </bean> * } * * @author Phillip Verheyden (phillipuniverse) * @author Brian Polster (bpolster) */ public interface RowLevelSecurityService extends RowLevelSecurityProvider { /** * Gets all of the registered providers * @return the providers configured for this service */ public List<RowLevelSecurityProvider> getProviders(); }
cengizhanozcan/BroadleafCommerce
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/security/service/RowLevelSecurityService.java
Java
apache-2.0
1,996
var $ = require('common:widget/ui/jquery/jquery.js'); var UT = require('common:widget/ui/ut/ut.js'); var FBClient = {}; var TPL_CONF = require('home:widget/ui/facebook/fbclient-tpl.js'); /** * Fackbook module init function * @return {object} [description] */ var WIN = window, DOC = document, conf = WIN.conf.FBClient, undef; var UI_CONF = { // ui el uiMod: "#fbMod" , uiBtnLogin: ".fb-mod_login_btn" , uiBtnLogout: ".fb-mod_logout" , uiBtnRefresh: ".fb-mod_refresh" , uiSide: ".fb-mod_side" , uiBtnClose: ".fb-mod_close" , uiWrap: ".fb-mod_wrap" , uiList: ".fb-mod_list" , uiUsrinfo: ".fb-mod_usrinfo" , uiAvatar: ".fb-mod_avatar" , uiTextareaSubmit: ".fb-mod_submit" , uiBtnSubmit: ".fb-mod_submit_btn" , uiBody: ".fb-mod_body" , uiTip: ".fb-mod_tip" , uiSideHome: ".fb-mod_side_home" , uiSideFriend: ".fb-mod_side_friend em" , uiSideMessages: ".fb-mod_side_messages em" , uiSideNotifications: ".fb-mod_side_notifications em" , uiBodyLoader: ".fb-mod_body_loader" }; FBClient.init = function() { // DOC.body.innerHTML += '<div id="fb-root"></div>'; var that = this, $this = $(UI_CONF.uiMod); /* ui controller */ that.ui = { uiMod: $this , side: $this.find(UI_CONF.uiSide) , btnLogin: $this.find(UI_CONF.uiBtnLogin) , btnLogout: $this.find(UI_CONF.uiBtnLogout) , btnClose: $this.find(UI_CONF.uiBtnClose) , btnRefresh: $this.find(UI_CONF.uiBtnRefresh) , wrap: $this.find(UI_CONF.uiWrap) , list: $this.find(UI_CONF.uiList) , usrinfo: $this.find(UI_CONF.uiUsrinfo) , avatar: $this.find(UI_CONF.uiAvatar) , textareaSubmit: $this.find(UI_CONF.uiTextareaSubmit) , btnSubmit: $this.find(UI_CONF.uiBtnSubmit) , body: $this.find(UI_CONF.uiBody) , tip: $this.find(UI_CONF.uiTip) , sideHome: $this.find(UI_CONF.uiSideHome) , sideFriend: $this.find(UI_CONF.uiSideFriend) , sideNotifications: $this.find(UI_CONF.uiSideNotifications) , sideMessages: $this.find(UI_CONF.uiSideMessages) , bodyLoader: $this.find(UI_CONF.uiBodyLoader) , panelHome: $this.find(".fb-mod_c") , panelFriend: $('<div class="fb-mod_c fb-mod_c_friend" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelNotifications: $('<div class="fb-mod_c fb-mod_c_notifications" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , panelMessages: $('<div class="fb-mod_c fb-mod_c_messages" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>') , bubble: $('<div class="fb-mod_bubble">' + (conf.tplBubble || "NEW") + '</div>') , placeholder: function(first, last) { return $(TPL_CONF.tplPlaceholder.replaceTpl({first: first, last: last })) } }; // live loader that.ui.liveLoader = that.ui.bodyLoader.clone(!0) .css({"width": "370px"}) .insertBefore(that.ui.list).hide(); $("body").append('<div id="fb-root" class=" fb_reset"></div>'); that.ui.wrap.append(that.ui.panelFriend).append(that.ui.panelNotifications).append(that.ui.panelMessages); // window.ActiveXObject && !window.XMLHttpRequest && $("body").append(that.ui.fakeBox = $(that.ui.textareaSubmit[0].cloneNode(false)).css({ "position": "absolute" , "top" : "0" , "left": "0" , "right": "-10000px" , "visibility": "hidden" , "padding-top": "0" , "padding-bottom": "0" , "height": "18" //for fixed , "width": that.ui.textareaSubmit.width() })); that.supportAnimate = function(style, name) { return 't' + name in style || 'webkitT' + name in style || 'MozT' + name in style || 'OT' + name in style; }((new Image).style, "ransition"); /* status controller 0 ==> none 1 ==> doing 2 ==> done */ that.status = { login: 0 , fold: 0 , sdkLoaded: 0 , scrollLoaded: 0 , insertLoaded: 0 , fixed: 0 , eventBinded: 0 , bubble: 0 }; // bubble !$.cookie("fb_bubble") && (that.status.bubble = 1, that.ui.uiMod.append(that.ui.bubble)); /* post status cache */ that.cache = { prePost: null , nextPost: null , refreshPost: null , noOldPost: 0 , myPost: 0 , stayTip: "" , userID: null , userName: "" , panel: that.ui.panelHome , curSideType: "" , panelRendered: 0 }; that.ui.btnClose.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_logo").mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"}); that.foldHandle.call(that, e); }); $(".fb-mod_side_home").mousedown(function(e) { UT && that.status.fold === 0 && UT.send({"type": "click", "position": "fb", "sort": "pull","modId":"fb-box"}); UT && UT.send({"type": "click", "position": "fb", "sort": "icon_home","modId":"fb-box"}); that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_home_cur", that.ui.panelHome); }); $(".fb-mod_side_friend").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_friend", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_friend_cur", that.ui.panelFriend); }); $(".fb-mod_side_messages").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_messages", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_messages_cur", that.ui.panelMessages); }); $(".fb-mod_side_notifications").mousedown(function(e) { var logObj = { "type": "click", "position": "fb", "sort": "icon_notifications", "modId": "fb-box" }; if(that.status.login !== 2) { logObj.ac = "b"; } UT && UT.send(logObj); if(that.status.login !== 2) return false; that.status.fold === 0 && that.foldHandle.call(that, e); that.clickHandle($(this), "fb-mod_side_notifications_cur", that.ui.panelNotifications); }); that.ui.btnRefresh.mousedown(function(e) { UT && UT.send({"type": "click", "position": "fb", "sort": "refresh","modId":"fb-box"}); }); $(".fb-mod_side_friend").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_messages").click(function(e) { e.preventDefault(); }); $(".fb-mod_side_notifications").click(function(e) { e.preventDefault(); }); // 7. FB-APP的打开、收缩机制;——点击F、箭头、new三个地方打开,点击F、箭头两个地方关闭;做上新功能上线的提示图标,放cookies内; // // kill the feature // that.ui.side.mouseover(function(e) { // that.status.fold === 0 && that.foldHandle.call(that, e); // }); that.ui.textareaSubmit.attr("placeholder", conf.tplSuggestText); // sdk loading that.status.sdkLoaded = 1; /*$.ajax({ url: that.conf.modPath, dataType: "script", cache: true, success: function() { }, error: function() { } });*/ require.async('home:widget/ui/facebook/fbclient-core.js'); }; if(window.ActiveXObject && !window.XMLHttpRequest) { var body = DOC.body; if(body) { body.style.backgroundAttachment = 'fixed'; if(body.currentStyle.backgroundImage == "none") { body.style.backgroundImage = (DOC.domain.indexOf("https:") == 0) ? 'url(https:///)' : 'url(about:blank)'; } } } FBClient.clickHandle = function($el, type, panel) { var that = this, fold = that.status.fold, sideHome = that.ui.sideHome, cache = that.cache; // fold && sideHome.removeClass(type); cache.curSide && cache.curSide.removeClass(cache.curSideType); $el && $el.addClass(type); cache.curSide = $el; cache.curSideType = type; cache.panel && cache.panel.hide(); panel && panel.show(); cache.panel = panel; }; FBClient.foldHandle = function(e) { var that = this, fold = that.status.fold, sdkLoaded = that.status.sdkLoaded; // playing animation if(fold === 1) return; that.status.fold = 1; that.clickHandle(fold ? null : that.ui.sideHome, fold ? "" : "fb-mod_side_home_cur", that.ui.panelHome); that.status.bubble && ($.cookie("fb_bubble", 1), that.status.bubble = 0, that.ui.bubble.hide()); fold ? that.ui.uiMod.removeClass("fb-mod--fixed").addClass("fb-mod--fold") : that.ui.uiMod.removeClass("fb-mod--fold"); setTimeout(function() { // fold ? sideHome.removeClass("fb-mod_side_home_cur") : that.ui.sideHome.addClass("fb-mod_side_home_cur"), that.cache.curSideType = "fb-mod_side_home_cur"; (that.status.fold = fold ? 0 : 2) && that.status.fixed && that.ui.uiMod.addClass("fb-mod--fixed"); if (!that.status.eventBinded) { if (sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; } else { var t = setInterval(function () { if (that.status.sdkLoaded === 2) { that.bindEvent.call(that); that.status.eventBinded = 2; clearInterval(t); } }, 1000); } } if(fold || sdkLoaded) return; !function(el) { if($.browser.mozilla){ el.addEventListener('DOMMouseScroll',function(e){ el.scrollTop += e.detail > 0 ? 30 : -30; e.preventDefault(); }, !1); } else el.onmousewheel = function(e){ e = e || WIN.event; el.scrollTop += e.wheelDelta > 0 ? -30 : 30; e.returnValue = false; }; }(that.ui.body[0]) }, that.supportAnimate ? 300 : 0); }; module.exports = FBClient;
femxd/fxd
test/diff_fis3_smarty/product_code/hao123_fis3_smarty/home/widget/ui/facebook/fbclient.js
JavaScript
bsd-2-clause
11,122
""" Contains CheesePreprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from ...preprocessors.base import Preprocessor #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class CheesePreprocessor(Preprocessor): """ Adds a cheese tag to the resources object """ def __init__(self, **kw): """ Public constructor """ super(CheesePreprocessor, self).__init__(**kw) def preprocess(self, nb, resources): """ Sphinx preprocessing to apply on each notebook. Parameters ---------- nb : NotebookNode Notebook being converted resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. """ resources['cheese'] = 'real' return nb, resources
unnikrishnankgs/va
venv/lib/python3.5/site-packages/nbconvert/exporters/tests/cheese.py
Python
bsd-2-clause
1,485
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* JOrbis * Copyright (C) 2000 ymnk, JCraft,Inc. * * Written by: 2000 ymnk<ymnk@jcraft.com> * * Many thanks to * Monty <monty@xiph.org> and * The XIPHOPHORUS Company http://www.xiph.org/ . * JOrbis has been based on their awesome works, Vorbis codec. * * This program 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 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package com.jcraft.jorbis; // psychoacoustic setup class PsyInfo{ int athp; int decayp; int smoothp; int noisefitp; int noisefit_subblock; float noisefit_threshdB; float ath_att; int tonemaskp; float[] toneatt_125Hz=new float[5]; float[] toneatt_250Hz=new float[5]; float[] toneatt_500Hz=new float[5]; float[] toneatt_1000Hz=new float[5]; float[] toneatt_2000Hz=new float[5]; float[] toneatt_4000Hz=new float[5]; float[] toneatt_8000Hz=new float[5]; int peakattp; float[] peakatt_125Hz=new float[5]; float[] peakatt_250Hz=new float[5]; float[] peakatt_500Hz=new float[5]; float[] peakatt_1000Hz=new float[5]; float[] peakatt_2000Hz=new float[5]; float[] peakatt_4000Hz=new float[5]; float[] peakatt_8000Hz=new float[5]; int noisemaskp; float[] noiseatt_125Hz=new float[5]; float[] noiseatt_250Hz=new float[5]; float[] noiseatt_500Hz=new float[5]; float[] noiseatt_1000Hz=new float[5]; float[] noiseatt_2000Hz=new float[5]; float[] noiseatt_4000Hz=new float[5]; float[] noiseatt_8000Hz=new float[5]; float max_curve_dB; float attack_coeff; float decay_coeff; void free(){ } }
XtremeMP-Project/xtrememp-fx
xtrememp-audio-spi-vorbis/src/com/jcraft/jorbis/PsyInfo.java
Java
bsd-3-clause
2,222
/** * @file * Progress behavior. * * @see progress.js */ .progress { position: relative; } .progress__track { background-color: #fff; border: 1px solid; margin-top: 5px; max-width: 100%; min-width: 100px; height: 16px; } .progress__bar { background-color: #000; height: 1.5em; width: 3%; min-width: 3%; max-width: 100%; } .progress__description, .progress__percentage { color: #555; overflow: hidden; font-size: .875em; margin-top: 0.2em; } .progress__description { float: left; /* LTR */ } [dir="rtl"] .progress__description { float: right; } .progress__percentage { float: right; /* LTR */ } [dir="rtl"] .progress__percentage { float: left; } .progress--small .progress__track { height: 7px; } .progress--small .progress__bar { height: 7px; background-size: 20px 20px; }
JeramyK/training
web/core/themes/stable/css/system/components/progress.module.css
CSS
gpl-2.0
825
#ifndef __ASMPARISC_ELF_H #define __ASMPARISC_ELF_H /* * ELF register definitions.. */ #include <asm/ptrace.h> #define EM_PARISC 15 /* HPPA specific definitions. */ /* Legal values for e_flags field of Elf32_Ehdr. */ #define EF_PARISC_TRAPNIL 0x00010000 /* Trap nil pointer dereference. */ #define EF_PARISC_EXT 0x00020000 /* Program uses arch. extensions. */ #define EF_PARISC_LSB 0x00040000 /* Program expects little endian. */ #define EF_PARISC_WIDE 0x00080000 /* Program expects wide mode. */ #define EF_PARISC_NO_KABP 0x00100000 /* No kernel assisted branch prediction. */ #define EF_PARISC_LAZYSWAP 0x00400000 /* Allow lazy swapping. */ #define EF_PARISC_ARCH 0x0000ffff /* Architecture version. */ /* Defined values for `e_flags & EF_PARISC_ARCH' are: */ #define EFA_PARISC_1_0 0x020b /* PA-RISC 1.0 big-endian. */ #define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */ #define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */ /* Additional section indices. */ #define SHN_PARISC_ANSI_COMMON 0xff00 /* Section for tenatively declared symbols in ANSI C. */ #define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */ /* Legal values for sh_type field of Elf32_Shdr. */ #define SHT_PARISC_EXT 0x70000000 /* Contains product specific ext. */ #define SHT_PARISC_UNWIND 0x70000001 /* Unwind information. */ #define SHT_PARISC_DOC 0x70000002 /* Debug info for optimized code. */ /* Legal values for sh_flags field of Elf32_Shdr. */ #define SHF_PARISC_SHORT 0x20000000 /* Section with short addressing. */ #define SHF_PARISC_HUGE 0x40000000 /* Section far from gp. */ #define SHF_PARISC_SBP 0x80000000 /* Static branch prediction code. */ /* Legal values for ST_TYPE subfield of st_info (symbol type). */ #define STT_PARISC_MILLICODE 13 /* Millicode function entry point. */ #define STT_HP_OPAQUE (STT_LOOS + 0x1) #define STT_HP_STUB (STT_LOOS + 0x2) /* HPPA relocs. */ #define R_PARISC_NONE 0 /* No reloc. */ #define R_PARISC_DIR32 1 /* Direct 32-bit reference. */ #define R_PARISC_DIR21L 2 /* Left 21 bits of eff. address. */ #define R_PARISC_DIR17R 3 /* Right 17 bits of eff. address. */ #define R_PARISC_DIR17F 4 /* 17 bits of eff. address. */ #define R_PARISC_DIR14R 6 /* Right 14 bits of eff. address. */ #define R_PARISC_PCREL32 9 /* 32-bit rel. address. */ #define R_PARISC_PCREL21L 10 /* Left 21 bits of rel. address. */ #define R_PARISC_PCREL17R 11 /* Right 17 bits of rel. address. */ #define R_PARISC_PCREL17F 12 /* 17 bits of rel. address. */ #define R_PARISC_PCREL14R 14 /* Right 14 bits of rel. address. */ #define R_PARISC_DPREL21L 18 /* Left 21 bits of rel. address. */ #define R_PARISC_DPREL14R 22 /* Right 14 bits of rel. address. */ #define R_PARISC_GPREL21L 26 /* GP-relative, left 21 bits. */ #define R_PARISC_GPREL14R 30 /* GP-relative, right 14 bits. */ #define R_PARISC_LTOFF21L 34 /* LT-relative, left 21 bits. */ #define R_PARISC_LTOFF14R 38 /* LT-relative, right 14 bits. */ #define R_PARISC_SECREL32 41 /* 32 bits section rel. address. */ #define R_PARISC_SEGBASE 48 /* No relocation, set segment base. */ #define R_PARISC_SEGREL32 49 /* 32 bits segment rel. address. */ #define R_PARISC_PLTOFF21L 50 /* PLT rel. address, left 21 bits. */ #define R_PARISC_PLTOFF14R 54 /* PLT rel. address, right 14 bits. */ #define R_PARISC_LTOFF_FPTR32 57 /* 32 bits LT-rel. function pointer. */ #define R_PARISC_LTOFF_FPTR21L 58 /* LT-rel. fct ptr, left 21 bits. */ #define R_PARISC_LTOFF_FPTR14R 62 /* LT-rel. fct ptr, right 14 bits. */ #define R_PARISC_FPTR64 64 /* 64 bits function address. */ #define R_PARISC_PLABEL32 65 /* 32 bits function address. */ #define R_PARISC_PCREL64 72 /* 64 bits PC-rel. address. */ #define R_PARISC_PCREL22F 74 /* 22 bits PC-rel. address. */ #define R_PARISC_PCREL14WR 75 /* PC-rel. address, right 14 bits. */ #define R_PARISC_PCREL14DR 76 /* PC rel. address, right 14 bits. */ #define R_PARISC_PCREL16F 77 /* 16 bits PC-rel. address. */ #define R_PARISC_PCREL16WF 78 /* 16 bits PC-rel. address. */ #define R_PARISC_PCREL16DF 79 /* 16 bits PC-rel. address. */ #define R_PARISC_DIR64 80 /* 64 bits of eff. address. */ #define R_PARISC_DIR14WR 83 /* 14 bits of eff. address. */ #define R_PARISC_DIR14DR 84 /* 14 bits of eff. address. */ #define R_PARISC_DIR16F 85 /* 16 bits of eff. address. */ #define R_PARISC_DIR16WF 86 /* 16 bits of eff. address. */ #define R_PARISC_DIR16DF 87 /* 16 bits of eff. address. */ #define R_PARISC_GPREL64 88 /* 64 bits of GP-rel. address. */ #define R_PARISC_GPREL14WR 91 /* GP-rel. address, right 14 bits. */ #define R_PARISC_GPREL14DR 92 /* GP-rel. address, right 14 bits. */ #define R_PARISC_GPREL16F 93 /* 16 bits GP-rel. address. */ #define R_PARISC_GPREL16WF 94 /* 16 bits GP-rel. address. */ #define R_PARISC_GPREL16DF 95 /* 16 bits GP-rel. address. */ #define R_PARISC_LTOFF64 96 /* 64 bits LT-rel. address. */ #define R_PARISC_LTOFF14WR 99 /* LT-rel. address, right 14 bits. */ #define R_PARISC_LTOFF14DR 100 /* LT-rel. address, right 14 bits. */ #define R_PARISC_LTOFF16F 101 /* 16 bits LT-rel. address. */ #define R_PARISC_LTOFF16WF 102 /* 16 bits LT-rel. address. */ #define R_PARISC_LTOFF16DF 103 /* 16 bits LT-rel. address. */ #define R_PARISC_SECREL64 104 /* 64 bits section rel. address. */ #define R_PARISC_SEGREL64 112 /* 64 bits segment rel. address. */ #define R_PARISC_PLTOFF14WR 115 /* PLT-rel. address, right 14 bits. */ #define R_PARISC_PLTOFF14DR 116 /* PLT-rel. address, right 14 bits. */ #define R_PARISC_PLTOFF16F 117 /* 16 bits LT-rel. address. */ #define R_PARISC_PLTOFF16WF 118 /* 16 bits PLT-rel. address. */ #define R_PARISC_PLTOFF16DF 119 /* 16 bits PLT-rel. address. */ #define R_PARISC_LTOFF_FPTR64 120 /* 64 bits LT-rel. function ptr. */ #define R_PARISC_LTOFF_FPTR14WR 123 /* LT-rel. fct. ptr., right 14 bits. */ #define R_PARISC_LTOFF_FPTR14DR 124 /* LT-rel. fct. ptr., right 14 bits. */ #define R_PARISC_LTOFF_FPTR16F 125 /* 16 bits LT-rel. function ptr. */ #define R_PARISC_LTOFF_FPTR16WF 126 /* 16 bits LT-rel. function ptr. */ #define R_PARISC_LTOFF_FPTR16DF 127 /* 16 bits LT-rel. function ptr. */ #define R_PARISC_LORESERVE 128 #define R_PARISC_COPY 128 /* Copy relocation. */ #define R_PARISC_IPLT 129 /* Dynamic reloc, imported PLT */ #define R_PARISC_EPLT 130 /* Dynamic reloc, exported PLT */ #define R_PARISC_TPREL32 153 /* 32 bits TP-rel. address. */ #define R_PARISC_TPREL21L 154 /* TP-rel. address, left 21 bits. */ #define R_PARISC_TPREL14R 158 /* TP-rel. address, right 14 bits. */ #define R_PARISC_LTOFF_TP21L 162 /* LT-TP-rel. address, left 21 bits. */ #define R_PARISC_LTOFF_TP14R 166 /* LT-TP-rel. address, right 14 bits.*/ #define R_PARISC_LTOFF_TP14F 167 /* 14 bits LT-TP-rel. address. */ #define R_PARISC_TPREL64 216 /* 64 bits TP-rel. address. */ #define R_PARISC_TPREL14WR 219 /* TP-rel. address, right 14 bits. */ #define R_PARISC_TPREL14DR 220 /* TP-rel. address, right 14 bits. */ #define R_PARISC_TPREL16F 221 /* 16 bits TP-rel. address. */ #define R_PARISC_TPREL16WF 222 /* 16 bits TP-rel. address. */ #define R_PARISC_TPREL16DF 223 /* 16 bits TP-rel. address. */ #define R_PARISC_LTOFF_TP64 224 /* 64 bits LT-TP-rel. address. */ #define R_PARISC_LTOFF_TP14WR 227 /* LT-TP-rel. address, right 14 bits.*/ #define R_PARISC_LTOFF_TP14DR 228 /* LT-TP-rel. address, right 14 bits.*/ #define R_PARISC_LTOFF_TP16F 229 /* 16 bits LT-TP-rel. address. */ #define R_PARISC_LTOFF_TP16WF 230 /* 16 bits LT-TP-rel. address. */ #define R_PARISC_LTOFF_TP16DF 231 /* 16 bits LT-TP-rel. address. */ #define R_PARISC_HIRESERVE 255 #define PA_PLABEL_FDESC 0x02 /* bit set if PLABEL points to * a function descriptor, not * an address */ /* The following are PA function descriptors * * addr: the absolute address of the function * gp: either the data pointer (r27) for non-PIC code or the * the PLT pointer (r19) for PIC code */ /* Format for the Elf32 Function descriptor */ typedef struct elf32_fdesc { __u32 addr; __u32 gp; } Elf32_Fdesc; /* Format for the Elf64 Function descriptor */ typedef struct elf64_fdesc { __u64 dummy[2]; /* FIXME: nothing uses these, why waste * the space */ __u64 addr; __u64 gp; } Elf64_Fdesc; #ifdef __KERNEL__ #ifdef CONFIG_64BIT #define Elf_Fdesc Elf64_Fdesc #else #define Elf_Fdesc Elf32_Fdesc #endif /*CONFIG_64BIT*/ #endif /*__KERNEL__*/ /* Legal values for p_type field of Elf32_Phdr/Elf64_Phdr. */ #define PT_HP_TLS (PT_LOOS + 0x0) #define PT_HP_CORE_NONE (PT_LOOS + 0x1) #define PT_HP_CORE_VERSION (PT_LOOS + 0x2) #define PT_HP_CORE_KERNEL (PT_LOOS + 0x3) #define PT_HP_CORE_COMM (PT_LOOS + 0x4) #define PT_HP_CORE_PROC (PT_LOOS + 0x5) #define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6) #define PT_HP_CORE_STACK (PT_LOOS + 0x7) #define PT_HP_CORE_SHM (PT_LOOS + 0x8) #define PT_HP_CORE_MMF (PT_LOOS + 0x9) #define PT_HP_PARALLEL (PT_LOOS + 0x10) #define PT_HP_FASTBIND (PT_LOOS + 0x11) #define PT_HP_OPT_ANNOT (PT_LOOS + 0x12) #define PT_HP_HSL_ANNOT (PT_LOOS + 0x13) #define PT_HP_STACK (PT_LOOS + 0x14) #define PT_PARISC_ARCHEXT 0x70000000 #define PT_PARISC_UNWIND 0x70000001 /* Legal values for p_flags field of Elf32_Phdr/Elf64_Phdr. */ #define PF_PARISC_SBP 0x08000000 #define PF_HP_PAGE_SIZE 0x00100000 #define PF_HP_FAR_SHARED 0x00200000 #define PF_HP_NEAR_SHARED 0x00400000 #define PF_HP_CODE 0x01000000 #define PF_HP_MODIFY 0x02000000 #define PF_HP_LAZYSWAP 0x04000000 #define PF_HP_SBP 0x08000000 /* * The following definitions are those for 32-bit ELF binaries on a 32-bit * kernel and for 64-bit binaries on a 64-bit kernel. To run 32-bit binaries * on a 64-bit kernel, arch/parisc/kernel/binfmt_elf32.c defines these * macros appropriately and then #includes binfmt_elf.c, which then includes * this file. */ #ifndef ELF_CLASS /* * This is used to ensure we don't load something for the wrong architecture. * * Note that this header file is used by default in fs/binfmt_elf.c. So * the following macros are for the default case. However, for the 64 * bit kernel we also support 32 bit parisc binaries. To do that * arch/parisc/kernel/binfmt_elf32.c defines its own set of these * macros, and then it includes fs/binfmt_elf.c to provide an alternate * elf binary handler for 32 bit binaries (on the 64 bit kernel). */ #ifdef CONFIG_64BIT #define ELF_CLASS ELFCLASS64 #else #define ELF_CLASS ELFCLASS32 #endif typedef unsigned long elf_greg_t; /* * This yields a string that ld.so will use to load implementation * specific libraries for optimization. This is more specific in * intent than poking at uname or /proc/cpuinfo. */ #define ELF_PLATFORM ("PARISC\0") #define SET_PERSONALITY(ex) \ current->personality = PER_LINUX; \ current->thread.map_base = DEFAULT_MAP_BASE; \ current->thread.task_size = DEFAULT_TASK_SIZE \ /* * Fill in general registers in a core dump. This saves pretty * much the same registers as hp-ux, although in a different order. * Registers marked # below are not currently saved in pt_regs, so * we use their current values here. * * gr0..gr31 * sr0..sr7 * iaoq0..iaoq1 * iasq0..iasq1 * cr11 (sar) * cr19 (iir) * cr20 (isr) * cr21 (ior) * # cr22 (ipsw) * # cr0 (recovery counter) * # cr24..cr31 (temporary registers) * # cr8,9,12,13 (protection IDs) * # cr10 (scr/ccr) * # cr15 (ext int enable mask) * */ #define ELF_CORE_COPY_REGS(dst, pt) \ memset(dst, 0, sizeof(dst)); /* don't leak any "random" bits */ \ memcpy(dst + 0, pt->gr, 32 * sizeof(elf_greg_t)); \ memcpy(dst + 32, pt->sr, 8 * sizeof(elf_greg_t)); \ memcpy(dst + 40, pt->iaoq, 2 * sizeof(elf_greg_t)); \ memcpy(dst + 42, pt->iasq, 2 * sizeof(elf_greg_t)); \ dst[44] = pt->sar; dst[45] = pt->iir; \ dst[46] = pt->isr; dst[47] = pt->ior; \ dst[48] = mfctl(22); dst[49] = mfctl(0); \ dst[50] = mfctl(24); dst[51] = mfctl(25); \ dst[52] = mfctl(26); dst[53] = mfctl(27); \ dst[54] = mfctl(28); dst[55] = mfctl(29); \ dst[56] = mfctl(30); dst[57] = mfctl(31); \ dst[58] = mfctl( 8); dst[59] = mfctl( 9); \ dst[60] = mfctl(12); dst[61] = mfctl(13); \ dst[62] = mfctl(10); dst[63] = mfctl(15); #endif /* ! ELF_CLASS */ #define ELF_NGREG 80 /* We only need 64 at present, but leave space for expansion. */ typedef elf_greg_t elf_gregset_t[ELF_NGREG]; #define ELF_NFPREG 32 typedef double elf_fpreg_t; typedef elf_fpreg_t elf_fpregset_t[ELF_NFPREG]; struct task_struct; extern int dump_task_fpu (struct task_struct *, elf_fpregset_t *); #define ELF_CORE_COPY_FPREGS(tsk, elf_fpregs) dump_task_fpu(tsk, elf_fpregs) struct pt_regs; /* forward declaration... */ #define elf_check_arch(x) ((x)->e_machine == EM_PARISC && (x)->e_ident[EI_CLASS] == ELF_CLASS) /* * These are used to set parameters in the core dumps. */ #define ELF_DATA ELFDATA2MSB #define ELF_ARCH EM_PARISC #define ELF_OSABI ELFOSABI_LINUX /* %r23 is set by ld.so to a pointer to a function which might be registered using atexit. This provides a means for the dynamic linker to call DT_FINI functions for shared libraries that have been loaded before the code runs. So that we can use the same startup file with static executables, we start programs with a value of 0 to indicate that there is no such function. */ #define ELF_PLAT_INIT(_r, load_addr) _r->gr[23] = 0 #define ELF_EXEC_PAGESIZE 4096 /* This is the location that an ET_DYN program is loaded if exec'ed. Typical use of this is to invoke "./ld.so someprog" to test out a new version of the loader. We need to make sure that it is out of the way of the program that it will "exec", and that there is sufficient room for the brk. (2 * TASK_SIZE / 3) turns into something undefined when run through a 32 bit preprocessor and in some cases results in the kernel trying to map ld.so to the kernel virtual base. Use a sane value instead. /Jes */ #define ELF_ET_DYN_BASE (TASK_UNMAPPED_BASE + 0x01000000) /* This yields a mask that user programs can use to figure out what instruction set this CPU supports. This could be done in user space, but it's not easy, and we've already done it here. */ #define ELF_HWCAP 0 #endif
talnoah/android_kernel_htc_dlx
virt/arch/parisc/include/asm/elf.h
C
gpl-2.0
14,247
/** * 404 (Not Found) Handler * * Usage: * return res.notFound(); * return res.notFound(err); * return res.notFound(err, 'some/specific/notfound/view'); * * e.g.: * ``` * return res.notFound(); * ``` * * NOTE: * If a request doesn't match any explicit routes (i.e. `config/routes.js`) * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()` * automatically. */ module.exports = function notFound (data, options) { // Get access to `req`, `res`, & `sails` var req = this.req; var res = this.res; var sails = req._sails; // Set status code res.status(404); // Log error to console if (data !== undefined) { sails.log.verbose('Sending 404 ("Not Found") response: \n',data); } else sails.log.verbose('Sending 404 ("Not Found") response'); // Only include errors in response if application environment // is not set to 'production'. In production, we shouldn't // send back any identifying information about errors. if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { data = undefined; } // If the user-agent wants JSON, always respond with JSON if (req.wantsJSON) { return res.jsonx(data); } // If second argument is a string, we take that to mean it refers to a view. // If it was omitted, use an empty object (`{}`) options = (typeof options === 'string') ? { view: options } : options || {}; // If a view was provided in options, serve it. // Otherwise try to guess an appropriate view, or if that doesn't // work, just send JSON. if (options.view) { return res.view(options.view, { data: data }); } // If no second argument provided, try to serve the default view, // but fall back to sending JSON(P) if any errors occur. else return res.view('404', { data: data }, function (err, html) { // If a view error occured, fall back to JSON(P). if (err) { // // Additionally: // • If the view was missing, ignore the error but provide a verbose log. if (err.code === 'E_VIEW_FAILED') { sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err); } // Otherwise, if this was a more serious error, log to the console with the details. else { sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); } return res.jsonx(data); } return res.send(html); }); };
Karnith/sails-generate-backend-gulp
templates/api/responses/notFound.js
JavaScript
mit
2,543
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.base; import android.os.Looper; import android.os.MessageQueue; import android.os.SystemClock; import android.util.Log; import android.util.Printer; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; /** * Java mirror of Chrome trace event API. See base/trace_event/trace_event.h. Unlike the native * version, Java does not have stack objects, so a TRACE_EVENT() which does both TRACE_EVENT_BEGIN() * and TRACE_EVENT_END() in ctor/dtor is not possible. * It is OK to use tracing before the native library has loaded, but such traces will * be ignored. (Perhaps we could devise to buffer them up in future?). */ @JNINamespace("base::android") public class TraceEvent { private static volatile boolean sEnabled = false; private static volatile boolean sATraceEnabled = false; // True when taking an Android systrace. private static class BasicLooperMonitor implements Printer { @Override public void println(final String line) { if (line.startsWith(">")) { beginHandling(line); } else { assert line.startsWith("<"); endHandling(line); } } void beginHandling(final String line) { if (sEnabled) nativeBeginToplevel(); } void endHandling(final String line) { if (sEnabled) nativeEndToplevel(); } } /** * A class that records, traces and logs statistics about the UI thead's Looper. * The output of this class can be used in a number of interesting ways: * <p> * <ol><li> * When using chrometrace, there will be a near-continuous line of * measurements showing both event dispatches as well as idles; * </li><li> * Logging messages are output for events that run too long on the * event dispatcher, making it easy to identify problematic areas; * </li><li> * Statistics are output whenever there is an idle after a non-trivial * amount of activity, allowing information to be gathered about task * density and execution cadence on the Looper; * </li></ol> * <p> * The class attaches itself as an idle handler to the main Looper, and * monitors the execution of events and idle notifications. Task counters * accumulate between idle notifications and get reset when a new idle * notification is received. */ private static final class IdleTracingLooperMonitor extends BasicLooperMonitor implements MessageQueue.IdleHandler { // Tags for dumping to logcat or TraceEvent private static final String TAG = "TraceEvent.LooperMonitor"; private static final String IDLE_EVENT_NAME = "Looper.queueIdle"; // Calculation constants private static final long FRAME_DURATION_MILLIS = 1000L / 60L; // 60 FPS // A reasonable threshold for defining a Looper event as "long running" private static final long MIN_INTERESTING_DURATION_MILLIS = FRAME_DURATION_MILLIS; // A reasonable threshold for a "burst" of tasks on the Looper private static final long MIN_INTERESTING_BURST_DURATION_MILLIS = MIN_INTERESTING_DURATION_MILLIS * 3; // Stats tracking private long mLastIdleStartedAt = 0L; private long mLastWorkStartedAt = 0L; private int mNumTasksSeen = 0; private int mNumIdlesSeen = 0; private int mNumTasksSinceLastIdle = 0; // State private boolean mIdleMonitorAttached = false; // Called from within the begin/end methods only. // This method can only execute on the looper thread, because that is // the only thread that is permitted to call Looper.myqueue(). private final void syncIdleMonitoring() { if (sEnabled && !mIdleMonitorAttached) { // approximate start time for computational purposes mLastIdleStartedAt = SystemClock.elapsedRealtime(); Looper.myQueue().addIdleHandler(this); mIdleMonitorAttached = true; Log.v(TAG, "attached idle handler"); } else if (mIdleMonitorAttached && !sEnabled) { Looper.myQueue().removeIdleHandler(this); mIdleMonitorAttached = false; Log.v(TAG, "detached idle handler"); } } @Override final void beginHandling(final String line) { // Close-out any prior 'idle' period before starting new task. if (mNumTasksSinceLastIdle == 0) { TraceEvent.end(IDLE_EVENT_NAME); } mLastWorkStartedAt = SystemClock.elapsedRealtime(); syncIdleMonitoring(); super.beginHandling(line); } @Override final void endHandling(final String line) { final long elapsed = SystemClock.elapsedRealtime() - mLastWorkStartedAt; if (elapsed > MIN_INTERESTING_DURATION_MILLIS) { traceAndLog(Log.WARN, "observed a task that took " + elapsed + "ms: " + line); } super.endHandling(line); syncIdleMonitoring(); mNumTasksSeen++; mNumTasksSinceLastIdle++; } private static void traceAndLog(int level, String message) { TraceEvent.instant("TraceEvent.LooperMonitor:IdleStats", message); Log.println(level, TAG, message); } @Override public final boolean queueIdle() { final long now = SystemClock.elapsedRealtime(); if (mLastIdleStartedAt == 0) mLastIdleStartedAt = now; final long elapsed = now - mLastIdleStartedAt; mNumIdlesSeen++; TraceEvent.begin(IDLE_EVENT_NAME, mNumTasksSinceLastIdle + " tasks since last idle."); if (elapsed > MIN_INTERESTING_BURST_DURATION_MILLIS) { // Dump stats String statsString = mNumTasksSeen + " tasks and " + mNumIdlesSeen + " idles processed so far, " + mNumTasksSinceLastIdle + " tasks bursted and " + elapsed + "ms elapsed since last idle"; traceAndLog(Log.DEBUG, statsString); } mLastIdleStartedAt = now; mNumTasksSinceLastIdle = 0; return true; // stay installed } } // Holder for monitor avoids unnecessary construction on non-debug runs private static final class LooperMonitorHolder { private static final BasicLooperMonitor sInstance = CommandLine.getInstance().hasSwitch(BaseSwitches.ENABLE_IDLE_TRACING) ? new IdleTracingLooperMonitor() : new BasicLooperMonitor(); } /** * Register an enabled observer, such that java traces are always enabled with native. */ public static void registerNativeEnabledObserver() { nativeRegisterEnabledObserver(); } /** * Notification from native that tracing is enabled/disabled. */ @CalledByNative public static void setEnabled(boolean enabled) { sEnabled = enabled; // Android M+ systrace logs this on its own. Only log it if not writing to Android systrace. if (sATraceEnabled) return; ThreadUtils.getUiThreadLooper().setMessageLogging( enabled ? LooperMonitorHolder.sInstance : null); } /** * Enables or disabled Android systrace path of Chrome tracing. If enabled, all Chrome * traces will be also output to Android systrace. Because of the overhead of Android * systrace, this is for WebView only. */ public static void setATraceEnabled(boolean enabled) { if (sATraceEnabled == enabled) return; sATraceEnabled = enabled; if (enabled) { // Calls TraceEvent.setEnabled(true) via // TraceLog::EnabledStateObserver::OnTraceLogEnabled nativeStartATrace(); } else { // Calls TraceEvent.setEnabled(false) via // TraceLog::EnabledStateObserver::OnTraceLogDisabled nativeStopATrace(); } } /** * @return True if tracing is enabled, false otherwise. * It is safe to call trace methods without checking if TraceEvent * is enabled. */ public static boolean enabled() { return sEnabled; } /** * Triggers the 'instant' native trace event with no arguments. * @param name The name of the event. */ public static void instant(String name) { if (sEnabled) nativeInstant(name, null); } /** * Triggers the 'instant' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void instant(String name, String arg) { if (sEnabled) nativeInstant(name, arg); } /** * Triggers the 'start' native trace event with no arguments. * @param name The name of the event. * @param id The id of the asynchronous event. */ public static void startAsync(String name, long id) { if (sEnabled) nativeStartAsync(name, id); } /** * Triggers the 'finish' native trace event with no arguments. * @param name The name of the event. * @param id The id of the asynchronous event. */ public static void finishAsync(String name, long id) { if (sEnabled) nativeFinishAsync(name, id); } /** * Triggers the 'begin' native trace event with no arguments. * @param name The name of the event. */ public static void begin(String name) { if (sEnabled) nativeBegin(name, null); } /** * Triggers the 'begin' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void begin(String name, String arg) { if (sEnabled) nativeBegin(name, arg); } /** * Triggers the 'end' native trace event with no arguments. * @param name The name of the event. */ public static void end(String name) { if (sEnabled) nativeEnd(name, null); } /** * Triggers the 'end' native trace event. * @param name The name of the event. * @param arg The arguments of the event. */ public static void end(String name, String arg) { if (sEnabled) nativeEnd(name, arg); } private static native void nativeRegisterEnabledObserver(); private static native void nativeStartATrace(); private static native void nativeStopATrace(); private static native void nativeInstant(String name, String arg); private static native void nativeBegin(String name, String arg); private static native void nativeEnd(String name, String arg); private static native void nativeBeginToplevel(); private static native void nativeEndToplevel(); private static native void nativeStartAsync(String name, long id); private static native void nativeFinishAsync(String name, long id); }
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/base/android/java/src/org/chromium/base/TraceEvent.java
Java
mit
11,372
(function(){var e=window.AmCharts;e.AmRectangularChart=e.Class({inherits:e.AmCoordinateChart,construct:function(a){e.AmRectangularChart.base.construct.call(this,a);this.theme=a;this.createEvents("zoomed","changed");this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=20;this.depth3D=this.angle=0;this.plotAreaFillColors="#FFFFFF";this.plotAreaFillAlphas=0;this.plotAreaBorderColor="#000000";this.plotAreaBorderAlpha=0;this.maxZoomFactor=20;this.zoomOutButtonImageSize=19;this.zoomOutButtonImage= "lens";this.zoomOutText="Show all";this.zoomOutButtonColor="#e5e5e5";this.zoomOutButtonAlpha=0;this.zoomOutButtonRollOverAlpha=1;this.zoomOutButtonPadding=8;this.trendLines=[];this.autoMargins=!0;this.marginsUpdated=!1;this.autoMarginOffset=10;e.applyTheme(this,a,"AmRectangularChart")},initChart:function(){e.AmRectangularChart.base.initChart.call(this);this.updateDxy();!this.marginsUpdated&&this.autoMargins&&(this.resetMargins(),this.drawGraphs=!1);this.processScrollbars();this.updateMargins();this.updatePlotArea(); this.updateScrollbars();this.updateTrendLines();this.updateChartCursor();this.updateValueAxes();this.scrollbarOnly||this.updateGraphs()},drawChart:function(){e.AmRectangularChart.base.drawChart.call(this);this.drawPlotArea();if(e.ifArray(this.chartData)){var a=this.chartCursor;a&&a.draw()}},resetMargins:function(){var a={},b;if("xy"==this.type){var c=this.xAxes,d=this.yAxes;for(b=0;b<c.length;b++){var g=c[b];g.ignoreAxisWidth||(g.setOrientation(!0),g.fixAxisPosition(),a[g.position]=!0)}for(b=0;b< d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(!1),c.fixAxisPosition(),a[c.position]=!0)}else{d=this.valueAxes;for(b=0;b<d.length;b++)c=d[b],c.ignoreAxisWidth||(c.setOrientation(this.rotate),c.fixAxisPosition(),a[c.position]=!0);(b=this.categoryAxis)&&!b.ignoreAxisWidth&&(b.setOrientation(!this.rotate),b.fixAxisPosition(),b.fixAxisPosition(),a[b.position]=!0)}a.left&&(this.marginLeft=0);a.right&&(this.marginRight=0);a.top&&(this.marginTop=0);a.bottom&&(this.marginBottom=0);this.fixMargins= a},measureMargins:function(){var a=this.valueAxes,b,c=this.autoMarginOffset,d=this.fixMargins,g=this.realWidth,e=this.realHeight,f=c,k=c,m=g;b=e;var l;for(l=0;l<a.length;l++)a[l].handleSynchronization(),b=this.getAxisBounds(a[l],f,m,k,b),f=Math.round(b.l),m=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b);if(a=this.categoryAxis)b=this.getAxisBounds(a,f,m,k,b),f=Math.round(b.l),m=Math.round(b.r),k=Math.round(b.t),b=Math.round(b.b);d.left&&f<c&&(this.marginLeft=Math.round(-f+c),!isNaN(this.minMarginLeft)&& this.marginLeft<this.minMarginLeft&&(this.marginLeft=this.minMarginLeft));d.right&&m>=g-c&&(this.marginRight=Math.round(m-g+c),!isNaN(this.minMarginRight)&&this.marginRight<this.minMarginRight&&(this.marginRight=this.minMarginRight));d.top&&k<c+this.titleHeight&&(this.marginTop=Math.round(this.marginTop-k+c+this.titleHeight),!isNaN(this.minMarginTop)&&this.marginTop<this.minMarginTop&&(this.marginTop=this.minMarginTop));d.bottom&&b>e-c&&(this.marginBottom=Math.round(this.marginBottom+b-e+c),!isNaN(this.minMarginBottom)&& this.marginBottom<this.minMarginBottom&&(this.marginBottom=this.minMarginBottom));this.initChart()},getAxisBounds:function(a,b,c,d,e){if(!a.ignoreAxisWidth){var h=a.labelsSet,f=a.tickLength;a.inside&&(f=0);if(h)switch(h=a.getBBox(),a.position){case "top":a=h.y;d>a&&(d=a);break;case "bottom":a=h.y+h.height;e<a&&(e=a);break;case "right":a=h.x+h.width+f+3;c<a&&(c=a);break;case "left":a=h.x-f,b>a&&(b=a)}}return{l:b,t:d,r:c,b:e}},drawZoomOutButton:function(){var a=this;if(!a.zbSet){var b=a.container.set(); a.zoomButtonSet.push(b);var c=a.color,d=a.fontSize,g=a.zoomOutButtonImageSize,h=a.zoomOutButtonImage.replace(/\.[a-z]*$/i,""),f=a.langObj.zoomOutText||a.zoomOutText,k=a.zoomOutButtonColor,m=a.zoomOutButtonAlpha,l=a.zoomOutButtonFontSize,p=a.zoomOutButtonPadding;isNaN(l)||(d=l);(l=a.zoomOutButtonFontColor)&&(c=l);var l=a.zoomOutButton,q;l&&(l.fontSize&&(d=l.fontSize),l.color&&(c=l.color),l.backgroundColor&&(k=l.backgroundColor),isNaN(l.backgroundAlpha)||(a.zoomOutButtonRollOverAlpha=l.backgroundAlpha)); var r=l=0,r=a.pathToImages;if(h){if(e.isAbsolute(h)||void 0===r)r="";q=a.container.image(r+h+a.extension,0,0,g,g);e.setCN(a,q,"zoom-out-image");b.push(q);q=q.getBBox();l=q.width+5}void 0!==f&&(c=e.text(a.container,f,c,a.fontFamily,d,"start"),e.setCN(a,c,"zoom-out-label"),d=c.getBBox(),r=q?q.height/2-3:d.height/2,c.translate(l,r),b.push(c));q=b.getBBox();c=1;e.isModern||(c=0);k=e.rect(a.container,q.width+2*p+5,q.height+2*p-2,k,1,1,k,c);k.setAttr("opacity",m);k.translate(-p,-p);e.setCN(a,k,"zoom-out-bg"); b.push(k);k.toBack();a.zbBG=k;q=k.getBBox();b.translate(a.marginLeftReal+a.plotAreaWidth-q.width+p,a.marginTopReal+p);b.hide();b.mouseover(function(){a.rollOverZB()}).mouseout(function(){a.rollOutZB()}).click(function(){a.clickZB()}).touchstart(function(){a.rollOverZB()}).touchend(function(){a.rollOutZB();a.clickZB()});for(m=0;m<b.length;m++)b[m].attr({cursor:"pointer"});void 0!==a.zoomOutButtonTabIndex&&(b.setAttr("tabindex",a.zoomOutButtonTabIndex),b.setAttr("role","menuitem"),b.keyup(function(b){13== b.keyCode&&a.clickZB()}));a.zbSet=b}},rollOverZB:function(){this.rolledOverZB=!0;this.zbBG.setAttr("opacity",this.zoomOutButtonRollOverAlpha)},rollOutZB:function(){this.rolledOverZB=!1;this.zbBG.setAttr("opacity",this.zoomOutButtonAlpha)},clickZB:function(){this.rolledOverZB=!1;this.zoomOut()},zoomOut:function(){this.zoomOutValueAxes()},drawPlotArea:function(){var a=this.dx,b=this.dy,c=this.marginLeftReal,d=this.marginTopReal,g=this.plotAreaWidth-1,h=this.plotAreaHeight-1,f=this.plotAreaFillColors, k=this.plotAreaFillAlphas,m=this.plotAreaBorderColor,l=this.plotAreaBorderAlpha;"object"==typeof k&&(k=k[0]);f=e.polygon(this.container,[0,g,g,0,0],[0,0,h,h,0],f,k,1,m,l,this.plotAreaGradientAngle);e.setCN(this,f,"plot-area");f.translate(c+a,d+b);this.set.push(f);0!==a&&0!==b&&(f=this.plotAreaFillColors,"object"==typeof f&&(f=f[0]),f=e.adjustLuminosity(f,-.15),g=e.polygon(this.container,[0,a,g+a,g,0],[0,b,b,0,0],f,k,1,m,l),e.setCN(this,g,"plot-area-bottom"),g.translate(c,d+h),this.set.push(g),a=e.polygon(this.container, [0,0,a,a,0],[0,h,h+b,b,0],f,k,1,m,l),e.setCN(this,a,"plot-area-left"),a.translate(c,d),this.set.push(a));(c=this.bbset)&&this.scrollbarOnly&&c.remove()},updatePlotArea:function(){var a=this.updateWidth(),b=this.updateHeight(),c=this.container;this.realWidth=a;this.realWidth=b;c&&this.container.setSize(a,b);var c=this.marginLeftReal,d=this.marginTopReal,a=a-c-this.marginRightReal-this.dx,b=b-d-this.marginBottomReal;1>a&&(a=1);1>b&&(b=1);this.plotAreaWidth=Math.round(a);this.plotAreaHeight=Math.round(b); this.plotBalloonsSet.translate(c,d)},updateDxy:function(){this.dx=Math.round(this.depth3D*Math.cos(this.angle*Math.PI/180));this.dy=Math.round(-this.depth3D*Math.sin(this.angle*Math.PI/180));this.d3x=Math.round(this.columnSpacing3D*Math.cos(this.angle*Math.PI/180));this.d3y=Math.round(-this.columnSpacing3D*Math.sin(this.angle*Math.PI/180))},updateMargins:function(){var a=this.getTitleHeight();this.titleHeight=a;this.marginTopReal=this.marginTop-this.dy;this.fixMargins&&!this.fixMargins.top&&(this.marginTopReal+= a);this.marginBottomReal=this.marginBottom;this.marginLeftReal=this.marginLeft;this.marginRightReal=this.marginRight},updateValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b];this.setAxisRenderers(c);this.updateObjectSize(c)}},setAxisRenderers:function(a){a.axisRenderer=e.RecAxis;a.guideFillRenderer=e.RecFill;a.axisItemRenderer=e.RecItem;a.marginsChanged=!0},updateGraphs:function(){var a=this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.index=b;c.rotate=this.rotate;this.updateObjectSize(c)}}, updateObjectSize:function(a){a.width=this.plotAreaWidth-1;a.height=this.plotAreaHeight-1;a.x=this.marginLeftReal;a.y=this.marginTopReal;a.dx=this.dx;a.dy=this.dy},updateChartCursor:function(){var a=this.chartCursor;a&&(a=e.processObject(a,e.ChartCursor,this.theme),this.updateObjectSize(a),this.addChartCursor(a),a.chart=this)},processScrollbars:function(){var a=this.chartScrollbar;a&&(a=e.processObject(a,e.ChartScrollbar,this.theme),this.addChartScrollbar(a))},updateScrollbars:function(){},removeChartCursor:function(){e.callMethod("destroy", [this.chartCursor]);this.chartCursor=null},zoomTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b];c.valueAxis.recalculateToPercents?c.set&&c.set.hide():(c.x=this.marginLeftReal,c.y=this.marginTopReal,c.draw())}},handleCursorValueZoom:function(){},addTrendLine:function(a){this.trendLines.push(a)},zoomOutValueAxes:function(){for(var a=this.valueAxes,b=0;b<a.length;b++)a[b].zoomOut()},removeTrendLine:function(a){var b=this.trendLines,c;for(c=b.length-1;0<=c;c--)b[c]==a&& b.splice(c,1)},adjustMargins:function(a,b){var c=a.position,d=a.scrollbarHeight+a.offset;a.enabled&&("top"==c?b?this.marginLeftReal+=d:this.marginTopReal+=d:b?this.marginRightReal+=d:this.marginBottomReal+=d)},getScrollbarPosition:function(a,b,c){var d="bottom",e="top";a.oppositeAxis||(e=d,d="top");a.position=b?"bottom"==c||"left"==c?d:e:"top"==c||"right"==c?d:e},updateChartScrollbar:function(a,b){if(a){a.rotate=b;var c=this.marginTopReal,d=this.marginLeftReal,e=a.scrollbarHeight,h=this.dx,f=this.dy, k=a.offset;"top"==a.position?b?(a.y=c,a.x=d-e-k):(a.y=c-e+f-k,a.x=d+h):b?(a.y=c+f,a.x=d+this.plotAreaWidth+h+k):(a.y=c+this.plotAreaHeight+k,a.x=this.marginLeftReal)}},showZB:function(a){var b=this.zbSet;a&&(b=this.zoomOutText,""!==b&&b&&this.drawZoomOutButton());if(b=this.zbSet)this.zoomButtonSet.push(b),a?b.show():b.hide(),this.rollOutZB()},handleReleaseOutside:function(a){e.AmRectangularChart.base.handleReleaseOutside.call(this,a);(a=this.chartCursor)&&a.handleReleaseOutside&&a.handleReleaseOutside()}, handleMouseDown:function(a){e.AmRectangularChart.base.handleMouseDown.call(this,a);var b=this.chartCursor;b&&b.handleMouseDown&&!this.rolledOverZB&&b.handleMouseDown(a)},update:function(){e.AmRectangularChart.base.update.call(this);this.chartCursor&&this.chartCursor.update&&this.chartCursor.update()},handleScrollbarValueZoom:function(a){this.relativeZoomValueAxes(a.target.valueAxes,a.relativeStart,a.relativeEnd);this.zoomAxesAndGraphs()},zoomValueScrollbar:function(a){if(a&&a.enabled){var b=a.valueAxes[0], c=b.relativeStart,d=b.relativeEnd;b.reversed&&(d=1-c,c=1-b.relativeEnd);a.percentZoom(c,d)}},zoomAxesAndGraphs:function(){if(!this.scrollbarOnly){var a=this.valueAxes,b;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);a=this.graphs;for(b=0;b<a.length;b++)a[b].zoom(this.start,this.end);(b=this.chartCursor)&&b.clearSelection();this.zoomTrendLines()}},handleValueAxisZoomReal:function(a,b){var c=a.relativeStart,d=a.relativeEnd;if(c>d)var e=c,c=d,d=e;this.relativeZoomValueAxes(b,c,d);this.updateAfterValueZoom()}, updateAfterValueZoom:function(){this.zoomAxesAndGraphs();this.zoomScrollbar()},relativeZoomValueAxes:function(a,b,c){b=e.fitToBounds(b,0,1);c=e.fitToBounds(c,0,1);if(b>c){var d=b;b=c;c=d}var d=1/this.maxZoomFactor,g=e.getDecimals(d)+4;c-b<d&&(c=b+(c-b)/2,b=c-d/2,c+=d/2,1<c&&(b-=c-1,c=1));b=e.roundTo(b,g);c=e.roundTo(c,g);d=!1;if(a){for(g=0;g<a.length;g++){var h=a[g].zoomToRelativeValues(b,c,!0);h&&(d=h)}this.showZB()}return d},addChartCursor:function(a){e.callMethod("destroy",[this.chartCursor]); a&&(this.listenTo(a,"moved",this.handleCursorMove),this.listenTo(a,"zoomed",this.handleCursorZoom),this.listenTo(a,"zoomStarted",this.handleCursorZoomStarted),this.listenTo(a,"panning",this.handleCursorPanning),this.listenTo(a,"onHideCursor",this.handleCursorHide));this.chartCursor=a},handleCursorChange:function(){},handleCursorMove:function(a){var b,c=this.valueAxes;for(b=0;b<c.length;b++)if(!a.panning){var d=c[b];d&&d.showBalloon&&d.showBalloon(a.x,a.y)}},handleCursorZoom:function(a){if(this.skipZoomed)this.skipZoomed= !1;else{var b=this.startX0,c=this.endX0,d=this.endY0,e=this.startY0,h=a.startX,f=a.endX,k=a.startY,m=a.endY;this.startX0=this.endX0=this.startY0=this.endY0=NaN;this.handleCursorZoomReal(b+h*(c-b),b+f*(c-b),e+k*(d-e),e+m*(d-e),a)}},handleCursorHide:function(){var a,b=this.valueAxes;for(a=0;a<b.length;a++)b[a].hideBalloon();b=this.graphs;for(a=0;a<b.length;a++)b[a].hideBalloonReal()}})})();(function(){var e=window.AmCharts;e.AmXYChart=e.Class({inherits:e.AmRectangularChart,construct:function(a){this.type="xy";e.AmXYChart.base.construct.call(this,a);this.cname="AmXYChart";this.theme=a;this.createEvents("zoomed");e.applyTheme(this,a,this.cname)},initChart:function(){e.AmXYChart.base.initChart.call(this);this.dataChanged&&this.updateData();this.drawChart();!this.marginsUpdated&&this.autoMargins&&(this.marginsUpdated=!0,this.measureMargins());var a=this.marginLeftReal,b=this.marginTopReal, c=this.plotAreaWidth,d=this.plotAreaHeight;this.graphsSet.clipRect(a,b,c,d);this.bulletSet.clipRect(a,b,c,d);this.trendLinesSet.clipRect(a,b,c,d);this.drawGraphs=!0;this.showZB()},prepareForExport:function(){var a=this.bulletSet;a.clipPath&&this.container.remove(a.clipPath)},createValueAxes:function(){var a=[],b=[];this.xAxes=a;this.yAxes=b;var c=this.valueAxes,d,g;for(g=0;g<c.length;g++){d=c[g];var h=d.position;if("top"==h||"bottom"==h)d.rotate=!0;d.setOrientation(d.rotate);h=d.orientation;"V"== h&&b.push(d);"H"==h&&a.push(d)}0===b.length&&(d=new e.ValueAxis(this.theme),d.rotate=!1,d.setOrientation(!1),c.push(d),b.push(d));0===a.length&&(d=new e.ValueAxis(this.theme),d.rotate=!0,d.setOrientation(!0),c.push(d),a.push(d));for(g=0;g<c.length;g++)this.processValueAxis(c[g],g);a=this.graphs;for(g=0;g<a.length;g++)this.processGraph(a[g],g)},drawChart:function(){e.AmXYChart.base.drawChart.call(this);var a=this.chartData;this.legend&&(this.legend.valueText=void 0);if(0<this.realWidth&&0<this.realHeight){e.ifArray(a)? (this.chartScrollbar&&this.updateScrollbars(),this.zoomChart()):this.cleanChart();if(a=this.scrollbarH)this.hideXScrollbar?(a&&a.destroy(),this.scrollbarH=null):a.draw();if(a=this.scrollbarV)this.hideYScrollbar?(a.destroy(),this.scrollbarV=null):a.draw();this.zoomScrollbar()}this.autoMargins&&!this.marginsUpdated||this.dispDUpd()},cleanChart:function(){e.callMethod("destroy",[this.valueAxes,this.graphs,this.scrollbarV,this.scrollbarH,this.chartCursor])},zoomChart:function(){this.zoomObjects(this.valueAxes); this.zoomObjects(this.graphs);this.zoomTrendLines();this.prevPlotAreaWidth=this.plotAreaWidth;this.prevPlotAreaHeight=this.plotAreaHeight},validateData:function(){if(this.zoomOutOnDataUpdate)for(var a=this.valueAxes,b=0;b<a.length;b++)a[b].minZoom=NaN,a[b].maxZoom=NaN;e.AmXYChart.base.validateData.call(this)},zoomObjects:function(a){var b=a.length,c,d;for(c=0;c<b;c++)d=a[c],d.zoom(0,this.chartData.length-1)},updateData:function(){this.parseData();var a=this.chartData,b=a.length-1,c=this.graphs,d= this.dataProvider,e=-Infinity,h=Infinity,f,k;if(d){for(f=0;f<c.length;f++)if(k=c[f],k.data=a,k.zoom(0,b),k=k.valueField){var m;for(m=0;m<d.length;m++){var l=Number(d[m][k]);null!==l&&(l>e&&(e=l),l<h&&(h=l))}}isNaN(this.minValue)||(h=this.minValue);isNaN(this.maxValue)||(e=this.maxValue);for(f=0;f<c.length;f++)k=c[f],k.maxValue=e,k.minValue=h;if(a=this.chartCursor)a.type="crosshair",a.valueBalloonsEnabled=!1;this.dataChanged=!1;this.dispatchDataUpdated=!0}},processValueAxis:function(a){a.chart=this; a.minMaxField="H"==a.orientation?"x":"y";a.min=NaN;a.max=NaN},processGraph:function(a){e.isString(a.xAxis)&&(a.xAxis=this.getValueAxisById(a.xAxis));e.isString(a.yAxis)&&(a.yAxis=this.getValueAxisById(a.yAxis));a.xAxis||(a.xAxis=this.xAxes[0]);a.yAxis||(a.yAxis=this.yAxes[0]);a.valueAxis=a.yAxis},parseData:function(){e.AmXYChart.base.parseData.call(this);this.chartData=[];var a=this.dataProvider,b=this.valueAxes,c=this.graphs,d;if(a)for(d=0;d<a.length;d++){var g={axes:{},x:{},y:{}},h=this.dataDateFormat, f=a[d],k;for(k=0;k<b.length;k++){var m=b[k].id;g.axes[m]={};g.axes[m].graphs={};var l;for(l=0;l<c.length;l++){var p=c[l],q=p.id;if(p.xAxis.id==m||p.yAxis.id==m){var r={};r.serialDataItem=g;r.index=d;var t={},n=f[p.valueField];null!==n&&(n=Number(n),isNaN(n)||(t.value=n));n=f[p.xField];null!==n&&("date"==p.xAxis.type&&(n=e.getDate(f[p.xField],h).getTime()),n=Number(n),isNaN(n)||(t.x=n));n=f[p.yField];null!==n&&("date"==p.yAxis.type&&(n=e.getDate(f[p.yField],h).getTime()),n=Number(n),isNaN(n)||(t.y= n));n=f[p.errorField];null!==n&&(n=Number(n),isNaN(n)||(t.error=n));r.values=t;this.processFields(p,r,f);r.serialDataItem=g;r.graph=p;g.axes[m].graphs[q]=r}}}this.chartData[d]=g}this.start=0;this.end=this.chartData.length-1},formatString:function(a,b,c){var d=b.graph,g=d.numberFormatter;g||(g=this.nf);var h,f;"date"==b.graph.xAxis.type&&(h=e.formatDate(new Date(b.values.x),d.dateFormat,this),f=RegExp("\\[\\[x\\]\\]","g"),a=a.replace(f,h));"date"==b.graph.yAxis.type&&(h=e.formatDate(new Date(b.values.y), d.dateFormat,this),f=RegExp("\\[\\[y\\]\\]","g"),a=a.replace(f,h));a=e.formatValue(a,b.values,["value","x","y"],g);-1!=a.indexOf("[[")&&(a=e.formatDataContextValue(a,b.dataContext));return a=e.AmXYChart.base.formatString.call(this,a,b,c)},addChartScrollbar:function(a){e.callMethod("destroy",[this.chartScrollbar,this.scrollbarH,this.scrollbarV]);if(a){this.chartScrollbar=a;this.scrollbarHeight=a.scrollbarHeight;var b="backgroundColor backgroundAlpha selectedBackgroundColor selectedBackgroundAlpha scrollDuration resizeEnabled hideResizeGrips scrollbarHeight updateOnReleaseOnly".split(" "); if(!this.hideYScrollbar){var c=new e.ChartScrollbar(this.theme);c.skipEvent=!0;c.chart=this;this.listenTo(c,"zoomed",this.handleScrollbarValueZoom);e.copyProperties(a,c,b);c.rotate=!0;this.scrollbarV=c}this.hideXScrollbar||(c=new e.ChartScrollbar(this.theme),c.skipEvent=!0,c.chart=this,this.listenTo(c,"zoomed",this.handleScrollbarValueZoom),e.copyProperties(a,c,b),c.rotate=!1,this.scrollbarH=c)}},updateTrendLines:function(){var a=this.trendLines,b;for(b=0;b<a.length;b++){var c=a[b],c=e.processObject(c, e.TrendLine,this.theme);a[b]=c;c.chart=this;var d=c.valueAxis;e.isString(d)&&(c.valueAxis=this.getValueAxisById(d));d=c.valueAxisX;e.isString(d)&&(c.valueAxisX=this.getValueAxisById(d));c.id||(c.id="trendLineAuto"+b+"_"+(new Date).getTime());c.valueAxis||(c.valueAxis=this.yAxes[0]);c.valueAxisX||(c.valueAxisX=this.xAxes[0])}},updateMargins:function(){e.AmXYChart.base.updateMargins.call(this);var a=this.scrollbarV;a&&(this.getScrollbarPosition(a,!0,this.yAxes[0].position),this.adjustMargins(a,!0)); if(a=this.scrollbarH)this.getScrollbarPosition(a,!1,this.xAxes[0].position),this.adjustMargins(a,!1)},updateScrollbars:function(){e.AmXYChart.base.updateScrollbars.call(this);var a=this.scrollbarV;a&&(this.updateChartScrollbar(a,!0),a.valueAxes=this.yAxes,a.gridAxis||(a.gridAxis=this.yAxes[0]));if(a=this.scrollbarH)this.updateChartScrollbar(a,!1),a.valueAxes=this.xAxes,a.gridAxis||(a.gridAxis=this.xAxes[0])},removeChartScrollbar:function(){e.callMethod("destroy",[this.scrollbarH,this.scrollbarV]); this.scrollbarV=this.scrollbarH=null},handleReleaseOutside:function(a){e.AmXYChart.base.handleReleaseOutside.call(this,a);e.callMethod("handleReleaseOutside",[this.scrollbarH,this.scrollbarV])},update:function(){e.AmXYChart.base.update.call(this);this.scrollbarH&&this.scrollbarH.update&&this.scrollbarH.update();this.scrollbarV&&this.scrollbarV.update&&this.scrollbarV.update()},zoomScrollbar:function(){this.zoomValueScrollbar(this.scrollbarV);this.zoomValueScrollbar(this.scrollbarH)},handleCursorZoomReal:function(a, b,c,d){isNaN(a)||isNaN(b)||this.relativeZoomValueAxes(this.xAxes,a,b);isNaN(c)||isNaN(d)||this.relativeZoomValueAxes(this.yAxes,c,d);this.updateAfterValueZoom()},handleCursorZoomStarted:function(){if(this.xAxes){var a=this.xAxes[0];this.startX0=a.relativeStart;this.endX0=a.relativeEnd;a.reversed&&(this.startX0=1-a.relativeEnd,this.endX0=1-a.relativeStart)}this.yAxes&&(a=this.yAxes[0],this.startY0=a.relativeStart,this.endY0=a.relativeEnd,a.reversed&&(this.startY0=1-a.relativeEnd,this.endY0=1-a.relativeStart))}, updateChartCursor:function(){e.AmXYChart.base.updateChartCursor.call(this);var a=this.chartCursor;if(a){a.valueLineEnabled=!0;a.categoryLineAxis||(a.categoryLineAxis=this.xAxes[0]);var b=this.valueAxis;if(a.valueLineBalloonEnabled){var c=a.categoryBalloonAlpha,d=a.categoryBalloonColor,g=a.color;void 0===d&&(d=a.cursorColor);for(var h=0;h<this.valueAxes.length;h++){var b=this.valueAxes[h],f=b.balloon;f||(f={});f=e.extend(f,this.balloon,!0);f.fillColor=d;f.balloonColor=d;f.fillAlpha=c;f.borderColor= d;f.color=g;b.balloon=f}}else for(c=0;c<this.valueAxes.length;c++)b=this.valueAxes[c],b.balloon&&(b.balloon=null);a.zoomable&&(this.hideYScrollbar||(a.vZoomEnabled=!0),this.hideXScrollbar||(a.hZoomEnabled=!0))}},handleCursorPanning:function(a){var b=a.deltaX,c=a.delta2X,d;isNaN(c)&&(c=b,d=!0);var g=this.endX0,h=this.startX0,f=g-h,c=g-f*c,g=f;d||(g=0);b=e.fitToBounds(h-f*b,0,1-g);c=e.fitToBounds(c,g,1);this.relativeZoomValueAxes(this.xAxes,b,c);f=a.deltaY;a=a.delta2Y;isNaN(a)&&(a=f,d=!0);c=this.endY0; b=this.startY0;h=c-b;f=c+h*f;c=h;d||(c=0);d=e.fitToBounds(b+h*a,0,1-c);f=e.fitToBounds(f,c,1);this.relativeZoomValueAxes(this.yAxes,d,f);this.updateAfterValueZoom()},handleValueAxisZoom:function(a){this.handleValueAxisZoomReal(a,"V"==a.valueAxis.orientation?this.yAxes:this.xAxes)},showZB:function(){var a,b=this.valueAxes;if(b)for(var c=0;c<b.length;c++){var d=b[c];0!==d.relativeStart&&(a=!0);1!=d.relativeEnd&&(a=!0)}e.AmXYChart.base.showZB.call(this,a)}})})();
Asaf-S/jsdelivr
files/amcharts/3.21.0/xy.js
JavaScript
mit
21,406
/* * Copyright (c) 2007-2012 SlimDX Group * * 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. */ #pragma once #include "../dxgi/Enums.h" #include "Enums11.h" namespace SlimDX { namespace Direct3D11 { /// <summary> /// Contains the description of the contents of an image file. /// </summary> /// <unmanaged>D3DX11_IMAGE_LOAD_INFO</unmanaged> [System::Runtime::InteropServices::StructLayout( System::Runtime::InteropServices::LayoutKind::Sequential )] public value class ImageLoadInformation : System::IEquatable<ImageLoadInformation> { private: int m_Width; int m_Height; int m_Depth; int m_FirstMipLevel; int m_MipLevels; ResourceUsage m_Usage; BindFlags m_BindFlags; CpuAccessFlags m_CPUAccessFlags; ResourceOptionFlags m_MiscFlags; DXGI::Format m_Format; FilterFlags m_Filter; FilterFlags m_MipFilter; internal: ImageLoadInformation( const D3DX11_IMAGE_LOAD_INFO& native ); D3DX11_IMAGE_LOAD_INFO CreateNativeVersion(); public: /// <summary> /// Initializes a new instance of the <see cref="ImageLoadInformation"/> struct using default values. /// </summary> /// <returns>The default image load information.</returns> static ImageLoadInformation FromDefaults(); /// <summary> /// The default value for load options. /// </summary> property static int FileDefaultValue { int get(); } /// <summary> /// Width of the original image, in pixels. /// </summary> property int Width { int get(); void set( int value ); } /// <summary> /// Height of the original image, in pixels. /// </summary> property int Height { int get(); void set( int value ); } /// <summary> /// Depth of the original image, in pixels. /// </summary> property int Depth { int get(); void set( int value ); } /// <summary> /// The highest resolution mipmap level of the texture; if greater than zero, /// this mipmap level will be mapped to level 0 in the loaded texture. /// </summary> property int FirstMipLevel { int get(); void set( int value ); } /// <summary> /// Number of mipmap levels in the original image. /// </summary> property int MipLevels { int get(); void set( int value ); } /// <summary> /// Gets or sets the intended usage pattern of the loaded texture. /// </summary> property ResourceUsage Usage { ResourceUsage get(); void set( ResourceUsage value ); } /// <summary> /// Gets or sets the flags specifying how the loaded texture is bound to the pipeline. /// </summary> property Direct3D11::BindFlags BindFlags { Direct3D11::BindFlags get(); void set( Direct3D11::BindFlags value ); } /// <summary> /// Gets or sets the flags specifying how the CPU will be allowed to access the loaded texture. /// </summary> property Direct3D11::CpuAccessFlags CpuAccessFlags { Direct3D11::CpuAccessFlags get(); void set( Direct3D11::CpuAccessFlags value ); } /// <summary> /// Gets or sets the flags specifying miscellaneous resource options. /// </summary> property ResourceOptionFlags OptionFlags { ResourceOptionFlags get(); void set( ResourceOptionFlags value ); } /// <summary> /// The format of the loaded texture. /// </summary> property DXGI::Format Format { DXGI::Format get(); void set( DXGI::Format value ); } /// <summary> /// The filter used when resampling the texture. /// </summary> property Direct3D11::FilterFlags FilterFlags { Direct3D11::FilterFlags get(); void set( Direct3D11::FilterFlags value ); } /// <summary> /// The filter used when resampling mipmap levels of the texture. /// </summary> property Direct3D11::FilterFlags MipFilterFlags { Direct3D11::FilterFlags get(); void set( Direct3D11::FilterFlags value ); } /// <summary> /// Tests for equality between two objects. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns><c>true</c> if <paramref name="left"/> has the same value as <paramref name="right"/>; otherwise, <c>false</c>.</returns> static bool operator == ( ImageLoadInformation left, ImageLoadInformation right ); /// <summary> /// Tests for inequality between two objects. /// </summary> /// <param name="left">The first value to compare.</param> /// <param name="right">The second value to compare.</param> /// <returns><c>true</c> if <paramref name="left"/> has a different value than <paramref name="right"/>; otherwise, <c>false</c>.</returns> static bool operator != ( ImageLoadInformation left, ImageLoadInformation right ); /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> virtual int GetHashCode() override; /// <summary> /// Returns a value that indicates whether the current instance is equal to a specified object. /// </summary> /// <param name="obj">Object to make the comparison with.</param> /// <returns><c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> virtual bool Equals( System::Object^ obj ) override; /// <summary> /// Returns a value that indicates whether the current instance is equal to the specified object. /// </summary> /// <param name="other">Object to make the comparison with.</param> /// <returns><c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns> virtual bool Equals( ImageLoadInformation other ); /// <summary> /// Determines whether the specified object instances are considered equal. /// </summary> /// <param name="value1">The first value to compare.</param> /// <param name="value2">The second value to compare.</param> /// <returns><c>true</c> if <paramref name="value1"/> is the same instance as <paramref name="value2"/> or /// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns> static bool Equals( ImageLoadInformation% value1, ImageLoadInformation% value2 ); }; } }
dawnoble/slimdx
source/direct3d11/ImageLoadInformation11.h
C
mit
7,609
/* * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package build.tools.jdwpgen; import java.util.*; import java.io.*; class AltNode extends AbstractGroupNode implements TypeNode { SelectNode select = null; void constrain(Context ctx) { super.constrain(ctx); if (!(nameNode instanceof NameValueNode)) { error("Alt name must have value: " + nameNode); } if (parent instanceof SelectNode) { select = (SelectNode)parent; } else { error("Alt must be in Select"); } } void document(PrintWriter writer) { docRowStart(writer); writer.println("<td colspan=" + (maxStructIndent - structIndent + 1) + ">"); writer.println("Case " + nameNode.name + " - if <i>" + ((SelectNode)parent).typeNode.name + "</i> is " + nameNode.value() + ":"); writer.println("<td>" + comment() + "&nbsp;"); ++structIndent; super.document(writer); --structIndent; } String javaClassImplements() { return " extends " + select.commonBaseClass(); } void genJavaClassSpecifics(PrintWriter writer, int depth) { indent(writer, depth); writer.print("static final " + select.typeNode.javaType()); writer.println(" ALT_ID = " + nameNode.value() + ";"); if (context.isWritingCommand()) { genJavaCreateMethod(writer, depth); } else { indent(writer, depth); writer.println(select.typeNode.javaParam() + "() {"); indent(writer, depth+1); writer.println("return ALT_ID;"); indent(writer, depth); writer.println("}"); } super.genJavaClassSpecifics(writer, depth); } void genJavaWriteMethod(PrintWriter writer, int depth) { genJavaWriteMethod(writer, depth, ""); } void genJavaReadsSelectCase(PrintWriter writer, int depth, String common) { indent(writer, depth); writer.println("case " + nameNode.value() + ":"); indent(writer, depth+1); writer.println(common + " = new " + name + "(vm, ps);"); indent(writer, depth+1); writer.println("break;"); } void genJavaCreateMethod(PrintWriter writer, int depth) { indent(writer, depth); writer.print("static " + select.name() + " create("); writer.print(javaParams()); writer.println(") {"); indent(writer, depth+1); writer.print("return new " + select.name() + "("); writer.print("ALT_ID, new " + javaClassName() + "("); for (Iterator it = components.iterator(); it.hasNext();) { TypeNode tn = (TypeNode)it.next(); writer.print(tn.name()); if (it.hasNext()) { writer.print(", "); } } writer.println("));"); indent(writer, depth); writer.println("}"); } }
rokn/Count_Words_2015
testing/openjdk/jdk/make/tools/src/build/tools/jdwpgen/AltNode.java
Java
mit
4,156
/* * Copyright (C) 2005-2020 Team Kodi * This file is part of Kodi - https://kodi.tv * * SPDX-License-Identifier: GPL-2.0-or-later * See LICENSES/README.md for more information. */ #include "DRMEncoder.h" #include <cstring> #include <errno.h> #include <stdexcept> #include <string> using namespace KODI::WINDOWING::GBM; CDRMEncoder::CDRMEncoder(int fd, uint32_t encoder) : CDRMObject(fd), m_encoder(drmModeGetEncoder(m_fd, encoder)) { if (!m_encoder) throw std::runtime_error("drmModeGetEncoder failed: " + std::string{strerror(errno)}); }
asavah/xbmc
xbmc/windowing/gbm/drm/DRMEncoder.cpp
C++
gpl-2.0
562
/* * Simplified MAC Kernel (smack) security module * * This file contains the smack hook function implementations. * * Author: * Casey Schaufler <casey@schaufler-ca.com> * * Copyright (C) 2007 Casey Schaufler <casey@schaufler-ca.com> * Copyright (C) 2009 Hewlett-Packard Development Company, L.P. * Paul Moore <paul.moore@hp.com> * * 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. */ #include <linux/xattr.h> #include <linux/pagemap.h> #include <linux/mount.h> #include <linux/stat.h> #include <linux/ext2_fs.h> #include <linux/kd.h> #include <asm/ioctls.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/udp.h> #include <linux/mutex.h> #include <linux/pipe_fs_i.h> #include <net/netlabel.h> #include <net/cipso_ipv4.h> #include <linux/audit.h> #include "smack.h" #define task_security(task) (task_cred_xxx((task), security)) /* * I hope these are the hokeyist lines of code in the module. Casey. */ #define DEVPTS_SUPER_MAGIC 0x1cd1 #define SOCKFS_MAGIC 0x534F434B #define TMPFS_MAGIC 0x01021994 /** * smk_fetch - Fetch the smack label from a file. * @ip: a pointer to the inode * @dp: a pointer to the dentry * * Returns a pointer to the master list entry for the Smack label * or NULL if there was no label to fetch. */ static char *smk_fetch(struct inode *ip, struct dentry *dp) { int rc; char in[SMK_LABELLEN]; if (ip->i_op->getxattr == NULL) return NULL; rc = ip->i_op->getxattr(dp, XATTR_NAME_SMACK, in, SMK_LABELLEN); if (rc < 0) return NULL; return smk_import(in, rc); } /** * new_inode_smack - allocate an inode security blob * @smack: a pointer to the Smack label to use in the blob * * Returns the new blob or NULL if there's no memory available */ struct inode_smack *new_inode_smack(char *smack) { struct inode_smack *isp; isp = kzalloc(sizeof(struct inode_smack), GFP_KERNEL); if (isp == NULL) return NULL; isp->smk_inode = smack; isp->smk_flags = 0; mutex_init(&isp->smk_lock); return isp; } /* * LSM hooks. * We he, that is fun! */ /** * smack_ptrace_may_access - Smack approval on PTRACE_ATTACH * @ctp: child task pointer * @mode: ptrace attachment mode * * Returns 0 if access is OK, an error code otherwise * * Do the capability checks, and require read and write. */ static int smack_ptrace_may_access(struct task_struct *ctp, unsigned int mode) { int rc; rc = cap_ptrace_may_access(ctp, mode); if (rc != 0) return rc; rc = smk_access(current_security(), task_security(ctp), MAY_READWRITE); if (rc != 0 && capable(CAP_MAC_OVERRIDE)) return 0; return rc; } /** * smack_ptrace_traceme - Smack approval on PTRACE_TRACEME * @ptp: parent task pointer * * Returns 0 if access is OK, an error code otherwise * * Do the capability checks, and require read and write. */ static int smack_ptrace_traceme(struct task_struct *ptp) { int rc; rc = cap_ptrace_traceme(ptp); if (rc != 0) return rc; rc = smk_access(task_security(ptp), current_security(), MAY_READWRITE); if (rc != 0 && has_capability(ptp, CAP_MAC_OVERRIDE)) return 0; return rc; } /** * smack_syslog - Smack approval on syslog * @type: message type * * Require that the task has the floor label * * Returns 0 on success, error code otherwise. */ static int smack_syslog(int type) { int rc; char *sp = current_security(); rc = cap_syslog(type); if (rc != 0) return rc; if (capable(CAP_MAC_OVERRIDE)) return 0; if (sp != smack_known_floor.smk_known) rc = -EACCES; return rc; } /* * Superblock Hooks. */ /** * smack_sb_alloc_security - allocate a superblock blob * @sb: the superblock getting the blob * * Returns 0 on success or -ENOMEM on error. */ static int smack_sb_alloc_security(struct super_block *sb) { struct superblock_smack *sbsp; sbsp = kzalloc(sizeof(struct superblock_smack), GFP_KERNEL); if (sbsp == NULL) return -ENOMEM; sbsp->smk_root = smack_known_floor.smk_known; sbsp->smk_default = smack_known_floor.smk_known; sbsp->smk_floor = smack_known_floor.smk_known; sbsp->smk_hat = smack_known_hat.smk_known; sbsp->smk_initialized = 0; spin_lock_init(&sbsp->smk_sblock); sb->s_security = sbsp; return 0; } /** * smack_sb_free_security - free a superblock blob * @sb: the superblock getting the blob * */ static void smack_sb_free_security(struct super_block *sb) { kfree(sb->s_security); sb->s_security = NULL; } /** * smack_sb_copy_data - copy mount options data for processing * @orig: where to start * @smackopts: mount options string * * Returns 0 on success or -ENOMEM on error. * * Copy the Smack specific mount options out of the mount * options list. */ static int smack_sb_copy_data(char *orig, char *smackopts) { char *cp, *commap, *otheropts, *dp; otheropts = (char *)get_zeroed_page(GFP_KERNEL); if (otheropts == NULL) return -ENOMEM; for (cp = orig, commap = orig; commap != NULL; cp = commap + 1) { if (strstr(cp, SMK_FSDEFAULT) == cp) dp = smackopts; else if (strstr(cp, SMK_FSFLOOR) == cp) dp = smackopts; else if (strstr(cp, SMK_FSHAT) == cp) dp = smackopts; else if (strstr(cp, SMK_FSROOT) == cp) dp = smackopts; else dp = otheropts; commap = strchr(cp, ','); if (commap != NULL) *commap = '\0'; if (*dp != '\0') strcat(dp, ","); strcat(dp, cp); } strcpy(orig, otheropts); free_page((unsigned long)otheropts); return 0; } /** * smack_sb_kern_mount - Smack specific mount processing * @sb: the file system superblock * @flags: the mount flags * @data: the smack mount options * * Returns 0 on success, an error code on failure */ static int smack_sb_kern_mount(struct super_block *sb, int flags, void *data) { struct dentry *root = sb->s_root; struct inode *inode = root->d_inode; struct superblock_smack *sp = sb->s_security; struct inode_smack *isp; char *op; char *commap; char *nsp; spin_lock(&sp->smk_sblock); if (sp->smk_initialized != 0) { spin_unlock(&sp->smk_sblock); return 0; } sp->smk_initialized = 1; spin_unlock(&sp->smk_sblock); for (op = data; op != NULL; op = commap) { commap = strchr(op, ','); if (commap != NULL) *commap++ = '\0'; if (strncmp(op, SMK_FSHAT, strlen(SMK_FSHAT)) == 0) { op += strlen(SMK_FSHAT); nsp = smk_import(op, 0); if (nsp != NULL) sp->smk_hat = nsp; } else if (strncmp(op, SMK_FSFLOOR, strlen(SMK_FSFLOOR)) == 0) { op += strlen(SMK_FSFLOOR); nsp = smk_import(op, 0); if (nsp != NULL) sp->smk_floor = nsp; } else if (strncmp(op, SMK_FSDEFAULT, strlen(SMK_FSDEFAULT)) == 0) { op += strlen(SMK_FSDEFAULT); nsp = smk_import(op, 0); if (nsp != NULL) sp->smk_default = nsp; } else if (strncmp(op, SMK_FSROOT, strlen(SMK_FSROOT)) == 0) { op += strlen(SMK_FSROOT); nsp = smk_import(op, 0); if (nsp != NULL) sp->smk_root = nsp; } } /* * Initialize the root inode. */ isp = inode->i_security; if (isp == NULL) inode->i_security = new_inode_smack(sp->smk_root); else isp->smk_inode = sp->smk_root; return 0; } /** * smack_sb_statfs - Smack check on statfs * @dentry: identifies the file system in question * * Returns 0 if current can read the floor of the filesystem, * and error code otherwise */ static int smack_sb_statfs(struct dentry *dentry) { struct superblock_smack *sbp = dentry->d_sb->s_security; return smk_curacc(sbp->smk_floor, MAY_READ); } /** * smack_sb_mount - Smack check for mounting * @dev_name: unused * @path: mount point * @type: unused * @flags: unused * @data: unused * * Returns 0 if current can write the floor of the filesystem * being mounted on, an error code otherwise. */ static int smack_sb_mount(char *dev_name, struct path *path, char *type, unsigned long flags, void *data) { struct superblock_smack *sbp = path->mnt->mnt_sb->s_security; return smk_curacc(sbp->smk_floor, MAY_WRITE); } /** * smack_sb_umount - Smack check for unmounting * @mnt: file system to unmount * @flags: unused * * Returns 0 if current can write the floor of the filesystem * being unmounted, an error code otherwise. */ static int smack_sb_umount(struct vfsmount *mnt, int flags) { struct superblock_smack *sbp; sbp = mnt->mnt_sb->s_security; return smk_curacc(sbp->smk_floor, MAY_WRITE); } /* * Inode hooks */ /** * smack_inode_alloc_security - allocate an inode blob * @inode: the inode in need of a blob * * Returns 0 if it gets a blob, -ENOMEM otherwise */ static int smack_inode_alloc_security(struct inode *inode) { inode->i_security = new_inode_smack(current_security()); if (inode->i_security == NULL) return -ENOMEM; return 0; } /** * smack_inode_free_security - free an inode blob * @inode: the inode with a blob * * Clears the blob pointer in inode */ static void smack_inode_free_security(struct inode *inode) { kfree(inode->i_security); inode->i_security = NULL; } /** * smack_inode_init_security - copy out the smack from an inode * @inode: the inode * @dir: unused * @name: where to put the attribute name * @value: where to put the attribute value * @len: where to put the length of the attribute * * Returns 0 if it all works out, -ENOMEM if there's no memory */ static int smack_inode_init_security(struct inode *inode, struct inode *dir, char **name, void **value, size_t *len) { char *isp = smk_of_inode(inode); if (name) { *name = kstrdup(XATTR_SMACK_SUFFIX, GFP_KERNEL); if (*name == NULL) return -ENOMEM; } if (value) { *value = kstrdup(isp, GFP_KERNEL); if (*value == NULL) return -ENOMEM; } if (len) *len = strlen(isp) + 1; return 0; } /** * smack_inode_link - Smack check on link * @old_dentry: the existing object * @dir: unused * @new_dentry: the new object * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry) { int rc; char *isp; isp = smk_of_inode(old_dentry->d_inode); rc = smk_curacc(isp, MAY_WRITE); if (rc == 0 && new_dentry->d_inode != NULL) { isp = smk_of_inode(new_dentry->d_inode); rc = smk_curacc(isp, MAY_WRITE); } return rc; } /** * smack_inode_unlink - Smack check on inode deletion * @dir: containing directory object * @dentry: file to unlink * * Returns 0 if current can write the containing directory * and the object, error code otherwise */ static int smack_inode_unlink(struct inode *dir, struct dentry *dentry) { struct inode *ip = dentry->d_inode; int rc; /* * You need write access to the thing you're unlinking */ rc = smk_curacc(smk_of_inode(ip), MAY_WRITE); if (rc == 0) /* * You also need write access to the containing directory */ rc = smk_curacc(smk_of_inode(dir), MAY_WRITE); return rc; } /** * smack_inode_rmdir - Smack check on directory deletion * @dir: containing directory object * @dentry: directory to unlink * * Returns 0 if current can write the containing directory * and the directory, error code otherwise */ static int smack_inode_rmdir(struct inode *dir, struct dentry *dentry) { int rc; /* * You need write access to the thing you're removing */ rc = smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE); if (rc == 0) /* * You also need write access to the containing directory */ rc = smk_curacc(smk_of_inode(dir), MAY_WRITE); return rc; } /** * smack_inode_rename - Smack check on rename * @old_inode: the old directory * @old_dentry: unused * @new_inode: the new directory * @new_dentry: unused * * Read and write access is required on both the old and * new directories. * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_rename(struct inode *old_inode, struct dentry *old_dentry, struct inode *new_inode, struct dentry *new_dentry) { int rc; char *isp; isp = smk_of_inode(old_dentry->d_inode); rc = smk_curacc(isp, MAY_READWRITE); if (rc == 0 && new_dentry->d_inode != NULL) { isp = smk_of_inode(new_dentry->d_inode); rc = smk_curacc(isp, MAY_READWRITE); } return rc; } /** * smack_inode_permission - Smack version of permission() * @inode: the inode in question * @mask: the access requested * * This is the important Smack hook. * * Returns 0 if access is permitted, -EACCES otherwise */ static int smack_inode_permission(struct inode *inode, int mask) { /* * No permission to check. Existence test. Yup, it's there. */ if (mask == 0) return 0; return smk_curacc(smk_of_inode(inode), mask); } /** * smack_inode_setattr - Smack check for setting attributes * @dentry: the object * @iattr: for the force flag * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_setattr(struct dentry *dentry, struct iattr *iattr) { /* * Need to allow for clearing the setuid bit. */ if (iattr->ia_valid & ATTR_FORCE) return 0; return smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE); } /** * smack_inode_getattr - Smack check for getting attributes * @mnt: unused * @dentry: the object * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_getattr(struct vfsmount *mnt, struct dentry *dentry) { return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ); } /** * smack_inode_setxattr - Smack check for setting xattrs * @dentry: the object * @name: name of the attribute * @value: unused * @size: unused * @flags: unused * * This protects the Smack attribute explicitly. * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags) { int rc = 0; if (strcmp(name, XATTR_NAME_SMACK) == 0 || strcmp(name, XATTR_NAME_SMACKIPIN) == 0 || strcmp(name, XATTR_NAME_SMACKIPOUT) == 0) { if (!capable(CAP_MAC_ADMIN)) rc = -EPERM; /* * check label validity here so import wont fail on * post_setxattr */ if (size == 0 || size >= SMK_LABELLEN || smk_import(value, size) == NULL) rc = -EINVAL; } else rc = cap_inode_setxattr(dentry, name, value, size, flags); if (rc == 0) rc = smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE); return rc; } /** * smack_inode_post_setxattr - Apply the Smack update approved above * @dentry: object * @name: attribute name * @value: attribute value * @size: attribute size * @flags: unused * * Set the pointer in the inode blob to the entry found * in the master label list. */ static void smack_inode_post_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags) { struct inode_smack *isp; char *nsp; /* * Not SMACK */ if (strcmp(name, XATTR_NAME_SMACK)) return; isp = dentry->d_inode->i_security; /* * No locking is done here. This is a pointer * assignment. */ nsp = smk_import(value, size); if (nsp != NULL) isp->smk_inode = nsp; else isp->smk_inode = smack_known_invalid.smk_known; return; } /* * smack_inode_getxattr - Smack check on getxattr * @dentry: the object * @name: unused * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_getxattr(struct dentry *dentry, const char *name) { return smk_curacc(smk_of_inode(dentry->d_inode), MAY_READ); } /* * smack_inode_removexattr - Smack check on removexattr * @dentry: the object * @name: name of the attribute * * Removing the Smack attribute requires CAP_MAC_ADMIN * * Returns 0 if access is permitted, an error code otherwise */ static int smack_inode_removexattr(struct dentry *dentry, const char *name) { int rc = 0; if (strcmp(name, XATTR_NAME_SMACK) == 0 || strcmp(name, XATTR_NAME_SMACKIPIN) == 0 || strcmp(name, XATTR_NAME_SMACKIPOUT) == 0) { if (!capable(CAP_MAC_ADMIN)) rc = -EPERM; } else rc = cap_inode_removexattr(dentry, name); if (rc == 0) rc = smk_curacc(smk_of_inode(dentry->d_inode), MAY_WRITE); return rc; } /** * smack_inode_getsecurity - get smack xattrs * @inode: the object * @name: attribute name * @buffer: where to put the result * @alloc: unused * * Returns the size of the attribute or an error code */ static int smack_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc) { struct socket_smack *ssp; struct socket *sock; struct super_block *sbp; struct inode *ip = (struct inode *)inode; char *isp; int ilen; int rc = 0; if (strcmp(name, XATTR_SMACK_SUFFIX) == 0) { isp = smk_of_inode(inode); ilen = strlen(isp) + 1; *buffer = isp; return ilen; } /* * The rest of the Smack xattrs are only on sockets. */ sbp = ip->i_sb; if (sbp->s_magic != SOCKFS_MAGIC) return -EOPNOTSUPP; sock = SOCKET_I(ip); if (sock == NULL || sock->sk == NULL) return -EOPNOTSUPP; ssp = sock->sk->sk_security; if (strcmp(name, XATTR_SMACK_IPIN) == 0) isp = ssp->smk_in; else if (strcmp(name, XATTR_SMACK_IPOUT) == 0) isp = ssp->smk_out; else return -EOPNOTSUPP; ilen = strlen(isp) + 1; if (rc == 0) { *buffer = isp; rc = ilen; } return rc; } /** * smack_inode_listsecurity - list the Smack attributes * @inode: the object * @buffer: where they go * @buffer_size: size of buffer * * Returns 0 on success, -EINVAL otherwise */ static int smack_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size) { int len = strlen(XATTR_NAME_SMACK); if (buffer != NULL && len <= buffer_size) { memcpy(buffer, XATTR_NAME_SMACK, len); return len; } return -EINVAL; } /** * smack_inode_getsecid - Extract inode's security id * @inode: inode to extract the info from * @secid: where result will be saved */ static void smack_inode_getsecid(const struct inode *inode, u32 *secid) { struct inode_smack *isp = inode->i_security; *secid = smack_to_secid(isp->smk_inode); } /* * File Hooks */ /** * smack_file_permission - Smack check on file operations * @file: unused * @mask: unused * * Returns 0 * * Should access checks be done on each read or write? * UNICOS and SELinux say yes. * Trusted Solaris, Trusted Irix, and just about everyone else says no. * * I'll say no for now. Smack does not do the frequent * label changing that SELinux does. */ static int smack_file_permission(struct file *file, int mask) { return 0; } /** * smack_file_alloc_security - assign a file security blob * @file: the object * * The security blob for a file is a pointer to the master * label list, so no allocation is done. * * Returns 0 */ static int smack_file_alloc_security(struct file *file) { file->f_security = current_security(); return 0; } /** * smack_file_free_security - clear a file security blob * @file: the object * * The security blob for a file is a pointer to the master * label list, so no memory is freed. */ static void smack_file_free_security(struct file *file) { file->f_security = NULL; } /** * smack_file_ioctl - Smack check on ioctls * @file: the object * @cmd: what to do * @arg: unused * * Relies heavily on the correct use of the ioctl command conventions. * * Returns 0 if allowed, error code otherwise */ static int smack_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int rc = 0; if (_IOC_DIR(cmd) & _IOC_WRITE) rc = smk_curacc(file->f_security, MAY_WRITE); if (rc == 0 && (_IOC_DIR(cmd) & _IOC_READ)) rc = smk_curacc(file->f_security, MAY_READ); return rc; } /** * smack_file_lock - Smack check on file locking * @file: the object * @cmd: unused * * Returns 0 if current has write access, error code otherwise */ static int smack_file_lock(struct file *file, unsigned int cmd) { return smk_curacc(file->f_security, MAY_WRITE); } /** * smack_file_fcntl - Smack check on fcntl * @file: the object * @cmd: what action to check * @arg: unused * * Returns 0 if current has access, error code otherwise */ static int smack_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { int rc; switch (cmd) { case F_DUPFD: case F_GETFD: case F_GETFL: case F_GETLK: case F_GETOWN: case F_GETSIG: rc = smk_curacc(file->f_security, MAY_READ); break; case F_SETFD: case F_SETFL: case F_SETLK: case F_SETLKW: case F_SETOWN: case F_SETSIG: rc = smk_curacc(file->f_security, MAY_WRITE); break; default: rc = smk_curacc(file->f_security, MAY_READWRITE); } return rc; } /** * smack_file_set_fowner - set the file security blob value * @file: object in question * * Returns 0 * Further research may be required on this one. */ static int smack_file_set_fowner(struct file *file) { file->f_security = current_security(); return 0; } /** * smack_file_send_sigiotask - Smack on sigio * @tsk: The target task * @fown: the object the signal come from * @signum: unused * * Allow a privileged task to get signals even if it shouldn't * * Returns 0 if a subject with the object's smack could * write to the task, an error code otherwise. */ static int smack_file_send_sigiotask(struct task_struct *tsk, struct fown_struct *fown, int signum) { struct file *file; int rc; /* * struct fown_struct is never outside the context of a struct file */ file = container_of(fown, struct file, f_owner); rc = smk_access(file->f_security, tsk->cred->security, MAY_WRITE); if (rc != 0 && has_capability(tsk, CAP_MAC_OVERRIDE)) return 0; return rc; } /** * smack_file_receive - Smack file receive check * @file: the object * * Returns 0 if current has access, error code otherwise */ static int smack_file_receive(struct file *file) { int may = 0; /* * This code relies on bitmasks. */ if (file->f_mode & FMODE_READ) may = MAY_READ; if (file->f_mode & FMODE_WRITE) may |= MAY_WRITE; return smk_curacc(file->f_security, may); } /* * Task hooks */ /** * smack_cred_free - "free" task-level security credentials * @cred: the credentials in question * * Smack isn't using copies of blobs. Everyone * points to an immutable list. The blobs never go away. * There is no leak here. */ static void smack_cred_free(struct cred *cred) { cred->security = NULL; } /** * smack_cred_prepare - prepare new set of credentials for modification * @new: the new credentials * @old: the original credentials * @gfp: the atomicity of any memory allocations * * Prepare a new set of credentials for modification. */ static int smack_cred_prepare(struct cred *new, const struct cred *old, gfp_t gfp) { new->security = old->security; return 0; } /** * smack_cred_commit - commit new credentials * @new: the new credentials * @old: the original credentials */ static void smack_cred_commit(struct cred *new, const struct cred *old) { } /** * smack_kernel_act_as - Set the subjective context in a set of credentials * @new: points to the set of credentials to be modified. * @secid: specifies the security ID to be set * * Set the security data for a kernel service. */ static int smack_kernel_act_as(struct cred *new, u32 secid) { char *smack = smack_from_secid(secid); if (smack == NULL) return -EINVAL; new->security = smack; return 0; } /** * smack_kernel_create_files_as - Set the file creation label in a set of creds * @new: points to the set of credentials to be modified * @inode: points to the inode to use as a reference * * Set the file creation context in a set of credentials to the same * as the objective context of the specified inode */ static int smack_kernel_create_files_as(struct cred *new, struct inode *inode) { struct inode_smack *isp = inode->i_security; new->security = isp->smk_inode; return 0; } /** * smack_task_setpgid - Smack check on setting pgid * @p: the task object * @pgid: unused * * Return 0 if write access is permitted */ static int smack_task_setpgid(struct task_struct *p, pid_t pgid) { return smk_curacc(task_security(p), MAY_WRITE); } /** * smack_task_getpgid - Smack access check for getpgid * @p: the object task * * Returns 0 if current can read the object task, error code otherwise */ static int smack_task_getpgid(struct task_struct *p) { return smk_curacc(task_security(p), MAY_READ); } /** * smack_task_getsid - Smack access check for getsid * @p: the object task * * Returns 0 if current can read the object task, error code otherwise */ static int smack_task_getsid(struct task_struct *p) { return smk_curacc(task_security(p), MAY_READ); } /** * smack_task_getsecid - get the secid of the task * @p: the object task * @secid: where to put the result * * Sets the secid to contain a u32 version of the smack label. */ static void smack_task_getsecid(struct task_struct *p, u32 *secid) { *secid = smack_to_secid(task_security(p)); } /** * smack_task_setnice - Smack check on setting nice * @p: the task object * @nice: unused * * Return 0 if write access is permitted */ static int smack_task_setnice(struct task_struct *p, int nice) { int rc; rc = cap_task_setnice(p, nice); if (rc == 0) rc = smk_curacc(task_security(p), MAY_WRITE); return rc; } /** * smack_task_setioprio - Smack check on setting ioprio * @p: the task object * @ioprio: unused * * Return 0 if write access is permitted */ static int smack_task_setioprio(struct task_struct *p, int ioprio) { int rc; rc = cap_task_setioprio(p, ioprio); if (rc == 0) rc = smk_curacc(task_security(p), MAY_WRITE); return rc; } /** * smack_task_getioprio - Smack check on reading ioprio * @p: the task object * * Return 0 if read access is permitted */ static int smack_task_getioprio(struct task_struct *p) { return smk_curacc(task_security(p), MAY_READ); } /** * smack_task_setscheduler - Smack check on setting scheduler * @p: the task object * @policy: unused * @lp: unused * * Return 0 if read access is permitted */ static int smack_task_setscheduler(struct task_struct *p, int policy, struct sched_param *lp) { int rc; rc = cap_task_setscheduler(p, policy, lp); if (rc == 0) rc = smk_curacc(task_security(p), MAY_WRITE); return rc; } /** * smack_task_getscheduler - Smack check on reading scheduler * @p: the task object * * Return 0 if read access is permitted */ static int smack_task_getscheduler(struct task_struct *p) { return smk_curacc(task_security(p), MAY_READ); } /** * smack_task_movememory - Smack check on moving memory * @p: the task object * * Return 0 if write access is permitted */ static int smack_task_movememory(struct task_struct *p) { return smk_curacc(task_security(p), MAY_WRITE); } /** * smack_task_kill - Smack check on signal delivery * @p: the task object * @info: unused * @sig: unused * @secid: identifies the smack to use in lieu of current's * * Return 0 if write access is permitted * * The secid behavior is an artifact of an SELinux hack * in the USB code. Someday it may go away. */ static int smack_task_kill(struct task_struct *p, struct siginfo *info, int sig, u32 secid) { /* * Sending a signal requires that the sender * can write the receiver. */ if (secid == 0) return smk_curacc(task_security(p), MAY_WRITE); /* * If the secid isn't 0 we're dealing with some USB IO * specific behavior. This is not clean. For one thing * we can't take privilege into account. */ return smk_access(smack_from_secid(secid), task_security(p), MAY_WRITE); } /** * smack_task_wait - Smack access check for waiting * @p: task to wait for * * Returns 0 if current can wait for p, error code otherwise */ static int smack_task_wait(struct task_struct *p) { int rc; rc = smk_access(current_security(), task_security(p), MAY_WRITE); if (rc == 0) return 0; /* * Allow the operation to succeed if either task * has privilege to perform operations that might * account for the smack labels having gotten to * be different in the first place. * * This breaks the strict subject/object access * control ideal, taking the object's privilege * state into account in the decision as well as * the smack value. */ if (capable(CAP_MAC_OVERRIDE) || has_capability(p, CAP_MAC_OVERRIDE)) return 0; return rc; } /** * smack_task_to_inode - copy task smack into the inode blob * @p: task to copy from * @inode: inode to copy to * * Sets the smack pointer in the inode security blob */ static void smack_task_to_inode(struct task_struct *p, struct inode *inode) { struct inode_smack *isp = inode->i_security; isp->smk_inode = task_security(p); } /* * Socket hooks. */ /** * smack_sk_alloc_security - Allocate a socket blob * @sk: the socket * @family: unused * @gfp_flags: memory allocation flags * * Assign Smack pointers to current * * Returns 0 on success, -ENOMEM is there's no memory */ static int smack_sk_alloc_security(struct sock *sk, int family, gfp_t gfp_flags) { char *csp = current_security(); struct socket_smack *ssp; ssp = kzalloc(sizeof(struct socket_smack), gfp_flags); if (ssp == NULL) return -ENOMEM; ssp->smk_in = csp; ssp->smk_out = csp; ssp->smk_packet[0] = '\0'; sk->sk_security = ssp; return 0; } /** * smack_sk_free_security - Free a socket blob * @sk: the socket * * Clears the blob pointer */ static void smack_sk_free_security(struct sock *sk) { kfree(sk->sk_security); } /** * smack_host_label - check host based restrictions * @sip: the object end * * looks for host based access restrictions * * This version will only be appropriate for really small sets of single label * hosts. The caller is responsible for ensuring that the RCU read lock is * taken before calling this function. * * Returns the label of the far end or NULL if it's not special. */ static char *smack_host_label(struct sockaddr_in *sip) { struct smk_netlbladdr *snp; struct in_addr *siap = &sip->sin_addr; if (siap->s_addr == 0) return NULL; list_for_each_entry_rcu(snp, &smk_netlbladdr_list, list) /* * we break after finding the first match because * the list is sorted from longest to shortest mask * so we have found the most specific match */ if ((&snp->smk_host.sin_addr)->s_addr == (siap->s_addr & (&snp->smk_mask)->s_addr)) { /* we have found the special CIPSO option */ if (snp->smk_label == smack_cipso_option) return NULL; return snp->smk_label; } return NULL; } /** * smack_set_catset - convert a capset to netlabel mls categories * @catset: the Smack categories * @sap: where to put the netlabel categories * * Allocates and fills attr.mls.cat */ static void smack_set_catset(char *catset, struct netlbl_lsm_secattr *sap) { unsigned char *cp; unsigned char m; int cat; int rc; int byte; if (!catset) return; sap->flags |= NETLBL_SECATTR_MLS_CAT; sap->attr.mls.cat = netlbl_secattr_catmap_alloc(GFP_ATOMIC); sap->attr.mls.cat->startbit = 0; for (cat = 1, cp = catset, byte = 0; byte < SMK_LABELLEN; cp++, byte++) for (m = 0x80; m != 0; m >>= 1, cat++) { if ((m & *cp) == 0) continue; rc = netlbl_secattr_catmap_setbit(sap->attr.mls.cat, cat, GFP_ATOMIC); } } /** * smack_to_secattr - fill a secattr from a smack value * @smack: the smack value * @nlsp: where the result goes * * Casey says that CIPSO is good enough for now. * It can be used to effect. * It can also be abused to effect when necessary. * Appologies to the TSIG group in general and GW in particular. */ static void smack_to_secattr(char *smack, struct netlbl_lsm_secattr *nlsp) { struct smack_cipso cipso; int rc; nlsp->domain = smack; nlsp->flags = NETLBL_SECATTR_DOMAIN | NETLBL_SECATTR_MLS_LVL; rc = smack_to_cipso(smack, &cipso); if (rc == 0) { nlsp->attr.mls.lvl = cipso.smk_level; smack_set_catset(cipso.smk_catset, nlsp); } else { nlsp->attr.mls.lvl = smack_cipso_direct; smack_set_catset(smack, nlsp); } } /** * smack_netlabel - Set the secattr on a socket * @sk: the socket * @labeled: socket label scheme * * Convert the outbound smack value (smk_out) to a * secattr and attach it to the socket. * * Returns 0 on success or an error code */ static int smack_netlabel(struct sock *sk, int labeled) { struct socket_smack *ssp = sk->sk_security; struct netlbl_lsm_secattr secattr; int rc = 0; /* * Usually the netlabel code will handle changing the * packet labeling based on the label. * The case of a single label host is different, because * a single label host should never get a labeled packet * even though the label is usually associated with a packet * label. */ local_bh_disable(); bh_lock_sock_nested(sk); if (ssp->smk_out == smack_net_ambient || labeled == SMACK_UNLABELED_SOCKET) netlbl_sock_delattr(sk); else { netlbl_secattr_init(&secattr); smack_to_secattr(ssp->smk_out, &secattr); rc = netlbl_sock_setattr(sk, sk->sk_family, &secattr); netlbl_secattr_destroy(&secattr); } bh_unlock_sock(sk); local_bh_enable(); return rc; } /** * smack_netlbel_send - Set the secattr on a socket and perform access checks * @sk: the socket * @sap: the destination address * * Set the correct secattr for the given socket based on the destination * address and perform any outbound access checks needed. * * Returns 0 on success or an error code. * */ static int smack_netlabel_send(struct sock *sk, struct sockaddr_in *sap) { int rc; int sk_lbl; char *hostsp; struct socket_smack *ssp = sk->sk_security; rcu_read_lock(); hostsp = smack_host_label(sap); if (hostsp != NULL) { sk_lbl = SMACK_UNLABELED_SOCKET; rc = smk_access(ssp->smk_out, hostsp, MAY_WRITE); } else { sk_lbl = SMACK_CIPSO_SOCKET; rc = 0; } rcu_read_unlock(); if (rc != 0) return rc; return smack_netlabel(sk, sk_lbl); } /** * smack_inode_setsecurity - set smack xattrs * @inode: the object * @name: attribute name * @value: attribute value * @size: size of the attribute * @flags: unused * * Sets the named attribute in the appropriate blob * * Returns 0 on success, or an error code */ static int smack_inode_setsecurity(struct inode *inode, const char *name, const void *value, size_t size, int flags) { char *sp; struct inode_smack *nsp = inode->i_security; struct socket_smack *ssp; struct socket *sock; int rc = 0; if (value == NULL || size > SMK_LABELLEN || size == 0) return -EACCES; sp = smk_import(value, size); if (sp == NULL) return -EINVAL; if (strcmp(name, XATTR_SMACK_SUFFIX) == 0) { nsp->smk_inode = sp; return 0; } /* * The rest of the Smack xattrs are only on sockets. */ if (inode->i_sb->s_magic != SOCKFS_MAGIC) return -EOPNOTSUPP; sock = SOCKET_I(inode); if (sock == NULL || sock->sk == NULL) return -EOPNOTSUPP; ssp = sock->sk->sk_security; if (strcmp(name, XATTR_SMACK_IPIN) == 0) ssp->smk_in = sp; else if (strcmp(name, XATTR_SMACK_IPOUT) == 0) { ssp->smk_out = sp; rc = smack_netlabel(sock->sk, SMACK_CIPSO_SOCKET); if (rc != 0) printk(KERN_WARNING "Smack: \"%s\" netlbl error %d.\n", __func__, -rc); } else return -EOPNOTSUPP; return 0; } /** * smack_socket_post_create - finish socket setup * @sock: the socket * @family: protocol family * @type: unused * @protocol: unused * @kern: unused * * Sets the netlabel information on the socket * * Returns 0 on success, and error code otherwise */ static int smack_socket_post_create(struct socket *sock, int family, int type, int protocol, int kern) { if (family != PF_INET || sock->sk == NULL) return 0; /* * Set the outbound netlbl. */ return smack_netlabel(sock->sk, SMACK_CIPSO_SOCKET); } /** * smack_socket_connect - connect access check * @sock: the socket * @sap: the other end * @addrlen: size of sap * * Verifies that a connection may be possible * * Returns 0 on success, and error code otherwise */ static int smack_socket_connect(struct socket *sock, struct sockaddr *sap, int addrlen) { if (sock->sk == NULL || sock->sk->sk_family != PF_INET) return 0; if (addrlen < sizeof(struct sockaddr_in)) return -EINVAL; return smack_netlabel_send(sock->sk, (struct sockaddr_in *)sap); } /** * smack_flags_to_may - convert S_ to MAY_ values * @flags: the S_ value * * Returns the equivalent MAY_ value */ static int smack_flags_to_may(int flags) { int may = 0; if (flags & S_IRUGO) may |= MAY_READ; if (flags & S_IWUGO) may |= MAY_WRITE; if (flags & S_IXUGO) may |= MAY_EXEC; return may; } /** * smack_msg_msg_alloc_security - Set the security blob for msg_msg * @msg: the object * * Returns 0 */ static int smack_msg_msg_alloc_security(struct msg_msg *msg) { msg->security = current_security(); return 0; } /** * smack_msg_msg_free_security - Clear the security blob for msg_msg * @msg: the object * * Clears the blob pointer */ static void smack_msg_msg_free_security(struct msg_msg *msg) { msg->security = NULL; } /** * smack_of_shm - the smack pointer for the shm * @shp: the object * * Returns a pointer to the smack value */ static char *smack_of_shm(struct shmid_kernel *shp) { return (char *)shp->shm_perm.security; } /** * smack_shm_alloc_security - Set the security blob for shm * @shp: the object * * Returns 0 */ static int smack_shm_alloc_security(struct shmid_kernel *shp) { struct kern_ipc_perm *isp = &shp->shm_perm; isp->security = current_security(); return 0; } /** * smack_shm_free_security - Clear the security blob for shm * @shp: the object * * Clears the blob pointer */ static void smack_shm_free_security(struct shmid_kernel *shp) { struct kern_ipc_perm *isp = &shp->shm_perm; isp->security = NULL; } /** * smack_shm_associate - Smack access check for shm * @shp: the object * @shmflg: access requested * * Returns 0 if current has the requested access, error code otherwise */ static int smack_shm_associate(struct shmid_kernel *shp, int shmflg) { char *ssp = smack_of_shm(shp); int may; may = smack_flags_to_may(shmflg); return smk_curacc(ssp, may); } /** * smack_shm_shmctl - Smack access check for shm * @shp: the object * @cmd: what it wants to do * * Returns 0 if current has the requested access, error code otherwise */ static int smack_shm_shmctl(struct shmid_kernel *shp, int cmd) { char *ssp; int may; switch (cmd) { case IPC_STAT: case SHM_STAT: may = MAY_READ; break; case IPC_SET: case SHM_LOCK: case SHM_UNLOCK: case IPC_RMID: may = MAY_READWRITE; break; case IPC_INFO: case SHM_INFO: /* * System level information. */ return 0; default: return -EINVAL; } ssp = smack_of_shm(shp); return smk_curacc(ssp, may); } /** * smack_shm_shmat - Smack access for shmat * @shp: the object * @shmaddr: unused * @shmflg: access requested * * Returns 0 if current has the requested access, error code otherwise */ static int smack_shm_shmat(struct shmid_kernel *shp, char __user *shmaddr, int shmflg) { char *ssp = smack_of_shm(shp); int may; may = smack_flags_to_may(shmflg); return smk_curacc(ssp, may); } /** * smack_of_sem - the smack pointer for the sem * @sma: the object * * Returns a pointer to the smack value */ static char *smack_of_sem(struct sem_array *sma) { return (char *)sma->sem_perm.security; } /** * smack_sem_alloc_security - Set the security blob for sem * @sma: the object * * Returns 0 */ static int smack_sem_alloc_security(struct sem_array *sma) { struct kern_ipc_perm *isp = &sma->sem_perm; isp->security = current_security(); return 0; } /** * smack_sem_free_security - Clear the security blob for sem * @sma: the object * * Clears the blob pointer */ static void smack_sem_free_security(struct sem_array *sma) { struct kern_ipc_perm *isp = &sma->sem_perm; isp->security = NULL; } /** * smack_sem_associate - Smack access check for sem * @sma: the object * @semflg: access requested * * Returns 0 if current has the requested access, error code otherwise */ static int smack_sem_associate(struct sem_array *sma, int semflg) { char *ssp = smack_of_sem(sma); int may; may = smack_flags_to_may(semflg); return smk_curacc(ssp, may); } /** * smack_sem_shmctl - Smack access check for sem * @sma: the object * @cmd: what it wants to do * * Returns 0 if current has the requested access, error code otherwise */ static int smack_sem_semctl(struct sem_array *sma, int cmd) { char *ssp; int may; switch (cmd) { case GETPID: case GETNCNT: case GETZCNT: case GETVAL: case GETALL: case IPC_STAT: case SEM_STAT: may = MAY_READ; break; case SETVAL: case SETALL: case IPC_RMID: case IPC_SET: may = MAY_READWRITE; break; case IPC_INFO: case SEM_INFO: /* * System level information */ return 0; default: return -EINVAL; } ssp = smack_of_sem(sma); return smk_curacc(ssp, may); } /** * smack_sem_semop - Smack checks of semaphore operations * @sma: the object * @sops: unused * @nsops: unused * @alter: unused * * Treated as read and write in all cases. * * Returns 0 if access is allowed, error code otherwise */ static int smack_sem_semop(struct sem_array *sma, struct sembuf *sops, unsigned nsops, int alter) { char *ssp = smack_of_sem(sma); return smk_curacc(ssp, MAY_READWRITE); } /** * smack_msg_alloc_security - Set the security blob for msg * @msq: the object * * Returns 0 */ static int smack_msg_queue_alloc_security(struct msg_queue *msq) { struct kern_ipc_perm *kisp = &msq->q_perm; kisp->security = current_security(); return 0; } /** * smack_msg_free_security - Clear the security blob for msg * @msq: the object * * Clears the blob pointer */ static void smack_msg_queue_free_security(struct msg_queue *msq) { struct kern_ipc_perm *kisp = &msq->q_perm; kisp->security = NULL; } /** * smack_of_msq - the smack pointer for the msq * @msq: the object * * Returns a pointer to the smack value */ static char *smack_of_msq(struct msg_queue *msq) { return (char *)msq->q_perm.security; } /** * smack_msg_queue_associate - Smack access check for msg_queue * @msq: the object * @msqflg: access requested * * Returns 0 if current has the requested access, error code otherwise */ static int smack_msg_queue_associate(struct msg_queue *msq, int msqflg) { char *msp = smack_of_msq(msq); int may; may = smack_flags_to_may(msqflg); return smk_curacc(msp, may); } /** * smack_msg_queue_msgctl - Smack access check for msg_queue * @msq: the object * @cmd: what it wants to do * * Returns 0 if current has the requested access, error code otherwise */ static int smack_msg_queue_msgctl(struct msg_queue *msq, int cmd) { char *msp; int may; switch (cmd) { case IPC_STAT: case MSG_STAT: may = MAY_READ; break; case IPC_SET: case IPC_RMID: may = MAY_READWRITE; break; case IPC_INFO: case MSG_INFO: /* * System level information */ return 0; default: return -EINVAL; } msp = smack_of_msq(msq); return smk_curacc(msp, may); } /** * smack_msg_queue_msgsnd - Smack access check for msg_queue * @msq: the object * @msg: unused * @msqflg: access requested * * Returns 0 if current has the requested access, error code otherwise */ static int smack_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg) { char *msp = smack_of_msq(msq); int rc; rc = smack_flags_to_may(msqflg); return smk_curacc(msp, rc); } /** * smack_msg_queue_msgsnd - Smack access check for msg_queue * @msq: the object * @msg: unused * @target: unused * @type: unused * @mode: unused * * Returns 0 if current has read and write access, error code otherwise */ static int smack_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg, struct task_struct *target, long type, int mode) { char *msp = smack_of_msq(msq); return smk_curacc(msp, MAY_READWRITE); } /** * smack_ipc_permission - Smack access for ipc_permission() * @ipp: the object permissions * @flag: access requested * * Returns 0 if current has read and write access, error code otherwise */ static int smack_ipc_permission(struct kern_ipc_perm *ipp, short flag) { char *isp = ipp->security; int may; may = smack_flags_to_may(flag); return smk_curacc(isp, may); } /** * smack_ipc_getsecid - Extract smack security id * @ipp: the object permissions * @secid: where result will be saved */ static void smack_ipc_getsecid(struct kern_ipc_perm *ipp, u32 *secid) { char *smack = ipp->security; *secid = smack_to_secid(smack); } /** * smack_d_instantiate - Make sure the blob is correct on an inode * @opt_dentry: unused * @inode: the object * * Set the inode's security blob if it hasn't been done already. */ static void smack_d_instantiate(struct dentry *opt_dentry, struct inode *inode) { struct super_block *sbp; struct superblock_smack *sbsp; struct inode_smack *isp; char *csp = current_security(); char *fetched; char *final; struct dentry *dp; if (inode == NULL) return; isp = inode->i_security; mutex_lock(&isp->smk_lock); /* * If the inode is already instantiated * take the quick way out */ if (isp->smk_flags & SMK_INODE_INSTANT) goto unlockandout; sbp = inode->i_sb; sbsp = sbp->s_security; /* * We're going to use the superblock default label * if there's no label on the file. */ final = sbsp->smk_default; /* * If this is the root inode the superblock * may be in the process of initialization. * If that is the case use the root value out * of the superblock. */ if (opt_dentry->d_parent == opt_dentry) { isp->smk_inode = sbsp->smk_root; isp->smk_flags |= SMK_INODE_INSTANT; goto unlockandout; } /* * This is pretty hackish. * Casey says that we shouldn't have to do * file system specific code, but it does help * with keeping it simple. */ switch (sbp->s_magic) { case SMACK_MAGIC: /* * Casey says that it's a little embarassing * that the smack file system doesn't do * extended attributes. */ final = smack_known_star.smk_known; break; case PIPEFS_MAGIC: /* * Casey says pipes are easy (?) */ final = smack_known_star.smk_known; break; case DEVPTS_SUPER_MAGIC: /* * devpts seems content with the label of the task. * Programs that change smack have to treat the * pty with respect. */ final = csp; break; case SOCKFS_MAGIC: /* * Casey says sockets get the smack of the task. */ final = csp; break; case PROC_SUPER_MAGIC: /* * Casey says procfs appears not to care. * The superblock default suffices. */ break; case TMPFS_MAGIC: /* * Device labels should come from the filesystem, * but watch out, because they're volitile, * getting recreated on every reboot. */ final = smack_known_star.smk_known; /* * No break. * * If a smack value has been set we want to use it, * but since tmpfs isn't giving us the opportunity * to set mount options simulate setting the * superblock default. */ default: /* * This isn't an understood special case. * Get the value from the xattr. * * No xattr support means, alas, no SMACK label. * Use the aforeapplied default. * It would be curious if the label of the task * does not match that assigned. */ if (inode->i_op->getxattr == NULL) break; /* * Get the dentry for xattr. */ if (opt_dentry == NULL) { dp = d_find_alias(inode); if (dp == NULL) break; } else { dp = dget(opt_dentry); if (dp == NULL) break; } fetched = smk_fetch(inode, dp); if (fetched != NULL) final = fetched; dput(dp); break; } if (final == NULL) isp->smk_inode = csp; else isp->smk_inode = final; isp->smk_flags |= SMK_INODE_INSTANT; unlockandout: mutex_unlock(&isp->smk_lock); return; } /** * smack_getprocattr - Smack process attribute access * @p: the object task * @name: the name of the attribute in /proc/.../attr * @value: where to put the result * * Places a copy of the task Smack into value * * Returns the length of the smack label or an error code */ static int smack_getprocattr(struct task_struct *p, char *name, char **value) { char *cp; int slen; if (strcmp(name, "current") != 0) return -EINVAL; cp = kstrdup(task_security(p), GFP_KERNEL); if (cp == NULL) return -ENOMEM; slen = strlen(cp); *value = cp; return slen; } /** * smack_setprocattr - Smack process attribute setting * @p: the object task * @name: the name of the attribute in /proc/.../attr * @value: the value to set * @size: the size of the value * * Sets the Smack value of the task. Only setting self * is permitted and only with privilege * * Returns the length of the smack label or an error code */ static int smack_setprocattr(struct task_struct *p, char *name, void *value, size_t size) { struct cred *new; char *newsmack; /* * Changing another process' Smack value is too dangerous * and supports no sane use case. */ if (p != current) return -EPERM; if (!capable(CAP_MAC_ADMIN)) return -EPERM; if (value == NULL || size == 0 || size >= SMK_LABELLEN) return -EINVAL; if (strcmp(name, "current") != 0) return -EINVAL; newsmack = smk_import(value, size); if (newsmack == NULL) return -EINVAL; /* * No process is ever allowed the web ("@") label. */ if (newsmack == smack_known_web.smk_known) return -EPERM; new = prepare_creds(); if (new == NULL) return -ENOMEM; new->security = newsmack; commit_creds(new); return size; } /** * smack_unix_stream_connect - Smack access on UDS * @sock: one socket * @other: the other socket * @newsk: unused * * Return 0 if a subject with the smack of sock could access * an object with the smack of other, otherwise an error code */ static int smack_unix_stream_connect(struct socket *sock, struct socket *other, struct sock *newsk) { struct inode *sp = SOCK_INODE(sock); struct inode *op = SOCK_INODE(other); return smk_access(smk_of_inode(sp), smk_of_inode(op), MAY_READWRITE); } /** * smack_unix_may_send - Smack access on UDS * @sock: one socket * @other: the other socket * * Return 0 if a subject with the smack of sock could access * an object with the smack of other, otherwise an error code */ static int smack_unix_may_send(struct socket *sock, struct socket *other) { struct inode *sp = SOCK_INODE(sock); struct inode *op = SOCK_INODE(other); return smk_access(smk_of_inode(sp), smk_of_inode(op), MAY_WRITE); } /** * smack_socket_sendmsg - Smack check based on destination host * @sock: the socket * @msg: the message * @size: the size of the message * * Return 0 if the current subject can write to the destination * host. This is only a question if the destination is a single * label host. */ static int smack_socket_sendmsg(struct socket *sock, struct msghdr *msg, int size) { struct sockaddr_in *sip = (struct sockaddr_in *) msg->msg_name; /* * Perfectly reasonable for this to be NULL */ if (sip == NULL || sip->sin_family != PF_INET) return 0; return smack_netlabel_send(sock->sk, sip); } /** * smack_from_secattr - Convert a netlabel attr.mls.lvl/attr.mls.cat pair to smack * @sap: netlabel secattr * @sip: where to put the result * * Copies a smack label into sip */ static void smack_from_secattr(struct netlbl_lsm_secattr *sap, char *sip) { char smack[SMK_LABELLEN]; char *sp; int pcat; if ((sap->flags & NETLBL_SECATTR_MLS_LVL) != 0) { /* * Looks like a CIPSO packet. * If there are flags but no level netlabel isn't * behaving the way we expect it to. * * Get the categories, if any * Without guidance regarding the smack value * for the packet fall back on the network * ambient value. */ memset(smack, '\0', SMK_LABELLEN); if ((sap->flags & NETLBL_SECATTR_MLS_CAT) != 0) for (pcat = -1;;) { pcat = netlbl_secattr_catmap_walk( sap->attr.mls.cat, pcat + 1); if (pcat < 0) break; smack_catset_bit(pcat, smack); } /* * If it is CIPSO using smack direct mapping * we are already done. WeeHee. */ if (sap->attr.mls.lvl == smack_cipso_direct) { memcpy(sip, smack, SMK_MAXLEN); return; } /* * Look it up in the supplied table if it is not * a direct mapping. */ smack_from_cipso(sap->attr.mls.lvl, smack, sip); return; } if ((sap->flags & NETLBL_SECATTR_SECID) != 0) { /* * Looks like a fallback, which gives us a secid. */ sp = smack_from_secid(sap->attr.secid); /* * This has got to be a bug because it is * impossible to specify a fallback without * specifying the label, which will ensure * it has a secid, and the only way to get a * secid is from a fallback. */ BUG_ON(sp == NULL); strncpy(sip, sp, SMK_MAXLEN); return; } /* * Without guidance regarding the smack value * for the packet fall back on the network * ambient value. */ strncpy(sip, smack_net_ambient, SMK_MAXLEN); return; } /** * smack_socket_sock_rcv_skb - Smack packet delivery access check * @sk: socket * @skb: packet * * Returns 0 if the packet should be delivered, an error code otherwise */ static int smack_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct netlbl_lsm_secattr secattr; struct socket_smack *ssp = sk->sk_security; char smack[SMK_LABELLEN]; char *csp; int rc; if (sk->sk_family != PF_INET && sk->sk_family != PF_INET6) return 0; /* * Translate what netlabel gave us. */ netlbl_secattr_init(&secattr); rc = netlbl_skbuff_getattr(skb, sk->sk_family, &secattr); if (rc == 0) { smack_from_secattr(&secattr, smack); csp = smack; } else csp = smack_net_ambient; netlbl_secattr_destroy(&secattr); /* * Receiving a packet requires that the other end * be able to write here. Read access is not required. * This is the simplist possible security model * for networking. */ rc = smk_access(csp, ssp->smk_in, MAY_WRITE); if (rc != 0) netlbl_skbuff_err(skb, rc, 0); return rc; } /** * smack_socket_getpeersec_stream - pull in packet label * @sock: the socket * @optval: user's destination * @optlen: size thereof * @len: max thereof * * returns zero on success, an error code otherwise */ static int smack_socket_getpeersec_stream(struct socket *sock, char __user *optval, int __user *optlen, unsigned len) { struct socket_smack *ssp; int slen; int rc = 0; ssp = sock->sk->sk_security; slen = strlen(ssp->smk_packet) + 1; if (slen > len) rc = -ERANGE; else if (copy_to_user(optval, ssp->smk_packet, slen) != 0) rc = -EFAULT; if (put_user(slen, optlen) != 0) rc = -EFAULT; return rc; } /** * smack_socket_getpeersec_dgram - pull in packet label * @sock: the socket * @skb: packet data * @secid: pointer to where to put the secid of the packet * * Sets the netlabel socket state on sk from parent */ static int smack_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid) { struct netlbl_lsm_secattr secattr; struct sock *sk; char smack[SMK_LABELLEN]; int family = PF_INET; u32 s; int rc; /* * Only works for families with packets. */ if (sock != NULL) { sk = sock->sk; if (sk->sk_family != PF_INET && sk->sk_family != PF_INET6) return 0; family = sk->sk_family; } /* * Translate what netlabel gave us. */ netlbl_secattr_init(&secattr); rc = netlbl_skbuff_getattr(skb, family, &secattr); if (rc == 0) smack_from_secattr(&secattr, smack); netlbl_secattr_destroy(&secattr); /* * Give up if we couldn't get anything */ if (rc != 0) return rc; s = smack_to_secid(smack); if (s == 0) return -EINVAL; *secid = s; return 0; } /** * smack_sock_graft - Initialize a newly created socket with an existing sock * @sk: child sock * @parent: parent socket * * Set the smk_{in,out} state of an existing sock based on the process that * is creating the new socket. */ static void smack_sock_graft(struct sock *sk, struct socket *parent) { struct socket_smack *ssp; if (sk == NULL || (sk->sk_family != PF_INET && sk->sk_family != PF_INET6)) return; ssp = sk->sk_security; ssp->smk_in = ssp->smk_out = current_security(); /* cssp->smk_packet is already set in smack_inet_csk_clone() */ } /** * smack_inet_conn_request - Smack access check on connect * @sk: socket involved * @skb: packet * @req: unused * * Returns 0 if a task with the packet label could write to * the socket, otherwise an error code */ static int smack_inet_conn_request(struct sock *sk, struct sk_buff *skb, struct request_sock *req) { u16 family = sk->sk_family; struct socket_smack *ssp = sk->sk_security; struct netlbl_lsm_secattr secattr; struct sockaddr_in addr; struct iphdr *hdr; char smack[SMK_LABELLEN]; int rc; /* handle mapped IPv4 packets arriving via IPv6 sockets */ if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP)) family = PF_INET; netlbl_secattr_init(&secattr); rc = netlbl_skbuff_getattr(skb, family, &secattr); if (rc == 0) smack_from_secattr(&secattr, smack); else strncpy(smack, smack_known_huh.smk_known, SMK_MAXLEN); netlbl_secattr_destroy(&secattr); /* * Receiving a packet requires that the other end be able to write * here. Read access is not required. */ rc = smk_access(smack, ssp->smk_in, MAY_WRITE); if (rc != 0) return rc; /* * Save the peer's label in the request_sock so we can later setup * smk_packet in the child socket so that SO_PEERCRED can report it. */ req->peer_secid = smack_to_secid(smack); /* * We need to decide if we want to label the incoming connection here * if we do we only need to label the request_sock and the stack will * propogate the wire-label to the sock when it is created. */ hdr = ip_hdr(skb); addr.sin_addr.s_addr = hdr->saddr; rcu_read_lock(); if (smack_host_label(&addr) == NULL) { rcu_read_unlock(); netlbl_secattr_init(&secattr); smack_to_secattr(smack, &secattr); rc = netlbl_req_setattr(req, &secattr); netlbl_secattr_destroy(&secattr); } else { rcu_read_unlock(); netlbl_req_delattr(req); } return rc; } /** * smack_inet_csk_clone - Copy the connection information to the new socket * @sk: the new socket * @req: the connection's request_sock * * Transfer the connection's peer label to the newly created socket. */ static void smack_inet_csk_clone(struct sock *sk, const struct request_sock *req) { struct socket_smack *ssp = sk->sk_security; char *smack; if (req->peer_secid != 0) { smack = smack_from_secid(req->peer_secid); strncpy(ssp->smk_packet, smack, SMK_MAXLEN); } else ssp->smk_packet[0] = '\0'; } /* * Key management security hooks * * Casey has not tested key support very heavily. * The permission check is most likely too restrictive. * If you care about keys please have a look. */ #ifdef CONFIG_KEYS /** * smack_key_alloc - Set the key security blob * @key: object * @cred: the credentials to use * @flags: unused * * No allocation required * * Returns 0 */ static int smack_key_alloc(struct key *key, const struct cred *cred, unsigned long flags) { key->security = cred->security; return 0; } /** * smack_key_free - Clear the key security blob * @key: the object * * Clear the blob pointer */ static void smack_key_free(struct key *key) { key->security = NULL; } /* * smack_key_permission - Smack access on a key * @key_ref: gets to the object * @cred: the credentials to use * @perm: unused * * Return 0 if the task has read and write to the object, * an error code otherwise */ static int smack_key_permission(key_ref_t key_ref, const struct cred *cred, key_perm_t perm) { struct key *keyp; keyp = key_ref_to_ptr(key_ref); if (keyp == NULL) return -EINVAL; /* * If the key hasn't been initialized give it access so that * it may do so. */ if (keyp->security == NULL) return 0; /* * This should not occur */ if (cred->security == NULL) return -EACCES; return smk_access(cred->security, keyp->security, MAY_READWRITE); } #endif /* CONFIG_KEYS */ /* * Smack Audit hooks * * Audit requires a unique representation of each Smack specific * rule. This unique representation is used to distinguish the * object to be audited from remaining kernel objects and also * works as a glue between the audit hooks. * * Since repository entries are added but never deleted, we'll use * the smack_known label address related to the given audit rule as * the needed unique representation. This also better fits the smack * model where nearly everything is a label. */ #ifdef CONFIG_AUDIT /** * smack_audit_rule_init - Initialize a smack audit rule * @field: audit rule fields given from user-space (audit.h) * @op: required testing operator (=, !=, >, <, ...) * @rulestr: smack label to be audited * @vrule: pointer to save our own audit rule representation * * Prepare to audit cases where (@field @op @rulestr) is true. * The label to be audited is created if necessay. */ static int smack_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule) { char **rule = (char **)vrule; *rule = NULL; if (field != AUDIT_SUBJ_USER && field != AUDIT_OBJ_USER) return -EINVAL; if (op != Audit_equal && op != Audit_not_equal) return -EINVAL; *rule = smk_import(rulestr, 0); return 0; } /** * smack_audit_rule_known - Distinguish Smack audit rules * @krule: rule of interest, in Audit kernel representation format * * This is used to filter Smack rules from remaining Audit ones. * If it's proved that this rule belongs to us, the * audit_rule_match hook will be called to do the final judgement. */ static int smack_audit_rule_known(struct audit_krule *krule) { struct audit_field *f; int i; for (i = 0; i < krule->field_count; i++) { f = &krule->fields[i]; if (f->type == AUDIT_SUBJ_USER || f->type == AUDIT_OBJ_USER) return 1; } return 0; } /** * smack_audit_rule_match - Audit given object ? * @secid: security id for identifying the object to test * @field: audit rule flags given from user-space * @op: required testing operator * @vrule: smack internal rule presentation * @actx: audit context associated with the check * * The core Audit hook. It's used to take the decision of * whether to audit or not to audit a given object. */ static int smack_audit_rule_match(u32 secid, u32 field, u32 op, void *vrule, struct audit_context *actx) { char *smack; char *rule = vrule; if (!rule) { audit_log(actx, GFP_KERNEL, AUDIT_SELINUX_ERR, "Smack: missing rule\n"); return -ENOENT; } if (field != AUDIT_SUBJ_USER && field != AUDIT_OBJ_USER) return 0; smack = smack_from_secid(secid); /* * No need to do string comparisons. If a match occurs, * both pointers will point to the same smack_known * label. */ if (op == Audit_equal) return (rule == smack); if (op == Audit_not_equal) return (rule != smack); return 0; } /** * smack_audit_rule_free - free smack rule representation * @vrule: rule to be freed. * * No memory was allocated. */ static void smack_audit_rule_free(void *vrule) { /* No-op */ } #endif /* CONFIG_AUDIT */ /** * smack_secid_to_secctx - return the smack label for a secid * @secid: incoming integer * @secdata: destination * @seclen: how long it is * * Exists for networking code. */ static int smack_secid_to_secctx(u32 secid, char **secdata, u32 *seclen) { char *sp = smack_from_secid(secid); *secdata = sp; *seclen = strlen(sp); return 0; } /** * smack_secctx_to_secid - return the secid for a smack label * @secdata: smack label * @seclen: how long result is * @secid: outgoing integer * * Exists for audit and networking code. */ static int smack_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid) { *secid = smack_to_secid(secdata); return 0; } /** * smack_release_secctx - don't do anything. * @secdata: unused * @seclen: unused * * Exists to make sure nothing gets done, and properly */ static void smack_release_secctx(char *secdata, u32 seclen) { } struct security_operations smack_ops = { .name = "smack", .ptrace_may_access = smack_ptrace_may_access, .ptrace_traceme = smack_ptrace_traceme, .capget = cap_capget, .capset = cap_capset, .capable = cap_capable, .syslog = smack_syslog, .settime = cap_settime, .vm_enough_memory = cap_vm_enough_memory, .bprm_set_creds = cap_bprm_set_creds, .bprm_secureexec = cap_bprm_secureexec, .sb_alloc_security = smack_sb_alloc_security, .sb_free_security = smack_sb_free_security, .sb_copy_data = smack_sb_copy_data, .sb_kern_mount = smack_sb_kern_mount, .sb_statfs = smack_sb_statfs, .sb_mount = smack_sb_mount, .sb_umount = smack_sb_umount, .inode_alloc_security = smack_inode_alloc_security, .inode_free_security = smack_inode_free_security, .inode_init_security = smack_inode_init_security, .inode_link = smack_inode_link, .inode_unlink = smack_inode_unlink, .inode_rmdir = smack_inode_rmdir, .inode_rename = smack_inode_rename, .inode_permission = smack_inode_permission, .inode_setattr = smack_inode_setattr, .inode_getattr = smack_inode_getattr, .inode_setxattr = smack_inode_setxattr, .inode_post_setxattr = smack_inode_post_setxattr, .inode_getxattr = smack_inode_getxattr, .inode_removexattr = smack_inode_removexattr, .inode_need_killpriv = cap_inode_need_killpriv, .inode_killpriv = cap_inode_killpriv, .inode_getsecurity = smack_inode_getsecurity, .inode_setsecurity = smack_inode_setsecurity, .inode_listsecurity = smack_inode_listsecurity, .inode_getsecid = smack_inode_getsecid, .file_permission = smack_file_permission, .file_alloc_security = smack_file_alloc_security, .file_free_security = smack_file_free_security, .file_ioctl = smack_file_ioctl, .file_lock = smack_file_lock, .file_fcntl = smack_file_fcntl, .file_set_fowner = smack_file_set_fowner, .file_send_sigiotask = smack_file_send_sigiotask, .file_receive = smack_file_receive, .cred_free = smack_cred_free, .cred_prepare = smack_cred_prepare, .cred_commit = smack_cred_commit, .kernel_act_as = smack_kernel_act_as, .kernel_create_files_as = smack_kernel_create_files_as, .task_fix_setuid = cap_task_fix_setuid, .task_setpgid = smack_task_setpgid, .task_getpgid = smack_task_getpgid, .task_getsid = smack_task_getsid, .task_getsecid = smack_task_getsecid, .task_setnice = smack_task_setnice, .task_setioprio = smack_task_setioprio, .task_getioprio = smack_task_getioprio, .task_setscheduler = smack_task_setscheduler, .task_getscheduler = smack_task_getscheduler, .task_movememory = smack_task_movememory, .task_kill = smack_task_kill, .task_wait = smack_task_wait, .task_to_inode = smack_task_to_inode, .task_prctl = cap_task_prctl, .ipc_permission = smack_ipc_permission, .ipc_getsecid = smack_ipc_getsecid, .msg_msg_alloc_security = smack_msg_msg_alloc_security, .msg_msg_free_security = smack_msg_msg_free_security, .msg_queue_alloc_security = smack_msg_queue_alloc_security, .msg_queue_free_security = smack_msg_queue_free_security, .msg_queue_associate = smack_msg_queue_associate, .msg_queue_msgctl = smack_msg_queue_msgctl, .msg_queue_msgsnd = smack_msg_queue_msgsnd, .msg_queue_msgrcv = smack_msg_queue_msgrcv, .shm_alloc_security = smack_shm_alloc_security, .shm_free_security = smack_shm_free_security, .shm_associate = smack_shm_associate, .shm_shmctl = smack_shm_shmctl, .shm_shmat = smack_shm_shmat, .sem_alloc_security = smack_sem_alloc_security, .sem_free_security = smack_sem_free_security, .sem_associate = smack_sem_associate, .sem_semctl = smack_sem_semctl, .sem_semop = smack_sem_semop, .netlink_send = cap_netlink_send, .netlink_recv = cap_netlink_recv, .d_instantiate = smack_d_instantiate, .getprocattr = smack_getprocattr, .setprocattr = smack_setprocattr, .unix_stream_connect = smack_unix_stream_connect, .unix_may_send = smack_unix_may_send, .socket_post_create = smack_socket_post_create, .socket_connect = smack_socket_connect, .socket_sendmsg = smack_socket_sendmsg, .socket_sock_rcv_skb = smack_socket_sock_rcv_skb, .socket_getpeersec_stream = smack_socket_getpeersec_stream, .socket_getpeersec_dgram = smack_socket_getpeersec_dgram, .sk_alloc_security = smack_sk_alloc_security, .sk_free_security = smack_sk_free_security, .sock_graft = smack_sock_graft, .inet_conn_request = smack_inet_conn_request, .inet_csk_clone = smack_inet_csk_clone, /* key management security hooks */ #ifdef CONFIG_KEYS .key_alloc = smack_key_alloc, .key_free = smack_key_free, .key_permission = smack_key_permission, #endif /* CONFIG_KEYS */ /* Audit hooks */ #ifdef CONFIG_AUDIT .audit_rule_init = smack_audit_rule_init, .audit_rule_known = smack_audit_rule_known, .audit_rule_match = smack_audit_rule_match, .audit_rule_free = smack_audit_rule_free, #endif /* CONFIG_AUDIT */ .secid_to_secctx = smack_secid_to_secctx, .secctx_to_secid = smack_secctx_to_secid, .release_secctx = smack_release_secctx, }; static __init void init_smack_know_list(void) { list_add(&smack_known_huh.list, &smack_known_list); list_add(&smack_known_hat.list, &smack_known_list); list_add(&smack_known_star.list, &smack_known_list); list_add(&smack_known_floor.list, &smack_known_list); list_add(&smack_known_invalid.list, &smack_known_list); list_add(&smack_known_web.list, &smack_known_list); } /** * smack_init - initialize the smack system * * Returns 0 */ static __init int smack_init(void) { struct cred *cred; if (!security_module_enable(&smack_ops)) return 0; printk(KERN_INFO "Smack: Initializing.\n"); /* * Set the security state for the initial task. */ cred = (struct cred *) current->cred; cred->security = &smack_known_floor.smk_known; /* initilize the smack_know_list */ init_smack_know_list(); /* * Initialize locks */ spin_lock_init(&smack_known_huh.smk_cipsolock); spin_lock_init(&smack_known_hat.smk_cipsolock); spin_lock_init(&smack_known_star.smk_cipsolock); spin_lock_init(&smack_known_floor.smk_cipsolock); spin_lock_init(&smack_known_invalid.smk_cipsolock); /* * Register with LSM */ if (register_security(&smack_ops)) panic("smack: Unable to register with kernel.\n"); return 0; } /* * Smack requires early initialization in order to label * all processes and objects when they are created. */ security_initcall(smack_init);
pichina/linux-bcache
security/smack/smack_lsm.c
C
gpl-2.0
70,465
/* * Copyright (C) 2005-2018 Team Kodi * This file is part of Kodi - https://kodi.tv * * SPDX-License-Identifier: GPL-2.0-or-later * See LICENSES/README.md for more information. */ #pragma once #include "IDirectory.h" #include "addons/AddonManager.h" class CURL; typedef std::shared_ptr<CFileItem> CFileItemPtr; namespace XFILE { /*! \ingroup windows \brief Get access to shares and it's directories. */ class CAddonsDirectory : public IDirectory { public: CAddonsDirectory(void); ~CAddonsDirectory(void) override; bool GetDirectory(const CURL& url, CFileItemList &items) override; bool Create(const CURL& url) override { return true; } bool Exists(const CURL& url) override { return true; } bool AllowAll() const override { return true; } /*! \brief Fetch script and plugin addons of a given content type \param content the content type to fetch \param addons the list of addons to fill with scripts and plugin content \return true if content is valid, false if it's invalid. */ static bool GetScriptsAndPlugins(const std::string &content, ADDON::VECADDONS &addons); /*! \brief Fetch scripts and plugins of a given content type \param content the content type to fetch \param items the list to fill with scripts and content \return true if more than one item is found, false otherwise. */ static bool GetScriptsAndPlugins(const std::string &content, CFileItemList &items); static void GenerateAddonListing(const CURL &path, const ADDON::VECADDONS& addons, CFileItemList &items, const std::string label); static CFileItemPtr FileItemFromAddon(const ADDON::AddonPtr &addon, const std::string& path, bool folder = false); /*! \brief Returns true if `path` is a path or subpath of the repository directory, otherwise false */ static bool IsRepoDirectory(const CURL& path); private: bool GetSearchResults(const CURL& path, CFileItemList &items); }; }
anthonyryan1/xbmc
xbmc/filesystem/AddonsDirectory.h
C
gpl-2.0
1,985
# # Copyright (C) 2014 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require File.expand_path(File.dirname(__FILE__) + '/../spec_helper.rb') require 'db/migrate/20141217222534_cleanup_duplicate_external_feeds' describe 'CleanupDuplicateExternalFeeds' do before do @migration = CleanupDuplicateExternalFeeds.new @migration.down end it "should find duplicates" do c1 = course_model feeds = 3.times.map { external_feed_model({}, false) } feeds.each{ |f| f.save(validate: false) } feeds[2].update_attribute(:url, "http://another-non-default-place.com") c2 = course_model feeds << external_feed_model expect(ExternalFeed.where(id: feeds).count).to eq 4 @migration.up expect(ExternalFeed.where(id: [feeds[0], feeds[2], feeds[3]]).count).to eq 3 expect(ExternalFeed.where(id: feeds[1]).count).to eq 0 end it "should cleanup associated entries and announcements of duplicates" do course_with_teacher @context = @course feeds = 2.times.map { external_feed_model({}, false) } feeds.each{ |f| f.save(validate: false) } entries = feeds.map do |feed| feed.external_feed_entries.create!( :user => @teacher, :title => 'blah', :message => 'blah', :workflow_state => :active ) end announcements = feeds.map do |feed| a = announcement_model a.update_attribute(:external_feed_id, feed.id) a end @migration.up expect(ExternalFeed.where(id: feeds[0]).count).to eq 1 expect(ExternalFeedEntry.where(id: entries[0]).count).to eq 1 expect(announcements[0].reload.external_feed_id).to eq feeds[0].id expect(ExternalFeed.where(id: feeds[1]).count).to eq 0 expect(ExternalFeedEntry.where(id: entries[1]).count).to eq 0 expect(announcements[1].reload.external_feed_id).to eq feeds[0].id end it "sets a default for any NULL verbosity field" do course = course_model feed = external_feed_model ExternalFeed.where(id: feed).update_all(verbosity: nil) @migration.up expect(feed.reload.verbosity).to eq 'full' end end
Rvor/canvas-lms
spec/migrations/cleanup_duplicate_external_feeds_spec.rb
Ruby
agpl-3.0
2,707
/* * Copyright (c) 2015, 张涛. * * 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.kymjs.blog.ui.widget; import java.io.File; import java.io.IOException; import org.kymjs.blog.AppConfig; import org.kymjs.blog.R; import org.kymjs.kjframe.ui.KJActivityStack; import org.kymjs.kjframe.ui.ViewInject; import org.kymjs.kjframe.utils.FileUtils; import org.kymjs.kjframe.utils.StringUtils; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.widget.TextView; /** * * {@link #RecordButton}需要的工具类 * * @author kymjs (http://www.kymjs.com/) * */ public class RecordButtonUtil { private final static String TAG = "AudioUtil"; public static final String AUDOI_DIR = FileUtils.getSDCardPath() + File.separator + AppConfig.audioPath; // 录音音频保存根路径 private String mAudioPath; // 要播放的声音的路径 private boolean mIsRecording;// 是否正在录音 private boolean mIsPlaying;// 是否正在播放 private MediaRecorder mRecorder; private MediaPlayer mPlayer; private OnPlayListener listener; public boolean isPlaying() { return mIsPlaying; } /** * 设置要播放的声音的路径 * * @param path */ public void setAudioPath(String path) { this.mAudioPath = path; } /** * 播放声音结束时调用 * * @param l */ public void setOnPlayListener(OnPlayListener l) { this.listener = l; } // 初始化 录音器 private void initRecorder() { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mRecorder.setOutputFile(mAudioPath); mIsRecording = true; } /** * 开始录音,并保存到文件中 */ public void recordAudio() { initRecorder(); try { mRecorder.prepare(); mRecorder.start(); } catch (IOException e) { ViewInject.toast("小屁孩不听你说话了,请返回重试"); } } /** * 获取音量值,只是针对录音音量 * * @return */ public int getVolumn() { int volumn = 0; // 录音 if (mRecorder != null && mIsRecording) { volumn = mRecorder.getMaxAmplitude(); if (volumn != 0) volumn = (int) (10 * Math.log(volumn) / Math.log(10)) / 5; } return volumn; } /** * 停止录音 */ public void stopRecord() { if (mRecorder != null) { mRecorder.stop(); mRecorder.release(); mRecorder = null; mIsRecording = false; } } public void stopPlay() { if (mPlayer != null) { mPlayer.stop(); mPlayer.release(); mPlayer = null; mIsPlaying = false; if (listener != null) { listener.stopPlay(); } } } public void startPlay(String audioPath, TextView timeView) { if (!mIsPlaying) { if (!StringUtils.isEmpty(audioPath)) { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(audioPath); mPlayer.prepare(); if (timeView != null) { int len = (mPlayer.getDuration() + 500) / 1000; timeView.setText(len + "s"); } mPlayer.start(); if (listener != null) { listener.starPlay(); } mIsPlaying = true; mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopPlay(); } }); } catch (Exception e) { e.printStackTrace(); } } else { ViewInject.toast(KJActivityStack.create().topActivity() .getString(R.string.record_sound_notfound)); } } else { stopPlay(); } // end playing } /** * 开始播放 */ public void startPlay() { startPlay(mAudioPath, null); } public interface OnPlayListener { /** * 播放声音结束时调用 */ void stopPlay(); /** * 播放声音开始时调用 */ void starPlay(); } }
supercwn/KJFrameForAndroid
KJFrame/app/src/main/java/org/kymjs/blog/ui/widget/RecordButtonUtil.java
Java
apache-2.0
5,318
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.trans.steps.salesforce; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.mockito.Mockito; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.mock.StepMockHelper; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class SalesforceStepTest { @ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment(); private StepMockHelper<SalesforceStepMeta, SalesforceStepData> smh; @BeforeClass public static void setUpBeforeClass() throws KettleException { KettleEnvironment.init( false ); } @Before public void setUp() throws KettleException { smh = new StepMockHelper<SalesforceStepMeta, SalesforceStepData>( "Salesforce", SalesforceStepMeta.class, SalesforceStepData.class ); when( smh.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenReturn( smh.logChannelInterface ); when( smh.trans.isRunning() ).thenReturn( true ); } @After public void cleanUp() { smh.cleanUp(); } @Test public void testErrorHandling() { SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS ); assertFalse( meta.supportsErrorHandling() ); } @Test public void testInitDispose() { SalesforceStepMeta meta = mock( SalesforceStepMeta.class, Mockito.CALLS_REAL_METHODS ); SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); /* * Salesforce Step should fail if username and password are not set * We should not set a default account for all users */ meta.setDefault(); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setTargetURL( null ); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setUsername( "anonymous" ); assertFalse( step.init( meta, smh.stepDataInterface ) ); meta.setDefault(); meta.setUsername( "anonymous" ); meta.setPassword( "myPwd" ); meta.setModule( null ); assertFalse( step.init( meta, smh.stepDataInterface ) ); /* * After setting username and password, we should have enough defaults to properly init */ meta.setDefault(); meta.setUsername( "anonymous" ); meta.setPassword( "myPwd" ); assertTrue( step.init( meta, smh.stepDataInterface ) ); // Dispose check assertNotNull( smh.stepDataInterface.connection ); step.dispose( meta, smh.stepDataInterface ); assertNull( smh.stepDataInterface.connection ); } class MockSalesforceStep extends SalesforceStep { public MockSalesforceStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } } @Test public void createIntObjectTest() throws KettleValueException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); Mockito.when( valueMeta.getType() ).thenReturn( ValueMetaInterface.TYPE_INTEGER ); Object value = step.normalizeValue( valueMeta, 100L ); Assert.assertTrue( value instanceof Integer ); } @Test public void createDateObjectTest() throws KettleValueException, ParseException { SalesforceStep step = spy( new MockSalesforceStep( smh.stepMeta, smh.stepDataInterface, 0, smh.transMeta, smh.trans ) ); ValueMetaInterface valueMeta = Mockito.mock( ValueMetaInterface.class ); DateFormat dateFormat = new SimpleDateFormat( "dd-MM-yyyy hh:mm:ss" ); Date date = dateFormat.parse( "12-10-2017 15:10:25" ); Mockito.when( valueMeta.isDate() ).thenReturn( true ); Mockito.when( valueMeta.getDateFormatTimeZone() ).thenReturn( TimeZone.getTimeZone( "UTC" ) ); Mockito.when( valueMeta.getDate( Mockito.eq( date ) ) ).thenReturn( date ); Object value = step.normalizeValue( valueMeta, date ); Assert.assertTrue( value instanceof Calendar ); DateFormat minutesDateFormat = new SimpleDateFormat( "mm:ss" ); //check not missing minutes and seconds Assert.assertEquals( minutesDateFormat.format( date ), minutesDateFormat.format( ( (Calendar) value ).getTime() ) ); } }
tkafalas/pentaho-kettle
plugins/salesforce/core/src/test/java/org/pentaho/di/trans/steps/salesforce/SalesforceStepTest.java
Java
apache-2.0
6,334
/** * Copyright 2015 IBM Corp. * * 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. **/ var express = require("express"); var util = require("util"); var path = require("path"); var fs = require("fs"); var clone = require("clone"); var defaultContext = { page: { title: "Node-RED", favicon: "favicon.ico" }, header: { title: "Node-RED", image: "red/images/node-red.png" }, asset: { red: (process.env.NODE_ENV == "development")? "red/red.js":"red/red.min.js" } }; var themeContext = clone(defaultContext); var themeSettings = null; function serveFile(app,baseUrl,file) { try { var stats = fs.statSync(file); var url = baseUrl+path.basename(file); //console.log(url,"->",file); app.get(url,function(req, res) { res.sendfile(file); }); return "theme"+url; } catch(err) { //TODO: log filenotfound return null; } } module.exports = { init: function(settings) { var i; var url; themeContext = clone(defaultContext); themeSettings = null; if (settings.editorTheme) { var theme = settings.editorTheme; themeSettings = {}; var themeApp = express(); if (theme.page) { if (theme.page.css) { var styles = theme.page.css; if (!util.isArray(styles)) { styles = [styles]; } themeContext.page.css = []; for (i=0;i<styles.length;i++) { url = serveFile(themeApp,"/css/",styles[i]); if (url) { themeContext.page.css.push(url); } } } if (theme.page.favicon) { url = serveFile(themeApp,"/favicon/",theme.page.favicon) if (url) { themeContext.page.favicon = url; } } themeContext.page.title = theme.page.title || themeContext.page.title; } if (theme.header) { themeContext.header.title = theme.header.title || themeContext.header.title; if (theme.header.hasOwnProperty("url")) { themeContext.header.url = theme.header.url; } if (theme.header.hasOwnProperty("image")) { if (theme.header.image) { url = serveFile(themeApp,"/header/",theme.header.image); if (url) { themeContext.header.image = url; } } else { themeContext.header.image = null; } } } if (theme.deployButton) { if (theme.deployButton.type == "simple") { themeSettings.deployButton = { type: "simple" } if (theme.deployButton.label) { themeSettings.deployButton.label = theme.deployButton.label; } if (theme.deployButton.icon) { url = serveFile(themeApp,"/deploy/",theme.deployButton.icon); if (url) { themeSettings.deployButton.icon = url; } } } } if (theme.hasOwnProperty("userMenu")) { themeSettings.userMenu = theme.userMenu; } if (theme.login) { if (theme.login.image) { url = serveFile(themeApp,"/login/",theme.login.image); if (url) { themeContext.login = { image: url } } } } if (theme.hasOwnProperty("menu")) { themeSettings.menu = theme.menu; } return themeApp; } }, context: function() { return themeContext; }, settings: function() { return themeSettings; } }
mikestebbins/node-red
red/api/theme.js
JavaScript
apache-2.0
5,062
/** ****************************************************************************** * @file stm32l1xx_hal_tim_ex.c * @author MCD Application Team * @brief TIM HAL module driver. * This file provides firmware functions to manage the following * functionalities of the Timer extension peripheral: * + Time Master and Slave synchronization configuration * + Timer remapping capabilities configuration @verbatim ============================================================================== ##### TIMER Extended features ##### ============================================================================== [..] The Timer Extension features include: (#) Synchronization circuit to control the timer with external signals and to interconnect several timers together. (#) Timer remapping capabilities configuration @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * 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 STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_hal.h" /** @addtogroup STM32L1xx_HAL_Driver * @{ */ /** @defgroup TIMEx TIMEx * @brief TIM Extended HAL module driver * @{ */ #ifdef HAL_TIM_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions ---------------------------------------------------------*/ /** @defgroup TIMEx_Exported_Functions TIMEx Exported Functions * @{ */ /** @defgroup TIMEx_Exported_Functions_Group1 Peripheral Control functions * @brief Peripheral Control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This section provides functions allowing to: (+)Configure Master synchronization. (+) Configure timer remapping capabilities. @endverbatim * @{ */ /** * @brief Configures the TIM in master mode. * @param htim: TIM handle. * @param sMasterConfig: pointer to a TIM_MasterConfigTypeDef structure that * contains the selected trigger output (TRGO) and the Master/Slave * mode. * @retval HAL status */ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig) { /* Check the parameters */ assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance)); assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger)); assert_param(IS_TIM_MSM_STATE(sMasterConfig->MasterSlaveMode)); __HAL_LOCK(htim); htim->State = HAL_TIM_STATE_BUSY; /* Reset the MMS Bits */ htim->Instance->CR2 &= ~TIM_CR2_MMS; /* Select the TRGO source */ htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger; /* Reset the MSM Bit */ htim->Instance->SMCR &= ~TIM_SMCR_MSM; /* Set or Reset the MSM Bit */ htim->Instance->SMCR |= sMasterConfig->MasterSlaveMode; htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @brief Configures the TIM2/TIM3/TIM9/TIM10/TIM11 Remapping input capabilities. * @param htim: TIM handle. * @param Remap: specifies the TIM remapping source. * This parameter is a combination of the following values depending on TIM instance. * @retval HAL status * * @note For TIM2, the parameter can have the following values: * @arg TIM_TIM2_ITR1_TIM10_OC: TIM2 ITR1 input is connected to TIM10 OC * @arg TIM_TIM2_ITR1_TIM5_TGO: TIM2 ITR1 input is connected to TIM5 TGO * * @note For TIM3, the parameter can have the following values: * @arg TIM_TIM3_ITR2_TIM11_OC: TIM3 ITR2 input is connected to TIM11 OC * @arg TIM_TIM3_ITR2_TIM5_TGO: TIM3 ITR2 input is connected to TIM5 TGO * * @note For TIM9, the parameter is a combination of 2 fields (field1 | field2): * @note For TIM9, the field1 can have the following values: * @arg TIM_TIM9_ITR1_TIM3_TGO: TIM9 ITR1 input is connected to TIM3 TGO * @arg TIM_TIM9_ITR1_TS: TIM9 ITR1 input is connected to touch sensing I/O * @note For TIM9, the field2 can have the following values: * @arg TIM_TIM9_GPIO: TIM9 Channel1 is connected to GPIO * @arg TIM_TIM9_LSE: TIM9 Channel1 is connected to LSE internal clock * @arg TIM_TIM9_GPIO1: TIM9 Channel1 is connected to GPIO * @arg TIM_TIM9_GPIO2: TIM9 Channel1 is connected to GPIO * * @note For TIM10, the parameter is a combination of 3 fields (field1 | field2 | field3): * @note For TIM10, the field1 can have the following values: * @arg TIM_TIM10_TI1RMP: TIM10 Channel 1 depends on TI1_RMP * @arg TIM_TIM10_RI: TIM10 Channel 1 is connected to RI * @note For TIM10, the field2 can have the following values: * @arg TIM_TIM10_ETR_LSE: TIM10 ETR input is connected to LSE clock * @arg TIM_TIM10_ETR_TIM9_TGO: TIM10 ETR input is connected to TIM9 TGO * @note For TIM10, the field3 can have the following values: * @arg TIM_TIM10_GPIO: TIM10 Channel1 is connected to GPIO * @arg TIM_TIM10_LSI: TIM10 Channel1 is connected to LSI internal clock * @arg TIM_TIM10_LSE: TIM10 Channel1 is connected to LSE internal clock * @arg TIM_TIM10_RTC: TIM10 Channel1 is connected to RTC wakeup interrupt * * @note For TIM11, the parameter is a combination of 3 fields (field1 | field2 | field3): * @note For TIM11, the field1 can have the following values: * @arg TIM_TIM11_TI1RMP: TIM11 Channel 1 depends on TI1_RMP * @arg TIM_TIM11_RI: TIM11 Channel 1 is connected to RI * @note For TIM11, the field2 can have the following values: * @arg TIM_TIM11_ETR_LSE: TIM11 ETR input is connected to LSE clock * @arg TIM_TIM11_ETR_TIM9_TGO: TIM11 ETR input is connected to TIM9 TGO * @note For TIM11, the field3 can have the following values: * @arg TIM_TIM11_GPIO: TIM11 Channel1 is connected to GPIO * @arg TIM_TIM11_MSI: TIM11 Channel1 is connected to MSI internal clock * @arg TIM_TIM11_HSE_RTC: TIM11 Channel1 is connected to HSE_RTC clock * @arg TIM_TIM11_GPIO1: TIM11 Channel1 is connected to GPIO * */ HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) { __HAL_LOCK(htim); /* Check parameters */ assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); assert_param(IS_TIM_REMAP(htim->Instance,Remap)); /* Set the Timer remapping configuration */ htim->Instance->OR = Remap; htim->State = HAL_TIM_STATE_READY; __HAL_UNLOCK(htim); return HAL_OK; } /** * @} */ #endif /* HAL_TIM_MODULE_ENABLED */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mbedmicro/mbed
targets/TARGET_STM/TARGET_STM32L1/device/stm32l1xx_hal_tim_ex.c
C
apache-2.0
9,388
#include "test_db_base.h" #include <cppcms/json.h> test_db_base::test_db_base(cppcms::service &srv) : cppcms::application(srv) { db_connection_str = settings().get<std::string>("app.db_connection_string"); } void test_db_base::init() { sql.open(db_connection_str); } void test_db_base::clear() { sql.close(); }
actframework/FrameworkBenchmarks
frameworks/C++/cppcms/src/test_db_base.cpp
C++
bsd-3-clause
326
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Autoloader and dependency injection initialization for Swift Mailer. */ //Load Swift utility class require_once dirname(__FILE__) . '/Swift.php'; //Start the autoloader Swift::registerAutoload(); //Load the init script to set up dependency injection require_once dirname(__FILE__) . '/swift_init.php';
monokal/docker-orangehrm
www/symfony/lib/vendor/symfony/lib/vendor/swiftmailer/swift_required_pear.php
PHP
gpl-2.0
524
using System; namespace fizz_buzz { class Program { static void Main(string[] args) { for (int i = 1; i < 101; i++) { if (i % 3 < 1) Console.Write("fizz"); if (i % 5 < 1) Console.Write("buzz"); if (i % 3 > 0 && i % 5 > 0) Console.Write("{0}", i); Console.WriteLine(""); } } } }
aloisdg/code-problems
solutions/cs/shortest-fizz-buzz.cs
C#
mit
477
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Class: LoaderParser</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="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-0"> <a href="Event.html">Event</a> </li> <li class="class-depth-0"> <a href="EventTarget.html">EventTarget</a> </li> <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.Bullet.html">Bullet</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.Hermite.html">Hermite</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.KeyCode.html">KeyCode</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.Path.html">Path</a> </li> <li class="class-depth-1"> <a href="Phaser.PathFollower.html">PathFollower</a> </li> <li class="class-depth-1"> <a href="Phaser.PathPoint.html">PathPoint</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-2"> <a href="Phaser.Plugin.PathManager.html">PathManager</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.Weapon.html">Weapon</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.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-2"> <a href="PIXI.PIXI.DisplayObject.html">DisplayObject</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.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#ANGLE_DOWN">ANGLE_DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_LEFT">ANGLE_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_EAST">ANGLE_NORTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_WEST">ANGLE_NORTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_RIGHT">ANGLE_RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_EAST">ANGLE_SOUTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_WEST">ANGLE_SOUTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_UP">ANGLE_UP</a> </li> <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#BOTTOM_CENTER">BOTTOM_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_LEFT">BOTTOM_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_RIGHT">BOTTOM_RIGHT</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#CENTER">CENTER</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#displayList">displayList</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#emit">emit</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#HORIZONTAL">HORIZONTAL</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#LANDSCAPE">LANDSCAPE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_BOTTOM">LEFT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_CENTER">LEFT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_TOP">LEFT_TOP</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#listeners">listeners</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#mixin">mixin</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#off">off</a> </li> <li class="class-depth-0"> <a href="global.html#on">on</a> </li> <li class="class-depth-0"> <a href="global.html#once">once</a> </li> <li class="class-depth-0"> <a href="global.html#PENDING_ATLAS">PENDING_ATLAS</a> </li> <li class="class-depth-2"> <a href="global.html#Phaser.Path#numPointsreturn%257Bnumber%257DThetotalnumberofPathPointsinthisPath.">Phaser.Path#numPoints return {number} The total number of PathPoints in this Path.</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#PORTRAIT">PORTRAIT</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#removeAllListeners">removeAllListeners</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#RIGHT_BOTTOM">RIGHT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_CENTER">RIGHT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_TOP">RIGHT_TOP</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#stopImmediatePropagation">stopImmediatePropagation</a> </li> <li class="class-depth-0"> <a href="global.html#stopPropagation">stopPropagation</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#TOP_CENTER">TOP_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_LEFT">TOP_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_RIGHT">TOP_RIGHT</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#VERTICAL">VERTICAL</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-2"><a href="Phaser.Weapon.html">Weapon</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.KeyCode.html">Key Codes</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="http://phaser.io/community/newsletter">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/slack">Slack</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/donate">Donate</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="span8"> <div id="main"> <!--<h1 class="page-title">Class: LoaderParser</h1>--> <section> <header> <h2> <span class="ancestors"><a href="Phaser.html">Phaser</a>.</span> LoaderParser </h2> </header> <article> <div class="container-overview"> <dt> <h4 class="name " id="LoaderParser"><span class="type-signature"></span>new LoaderParser<span class="signature">()</span><span class="type-signature"></span></h4> </dt> <dd> <div class="description"> <p>Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.</p> </div> <dl class="details"> <dt class="tag-source">Source - <a href="src_loader_LoaderParser.js.html">loader/LoaderParser.js</a>, <a href="src_loader_LoaderParser.js.html#sunlight-1-line-12">line 12</a> </dt> </dl> </dd> </div> <h3 class="subsection-title">Methods</h3> <dl> <dt> <h4 class="name " id=".bitmapFont"><span class="type-signature">&lt;static> </span>bitmapFont<span class="signature">(xml, baseTexture, <span class="optional">xSpacing</span>, <span class="optional">ySpacing</span>)</span><span class="type-signature"> &rarr; {object}</span></h4> </dt> <dd> <div class="description"> <p>Alias for xmlBitmapFont, for backwards compatibility.</p> </div> <h5>Parameters:</h5> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Argument</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>xml</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>XML data you want to parse.</p></td> </tr> <tr> <td class="name"><code>baseTexture</code></td> <td class="type"> <span class="param-type"><a href="PIXI.BaseTexture.html">PIXI.BaseTexture</a></span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>The BaseTexture this font uses.</p></td> </tr> <tr> <td class="name"><code>xSpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional horizontal spacing between the characters.</p></td> </tr> <tr> <td class="name"><code>ySpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional vertical spacing between the characters.</p></td> </tr> </tbody> </table> <h5>Returns:</h5> <div class="returns"> <div class="returns-type"> <span class="param-type">object</span> - </div> <div class="returns-desc param-desc"> <p>The parsed Bitmap Font data.</p> </div> </div> <dl class="details"> <dt class="tag-source">Source - <a href="src_loader_LoaderParser.js.html">loader/LoaderParser.js</a>, <a href="src_loader_LoaderParser.js.html#sunlight-1-line-14">line 14</a> </dt> </dl> </dd> <dt> <h4 class="name " id=".jsonBitmapFont"><span class="type-signature">&lt;static> </span>jsonBitmapFont<span class="signature">(json, baseTexture, <span class="optional">xSpacing</span>, <span class="optional">ySpacing</span>)</span><span class="type-signature"> &rarr; {object}</span></h4> </dt> <dd> <div class="description"> <p>Parse a Bitmap Font from a JSON file.</p> </div> <h5>Parameters:</h5> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Argument</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>json</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>JSON data you want to parse.</p></td> </tr> <tr> <td class="name"><code>baseTexture</code></td> <td class="type"> <span class="param-type"><a href="PIXI.BaseTexture.html">PIXI.BaseTexture</a></span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>The BaseTexture this font uses.</p></td> </tr> <tr> <td class="name"><code>xSpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional horizontal spacing between the characters.</p></td> </tr> <tr> <td class="name"><code>ySpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional vertical spacing between the characters.</p></td> </tr> </tbody> </table> <h5>Returns:</h5> <div class="returns"> <div class="returns-type"> <span class="param-type">object</span> - </div> <div class="returns-desc param-desc"> <p>The parsed Bitmap Font data.</p> </div> </div> <dl class="details"> <dt class="tag-source">Source - <a href="src_loader_LoaderParser.js.html">loader/LoaderParser.js</a>, <a href="src_loader_LoaderParser.js.html#sunlight-1-line-84">line 84</a> </dt> </dl> </dd> <dt> <h4 class="name " id=".xmlBitmapFont"><span class="type-signature">&lt;static> </span>xmlBitmapFont<span class="signature">(xml, baseTexture, <span class="optional">xSpacing</span>, <span class="optional">ySpacing</span>)</span><span class="type-signature"> &rarr; {object}</span></h4> </dt> <dd> <div class="description"> <p>Parse a Bitmap Font from an XML file.</p> </div> <h5>Parameters:</h5> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Argument</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>xml</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>XML data you want to parse.</p></td> </tr> <tr> <td class="name"><code>baseTexture</code></td> <td class="type"> <span class="param-type"><a href="PIXI.BaseTexture.html">PIXI.BaseTexture</a></span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>The BaseTexture this font uses.</p></td> </tr> <tr> <td class="name"><code>xSpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional horizontal spacing between the characters.</p></td> </tr> <tr> <td class="name"><code>ySpacing</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>Additional vertical spacing between the characters.</p></td> </tr> </tbody> </table> <h5>Returns:</h5> <div class="returns"> <div class="returns-type"> <span class="param-type">object</span> - </div> <div class="returns-desc param-desc"> <p>The parsed Bitmap Font data.</p> </div> </div> <dl class="details"> <dt class="tag-source">Source - <a href="src_loader_LoaderParser.js.html">loader/LoaderParser.js</a>, <a href="src_loader_LoaderParser.js.html#sunlight-1-line-30">line 30</a> </dt> </dl> </dd> </dl> </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.4.0</a> on Fri Aug 26 2016 01:16:14 GMT+0100 (BST) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <div class="span3"> <div id="toc"></div> </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>
clark-stevenson/phaser
v2/docs/Phaser.LoaderParser.html
HTML
mit
53,122
# # config.rb # #-- # Copyright (c) 1998-2003 Minero Aoki <aamine@loveruby.net> # # 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. # # Note: Originally licensed under LGPL v2+. Using MIT license for Rails # with permission of Minero Aoki. #++ module TMail class Config def initialize( strict ) @strict_parse = strict @strict_base64decode = strict end def strict_parse? @strict_parse end attr_writer :strict_parse def strict_base64decode? @strict_base64decode end attr_writer :strict_base64decode def new_body_port( mail ) StringPort.new end alias new_preamble_port new_body_port alias new_part_port new_body_port end DEFAULT_CONFIG = Config.new(false) DEFAULT_STRICT_CONFIG = Config.new(true) def Config.to_config( arg ) return DEFAULT_STRICT_CONFIG if arg == true return DEFAULT_CONFIG if arg == false arg or DEFAULT_CONFIG end end
mjgiarlo/noidman
vendor/rails/actionmailer/lib/action_mailer/vendor/tmail/config.rb
Ruby
mit
1,978
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: src/animation/Animation.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="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-0"> <a href="Event.html">Event</a> </li> <li class="class-depth-0"> <a href="EventTarget.html">EventTarget</a> </li> <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.Bullet.html">Bullet</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.Hermite.html">Hermite</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.KeyCode.html">KeyCode</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.Path.html">Path</a> </li> <li class="class-depth-1"> <a href="Phaser.PathFollower.html">PathFollower</a> </li> <li class="class-depth-1"> <a href="Phaser.PathPoint.html">PathPoint</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-2"> <a href="Phaser.Plugin.PathManager.html">PathManager</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.Weapon.html">Weapon</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.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-2"> <a href="PIXI.PIXI.DisplayObject.html">DisplayObject</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.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#ANGLE_DOWN">ANGLE_DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_LEFT">ANGLE_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_EAST">ANGLE_NORTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_NORTH_WEST">ANGLE_NORTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_RIGHT">ANGLE_RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_EAST">ANGLE_SOUTH_EAST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_SOUTH_WEST">ANGLE_SOUTH_WEST</a> </li> <li class="class-depth-0"> <a href="global.html#ANGLE_UP">ANGLE_UP</a> </li> <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#BOTTOM_CENTER">BOTTOM_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_LEFT">BOTTOM_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#BOTTOM_RIGHT">BOTTOM_RIGHT</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#CENTER">CENTER</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#displayList">displayList</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#emit">emit</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#HORIZONTAL">HORIZONTAL</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#LANDSCAPE">LANDSCAPE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_BOTTOM">LEFT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_CENTER">LEFT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT_TOP">LEFT_TOP</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#listeners">listeners</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#mixin">mixin</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#off">off</a> </li> <li class="class-depth-0"> <a href="global.html#on">on</a> </li> <li class="class-depth-0"> <a href="global.html#once">once</a> </li> <li class="class-depth-0"> <a href="global.html#PENDING_ATLAS">PENDING_ATLAS</a> </li> <li class="class-depth-2"> <a href="global.html#Phaser.Path#numPointsreturn%257Bnumber%257DThetotalnumberofPathPointsinthisPath.">Phaser.Path#numPoints return {number} The total number of PathPoints in this Path.</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#PORTRAIT">PORTRAIT</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#removeAllListeners">removeAllListeners</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#RIGHT_BOTTOM">RIGHT_BOTTOM</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_CENTER">RIGHT_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT_TOP">RIGHT_TOP</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#stopImmediatePropagation">stopImmediatePropagation</a> </li> <li class="class-depth-0"> <a href="global.html#stopPropagation">stopPropagation</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#TOP_CENTER">TOP_CENTER</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_LEFT">TOP_LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#TOP_RIGHT">TOP_RIGHT</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#VERTICAL">VERTICAL</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-2"><a href="Phaser.Weapon.html">Weapon</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.KeyCode.html">Key Codes</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="http://phaser.io/community/newsletter">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/slack">Slack</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/donate">Donate</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/animation/Animation.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Richard Davey &lt;rich@photonstorm.com> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * An Animation instance contains a single animation and the controls to play it. * * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. * * @class Phaser.Animation * @constructor * @param {Phaser.Game} game - A reference to the currently running game. * @param {Phaser.Sprite} parent - A reference to the owner of this Animation. * @param {string} name - The unique name for this animation, used in playback commands. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. * @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. */ Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) { if (loop === undefined) { loop = false; } /** * @property {Phaser.Game} game - A reference to the currently running Game. */ this.game = game; /** * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. * @private */ this._parent = parent; /** * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. * @private */ this._frameData = frameData; /** * @property {string} name - The user defined name given to this Animation. */ this.name = name; /** * @property {array} _frames * @private */ this._frames = []; this._frames = this._frames.concat(frames); /** * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate. */ this.delay = 1000 / frameRate; /** * @property {boolean} loop - The loop state of the Animation. */ this.loop = loop; /** * @property {number} loopCount - The number of times the animation has looped since it was last started. */ this.loopCount = 0; /** * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes? * @default */ this.killOnComplete = false; /** * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. * @default */ this.isFinished = false; /** * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. * @default */ this.isPlaying = false; /** * @property {boolean} isPaused - The paused state of the Animation. * @default */ this.isPaused = false; /** * @property {boolean} _pauseStartTime - The time the animation paused. * @private * @default */ this._pauseStartTime = 0; /** * @property {number} _frameIndex * @private * @default */ this._frameIndex = 0; /** * @property {number} _frameDiff * @private * @default */ this._frameDiff = 0; /** * @property {number} _frameSkip * @private * @default */ this._frameSkip = 1; /** * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. */ this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); /** * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback. */ this.onStart = new Phaser.Signal(); /** * This event is dispatched when the Animation changes frame. * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`. * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations * will automatically frame-skip to try and claw back time, so do not base your code on expecting to * receive a perfectly sequential set of frames from this event. * @property {Phaser.Signal|null} onUpdate * @default */ this.onUpdate = null; /** * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead. */ this.onComplete = new Phaser.Signal(); /** * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops. */ this.onLoop = new Phaser.Signal(); /** * @property {boolean} isReversed - Indicates if the animation will play backwards. * @default */ this.isReversed = false; // Set-up some event listeners this.game.onPause.add(this.onPause, this); this.game.onResume.add(this.onResume, this); }; Phaser.Animation.prototype = { /** * Plays this animation. * * @method Phaser.Animation#play * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. * @return {Phaser.Animation} - A reference to this Animation instance. */ play: function (frameRate, loop, killOnComplete) { if (typeof frameRate === 'number') { // If they set a new frame rate then use it, otherwise use the one set on creation this.delay = 1000 / frameRate; } if (typeof loop === 'boolean') { // If they set a new loop value then use it, otherwise use the one set on creation this.loop = loop; } if (typeof killOnComplete !== 'undefined') { // Remove the parent sprite once the animation has finished? this.killOnComplete = killOnComplete; } this.isPlaying = true; this.isFinished = false; this.paused = false; this.loopCount = 0; this._timeLastFrame = this.game.time.time; this._timeNextFrame = this.game.time.time + this.delay; this._frameIndex = this.isReversed ? this._frames.length - 1 : 0; this.updateCurrentFrame(false, true); this._parent.events.onAnimationStart$dispatch(this._parent, this); this.onStart.dispatch(this._parent, this); this._parent.animations.currentAnim = this; this._parent.animations.currentFrame = this.currentFrame; return this; }, /** * Sets this animation back to the first frame and restarts the animation. * * @method Phaser.Animation#restart */ restart: function () { this.isPlaying = true; this.isFinished = false; this.paused = false; this.loopCount = 0; this._timeLastFrame = this.game.time.time; this._timeNextFrame = this.game.time.time + this.delay; this._frameIndex = 0; this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); this._parent.setFrame(this.currentFrame); this._parent.animations.currentAnim = this; this._parent.animations.currentFrame = this.currentFrame; this.onStart.dispatch(this._parent, this); }, /** * Reverses the animation direction. * * @method Phaser.Animation#reverse * @return {Phaser.Animation} The animation instance. */ reverse: function () { this.reversed = !this.reversed; return this; }, /** * Reverses the animation direction for the current/next animation only * Once the onComplete event is called this method will be called again and revert * the reversed state. * * @method Phaser.Animation#reverseOnce * @return {Phaser.Animation} The animation instance. */ reverseOnce: function () { this.onComplete.addOnce(this.reverse, this); return this.reverse(); }, /** * Sets this animations playback to a given frame with the given ID. * * @method Phaser.Animation#setFrame * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index. * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation. */ setFrame: function(frameId, useLocalFrameIndex) { var frameIndex; if (useLocalFrameIndex === undefined) { useLocalFrameIndex = false; } // Find the index to the desired frame. if (typeof frameId === "string") { for (var i = 0; i &lt; this._frames.length; i++) { if (this._frameData.getFrame(this._frames[i]).name === frameId) { frameIndex = i; } } } else if (typeof frameId === "number") { if (useLocalFrameIndex) { frameIndex = frameId; } else { for (var i = 0; i &lt; this._frames.length; i++) { if (this._frames[i] === frameId) { frameIndex = i; } } } } if (frameIndex) { // Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update. this._frameIndex = frameIndex - 1; // Make the animation update at next update this._timeNextFrame = this.game.time.time; this.update(); } }, /** * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored. * * @method Phaser.Animation#stop * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events? */ stop: function (resetFrame, dispatchComplete) { if (resetFrame === undefined) { resetFrame = false; } if (dispatchComplete === undefined) { dispatchComplete = false; } this.isPlaying = false; this.isFinished = true; this.paused = false; if (resetFrame) { this.currentFrame = this._frameData.getFrame(this._frames[0]); this._parent.setFrame(this.currentFrame); } if (dispatchComplete) { this._parent.events.onAnimationComplete$dispatch(this._parent, this); this.onComplete.dispatch(this._parent, this); } }, /** * Called when the Game enters a paused state. * * @method Phaser.Animation#onPause */ onPause: function () { if (this.isPlaying) { this._frameDiff = this._timeNextFrame - this.game.time.time; } }, /** * Called when the Game resumes from a paused state. * * @method Phaser.Animation#onResume */ onResume: function () { if (this.isPlaying) { this._timeNextFrame = this.game.time.time + this._frameDiff; } }, /** * Updates this animation. Called automatically by the AnimationManager. * * @method Phaser.Animation#update */ update: function () { if (this.isPaused) { return false; } if (this.isPlaying &amp;&amp; this.game.time.time >= this._timeNextFrame) { this._frameSkip = 1; // Lagging? this._frameDiff = this.game.time.time - this._timeNextFrame; this._timeLastFrame = this.game.time.time; if (this._frameDiff > this.delay) { // We need to skip a frame, work out how many this._frameSkip = Math.floor(this._frameDiff / this.delay); this._frameDiff -= (this._frameSkip * this.delay); } // And what's left now? this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff); if (this.isReversed) { this._frameIndex -= this._frameSkip; } else { this._frameIndex += this._frameSkip; } if (!this.isReversed &amp;&amp; this._frameIndex >= this._frames.length || this.isReversed &amp;&amp; this._frameIndex &lt;= -1) { if (this.loop) { // Update current state before event callback this._frameIndex = Math.abs(this._frameIndex) % this._frames.length; if (this.isReversed) { this._frameIndex = this._frames.length - 1 - this._frameIndex; } this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); // Instead of calling updateCurrentFrame we do it here instead if (this.currentFrame) { this._parent.setFrame(this.currentFrame); } this.loopCount++; this._parent.events.onAnimationLoop$dispatch(this._parent, this); this.onLoop.dispatch(this._parent, this); if (this.onUpdate) { this.onUpdate.dispatch(this, this.currentFrame); // False if the animation was destroyed from within a callback return !!this._frameData; } else { return true; } } else { this.complete(); return false; } } else { return this.updateCurrentFrame(true); } } return false; }, /** * Changes the currentFrame per the _frameIndex, updates the display state, * and triggers the update signal. * * Returns true if the current frame update was 'successful', false otherwise. * * @method Phaser.Animation#updateCurrentFrame * @private * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched. * @param {boolean} fromPlay - Was this call made from the playing of a new animation? * @return {boolean} True if the current frame was updated, otherwise false. */ updateCurrentFrame: function (signalUpdate, fromPlay) { if (fromPlay === undefined) { fromPlay = false; } if (!this._frameData) { // The animation is already destroyed, probably from a callback return false; } // Previous index var idx = this.currentFrame.index; this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); if (this.currentFrame &amp;&amp; (fromPlay || (!fromPlay &amp;&amp; idx !== this.currentFrame.index))) { this._parent.setFrame(this.currentFrame); } if (this.onUpdate &amp;&amp; signalUpdate) { this.onUpdate.dispatch(this, this.currentFrame); // False if the animation was destroyed from within a callback return !!this._frameData; } else { return true; } }, /** * Advances by the given number of frames in the Animation, taking the loop value into consideration. * * @method Phaser.Animation#next * @param {number} [quantity=1] - The number of frames to advance. */ next: function (quantity) { if (quantity === undefined) { quantity = 1; } var frame = this._frameIndex + quantity; if (frame >= this._frames.length) { if (this.loop) { frame %= this._frames.length; } else { frame = this._frames.length - 1; } } if (frame !== this._frameIndex) { this._frameIndex = frame; this.updateCurrentFrame(true); } }, /** * Moves backwards the given number of frames in the Animation, taking the loop value into consideration. * * @method Phaser.Animation#previous * @param {number} [quantity=1] - The number of frames to move back. */ previous: function (quantity) { if (quantity === undefined) { quantity = 1; } var frame = this._frameIndex - quantity; if (frame &lt; 0) { if (this.loop) { frame = this._frames.length + frame; } else { frame++; } } if (frame !== this._frameIndex) { this._frameIndex = frame; this.updateCurrentFrame(true); } }, /** * Changes the FrameData object this Animation is using. * * @method Phaser.Animation#updateFrameData * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. */ updateFrameData: function (frameData) { this._frameData = frameData; this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null; }, /** * Cleans up this animation ready for deletion. Nulls all values and references. * * @method Phaser.Animation#destroy */ destroy: function () { if (!this._frameData) { // Already destroyed return; } this.game.onPause.remove(this.onPause, this); this.game.onResume.remove(this.onResume, this); this.game = null; this._parent = null; this._frames = null; this._frameData = null; this.currentFrame = null; this.isPlaying = false; this.onStart.dispose(); this.onLoop.dispose(); this.onComplete.dispose(); if (this.onUpdate) { this.onUpdate.dispose(); } }, /** * Called internally when the animation finishes playback. * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event. * * @method Phaser.Animation#complete */ complete: function () { this._frameIndex = this._frames.length - 1; this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); this.isPlaying = false; this.isFinished = true; this.paused = false; this._parent.events.onAnimationComplete$dispatch(this._parent, this); this.onComplete.dispatch(this._parent, this); if (this.killOnComplete) { this._parent.kill(); } } }; Phaser.Animation.prototype.constructor = Phaser.Animation; /** * @name Phaser.Animation#paused * @property {boolean} paused - Gets and sets the paused state of this Animation. */ Object.defineProperty(Phaser.Animation.prototype, 'paused', { get: function () { return this.isPaused; }, set: function (value) { this.isPaused = value; if (value) { // Paused this._pauseStartTime = this.game.time.time; } else { // Un-paused if (this.isPlaying) { this._timeNextFrame = this.game.time.time + this.delay; } } } }); /** * @name Phaser.Animation#reversed * @property {boolean} reversed - Gets and sets the isReversed state of this Animation. */ Object.defineProperty(Phaser.Animation.prototype, 'reversed', { get: function () { return this.isReversed; }, set: function (value) { this.isReversed = value; } }); /** * @name Phaser.Animation#frameTotal * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. * @readonly */ Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', { get: function () { return this._frames.length; } }); /** * @name Phaser.Animation#frame * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. */ Object.defineProperty(Phaser.Animation.prototype, 'frame', { get: function () { if (this.currentFrame !== null) { return this.currentFrame.index; } else { return this._frameIndex; } }, set: function (value) { this.currentFrame = this._frameData.getFrame(this._frames[value]); if (this.currentFrame !== null) { this._frameIndex = value; this._parent.setFrame(this.currentFrame); if (this.onUpdate) { this.onUpdate.dispatch(this, this.currentFrame); } } } }); /** * @name Phaser.Animation#speed * @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0. */ Object.defineProperty(Phaser.Animation.prototype, 'speed', { get: function () { return 1000 / this.delay; }, set: function (value) { if (value > 0) { this.delay = 1000 / value; } } }); /** * @name Phaser.Animation#enableUpdate * @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame. */ Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', { get: function () { return (this.onUpdate !== null); }, set: function (value) { if (value &amp;&amp; this.onUpdate === null) { this.onUpdate = new Phaser.Signal(); } else if (!value &amp;&amp; this.onUpdate !== null) { this.onUpdate.dispose(); this.onUpdate = null; } } }); /** * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); * * @method Phaser.Animation.generateFrameNames * @static * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. * @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. * @return {string[]} An array of framenames. */ Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { if (suffix === undefined) { suffix = ''; } var output = []; var frame = ''; if (start &lt; stop) { for (var i = start; i &lt;= stop; i++) { if (typeof zeroPad === 'number') { // str, len, pad, dir frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); } else { frame = i.toString(); } frame = prefix + frame + suffix; output.push(frame); } } else { for (var i = start; i >= stop; i--) { if (typeof zeroPad === 'number') { // str, len, pad, dir frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); } else { frame = i.toString(); } frame = prefix + frame + suffix; output.push(frame); } } return output; }; </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.4.0</a> on Fri Aug 26 2016 01:16:09 GMT+0100 (BST) 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>
clark-stevenson/phaser
v2/docs/src_animation_Animation.js.html
HTML
mit
65,601
require "rack/chunked" module ActionController #:nodoc: # Allows views to be streamed back to the client as they are rendered. # # By default, Rails renders views by first rendering the template # and then the layout. The response is sent to the client after the whole # template is rendered, all queries are made, and the layout is processed. # # Streaming inverts the rendering flow by rendering the layout first and # streaming each part of the layout as they are processed. This allows the # header of the HTML (which is usually in the layout) to be streamed back # to client very quickly, allowing JavaScripts and stylesheets to be loaded # earlier than usual. # # This approach was introduced in Rails 3.1 and is still improving. Several # Rack middlewares may not work and you need to be careful when streaming. # Those points are going to be addressed soon. # # In order to use streaming, you will need to use a Ruby version that # supports fibers (fibers are supported since version 1.9.2 of the main # Ruby implementation). # # Streaming can be added to a given template easily, all you need to do is # to pass the :stream option. # # class PostsController # def index # @posts = Post.all # render stream: true # end # end # # == When to use streaming # # Streaming may be considered to be overkill for lightweight actions like # +new+ or +edit+. The real benefit of streaming is on expensive actions # that, for example, do a lot of queries on the database. # # In such actions, you want to delay queries execution as much as you can. # For example, imagine the following +dashboard+ action: # # def dashboard # @posts = Post.all # @pages = Page.all # @articles = Article.all # end # # Most of the queries here are happening in the controller. In order to benefit # from streaming you would want to rewrite it as: # # def dashboard # # Allow lazy execution of the queries # @posts = Post.all # @pages = Page.all # @articles = Article.all # render stream: true # end # # Notice that :stream only works with templates. Rendering :json # or :xml with :stream won't work. # # == Communication between layout and template # # When streaming, rendering happens top-down instead of inside-out. # Rails starts with the layout, and the template is rendered later, # when its +yield+ is reached. # # This means that, if your application currently relies on instance # variables set in the template to be used in the layout, they won't # work once you move to streaming. The proper way to communicate # between layout and template, regardless of whether you use streaming # or not, is by using +content_for+, +provide+ and +yield+. # # Take a simple example where the layout expects the template to tell # which title to use: # # <html> # <head><title><%= yield :title %></title></head> # <body><%= yield %></body> # </html> # # You would use +content_for+ in your template to specify the title: # # <%= content_for :title, "Main" %> # Hello # # And the final result would be: # # <html> # <head><title>Main</title></head> # <body>Hello</body> # </html> # # However, if +content_for+ is called several times, the final result # would have all calls concatenated. For instance, if we have the following # template: # # <%= content_for :title, "Main" %> # Hello # <%= content_for :title, " page" %> # # The final result would be: # # <html> # <head><title>Main page</title></head> # <body>Hello</body> # </html> # # This means that, if you have <code>yield :title</code> in your layout # and you want to use streaming, you would have to render the whole template # (and eventually trigger all queries) before streaming the title and all # assets, which kills the purpose of streaming. For this purpose, you can use # a helper called +provide+ that does the same as +content_for+ but tells the # layout to stop searching for other entries and continue rendering. # # For instance, the template above using +provide+ would be: # # <%= provide :title, "Main" %> # Hello # <%= content_for :title, " page" %> # # Giving: # # <html> # <head><title>Main</title></head> # <body>Hello</body> # </html> # # That said, when streaming, you need to properly check your templates # and choose when to use +provide+ and +content_for+. # # == Headers, cookies, session and flash # # When streaming, the HTTP headers are sent to the client right before # it renders the first line. This means that, modifying headers, cookies, # session or flash after the template starts rendering will not propagate # to the client. # # == Middlewares # # Middlewares that need to manipulate the body won't work with streaming. # You should disable those middlewares whenever streaming in development # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it # needs to inject contents in the HTML body. # # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support # streaming bodies yet. Whenever streaming Cache-Control is automatically # set to "no-cache". # # == Errors # # When it comes to streaming, exceptions get a bit more complicated. This # happens because part of the template was already rendered and streamed to # the client, making it impossible to render a whole exception page. # # Currently, when an exception happens in development or production, Rails # will automatically stream to the client: # # "><script>window.location = "/500.html"</script></html> # # The first two characters (">) are required in case the exception happens # while rendering attributes for a given tag. You can check the real cause # for the exception in your logger. # # == Web server support # # Not all web servers support streaming out-of-the-box. You need to check # the instructions for each of them. # # ==== Unicorn # # Unicorn supports streaming but it needs to be configured. For this, you # need to create a config file as follow: # # # unicorn.config.rb # listen 3000, tcp_nopush: false # # And use it on initialization: # # unicorn_rails --config-file unicorn.config.rb # # You may also want to configure other parameters like <tt>:tcp_nodelay</tt>. # Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen # # If you are using Unicorn with NGINX, you may need to tweak NGINX. # Streaming should work out of the box on Rainbows. # # ==== Passenger # # To be described. # module Streaming extend ActiveSupport::Concern private # Set proper cache control and transfer encoding when streaming def _process_options(options) super if options[:stream] if request.version == "HTTP/1.0" options.delete(:stream) else headers["Cache-Control"] ||= "no-cache" headers["Transfer-Encoding"] = "chunked" headers.delete("Content-Length") end end end # Call render_body if we are streaming instead of usual +render+. def _render_template(options) if options.delete(:stream) Rack::Chunked::Body.new view_renderer.render_body(view_context, options) else super end end end end
lrosskamp/makealist-public
vendor/cache/ruby/2.3.0/gems/actionpack-5.1.2/lib/action_controller/metal/streaming.rb
Ruby
mit
7,653
// 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 System.Buffers; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System { public static partial class Environment { private static string? GetEnvironmentVariableCore(string variable) { Span<char> buffer = stackalloc char[128]; // a somewhat reasonable default size int requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer); if (requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) { return null; } if (requiredSize <= buffer.Length) { return new string(buffer.Slice(0, requiredSize)); } char[] chars = ArrayPool<char>.Shared.Rent(requiredSize); try { buffer = chars; requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer); if ((requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) || requiredSize > buffer.Length) { return null; } return new string(buffer.Slice(0, requiredSize)); } finally { ArrayPool<char>.Shared.Return(chars); } } private static void SetEnvironmentVariableCore(string variable, string? value) { if (!Interop.Kernel32.SetEnvironmentVariable(variable, value)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_ENVVAR_NOT_FOUND: // Allow user to try to clear a environment variable return; case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: // The error message from Win32 is "The filename or extension is too long", // which is not accurate. throw new ArgumentException(SR.Argument_LongEnvVarValue); case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY: case Interop.Errors.ERROR_NO_SYSTEM_RESOURCES: throw new OutOfMemoryException(Interop.Kernel32.GetMessage(errorCode)); default: throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode)); } } } public static unsafe IDictionary GetEnvironmentVariables() { char* pStrings = Interop.Kernel32.GetEnvironmentStrings(); if (pStrings == null) { throw new OutOfMemoryException(); } try { // Format for GetEnvironmentStrings is: // [=HiddenVar=value\0]* [Variable=value\0]* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Search for terminating \0\0 (two unicode \0's). char* p = pStrings; while (!(*p == '\0' && *(p + 1) == '\0')) { p++; } Span<char> block = new Span<char>(pStrings, (int)(p - pStrings + 1)); // Format for GetEnvironmentStrings is: // (=HiddenVar=value\0 | Variable=value\0)* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Note the =HiddenVar's aren't always at the beginning. // Copy strings out, parsing into pairs and inserting into the table. // The first few environment variable entries start with an '='. // The current working directory of every drive (except for those drives // you haven't cd'ed into in your DOS window) are stored in the // environment block (as =C:=pwd) and the program's exit code is // as well (=ExitCode=00000000). var results = new Hashtable(); for (int i = 0; i < block.Length; i++) { int startKey = i; // Skip to key. On some old OS, the environment block can be corrupted. // Some will not have '=', so we need to check for '\0'. while (block[i] != '=' && block[i] != '\0') { i++; } if (block[i] == '\0') { continue; } // Skip over environment variables starting with '=' if (i - startKey == 0) { while (block[i] != 0) { i++; } continue; } string key = new string(block.Slice(startKey, i - startKey)); i++; // skip over '=' int startValue = i; while (block[i] != 0) { i++; // Read to end of this entry } string value = new string(block.Slice(startValue, i - startValue)); // skip over 0 handled by for loop's i++ try { results.Add(key, value); } catch (ArgumentException) { // Throw and catch intentionally to provide non-fatal notification about corrupted environment block } } return results; } finally { bool success = Interop.Kernel32.FreeEnvironmentStrings(pStrings); Debug.Assert(success); } } } }
BrennanConroy/corefx
src/Common/src/CoreLib/System/Environment.Variables.Windows.cs
C#
mit
6,424
export { Moon16 as default } from "../../";
markogresak/DefinitelyTyped
types/carbon__icons-react/es/moon/16.d.ts
TypeScript
mit
44
/*************************************************************************/ /* area_2d.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 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 AREA_2D_H #define AREA_2D_H #include "scene/2d/collision_object_2d.h" #include "vset.h" class Area2D : public CollisionObject2D { OBJ_TYPE( Area2D, CollisionObject2D ); public: enum SpaceOverride { SPACE_OVERRIDE_DISABLED, SPACE_OVERRIDE_COMBINE, SPACE_OVERRIDE_COMBINE_REPLACE, SPACE_OVERRIDE_REPLACE, SPACE_OVERRIDE_REPLACE_COMBINE }; private: SpaceOverride space_override; Vector2 gravity_vec; real_t gravity; bool gravity_is_point; real_t gravity_distance_scale; real_t linear_damp; real_t angular_damp; uint32_t collision_mask; uint32_t layer_mask; int priority; bool monitoring; bool monitorable; bool locked; void _body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape); void _body_enter_tree(ObjectID p_id); void _body_exit_tree(ObjectID p_id); struct ShapePair { int body_shape; int area_shape; bool operator<(const ShapePair& p_sp) const { if (body_shape==p_sp.body_shape) return area_shape < p_sp.area_shape; else return body_shape < p_sp.body_shape; } ShapePair() {} ShapePair(int p_bs, int p_as) { body_shape=p_bs; area_shape=p_as; } }; struct BodyState { int rc; bool in_tree; VSet<ShapePair> shapes; }; Map<ObjectID,BodyState> body_map; void _area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape); void _area_enter_tree(ObjectID p_id); void _area_exit_tree(ObjectID p_id); struct AreaShapePair { int area_shape; int self_shape; bool operator<(const AreaShapePair& p_sp) const { if (area_shape==p_sp.area_shape) return self_shape < p_sp.self_shape; else return area_shape < p_sp.area_shape; } AreaShapePair() {} AreaShapePair(int p_bs, int p_as) { area_shape=p_bs; self_shape=p_as; } }; struct AreaState { int rc; bool in_tree; VSet<AreaShapePair> shapes; }; Map<ObjectID,AreaState> area_map; void _clear_monitoring(); protected: void _notification(int p_what); static void _bind_methods(); public: void set_space_override_mode(SpaceOverride p_mode); SpaceOverride get_space_override_mode() const; void set_gravity_is_point(bool p_enabled); bool is_gravity_a_point() const; void set_gravity_distance_scale(real_t p_scale); real_t get_gravity_distance_scale() const; void set_gravity_vector(const Vector2& p_vec); Vector2 get_gravity_vector() const; void set_gravity(real_t p_gravity); real_t get_gravity() const; void set_linear_damp(real_t p_linear_damp); real_t get_linear_damp() const; void set_angular_damp(real_t p_angular_damp); real_t get_angular_damp() const; void set_priority(real_t p_priority); real_t get_priority() const; void set_enable_monitoring(bool p_enable); bool is_monitoring_enabled() const; void set_monitorable(bool p_enable); bool is_monitorable() const; void set_collision_mask(uint32_t p_mask); uint32_t get_collision_mask() const; void set_layer_mask(uint32_t p_mask); uint32_t get_layer_mask() const; void set_collision_mask_bit(int p_bit, bool p_value); bool get_collision_mask_bit(int p_bit) const; void set_layer_mask_bit(int p_bit, bool p_value); bool get_layer_mask_bit(int p_bit) const; Array get_overlapping_bodies() const; //function for script Array get_overlapping_areas() const; //function for script bool overlaps_area(Node* p_area) const; bool overlaps_body(Node* p_body) const; Area2D(); ~Area2D(); }; VARIANT_ENUM_CAST(Area2D::SpaceOverride); #endif // AREA_2D_H
OpenSocialGames/godot
scene/2d/area_2d.h
C
mit
5,625
export { Mpeg16 as default } from "../../";
georgemarshall/DefinitelyTyped
types/carbon__icons-react/es/MPEG/16.d.ts
TypeScript
mit
44
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>RakNet: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">RakNet &#160;<span id="projectnumber">4.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceRakNet.html">RakNet</a></li><li class="navelem"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">Clans_GrantLeader</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">RakNet::Clans_GrantLeader Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6e29d665abe3559b60e9fadfb2fa1b40">callbackId</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a7d2c66bbb0ffbcda05e83e936976c41a">CallCallback</a>(Lobby2Callbacks *cb)=0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#a206ef0066b727e6bd46fb3dba7405cba">CancelOnDisconnect</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a73681a9a5bcfe6d7344cb7500c1bae72">ClientImpl</a>(RakNet::Lobby2Plugin *client)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ad48d6053a9d086c29dc3108e7de557dc">DebugMsg</a>(RakNet::RakString &amp;out) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#accf4946d351e9bb17ad197fc21b0b473">DebugPrintf</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5046c82fcca8bac36babe863c55ec9eb">extendedResultCode</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a92248c1609297987f41dbfcfd75806f9">GetID</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ae417f773c4d48bc1cce69c656f2952fd">GetName</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#aa033ee181c38996e109b44f637ec6969">PrevalidateInput</a>(void)</td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a49c6460be7043aa3dd8f69955a4fb426">requestId</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#a0bcda1db110f90411dc45be3fd1aceca">RequiresAdmin</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#a7bbb41b4f12f9ecfe1775089e557c1a2">RequiresLogin</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#a7a36443cc7e2797278fca73c418c779b">RequiresRankingPermission</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a750b6a5d792d6f6c2532bfc7e3f74c99">resultCode</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html#ac71663037f32c161577d5603c82e9524">Serialize</a>(bool writeToBitstream, bool serializeOutput, RakNet::BitStream *bitStream)</td><td class="entry"><a class="el" href="structRakNet_1_1Clans__GrantLeader.html">RakNet::Clans_GrantLeader</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a39a885f1a8d8b636e5c7bbeb13d4f822">ServerDBImpl</a>(Lobby2ServerCommand *command, void *databaseInterface)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a62cc92ba3fb0e6562cf77d929d231a35">ServerPostDBMemoryImpl</a>(Lobby2Server *server, RakString userHandle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5213270ccd16a7bc6afc8df001b623e7">ServerPreDBMemoryImpl</a>(Lobby2Server *server, RakString userHandle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#af510ed0df868969f12118ea32027334b">ValidateBinary</a>(RakNetSmartPtr&lt; BinaryDataBlock &gt;binaryDataBlock)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#aec0eeb9161acabd01464f4b875abed31">ValidateEmailAddress</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6a85caa9e47c7d9fec7f156c5e7c723a">ValidateHandle</a>(RakNet::RakString *handle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a4cf58429201d0c452d354b6add784712">ValidatePassword</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ada4ddbe1b8d880b6beb3cec2d107c3cf">ValidateRequiredText</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 2 2014 20:10:30 for RakNet by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.2 </small></address> </body> </html>
JayStilla/AIEComplexSystems
dep/RakNet/Help/Doxygen/html/structRakNet_1_1Clans__GrantLeader-members.html
HTML
mit
10,780
<?php namespace Illuminate\Mail\Transport; use Swift_Mime_Message; use Illuminate\Support\Collection; class ArrayTransport extends Transport { /** * The collection of Swift Messages. * * @var \Illuminate\Support\Collection */ protected $messages; /** * Create a new array transport instance. * * @return void */ public function __construct() { $this->messages = new Collection; } /** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $this->messages[] = $message; return $this->numberOfRecipients($message); } /** * Retrieve the collection of messages. * * @return \Illuminate\Support\Collection */ public function messages() { return $this->messages; } /** * Clear all of the messages from the local collection. * * @return void */ public function flush() { return $this->messages = new Collection; } }
vileopratama/portal-toyotadjakarta
vendor/laravel/framework/src/Illuminate/Mail/Transport/ArrayTransport.php
PHP
mit
1,109
/*! asynquence-contrib v0.13.0 (c) Kyle Simpson MIT License: http://getify.mit-license.org */ (function UMD(dependency,definition){ if (typeof module !== "undefined" && module.exports) { // make dependency injection wrapper first module.exports = function $$inject$dependency(dep) { // only try to `require(..)` if dependency is a string module path if (typeof dep == "string") { try { dep = require(dep); } catch (err) { // dependency not yet fulfilled, so just return // dependency injection wrapper again return $$inject$dependency; } } return definition(dep); }; // if possible, immediately try to resolve wrapper // (with peer dependency) if (typeof dependency == "string") { module.exports = module.exports( require("path").join("..",dependency) ); } } else if (typeof define == "function" && define.amd) { define([dependency],definition); } else { definition(dependency); } })(this.ASQ || "asynquence",function DEF(ASQ){ "use strict"; var ARRAY_SLICE = Array.prototype.slice, ø = Object.create(null), brand = "__ASQ__", schedule = ASQ.__schedule, tapSequence = ASQ.__tapSequence ; function wrapGate(api,fns,success,failure,reset) { fns = fns.map(function $$map(v,idx){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(next) { def.seq.val(function $$val(){ success(next,idx,ARRAY_SLICE.call(arguments)); }) .or(function $$or(){ failure(next,idx,ARRAY_SLICE.call(arguments)); }); }; } else { return function $$fn(next) { var args = ARRAY_SLICE.call(arguments); args[0] = function $$next() { success(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].fail = function $$fail() { failure(next,idx,ARRAY_SLICE.call(arguments)); }; args[0].abort = function $$abort() { reset(); }; args[0].errfcb = function $$errfcb(err) { if (err) { failure(next,idx,[err]); } else { success(next,idx,ARRAY_SLICE.call(arguments,1)); } }; v.apply(ø,args); }; } }); api.then(function $$then(){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); } function isPromise(v) { var val_type = typeof v; return ( v !== null && ( val_type == "object" || val_type == "function" ) && !ASQ.isSequence(v) && // NOTE: `then` duck-typing of promises is stupid typeof v.then == "function" ); } // "after" ASQ.extend("after",function $$extend(api,internals){ return function $$after(num) { var orig_args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ var args = orig_args || ARRAY_SLICE.call(arguments,1); setTimeout(function $$set$timeout(){ done.apply(ø,args); },num); }); return api; }; }); ASQ.after = function $$after() { return ASQ().after.apply(ø,arguments); }; // "any" ASQ.extend("any",function $$extend(api,internals){ return function $$any() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as success success_messages.length = fns.length; trigger.apply(ø,success_messages); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, success_messages = [], sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "errfcb" ASQ.extend("errfcb",function $$extend(api,internals){ return function $$errfcb() { // create a fake sequence to extract the callbacks var sq = { val: function $$then(cb){ sq.val_cb = cb; return sq; }, or: function $$or(cb){ sq.or_cb = cb; return sq; } }; // trick `seq(..)`s checks for a sequence sq[brand] = true; // immediately register our fake sequence on the // main sequence api.seq(sq); // provide the "error-first" callback return function $$errorfirst$callback(err) { if (err) { sq.or_cb(err); } else { sq.val_cb.apply(ø,ARRAY_SLICE.call(arguments,1)); } }; }; }); // "failAfter" ASQ.extend("failAfter",function $$extend(api,internals){ return function $$failAfter(num) { var args = arguments.length > 1 ? ARRAY_SLICE.call(arguments,1) : void 0 ; num = +num || 0; api.then(function $$then(done){ setTimeout(function $$set$timeout(){ done.fail.apply(ø,args); },num); }); return api; }; }); ASQ.failAfter = function $$fail$after() { return ASQ().failAfter.apply(ø,arguments); }; // "first" ASQ.extend("first",function $$extend(api,internals){ return function $$first() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { error_messages.length = 0; } function success(trigger,idx,args) { if (!finished) { finished = true; // first successful segment triggers // main sequence to proceed as success trigger( args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ); reset(); } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete without success? if (completed === fns.length) { finished = true; // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); reset(); } } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "go-style CSP" "use strict"; (function IIFE() { // filter out already-resolved queue entries function filterResolved(queue) { return queue.filter(function $$filter(entry) { return !entry.resolved; }); } function closeQueue(queue, finalValue) { queue.forEach(function $$each(iter) { if (!iter.resolved) { iter.next(); iter.next(finalValue); } }); queue.length = 0; } function channel(bufSize) { var ch = { close: function $$close() { ch.closed = true; closeQueue(ch.put_queue, false); closeQueue(ch.take_queue, ASQ.csp.CLOSED); }, closed: false, messages: [], put_queue: [], take_queue: [], buffer_size: +bufSize || 0 }; return ch; } function unblock(iter) { if (iter && !iter.resolved) { iter.next(iter.next().value); } } function put(channel, value) { var ret; if (channel.closed) { return false; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate put? if (channel.messages.length < channel.buffer_size) { channel.messages.push(value); unblock(channel.take_queue.shift()); return true; } // queued put else { channel.put_queue.push( // make a notifiable iterable for 'put' blocking ASQ.iterable().then(function $$then() { if (!channel.closed) { channel.messages.push(value); return true; } else { return false; } })); // wrap a sequence/promise around the iterable ret = ASQ(channel.put_queue[channel.put_queue.length - 1]); // take waiting on this queued put? if (channel.take_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return ret; } } function putAsync(channel, value, cb) { var ret = ASQ(put(channel, value)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function take(channel) { var ret; try { ret = takem(channel); } catch (err) { ret = err; } if (ASQ.isSequence(ret)) { ret.pCatch(function $$pcatch(err) { return err; }); } return ret; } function takeAsync(channel, cb) { var ret = ASQ(take(channel)); if (cb && typeof cb == "function") { ret.val(cb); } else { return ret; } } function takem(channel) { var msg; if (channel.closed) { return ASQ.csp.CLOSED; } // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); // immediate take? if (channel.messages.length > 0) { msg = channel.messages.shift(); unblock(channel.put_queue.shift()); if (msg instanceof Error) { throw msg; } return msg; } // queued take else { channel.take_queue.push( // make a notifiable iterable for 'take' blocking ASQ.iterable().then(function $$then() { if (!channel.closed) { var v = channel.messages.shift(); if (v instanceof Error) { throw v; } return v; } else { return ASQ.csp.CLOSED; } })); // wrap a sequence/promise around the iterable msg = ASQ(channel.take_queue[channel.take_queue.length - 1]); // put waiting on this take? if (channel.put_queue.length > 0) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } return msg; } } function takemAsync(channel, cb) { var ret = ASQ(takem(channel)); if (cb && typeof cb == "function") { ret.pThen(cb, cb); } else { return ret.val(function $$val(v) { if (v instanceof Error) { throw v; } return v; }); } } function alts(actions) { var closed, open, handlers, i, isq, ret, resolved = false; // used `alts(..)` incorrectly? if (!Array.isArray(actions) || actions.length == 0) { throw Error("Invalid usage"); } closed = []; open = []; handlers = []; // separate actions by open/closed channel status actions.forEach(function $$each(action) { var channel = Array.isArray(action) ? action[0] : action; // remove already-resolved entries channel.put_queue = filterResolved(channel.put_queue); channel.take_queue = filterResolved(channel.take_queue); if (channel.closed) { closed.push(channel); } else { open.push(action); } }); // if no channels are still open, we're done if (open.length == 0) { return { value: ASQ.csp.CLOSED, channel: closed }; } // can any channel action be executed immediately? for (i = 0; i < open.length; i++) { // put action if (Array.isArray(open[i])) { // immediate put? if (open[i][0].messages.length < open[i][0].buffer_size) { return { value: put(open[i][0], open[i][1]), channel: open[i][0] }; } } // immediate take? else if (open[i].messages.length > 0) { return { value: take(open[i]), channel: open[i] }; } } isq = ASQ.iterable(); var ret = ASQ(isq); // setup channel action handlers for (i = 0; i < open.length; i++) { (function iteration(action, channel, value) { // put action? if (Array.isArray(action)) { channel = action[0]; value = action[1]; // define put handler handlers.push(ASQ.iterable().then(function $$then() { resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler) { return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { channel.messages.push(value); isq.next({ value: true, channel: channel }); } // channel already closed? else { isq.next({ value: false, channel: channel }); } })); // queue up put handler channel.put_queue.push(handlers[handlers.length - 1]); // take waiting on this queued put? if (channel.take_queue.length > 0) { schedule(function handleUnblocking() { if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } }, 0); } } // take action? else { channel = action; // define take handler handlers.push(ASQ.iterable().then(function $$then() { resolved = true; // mark all handlers across this `alts(..)` as resolved now handlers = handlers.filter(function $$filter(handler) { return !(handler.resolved = true); }); // channel still open? if (!channel.closed) { isq.next({ value: channel.messages.shift(), channel: channel }); } // channel already closed? else { isq.next({ value: ASQ.csp.CLOSED, channel: channel }); } })); // queue up take handler channel.take_queue.push(handlers[handlers.length - 1]); // put waiting on this queued take? if (channel.put_queue.length > 0) { schedule(function handleUnblocking() { if (!resolved) { unblock(channel.put_queue.shift()); unblock(channel.take_queue.shift()); } }); } } })(open[i]); } return ret; } function altsAsync(chans, cb) { var ret = ASQ(alts(channel)); if (cb && typeof cb == "function") { ret.pThen(cb, cb); } else { return ret; } } function timeout(delay) { var ch = channel(); setTimeout(ch.close, delay); return ch; } function go(gen, args) { // goroutine arguments passed? if (arguments.length > 1) { if (!args || !Array.isArray(args)) { args = [args]; } } else { args = []; } return regeneratorRuntime.mark(function $$go(token) { var unblock, ret, msg, err, type, done, it; return regeneratorRuntime.wrap(function $$go$(context$3$0) { while (1) switch (context$3$0.prev = context$3$0.next) { case 0: unblock = function unblock() { if (token.block && !token.block.marked) { token.block.marked = true; token.block.next(); } }; done = false; // keep track of how many goroutines are running // so we can infer when we're done go'ing token.go_count = (token.go_count || 0) + 1; // need to initialize a set of goroutines? if (token.go_count === 1) { // create a default channel for these goroutines token.channel = channel(); token.channel.messages = token.messages; token.channel.go = function $$go() { // unblock the goroutine handling for these // new goroutine(s)? unblock(); // add the goroutine(s) to the handling queue token.add(go.apply(ø, arguments)); }; // starting out with initial channel messages? if (token.channel.messages.length > 0) { // fake back-pressure blocking for each token.channel.put_queue = token.channel.messages.map(function $$map() { // make a notifiable iterable for 'put' blocking return ASQ.iterable().then(function $$then() { unblock(token.channel.take_queue.shift()); return !token.channel.closed; }); }); } } // initialize the generator it = gen.apply(ø, [token.channel].concat(args)); (function iterate() { function next() { // keep going with next step in goroutine? if (!done) { iterate(); } // unblock overall goroutine handling to // continue with other goroutines else { unblock(); } } // has a resumption value been achieved yet? if (!ret) { // try to resume the goroutine try { // resume with injected exception? if (err) { ret = it["throw"](err); err = null; } // resume normally else { ret = it.next(msg); } } // resumption failed, so bail catch (e) { done = true; err = e; msg = null; unblock(); return; } // keep track of the result of the resumption done = ret.done; ret = ret.value; type = typeof ret; // if this goroutine is complete, unblock the // overall goroutine handling if (done) { unblock(); } // received a thenable/promise back? if (isPromise(ret)) { ret = ASQ().promise(ret); } // wait for the value? if (ASQ.isSequence(ret)) { ret.val(function $$val() { ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0]; next(); }).or(function $$or() { ret = null; msg = arguments.length > 1 ? ASQ.messages.apply(ø, arguments) : arguments[0]; if (msg instanceof Error) { err = msg; msg = null; } next(); }); } // immediate value, prepare it to go right back in else { msg = ret; ret = null; next(); } } })(); // keep this goroutine alive until completion case 6: if (done) { context$3$0.next = 15; break; } context$3$0.next = 9; return token; case 9: if (!(!done && !token.block)) { context$3$0.next = 13; break; } context$3$0.next = 12; return token.block = ASQ.iterable(); case 12: token.block = false; case 13: context$3$0.next = 6; break; case 15: // this goroutine is done now token.go_count--; // all goroutines done? if (token.go_count === 0) { // any lingering blocking need to be cleaned up? unblock(); // capture any untaken messages msg = ASQ.messages.apply(ø, token.messages); // need to implicitly force-close channel? if (token.channel && !token.channel.closed) { token.channel.closed = true; token.channel.put_queue.length = token.channel.take_queue.length = 0; token.channel.close = token.channel.go = token.channel.messages = null; } token.channel = null; } // make sure leftover error or message are // passed along if (!err) { context$3$0.next = 21; break; } throw err; case 21: if (!(token.go_count === 0)) { context$3$0.next = 25; break; } return context$3$0.abrupt("return", msg); case 25: return context$3$0.abrupt("return", token); case 26: case "end": return context$3$0.stop(); } }, $$go, this); }); } ASQ.csp = { chan: channel, put: put, putAsync: putAsync, take: take, takeAsync: takeAsync, takem: takem, takemAsync: takemAsync, alts: alts, altsAsync: altsAsync, timeout: timeout, go: go, CLOSED: {} }; })(); // unblock the overall goroutine handling // transfer control to another goroutine // need to block overall goroutine handling // while idle? // wait here while idle// "ASQ.iterable()" "use strict"; (function IIFE() { var template; ASQ.iterable = function $$iterable() { function throwSequenceErrors() { throw sequence_errors.length === 1 ? sequence_errors[0] : sequence_errors; } function notifyErrors() { var fn; seq_tick = null; if (seq_error) { if (or_queue.length === 0 && !error_reported) { error_reported = true; throwSequenceErrors(); } while (or_queue.length > 0) { error_reported = true; fn = or_queue.shift(); try { fn.apply(ø, sequence_errors); } catch (err) { if (checkBranding(err)) { sequence_errors = sequence_errors.concat(err); } else { sequence_errors.push(err); } if (or_queue.length === 0) { throwSequenceErrors(); } } } } } function val() { if (seq_error || seq_aborted || arguments.length === 0) { return sequence_api; } var args = ARRAY_SLICE.call(arguments).map(function mapper(arg) { if (typeof arg != "function") return function $$val() { return arg; };else return arg; }); val_queue.push.apply(val_queue, args); return sequence_api; } function or() { if (seq_aborted || arguments.length === 0) { return sequence_api; } or_queue.push.apply(or_queue, arguments); if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function pipe() { if (seq_aborted || arguments.length === 0) { return sequence_api; } ARRAY_SLICE.call(arguments).forEach(function $$each(fn) { val(fn).or(fn.fail); }); return sequence_api; } function next() { if (seq_error || seq_aborted || val_queue.length === 0) { if (val_queue.length > 0) { $throw$("Sequence cannot be iterated"); } return { done: true }; } try { return { value: val_queue.shift().apply(ø, arguments) }; } catch (err) { if (ASQ.isMessageWrapper(err)) { $throw$.apply(ø, err); } else { $throw$(err); } return {}; } } function $throw$() { if (seq_error || seq_aborted) { return sequence_api; } sequence_errors.push.apply(sequence_errors, arguments); seq_error = true; if (!seq_tick) { seq_tick = schedule(notifyErrors); } return sequence_api; } function $return$(val) { if (seq_error || seq_aborted) { val = void 0; } abort(); return { done: true, value: val }; } function abort() { if (seq_error || seq_aborted) { return; } seq_aborted = true; clearTimeout(seq_tick); seq_tick = null; val_queue.length = or_queue.length = sequence_errors.length = 0; } function duplicate() { var isq; template = { val_queue: val_queue.slice(), or_queue: or_queue.slice() }; isq = ASQ.iterable(); template = null; return isq; } // opt-out of global error reporting for this sequence function defer() { or_queue.push(function $$ignored() {}); return sequence_api; } // *********************************************** // Object branding utilities // *********************************************** function brandIt(obj) { Object.defineProperty(obj, brand, { enumerable: false, value: true }); return obj; } var sequence_api, seq_error = false, error_reported = false, seq_aborted = false, seq_tick, val_queue = [], or_queue = [], sequence_errors = []; // *********************************************** // Setup the ASQ.iterable() public API // *********************************************** sequence_api = brandIt({ val: val, then: val, or: or, pipe: pipe, next: next, "throw": $throw$, "return": $return$, abort: abort, duplicate: duplicate, defer: defer }); // useful for ES6 `for..of` loops, // add `@@iterator` to simply hand back // our iterable sequence itself! sequence_api[typeof Symbol == "function" && Symbol.iterator || "@@iterator"] = function $$iter() { return sequence_api; }; // templating the iterable-sequence setup? if (template) { val_queue = template.val_queue.slice(0); or_queue = template.or_queue.slice(0); } // treat ASQ.iterable() constructor parameters as having been // passed to `val()` sequence_api.val.apply(ø, arguments); return sequence_api; }; })();// "last" ASQ.extend("last",function $$extend(api,internals){ return function $$last() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages = null; } function complete(trigger) { if (success_messages != null) { // last successful segment's message(s) sent // to main sequence to proceed as success trigger( success_messages.length > 1 ? ASQ.messages.apply(ø,success_messages) : success_messages[0] ); } else { // send errors into main sequence error_messages.length = fns.length; trigger.fail.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages = args; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "map" ASQ.extend("map",function $$extend(api,internals){ return function $$map(pArr,pEach) { if (internals("seq_error") || internals("seq_aborted")) { return api; } api.seq(function $$seq(){ var tmp, args = ARRAY_SLICE.call(arguments), arr = pArr, each = pEach; // if missing `map(..)` args, use value-messages (if any) if (!each) each = args.shift(); if (!arr) arr = args.shift(); // if arg types in reverse order (each,arr), swap if (typeof arr === "function" && Array.isArray(each)) { tmp = arr; arr = each; each = tmp; } return ASQ.apply(ø,args) .gate.apply(ø,arr.map(function $$map(item){ return function $$segment(){ each.apply(ø,[item].concat(ARRAY_SLICE.call(arguments))); }; })); }) .val(function $$val(){ // collect all gate segment output into one value-message // Note: return a normal array here, not a message wrapper! return ARRAY_SLICE.call(arguments); }); return api; }; }); // "none" ASQ.extend("none",function $$extend(api,internals){ return function $$none() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ function reset() { finished = true; error_messages.length = 0; success_messages.length = 0; } function complete(trigger) { if (success_messages.length > 0) { // any successful segment's message(s) sent // to main sequence to proceed as **error** success_messages.length = fns.length; trigger.fail.apply(ø,success_messages); } else { // send errors as **success** to main sequence error_messages.length = fns.length; trigger.apply(ø,error_messages); } reset(); } function success(trigger,idx,args) { if (!finished) { completed++; success_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; // all segments complete? if (completed === fns.length) { finished = true; complete(trigger); } } } function failure(trigger,idx,args) { if (!finished && !(idx in error_messages) ) { completed++; error_messages[idx] = args.length > 1 ? ASQ.messages.apply(ø,args) : args[0] ; } // all segments complete? if (!finished && completed === fns.length ) { finished = true; complete(trigger); } } var completed = 0, error_messages = [], finished = false, sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)), success_messages = [] ; wrapGate(sq,fns,success,failure,reset); sq.pipe(done); }); return api; }; }); // "pThen" ASQ.extend("pThen",function $$extend(api,internals){ return function $$pthen(success,failure) { if (internals("seq_aborted")) { return api; } var ignore_success_handler = false, ignore_failure_handler = false; if (typeof success === "function") { api.then(function $$then(done){ if (!ignore_success_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments); msgs.shift(); if (msgs.length === 1) { msgs = msgs[0]; } ignore_failure_handler = true; try { ret = success(msgs); } catch (err) { if (!ASQ.isMessageWrapper(err)) { err = [err]; } done.fail.apply(ø,err); return; } // returned a sequence? if (ASQ.isSequence(ret)) { ret.pipe(done); } // returned a message wrapper? else if (ASQ.isMessageWrapper(ret)) { done.apply(ø,ret); } // returned a promise/thenable? else if (isPromise(ret)) { ret.then(done,done.fail); } // just a normal value to pass along else { done(ret); } } else { done.apply(ø,ARRAY_SLICE.call(arguments,1)); } }); } if (typeof failure === "function") { api.or(function $$or(){ if (!ignore_failure_handler) { var ret, msgs = ASQ.messages.apply(ø,arguments), smgs, or_queue = ARRAY_SLICE.call(internals("or_queue")) ; if (msgs.length === 1) { msgs = msgs[0]; } ignore_success_handler = true; // NOTE: if this call throws, that'll automatically // be handled by core as we'd want it to be ret = failure(msgs); // if we get this far: // first, inject return value (if any) as // next step's sequence messages smgs = internals("sequence_messages"); smgs.length = 0; if (typeof ret !== "undefined") { if (!ASQ.isMessageWrapper(ret)) { ret = [ret]; } smgs.push.apply(smgs,ret); } // reset internal error state, because we've exclusively // handled any errors up to this point of the sequence internals("sequence_errors").length = 0; internals("seq_error",false); internals("then_ready",true); // temporarily empty the or-queue internals("or_queue").length = 0; // make sure to schedule success-procession on the chain api.val(function $$val(){ // pass thru messages return ASQ.messages.apply(ø,arguments); }); // at next cycle, reinstate the or-queue (if any) if (or_queue.length > 0) { schedule(function $$schedule(){ api.or.apply(ø,or_queue); }); } } }); } return api; }; }); // "pCatch" ASQ.extend("pCatch",function $$extend(api,internals){ return function $$pcatch(failure) { if (internals("seq_aborted")) { return api; } api.pThen(void 0,failure); return api; }; }); // "race" ASQ.extend("race",function $$extend(api,internals){ return function $$race() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(v){ var def; // tap any directly-provided sequences immediately if (ASQ.isSequence(v)) { def = { seq: v }; tapSequence(def); return function $$fn(done) { def.seq.pipe(done); }; } else return v; }); api.then(function $$then(done){ var args = ARRAY_SLICE.call(arguments); fns.forEach(function $$each(fn){ fn.apply(ø,args); }); }); return api; }; }); // "react" (reactive sequences) ASQ.react = function $$react(reactor) { function next() { if (template) { var sq = template.duplicate(); sq.unpause.apply(ø,arguments); return sq; } return ASQ(function $$asq(){ throw "Disabled Sequence"; }); } function registerTeardown(fn) { if (template && typeof fn === "function") { teardowns.push(fn); } } var template = ASQ().duplicate(), teardowns = [] ; // add reactive sequence kill switch template.stop = function $$stop() { if (template) { template = null; teardowns.forEach(Function.call,Function.call); teardowns.length = 0; } }; next.onStream = function $$onStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.on("data",next); stream.on("error",next); }); }; next.unStream = function $$unStream() { ARRAY_SLICE.call(arguments) .forEach(function $$each(stream){ stream.removeListener("data",next); stream.removeListener("error",next); }); }; // make sure `reactor(..)` is called async ASQ.__schedule(function $$schedule(){ reactor.call(template,next,registerTeardown); }); return template; }; // "react" helpers (function IIFE(){ function tapSequences() { function tapSequence(seq) { // temporary `trigger` which, if called before being replaced // below, creates replacement proxy sequence with the // event message(s) re-fired function trigger() { var args = ARRAY_SLICE.call(arguments); def.seq = ASQ.react(function $$react(next){ next.apply(ø,args); }); } if (ASQ.isSequence(seq)) { var def = { seq: seq }; // listen for events from the sequence-stream seq.val(function $$val(){ trigger.apply(ø,arguments); return ASQ.messages.apply(ø,arguments); }); // make a reactive sequence to act as a proxy to the original // sequence def.seq = ASQ.react(function $$react(next){ // replace the temporary trigger (created above) // with this proxy's trigger trigger = next; }); return def; } } return ARRAY_SLICE.call(arguments) .map(tapSequence) .filter(Boolean); } function createReactOperator(buffer) { return function $$react$operator(){ function reactor(next,registerTeardown){ function processSequence(def) { // sequence-stream event listener function trigger() { var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // store event message(s), if any seq_events[seq_id] = [].concat( buffer ? seq_events[seq_id] : [], args.length > 0 ? [args] : undefined ); // collect event message(s) across the // sequence-stream sources var messages = seq_events.reduce(function reducer(msgs,eventList,idx){ if (eventList.length > 0) msgs.push(eventList[0]); return msgs; },[]); // did all sequence-streams get an event? if (messages.length == seq_events.length) { if (messages.length == 1) messages = messages[0]; // fire off reactive sequence instance next.apply(ø,messages); // discard stored event message(s) seq_events.forEach(function $$each(eventList){ eventList.shift(); }); } } // keep sequence going return args; } var seq_id = seq_events.length; seq_events.push([]); def.seq.val(trigger); } // process all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = seq_events = null; }); } var seq_events = [], // observe all sequence-streams seqs = tapSequences.apply(null,arguments) ; if (seqs.length == 0) return; return ASQ.react(reactor); }; } ASQ.react.all = ASQ.react.zip = createReactOperator(/*buffer=*/true); ASQ.react.latest = ASQ.react.combine = createReactOperator(/*buffer=false*/); ASQ.react.any = ASQ.react.merge = function $$react$any(){ function reactor(next,registerTeardown){ function processSequence(def){ function trigger(){ var args = ASQ.messages.apply(ø,arguments); // still observing sequence-streams? if (seqs && seqs.length > 0) { // fire off reactive sequence instance next.apply(ø,args); } // keep sequence going return args; } // sequence-stream event listener def.seq.val(trigger); } // observe all sequence-streams seqs.forEach(processSequence); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ seqs = null; }); } // observe all sequence-streams var seqs = tapSequences.apply(null,arguments); if (seqs.length == 0) return; return ASQ.react(reactor); }; ASQ.react.distinct = function $$react$distinct(seq){ function filterer() { function isDuplicate(msgs) { return ( msgs.length == messages.length && msgs.every(function $$every(val,idx){ return val === messages[idx]; }) ); } var messages = ASQ.messages.apply(ø,arguments); // any messages to check against? if (messages.length > 0) { // messages already sent before? if (prev_messages.some(isDuplicate)) { // bail on duplicate messages return false; } // save messages for future distinct checking prev_messages.push(messages); } // allow distinct non-duplicate value through return true; } var prev_messages = []; return ASQ.react.filter(seq,filterer); }; ASQ.react.filter = function $$react$filter(seq,filterer){ function reactor(next,registerTeardown) { function trigger(){ var messages = ASQ.messages.apply(ø,arguments); if (filterer && filterer.apply(ø,messages)) { // fire off reactive sequence instance next.apply(ø,messages); } // keep sequence going return messages; } // sequence-stream event listener def.seq.val(trigger); // listen for stop() of reactive sequence registerTeardown(function $$teardown(){ def = filterer = null; }); } // observe sequence-stream var def = tapSequences(seq)[0]; if (!def) return; return ASQ.react(reactor); }; ASQ.react.fromObservable = function $$react$from$observable(obsv){ function reactor(next,registerTeardown){ // process buffer (if any) buffer.forEach(next); buffer.length = 0; // start non-buffered notifications? if (!buffer.complete) { notify = next; } registerTeardown(function $$teardown(){ obsv.dispose(); }); } function notify(v) { buffer.push(v); } var buffer = []; obsv.subscribe( function $$on$next(v){ notify(v); }, function $$on$error(){}, function $$on$complete(){ buffer.complete = true; obsv.dispose(); } ); return ASQ.react(reactor); }; ASQ.extend("toObservable",function $$extend(api,internals){ return function $$to$observable(){ function init(observer) { function define(pair){ function listen(){ var args = ASQ.messages.apply(ø,arguments); observer[pair[1]].apply(observer, args.length == 1 ? [args[0]] : args ); return args; } api[pair[0]](listen); } [["val","onNext"],["or","onError"]] .forEach(define); } return Rx.Observable.create(init); }; }); })(); // "runner" ASQ.extend("runner",function $$extend(api,internals){ return function $$runner() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var args = ARRAY_SLICE.call(arguments); api .then(function $$then(mainDone){ function wrap(v) { // function? expected to produce an iterator // (like a generator) or a promise if (typeof v === "function") { // call function passing in the control token // note: neutralize `this` in call to prevent // unexpected behavior v = v.call(ø,next_val); // promise returned (ie, from async function)? if (isPromise(v)) { // wrap it in iterable sequence v = ASQ.iterable(v); } } // an iterable sequence? duplicate it (in case of multiple runs) else if (ASQ.isSequence(v) && "next" in v) { v = v.duplicate(); } // wrap anything else in iterable sequence else { v = ASQ.iterable(v); } // a sequence to tap for errors? if (ASQ.isSequence(v)) { // listen for any sequence failures v.or(function $$or(){ // signal iteration-error mainDone.fail.apply(ø,arguments); }); } return v; } function addWrapped() { iterators.push.apply( iterators, ARRAY_SLICE.call(arguments).map(wrap) ); } var iterators = args, token = { messages: ARRAY_SLICE.call(arguments,1), add: addWrapped }, iter, ret, next_val = token ; // map co-routines to round-robin list of iterators iterators = iterators.map(wrap); // async iteration of round-robin list (function iterate(){ // get next co-routine in list iter = iterators.shift(); // process the iteration try { // multiple messages to send to an iterable // sequence? if (ASQ.isMessageWrapper(next_val) && ASQ.isSequence(iter) ) { ret = iter.next.apply(iter,next_val); } else { ret = iter.next(next_val); } } catch (err) { return mainDone.fail(err); } // bail on run in aborted sequence if (internals("seq_aborted")) return; // was the control token yielded? if (ret.value === token) { // round-robin: put co-routine back into the list // at the end where it was so it can be processed // again on next loop-iteration iterators.push(iter); next_val = token; schedule(iterate); // async recurse } else { // not a recognized ASQ instance returned? if (!ASQ.isSequence(ret.value)) { // received a thenable/promise back? if (isPromise(ret.value)) { // wrap in a sequence ret.value = ASQ().promise(ret.value); } // thunk yielded? else if (typeof ret.value === "function") { // wrap thunk call in a sequence var fn = ret.value; ret.value = ASQ(function $$ASQ(done){ fn(done.errfcb); }); } // message wrapper returned? else if (ASQ.isMessageWrapper(ret.value)) { // wrap message(s) in a sequence ret.value = ASQ.apply(ø, // don't let `apply(..)` discard an empty message // wrapper! instead, pass it along as its own value // itself. ret.value.length > 0 ? ret.value : ASQ.messages(undefined) ); } // non-undefined value returned? else if (typeof ret.value !== "undefined") { // wrap the value in a sequence ret.value = ASQ(ret.value); } else { // make an empty sequence ret.value = ASQ(); } } ret.value .val(function $$val(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; if (arguments.length > 0) { // save any return messages for input // to next iteration next_val = arguments.length > 1 ? ASQ.messages.apply(ø,arguments) : arguments[0] ; } // still more to iterate? if (!ret.done) { // was the control token passed along? if (next_val === token) { // round-robin: put co-routine back into the list // at the end, so that the the next iterator can be // processed on next loop-iteration iterators.push(iter); } else { // put co-routine back in where it just // was so it can be processed again on // next loop-iteration iterators.unshift(iter); } } // still have some co-routine runs to process? if (iterators.length > 0) { iterate(); // async recurse } // all done! else { // previous value message? if (typeof next_val !== "undefined") { // not a message wrapper array? if (!ASQ.isMessageWrapper(next_val)) { // wrap value for the subsequent `apply(..)` next_val = [next_val]; } } else { // nothing to affirmatively pass along next_val = []; } // signal done with all co-routine runs mainDone.apply(ø,next_val); } }) .or(function $$or(){ // bail on run in aborted sequence if (internals("seq_aborted")) return; try { // if an error occurs in the step-continuation // promise or sequence, throw it back into the // generator or iterable-sequence iter["throw"].apply(iter,arguments); } catch (err) { // if an error comes back out of after the throw, // pass it out to the main sequence, as iteration // must now be complete mainDone.fail(err); } }); } })(); }); return api; }; }); // "toPromise" ASQ.extend("toPromise",function $$extend(api,internals){ return function $$to$promise() { return new Promise(function $$executor(resolve,reject){ api .val(function $$val(){ var args = ARRAY_SLICE.call(arguments); resolve.call(ø,args.length > 1 ? args : args[0]); return ASQ.messages.apply(ø,args); }) .or(function $$or(){ var args = ARRAY_SLICE.call(arguments); reject.call(ø,args.length > 1 ? args : args[0]); }); }); }; }); // "try" ASQ.extend("try",function $$extend(api,internals){ return function $$try() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ fn.apply(ø,arguments); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ var msgs = ASQ.messages.apply(ø,arguments); // failed, so map error(s) as `catch` mainDone({ "catch": msgs.length > 1 ? msgs : msgs[0] }); }); }; }); api.then.apply(ø,fns); return api; }; }); // "until" ASQ.extend("until",function $$extend(api,internals){ return function $$until() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments) .map(function $$map(fn){ return function $$then(mainDone) { var main_args = ARRAY_SLICE.call(arguments), sq = ASQ.apply(ø,main_args.slice(1)) ; sq .then(function $$inner$then(){ var args = ARRAY_SLICE.call(arguments); args[0]["break"] = function $$break(){ mainDone.fail.apply(ø,arguments); sq.abort(); }; fn.apply(ø,args); }) .val(function $$val(){ mainDone.apply(ø,arguments); }) .or(function $$inner$or(){ // failed, retry $$then.apply(ø,main_args); }); }; }); api.then.apply(ø,fns); return api; }; }); // "waterfall" ASQ.extend("waterfall",function $$extend(api,internals){ return function $$waterfall() { if (internals("seq_error") || internals("seq_aborted") || arguments.length === 0 ) { return api; } var fns = ARRAY_SLICE.call(arguments); api.then(function $$then(done){ var msgs = ASQ.messages(), sq = ASQ.apply(ø,ARRAY_SLICE.call(arguments,1)) ; fns.forEach(function $$each(fn){ sq.then(fn) .val(function $$val(){ var args = ASQ.messages.apply(ø,arguments); msgs.push(args.length > 1 ? args : args[0]); return msgs; }); }); sq.pipe(done); }); return api; }; }); // "wrap" ASQ.wrap = function $$wrap(fn,opts) { function checkThis(t,o) { return (!t || (typeof window != "undefined" && t === window) || (typeof global != "undefined" && t === global) ) ? o : t; } var errfcb, params_first, act, this_obj; opts = (opts && typeof opts == "object") ? opts : {}; if ( (opts.errfcb && opts.splitcb) || (opts.errfcb && opts.simplecb) || (opts.splitcb && opts.simplecb) || ("errfcb" in opts && !opts.errfcb && !opts.splitcb && !opts.simplecb) || (opts.params_first && opts.params_last) ) { throw Error("Invalid options"); } // initialize default flags this_obj = (opts["this"] && typeof opts["this"] == "object") ? opts["this"] : ø; errfcb = opts.errfcb || !(opts.splitcb || opts.simplecb); params_first = !!opts.params_first || (!opts.params_last && !("params_first" in opts || opts.params_first)) || ("params_last" in opts && !opts.params_first && !opts.params_last) ; if (params_first) { act = "push"; } else { act = "unshift"; } if (opts.gen) { return function $$wrapped$gen() { return ASQ.apply(ø,arguments).runner(fn); }; } if (errfcb) { return function $$wrapped$errfcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done.errfcb); fn.apply(_this,args); }); }; } if (opts.splitcb) { return function $$wrapped$splitcb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done,done.fail); fn.apply(_this,args); }); }; } if (opts.simplecb) { return function $$wrapped$simplecb() { var args = ARRAY_SLICE.call(arguments), _this = checkThis(this,this_obj) ; return ASQ(function $$asq(done){ args[act](done); fn.apply(_this,args); }); }; } }; // just return `ASQ` itself for convenience sake return ASQ; });
x112358/cdnjs
ajax/libs/asynquence-contrib/0.13.0/contrib.src.js
JavaScript
mit
50,809
/* * Copyright (C) 2013-2017 Oracle Corporation * This file is based on ast_mode.c * Copyright 2012 Red Hat Inc. * Parts based on xf86-video-ast * Copyright (c) 2005 ASPEED Technology Inc. * * 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, sub license, 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 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 NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * */ /* * Authors: Dave Airlie <airlied@redhat.com> * Michael Thayer <michael.thayer@oracle.com, * Hans de Goede <hdegoede@redhat.com> */ #include <linux/export.h> #include <drm/drm_crtc_helper.h> #include <drm/drm_plane_helper.h> #include "vbox_drv.h" #include "vboxvideo.h" #include "hgsmi_channels.h" static int vbox_cursor_set2(struct drm_crtc *crtc, struct drm_file *file_priv, u32 handle, u32 width, u32 height, s32 hot_x, s32 hot_y); static int vbox_cursor_move(struct drm_crtc *crtc, int x, int y); /** * Set a graphics mode. Poke any required values into registers, do an HGSMI * mode set and tell the host we support advanced graphics functions. */ static void vbox_do_modeset(struct drm_crtc *crtc, const struct drm_display_mode *mode) { struct vbox_crtc *vbox_crtc = to_vbox_crtc(crtc); struct vbox_private *vbox; int width, height, bpp, pitch; u16 flags; s32 x_offset, y_offset; vbox = crtc->dev->dev_private; width = mode->hdisplay ? mode->hdisplay : 640; height = mode->vdisplay ? mode->vdisplay : 480; bpp = crtc->enabled ? CRTC_FB(crtc)->format->cpp[0] * 8 : 32; pitch = crtc->enabled ? CRTC_FB(crtc)->pitches[0] : width * bpp / 8; x_offset = vbox->single_framebuffer ? crtc->x : vbox_crtc->x_hint; y_offset = vbox->single_framebuffer ? crtc->y : vbox_crtc->y_hint; /* * This is the old way of setting graphics modes. It assumed one screen * and a frame-buffer at the start of video RAM. On older versions of * VirtualBox, certain parts of the code still assume that the first * screen is programmed this way, so try to fake it. */ if (vbox_crtc->crtc_id == 0 && crtc->enabled && vbox_crtc->fb_offset / pitch < 0xffff - crtc->y && vbox_crtc->fb_offset % (bpp / 8) == 0) { vbox_write_ioport(VBE_DISPI_INDEX_XRES, width); vbox_write_ioport(VBE_DISPI_INDEX_YRES, height); vbox_write_ioport(VBE_DISPI_INDEX_VIRT_WIDTH, pitch * 8 / bpp); vbox_write_ioport(VBE_DISPI_INDEX_BPP, CRTC_FB(crtc)->format->cpp[0] * 8); vbox_write_ioport(VBE_DISPI_INDEX_ENABLE, VBE_DISPI_ENABLED); vbox_write_ioport( VBE_DISPI_INDEX_X_OFFSET, vbox_crtc->fb_offset % pitch / bpp * 8 + crtc->x); vbox_write_ioport(VBE_DISPI_INDEX_Y_OFFSET, vbox_crtc->fb_offset / pitch + crtc->y); } flags = VBVA_SCREEN_F_ACTIVE; flags |= (crtc->enabled && !vbox_crtc->blanked) ? 0 : VBVA_SCREEN_F_BLANK; flags |= vbox_crtc->disconnected ? VBVA_SCREEN_F_DISABLED : 0; hgsmi_process_display_info(vbox->guest_pool, vbox_crtc->crtc_id, x_offset, y_offset, crtc->x * bpp / 8 + crtc->y * pitch, pitch, width, height, vbox_crtc->blanked ? 0 : bpp, flags); } static int vbox_set_view(struct drm_crtc *crtc) { struct vbox_crtc *vbox_crtc = to_vbox_crtc(crtc); struct vbox_private *vbox = crtc->dev->dev_private; struct vbva_infoview *p; /* * Tell the host about the view. This design originally targeted the * Windows XP driver architecture and assumed that each screen would * have a dedicated frame buffer with the command buffer following it, * the whole being a "view". The host works out which screen a command * buffer belongs to by checking whether it is in the first view, then * whether it is in the second and so on. The first match wins. We * cheat around this by making the first view be the managed memory * plus the first command buffer, the second the same plus the second * buffer and so on. */ p = hgsmi_buffer_alloc(vbox->guest_pool, sizeof(*p), HGSMI_CH_VBVA, VBVA_INFO_VIEW); if (!p) return -ENOMEM; p->view_index = vbox_crtc->crtc_id; p->view_offset = vbox_crtc->fb_offset; p->view_size = vbox->available_vram_size - vbox_crtc->fb_offset + vbox_crtc->crtc_id * VBVA_MIN_BUFFER_SIZE; p->max_screen_size = vbox->available_vram_size - vbox_crtc->fb_offset; hgsmi_buffer_submit(vbox->guest_pool, p); hgsmi_buffer_free(vbox->guest_pool, p); return 0; } static void vbox_crtc_dpms(struct drm_crtc *crtc, int mode) { struct vbox_crtc *vbox_crtc = to_vbox_crtc(crtc); struct vbox_private *vbox = crtc->dev->dev_private; switch (mode) { case DRM_MODE_DPMS_ON: vbox_crtc->blanked = false; break; case DRM_MODE_DPMS_STANDBY: case DRM_MODE_DPMS_SUSPEND: case DRM_MODE_DPMS_OFF: vbox_crtc->blanked = true; break; } mutex_lock(&vbox->hw_mutex); vbox_do_modeset(crtc, &crtc->hwmode); mutex_unlock(&vbox->hw_mutex); } static bool vbox_crtc_mode_fixup(struct drm_crtc *crtc, const struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode) { return true; } /* * Try to map the layout of virtual screens to the range of the input device. * Return true if we need to re-set the crtc modes due to screen offset * changes. */ static bool vbox_set_up_input_mapping(struct vbox_private *vbox) { struct drm_crtc *crtci; struct drm_connector *connectori; struct drm_framebuffer *fb1 = NULL; bool single_framebuffer = true; bool old_single_framebuffer = vbox->single_framebuffer; u16 width = 0, height = 0; /* * Are we using an X.Org-style single large frame-buffer for all crtcs? * If so then screen layout can be deduced from the crtc offsets. * Same fall-back if this is the fbdev frame-buffer. */ list_for_each_entry(crtci, &vbox->dev->mode_config.crtc_list, head) { if (!fb1) { fb1 = CRTC_FB(crtci); if (to_vbox_framebuffer(fb1) == &vbox->fbdev->afb) break; } else if (CRTC_FB(crtci) && fb1 != CRTC_FB(crtci)) { single_framebuffer = false; } } if (single_framebuffer) { list_for_each_entry(crtci, &vbox->dev->mode_config.crtc_list, head) { if (to_vbox_crtc(crtci)->crtc_id != 0) continue; vbox->single_framebuffer = true; vbox->input_mapping_width = CRTC_FB(crtci)->width; vbox->input_mapping_height = CRTC_FB(crtci)->height; return old_single_framebuffer != vbox->single_framebuffer; } } /* Otherwise calculate the total span of all screens. */ list_for_each_entry(connectori, &vbox->dev->mode_config.connector_list, head) { struct vbox_connector *vbox_connector = to_vbox_connector(connectori); struct vbox_crtc *vbox_crtc = vbox_connector->vbox_crtc; width = max_t(u16, width, vbox_crtc->x_hint + vbox_connector->mode_hint.width); height = max_t(u16, height, vbox_crtc->y_hint + vbox_connector->mode_hint.height); } vbox->single_framebuffer = false; vbox->input_mapping_width = width; vbox->input_mapping_height = height; return old_single_framebuffer != vbox->single_framebuffer; } static int vbox_crtc_do_set_base(struct drm_crtc *crtc, struct drm_framebuffer *old_fb, int x, int y) { struct vbox_private *vbox = crtc->dev->dev_private; struct vbox_crtc *vbox_crtc = to_vbox_crtc(crtc); struct drm_gem_object *obj; struct vbox_framebuffer *vbox_fb; struct vbox_bo *bo; int ret; u64 gpu_addr; /* Unpin the previous fb. */ if (old_fb) { vbox_fb = to_vbox_framebuffer(old_fb); obj = vbox_fb->obj; bo = gem_to_vbox_bo(obj); ret = vbox_bo_reserve(bo, false); if (ret) return ret; vbox_bo_unpin(bo); vbox_bo_unreserve(bo); } vbox_fb = to_vbox_framebuffer(CRTC_FB(crtc)); obj = vbox_fb->obj; bo = gem_to_vbox_bo(obj); ret = vbox_bo_reserve(bo, false); if (ret) return ret; ret = vbox_bo_pin(bo, TTM_PL_FLAG_VRAM, &gpu_addr); if (ret) { vbox_bo_unreserve(bo); return ret; } if (&vbox->fbdev->afb == vbox_fb) vbox_fbdev_set_base(vbox, gpu_addr); vbox_bo_unreserve(bo); /* vbox_set_start_address_crt1(crtc, (u32)gpu_addr); */ vbox_crtc->fb_offset = gpu_addr; if (vbox_set_up_input_mapping(vbox)) { struct drm_crtc *crtci; list_for_each_entry(crtci, &vbox->dev->mode_config.crtc_list, head) { vbox_set_view(crtc); vbox_do_modeset(crtci, &crtci->mode); } } return 0; } static int vbox_crtc_mode_set_base(struct drm_crtc *crtc, int x, int y, struct drm_framebuffer *old_fb) { return vbox_crtc_do_set_base(crtc, old_fb, x, y); } static int vbox_crtc_mode_set(struct drm_crtc *crtc, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode, int x, int y, struct drm_framebuffer *old_fb) { struct vbox_private *vbox = crtc->dev->dev_private; int ret; vbox_crtc_mode_set_base(crtc, x, y, old_fb); mutex_lock(&vbox->hw_mutex); ret = vbox_set_view(crtc); if (!ret) vbox_do_modeset(crtc, mode); hgsmi_update_input_mapping(vbox->guest_pool, 0, 0, vbox->input_mapping_width, vbox->input_mapping_height); mutex_unlock(&vbox->hw_mutex); return ret; } static void vbox_crtc_disable(struct drm_crtc *crtc) { } static void vbox_crtc_prepare(struct drm_crtc *crtc) { } static void vbox_crtc_commit(struct drm_crtc *crtc) { } static const struct drm_crtc_helper_funcs vbox_crtc_helper_funcs = { .dpms = vbox_crtc_dpms, .mode_fixup = vbox_crtc_mode_fixup, .mode_set = vbox_crtc_mode_set, /* .mode_set_base = vbox_crtc_mode_set_base, */ .disable = vbox_crtc_disable, .prepare = vbox_crtc_prepare, .commit = vbox_crtc_commit, }; static void vbox_crtc_reset(struct drm_crtc *crtc) { } static void vbox_crtc_destroy(struct drm_crtc *crtc) { drm_crtc_cleanup(crtc); kfree(crtc); } static const struct drm_crtc_funcs vbox_crtc_funcs = { .cursor_move = vbox_cursor_move, .cursor_set2 = vbox_cursor_set2, .reset = vbox_crtc_reset, .set_config = drm_crtc_helper_set_config, /* .gamma_set = vbox_crtc_gamma_set, */ .destroy = vbox_crtc_destroy, }; static struct vbox_crtc *vbox_crtc_init(struct drm_device *dev, unsigned int i) { struct vbox_crtc *vbox_crtc; vbox_crtc = kzalloc(sizeof(*vbox_crtc), GFP_KERNEL); if (!vbox_crtc) return NULL; vbox_crtc->crtc_id = i; drm_crtc_init(dev, &vbox_crtc->base, &vbox_crtc_funcs); drm_mode_crtc_set_gamma_size(&vbox_crtc->base, 256); drm_crtc_helper_add(&vbox_crtc->base, &vbox_crtc_helper_funcs); return vbox_crtc; } static void vbox_encoder_destroy(struct drm_encoder *encoder) { drm_encoder_cleanup(encoder); kfree(encoder); } static struct drm_encoder *vbox_best_single_encoder(struct drm_connector *connector) { int enc_id = connector->encoder_ids[0]; /* pick the encoder ids */ if (enc_id) return drm_encoder_find(connector->dev, enc_id); return NULL; } static const struct drm_encoder_funcs vbox_enc_funcs = { .destroy = vbox_encoder_destroy, }; static void vbox_encoder_dpms(struct drm_encoder *encoder, int mode) { } static bool vbox_mode_fixup(struct drm_encoder *encoder, const struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode) { return true; } static void vbox_encoder_mode_set(struct drm_encoder *encoder, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode) { } static void vbox_encoder_prepare(struct drm_encoder *encoder) { } static void vbox_encoder_commit(struct drm_encoder *encoder) { } static const struct drm_encoder_helper_funcs vbox_enc_helper_funcs = { .dpms = vbox_encoder_dpms, .mode_fixup = vbox_mode_fixup, .prepare = vbox_encoder_prepare, .commit = vbox_encoder_commit, .mode_set = vbox_encoder_mode_set, }; static struct drm_encoder *vbox_encoder_init(struct drm_device *dev, unsigned int i) { struct vbox_encoder *vbox_encoder; vbox_encoder = kzalloc(sizeof(*vbox_encoder), GFP_KERNEL); if (!vbox_encoder) return NULL; drm_encoder_init(dev, &vbox_encoder->base, &vbox_enc_funcs, DRM_MODE_ENCODER_DAC, NULL); drm_encoder_helper_add(&vbox_encoder->base, &vbox_enc_helper_funcs); vbox_encoder->base.possible_crtcs = 1 << i; return &vbox_encoder->base; } /** * Generate EDID data with a mode-unique serial number for the virtual * monitor to try to persuade Unity that different modes correspond to * different monitors and it should not try to force the same resolution on * them. */ static void vbox_set_edid(struct drm_connector *connector, int width, int height) { enum { EDID_SIZE = 128 }; unsigned char edid[EDID_SIZE] = { 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, /* header */ 0x58, 0x58, /* manufacturer (VBX) */ 0x00, 0x00, /* product code */ 0x00, 0x00, 0x00, 0x00, /* serial number goes here */ 0x01, /* week of manufacture */ 0x00, /* year of manufacture */ 0x01, 0x03, /* EDID version */ 0x80, /* capabilities - digital */ 0x00, /* horiz. res in cm, zero for projectors */ 0x00, /* vert. res in cm */ 0x78, /* display gamma (120 == 2.2). */ 0xEE, /* features (standby, suspend, off, RGB, std */ /* colour space, preferred timing mode) */ 0xEE, 0x91, 0xA3, 0x54, 0x4C, 0x99, 0x26, 0x0F, 0x50, 0x54, /* chromaticity for standard colour space. */ 0x00, 0x00, 0x00, /* no default timings */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, /* no standard timings */ 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x06, 0x00, 0x02, 0x02, 0x02, 0x02, /* descriptor block 1 goes below */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* descriptor block 2, monitor ranges */ 0x00, 0x00, 0x00, 0xFD, 0x00, 0x00, 0xC8, 0x00, 0xC8, 0x64, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, /* 0-200Hz vertical, 0-200KHz horizontal, 1000MHz pixel clock */ 0x20, /* descriptor block 3, monitor name */ 0x00, 0x00, 0x00, 0xFC, 0x00, 'V', 'B', 'O', 'X', ' ', 'm', 'o', 'n', 'i', 't', 'o', 'r', '\n', /* descriptor block 4: dummy data */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, /* number of extensions */ 0x00 /* checksum goes here */ }; int clock = (width + 6) * (height + 6) * 60 / 10000; unsigned int i, sum = 0; edid[12] = width & 0xff; edid[13] = width >> 8; edid[14] = height & 0xff; edid[15] = height >> 8; edid[54] = clock & 0xff; edid[55] = clock >> 8; edid[56] = width & 0xff; edid[58] = (width >> 4) & 0xf0; edid[59] = height & 0xff; edid[61] = (height >> 4) & 0xf0; for (i = 0; i < EDID_SIZE - 1; ++i) sum += edid[i]; edid[EDID_SIZE - 1] = (0x100 - (sum & 0xFF)) & 0xFF; drm_mode_connector_update_edid_property(connector, (struct edid *)edid); } static int vbox_get_modes(struct drm_connector *connector) { struct vbox_connector *vbox_connector = NULL; struct drm_display_mode *mode = NULL; struct vbox_private *vbox = NULL; unsigned int num_modes = 0; int preferred_width, preferred_height; vbox_connector = to_vbox_connector(connector); vbox = connector->dev->dev_private; /* * Heuristic: we do not want to tell the host that we support dynamic * resizing unless we feel confident that the user space client using * the video driver can handle hot-plug events. So the first time modes * are queried after a "master" switch we tell the host that we do not, * and immediately after we send the client a hot-plug notification as * a test to see if they will respond and query again. * That is also the reason why capabilities are reported to the host at * this place in the code rather than elsewhere. * We need to report the flags location before reporting the IRQ * capability. */ hgsmi_report_flags_location(vbox->guest_pool, GUEST_HEAP_OFFSET(vbox) + HOST_FLAGS_OFFSET); if (vbox_connector->vbox_crtc->crtc_id == 0) vbox_report_caps(vbox); if (!vbox->initial_mode_queried) { if (vbox_connector->vbox_crtc->crtc_id == 0) { vbox->initial_mode_queried = true; vbox_report_hotplug(vbox); } return drm_add_modes_noedid(connector, 800, 600); } num_modes = drm_add_modes_noedid(connector, 2560, 1600); preferred_width = vbox_connector->mode_hint.width ? vbox_connector->mode_hint.width : 1024; preferred_height = vbox_connector->mode_hint.height ? vbox_connector->mode_hint.height : 768; mode = drm_cvt_mode(connector->dev, preferred_width, preferred_height, 60, false, false, false); if (mode) { mode->type |= DRM_MODE_TYPE_PREFERRED; drm_mode_probed_add(connector, mode); ++num_modes; } vbox_set_edid(connector, preferred_width, preferred_height); drm_object_property_set_value( &connector->base, vbox->dev->mode_config.suggested_x_property, vbox_connector->vbox_crtc->x_hint); drm_object_property_set_value( &connector->base, vbox->dev->mode_config.suggested_y_property, vbox_connector->vbox_crtc->y_hint); return num_modes; } static int vbox_mode_valid(struct drm_connector *connector, struct drm_display_mode *mode) { return MODE_OK; } static void vbox_connector_destroy(struct drm_connector *connector) { drm_connector_unregister(connector); drm_connector_cleanup(connector); kfree(connector); } static enum drm_connector_status vbox_connector_detect(struct drm_connector *connector, bool force) { struct vbox_connector *vbox_connector; vbox_connector = to_vbox_connector(connector); return vbox_connector->mode_hint.disconnected ? connector_status_disconnected : connector_status_connected; } static int vbox_fill_modes(struct drm_connector *connector, u32 max_x, u32 max_y) { struct vbox_connector *vbox_connector; struct drm_device *dev; struct drm_display_mode *mode, *iterator; vbox_connector = to_vbox_connector(connector); dev = vbox_connector->base.dev; list_for_each_entry_safe(mode, iterator, &connector->modes, head) { list_del(&mode->head); drm_mode_destroy(dev, mode); } return drm_helper_probe_single_connector_modes(connector, max_x, max_y); } static const struct drm_connector_helper_funcs vbox_connector_helper_funcs = { .mode_valid = vbox_mode_valid, .get_modes = vbox_get_modes, .best_encoder = vbox_best_single_encoder, }; static const struct drm_connector_funcs vbox_connector_funcs = { .dpms = drm_helper_connector_dpms, .detect = vbox_connector_detect, .fill_modes = vbox_fill_modes, .destroy = vbox_connector_destroy, }; static int vbox_connector_init(struct drm_device *dev, struct vbox_crtc *vbox_crtc, struct drm_encoder *encoder) { struct vbox_connector *vbox_connector; struct drm_connector *connector; vbox_connector = kzalloc(sizeof(*vbox_connector), GFP_KERNEL); if (!vbox_connector) return -ENOMEM; connector = &vbox_connector->base; vbox_connector->vbox_crtc = vbox_crtc; drm_connector_init(dev, connector, &vbox_connector_funcs, DRM_MODE_CONNECTOR_VGA); drm_connector_helper_add(connector, &vbox_connector_helper_funcs); connector->interlace_allowed = 0; connector->doublescan_allowed = 0; drm_mode_create_suggested_offset_properties(dev); drm_object_attach_property(&connector->base, dev->mode_config.suggested_x_property, -1); drm_object_attach_property(&connector->base, dev->mode_config.suggested_y_property, -1); drm_connector_register(connector); drm_mode_connector_attach_encoder(connector, encoder); return 0; } int vbox_mode_init(struct drm_device *dev) { struct vbox_private *vbox = dev->dev_private; struct drm_encoder *encoder; struct vbox_crtc *vbox_crtc; unsigned int i; int ret; /* vbox_cursor_init(dev); */ for (i = 0; i < vbox->num_crtcs; ++i) { vbox_crtc = vbox_crtc_init(dev, i); if (!vbox_crtc) return -ENOMEM; encoder = vbox_encoder_init(dev, i); if (!encoder) return -ENOMEM; ret = vbox_connector_init(dev, vbox_crtc, encoder); if (ret) return ret; } return 0; } void vbox_mode_fini(struct drm_device *dev) { /* vbox_cursor_fini(dev); */ } /** * Copy the ARGB image and generate the mask, which is needed in case the host * does not support ARGB cursors. The mask is a 1BPP bitmap with the bit set * if the corresponding alpha value in the ARGB image is greater than 0xF0. */ static void copy_cursor_image(u8 *src, u8 *dst, u32 width, u32 height, size_t mask_size) { size_t line_size = (width + 7) / 8; u32 i, j; memcpy(dst + mask_size, src, width * height * 4); for (i = 0; i < height; ++i) for (j = 0; j < width; ++j) if (((u32 *)src)[i * width + j] > 0xf0000000) dst[i * line_size + j / 8] |= (0x80 >> (j % 8)); } static int vbox_cursor_set2(struct drm_crtc *crtc, struct drm_file *file_priv, u32 handle, u32 width, u32 height, s32 hot_x, s32 hot_y) { struct vbox_private *vbox = crtc->dev->dev_private; struct vbox_crtc *vbox_crtc = to_vbox_crtc(crtc); struct ttm_bo_kmap_obj uobj_map; size_t data_size, mask_size; struct drm_gem_object *obj; u32 flags, caps = 0; struct vbox_bo *bo; bool src_isiomem; u8 *dst = NULL; u8 *src; int ret; /* * Re-set this regularly as in 5.0.20 and earlier the information was * lost on save and restore. */ hgsmi_update_input_mapping(vbox->guest_pool, 0, 0, vbox->input_mapping_width, vbox->input_mapping_height); if (!handle) { bool cursor_enabled = false; struct drm_crtc *crtci; /* Hide cursor. */ vbox_crtc->cursor_enabled = false; list_for_each_entry(crtci, &vbox->dev->mode_config.crtc_list, head) { if (to_vbox_crtc(crtci)->cursor_enabled) cursor_enabled = true; } if (!cursor_enabled) hgsmi_update_pointer_shape(vbox->guest_pool, 0, 0, 0, 0, 0, NULL, 0); return 0; } vbox_crtc->cursor_enabled = true; if (width > VBOX_MAX_CURSOR_WIDTH || height > VBOX_MAX_CURSOR_HEIGHT || width == 0 || height == 0) return -EINVAL; ret = hgsmi_query_conf(vbox->guest_pool, VBOX_VBVA_CONF32_CURSOR_CAPABILITIES, &caps); if (ret) return ret; if (!(caps & VBOX_VBVA_CURSOR_CAPABILITY_HARDWARE)) { /* * -EINVAL means cursor_set2() not supported, -EAGAIN means * retry at once. */ return -EBUSY; } obj = drm_gem_object_lookup(file_priv, handle); if (!obj) { DRM_ERROR("Cannot find cursor object %x for crtc\n", handle); return -ENOENT; } bo = gem_to_vbox_bo(obj); ret = vbox_bo_reserve(bo, false); if (ret) goto out_unref_obj; /* * The mask must be calculated based on the alpha * channel, one bit per ARGB word, and must be 32-bit * padded. */ mask_size = ((width + 7) / 8 * height + 3) & ~3; data_size = width * height * 4 + mask_size; vbox->cursor_hot_x = min_t(u32, max(hot_x, 0), width); vbox->cursor_hot_y = min_t(u32, max(hot_y, 0), height); vbox->cursor_width = width; vbox->cursor_height = height; vbox->cursor_data_size = data_size; dst = vbox->cursor_data; ret = ttm_bo_kmap(&bo->bo, 0, bo->bo.num_pages, &uobj_map); if (ret) { vbox->cursor_data_size = 0; goto out_unreserve_bo; } src = ttm_kmap_obj_virtual(&uobj_map, &src_isiomem); if (src_isiomem) { DRM_ERROR("src cursor bo not in main memory\n"); ret = -EIO; goto out_unmap_bo; } copy_cursor_image(src, dst, width, height, mask_size); flags = VBOX_MOUSE_POINTER_VISIBLE | VBOX_MOUSE_POINTER_SHAPE | VBOX_MOUSE_POINTER_ALPHA; ret = hgsmi_update_pointer_shape(vbox->guest_pool, flags, vbox->cursor_hot_x, vbox->cursor_hot_y, width, height, dst, data_size); out_unmap_bo: ttm_bo_kunmap(&uobj_map); out_unreserve_bo: vbox_bo_unreserve(bo); out_unref_obj: drm_gem_object_put_unlocked(obj); return ret; } static int vbox_cursor_move(struct drm_crtc *crtc, int x, int y) { struct vbox_private *vbox = crtc->dev->dev_private; u32 flags = VBOX_MOUSE_POINTER_VISIBLE | VBOX_MOUSE_POINTER_SHAPE | VBOX_MOUSE_POINTER_ALPHA; s32 crtc_x = vbox->single_framebuffer ? crtc->x : to_vbox_crtc(crtc)->x_hint; s32 crtc_y = vbox->single_framebuffer ? crtc->y : to_vbox_crtc(crtc)->y_hint; u32 host_x, host_y; u32 hot_x = 0; u32 hot_y = 0; int ret; /* * We compare these to unsigned later and don't * need to handle negative. */ if (x + crtc_x < 0 || y + crtc_y < 0 || vbox->cursor_data_size == 0) return 0; ret = hgsmi_cursor_position(vbox->guest_pool, true, x + crtc_x, y + crtc_y, &host_x, &host_y); /* * The only reason we have vbox_cursor_move() is that some older clients * might use DRM_IOCTL_MODE_CURSOR instead of DRM_IOCTL_MODE_CURSOR2 and * use DRM_MODE_CURSOR_MOVE to set the hot-spot. * * However VirtualBox 5.0.20 and earlier has a bug causing it to return * 0,0 as host cursor location after a save and restore. * * To work around this we ignore a 0, 0 return, since missing the odd * time when it legitimately happens is not going to hurt much. */ if (ret || (host_x == 0 && host_y == 0)) return ret; if (x + crtc_x < host_x) hot_x = min(host_x - x - crtc_x, vbox->cursor_width); if (y + crtc_y < host_y) hot_y = min(host_y - y - crtc_y, vbox->cursor_height); if (hot_x == vbox->cursor_hot_x && hot_y == vbox->cursor_hot_y) return 0; vbox->cursor_hot_x = hot_x; vbox->cursor_hot_y = hot_y; return hgsmi_update_pointer_shape(vbox->guest_pool, flags, hot_x, hot_y, vbox->cursor_width, vbox->cursor_height, vbox->cursor_data, vbox->cursor_data_size); }
jmahler/linux-next
drivers/staging/vboxvideo/vbox_mode.c
C
gpl-2.0
25,976
/*************************************************************************** qgslayoutviewtooladdnodeitem.h -------------------------- Date : October 2017 Copyright : (C) 2017 Nyall Dawson Email : nyall dot dawson at gmail dot com *************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef QGSLAYOUTVIEWTOOLADDNODEITEM_H #define QGSLAYOUTVIEWTOOLADDNODEITEM_H #include "qgis_sip.h" #include "qgis_gui.h" #include "qgslayoutviewtool.h" #include <memory> #include <QAbstractGraphicsShapeItem> /** * \ingroup gui * Layout view tool for adding node based items to a layout. * \since QGIS 3.0 */ class GUI_EXPORT QgsLayoutViewToolAddNodeItem : public QgsLayoutViewTool { Q_OBJECT public: //! Constructs a QgsLayoutViewToolAddNodeItem for the given layout \a view. QgsLayoutViewToolAddNodeItem( QgsLayoutView *view SIP_TRANSFERTHIS ); /** * Returns the item metadata id for items created by the tool. * \see setItemMetadataId() */ int itemMetadataId() const; /** * Sets the item metadata \a metadataId for items created by the tool. * * The \a metadataId associates the current tool behavior with a metadata entry * from QgsLayoutItemGuiRegistry. * * \see itemMetadataId() */ void setItemMetadataId( int metadataId ); void layoutPressEvent( QgsLayoutViewMouseEvent *event ) override; void layoutMoveEvent( QgsLayoutViewMouseEvent *event ) override; void layoutReleaseEvent( QgsLayoutViewMouseEvent *event ) override; void keyPressEvent( QKeyEvent *event ) override; void deactivate() override; signals: /** * Emitted when an item has been created using the tool. */ void createdItem(); private: int mItemMetadataId = -1; //! Rubber band item std::unique_ptr< QAbstractGraphicsShapeItem > mRubberBand; QPolygonF mPolygon; void addNode( QPointF scenePoint ); void moveTemporaryNode( QPointF scenePoint, Qt::KeyboardModifiers modifiers ); void setRubberBandNodes(); }; #endif // QGSLAYOUTVIEWTOOLADDNODEITEM_H
ghtmtt/QGIS
src/gui/layout/qgslayoutviewtooladdnodeitem.h
C
gpl-2.0
2,751
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>lxml.html</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="lxml-module.html">Package&nbsp;lxml</a> :: Package&nbsp;html </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="lxml.html-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== PACKAGE DESCRIPTION ==================== --> <h1 class="epydoc">Package html</h1><p class="nomargin-top"><span class="codelink"><a href="lxml.html-pysrc.html">source&nbsp;code</a></span></p> The <tt class="rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal"><span class="pre">lxml.html</span></tt> tool set for HTML handling. <!-- ==================== SUBMODULES ==================== --> <a name="section-Submodules"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Submodules</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Submodules" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr><td class="summary"> <ul class="nomargin"> <li> <strong class="uidlink"><a href="lxml.html.ElementSoup-module.html">lxml.html.ElementSoup</a></strong>: <em class="summary">Legacy interface to the BeautifulSoup HTML parser.</em> </li> <li class="private"> <strong class="uidlink">lxml.html._dictmixin</strong> </li> <li class="private"> <strong class="uidlink">lxml.html._setmixin</strong> </li> <li> <strong class="uidlink"><a href="lxml.html.builder-module.html">lxml.html.builder</a></strong>: <em class="summary">A set of HTML generator tags for building HTML documents.</em> </li> <li> <strong class="uidlink"><a href="lxml.html.clean-module.html">lxml.html.clean</a></strong>: <em class="summary">A cleanup tool for HTML.</em> </li> <li> <strong class="uidlink"><a href="lxml.html.defs-module.html">lxml.html.defs</a></strong> </li> <li> <strong class="uidlink"><a href="lxml.html.diff-module.html">lxml.html.diff</a></strong> </li> <li> <strong class="uidlink"><a href="lxml.html.formfill-module.html">lxml.html.formfill</a></strong> </li> <li> <strong class="uidlink"><a href="lxml.html.html5parser-module.html">lxml.html.html5parser</a></strong>: <em class="summary">An interface to html5lib.</em> </li> <li> <strong class="uidlink"><a href="lxml.html.soupparser-module.html">lxml.html.soupparser</a></strong>: <em class="summary">External interface to the BeautifulSoup HTML parser.</em> </li> <li> <strong class="uidlink"><a href="lxml.html.usedoctest-module.html">lxml.html.usedoctest</a></strong>: <em class="summary">Doctest module for HTML comparison.</em> </li> </ul></td></tr> </table> <br /> <!-- ==================== CLASSES ==================== --> <a name="section-Classes"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Classes</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Classes" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlMixin-class.html" class="summary-name" onclick="show_private();">HtmlMixin</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html._MethodFunc-class.html" class="summary-name" onclick="show_private();">_MethodFunc</a><br /> An object that represents a method on an element as a function; the function takes either an element or an HTML string. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlComment-class.html" class="summary-name" onclick="show_private();">HtmlComment</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlElement-class.html" class="summary-name" onclick="show_private();">HtmlElement</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlProcessingInstruction-class.html" class="summary-name" onclick="show_private();">HtmlProcessingInstruction</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlEntity-class.html" class="summary-name" onclick="show_private();">HtmlEntity</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HtmlElementClassLookup-class.html" class="summary-name" onclick="show_private();">HtmlElementClassLookup</a><br /> A lookup scheme for HTML Element classes. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.FormElement-class.html" class="summary-name" onclick="show_private();">FormElement</a><br /> Represents a &lt;form&gt; element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.FieldsDict-class.html" class="summary-name" onclick="show_private();">FieldsDict</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.InputGetter-class.html" class="summary-name" onclick="show_private();">InputGetter</a><br /> An accessor that represents all the input fields in a form. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.InputMixin-class.html" class="summary-name" onclick="show_private();">InputMixin</a><br /> Mix-in for all input elements (input, select, and textarea) </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.TextareaElement-class.html" class="summary-name" onclick="show_private();">TextareaElement</a><br /> <tt class="rst-rst-rst-rst-docutils literal rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;textarea&gt;</span></tt> element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.SelectElement-class.html" class="summary-name" onclick="show_private();">SelectElement</a><br /> <tt class="rst-rst-rst-rst-docutils literal rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;select&gt;</span></tt> element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.MultipleSelectOptions-class.html" class="summary-name" onclick="show_private();">MultipleSelectOptions</a><br /> Represents all the selected options in a <tt class="rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;select</span> <span class="pre">multiple&gt;</span></tt> element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.RadioGroup-class.html" class="summary-name" onclick="show_private();">RadioGroup</a><br /> This object represents several <tt class="rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;input</span> <span class="pre">type=radio&gt;</span></tt> elements that have the same name. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.CheckboxGroup-class.html" class="summary-name" onclick="show_private();">CheckboxGroup</a><br /> Represents a group of checkboxes (<tt class="rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;input</span> <span class="pre">type=checkbox&gt;</span></tt>) that have the same name. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.CheckboxValues-class.html" class="summary-name" onclick="show_private();">CheckboxValues</a><br /> Represents the values of the checked checkboxes in a group of checkboxes with the same name. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.InputElement-class.html" class="summary-name" onclick="show_private();">InputElement</a><br /> Represents an <tt class="rst-rst-rst-rst-docutils literal rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;input&gt;</span></tt> element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.LabelElement-class.html" class="summary-name" onclick="show_private();">LabelElement</a><br /> Represents a <tt class="rst-rst-rst-docutils literal rst-rst-docutils literal rst-docutils literal"><span class="pre">&lt;label&gt;</span></tt> element. </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.HTMLParser-class.html" class="summary-name" onclick="show_private();">HTMLParser</a> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html.XHTMLParser-class.html" class="summary-name" onclick="show_private();">XHTMLParser</a> </td> </tr> </table> <!-- ==================== FUNCTIONS ==================== --> <a name="section-Functions"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Functions</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Functions" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="__fix_docstring"></a><span class="summary-sig-name">__fix_docstring</span>(<span class="summary-sig-arg">s</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#__fix_docstring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_unquote_match"></a><span class="summary-sig-name">_unquote_match</span>(<span class="summary-sig-arg">s</span>, <span class="summary-sig-arg">pos</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#_unquote_match">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_transform_result"></a><span class="summary-sig-name">_transform_result</span>(<span class="summary-sig-arg">typ</span>, <span class="summary-sig-arg">result</span>)</span><br /> Convert the result back into the input type.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#_transform_result">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_nons"></a><span class="summary-sig-name">_nons</span>(<span class="summary-sig-arg">tag</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#_nons">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="document_fromstring"></a><span class="summary-sig-name">document_fromstring</span>(<span class="summary-sig-arg">html</span>, <span class="summary-sig-arg">parser</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">**kw</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#document_fromstring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#fragments_fromstring" class="summary-sig-name">fragments_fromstring</a>(<span class="summary-sig-arg">html</span>, <span class="summary-sig-arg">no_leading_text</span>=<span class="summary-sig-default">False</span>, <span class="summary-sig-arg">base_url</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">parser</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">**kw</span>)</span><br /> Parses several HTML elements, returning a list of elements.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#fragments_fromstring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#fragment_fromstring" class="summary-sig-name">fragment_fromstring</a>(<span class="summary-sig-arg">html</span>, <span class="summary-sig-arg">create_parent</span>=<span class="summary-sig-default">False</span>, <span class="summary-sig-arg">base_url</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">parser</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">**kw</span>)</span><br /> Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#fragment_fromstring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#fromstring" class="summary-sig-name">fromstring</a>(<span class="summary-sig-arg">html</span>, <span class="summary-sig-arg">base_url</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">parser</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">**kw</span>)</span><br /> Parse the html, returning a single element/document.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#fromstring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#parse" class="summary-sig-name">parse</a>(<span class="summary-sig-arg">filename_or_url</span>, <span class="summary-sig-arg">parser</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">base_url</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">**kw</span>)</span><br /> Parse a filename, URL, or file-like object into an HTML document tree.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#parse">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_contains_block_level_tag"></a><span class="summary-sig-name">_contains_block_level_tag</span>(<span class="summary-sig-arg">el</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#_contains_block_level_tag">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="_element_name"></a><span class="summary-sig-name">_element_name</span>(<span class="summary-sig-arg">el</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#_element_name">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#submit_form" class="summary-sig-name">submit_form</a>(<span class="summary-sig-arg">form</span>, <span class="summary-sig-arg">extra_values</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">open_http</span>=<span class="summary-sig-default">None</span>)</span><br /> Helper function to submit a form.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#submit_form">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="open_http_urllib"></a><span class="summary-sig-name">open_http_urllib</span>(<span class="summary-sig-arg">method</span>, <span class="summary-sig-arg">url</span>, <span class="summary-sig-arg">values</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#open_http_urllib">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="html_to_xhtml"></a><span class="summary-sig-name">html_to_xhtml</span>(<span class="summary-sig-arg">html</span>)</span><br /> Convert all tags in an HTML tree to XHTML by moving them to the XHTML namespace.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#html_to_xhtml">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="xhtml_to_html"></a><span class="summary-sig-name">xhtml_to_html</span>(<span class="summary-sig-arg">xhtml</span>)</span><br /> Convert all tags in an XHTML tree to HTML by removing their XHTML namespace.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#xhtml_to_html">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="__str_replace_meta_content_type"></a><span class="summary-sig-name">__str_replace_meta_content_type</span>(<span class="summary-sig-arg">...</span>)</span><br /> sub(repl, string[, count = 0]) --&gt; newstring Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#__str_replace_meta_content_type">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="__bytes_replace_meta_content_type"></a><span class="summary-sig-name">__bytes_replace_meta_content_type</span>(<span class="summary-sig-arg">...</span>)</span><br /> sub(repl, string[, count = 0]) --&gt; newstring Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#__bytes_replace_meta_content_type">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#tostring" class="summary-sig-name">tostring</a>(<span class="summary-sig-arg">doc</span>, <span class="summary-sig-arg">pretty_print</span>=<span class="summary-sig-default">False</span>, <span class="summary-sig-arg">include_meta_content_type</span>=<span class="summary-sig-default">False</span>, <span class="summary-sig-arg">encoding</span>=<span class="summary-sig-default">None</span>, <span class="summary-sig-arg">method</span>=<span class="summary-sig-default"><code class="variable-quote">'</code><code class="variable-string">html</code><code class="variable-quote">'</code></span>)</span><br /> Return an HTML string representation of the document.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#tostring">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="open_in_browser"></a><span class="summary-sig-name">open_in_browser</span>(<span class="summary-sig-arg">doc</span>)</span><br /> Open the HTML document in a web browser (saving it to a temporary file to open it).</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#open_in_browser">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="lxml.html-module.html#Element" class="summary-sig-name">Element</a>(<span class="summary-sig-arg">*args</span>, <span class="summary-sig-arg">**kw</span>)</span><br /> Create a new HTML Element.</td> <td align="right" valign="top"> <span class="codelink"><a href="lxml.html-pysrc.html#Element">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> </table> <!-- ==================== VARIABLES ==================== --> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Variables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="XHTML_NAMESPACE"></a><span class="summary-name">XHTML_NAMESPACE</span> = <code title="'http://www.w3.org/1999/xhtml'"><code class="variable-quote">'</code><code class="variable-string">http://www.w3.org/1999/xhtml</code><code class="variable-quote">'</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#_rel_links_xpath" class="summary-name" onclick="show_private();">_rel_links_xpath</a> = <code title="descendant-or-self::a[@rel]|descendant-or-self::x:a[@rel]">descendant-or-self::a[@rel]|descendant-or-s<code class="variable-ellipsis">...</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#_options_xpath" class="summary-name" onclick="show_private();">_options_xpath</a> = <code title="descendant-or-self::option|descendant-or-self::x:option">descendant-or-self::option|descendant-or-self<code class="variable-ellipsis">...</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#_forms_xpath" class="summary-name" onclick="show_private();">_forms_xpath</a> = <code title="descendant-or-self::form|descendant-or-self::x:form">descendant-or-self::form|descendant-or-self::x:<code class="variable-ellipsis">...</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#_class_xpath" class="summary-name" onclick="show_private();">_class_xpath</a> = <code title="descendant-or-self::*[@class and contains(concat(' ', normalize-space(\ @class), ' '), concat(' ', $class_name, ' '))]">descendant-or-self::*[@class and contains(conca<code class="variable-ellipsis">...</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="_id_xpath"></a><span class="summary-name">_id_xpath</span> = <code title="descendant-or-self::*[@id=$id]">descendant-or-self::*[@id=$id]</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="_collect_string_content"></a><span class="summary-name">_collect_string_content</span> = <code title="string()">string()</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#_css_url_re" class="summary-name" onclick="show_private();">_css_url_re</a> = <code title="re.compile(r'(?i)url\((&quot;[^&quot;]*&quot;|\'[^\']*\'|[^\)]*)\)')">re.compile(r'<code class="re-flags">(?i)</code>url\(<code class="re-group">(</code>&quot;<code class="re-group">[^</code>&quot;<code class="re-group">]</code><code class="re-op">*</code>&quot;<code class="re-op">|</code>\'<code class="re-group">[^</code>\'<code class="re-group">]</code><code class="re-op">*</code>\'<code class="re-op">|</code><code class="re-group">[^</code>\)<code class="re-group">]</code><code class="re-op">*</code><code class="variable-ellipsis">...</code></code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="_css_import_re"></a><span class="summary-name">_css_import_re</span> = <code title="re.compile(r'@import &quot;(.*?)&quot;')">re.compile(r'@import &quot;<code class="re-group">(</code>.<code class="re-op">*?</code><code class="re-group">)</code>&quot;')</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="_label_xpath"></a><span class="summary-name">_label_xpath</span> = <code title="//label[@for=$id]|//x:label[@for=$id]">//label[@for=$id]|//x:label[@for=$id]</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="_archive_re"></a><span class="summary-name">_archive_re</span> = <code title="re.compile(r'[^ ]+')">re.compile(r'<code class="re-group">[^</code> <code class="re-group">]</code><code class="re-op">+</code>')</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="find_rel_links"></a><span class="summary-name">find_rel_links</span> = <code title="_MethodFunc('find_rel_links', copy= False)">_MethodFunc('find_rel_links', copy= False)</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="find_class"></a><span class="summary-name">find_class</span> = <code title="_MethodFunc('find_class', copy= False)">_MethodFunc('find_class', copy= False)</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="lxml.html-module.html#make_links_absolute" class="summary-name">make_links_absolute</a> = <code title="_MethodFunc('make_links_absolute', copy= True)">_MethodFunc('make_links_absolute', copy=<code class="variable-ellipsis">...</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="resolve_base_href"></a><span class="summary-name">resolve_base_href</span> = <code title="_MethodFunc('resolve_base_href', copy= True)">_MethodFunc('resolve_base_href', copy= True)</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="iterlinks"></a><span class="summary-name">iterlinks</span> = <code title="_MethodFunc('iterlinks', copy= False)">_MethodFunc('iterlinks', copy= False)</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="rewrite_links"></a><span class="summary-name">rewrite_links</span> = <code title="_MethodFunc('rewrite_links', copy= True)">_MethodFunc('rewrite_links', copy= True)</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="html_parser"></a><span class="summary-name">html_parser</span> = <code title="HTMLParser()">HTMLParser()</code> </td> </tr> <tr class="private"> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="xhtml_parser"></a><span class="summary-name">xhtml_parser</span> = <code title="XHTMLParser()">XHTMLParser()</code> </td> </tr> </table> <!-- ==================== FUNCTION DETAILS ==================== --> <a name="section-FunctionDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Function Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-FunctionDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="fragments_fromstring"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">fragments_fromstring</span>(<span class="sig-arg">html</span>, <span class="sig-arg">no_leading_text</span>=<span class="sig-default">False</span>, <span class="sig-arg">base_url</span>=<span class="sig-default">None</span>, <span class="sig-arg">parser</span>=<span class="sig-default">None</span>, <span class="sig-arg">**kw</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#fragments_fromstring">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Parses several HTML elements, returning a list of elements.</p> <p>The first item in the list may be a string (though leading whitespace is removed). If no_leading_text is true, then it will be an error if there is leading text, and it will always be a list of only elements.</p> <p>base_url will set the document's base_url attribute (and the tree's docinfo.URL)</p> <dl class="fields"> </dl> </td></tr></table> </div> <a name="fragment_fromstring"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">fragment_fromstring</span>(<span class="sig-arg">html</span>, <span class="sig-arg">create_parent</span>=<span class="sig-default">False</span>, <span class="sig-arg">base_url</span>=<span class="sig-default">None</span>, <span class="sig-arg">parser</span>=<span class="sig-default">None</span>, <span class="sig-arg">**kw</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#fragment_fromstring">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element.</p> <p>If create_parent is true (or is a tag name) then a parent node will be created to encapsulate the HTML in a single element.</p> <p>base_url will set the document's base_url attribute (and the tree's docinfo.URL)</p> <dl class="fields"> </dl> </td></tr></table> </div> <a name="fromstring"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">fromstring</span>(<span class="sig-arg">html</span>, <span class="sig-arg">base_url</span>=<span class="sig-default">None</span>, <span class="sig-arg">parser</span>=<span class="sig-default">None</span>, <span class="sig-arg">**kw</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#fromstring">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Parse the html, returning a single element/document.</p> <p>This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document.</p> <p>base_url will set the document's base_url attribute (and the tree's docinfo.URL)</p> <dl class="fields"> </dl> </td></tr></table> </div> <a name="parse"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">parse</span>(<span class="sig-arg">filename_or_url</span>, <span class="sig-arg">parser</span>=<span class="sig-default">None</span>, <span class="sig-arg">base_url</span>=<span class="sig-default">None</span>, <span class="sig-arg">**kw</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#parse">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Parse a filename, URL, or file-like object into an HTML document tree. Note: this returns a tree, not an element. Use <tt class="rst-docutils literal"><span class="pre">parse(...).getroot()</span></tt> to get the document root.</p> <p>You can override the base URL with the <tt class="rst-docutils literal"><span class="pre">base_url</span></tt> keyword. This is most useful when parsing from a file-like object.</p> <dl class="fields"> </dl> </td></tr></table> </div> <a name="submit_form"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">submit_form</span>(<span class="sig-arg">form</span>, <span class="sig-arg">extra_values</span>=<span class="sig-default">None</span>, <span class="sig-arg">open_http</span>=<span class="sig-default">None</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#submit_form">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Helper function to submit a form. Returns a file-like object, as from <tt class="rst-docutils literal"><span class="pre">urllib.urlopen()</span></tt>. This object also has a <tt class="rst-docutils literal"><span class="pre">.geturl()</span></tt> function, which shows the URL if there were any redirects.</p> <p>You can use this like:</p> <pre class="rst-literal-block"> form = doc.forms[0] form.inputs['foo'].value = 'bar' # etc response = form.submit() doc = parse(response) doc.make_links_absolute(response.geturl()) </pre> <p>To change the HTTP requester, pass a function as <tt class="rst-docutils literal"><span class="pre">open_http</span></tt> keyword argument that opens the URL for you. The function must have the following signature:</p> <pre class="rst-literal-block"> open_http(method, URL, values) </pre> <p>The action is one of 'GET' or 'POST', the URL is the target URL as a string, and the values are a sequence of <tt class="rst-docutils literal"><span class="pre">(name,</span> <span class="pre">value)</span></tt> tuples with the form data.</p> <dl class="fields"> </dl> </td></tr></table> </div> <a name="tostring"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">tostring</span>(<span class="sig-arg">doc</span>, <span class="sig-arg">pretty_print</span>=<span class="sig-default">False</span>, <span class="sig-arg">include_meta_content_type</span>=<span class="sig-default">False</span>, <span class="sig-arg">encoding</span>=<span class="sig-default">None</span>, <span class="sig-arg">method</span>=<span class="sig-default"><code class="variable-quote">'</code><code class="variable-string">html</code><code class="variable-quote">'</code></span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#tostring">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Return an HTML string representation of the document.</p> <p>Note: if include_meta_content_type is true this will create a <tt class="rst-docutils literal"><span class="pre">&lt;meta</span> <span class="pre">http-equiv=&quot;Content-Type&quot;</span> <span class="pre">...&gt;</span></tt> tag in the head; regardless of the value of include_meta_content_type any existing <tt class="rst-docutils literal"><span class="pre">&lt;meta</span> <span class="pre">http-equiv=&quot;Content-Type&quot;</span> <span class="pre">...&gt;</span></tt> tag will be removed</p> <p>The <tt class="rst-docutils literal"><span class="pre">encoding</span></tt> argument controls the output encoding (defauts to ASCII, with &amp;#...; character references for any characters outside of ASCII).</p> <p>The <tt class="rst-docutils literal"><span class="pre">method</span></tt> argument defines the output method. It defaults to 'html', but can also be 'xml' for xhtml output, or 'text' to serialise to plain text without markup. Note that you can pass the builtin <tt class="rst-docutils literal"><span class="pre">unicode</span></tt> type as <tt class="rst-docutils literal"><span class="pre">encoding</span></tt> argument to serialise to a unicode string.</p> <p>Example:</p> <pre class="rst-literal-block"> &gt;&gt;&gt; from lxml import html &gt;&gt;&gt; root = html.fragment_fromstring('&lt;p&gt;Hello&lt;br&gt;world!&lt;/p&gt;') &gt;&gt;&gt; html.tostring(root) '&lt;p&gt;Hello&lt;br&gt;world!&lt;/p&gt;' &gt;&gt;&gt; html.tostring(root, method='html') '&lt;p&gt;Hello&lt;br&gt;world!&lt;/p&gt;' &gt;&gt;&gt; html.tostring(root, method='xml') '&lt;p&gt;Hello&lt;br/&gt;world!&lt;/p&gt;' &gt;&gt;&gt; html.tostring(root, method='text') 'Helloworld!' &gt;&gt;&gt; html.tostring(root, method='text', encoding=unicode) u'Helloworld!' </pre> <dl class="fields"> </dl> </td></tr></table> </div> <a name="Element"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">Element</span>(<span class="sig-arg">*args</span>, <span class="sig-arg">**kw</span>)</span> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="lxml.html-pysrc.html#Element">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Create a new HTML Element.</p> <p>This can also be used for XHTML documents.</p> <dl class="fields"> </dl> </td></tr></table> </div> <br /> <!-- ==================== VARIABLES DETAILS ==================== --> <a name="section-VariablesDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-VariablesDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="_rel_links_xpath"></a> <div class="private"> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">_rel_links_xpath</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> descendant-or-self::a[@rel]|descendant-or-self::x:a[@rel] </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="_options_xpath"></a> <div class="private"> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">_options_xpath</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> descendant-or-self::option|descendant-or-self::x:option </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="_forms_xpath"></a> <div class="private"> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">_forms_xpath</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> descendant-or-self::form|descendant-or-self::x:form </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="_class_xpath"></a> <div class="private"> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">_class_xpath</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> descendant-or-self::*[@class and contains(concat(' ', normalize-space(<span class="variable-linewrap"><img src="crarr.png" alt="\" /></span> @class), ' '), concat(' ', $class_name, ' '))] </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="_css_url_re"></a> <div class="private"> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">_css_url_re</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> re.compile(r'<code class="re-flags">(?i)</code>url\(<code class="re-group">(</code>&quot;<code class="re-group">[^</code>&quot;<code class="re-group">]</code><code class="re-op">*</code>&quot;<code class="re-op">|</code>\'<code class="re-group">[^</code>\'<code class="re-group">]</code><code class="re-op">*</code>\'<code class="re-op">|</code><code class="re-group">[^</code>\)<code class="re-group">]</code><code class="re-op">*</code><code class="re-group">)</code>\)') </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <a name="make_links_absolute"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <h3 class="epydoc">make_links_absolute</h3> <dl class="fields"> </dl> <dl class="fields"> <dt>Value:</dt> <dd><table><tr><td><pre class="variable"> _MethodFunc('make_links_absolute', copy= True) </pre></td></tr></table> </dd> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0 on Sun Jun 21 09:44:36 2009 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
vmanoria/bluemix-hue-filebrowser
hue-3.8.1-bluemix/desktop/core/ext-py/lxml/doc/html/api/lxml.html-module.html
HTML
gpl-2.0
56,518
/* * Copyright (c) 1997 Adrian Sun (asun@zoology.washington.edu) * All rights reserved. */ #ifndef _ATALK_SERVER_CHILD_H #define _ATALK_SERVER_CHILD_H 1 #include <sys/types.h> #include <arpa/inet.h> #include <pthread.h> /* useful stuff for child processes. most of this is hidden in * server_child.c to ease changes in implementation */ #define CHILD_HASHSIZE 32 /* One AFP session child process */ typedef struct afp_child { pid_t afpch_pid; /* afpd worker process pid (from the worker afpd process )*/ uid_t afpch_uid; /* user id of connected client (from the worker afpd process) */ int afpch_valid; /* 1 if we have a clientid */ int afpch_killed; /* 1 if we already tried to kill the client */ uint32_t afpch_boottime; /* client boot time (from the mac client) */ time_t afpch_logintime; /* time the child was added */ uint32_t afpch_idlen; /* clientid len (from the Mac client) */ char *afpch_clientid; /* clientid (from the Mac client) */ int afpch_ipc_fd; /* socket for IPC bw afpd parent and childs */ int16_t afpch_state; /* state of AFP session (eg active, sleeping, disconnected) */ char *afpch_volumes; /* mounted volumes */ struct afp_child **afpch_prevp; struct afp_child *afpch_next; } afp_child_t; /* Info and table with all AFP session child processes */ typedef struct { pthread_mutex_t servch_lock; /* Lock */ int servch_count; /* Current count of active AFP sessions */ int servch_nsessions; /* Number of allowed AFP sessions */ afp_child_t *servch_table[CHILD_HASHSIZE]; /* Hashtable with data of AFP sesssions */ } server_child_t; /* server_child.c */ extern server_child_t *server_child_alloc(int); extern afp_child_t *server_child_add(server_child_t *, pid_t, int ipc_fd); extern int server_child_remove(server_child_t *, pid_t); extern void server_child_free(server_child_t *); extern afp_child_t *server_child_resolve(server_child_t *childs, id_t pid); extern void server_child_kill(server_child_t *, int); extern void server_child_kill_one_by_id(server_child_t *children, pid_t pid, uid_t, uint32_t len, char *id, uint32_t boottime); extern int server_child_transfer_session(server_child_t *children, pid_t, uid_t, int, uint16_t); extern void server_child_handler(server_child_t *); extern void server_reset_signal(void); #endif
ghmajx/asuswrt-merlin
release/src/router/netatalk-3.0.5/include/atalk/server_child.h
C
gpl-2.0
2,623
<?php define( "MSG_TIMEOUT", 2.0 ); define( "MSG_DATA_SIZE", 4+256 ); if ( canEdit( 'Monitors' ) ) { $zmuCommand = getZmuCommand( " -m ".validInt($_REQUEST['id']) ); switch ( validJsStr($_REQUEST['command']) ) { case "disableAlarms" : { $zmuCommand .= " -n"; break; } case "enableAlarms" : { $zmuCommand .= " -c"; break; } case "forceAlarm" : { $zmuCommand .= " -a"; break; } case "cancelForcedAlarm" : { $zmuCommand .= " -c"; break; } default : { ajaxError( "Unexpected command '".validJsStr($_REQUEST['command'])."'" ); } } ajaxResponse( exec( escapeshellcmd( $zmuCommand ) ) ); } ajaxError( 'Unrecognised action or insufficient permissions' ); ?>
seebaer1976/ZoneMinder
web/ajax/alarm.php
PHP
gpl-2.0
907
/* GStreamer dmabuf allocator * Copyright (C) 2013 Linaro SA * Author: Benjamin Gaignard <benjamin.gaignard@linaro.org> for Linaro. * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef __GST_DMABUF_H__ #define __GST_DMABUF_H__ #include <gst/gst.h> G_BEGIN_DECLS #define GST_ALLOCATOR_DMABUF "dmabuf" GstAllocator * gst_dmabuf_allocator_new (void); GstMemory * gst_dmabuf_allocator_alloc (GstAllocator * allocator, gint fd, gsize size); gint gst_dmabuf_memory_get_fd (GstMemory * mem); gboolean gst_is_dmabuf_memory (GstMemory * mem); G_END_DECLS #endif /* __GST_DMABUF_H__ */
JulienMcJay/eclock
windows/gstreamer/include/gstreamer-1.0/gst/allocators/gstdmabuf.h
C
gpl-2.0
1,309
/* * inode.c -- user mode filesystem api for usb gadget controllers * * Copyright (C) 2003-2004 David Brownell * Copyright (C) 2003 Agilent Technologies * * 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. */ /* #define VERBOSE_DEBUG */ #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/uts.h> #include <linux/wait.h> #include <linux/compiler.h> #include <asm/uaccess.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/mmu_context.h> #include <linux/aio.h> #include <linux/device.h> #include <linux/moduleparam.h> #include <linux/usb/gadgetfs.h> #include <linux/usb/gadget.h> /* * The gadgetfs API maps each endpoint to a file descriptor so that you * can use standard synchronous read/write calls for I/O. There's some * O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode * drivers show how this works in practice. You can also use AIO to * eliminate I/O gaps between requests, to help when streaming data. * * Key parts that must be USB-specific are protocols defining how the * read/write operations relate to the hardware state machines. There * are two types of files. One type is for the device, implementing ep0. * The other type is for each IN or OUT endpoint. In both cases, the * user mode driver must configure the hardware before using it. * * - First, dev_config() is called when /dev/gadget/$CHIP is configured * (by writing configuration and device descriptors). Afterwards it * may serve as a source of device events, used to handle all control * requests other than basic enumeration. * * - Then, after a SET_CONFIGURATION control request, ep_config() is * called when each /dev/gadget/ep* file is configured (by writing * endpoint descriptors). Afterwards these files are used to write() * IN data or to read() OUT data. To halt the endpoint, a "wrong * direction" request is issued (like reading an IN endpoint). * * Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe * not possible on all hardware. For example, precise fault handling with * respect to data left in endpoint fifos after aborted operations; or * selective clearing of endpoint halts, to implement SET_INTERFACE. */ #define DRIVER_DESC "USB Gadget filesystem" #define DRIVER_VERSION "24 Aug 2004" static const char driver_desc [] = DRIVER_DESC; static const char shortname [] = "gadgetfs"; MODULE_DESCRIPTION (DRIVER_DESC); MODULE_AUTHOR ("David Brownell"); MODULE_LICENSE ("GPL"); /*----------------------------------------------------------------------*/ #define GADGETFS_MAGIC 0xaee71ee7 /* /dev/gadget/$CHIP represents ep0 and the whole device */ enum ep0_state { /* DISBLED is the initial state. */ STATE_DEV_DISABLED = 0, /* Only one open() of /dev/gadget/$CHIP; only one file tracks * ep0/device i/o modes and binding to the controller. Driver * must always write descriptors to initialize the device, then * the device becomes UNCONNECTED until enumeration. */ STATE_DEV_OPENED, /* From then on, ep0 fd is in either of two basic modes: * - (UN)CONNECTED: read usb_gadgetfs_event(s) from it * - SETUP: read/write will transfer control data and succeed; * or if "wrong direction", performs protocol stall */ STATE_DEV_UNCONNECTED, STATE_DEV_CONNECTED, STATE_DEV_SETUP, /* UNBOUND means the driver closed ep0, so the device won't be * accessible again (DEV_DISABLED) until all fds are closed. */ STATE_DEV_UNBOUND, }; /* enough for the whole queue: most events invalidate others */ #define N_EVENT 5 struct dev_data { spinlock_t lock; atomic_t count; enum ep0_state state; /* P: lock */ struct usb_gadgetfs_event event [N_EVENT]; unsigned ev_next; struct fasync_struct *fasync; u8 current_config; /* drivers reading ep0 MUST handle control requests (SETUP) * reported that way; else the host will time out. */ unsigned usermode_setup : 1, setup_in : 1, setup_can_stall : 1, setup_out_ready : 1, setup_out_error : 1, setup_abort : 1; unsigned setup_wLength; /* the rest is basically write-once */ struct usb_config_descriptor *config, *hs_config; struct usb_device_descriptor *dev; struct usb_request *req; struct usb_gadget *gadget; struct list_head epfiles; void *buf; wait_queue_head_t wait; struct super_block *sb; struct dentry *dentry; /* except this scratch i/o buffer for ep0 */ u8 rbuf [256]; }; static inline void get_dev (struct dev_data *data) { atomic_inc (&data->count); } static void put_dev (struct dev_data *data) { if (likely (!atomic_dec_and_test (&data->count))) return; /* needs no more cleanup */ BUG_ON (waitqueue_active (&data->wait)); kfree (data); } static struct dev_data *dev_new (void) { struct dev_data *dev; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return NULL; dev->state = STATE_DEV_DISABLED; atomic_set (&dev->count, 1); spin_lock_init (&dev->lock); INIT_LIST_HEAD (&dev->epfiles); init_waitqueue_head (&dev->wait); return dev; } /*----------------------------------------------------------------------*/ /* other /dev/gadget/$ENDPOINT files represent endpoints */ enum ep_state { STATE_EP_DISABLED = 0, STATE_EP_READY, STATE_EP_ENABLED, STATE_EP_UNBOUND, }; struct ep_data { struct mutex lock; enum ep_state state; atomic_t count; struct dev_data *dev; /* must hold dev->lock before accessing ep or req */ struct usb_ep *ep; struct usb_request *req; ssize_t status; char name [16]; struct usb_endpoint_descriptor desc, hs_desc; struct list_head epfiles; wait_queue_head_t wait; struct dentry *dentry; struct inode *inode; }; static inline void get_ep (struct ep_data *data) { atomic_inc (&data->count); } static void put_ep (struct ep_data *data) { if (likely (!atomic_dec_and_test (&data->count))) return; put_dev (data->dev); /* needs no more cleanup */ BUG_ON (!list_empty (&data->epfiles)); BUG_ON (waitqueue_active (&data->wait)); kfree (data); } /*----------------------------------------------------------------------*/ /* most "how to use the hardware" policy choices are in userspace: * mapping endpoint roles (which the driver needs) to the capabilities * which the usb controller has. most of those capabilities are exposed * implicitly, starting with the driver name and then endpoint names. */ static const char *CHIP; /*----------------------------------------------------------------------*/ /* NOTE: don't use dev_printk calls before binding to the gadget * at the end of ep0 configuration, or after unbind. */ /* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */ #define xprintk(d,level,fmt,args...) \ printk(level "%s: " fmt , shortname , ## args) #ifdef DEBUG #define DBG(dev,fmt,args...) \ xprintk(dev , KERN_DEBUG , fmt , ## args) #else #define DBG(dev,fmt,args...) \ do { } while (0) #endif /* DEBUG */ #ifdef VERBOSE_DEBUG #define VDEBUG DBG #else #define VDEBUG(dev,fmt,args...) \ do { } while (0) #endif /* DEBUG */ #define ERROR(dev,fmt,args...) \ xprintk(dev , KERN_ERR , fmt , ## args) #define INFO(dev,fmt,args...) \ xprintk(dev , KERN_INFO , fmt , ## args) /*----------------------------------------------------------------------*/ /* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso) * * After opening, configure non-control endpoints. Then use normal * stream read() and write() requests; and maybe ioctl() to get more * precise FIFO status when recovering from cancellation. */ static void epio_complete (struct usb_ep *ep, struct usb_request *req) { struct ep_data *epdata = ep->driver_data; if (!req->context) return; if (req->status) epdata->status = req->status; else epdata->status = req->actual; complete ((struct completion *)req->context); } /* tasklock endpoint, returning when it's connected. * still need dev->lock to use epdata->ep. */ static int get_ready_ep (unsigned f_flags, struct ep_data *epdata) { int val; if (f_flags & O_NONBLOCK) { if (!mutex_trylock(&epdata->lock)) goto nonblock; if (epdata->state != STATE_EP_ENABLED) { mutex_unlock(&epdata->lock); nonblock: val = -EAGAIN; } else val = 0; return val; } val = mutex_lock_interruptible(&epdata->lock); if (val < 0) return val; switch (epdata->state) { case STATE_EP_ENABLED: break; // case STATE_EP_DISABLED: /* "can't happen" */ // case STATE_EP_READY: /* "can't happen" */ default: /* error! */ pr_debug ("%s: ep %pK not available, state %d\n", shortname, epdata, epdata->state); // FALLTHROUGH case STATE_EP_UNBOUND: /* clean disconnect */ val = -ENODEV; mutex_unlock(&epdata->lock); } return val; } static ssize_t ep_io (struct ep_data *epdata, void *buf, unsigned len) { DECLARE_COMPLETION_ONSTACK (done); int value; spin_lock_irq (&epdata->dev->lock); if (likely (epdata->ep != NULL)) { struct usb_request *req = epdata->req; req->context = &done; req->complete = epio_complete; req->buf = buf; req->length = len; value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC); } else value = -ENODEV; spin_unlock_irq (&epdata->dev->lock); if (likely (value == 0)) { value = wait_event_interruptible (done.wait, done.done); if (value != 0) { spin_lock_irq (&epdata->dev->lock); if (likely (epdata->ep != NULL)) { DBG (epdata->dev, "%s i/o interrupted\n", epdata->name); usb_ep_dequeue (epdata->ep, epdata->req); spin_unlock_irq (&epdata->dev->lock); wait_event (done.wait, done.done); if (epdata->status == -ECONNRESET) epdata->status = -EINTR; } else { spin_unlock_irq (&epdata->dev->lock); DBG (epdata->dev, "endpoint gone\n"); epdata->status = -ENODEV; } } return epdata->status; } return value; } /* handle a synchronous OUT bulk/intr/iso transfer */ static ssize_t ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr) { struct ep_data *data = fd->private_data; void *kbuf; ssize_t value; if ((value = get_ready_ep (fd->f_flags, data)) < 0) return value; /* halt any endpoint by doing a "wrong direction" i/o call */ if (usb_endpoint_dir_in(&data->desc)) { if (usb_endpoint_xfer_isoc(&data->desc)) { mutex_unlock(&data->lock); return -EINVAL; } DBG (data->dev, "%s halt\n", data->name); spin_lock_irq (&data->dev->lock); if (likely (data->ep != NULL)) usb_ep_set_halt (data->ep); spin_unlock_irq (&data->dev->lock); mutex_unlock(&data->lock); return -EBADMSG; } /* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */ value = -ENOMEM; kbuf = kmalloc (len, GFP_KERNEL); if (unlikely (!kbuf)) goto free1; value = ep_io (data, kbuf, len); VDEBUG (data->dev, "%s read %zu OUT, status %d\n", data->name, len, (int) value); if (value >= 0 && copy_to_user (buf, kbuf, value)) value = -EFAULT; free1: mutex_unlock(&data->lock); kfree (kbuf); return value; } /* handle a synchronous IN bulk/intr/iso transfer */ static ssize_t ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct ep_data *data = fd->private_data; void *kbuf; ssize_t value; if ((value = get_ready_ep (fd->f_flags, data)) < 0) return value; /* halt any endpoint by doing a "wrong direction" i/o call */ if (!usb_endpoint_dir_in(&data->desc)) { if (usb_endpoint_xfer_isoc(&data->desc)) { mutex_unlock(&data->lock); return -EINVAL; } DBG (data->dev, "%s halt\n", data->name); spin_lock_irq (&data->dev->lock); if (likely (data->ep != NULL)) usb_ep_set_halt (data->ep); spin_unlock_irq (&data->dev->lock); mutex_unlock(&data->lock); return -EBADMSG; } /* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */ value = -ENOMEM; kbuf = kmalloc (len, GFP_KERNEL); if (!kbuf) goto free1; if (copy_from_user (kbuf, buf, len)) { value = -EFAULT; goto free1; } value = ep_io (data, kbuf, len); VDEBUG (data->dev, "%s write %zu IN, status %d\n", data->name, len, (int) value); free1: mutex_unlock(&data->lock); kfree (kbuf); return value; } static int ep_release (struct inode *inode, struct file *fd) { struct ep_data *data = fd->private_data; int value; value = mutex_lock_interruptible(&data->lock); if (value < 0) return value; /* clean up if this can be reopened */ if (data->state != STATE_EP_UNBOUND) { data->state = STATE_EP_DISABLED; data->desc.bDescriptorType = 0; data->hs_desc.bDescriptorType = 0; usb_ep_disable(data->ep); } mutex_unlock(&data->lock); put_ep (data); return 0; } static long ep_ioctl(struct file *fd, unsigned code, unsigned long value) { struct ep_data *data = fd->private_data; int status; if ((status = get_ready_ep (fd->f_flags, data)) < 0) return status; spin_lock_irq (&data->dev->lock); if (likely (data->ep != NULL)) { switch (code) { case GADGETFS_FIFO_STATUS: status = usb_ep_fifo_status (data->ep); break; case GADGETFS_FIFO_FLUSH: usb_ep_fifo_flush (data->ep); break; case GADGETFS_CLEAR_HALT: status = usb_ep_clear_halt (data->ep); break; default: status = -ENOTTY; } } else status = -ENODEV; spin_unlock_irq (&data->dev->lock); mutex_unlock(&data->lock); return status; } /*----------------------------------------------------------------------*/ /* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */ struct kiocb_priv { struct usb_request *req; struct ep_data *epdata; struct kiocb *iocb; struct mm_struct *mm; struct work_struct work; void *buf; const struct iovec *iv; unsigned long nr_segs; unsigned actual; }; static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e) { struct kiocb_priv *priv = iocb->private; struct ep_data *epdata; int value; local_irq_disable(); epdata = priv->epdata; // spin_lock(&epdata->dev->lock); if (likely(epdata && epdata->ep && priv->req)) value = usb_ep_dequeue (epdata->ep, priv->req); else value = -EINVAL; // spin_unlock(&epdata->dev->lock); local_irq_enable(); aio_put_req(iocb); return value; } static ssize_t ep_copy_to_user(struct kiocb_priv *priv) { ssize_t len, total; void *to_copy; int i; /* copy stuff into user buffers */ total = priv->actual; len = 0; to_copy = priv->buf; for (i=0; i < priv->nr_segs; i++) { ssize_t this = min((ssize_t)(priv->iv[i].iov_len), total); if (copy_to_user(priv->iv[i].iov_base, to_copy, this)) { if (len == 0) len = -EFAULT; break; } total -= this; len += this; to_copy += this; if (total == 0) break; } return len; } static void ep_user_copy_worker(struct work_struct *work) { struct kiocb_priv *priv = container_of(work, struct kiocb_priv, work); struct mm_struct *mm = priv->mm; struct kiocb *iocb = priv->iocb; size_t ret; use_mm(mm); ret = ep_copy_to_user(priv); unuse_mm(mm); /* completing the iocb can drop the ctx and mm, don't touch mm after */ aio_complete(iocb, ret, ret); kfree(priv->buf); kfree(priv); } static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req) { struct kiocb *iocb = req->context; struct kiocb_priv *priv = iocb->private; struct ep_data *epdata = priv->epdata; /* lock against disconnect (and ideally, cancel) */ spin_lock(&epdata->dev->lock); priv->req = NULL; priv->epdata = NULL; /* if this was a write or a read returning no data then we * don't need to copy anything to userspace, so we can * complete the aio request immediately. */ if (priv->iv == NULL || unlikely(req->actual == 0)) { kfree(req->buf); kfree(priv); iocb->private = NULL; /* aio_complete() reports bytes-transferred _and_ faults */ aio_complete(iocb, req->actual ? req->actual : req->status, req->status); } else { /* ep_copy_to_user() won't report both; we hide some faults */ if (unlikely(0 != req->status)) DBG(epdata->dev, "%s fault %d len %d\n", ep->name, req->status, req->actual); priv->buf = req->buf; priv->actual = req->actual; schedule_work(&priv->work); } spin_unlock(&epdata->dev->lock); usb_ep_free_request(ep, req); put_ep(epdata); } static ssize_t ep_aio_rwtail( struct kiocb *iocb, char *buf, size_t len, struct ep_data *epdata, const struct iovec *iv, unsigned long nr_segs ) { struct kiocb_priv *priv; struct usb_request *req; ssize_t value; priv = kmalloc(sizeof *priv, GFP_KERNEL); if (!priv) { value = -ENOMEM; fail: kfree(buf); return value; } iocb->private = priv; priv->iocb = iocb; priv->iv = iv; priv->nr_segs = nr_segs; INIT_WORK(&priv->work, ep_user_copy_worker); value = get_ready_ep(iocb->ki_filp->f_flags, epdata); if (unlikely(value < 0)) { kfree(priv); goto fail; } kiocb_set_cancel_fn(iocb, ep_aio_cancel); get_ep(epdata); priv->epdata = epdata; priv->actual = 0; priv->mm = current->mm; /* mm teardown waits for iocbs in exit_aio() */ /* each kiocb is coupled to one usb_request, but we can't * allocate or submit those if the host disconnected. */ spin_lock_irq(&epdata->dev->lock); if (likely(epdata->ep)) { req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC); if (likely(req)) { priv->req = req; req->buf = buf; req->length = len; req->complete = ep_aio_complete; req->context = iocb; value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC); if (unlikely(0 != value)) usb_ep_free_request(epdata->ep, req); } else value = -EAGAIN; } else value = -ENODEV; spin_unlock_irq(&epdata->dev->lock); mutex_unlock(&epdata->lock); if (unlikely(value)) { kfree(priv); put_ep(epdata); } else value = -EIOCBQUEUED; return value; } static ssize_t ep_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t o) { struct ep_data *epdata = iocb->ki_filp->private_data; char *buf; if (unlikely(usb_endpoint_dir_in(&epdata->desc))) return -EINVAL; buf = kmalloc(iocb->ki_left, GFP_KERNEL); if (unlikely(!buf)) return -ENOMEM; return ep_aio_rwtail(iocb, buf, iocb->ki_left, epdata, iov, nr_segs); } static ssize_t ep_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t o) { struct ep_data *epdata = iocb->ki_filp->private_data; char *buf; size_t len = 0; int i = 0; if (unlikely(!usb_endpoint_dir_in(&epdata->desc))) return -EINVAL; buf = kmalloc(iocb->ki_left, GFP_KERNEL); if (unlikely(!buf)) return -ENOMEM; for (i=0; i < nr_segs; i++) { if (unlikely(copy_from_user(&buf[len], iov[i].iov_base, iov[i].iov_len) != 0)) { kfree(buf); return -EFAULT; } len += iov[i].iov_len; } return ep_aio_rwtail(iocb, buf, len, epdata, NULL, 0); } /*----------------------------------------------------------------------*/ /* used after endpoint configuration */ static const struct file_operations ep_io_operations = { .owner = THIS_MODULE, .llseek = no_llseek, .read = ep_read, .write = ep_write, .unlocked_ioctl = ep_ioctl, .release = ep_release, .aio_read = ep_aio_read, .aio_write = ep_aio_write, }; /* ENDPOINT INITIALIZATION * * fd = open ("/dev/gadget/$ENDPOINT", O_RDWR) * status = write (fd, descriptors, sizeof descriptors) * * That write establishes the endpoint configuration, configuring * the controller to process bulk, interrupt, or isochronous transfers * at the right maxpacket size, and so on. * * The descriptors are message type 1, identified by a host order u32 * at the beginning of what's written. Descriptor order is: full/low * speed descriptor, then optional high speed descriptor. */ static ssize_t ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct ep_data *data = fd->private_data; struct usb_ep *ep; u32 tag; int value, length = len; value = mutex_lock_interruptible(&data->lock); if (value < 0) return value; if (data->state != STATE_EP_READY) { value = -EL2HLT; goto fail; } value = len; if (len < USB_DT_ENDPOINT_SIZE + 4) goto fail0; /* we might need to change message format someday */ if (copy_from_user (&tag, buf, 4)) { goto fail1; } if (tag != 1) { DBG(data->dev, "config %s, bad tag %d\n", data->name, tag); goto fail0; } buf += 4; len -= 4; /* NOTE: audio endpoint extensions not accepted here; * just don't include the extra bytes. */ /* full/low speed descriptor, then high speed */ if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) { goto fail1; } if (data->desc.bLength != USB_DT_ENDPOINT_SIZE || data->desc.bDescriptorType != USB_DT_ENDPOINT) goto fail0; if (len != USB_DT_ENDPOINT_SIZE) { if (len != 2 * USB_DT_ENDPOINT_SIZE) goto fail0; if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE, USB_DT_ENDPOINT_SIZE)) { goto fail1; } if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE || data->hs_desc.bDescriptorType != USB_DT_ENDPOINT) { DBG(data->dev, "config %s, bad hs length or type\n", data->name); goto fail0; } } spin_lock_irq (&data->dev->lock); if (data->dev->state == STATE_DEV_UNBOUND) { value = -ENOENT; goto gone; } else if ((ep = data->ep) == NULL) { value = -ENODEV; goto gone; } switch (data->dev->gadget->speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: ep->desc = &data->desc; value = usb_ep_enable(ep); if (value == 0) data->state = STATE_EP_ENABLED; break; case USB_SPEED_HIGH: /* fails if caller didn't provide that descriptor... */ ep->desc = &data->hs_desc; value = usb_ep_enable(ep); if (value == 0) data->state = STATE_EP_ENABLED; break; default: DBG(data->dev, "unconnected, %s init abandoned\n", data->name); value = -EINVAL; } if (value == 0) { fd->f_op = &ep_io_operations; value = length; } gone: spin_unlock_irq (&data->dev->lock); if (value < 0) { fail: data->desc.bDescriptorType = 0; data->hs_desc.bDescriptorType = 0; } mutex_unlock(&data->lock); return value; fail0: value = -EINVAL; goto fail; fail1: value = -EFAULT; goto fail; } static int ep_open (struct inode *inode, struct file *fd) { struct ep_data *data = inode->i_private; int value = -EBUSY; if (mutex_lock_interruptible(&data->lock) != 0) return -EINTR; spin_lock_irq (&data->dev->lock); if (data->dev->state == STATE_DEV_UNBOUND) value = -ENOENT; else if (data->state == STATE_EP_DISABLED) { value = 0; data->state = STATE_EP_READY; get_ep (data); fd->private_data = data; VDEBUG (data->dev, "%s ready\n", data->name); } else DBG (data->dev, "%s state %d\n", data->name, data->state); spin_unlock_irq (&data->dev->lock); mutex_unlock(&data->lock); return value; } /* used before endpoint configuration */ static const struct file_operations ep_config_operations = { .llseek = no_llseek, .open = ep_open, .write = ep_config, .release = ep_release, }; /*----------------------------------------------------------------------*/ /* EP0 IMPLEMENTATION can be partly in userspace. * * Drivers that use this facility receive various events, including * control requests the kernel doesn't handle. Drivers that don't * use this facility may be too simple-minded for real applications. */ static inline void ep0_readable (struct dev_data *dev) { wake_up (&dev->wait); kill_fasync (&dev->fasync, SIGIO, POLL_IN); } static void clean_req (struct usb_ep *ep, struct usb_request *req) { struct dev_data *dev = ep->driver_data; if (req->buf != dev->rbuf) { kfree(req->buf); req->buf = dev->rbuf; } req->complete = epio_complete; dev->setup_out_ready = 0; } static void ep0_complete (struct usb_ep *ep, struct usb_request *req) { struct dev_data *dev = ep->driver_data; unsigned long flags; int free = 1; /* for control OUT, data must still get to userspace */ spin_lock_irqsave(&dev->lock, flags); if (!dev->setup_in) { dev->setup_out_error = (req->status != 0); if (!dev->setup_out_error) free = 0; dev->setup_out_ready = 1; ep0_readable (dev); } /* clean up as appropriate */ if (free && req->buf != &dev->rbuf) clean_req (ep, req); req->complete = epio_complete; spin_unlock_irqrestore(&dev->lock, flags); } static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len) { struct dev_data *dev = ep->driver_data; if (dev->setup_out_ready) { DBG (dev, "ep0 request busy!\n"); return -EBUSY; } if (len > sizeof (dev->rbuf)) req->buf = kmalloc(len, GFP_ATOMIC); if (req->buf == NULL) { req->buf = dev->rbuf; return -ENOMEM; } req->complete = ep0_complete; req->length = len; req->zero = 0; return 0; } static ssize_t ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t retval; enum ep0_state state; spin_lock_irq (&dev->lock); /* report fd mode change before acting on it */ if (dev->setup_abort) { dev->setup_abort = 0; retval = -EIDRM; goto done; } /* control DATA stage */ if ((state = dev->state) == STATE_DEV_SETUP) { if (dev->setup_in) { /* stall IN */ VDEBUG(dev, "ep0in stall\n"); (void) usb_ep_set_halt (dev->gadget->ep0); retval = -EL2HLT; dev->state = STATE_DEV_CONNECTED; } else if (len == 0) { /* ack SET_CONFIGURATION etc */ struct usb_ep *ep = dev->gadget->ep0; struct usb_request *req = dev->req; if ((retval = setup_req (ep, req, 0)) == 0) retval = usb_ep_queue (ep, req, GFP_ATOMIC); dev->state = STATE_DEV_CONNECTED; /* assume that was SET_CONFIGURATION */ if (dev->current_config) { unsigned power; if (gadget_is_dualspeed(dev->gadget) && (dev->gadget->speed == USB_SPEED_HIGH)) power = dev->hs_config->bMaxPower; else power = dev->config->bMaxPower; usb_gadget_vbus_draw(dev->gadget, 2 * power); } } else { /* collect OUT data */ if ((fd->f_flags & O_NONBLOCK) != 0 && !dev->setup_out_ready) { retval = -EAGAIN; goto done; } spin_unlock_irq (&dev->lock); retval = wait_event_interruptible (dev->wait, dev->setup_out_ready != 0); /* FIXME state could change from under us */ spin_lock_irq (&dev->lock); if (retval) goto done; if (dev->state != STATE_DEV_SETUP) { retval = -ECANCELED; goto done; } dev->state = STATE_DEV_CONNECTED; if (dev->setup_out_error) retval = -EIO; else { len = min (len, (size_t)dev->req->actual); // FIXME don't call this with the spinlock held ... if (copy_to_user (buf, dev->req->buf, len)) retval = -EFAULT; else retval = len; clean_req (dev->gadget->ep0, dev->req); /* NOTE userspace can't yet choose to stall */ } } goto done; } /* else normal: return event data */ if (len < sizeof dev->event [0]) { retval = -EINVAL; goto done; } len -= len % sizeof (struct usb_gadgetfs_event); dev->usermode_setup = 1; scan: /* return queued events right away */ if (dev->ev_next != 0) { unsigned i, n; n = len / sizeof (struct usb_gadgetfs_event); if (dev->ev_next < n) n = dev->ev_next; /* ep0 i/o has special semantics during STATE_DEV_SETUP */ for (i = 0; i < n; i++) { if (dev->event [i].type == GADGETFS_SETUP) { dev->state = STATE_DEV_SETUP; n = i + 1; break; } } spin_unlock_irq (&dev->lock); len = n * sizeof (struct usb_gadgetfs_event); if (copy_to_user (buf, &dev->event, len)) retval = -EFAULT; else retval = len; if (len > 0) { /* NOTE this doesn't guard against broken drivers; * concurrent ep0 readers may lose events. */ spin_lock_irq (&dev->lock); if (dev->ev_next > n) { memmove(&dev->event[0], &dev->event[n], sizeof (struct usb_gadgetfs_event) * (dev->ev_next - n)); } dev->ev_next -= n; spin_unlock_irq (&dev->lock); } return retval; } if (fd->f_flags & O_NONBLOCK) { retval = -EAGAIN; goto done; } switch (state) { default: DBG (dev, "fail %s, state %d\n", __func__, state); retval = -ESRCH; break; case STATE_DEV_UNCONNECTED: case STATE_DEV_CONNECTED: spin_unlock_irq (&dev->lock); DBG (dev, "%s wait\n", __func__); /* wait for events */ retval = wait_event_interruptible (dev->wait, dev->ev_next != 0); if (retval < 0) return retval; spin_lock_irq (&dev->lock); goto scan; } done: spin_unlock_irq (&dev->lock); return retval; } static struct usb_gadgetfs_event * next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type) { struct usb_gadgetfs_event *event; unsigned i; switch (type) { /* these events purge the queue */ case GADGETFS_DISCONNECT: if (dev->state == STATE_DEV_SETUP) dev->setup_abort = 1; // FALL THROUGH case GADGETFS_CONNECT: dev->ev_next = 0; break; case GADGETFS_SETUP: /* previous request timed out */ case GADGETFS_SUSPEND: /* same effect */ /* these events can't be repeated */ for (i = 0; i != dev->ev_next; i++) { if (dev->event [i].type != type) continue; DBG(dev, "discard old event[%d] %d\n", i, type); dev->ev_next--; if (i == dev->ev_next) break; /* indices start at zero, for simplicity */ memmove (&dev->event [i], &dev->event [i + 1], sizeof (struct usb_gadgetfs_event) * (dev->ev_next - i)); } break; default: BUG (); } VDEBUG(dev, "event[%d] = %d\n", dev->ev_next, type); event = &dev->event [dev->ev_next++]; BUG_ON (dev->ev_next > N_EVENT); memset (event, 0, sizeof *event); event->type = type; return event; } static ssize_t ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t retval = -ESRCH; spin_lock_irq (&dev->lock); /* report fd mode change before acting on it */ if (dev->setup_abort) { dev->setup_abort = 0; retval = -EIDRM; /* data and/or status stage for control request */ } else if (dev->state == STATE_DEV_SETUP) { len = min_t(size_t, len, dev->setup_wLength); if (dev->setup_in) { retval = setup_req (dev->gadget->ep0, dev->req, len); if (retval == 0) { dev->state = STATE_DEV_CONNECTED; spin_unlock_irq (&dev->lock); if (copy_from_user (dev->req->buf, buf, len)) retval = -EFAULT; else { if (len < dev->setup_wLength) dev->req->zero = 1; retval = usb_ep_queue ( dev->gadget->ep0, dev->req, GFP_KERNEL); } if (retval < 0) { spin_lock_irq (&dev->lock); clean_req (dev->gadget->ep0, dev->req); spin_unlock_irq (&dev->lock); } else retval = len; return retval; } /* can stall some OUT transfers */ } else if (dev->setup_can_stall) { VDEBUG(dev, "ep0out stall\n"); (void) usb_ep_set_halt (dev->gadget->ep0); retval = -EL2HLT; dev->state = STATE_DEV_CONNECTED; } else { DBG(dev, "bogus ep0out stall!\n"); } } else DBG (dev, "fail %s, state %d\n", __func__, dev->state); spin_unlock_irq (&dev->lock); return retval; } static int ep0_fasync (int f, struct file *fd, int on) { struct dev_data *dev = fd->private_data; // caller must F_SETOWN before signal delivery happens VDEBUG (dev, "%s %s\n", __func__, on ? "on" : "off"); return fasync_helper (f, fd, on, &dev->fasync); } static struct usb_gadget_driver gadgetfs_driver; static int dev_release (struct inode *inode, struct file *fd) { struct dev_data *dev = fd->private_data; /* closing ep0 === shutdown all */ usb_gadget_unregister_driver (&gadgetfs_driver); /* at this point "good" hardware has disconnected the * device from USB; the host won't see it any more. * alternatively, all host requests will time out. */ kfree (dev->buf); dev->buf = NULL; put_dev (dev); /* other endpoints were all decoupled from this device */ spin_lock_irq(&dev->lock); dev->state = STATE_DEV_DISABLED; spin_unlock_irq(&dev->lock); return 0; } static unsigned int ep0_poll (struct file *fd, poll_table *wait) { struct dev_data *dev = fd->private_data; int mask = 0; poll_wait(fd, &dev->wait, wait); spin_lock_irq (&dev->lock); /* report fd mode change before acting on it */ if (dev->setup_abort) { dev->setup_abort = 0; mask = POLLHUP; goto out; } if (dev->state == STATE_DEV_SETUP) { if (dev->setup_in || dev->setup_can_stall) mask = POLLOUT; } else { if (dev->ev_next != 0) mask = POLLIN; } out: spin_unlock_irq(&dev->lock); return mask; } static long dev_ioctl (struct file *fd, unsigned code, unsigned long value) { struct dev_data *dev = fd->private_data; struct usb_gadget *gadget = dev->gadget; long ret = -ENOTTY; if (gadget->ops->ioctl) ret = gadget->ops->ioctl (gadget, code, value); return ret; } /* used after device configuration */ static const struct file_operations ep0_io_operations = { .owner = THIS_MODULE, .llseek = no_llseek, .read = ep0_read, .write = ep0_write, .fasync = ep0_fasync, .poll = ep0_poll, .unlocked_ioctl = dev_ioctl, .release = dev_release, }; /*----------------------------------------------------------------------*/ /* The in-kernel gadget driver handles most ep0 issues, in particular * enumerating the single configuration (as provided from user space). * * Unrecognized ep0 requests may be handled in user space. */ static void make_qualifier (struct dev_data *dev) { struct usb_qualifier_descriptor qual; struct usb_device_descriptor *desc; qual.bLength = sizeof qual; qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER; qual.bcdUSB = cpu_to_le16 (0x0200); desc = dev->dev; qual.bDeviceClass = desc->bDeviceClass; qual.bDeviceSubClass = desc->bDeviceSubClass; qual.bDeviceProtocol = desc->bDeviceProtocol; /* assumes ep0 uses the same value for both speeds ... */ qual.bMaxPacketSize0 = dev->gadget->ep0->maxpacket; qual.bNumConfigurations = 1; qual.bRESERVED = 0; memcpy (dev->rbuf, &qual, sizeof qual); } static int config_buf (struct dev_data *dev, u8 type, unsigned index) { int len; int hs = 0; /* only one configuration */ if (index > 0) return -EINVAL; if (gadget_is_dualspeed(dev->gadget)) { hs = (dev->gadget->speed == USB_SPEED_HIGH); if (type == USB_DT_OTHER_SPEED_CONFIG) hs = !hs; } if (hs) { dev->req->buf = dev->hs_config; len = le16_to_cpu(dev->hs_config->wTotalLength); } else { dev->req->buf = dev->config; len = le16_to_cpu(dev->config->wTotalLength); } ((u8 *)dev->req->buf) [1] = type; return len; } static int gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl) { struct dev_data *dev = get_gadget_data (gadget); struct usb_request *req = dev->req; int value = -EOPNOTSUPP; struct usb_gadgetfs_event *event; u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); spin_lock (&dev->lock); dev->setup_abort = 0; if (dev->state == STATE_DEV_UNCONNECTED) { if (gadget_is_dualspeed(gadget) && gadget->speed == USB_SPEED_HIGH && dev->hs_config == NULL) { spin_unlock(&dev->lock); ERROR (dev, "no high speed config??\n"); return -EINVAL; } dev->state = STATE_DEV_CONNECTED; INFO (dev, "connected\n"); event = next_event (dev, GADGETFS_CONNECT); event->u.speed = gadget->speed; ep0_readable (dev); /* host may have given up waiting for response. we can miss control * requests handled lower down (device/endpoint status and features); * then ep0_{read,write} will report the wrong status. controller * driver will have aborted pending i/o. */ } else if (dev->state == STATE_DEV_SETUP) dev->setup_abort = 1; req->buf = dev->rbuf; req->context = NULL; value = -EOPNOTSUPP; switch (ctrl->bRequest) { case USB_REQ_GET_DESCRIPTOR: if (ctrl->bRequestType != USB_DIR_IN) goto unrecognized; switch (w_value >> 8) { case USB_DT_DEVICE: value = min (w_length, (u16) sizeof *dev->dev); dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket; req->buf = dev->dev; break; case USB_DT_DEVICE_QUALIFIER: if (!dev->hs_config) break; value = min (w_length, (u16) sizeof (struct usb_qualifier_descriptor)); make_qualifier (dev); break; case USB_DT_OTHER_SPEED_CONFIG: // FALLTHROUGH case USB_DT_CONFIG: value = config_buf (dev, w_value >> 8, w_value & 0xff); if (value >= 0) value = min (w_length, (u16) value); break; case USB_DT_STRING: goto unrecognized; default: // all others are errors break; } break; /* currently one config, two speeds */ case USB_REQ_SET_CONFIGURATION: if (ctrl->bRequestType != 0) goto unrecognized; if (0 == (u8) w_value) { value = 0; dev->current_config = 0; usb_gadget_vbus_draw(gadget, 8 /* mA */ ); // user mode expected to disable endpoints } else { u8 config, power; if (gadget_is_dualspeed(gadget) && gadget->speed == USB_SPEED_HIGH) { config = dev->hs_config->bConfigurationValue; power = dev->hs_config->bMaxPower; } else { config = dev->config->bConfigurationValue; power = dev->config->bMaxPower; } if (config == (u8) w_value) { value = 0; dev->current_config = config; usb_gadget_vbus_draw(gadget, 2 * power); } } /* report SET_CONFIGURATION like any other control request, * except that usermode may not stall this. the next * request mustn't be allowed start until this finishes: * endpoints and threads set up, etc. * * NOTE: older PXA hardware (before PXA 255: without UDCCFR) * has bad/racey automagic that prevents synchronizing here. * even kernel mode drivers often miss them. */ if (value == 0) { INFO (dev, "configuration #%d\n", dev->current_config); if (dev->usermode_setup) { dev->setup_can_stall = 0; goto delegate; } } break; #ifndef CONFIG_USB_PXA25X /* PXA automagically handles this request too */ case USB_REQ_GET_CONFIGURATION: if (ctrl->bRequestType != 0x80) goto unrecognized; *(u8 *)req->buf = dev->current_config; value = min (w_length, (u16) 1); break; #endif default: unrecognized: VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n", dev->usermode_setup ? "delegate" : "fail", ctrl->bRequestType, ctrl->bRequest, w_value, le16_to_cpu(ctrl->wIndex), w_length); /* if there's an ep0 reader, don't stall */ if (dev->usermode_setup) { dev->setup_can_stall = 1; delegate: dev->setup_in = (ctrl->bRequestType & USB_DIR_IN) ? 1 : 0; dev->setup_wLength = w_length; dev->setup_out_ready = 0; dev->setup_out_error = 0; value = 0; /* read DATA stage for OUT right away */ if (unlikely (!dev->setup_in && w_length)) { value = setup_req (gadget->ep0, dev->req, w_length); if (value < 0) break; value = usb_ep_queue (gadget->ep0, dev->req, GFP_ATOMIC); if (value < 0) { clean_req (gadget->ep0, dev->req); break; } /* we can't currently stall these */ dev->setup_can_stall = 0; } /* state changes when reader collects event */ event = next_event (dev, GADGETFS_SETUP); event->u.setup = *ctrl; ep0_readable (dev); spin_unlock (&dev->lock); return 0; } } /* proceed with data transfer and status phases? */ if (value >= 0 && dev->state != STATE_DEV_SETUP) { req->length = value; req->zero = value < w_length; value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC); if (value < 0) { DBG (dev, "ep_queue --> %d\n", value); req->status = 0; } } /* device stalls when value < 0 */ spin_unlock (&dev->lock); return value; } static void destroy_ep_files (struct dev_data *dev) { DBG (dev, "%s %d\n", __func__, dev->state); /* dev->state must prevent interference */ spin_lock_irq (&dev->lock); while (!list_empty(&dev->epfiles)) { struct ep_data *ep; struct inode *parent; struct dentry *dentry; /* break link to FS */ ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles); list_del_init (&ep->epfiles); dentry = ep->dentry; ep->dentry = NULL; parent = dentry->d_parent->d_inode; /* break link to controller */ if (ep->state == STATE_EP_ENABLED) (void) usb_ep_disable (ep->ep); ep->state = STATE_EP_UNBOUND; usb_ep_free_request (ep->ep, ep->req); ep->ep = NULL; wake_up (&ep->wait); put_ep (ep); spin_unlock_irq (&dev->lock); /* break link to dcache */ mutex_lock (&parent->i_mutex); d_delete (dentry); dput (dentry); mutex_unlock (&parent->i_mutex); spin_lock_irq (&dev->lock); } spin_unlock_irq (&dev->lock); } static struct inode * gadgetfs_create_file (struct super_block *sb, char const *name, void *data, const struct file_operations *fops, struct dentry **dentry_p); static int activate_ep_files (struct dev_data *dev) { struct usb_ep *ep; struct ep_data *data; gadget_for_each_ep (ep, dev->gadget) { data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) goto enomem0; data->state = STATE_EP_DISABLED; mutex_init(&data->lock); init_waitqueue_head (&data->wait); strncpy (data->name, ep->name, sizeof (data->name) - 1); atomic_set (&data->count, 1); data->dev = dev; get_dev (dev); data->ep = ep; ep->driver_data = data; data->req = usb_ep_alloc_request (ep, GFP_KERNEL); if (!data->req) goto enomem1; data->inode = gadgetfs_create_file (dev->sb, data->name, data, &ep_config_operations, &data->dentry); if (!data->inode) goto enomem2; list_add_tail (&data->epfiles, &dev->epfiles); } return 0; enomem2: usb_ep_free_request (ep, data->req); enomem1: put_dev (dev); kfree (data); enomem0: DBG (dev, "%s enomem\n", __func__); destroy_ep_files (dev); return -ENOMEM; } static void gadgetfs_unbind (struct usb_gadget *gadget) { struct dev_data *dev = get_gadget_data (gadget); DBG (dev, "%s\n", __func__); spin_lock_irq (&dev->lock); dev->state = STATE_DEV_UNBOUND; spin_unlock_irq (&dev->lock); destroy_ep_files (dev); gadget->ep0->driver_data = NULL; set_gadget_data (gadget, NULL); /* we've already been disconnected ... no i/o is active */ if (dev->req) usb_ep_free_request (gadget->ep0, dev->req); DBG (dev, "%s done\n", __func__); put_dev (dev); } static struct dev_data *the_device; static int gadgetfs_bind(struct usb_gadget *gadget, struct usb_gadget_driver *driver) { struct dev_data *dev = the_device; if (!dev) return -ESRCH; if (0 != strcmp (CHIP, gadget->name)) { pr_err("%s expected %s controller not %s\n", shortname, CHIP, gadget->name); return -ENODEV; } set_gadget_data (gadget, dev); dev->gadget = gadget; gadget->ep0->driver_data = dev; /* preallocate control response and buffer */ dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL); if (!dev->req) goto enomem; dev->req->context = NULL; dev->req->complete = epio_complete; if (activate_ep_files (dev) < 0) goto enomem; INFO (dev, "bound to %s driver\n", gadget->name); spin_lock_irq(&dev->lock); dev->state = STATE_DEV_UNCONNECTED; spin_unlock_irq(&dev->lock); get_dev (dev); return 0; enomem: gadgetfs_unbind (gadget); return -ENOMEM; } static void gadgetfs_disconnect (struct usb_gadget *gadget) { struct dev_data *dev = get_gadget_data (gadget); unsigned long flags; spin_lock_irqsave (&dev->lock, flags); if (dev->state == STATE_DEV_UNCONNECTED) goto exit; dev->state = STATE_DEV_UNCONNECTED; INFO (dev, "disconnected\n"); next_event (dev, GADGETFS_DISCONNECT); ep0_readable (dev); exit: spin_unlock_irqrestore (&dev->lock, flags); } static void gadgetfs_suspend (struct usb_gadget *gadget) { struct dev_data *dev = get_gadget_data (gadget); INFO (dev, "suspended from state %d\n", dev->state); spin_lock (&dev->lock); switch (dev->state) { case STATE_DEV_SETUP: // VERY odd... host died?? case STATE_DEV_CONNECTED: case STATE_DEV_UNCONNECTED: next_event (dev, GADGETFS_SUSPEND); ep0_readable (dev); /* FALLTHROUGH */ default: break; } spin_unlock (&dev->lock); } static struct usb_gadget_driver gadgetfs_driver = { .function = (char *) driver_desc, .bind = gadgetfs_bind, .unbind = gadgetfs_unbind, .setup = gadgetfs_setup, .disconnect = gadgetfs_disconnect, .suspend = gadgetfs_suspend, .driver = { .name = (char *) shortname, }, }; /*----------------------------------------------------------------------*/ static void gadgetfs_nop(struct usb_gadget *arg) { } static int gadgetfs_probe(struct usb_gadget *gadget, struct usb_gadget_driver *driver) { CHIP = gadget->name; return -EISNAM; } static struct usb_gadget_driver probe_driver = { .max_speed = USB_SPEED_HIGH, .bind = gadgetfs_probe, .unbind = gadgetfs_nop, .setup = (void *)gadgetfs_nop, .disconnect = gadgetfs_nop, .driver = { .name = "nop", }, }; /* DEVICE INITIALIZATION * * fd = open ("/dev/gadget/$CHIP", O_RDWR) * status = write (fd, descriptors, sizeof descriptors) * * That write establishes the device configuration, so the kernel can * bind to the controller ... guaranteeing it can handle enumeration * at all necessary speeds. Descriptor order is: * * . message tag (u32, host order) ... for now, must be zero; it * would change to support features like multi-config devices * . full/low speed config ... all wTotalLength bytes (with interface, * class, altsetting, endpoint, and other descriptors) * . high speed config ... all descriptors, for high speed operation; * this one's optional except for high-speed hardware * . device descriptor * * Endpoints are not yet enabled. Drivers must wait until device * configuration and interface altsetting changes create * the need to configure (or unconfigure) them. * * After initialization, the device stays active for as long as that * $CHIP file is open. Events must then be read from that descriptor, * such as configuration notifications. */ static int is_valid_config(struct usb_config_descriptor *config, unsigned int total) { return config->bDescriptorType == USB_DT_CONFIG && config->bLength == USB_DT_CONFIG_SIZE && total >= USB_DT_CONFIG_SIZE && config->bConfigurationValue != 0 && (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0 && (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0; /* FIXME if gadget->is_otg, _must_ include an otg descriptor */ /* FIXME check lengths: walk to end */ } static ssize_t dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr) { struct dev_data *dev = fd->private_data; ssize_t value = len, length = len; unsigned total; u32 tag; char *kbuf; if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) || (len > PAGE_SIZE * 4)) return -EINVAL; /* we might need to change message format someday */ if (copy_from_user (&tag, buf, 4)) return -EFAULT; if (tag != 0) return -EINVAL; buf += 4; length -= 4; kbuf = memdup_user(buf, length); if (IS_ERR(kbuf)) return PTR_ERR(kbuf); spin_lock_irq (&dev->lock); value = -EINVAL; if (dev->buf) goto fail; dev->buf = kbuf; /* full or low speed config */ dev->config = (void *) kbuf; total = le16_to_cpu(dev->config->wTotalLength); if (!is_valid_config(dev->config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; /* optional high speed config */ if (kbuf [1] == USB_DT_CONFIG) { dev->hs_config = (void *) kbuf; total = le16_to_cpu(dev->hs_config->wTotalLength); if (!is_valid_config(dev->hs_config, total) || total > length - USB_DT_DEVICE_SIZE) goto fail; kbuf += total; length -= total; } else { dev->hs_config = NULL; } /* could support multiple configs, using another encoding! */ /* device descriptor (tweaked for paranoia) */ if (length != USB_DT_DEVICE_SIZE) goto fail; dev->dev = (void *)kbuf; if (dev->dev->bLength != USB_DT_DEVICE_SIZE || dev->dev->bDescriptorType != USB_DT_DEVICE || dev->dev->bNumConfigurations != 1) goto fail; dev->dev->bNumConfigurations = 1; dev->dev->bcdUSB = cpu_to_le16 (0x0200); /* triggers gadgetfs_bind(); then we can enumerate. */ spin_unlock_irq (&dev->lock); if (dev->hs_config) gadgetfs_driver.max_speed = USB_SPEED_HIGH; else gadgetfs_driver.max_speed = USB_SPEED_FULL; value = usb_gadget_probe_driver(&gadgetfs_driver); if (value != 0) { kfree (dev->buf); dev->buf = NULL; } else { /* at this point "good" hardware has for the first time * let the USB the host see us. alternatively, if users * unplug/replug that will clear all the error state. * * note: everything running before here was guaranteed * to choke driver model style diagnostics. from here * on, they can work ... except in cleanup paths that * kick in after the ep0 descriptor is closed. */ fd->f_op = &ep0_io_operations; value = len; } return value; fail: spin_unlock_irq (&dev->lock); pr_debug ("%s: %s fail %Zd, %pK\n", shortname, __func__, value, dev); kfree (dev->buf); dev->buf = NULL; return value; } static int dev_open (struct inode *inode, struct file *fd) { struct dev_data *dev = inode->i_private; int value = -EBUSY; spin_lock_irq(&dev->lock); if (dev->state == STATE_DEV_DISABLED) { dev->ev_next = 0; dev->state = STATE_DEV_OPENED; fd->private_data = dev; get_dev (dev); value = 0; } spin_unlock_irq(&dev->lock); return value; } static const struct file_operations dev_init_operations = { .llseek = no_llseek, .open = dev_open, .write = dev_config, .fasync = ep0_fasync, .unlocked_ioctl = dev_ioctl, .release = dev_release, }; /*----------------------------------------------------------------------*/ /* FILESYSTEM AND SUPERBLOCK OPERATIONS * * Mounting the filesystem creates a controller file, used first for * device configuration then later for event monitoring. */ /* FIXME PAM etc could set this security policy without mount options * if epfiles inherited ownership and permissons from ep0 ... */ static unsigned default_uid; static unsigned default_gid; static unsigned default_perm = S_IRUSR | S_IWUSR; module_param (default_uid, uint, 0644); module_param (default_gid, uint, 0644); module_param (default_perm, uint, 0644); static struct inode * gadgetfs_make_inode (struct super_block *sb, void *data, const struct file_operations *fops, int mode) { struct inode *inode = new_inode (sb); if (inode) { inode->i_ino = get_next_ino(); inode->i_mode = mode; inode->i_uid = make_kuid(&init_user_ns, default_uid); inode->i_gid = make_kgid(&init_user_ns, default_gid); inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; inode->i_private = data; inode->i_fop = fops; } return inode; } /* creates in fs root directory, so non-renamable and non-linkable. * so inode and dentry are paired, until device reconfig. */ static struct inode * gadgetfs_create_file (struct super_block *sb, char const *name, void *data, const struct file_operations *fops, struct dentry **dentry_p) { struct dentry *dentry; struct inode *inode; dentry = d_alloc_name(sb->s_root, name); if (!dentry) return NULL; inode = gadgetfs_make_inode (sb, data, fops, S_IFREG | (default_perm & S_IRWXUGO)); if (!inode) { dput(dentry); return NULL; } d_add (dentry, inode); *dentry_p = dentry; return inode; } static const struct super_operations gadget_fs_operations = { .statfs = simple_statfs, .drop_inode = generic_delete_inode, }; static int gadgetfs_fill_super (struct super_block *sb, void *opts, int silent) { struct inode *inode; struct dev_data *dev; if (the_device) return -ESRCH; /* fake probe to determine $CHIP */ usb_gadget_probe_driver(&probe_driver); if (!CHIP) return -ENODEV; /* superblock */ sb->s_blocksize = PAGE_CACHE_SIZE; sb->s_blocksize_bits = PAGE_CACHE_SHIFT; sb->s_magic = GADGETFS_MAGIC; sb->s_op = &gadget_fs_operations; sb->s_time_gran = 1; /* root inode */ inode = gadgetfs_make_inode (sb, NULL, &simple_dir_operations, S_IFDIR | S_IRUGO | S_IXUGO); if (!inode) goto Enomem; inode->i_op = &simple_dir_inode_operations; if (!(sb->s_root = d_make_root (inode))) goto Enomem; /* the ep0 file is named after the controller we expect; * user mode code can use it for sanity checks, like we do. */ dev = dev_new (); if (!dev) goto Enomem; dev->sb = sb; if (!gadgetfs_create_file (sb, CHIP, dev, &dev_init_operations, &dev->dentry)) { put_dev(dev); goto Enomem; } /* other endpoint files are available after hardware setup, * from binding to a controller. */ the_device = dev; return 0; Enomem: return -ENOMEM; } /* "mount -t gadgetfs path /dev/gadget" ends up here */ static struct dentry * gadgetfs_mount (struct file_system_type *t, int flags, const char *path, void *opts) { return mount_single (t, flags, opts, gadgetfs_fill_super); } static void gadgetfs_kill_sb (struct super_block *sb) { kill_litter_super (sb); if (the_device) { put_dev (the_device); the_device = NULL; } } /*----------------------------------------------------------------------*/ static struct file_system_type gadgetfs_type = { .owner = THIS_MODULE, .name = shortname, .mount = gadgetfs_mount, .kill_sb = gadgetfs_kill_sb, }; MODULE_ALIAS_FS("gadgetfs"); /*----------------------------------------------------------------------*/ static int __init init (void) { int status; status = register_filesystem (&gadgetfs_type); if (status == 0) pr_info ("%s: %s, version " DRIVER_VERSION "\n", shortname, driver_desc); return status; } module_init (init); static void __exit cleanup (void) { pr_debug ("unregister %s\n", shortname); unregister_filesystem (&gadgetfs_type); } module_exit (cleanup);
DreamStar001/Vegito_vibe_k5
drivers/usb/gadget/inode.c
C
gpl-2.0
53,765
/* * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. * Created by: rusty.lynch REMOVE-THIS AT intel DOT com * This file is licensed under the GPL license. For the full content * of this license, see the COPYING file at the top level of this * source tree. Test case for assertion #4 of the sigaction system call that shows that attempting to add SIGSTOP to the signal mask of SIGTTIN will not result in sigaction returning -1 */ #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include "posixtest.h" void handler(int signo) { } int main(void) { struct sigaction act; act.sa_handler = handler; act.sa_flags = 0; sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask, SIGSTOP); if (sigaction(SIGTTIN, &act, 0) == -1) { printf("Test FAILED\n"); return PTS_FAIL; } printf("Test PASSED\n"); return PTS_PASS; }
heluxie/LTP
testcases/open_posix_testsuite/conformance/interfaces/sigaction/4-93.c
C
gpl-2.0
904
/** * Copyright 2014 Google Inc. 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. * 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. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Cloud Storage API * * @classdesc Lets you store and retrieve potentially-large, immutable data objects. * @namespace storage * @version v1 * @variation v1 * @this Storage * @param {object=} options Options for Storage */ function Storage(options) { var self = this; this._options = options || {}; this.bucketAccessControls = { /** * storage.bucketAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified bucket. * * @alias storage.bucketAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.insert * * @desc Creates a new ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.list * * @desc Retrieves ACL entries on the specified bucket. * * @alias storage.bucketAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.patch * * @desc Updates an ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.bucketAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.bucketAccessControls.update * * @desc Updates an ACL entry on the specified bucket. * * @alias storage.bucketAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.buckets = { /** * storage.buckets.delete * * @desc Permanently deletes an empty bucket. * * @alias storage.buckets.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If set, only deletes the bucket if its metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If set, only deletes the bucket if its metageneration does not match this value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'DELETE' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.get * * @desc Returns metadata for the specified bucket. * * @alias storage.buckets.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.insert * * @desc Creates a new bucket. * * @alias storage.buckets.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'POST' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.list * * @desc Retrieves a list of buckets for a given project. * * @alias storage.buckets.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {integer=} params.maxResults - Maximum number of buckets to return. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to buckets whose names begin with this prefix. * @param {string} params.project - A valid API project identifier. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b', method: 'GET' }, params: params, requiredParams: ['project'], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.patch * * @desc Updates a bucket. This method supports patch semantics. * * @alias storage.buckets.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PATCH' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.buckets.update * * @desc Updates a bucket. * * @alias storage.buckets.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket. * @param {string=} params.predefinedDefaultObjectAcl - Apply a predefined set of default object access controls to this bucket. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}', method: 'PUT' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; this.channels = { /** * storage.channels.stop * * @desc Stop watching resources through this channel * * @alias storage.channels.stop * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ stop: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/channels/stop', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.defaultObjectAccessControls = { /** * storage.defaultObjectAccessControls.delete * * @desc Permanently deletes the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.get * * @desc Returns the default object ACL entry for the specified entity on the specified bucket. * * @alias storage.defaultObjectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.insert * * @desc Creates a new default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.list * * @desc Retrieves default object ACL entries on the specified bucket. * * @alias storage.defaultObjectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.ifMetagenerationMatch - If present, only return default ACL listing if the bucket's current metageneration matches this value. * @param {string=} params.ifMetagenerationNotMatch - If present, only return default ACL listing if the bucket's current metageneration does not match the given value. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.patch * * @desc Updates a default object ACL entry on the specified bucket. This method supports patch semantics. * * @alias storage.defaultObjectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.defaultObjectAccessControls.update * * @desc Updates a default object ACL entry on the specified bucket. * * @alias storage.defaultObjectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/defaultObjectAcl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'entity'], pathParams: ['bucket', 'entity'], context: self }; return createAPIRequest(parameters, callback); } }; this.objectAccessControls = { /** * storage.objectAccessControls.delete * * @desc Permanently deletes the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.get * * @desc Returns the ACL entry for the specified entity on the specified object. * * @alias storage.objectAccessControls.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.insert * * @desc Creates a new ACL entry on the specified object. * * @alias storage.objectAccessControls.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'POST' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.list * * @desc Retrieves ACL entries on the specified object. * * @alias storage.objectAccessControls.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.patch * * @desc Updates an ACL entry on the specified object. This method supports patch semantics. * * @alias storage.objectAccessControls.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objectAccessControls.update * * @desc Updates an ACL entry on the specified object. * * @alias storage.objectAccessControls.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of a bucket. * @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string} params.object - Name of the object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}/acl/{entity}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object', 'entity'], pathParams: ['bucket', 'entity', 'object'], context: self }; return createAPIRequest(parameters, callback); } }; this.objects = { /** * storage.objects.compose * * @desc Concatenates a list of existing objects into a new object in the same bucket. * * @alias storage.objects.compose * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. * @param {string} params.destinationObject - Name of the new object. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ compose: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{destinationBucket}/o/{destinationObject}/compose', method: 'POST' }, params: params, requiredParams: ['destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.copy * * @desc Copies an object to a specified location. Optionally overrides metadata. * * @alias storage.objects.copy * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.destinationBucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string} params.destinationObject - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the destination object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the destination object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the destination object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the destination object's current metageneration does not match the given value. * @param {string=} params.ifSourceGenerationMatch - Makes the operation conditional on whether the source object's generation matches the given value. * @param {string=} params.ifSourceGenerationNotMatch - Makes the operation conditional on whether the source object's generation does not match the given value. * @param {string=} params.ifSourceMetagenerationMatch - Makes the operation conditional on whether the source object's current metageneration matches the given value. * @param {string=} params.ifSourceMetagenerationNotMatch - Makes the operation conditional on whether the source object's current metageneration does not match the given value. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {string} params.sourceBucket - Name of the bucket in which to find the source object. * @param {string=} params.sourceGeneration - If present, selects a specific revision of the source object (as opposed to the latest version, the default). * @param {string} params.sourceObject - Name of the source object. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ copy: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}', method: 'POST' }, params: params, requiredParams: ['sourceBucket', 'sourceObject', 'destinationBucket', 'destinationObject'], pathParams: ['destinationBucket', 'destinationObject', 'sourceBucket', 'sourceObject'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.delete * * @desc Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used. * * @alias storage.objects.delete * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'DELETE' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.get * * @desc Retrieves an object or its metadata. * * @alias storage.objects.get * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'GET' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.insert * * @desc Stores a new object and metadata. * * @alias storage.objects.insert * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. * @param {string=} params.contentEncoding - If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded. * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string=} params.name - Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. * @param {object} params.resource - Media resource metadata * @param {object} params.media - Media object * @param {string} params.media.mimeType - Media mime-type * @param {string|object} params.media.body - Media body contents * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'POST' }, params: params, mediaUrl: 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o', requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.list * * @desc Retrieves a list of objects matching the criteria. * * @alias storage.objects.list * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o', method: 'GET' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.patch * * @desc Updates an object's metadata. This method supports patch semantics. * * @alias storage.objects.patch * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PATCH' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.update * * @desc Updates an object's metadata. * * @alias storage.objects.update * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which the object resides. * @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default). * @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value. * @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value. * @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value. * @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value. * @param {string} params.object - Name of the object. * @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object. * @param {string=} params.projection - Set of properties to return. Defaults to full. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/{object}', method: 'PUT' }, params: params, requiredParams: ['bucket', 'object'], pathParams: ['bucket', 'object'], context: self }; return createAPIRequest(parameters, callback); }, /** * storage.objects.watchAll * * @desc Watch for changes on all objects in a bucket. * * @alias storage.objects.watchAll * @memberOf! storage(v1) * * @param {object} params - Parameters for request * @param {string} params.bucket - Name of the bucket in which to look for objects. * @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. * @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. * @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view. * @param {string=} params.prefix - Filter results to objects whose names begin with this prefix. * @param {string=} params.projection - Set of properties to return. Defaults to noAcl. * @param {boolean=} params.versions - If true, lists all versions of a file as distinct results. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watchAll: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/storage/v1/b/{bucket}/o/watch', method: 'POST' }, params: params, requiredParams: ['bucket'], pathParams: ['bucket'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Storage object * @type Storage */ module.exports = Storage;
Shance/newsaity74.ru
templates/blank_j3/node_modules/psi/node_modules/googleapis/apis/storage/v1.js
JavaScript
gpl-2.0
48,996
/* CopyRight (C) 1999, Dmitry Obukhov, dso@usa.net mailto: dso@usa.net http://www.EmbeddedStuff.com ---------------------------------------------- Last modified 6 Apr 97 ---------------------------------------------- Converts C (C++) source to HTML code fragment with syntax highlighting. Since program written for personal purpose the <TABLE> tags generated. This is optional page format specific thing. Usage: CTHM <input_file>. All output is done to STDOUTPUT, error messages to STDERR. For HTML fragment generation: CHTM file.c > file.htm - Some input convertion required to use this code as CGI module. Will be done soon. - Optimization required for blocks of EOL comments */ #include <stdio.h> // ------------------- Decoding status values #define START 0 #define INLINE 1 #define DEFINE 2 // ------------------- Decoding Remark #define REM1 20 #define REM2 21 #define REM_END 22 #define REM_STAR 23 #define REM_STAR_1 24 #define STRING 25 // String is "like" remark // ------------------- HTML TAG Generation #define ON 1 #define OFF 0 // ------------------- HTML TAG type #define MODE_KEYWORD 0 #define MODE_REMARK 2 #define MODE_REMARK_EOL 4 #define MODE_DEFINE 6 #define MODE_STRING 8 int is_delimeter(char c) { int ii=0; char dlms[] = "\t\r\n (){}[]+-*/%\"'&|^~:;<>.,"; //-------------------------------- while (dlms[ii]) { if (c==dlms[ii++]) return 1; } return 0; } int is_keyword(char * str) { char * kwords[] = { "asm", "auto", "break", "case", "cdecl", "char", "class", "const", "continue", "default", "delete", "do", "double", "else", "enum", "extern", "far", "float", "for", "friend", "goto", "huge", "if", "inline", "int", "interrupt", "long", "near", "new", "operator", "pascal", "private", "protected", "public", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "template", "this", "typedef", "union", "unsigned", "virtual", "void", "volatile", "while", NULL }; int ii=0; int jj; int check; while (kwords[ii]) { jj = 0; check = 1; while (kwords[ii][jj] && check) { if (str[jj] != kwords[ii][jj]) { check = 0; } jj++; } if (check) return 1; ii++; } return 0; } void set_mode(int on_off, int mode) { char * tags[] = { //-------------------- KEYWORD "<strong>", "</strong>", //-------------------- Classic remarks "<font color=\"#336600\">", "</font>", //-------------------- EOL Remarks "<font color=\"#336600\">", "</font>", //-------------------- #DEFINE "<font color=\"#663300\"><strong>", "</strong></font>", //-------------------- "string" "<font color=\"#0000CC\">", "</font>", NULL, NULL }; fprintf(stdout,tags[mode + 1 - on_off]); } void print_char_html(char c) { switch (c) { case '<': fprintf(stdout,"&lt;"); break; case '>': fprintf(stdout,"&gt;"); break; case '"': fprintf(stdout,"&quot;"); break; case '&': fprintf(stdout,"&amp;"); break; case '|': fprintf(stdout,"&brvbar;"); break; default: fprintf(stdout,"%c",c); } } int main(int _argc, char** _argv) { FILE *in, *out; char c; int mode; char buf[80]; int bufidx = 0; int progress = 1; int echo; int saved_mode; int kw; char tmpc; char prevc; if (_argc < 2) { fprintf(stderr, "USAGE: c2html <file>\n"); return 1; } if ((in = fopen(_argv[1], "rt")) == NULL) { fprintf(stderr, "Cannot open input file.\n"); return 1; } fprintf(stdout, "<pre>"); mode = START; while (!feof(in) && progress) { echo = 1; prevc = c; c = fgetc(in); if (c=='/' && (mode < REM1)) { saved_mode = mode; mode = REM1; } switch (mode) { case REM1: echo = 0; mode = REM2; break; case REM2: if (c=='/') { if (saved_mode == DEFINE) { set_mode(OFF, MODE_DEFINE); } mode = REM_END; set_mode(ON, MODE_REMARK_EOL); } else if (c=='*') { if (saved_mode == DEFINE) { set_mode(OFF, MODE_DEFINE); } mode = REM_STAR; set_mode(ON, MODE_REMARK); } else { mode = saved_mode; } printf("/"); break; case REM_END: if (c=='\n') { set_mode(OFF, MODE_REMARK_EOL); } break; case REM_STAR: if (c=='*') { mode = REM_STAR_1; } break; case REM_STAR_1: if (c=='/') { mode = INLINE; fprintf(stdout,"/"); echo = 0; set_mode(OFF, MODE_REMARK); } else mode = REM_STAR; break; case START: if (c=='#') { mode = DEFINE; set_mode(ON, MODE_DEFINE); break; } else if (c==' ') break; mode = INLINE; // and continue in next case case INLINE: if (c=='"' && // prevc != 0x27 && // prevc != '\\') // { set_mode(ON, MODE_STRING); mode = STRING; } break; case STRING: if (c=='"' && prevc != '\\') { print_char_html('"'); set_mode(OFF, MODE_STRING); echo = 0; mode = INLINE; } break; case DEFINE: if (c=='\n') { set_mode(OFF, MODE_DEFINE); } break; } if (echo && // (mode == INLINE || // (mode!=INLINE && // bufidx))) // { buf[bufidx++] = c; buf[bufidx] = 0; if (is_delimeter(c)) { kw = 0; if (bufidx>2) { kw = is_keyword(buf); } if (kw) { set_mode(ON, MODE_KEYWORD); } tmpc = buf[bufidx-1]; buf[bufidx-1] = 0; fprintf(stdout,"%s",buf); if (kw) { set_mode(OFF, MODE_KEYWORD); } print_char_html(tmpc); bufidx = 0; buf[0] = 0; } } else if (echo) print_char_html(c); if (c=='\n' && mode != REM_STAR) { mode = START; } } fclose(in); fprintf(stdout,"</pre>\n"); fprintf(stdout, "<!-- == Generated by CHTM convertor -->\n"); fprintf(stdout, "<!-- == CopyRight (C) 1999, Dmitry Obukhov, dso@usa.net -->\n"); return 0; }
kevintianbalance/.emacs.d
elisp/cscope-15.7a/contrib/webcscope/hilite.c
C
gpl-2.0
8,434
/* * Copyright 2010-2011 Freescale Semiconductor, Inc. * * 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 */ #include <common.h> #include <command.h> #include <hwconfig.h> #include <pci.h> #include <i2c.h> #include <asm/processor.h> #include <asm/mmu.h> #include <asm/cache.h> #include <asm/immap_85xx.h> #include <asm/fsl_pci.h> #include <asm/fsl_ddr_sdram.h> #include <asm/io.h> #include <asm/fsl_law.h> #include <asm/fsl_lbc.h> #include <asm/mp.h> #include <miiphy.h> #include <libfdt.h> #include <fdt_support.h> #include <fsl_mdio.h> #include <tsec.h> #include <vsc7385.h> #include <ioports.h> #include <asm/fsl_serdes.h> #include <netdev.h> #ifdef CONFIG_QE #define GPIO_GETH_SW_PORT 1 #define GPIO_GETH_SW_PIN 29 #define GPIO_GETH_SW_DATA (1 << (31 - GPIO_GETH_SW_PIN)) #define GPIO_SLIC_PORT 1 #define GPIO_SLIC_PIN 30 #define GPIO_SLIC_DATA (1 << (31 - GPIO_SLIC_PIN)) #if defined(CONFIG_P1025RDB) || defined(CONFIG_P1021RDB) #define PCA_IOPORT_I2C_ADDR 0x23 #define PCA_IOPORT_OUTPUT_CMD 0x2 #define PCA_IOPORT_CFG_CMD 0x6 #define PCA_IOPORT_QE_PIN_ENABLE 0xf8 #define PCA_IOPORT_QE_TDM_ENABLE 0xf6 #endif const qe_iop_conf_t qe_iop_conf_tab[] = { /* GPIO */ {1, 1, 2, 0, 0}, /* GPIO7/PB1 - LOAD_DEFAULT_N */ #if 0 {1, 8, 1, 1, 0}, /* GPIO10/PB8 - DDR_RST */ #endif {0, 15, 1, 0, 0}, /* GPIO11/A15 - WDI */ {GPIO_GETH_SW_PORT, GPIO_GETH_SW_PIN, 1, 0, 0}, /* RST_GETH_SW_N */ {GPIO_SLIC_PORT, GPIO_SLIC_PIN, 1, 0, 0}, /* RST_SLIC_N */ #ifdef CONFIG_P1025RDB /* QE_MUX_MDC */ {1, 19, 1, 0, 1}, /* QE_MUX_MDC */ /* QE_MUX_MDIO */ {1, 20, 3, 0, 1}, /* QE_MUX_MDIO */ /* UCC_1_MII */ {0, 23, 2, 0, 2}, /* CLK12 */ {0, 24, 2, 0, 1}, /* CLK9 */ {0, 7, 1, 0, 2}, /* ENET1_TXD0_SER1_TXD0 */ {0, 9, 1, 0, 2}, /* ENET1_TXD1_SER1_TXD1 */ {0, 11, 1, 0, 2}, /* ENET1_TXD2_SER1_TXD2 */ {0, 12, 1, 0, 2}, /* ENET1_TXD3_SER1_TXD3 */ {0, 6, 2, 0, 2}, /* ENET1_RXD0_SER1_RXD0 */ {0, 10, 2, 0, 2}, /* ENET1_RXD1_SER1_RXD1 */ {0, 14, 2, 0, 2}, /* ENET1_RXD2_SER1_RXD2 */ {0, 15, 2, 0, 2}, /* ENET1_RXD3_SER1_RXD3 */ {0, 5, 1, 0, 2}, /* ENET1_TX_EN_SER1_RTS_B */ {0, 13, 1, 0, 2}, /* ENET1_TX_ER */ {0, 4, 2, 0, 2}, /* ENET1_RX_DV_SER1_CTS_B */ {0, 8, 2, 0, 2}, /* ENET1_RX_ER_SER1_CD_B */ {0, 17, 2, 0, 2}, /* ENET1_CRS */ {0, 16, 2, 0, 2}, /* ENET1_COL */ /* UCC_5_RMII */ {1, 11, 2, 0, 1}, /* CLK13 */ {1, 7, 1, 0, 2}, /* ENET5_TXD0_SER5_TXD0 */ {1, 10, 1, 0, 2}, /* ENET5_TXD1_SER5_TXD1 */ {1, 6, 2, 0, 2}, /* ENET5_RXD0_SER5_RXD0 */ {1, 9, 2, 0, 2}, /* ENET5_RXD1_SER5_RXD1 */ {1, 5, 1, 0, 2}, /* ENET5_TX_EN_SER5_RTS_B */ {1, 4, 2, 0, 2}, /* ENET5_RX_DV_SER5_CTS_B */ {1, 8, 2, 0, 2}, /* ENET5_RX_ER_SER5_CD_B */ #endif {0, 0, 0, 0, QE_IOP_TAB_END} /* END of table */ }; #endif struct cpld_data { u8 cpld_rev_major; u8 pcba_rev; u8 wd_cfg; u8 rst_bps_sw; u8 load_default_n; u8 rst_bps_wd; u8 bypass_enable; u8 bps_led; u8 status_led; /* offset: 0x8 */ u8 fxo_led; /* offset: 0x9 */ u8 fxs_led; /* offset: 0xa */ u8 rev4[2]; u8 system_rst; /* offset: 0xd */ u8 bps_out; u8 rev5[3]; u8 cpld_rev_minor; }; #define CPLD_WD_CFG 0x03 #define CPLD_RST_BSW 0x00 #define CPLD_RST_BWD 0x00 #define CPLD_BYPASS_EN 0x03 #define CPLD_STATUS_LED 0x01 #define CPLD_FXO_LED 0x01 #define CPLD_FXS_LED 0x0F #define CPLD_SYS_RST 0x00 void board_cpld_init(void) { struct cpld_data *cpld_data = (void *)(CONFIG_SYS_CPLD_BASE); out_8(&cpld_data->wd_cfg, CPLD_WD_CFG); out_8(&cpld_data->status_led, CPLD_STATUS_LED); out_8(&cpld_data->fxo_led, CPLD_FXO_LED); out_8(&cpld_data->fxs_led, CPLD_FXS_LED); out_8(&cpld_data->system_rst, CPLD_SYS_RST); } void board_gpio_init(void) { #ifdef CONFIG_QE ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); par_io_t *par_io = (par_io_t *) &(gur->qe_par_io); /* Enable VSC7385 switch */ setbits_be32(&par_io[GPIO_GETH_SW_PORT].cpdat, GPIO_GETH_SW_DATA); /* Enable SLIC */ setbits_be32(&par_io[GPIO_SLIC_PORT].cpdat, GPIO_SLIC_DATA); #else ccsr_gpio_t *pgpio = (void *)(CONFIG_SYS_MPC85xx_GPIO_ADDR); /* * GPIO10 DDR Reset, open drain * GPIO7 LOAD_DEFAULT_N Input * GPIO11 WDI (watchdog input) * GPIO12 Ethernet Switch Reset * GPIO13 SLIC Reset */ setbits_be32(&pgpio->gpdir, 0x02130000); #if !defined(CONFIG_SYS_RAMBOOT) && !defined(CONFIG_SPL) /* init DDR3 reset signal */ setbits_be32(&pgpio->gpdir, 0x00200000); setbits_be32(&pgpio->gpodr, 0x00200000); clrbits_be32(&pgpio->gpdat, 0x00200000); udelay(1000); setbits_be32(&pgpio->gpdat, 0x00200000); udelay(1000); clrbits_be32(&pgpio->gpdir, 0x00200000); #endif #ifdef CONFIG_VSC7385_ENET /* reset VSC7385 Switch */ setbits_be32(&pgpio->gpdir, 0x00080000); setbits_be32(&pgpio->gpdat, 0x00080000); #endif #ifdef CONFIG_SLIC /* reset SLIC */ setbits_be32(&pgpio->gpdir, 0x00040000); setbits_be32(&pgpio->gpdat, 0x00040000); #endif #endif } int board_early_init_f(void) { ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); setbits_be32(&gur->pmuxcr, (MPC85xx_PMUXCR_SDHC_CD | MPC85xx_PMUXCR_SDHC_WP)); clrbits_be32(&gur->sdhcdcr, SDHCDCR_CD_INV); clrbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_SD_DATA); setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_TDM_ENA); board_gpio_init(); board_cpld_init(); return 0; } int checkboard(void) { struct cpld_data *cpld_data = (void *)(CONFIG_SYS_CPLD_BASE); ccsr_gur_t *gur = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); u8 in, out, io_config, val; printf("Board: %s CPLD: V%d.%d PCBA: V%d.0\n", CONFIG_BOARDNAME, in_8(&cpld_data->cpld_rev_major) & 0x0F, in_8(&cpld_data->cpld_rev_minor) & 0x0F, in_8(&cpld_data->pcba_rev) & 0x0F); /* Initialize i2c early for rom_loc and flash bank information */ i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); if (i2c_read(CONFIG_SYS_I2C_PCA9557_ADDR, 0, 1, &in, 1) < 0 || i2c_read(CONFIG_SYS_I2C_PCA9557_ADDR, 1, 1, &out, 1) < 0 || i2c_read(CONFIG_SYS_I2C_PCA9557_ADDR, 3, 1, &io_config, 1) < 0) { printf("Error reading i2c boot information!\n"); return 0; /* Don't want to hang() on this error */ } val = (in & io_config) | (out & (~io_config)); puts("rom_loc: "); if ((val & (~__SW_BOOT_MASK)) == __SW_BOOT_SD) { puts("sd"); #ifdef __SW_BOOT_SPI } else if ((val & (~__SW_BOOT_MASK)) == __SW_BOOT_SPI) { puts("spi"); #endif #ifdef __SW_BOOT_NAND } else if ((val & (~__SW_BOOT_MASK)) == __SW_BOOT_NAND) { puts("nand"); #endif #ifdef __SW_BOOT_PCIE } else if ((val & (~__SW_BOOT_MASK)) == __SW_BOOT_PCIE) { puts("pcie"); #endif } else { if (val & 0x2) puts("nor lower bank"); else puts("nor upper bank"); } puts("\n"); if (val & 0x1) { setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_SD_DATA); puts("SD/MMC : 8-bit Mode\n"); puts("eSPI : Disabled\n"); } else { puts("SD/MMC : 4-bit Mode\n"); puts("eSPI : Enabled\n"); } return 0; } #ifdef CONFIG_PCI void pci_init_board(void) { fsl_pcie_init_board(0); } #endif int board_early_init_r(void) { const unsigned int flashbase = CONFIG_SYS_FLASH_BASE; const u8 flash_esel = find_tlb_idx((void *)flashbase, 1); /* * Remap Boot flash region to caching-inhibited * so that flash can be erased properly. */ /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); /* invalidate existing TLB entry for flash */ disable_tlb(flash_esel); set_tlb(1, flashbase, CONFIG_SYS_FLASH_BASE_PHYS, /* tlb, epn, rpn */ MAS3_SX|MAS3_SW|MAS3_SR, MAS2_I|MAS2_G,/* perms, wimge */ 0, flash_esel, BOOKE_PAGESZ_64M, 1);/* ts, esel, tsize, iprot */ return 0; } int board_eth_init(bd_t *bis) { struct fsl_pq_mdio_info mdio_info; struct tsec_info_struct tsec_info[4]; ccsr_gur_t *gur __attribute__((unused)) = (void *)(CONFIG_SYS_MPC85xx_GUTS_ADDR); int num = 0; #ifdef CONFIG_VSC7385_ENET char *tmp; unsigned int vscfw_addr; #endif #ifdef CONFIG_TSEC1 SET_STD_TSEC_INFO(tsec_info[num], 1); num++; #endif #ifdef CONFIG_TSEC2 SET_STD_TSEC_INFO(tsec_info[num], 2); if (is_serdes_configured(SGMII_TSEC2)) { printf("eTSEC2 is in sgmii mode.\n"); tsec_info[num].flags |= TSEC_SGMII; } num++; #endif #ifdef CONFIG_TSEC3 SET_STD_TSEC_INFO(tsec_info[num], 3); num++; #endif if (!num) { printf("No TSECs initialized\n"); return 0; } #ifdef CONFIG_VSC7385_ENET /* If a VSC7385 microcode image is present, then upload it. */ if ((tmp = getenv("vscfw_addr")) != NULL) { vscfw_addr = simple_strtoul(tmp, NULL, 16); printf("uploading VSC7385 microcode from %x\n", vscfw_addr); if (vsc7385_upload_firmware((void *) vscfw_addr, CONFIG_VSC7385_IMAGE_SIZE)) puts("Failure uploading VSC7385 microcode.\n"); } else puts("No address specified for VSC7385 microcode.\n"); #endif mdio_info.regs = (struct tsec_mii_mng *)CONFIG_SYS_MDIO_BASE_ADDR; mdio_info.name = DEFAULT_MII_NAME; fsl_pq_mdio_init(bis, &mdio_info); tsec_eth_init(bis, tsec_info, num); #if defined(CONFIG_UEC_ETH) /* QE0 and QE3 need to be exposed for UCC1 and UCC5 Eth mode */ setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_QE0); setbits_be32(&gur->pmuxcr, MPC85xx_PMUXCR_QE3); uec_standard_init(bis); #endif return pci_eth_init(bis); } #if defined(CONFIG_QE) && \ (defined(CONFIG_P1025RDB) || defined(CONFIG_P1021RDB)) static void fdt_board_fixup_qe_pins(void *blob) { unsigned int oldbus; u8 val8; int node; fsl_lbc_t *lbc = LBC_BASE_ADDR; if (hwconfig("qe")) { /* For QE and eLBC pins multiplexing, * there is a PCA9555 device on P1025RDB. * It control the multiplex pins' functions, * and setting the PCA9555 can switch the * function between QE and eLBC. */ oldbus = i2c_get_bus_num(); i2c_set_bus_num(0); if (hwconfig("tdm")) val8 = PCA_IOPORT_QE_TDM_ENABLE; else val8 = PCA_IOPORT_QE_PIN_ENABLE; i2c_write(PCA_IOPORT_I2C_ADDR, PCA_IOPORT_CFG_CMD, 1, &val8, 1); i2c_write(PCA_IOPORT_I2C_ADDR, PCA_IOPORT_OUTPUT_CMD, 1, &val8, 1); i2c_set_bus_num(oldbus); /* if run QE TDM, Set ABSWP to implement * conversion of addresses in the eLBC. */ if (hwconfig("tdm")) { set_lbc_or(2, CONFIG_PMC_OR_PRELIM); set_lbc_br(2, CONFIG_PMC_BR_PRELIM); setbits_be32(&lbc->lbcr, CONFIG_SYS_LBC_LBCR); } } else { node = fdt_path_offset(blob, "/qe"); if (node >= 0) fdt_del_node(blob, node); } return; } #endif #ifdef CONFIG_OF_BOARD_SETUP void ft_board_setup(void *blob, bd_t *bd) { phys_addr_t base; phys_size_t size; ft_cpu_setup(blob, bd); base = getenv_bootm_low(); size = getenv_bootm_size(); fdt_fixup_memory(blob, (u64)base, (u64)size); FT_FSL_PCI_SETUP; #ifdef CONFIG_QE do_fixup_by_compat(blob, "fsl,qe", "status", "okay", sizeof("okay"), 0); #if defined(CONFIG_P1025RDB) || defined(CONFIG_P1021RDB) fdt_board_fixup_qe_pins(blob); #endif #endif #if defined(CONFIG_HAS_FSL_DR_USB) fdt_fixup_dr_usb(blob, bd); #endif } #endif
JeremySavonet/Eurobot-2017-Moon-Village
software/custom_leds/fpga/software/spl_bsp/uboot-socfpga/board/freescale/p1_p2_rdb_pc/p1_p2_rdb_pc.c
C
gpl-3.0
11,737
/* =========================================================================== Copyright (c) 2010-2015 Darkstar Dev Teams 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 3 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/ This file is part of DarkStar-server source code. =========================================================================== */ #include "../../common/socket.h" #include "char_sync.h" #include "../entities/charentity.h" CCharSyncPacket::CCharSyncPacket(CCharEntity* PChar) { this->type = 0x67; this->size = 0x14; WBUFB(data,(0x04)) = 0x02; WBUFB(data,(0x05)) = 0x09; WBUFW(data,(0x06)) = PChar->targid; WBUFL(data,(0x08)) = PChar->id; WBUFB(data,(0x10)) = PChar->StatusEffectContainer->HasStatusEffect(EFFECT_LEVEL_SYNC) ? 4 : 0; // 0x02 - Campaign Battle, 0x04 - Level Sync WBUFB(data,(0x25)) = PChar->jobs.job[PChar->GetMJob()]; // реальный уровень персонажа (при ограничении уровня отличается от m_mlvl) }
n0xus/darkstar
src/map/packets/char_sync.cpp
C++
gpl-3.0
1,592
<?php /** * Locale data for 'saq_KE'. * * This file is automatically generated by yiic cldr command. * * Copyright © 1991-2007 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in http://www.unicode.org/copyright.html. * * Copyright © 2008-2011 Yii Software LLC (http://www.yiiframework.com/license/) */ return array ( 'version' => '4590', 'numberSymbols' => array ( 'decimal' => '.', 'group' => ',', 'list' => ';', 'percentSign' => '%', 'nativeZeroDigit' => '0', 'patternDigit' => '#', 'plusSign' => '+', 'minusSign' => '-', 'exponential' => 'E', 'perMille' => '‰', 'infinity' => '∞', 'nan' => 'NaN', ), 'decimalFormat' => '#,##0.###', 'scientificFormat' => '#E0', 'percentFormat' => '#,##0%', 'currencyFormat' => '¤#,##0.00;(¤#,##0.00)', 'currencySymbols' => array ( 'AFN' => 'Af', 'ANG' => 'NAf.', 'AOA' => 'Kz', 'ARA' => '₳', 'ARL' => '$L', 'ARM' => 'm$n', 'ARS' => 'AR$', 'AUD' => 'AU$', 'AWG' => 'Afl.', 'AZN' => 'man.', 'BAM' => 'KM', 'BBD' => 'Bds$', 'BDT' => 'Tk', 'BEF' => 'BF', 'BHD' => 'BD', 'BIF' => 'FBu', 'BMD' => 'BD$', 'BND' => 'BN$', 'BOB' => 'Bs', 'BOP' => '$b.', 'BRL' => 'R$', 'BSD' => 'BS$', 'BTN' => 'Nu.', 'BWP' => 'BWP', 'BZD' => 'BZ$', 'CAD' => 'CA$', 'CDF' => 'CDF', 'CLE' => 'Eº', 'CLP' => 'CL$', 'CNY' => 'CN¥', 'COP' => 'CO$', 'CRC' => '₡', 'CUC' => 'CUC$', 'CUP' => 'CU$', 'CVE' => 'CV$', 'CYP' => 'CY£', 'CZK' => 'Kč', 'DEM' => 'DM', 'DJF' => 'Fdj', 'DKK' => 'Dkr', 'DOP' => 'RD$', 'DZD' => 'DA', 'EEK' => 'Ekr', 'ERN' => 'Nfk', 'ESP' => 'Pts', 'ETB' => 'Br', 'EUR' => '€', 'FIM' => 'mk', 'FJD' => 'FJ$', 'FKP' => 'FK£', 'FRF' => '₣', 'GBP' => '£', 'GHC' => '₵', 'GHS' => 'GH₵', 'GIP' => 'GI£', 'GMD' => 'GMD', 'GNF' => 'FG', 'GRD' => '₯', 'GTQ' => 'GTQ', 'GYD' => 'GY$', 'HKD' => 'HK$', 'HNL' => 'HNL', 'HRK' => 'kn', 'HTG' => 'HTG', 'HUF' => 'Ft', 'IDR' => 'Rp', 'IEP' => 'IR£', 'ILP' => 'I£', 'ILS' => '₪', 'INR' => 'Rs', 'ISK' => 'Ikr', 'ITL' => 'IT₤', 'JMD' => 'J$', 'JOD' => 'JD', 'JPY' => 'JP¥', 'KES' => 'Ksh', 'KMF' => 'CF', 'KRW' => '₩', 'KWD' => 'KD', 'KYD' => 'KY$', 'LAK' => '₭', 'LBP' => 'LB£', 'LKR' => 'SLRs', 'LRD' => 'L$', 'LSL' => 'LSL', 'LTL' => 'Lt', 'LVL' => 'Ls', 'LYD' => 'LD', 'MMK' => 'MMK', 'MNT' => '₮', 'MOP' => 'MOP$', 'MRO' => 'UM', 'MTL' => 'Lm', 'MTP' => 'MT£', 'MUR' => 'MURs', 'MXN' => 'MX$', 'MYR' => 'RM', 'MZM' => 'Mt', 'MZN' => 'MTn', 'NAD' => 'N$', 'NGN' => '₦', 'NIO' => 'C$', 'NLG' => 'fl', 'NOK' => 'Nkr', 'NPR' => 'NPRs', 'NZD' => 'NZ$', 'PAB' => 'B/.', 'PEI' => 'I/.', 'PEN' => 'S/.', 'PGK' => 'PGK', 'PHP' => '₱', 'PKR' => 'PKRs', 'PLN' => 'zł', 'PTE' => 'Esc', 'PYG' => '₲', 'QAR' => 'QR', 'RHD' => 'RH$', 'RON' => 'RON', 'RSD' => 'din.', 'SAR' => 'SR', 'SBD' => 'SI$', 'SCR' => 'SRe', 'SDD' => 'LSd', 'SEK' => 'Skr', 'SGD' => 'S$', 'SHP' => 'SH£', 'SKK' => 'Sk', 'SLL' => 'Le', 'SOS' => 'Ssh', 'SRD' => 'SR$', 'SRG' => 'Sf', 'STD' => 'Db', 'SVC' => 'SV₡', 'SYP' => 'SY£', 'SZL' => 'SZL', 'THB' => '฿', 'TMM' => 'TMM', 'TND' => 'DT', 'TOP' => 'T$', 'TRL' => 'TRL', 'TRY' => 'TL', 'TTD' => 'TT$', 'TWD' => 'NT$', 'TZS' => 'TSh', 'UAH' => '₴', 'UGX' => 'USh', 'USD' => 'US$', 'UYU' => '$U', 'VEF' => 'Bs.F.', 'VND' => '₫', 'VUV' => 'VT', 'WST' => 'WS$', 'XAF' => 'FCFA', 'XCD' => 'EC$', 'XOF' => 'CFA', 'XPF' => 'CFPF', 'YER' => 'YR', 'ZAR' => 'R', 'ZMK' => 'ZK', 'ZRN' => 'NZ', 'ZRZ' => 'ZRZ', 'ZWD' => 'Z$', ), 'monthNames' => array ( 'wide' => array ( 1 => 'Lapa le obo', 2 => 'Lapa le waare', 3 => 'Lapa le okuni', 4 => 'Lapa le ong\'wan', 5 => 'Lapa le imet', 6 => 'Lapa le ile', 7 => 'Lapa le sapa', 8 => 'Lapa le isiet', 9 => 'Lapa le saal', 10 => 'Lapa le tomon', 11 => 'Lapa le tomon obo', 12 => 'Lapa le tomon waare', ), 'abbreviated' => array ( 1 => 'Obo', 2 => 'Waa', 3 => 'Oku', 4 => 'Ong', 5 => 'Ime', 6 => 'Ile', 7 => 'Sap', 8 => 'Isi', 9 => 'Saa', 10 => 'Tom', 11 => 'Tob', 12 => 'Tow', ), ), 'monthNamesSA' => array ( 'narrow' => array ( 1 => 'O', 2 => 'W', 3 => 'O', 4 => 'O', 5 => 'I', 6 => 'I', 7 => 'S', 8 => 'I', 9 => 'S', 10 => 'T', 11 => 'T', 12 => 'T', ), ), 'weekDayNames' => array ( 'wide' => array ( 0 => 'Mderot ee are', 1 => 'Mderot ee kuni', 2 => 'Mderot ee ong\'wan', 3 => 'Mderot ee inet', 4 => 'Mderot ee ile', 5 => 'Mderot ee sapa', 6 => 'Mderot ee kwe', ), 'abbreviated' => array ( 0 => 'Are', 1 => 'Kun', 2 => 'Ong', 3 => 'Ine', 4 => 'Ile', 5 => 'Sap', 6 => 'Kwe', ), ), 'weekDayNamesSA' => array ( 'narrow' => array ( 0 => 'A', 1 => 'K', 2 => 'O', 3 => 'I', 4 => 'I', 5 => 'S', 6 => 'K', ), ), 'eraNames' => array ( 'abbreviated' => array ( 0 => 'KK', 1 => 'BK', ), 'wide' => array ( 0 => 'Kabla ya Christo', 1 => 'Baada ya Christo', ), 'narrow' => array ( 0 => 'KK', 1 => 'BK', ), ), 'dateFormats' => array ( 'full' => 'EEEE, d MMMM y', 'long' => 'd MMMM y', 'medium' => 'd MMM y', 'short' => 'dd/MM/yyyy', ), 'timeFormats' => array ( 'full' => 'h:mm:ss a zzzz', 'long' => 'h:mm:ss a z', 'medium' => 'h:mm:ss a', 'short' => 'h:mm a', ), 'dateTimeFormat' => '{1} {0}', 'amName' => 'Tesiran', 'pmName' => 'Teipa', 'orientation' => 'ltr', );
anandaverma/ixpense
yii/yii/framework/i18n/data/saq_ke.php
PHP
gpl-3.0
6,351
/* GStreamer * Copyright (C) 2008 David Schleef <ds@entropywave.com> * * 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., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef _GST_CMS_H_ #define _GST_CMS_H_ #include <gst/gst.h> G_BEGIN_DECLS typedef struct _Color Color; typedef struct _ColorMatrix ColorMatrix; struct _Color { double v[3]; }; struct _ColorMatrix { double m[4][4]; }; void color_xyY_to_XYZ (Color * c); void color_XYZ_to_xyY (Color * c); void color_set (Color * c, double x, double y, double z); void color_matrix_set_identity (ColorMatrix * m); void color_matrix_dump (ColorMatrix * m); void color_matrix_multiply (ColorMatrix * dst, ColorMatrix * a, ColorMatrix * b); void color_matrix_apply (ColorMatrix * m, Color * dest, Color * src); void color_matrix_offset_components (ColorMatrix * m, double a1, double a2, double a3); void color_matrix_scale_components (ColorMatrix * m, double a1, double a2, double a3); void color_matrix_YCbCr_to_RGB (ColorMatrix * m, double Kr, double Kb); void color_matrix_RGB_to_YCbCr (ColorMatrix * m, double Kr, double Kb); void color_matrix_build_yuv_to_rgb_601 (ColorMatrix * dst); void color_matrix_build_bt709_to_bt601 (ColorMatrix * dst); void color_matrix_build_rgb_to_yuv_601 (ColorMatrix * dst); void color_matrix_invert (ColorMatrix * m); void color_matrix_copy (ColorMatrix * dest, ColorMatrix * src); void color_matrix_transpose (ColorMatrix * m); void color_matrix_build_XYZ (ColorMatrix * dst, double rx, double ry, double gx, double gy, double bx, double by, double wx, double wy); void color_matrix_build_rgb_to_XYZ_601 (ColorMatrix * dst); void color_matrix_build_XYZ_to_rgb_709 (ColorMatrix * dst); void color_matrix_build_XYZ_to_rgb_dell (ColorMatrix * dst); void color_transfer_function_apply (Color * dest, Color * src); void color_transfer_function_unapply (Color * dest, Color * src); void color_gamut_clamp (Color * dest, Color * src); G_END_DECLS #endif
cpopescu/whispermedialib
third-party/gstreamer/gst-plugins-bad-0.10.19/ext/cog/gstcms.h
C
lgpl-3.0
2,607
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Statistics.php 20096 2010-01-06 02:05:09Z bkarwin $ */ /** * @see Zend_Gdata_Extension */ #require_once 'Zend/Gdata/Extension.php'; /** * Represents the yt:statistics element used by the YouTube data API * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_Extension_Statistics extends Zend_Gdata_Extension { protected $_rootNamespace = 'yt'; protected $_rootElement = 'statistics'; /** * The videoWatchCount attribute specifies the number of videos * that a user has watched on YouTube. The videoWatchCount attribute * is only specified when the <yt:statistics> tag appears within a * user profile entry. * * @var integer */ protected $_videoWatchCount = null; /** * When the viewCount attribute refers to a video entry, the attribute * specifies the number of times that the video has been viewed. * When the viewCount attribute refers to a user profile, the attribute * specifies the number of times that the user's profile has been * viewed. * * @var integer */ protected $_viewCount = null; /** * The subscriberCount attribute specifies the number of YouTube users * who have subscribed to a particular user's YouTube channel. * The subscriberCount attribute is only specified when the * <yt:statistics> tag appears within a user profile entry. * * @var integer */ protected $_subscriberCount = null; /** * The lastWebAccess attribute indicates the most recent time that * a particular user used YouTube. * * @var string */ protected $_lastWebAccess = null; /** * The favoriteCount attribute specifies the number of YouTube users * who have added a video to their list of favorite videos. The * favoriteCount attribute is only specified when the * <yt:statistics> tag appears within a video entry. * * @var integer */ protected $_favoriteCount = null; /** * Constructs a new Zend_Gdata_YouTube_Extension_Statistics object. * @param string $viewCount(optional) The viewCount value * @param string $videoWatchCount(optional) The videoWatchCount value * @param string $subscriberCount(optional) The subscriberCount value * @param string $lastWebAccess(optional) The lastWebAccess value * @param string $favoriteCount(optional) The favoriteCount value */ public function __construct($viewCount = null, $videoWatchCount = null, $subscriberCount = null, $lastWebAccess = null, $favoriteCount = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct(); $this->_viewCount = $viewCount; $this->_videoWatchCount = $videoWatchCount; $this->_subscriberCount = $subscriberCount; $this->_lastWebAccess = $lastWebAccess; $this->_favoriteCount = $favoriteCount; } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for sending to the server upon updates, or * for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_videoWatchCount !== null) { $element->setAttribute('watchCount', $this->_videoWatchCount); } if ($this->_viewCount !== null) { $element->setAttribute('viewCount', $this->_viewCount); } if ($this->_subscriberCount !== null) { $element->setAttribute('subscriberCount', $this->_subscriberCount); } if ($this->_lastWebAccess !== null) { $element->setAttribute('lastWebAccess', $this->_lastWebAccess); } if ($this->_favoriteCount !== null) { $element->setAttribute('favoriteCount', $this->_favoriteCount); } return $element; } /** * Given a DOMNode representing an attribute, tries to map the data into * instance members. If no mapping is defined, the name and valueare * stored in an array. * TODO: Convert attributes to proper types * * @param DOMNode $attribute The DOMNode attribute needed to be handled */ protected function takeAttributeFromDOM($attribute) { switch ($attribute->localName) { case 'videoWatchCount': $this->_videoWatchCount = $attribute->nodeValue; break; case 'viewCount': $this->_viewCount = $attribute->nodeValue; break; case 'subscriberCount': $this->_subscriberCount = $attribute->nodeValue; break; case 'lastWebAccess': $this->_lastWebAccess = $attribute->nodeValue; break; case 'favoriteCount': $this->_favoriteCount = $attribute->nodeValue; break; default: parent::takeAttributeFromDOM($attribute); } } /** * Get the value for this element's viewCount attribute. * * @return int The value associated with this attribute. */ public function getViewCount() { return $this->_viewCount; } /** * Set the value for this element's viewCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setViewCount($value) { $this->_viewCount = $value; return $this; } /** * Get the value for this element's videoWatchCount attribute. * * @return int The value associated with this attribute. */ public function getVideoWatchCount() { return $this->_videoWatchCount; } /** * Set the value for this element's videoWatchCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setVideoWatchCount($value) { $this->_videoWatchCount = $value; return $this; } /** * Get the value for this element's subscriberCount attribute. * * @return int The value associated with this attribute. */ public function getSubscriberCount() { return $this->_subscriberCount; } /** * Set the value for this element's subscriberCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setSubscriberCount($value) { $this->_subscriberCount = $value; return $this; } /** * Get the value for this element's lastWebAccess attribute. * * @return int The value associated with this attribute. */ public function getLastWebAccess() { return $this->_lastWebAccess; } /** * Set the value for this element's lastWebAccess attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setLastWebAccess($value) { $this->_lastWebAccess = $value; return $this; } /** * Get the value for this element's favoriteCount attribute. * * @return int The value associated with this attribute. */ public function getFavoriteCount() { return $this->_favoriteCount; } /** * Set the value for this element's favoriteCount attribute. * * @param int $value The desired value for this attribute. * @return Zend_Gdata_YouTube_Extension_Statistics The element being * modified. */ public function setFavoriteCount($value) { $this->_favoriteCount = $value; return $this; } /** * Magic toString method allows using this directly via echo * Works best in PHP >= 4.2.0 * * @return string */ public function __toString() { return 'View Count=' . $this->_viewCount . ' VideoWatchCount=' . $this->_videoWatchCount . ' SubscriberCount=' . $this->_subscriberCount . ' LastWebAccess=' . $this->_lastWebAccess . ' FavoriteCount=' . $this->_favoriteCount; } }
dbashyal/MagentoStarterBase
trunk/lib/Zend/Gdata/YouTube/Extension/Statistics.php
PHP
lgpl-3.0
9,761
/*========================================================================= Program: Visualization Toolkit Module: TaskParallelismWithPorts.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __TASKPARA_H #define __TASKPARA_H #include "vtkMultiProcessController.h" #include "vtkRTAnalyticSource.h" #include "vtkFieldDataToAttributeDataFilter.h" #include "vtkAttributeDataToFieldDataFilter.h" #include "vtkImageShrink3D.h" #include "vtkGlyph3D.h" #include "vtkGlyphSource2D.h" #include "vtkImageGradient.h" #include "vtkImageGradientMagnitude.h" #include "vtkImageGaussianSmooth.h" #include "vtkProbeFilter.h" #include "vtkDataSetMapper.h" #include "vtkContourFilter.h" #include "vtkActor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkAssignAttribute.h" typedef void (*taskFunction)(double data); void task3(double data); void task4(double data); static const double EXTENT = 20; static const int WINDOW_WIDTH = 400; static const int WINDOW_HEIGHT = 300; #endif
gisfromscratch/datavisualizer
lib/vtk/include/Examples/ParallelProcessing/Generic/Cxx/TaskParallelismWithPorts.h
C
apache-2.0
1,405
/* * Copyright 2010-2015 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. */ package com.amazonaws.services.glacier.model.transform; import com.amazonaws.AmazonServiceException; import com.amazonaws.transform.GlacierErrorUnmarshaller; import com.amazonaws.util.json.JSONObject; import com.amazonaws.services.glacier.model.InvalidParameterValueException; public class InvalidParameterValueExceptionUnmarshaller extends GlacierErrorUnmarshaller { public InvalidParameterValueExceptionUnmarshaller() { super(InvalidParameterValueException.class); } @Override public boolean match(String errorTypeFromHeader, JSONObject json) throws Exception { if (errorTypeFromHeader == null) { // Parse error type from the JSON content if it's not available in the response headers String errorCodeFromContent = parseErrorCode(json); return (errorCodeFromContent != null && errorCodeFromContent.equals("InvalidParameterValueException")); } else { return errorTypeFromHeader.equals("InvalidParameterValueException"); } } @Override public AmazonServiceException unmarshall(JSONObject json) throws Exception { InvalidParameterValueException e = (InvalidParameterValueException)super.unmarshall(json); e.setErrorCode("InvalidParameterValueException"); e.setType(parseMember("Type", json)); e.setCode(parseMember("Code", json)); return e; } }
mahaliachante/aws-sdk-java
aws-java-sdk-glacier/src/main/java/com/amazonaws/services/glacier/model/transform/InvalidParameterValueExceptionUnmarshaller.java
Java
apache-2.0
2,012
.mblTextArea {overflow: auto;}.dj_ff3 .mblTextArea {-moz-border-radius: 0;}
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/mobile/themes/windows/TextArea-compat.css
CSS
apache-2.0
75
<?php final class ArcanistPuppetLintLinterTestCase extends ArcanistExternalLinterTestCase { public function testLinter() { $this->executeTestsInDirectory(dirname(__FILE__).'/puppet-lint/'); } }
codelabs-ch/arcanist
src/lint/linter/__tests__/ArcanistPuppetLintLinterTestCase.php
PHP
apache-2.0
207
### `tf.sigmoid(x, name=None)` {#sigmoid} Computes sigmoid of `x` element-wise. Specifically, `y = 1 / (1 + exp(-x))`. ##### Args: * <b>`x`</b>: A Tensor with type `float32`, `float64`, `int32`, `complex64`, `int64`, or `qint32`. * <b>`name`</b>: A name for the operation (optional). ##### Returns: A Tensor with the same type as `x` if `x.dtype != qint32` otherwise the return type is `quint8`. @compatibility(numpy) Equivalent to np.scipy.special.expit @end_compatibility
anilmuthineni/tensorflow
tensorflow/g3doc/api_docs/python/functions_and_classes/shard6/tf.sigmoid.md
Markdown
apache-2.0
495
/* * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project * * 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 com.sina.weibo.sdk.openapi.models; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * 微博结构体。 * * @author SINA * @since 2013-11-22 */ public class Status { /** 微博创建时间 */ public String created_at; /** 微博ID */ public String id; /** 微博MID */ public String mid; /** 字符串型的微博ID */ public String idstr; /** 微博信息内容 */ public String text; /** 微博来源 */ public String source; /** 是否已收藏,true:是,false:否 */ public boolean favorited; /** 是否被截断,true:是,false:否 */ public boolean truncated; /**(暂未支持)回复ID */ public String in_reply_to_status_id; /**(暂未支持)回复人UID */ public String in_reply_to_user_id; /**(暂未支持)回复人昵称 */ public String in_reply_to_screen_name; /** 缩略图片地址(小图),没有时不返回此字段 */ public String thumbnail_pic; /** 中等尺寸图片地址(中图),没有时不返回此字段 */ public String bmiddle_pic; /** 原始图片地址(原图),没有时不返回此字段 */ public String original_pic; /** 地理信息字段 */ public Geo geo; /** 微博作者的用户信息字段 */ public User user; /** 被转发的原微博信息字段,当该微博为转发微博时返回 */ public Status retweeted_status; /** 转发数 */ public int reposts_count; /** 评论数 */ public int comments_count; /** 表态数 */ public int attitudes_count; /** 暂未支持 */ public int mlevel; /** * 微博的可见性及指定可见分组信息。该 object 中 type 取值, * 0:普通微博,1:私密微博,3:指定分组微博,4:密友微博; * list_id为分组的组号 */ public Visible visible; /** 微博配图地址。多图时返回多图链接。无配图返回"[]" */ public ArrayList<String> pic_urls; /** 微博流内的推广微博ID */ //public Ad ad; public static Status parse(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); return Status.parse(jsonObject); } catch (JSONException e) { e.printStackTrace(); } return null; } public static Status parse(JSONObject jsonObject) { if (null == jsonObject) { return null; } Status status = new Status(); status.created_at = jsonObject.optString("created_at"); status.id = jsonObject.optString("id"); status.mid = jsonObject.optString("mid"); status.idstr = jsonObject.optString("idstr"); status.text = jsonObject.optString("text"); status.source = jsonObject.optString("source"); status.favorited = jsonObject.optBoolean("favorited", false); status.truncated = jsonObject.optBoolean("truncated", false); // Have NOT supported status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id"); status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id"); status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name"); status.thumbnail_pic = jsonObject.optString("thumbnail_pic"); status.bmiddle_pic = jsonObject.optString("bmiddle_pic"); status.original_pic = jsonObject.optString("original_pic"); status.geo = Geo.parse(jsonObject.optJSONObject("geo")); status.user = User.parse(jsonObject.optJSONObject("user")); status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status")); status.reposts_count = jsonObject.optInt("reposts_count"); status.comments_count = jsonObject.optInt("comments_count"); status.attitudes_count = jsonObject.optInt("attitudes_count"); status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported status.visible = Visible.parse(jsonObject.optJSONObject("visible")); JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls"); if (picUrlsArray != null && picUrlsArray.length() > 0) { int length = picUrlsArray.length(); status.pic_urls = new ArrayList<String>(length); JSONObject tmpObject = null; for (int ix = 0; ix < length; ix++) { tmpObject = picUrlsArray.optJSONObject(ix); if (tmpObject != null) { status.pic_urls.add(tmpObject.optString("thumbnail_pic")); } } } //status.ad = jsonObject.optString("ad", ""); return status; } }
zjupure/SneezeReader
weibosdk/src/main/java/com/sina/weibo/sdk/openapi/models/Status.java
Java
apache-2.0
5,659
// Random number generator - requires a PRNG backend, e.g. prng4.js // For best results, put code like // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'> // in your main HTML document. var rng_state; var rng_pool; var rng_pptr; // Mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // Mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new Date().getTime()); } // Initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new Array(); rng_pptr = 0; var t; if(window.crypto && window.crypto.getRandomValues) { // Use webcrypto if available var ua = new Uint8Array(32); window.crypto.getRandomValues(ua); for(t = 0; t < 32; ++t) rng_pool[rng_pptr++] = ua[t]; } if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) { // Extract entropy (256 bits) from NS4 RNG if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charCodeAt(t) & 255; } while(rng_pptr < rng_psize) { // extract some randomness from Math.random() t = Math.floor(65536 * Math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenX); //rng_seed_int(window.screenY); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // TODO: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function SecureRandom() {} SecureRandom.prototype.nextBytes = rng_get_bytes;
enketosurvey/mo
www/lib/rsa/rng.js
JavaScript
apache-2.0
2,112
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2011 Bryce Lelbach Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include "uint.hpp" int main() { using spirit_test::test; using spirit_test::test_attr; /////////////////////////////////////////////////////////////////////////// // unsigned tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::uint_; unsigned u; BOOST_TEST(test("123456", uint_)); BOOST_TEST(test_attr("123456", uint_, u)); BOOST_TEST(u == 123456); BOOST_TEST(test(max_unsigned, uint_)); BOOST_TEST(test_attr(max_unsigned, uint_, u)); BOOST_TEST(u == UINT_MAX); BOOST_TEST(!test(unsigned_overflow, uint_)); BOOST_TEST(!test_attr(unsigned_overflow, uint_, u)); } /////////////////////////////////////////////////////////////////////////// // binary tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::bin; unsigned u; BOOST_TEST(test("11111110", bin)); BOOST_TEST(test_attr("11111110", bin, u)); BOOST_TEST(u == 0xFE); BOOST_TEST(test(max_binary, bin)); BOOST_TEST(test_attr(max_binary, bin, u)); BOOST_TEST(u == UINT_MAX); BOOST_TEST(!test(binary_overflow, bin)); BOOST_TEST(!test_attr(binary_overflow, bin, u)); } /////////////////////////////////////////////////////////////////////////// // octal tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::oct; unsigned u; BOOST_TEST(test("12545674515", oct)); BOOST_TEST(test_attr("12545674515", oct, u)); BOOST_TEST(u == 012545674515); BOOST_TEST(test(max_octal, oct)); BOOST_TEST(test_attr(max_octal, oct, u)); BOOST_TEST(u == UINT_MAX); BOOST_TEST(!test(octal_overflow, oct)); BOOST_TEST(!test_attr(octal_overflow, oct, u)); } /////////////////////////////////////////////////////////////////////////// // hex tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::hex; unsigned u; BOOST_TEST(test("95BC8DF", hex)); BOOST_TEST(test_attr("95BC8DF", hex, u)); BOOST_TEST(u == 0x95BC8DF); BOOST_TEST(test("abcdef12", hex)); BOOST_TEST(test_attr("abcdef12", hex, u)); BOOST_TEST(u == 0xabcdef12); BOOST_TEST(test(max_hex, hex)); BOOST_TEST(test_attr(max_hex, hex, u)); BOOST_TEST(u == UINT_MAX); BOOST_TEST(!test(hex_overflow, hex)); BOOST_TEST(!test_attr(hex_overflow, hex, u)); } /////////////////////////////////////////////////////////////////////////// // limited fieldwidth /////////////////////////////////////////////////////////////////////////// { unsigned u; using boost::spirit::qi::uint_parser; uint_parser<unsigned, 10, 1, 3> uint3; BOOST_TEST(test("123456", uint3, false)); BOOST_TEST(test_attr("123456", uint3, u, false)); BOOST_TEST(u == 123); uint_parser<unsigned, 10, 2, 4> uint4; BOOST_TEST(test("123456", uint4, false)); BOOST_TEST(test_attr("123456", uint4, u, false)); BOOST_TEST(u == 1234); char const * first = "0000000"; char const * last = first + std::strlen(first); uint_parser<unsigned, 10, 4, 4> uint_exact4; BOOST_TEST(boost::spirit::qi::parse(first, last, uint_exact4, u) && first != last && (last-first == 3) && u == 0); first = "0001400"; last = first + std::strlen(first); BOOST_TEST(boost::spirit::qi::parse(first, last, uint_exact4, u) && first != last && (last-first == 3) && u == 1); BOOST_TEST(!test("1", uint4)); BOOST_TEST(!test_attr("1", uint4, u)); BOOST_TEST(test_attr("014567", uint4, u, false) && u == 145); } /////////////////////////////////////////////////////////////////////////// // action tests /////////////////////////////////////////////////////////////////////////// { using boost::phoenix::ref; using boost::spirit::qi::_1; using boost::spirit::qi::uint_; using boost::spirit::ascii::space; int n; BOOST_TEST(test("123", uint_[ref(n) = _1])); BOOST_TEST(n == 123); BOOST_TEST(test(" 456", uint_[ref(n) = _1], space)); BOOST_TEST(n == 456); } /////////////////////////////////////////////////////////////////////////// // Check overflow is parse error /////////////////////////////////////////////////////////////////////////// { boost::spirit::qi::uint_parser<boost::uint8_t> uint8_; boost::uint8_t u8; BOOST_TEST(!test_attr("999", uint8_, u8)); BOOST_TEST(!test_attr("256", uint8_, u8)); BOOST_TEST(test_attr("255", uint8_, u8)); boost::spirit::qi::uint_parser<boost::uint16_t> uint16_; boost::uint16_t u16; BOOST_TEST(!test_attr("99999", uint16_, u16)); BOOST_TEST(!test_attr("65536", uint16_, u16)); BOOST_TEST(test_attr("65535", uint16_, u16)); boost::spirit::qi::uint_parser<boost::uint32_t> uint32_; boost::uint32_t u32; BOOST_TEST(!test_attr("9999999999", uint32_, u32)); BOOST_TEST(!test_attr("4294967296", uint32_, u32)); BOOST_TEST(test_attr("4294967295", uint32_, u32)); } /////////////////////////////////////////////////////////////////////////// // custom uint tests /////////////////////////////////////////////////////////////////////////// { using boost::spirit::qi::uint_; using boost::spirit::qi::uint_parser; custom_uint u; BOOST_TEST(test_attr("123456", uint_, u)); uint_parser<custom_uint, 10, 1, 2> uint2; BOOST_TEST(test_attr("12", uint2, u)); } return boost::report_errors(); }
NixaSoftware/CVis
venv/bin/libs/spirit/test/qi/uint1.cpp
C++
apache-2.0
6,465
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.filter; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.search.aggregations.AggregationStreams; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.InternalSingleBucketAggregation; import java.io.IOException; /** * */ public class InternalFilter extends InternalSingleBucketAggregation implements Filter { public final static Type TYPE = new Type("filter"); public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public InternalFilter readResult(StreamInput in) throws IOException { InternalFilter result = new InternalFilter(); result.readFrom(in); return result; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } InternalFilter() {} // for serialization InternalFilter(String name, long docCount, InternalAggregations subAggregations) { super(name, docCount, subAggregations); } @Override public Type type() { return TYPE; } @Override protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) { return new InternalFilter(name, docCount, subAggregations); } }
corochoone/elasticsearch
src/main/java/org/elasticsearch/search/aggregations/bucket/filter/InternalFilter.java
Java
apache-2.0
2,222
/* ========================================================== * bootstrap-formhelpers-countries.en_US.js * https://github.com/vlamanna/BootstrapFormHelpers * ========================================================== * Copyright 2012 Vincent Lamanna * * 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. * ========================================================== */ var BFHCountriesList = { 'AF': 'Afghanistan', 'AL': 'Albania', 'DZ': 'Algeria', 'AS': 'American Samoa', 'AD': 'Andorra', 'AO': 'Angola', 'AI': 'Anguilla', 'AQ': 'Antarctica', 'AG': 'Antigua and Barbuda', 'AR': 'Argentina', 'AM': 'Armenia', 'AW': 'Aruba', 'AU': 'Australia', 'AT': 'Austria', 'AZ': 'Azerbaijan', 'BH': 'Bahrain', 'BD': 'Bangladesh', 'BB': 'Barbados', 'BY': 'Belarus', 'BE': 'Belgium', 'BZ': 'Belize', 'BJ': 'Benin', 'BM': 'Bermuda', 'BT': 'Bhutan', 'BO': 'Bolivia', 'BA': 'Bosnia and Herzegovina', 'BW': 'Botswana', 'BV': 'Bouvet Island', 'BR': 'Brazil', 'IO': 'British Indian Ocean Territory', 'VG': 'British Virgin Islands', 'BN': 'Brunei', 'BG': 'Bulgaria', 'BF': 'Burkina Faso', 'BI': 'Burundi', 'CI': 'Côte d\'Ivoire', 'KH': 'Cambodia', 'CM': 'Cameroon', 'CA': 'Canada', 'CV': 'Cape Verde', 'KY': 'Cayman Islands', 'CF': 'Central African Republic', 'TD': 'Chad', 'CL': 'Chile', 'CN': 'China', 'CX': 'Christmas Island', 'CC': 'Cocos (Keeling) Islands', 'CO': 'Colombia', 'KM': 'Comoros', 'CG': 'Congo', 'CK': 'Cook Islands', 'CR': 'Costa Rica', 'HR': 'Croatia', 'CU': 'Cuba', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'CD': 'Democratic Republic of the Congo', 'DK': 'Denmark', 'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'TP': 'East Timor', 'EC': 'Ecuador', 'EG': 'Egypt', 'SV': 'El Salvador', 'GQ': 'Equatorial Guinea', 'ER': 'Eritrea', 'EE': 'Estonia', 'ET': 'Ethiopia', 'FO': 'Faeroe Islands', 'FK': 'Falkland Islands', 'FJ': 'Fiji', 'FI': 'Finland', 'MK': 'Former Yugoslav Republic of Macedonia', 'FR': 'France', 'FX': 'France, Metropolitan', 'GF': 'French Guiana', 'PF': 'French Polynesia', 'TF': 'French Southern Territories', 'GA': 'Gabon', 'GE': 'Georgia', 'DE': 'Germany', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GR': 'Greece', 'GL': 'Greenland', 'GD': 'Grenada', 'GP': 'Guadeloupe', 'GU': 'Guam', 'GT': 'Guatemala', 'GN': 'Guinea', 'GW': 'Guinea-Bissau', 'GY': 'Guyana', 'HT': 'Haiti', 'HM': 'Heard and Mc Donald Islands', 'HN': 'Honduras', 'HK': 'Hong Kong', 'HU': 'Hungary', 'IS': 'Iceland', 'IN': 'India', 'ID': 'Indonesia', 'IR': 'Iran', 'IQ': 'Iraq', 'IE': 'Ireland', 'IL': 'Israel', 'IT': 'Italy', 'JM': 'Jamaica', 'JP': 'Japan', 'JO': 'Jordan', 'KZ': 'Kazakhstan', 'KE': 'Kenya', 'KI': 'Kiribati', 'KW': 'Kuwait', 'KG': 'Kyrgyzstan', 'LA': 'Laos', 'LV': 'Latvia', 'LB': 'Lebanon', 'LS': 'Lesotho', 'LR': 'Liberia', 'LY': 'Libya', 'LI': 'Liechtenstein', 'LT': 'Lithuania', 'LU': 'Luxembourg', 'MO': 'Macau', 'MG': 'Madagascar', 'MW': 'Malawi', 'MY': 'Malaysia', 'MV': 'Maldives', 'ML': 'Mali', 'MT': 'Malta', 'MH': 'Marshall Islands', 'MQ': 'Martinique', 'MR': 'Mauritania', 'MU': 'Mauritius', 'YT': 'Mayotte', 'MX': 'Mexico', 'FM': 'Micronesia', 'MD': 'Moldova', 'MC': 'Monaco', 'MN': 'Mongolia', 'ME': 'Montenegro', 'MS': 'Montserrat', 'MA': 'Morocco', 'MZ': 'Mozambique', 'MM': 'Myanmar', 'NA': 'Namibia', 'NR': 'Nauru', 'NP': 'Nepal', 'NL': 'Netherlands', 'AN': 'Netherlands Antilles', 'NC': 'New Caledonia', 'NZ': 'New Zealand', 'NI': 'Nicaragua', 'NE': 'Niger', 'NG': 'Nigeria', 'NU': 'Niue', 'NF': 'Norfolk Island', 'KP': 'North Korea', 'MP': 'Northern Marianas', 'NO': 'Norway', 'OM': 'Oman', 'PK': 'Pakistan', 'PW': 'Palau', 'PS': 'Palestine', 'PA': 'Panama', 'PG': 'Papua New Guinea', 'PY': 'Paraguay', 'PE': 'Peru', 'PH': 'Philippines', 'PN': 'Pitcairn Islands', 'PL': 'Poland', 'PT': 'Portugal', 'PR': 'Puerto Rico', 'QA': 'Qatar', 'RE': 'Reunion', 'RO': 'Romania', 'RU': 'Russia', 'RW': 'Rwanda', 'ST': 'São Tomé and Príncipe', 'SH': 'Saint Helena', 'PM': 'St. Pierre and Miquelon', 'KN': 'Saint Kitts and Nevis', 'LC': 'Saint Lucia', 'VC': 'Saint Vincent and the Grenadines', 'WS': 'Samoa', 'SM': 'San Marino', 'SA': 'Saudi Arabia', 'SN': 'Senegal', 'RS': 'Serbia', 'SC': 'Seychelles', 'SL': 'Sierra Leone', 'SG': 'Singapore', 'SK': 'Slovakia', 'SI': 'Slovenia', 'SB': 'Solomon Islands', 'SO': 'Somalia', 'ZA': 'South Africa', 'GS': 'South Georgia and the South Sandwich Islands', 'KR': 'South Korea', 'ES': 'Spain', 'LK': 'Sri Lanka', 'SD': 'Sudan', 'SR': 'Suriname', 'SJ': 'Svalbard and Jan Mayen Islands', 'SZ': 'Swaziland', 'SE': 'Sweden', 'CH': 'Switzerland', 'SY': 'Syria', 'TW': 'Taiwan', 'TJ': 'Tajikistan', 'TZ': 'Tanzania', 'TH': 'Thailand', 'BS': 'The Bahamas', 'GM': 'The Gambia', 'TG': 'Togo', 'TK': 'Tokelau', 'TO': 'Tonga', 'TT': 'Trinidad and Tobago', 'TN': 'Tunisia', 'TR': 'Turkey', 'TM': 'Turkmenistan', 'TC': 'Turks and Caicos Islands', 'TV': 'Tuvalu', 'VI': 'US Virgin Islands', 'UG': 'Uganda', 'UA': 'Ukraine', 'AE': 'United Arab Emirates', 'GB': 'United Kingdom', 'US': 'United States', 'UM': 'United States Minor Outlying Islands', 'UY': 'Uruguay', 'UZ': 'Uzbekistan', 'VU': 'Vanuatu', 'VA': 'Vatican City', 'VE': 'Venezuela', 'VN': 'Vietnam', 'WF': 'Wallis and Futuna Islands', 'EH': 'Western Sahara', 'YE': 'Yemen', 'ZM': 'Zambia', 'ZW': 'Zimbabwe' };
Eonic/EonicWeb5
wwwroot/ewcommon/bs3/addons/formHelpers/js/lang/en_US/bootstrap-formhelpers-countries.en_US.js
JavaScript
apache-2.0
6,201
<!DOCTYPE html> <html lang="en"> <head> <!-- head --> <meta charset="utf-8"> <meta name="msapplication-tap-highlight" content="no" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Owl Carousel Documentation"> <meta name="author" content="David Deutsch"> <title> Contact | Owl Carousel | 2.2.1 </title> <!-- Stylesheets --> <link href='https://fonts.googleapis.com/css?family=Lato:300,400,700,400italic,300italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../assets/css/docs.theme.min.css"> <!-- Owl Stylesheets --> <link rel="stylesheet" href="../assets/owlcarousel/assets/owl.carousel.min.css"> <link rel="stylesheet" href="../assets/owlcarousel/assets/owl.theme.default.min.css"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <!-- Favicons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png"> <link rel="shortcut icon" href="../assets/ico/favicon.png"> <link rel="shortcut icon" href="favicon.ico"> <!-- Yeah i know js should not be in header. Its required for demos.--> <!-- javascript --> <script src="../assets/vendors/jquery.min.js"></script> <script src="../assets/owlcarousel/owl.carousel.js"></script> </head> <body> <!-- header --> <header class="header"> <div class="row"> <div class="large-12 columns"> <div class="brand left"> <h3> <a href="/OwlCarousel2/">owl.carousel.js</a> </h3> </div> <a id="toggle-nav" class="right"> <span></span> <span></span> <span></span> </a> <div class="nav-bar"> <ul class="clearfix"> <li> <a href="/OwlCarousel2/index.html">Home</a> </li> <li> <a href="/OwlCarousel2/demos/demos.html">Demos</a> </li> <li class="active"> <a href="/OwlCarousel2/docs/started-welcome.html">Docs</a> </li> <li> <a href="https://github.com/OwlCarousel2/OwlCarousel2/archive/2.2.1.zip">Download</a> <span class="download"></span> </li> </ul> </div> </div> </div> </header> <!-- title --> <section class="title"> <div class="row"> <div class="large-12 columns"> <h1>Support</h1> </div> </div> </section> <div id="docs"> <div class="row"> <div class="small-12 medium-3 large-3 columns"> <ul class="side-nav"> <li class="side-nav-head">Getting Started</li> <li> <a href="started-welcome.html">Welcome</a> </li> <li> <a href="started-installation.html">Installation</a> </li> <li> <a href="started-faq.html">FAQ</a> </li> </ul> <ul class="side-nav"> <li class="side-nav-head">API</li> <li> <a href="api-options.html">Options</a> </li> <li> <a href="api-classes.html">Classes</a> </li> <li> <a href="api-events.html">Events</a> </li> </ul> <ul class="side-nav"> <li class="side-nav-head">Development</li> <li> <a href="dev-buildin-plugins.html">Built-in Plugins</a> </li> <li> <a href="dev-plugin-api.html">Plugin API</a> </li> <li> <a href="dev-styles.html">Sass Styles</a> </li> <li> <a href="dev-external.html">External Libs</a> </li> </ul> <ul class="side-nav"> <li class="side-nav-head">Support</li> <li> <a href="support-contributing.html">Contributing</a> </li> <li> <a href="support-changelog.html">Changelog</a> </li> <li> <a href="support-contact.html">Contact</a> </li> </ul> </div> <div class="small-12 medium-9 large-9 columns"> <article class="docs-content"> <h2 id="contact">Contact</h2> <hr> <p>If you are looking for help then the best place to ask a question is <a href="https://github.com/OwlCarousel2/OwlCarousel2/issues">Github</a> . Also don&#39;t forget to add a <a href="https://jsfiddle.net/">jsfiddle</a> or a link to your demo/example website!</p> <h3 id="report-a-bug">Report a bug</h3> <p>Please use <a href="https://github.com/OwlCarousel2/OwlCarousel2/issues">Github</a> to report bugs.</p> </article> </div> </div> </div> <!-- footer --> <footer class="footer"> <div class="row"> <div class="large-12 columns"> <h5> <a href="/OwlCarousel2/docs/support-contact.html">David Deutsch</a> <a id="custom-tweet-button" href="https://twitter.com/share?url=https://github.com/OwlCarousel2/OwlCarousel2&text=Owl Carousel - This is so awesome! " target="_blank"></a> </h5> </div> </div> </footer> <!-- vendors --> <script src="../assets/vendors/highlight.js"></script> <script src="../assets/js/app.js"></script> </body> </html>
chester0516/htc-prototype-bak
wip/pdp-2017/bower_components/owl.carousel/docs/docs/support-contact.html
HTML
mit
5,521
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0"> <title>ColReorder example - State saving</title> <link rel="stylesheet" type="text/css" href="../../../../media/css/jquery.dataTables.css"> <link rel="stylesheet" type="text/css" href="../../css/colReorder.dataTables.css"> <link rel="stylesheet" type="text/css" href="../../../../examples/resources/syntax/shCore.css"> <link rel="stylesheet" type="text/css" href="../../../../examples/resources/demo.css"> <style type="text/css" class="init"> </style> <script type="text/javascript" language="javascript" src="//code.jquery.com/jquery-1.12.0.min.js"> </script> <script type="text/javascript" language="javascript" src="../../../../media/js/jquery.dataTables.js"> </script> <script type="text/javascript" language="javascript" src="../../js/dataTables.colReorder.js"> </script> <script type="text/javascript" language="javascript" src="../../../../examples/resources/syntax/shCore.js"> </script> <script type="text/javascript" language="javascript" src="../../../../examples/resources/demo.js"> </script> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').dataTable( { colReorder: true, stateSave: true } ); } ); </script> </head> <body class="dt-example"> <div class="container"> <section> <h1>ColReorder example <span>State saving</span></h1> <div class="info"> <p>A useful interaction pattern to use in DataTables is state saving, so when the end user reloads or revisits a page its previous state is retained. ColReorder works seamlessly with state saving in DataTables (<a href="//datatables.net/reference/option/stateSave"><code class="option" title= "DataTables initialisation option">stateSave</code></a>), remembering and restoring the column positions, as well as everything else such as sorting and filtering.</p> </div> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tfoot> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </tfoot> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior Javascript Developer</td> <td>Edinburgh</td> <td>22</td> <td>2012/03/29</td> <td>$433,060</td> </tr> <tr> <td>Airi Satou</td> <td>Accountant</td> <td>Tokyo</td> <td>33</td> <td>2008/11/28</td> <td>$162,700</td> </tr> <tr> <td>Brielle Williamson</td> <td>Integration Specialist</td> <td>New York</td> <td>61</td> <td>2012/12/02</td> <td>$372,000</td> </tr> <tr> <td>Herrod Chandler</td> <td>Sales Assistant</td> <td>San Francisco</td> <td>59</td> <td>2012/08/06</td> <td>$137,500</td> </tr> <tr> <td>Rhona Davidson</td> <td>Integration Specialist</td> <td>Tokyo</td> <td>55</td> <td>2010/10/14</td> <td>$327,900</td> </tr> <tr> <td>Colleen Hurst</td> <td>Javascript Developer</td> <td>San Francisco</td> <td>39</td> <td>2009/09/15</td> <td>$205,500</td> </tr> <tr> <td>Sonya Frost</td> <td>Software Engineer</td> <td>Edinburgh</td> <td>23</td> <td>2008/12/13</td> <td>$103,600</td> </tr> <tr> <td>Jena Gaines</td> <td>Office Manager</td> <td>London</td> <td>30</td> <td>2008/12/19</td> <td>$90,560</td> </tr> <tr> <td>Quinn Flynn</td> <td>Support Lead</td> <td>Edinburgh</td> <td>22</td> <td>2013/03/03</td> <td>$342,000</td> </tr> <tr> <td>Charde Marshall</td> <td>Regional Director</td> <td>San Francisco</td> <td>36</td> <td>2008/10/16</td> <td>$470,600</td> </tr> <tr> <td>Haley Kennedy</td> <td>Senior Marketing Designer</td> <td>London</td> <td>43</td> <td>2012/12/18</td> <td>$313,500</td> </tr> <tr> <td>Tatyana Fitzpatrick</td> <td>Regional Director</td> <td>London</td> <td>19</td> <td>2010/03/17</td> <td>$385,750</td> </tr> <tr> <td>Michael Silva</td> <td>Marketing Designer</td> <td>London</td> <td>66</td> <td>2012/11/27</td> <td>$198,500</td> </tr> <tr> <td>Paul Byrd</td> <td>Chief Financial Officer (CFO)</td> <td>New York</td> <td>64</td> <td>2010/06/09</td> <td>$725,000</td> </tr> <tr> <td>Gloria Little</td> <td>Systems Administrator</td> <td>New York</td> <td>59</td> <td>2009/04/10</td> <td>$237,500</td> </tr> <tr> <td>Bradley Greer</td> <td>Software Engineer</td> <td>London</td> <td>41</td> <td>2012/10/13</td> <td>$132,000</td> </tr> <tr> <td>Dai Rios</td> <td>Personnel Lead</td> <td>Edinburgh</td> <td>35</td> <td>2012/09/26</td> <td>$217,500</td> </tr> <tr> <td>Jenette Caldwell</td> <td>Development Lead</td> <td>New York</td> <td>30</td> <td>2011/09/03</td> <td>$345,000</td> </tr> <tr> <td>Yuri Berry</td> <td>Chief Marketing Officer (CMO)</td> <td>New York</td> <td>40</td> <td>2009/06/25</td> <td>$675,000</td> </tr> <tr> <td>Caesar Vance</td> <td>Pre-Sales Support</td> <td>New York</td> <td>21</td> <td>2011/12/12</td> <td>$106,450</td> </tr> <tr> <td>Doris Wilder</td> <td>Sales Assistant</td> <td>Sidney</td> <td>23</td> <td>2010/09/20</td> <td>$85,600</td> </tr> <tr> <td>Angelica Ramos</td> <td>Chief Executive Officer (CEO)</td> <td>London</td> <td>47</td> <td>2009/10/09</td> <td>$1,200,000</td> </tr> <tr> <td>Gavin Joyce</td> <td>Developer</td> <td>Edinburgh</td> <td>42</td> <td>2010/12/22</td> <td>$92,575</td> </tr> <tr> <td>Jennifer Chang</td> <td>Regional Director</td> <td>Singapore</td> <td>28</td> <td>2010/11/14</td> <td>$357,650</td> </tr> <tr> <td>Brenden Wagner</td> <td>Software Engineer</td> <td>San Francisco</td> <td>28</td> <td>2011/06/07</td> <td>$206,850</td> </tr> <tr> <td>Fiona Green</td> <td>Chief Operating Officer (COO)</td> <td>San Francisco</td> <td>48</td> <td>2010/03/11</td> <td>$850,000</td> </tr> <tr> <td>Shou Itou</td> <td>Regional Marketing</td> <td>Tokyo</td> <td>20</td> <td>2011/08/14</td> <td>$163,000</td> </tr> <tr> <td>Michelle House</td> <td>Integration Specialist</td> <td>Sidney</td> <td>37</td> <td>2011/06/02</td> <td>$95,400</td> </tr> <tr> <td>Suki Burks</td> <td>Developer</td> <td>London</td> <td>53</td> <td>2009/10/22</td> <td>$114,500</td> </tr> <tr> <td>Prescott Bartlett</td> <td>Technical Author</td> <td>London</td> <td>27</td> <td>2011/05/07</td> <td>$145,000</td> </tr> <tr> <td>Gavin Cortez</td> <td>Team Leader</td> <td>San Francisco</td> <td>22</td> <td>2008/10/26</td> <td>$235,500</td> </tr> <tr> <td>Martena Mccray</td> <td>Post-Sales support</td> <td>Edinburgh</td> <td>46</td> <td>2011/03/09</td> <td>$324,050</td> </tr> <tr> <td>Unity Butler</td> <td>Marketing Designer</td> <td>San Francisco</td> <td>47</td> <td>2009/12/09</td> <td>$85,675</td> </tr> <tr> <td>Howard Hatfield</td> <td>Office Manager</td> <td>San Francisco</td> <td>51</td> <td>2008/12/16</td> <td>$164,500</td> </tr> <tr> <td>Hope Fuentes</td> <td>Secretary</td> <td>San Francisco</td> <td>41</td> <td>2010/02/12</td> <td>$109,850</td> </tr> <tr> <td>Vivian Harrell</td> <td>Financial Controller</td> <td>San Francisco</td> <td>62</td> <td>2009/02/14</td> <td>$452,500</td> </tr> <tr> <td>Timothy Mooney</td> <td>Office Manager</td> <td>London</td> <td>37</td> <td>2008/12/11</td> <td>$136,200</td> </tr> <tr> <td>Jackson Bradshaw</td> <td>Director</td> <td>New York</td> <td>65</td> <td>2008/09/26</td> <td>$645,750</td> </tr> <tr> <td>Olivia Liang</td> <td>Support Engineer</td> <td>Singapore</td> <td>64</td> <td>2011/02/03</td> <td>$234,500</td> </tr> <tr> <td>Bruno Nash</td> <td>Software Engineer</td> <td>London</td> <td>38</td> <td>2011/05/03</td> <td>$163,500</td> </tr> <tr> <td>Sakura Yamamoto</td> <td>Support Engineer</td> <td>Tokyo</td> <td>37</td> <td>2009/08/19</td> <td>$139,575</td> </tr> <tr> <td>Thor Walton</td> <td>Developer</td> <td>New York</td> <td>61</td> <td>2013/08/11</td> <td>$98,540</td> </tr> <tr> <td>Finn Camacho</td> <td>Support Engineer</td> <td>San Francisco</td> <td>47</td> <td>2009/07/07</td> <td>$87,500</td> </tr> <tr> <td>Serge Baldwin</td> <td>Data Coordinator</td> <td>Singapore</td> <td>64</td> <td>2012/04/09</td> <td>$138,575</td> </tr> <tr> <td>Zenaida Frank</td> <td>Software Engineer</td> <td>New York</td> <td>63</td> <td>2010/01/04</td> <td>$125,250</td> </tr> <tr> <td>Zorita Serrano</td> <td>Software Engineer</td> <td>San Francisco</td> <td>56</td> <td>2012/06/01</td> <td>$115,000</td> </tr> <tr> <td>Jennifer Acosta</td> <td>Junior Javascript Developer</td> <td>Edinburgh</td> <td>43</td> <td>2013/02/01</td> <td>$75,650</td> </tr> <tr> <td>Cara Stevens</td> <td>Sales Assistant</td> <td>New York</td> <td>46</td> <td>2011/12/06</td> <td>$145,600</td> </tr> <tr> <td>Hermione Butler</td> <td>Regional Director</td> <td>London</td> <td>47</td> <td>2011/03/21</td> <td>$356,250</td> </tr> <tr> <td>Lael Greer</td> <td>Systems Administrator</td> <td>London</td> <td>21</td> <td>2009/02/27</td> <td>$103,500</td> </tr> <tr> <td>Jonas Alexander</td> <td>Developer</td> <td>San Francisco</td> <td>30</td> <td>2010/07/14</td> <td>$86,500</td> </tr> <tr> <td>Shad Decker</td> <td>Regional Director</td> <td>Edinburgh</td> <td>51</td> <td>2008/11/13</td> <td>$183,000</td> </tr> <tr> <td>Michael Bruce</td> <td>Javascript Developer</td> <td>Singapore</td> <td>29</td> <td>2011/06/27</td> <td>$183,000</td> </tr> <tr> <td>Donna Snider</td> <td>Customer Support</td> <td>New York</td> <td>27</td> <td>2011/01/25</td> <td>$112,000</td> </tr> </tbody> </table> <ul class="tabs"> <li class="active">Javascript</li> <li>HTML</li> <li>CSS</li> <li>Ajax</li> <li>Server-side script</li> </ul> <div class="tabs"> <div class="js"> <p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() { $('#example').dataTable( { colReorder: true, stateSave: true } ); } );</code> <p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p> <ul> <li> <a href="//code.jquery.com/jquery-1.12.0.min.js">//code.jquery.com/jquery-1.12.0.min.js</a> </li> <li> <a href="../../../../media/js/jquery.dataTables.js">../../../../media/js/jquery.dataTables.js</a> </li> <li> <a href="../../js/dataTables.colReorder.js">../../js/dataTables.colReorder.js</a> </li> </ul> </div> <div class="table"> <p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p> </div> <div class="css"> <div> <p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below:</p><code class="multiline language-css"></code> </div> <p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p> <ul> <li> <a href="../../../../media/css/jquery.dataTables.css">../../../../media/css/jquery.dataTables.css</a> </li> <li> <a href="../../css/colReorder.dataTables.css">../../css/colReorder.dataTables.css</a> </li> </ul> </div> <div class="ajax"> <p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is loaded.</p> </div> <div class="php"> <p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables documentation</a>.</p> </div> </div> </section> </div> <section> <div class="footer"> <div class="gradient"></div> <div class="liner"> <h2>Other examples</h2> <div class="toc"> <div class="toc-group"> <h3><a href="../initialisation/index.html">Initialisation and options</a></h3> <ul class="toc"> <li> <a href="../initialisation/simple.html">Basic initialisation</a> </li> <li> <a href="../initialisation/scrolling.html">Scrolling table</a> </li> <li> <a href="../initialisation/predefined.html">Predefined column ordering</a> </li> <li> <a href="../initialisation/realtime.html">Realtime updating</a> </li> <li> <a href="../initialisation/col_filter.html">Individual column filtering</a> </li> <li> <a href="../initialisation/new_init.html">Initialisation using `new`</a> </li> <li> <a href="../initialisation/reset.html">Reset ordering API</a> </li> </ul> </div> <div class="toc-group"> <h3><a href="./index.html">Integration with other DataTables extensions</a></h3> <ul class="toc active"> <li> <a href="./colvis.html">Column visibility integration</a> </li> <li> <a href="./fixedcolumns.html">FixedColumns integration</a> </li> <li> <a href="./fixedheader.html">FixedHeader integration</a> </li> <li> <a href="./responsive.html">Responsive integration</a> </li> <li> <a href="./server_side.html">Server-side processing</a> </li> <li class="active"> <a href="./state_save.html">State saving</a> </li> </ul> </div> <div class="toc-group"> <h3><a href="../styling/index.html">Styling</a></h3> <ul class="toc"> <li> <a href="../styling/alt_insert.html">Alternative insert styling</a> </li> <li> <a href="../styling/bootstrap.html">Bootstrap styling</a> </li> <li> <a href="../styling/foundation.html">Foundation styling</a> </li> <li> <a href="../styling/jqueryui.html">jQuery UI styling</a> </li> </ul> </div> </div> <div class="epilogue"> <p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br> Additionally, there are a wide range of <a href="http://www.datatables.net/extensions">extensions</a> and <a href= "http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.</p> <p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2016<br> DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p> </div> </div> </div> </section> </body> </html>
antho-firuze/_g.ene.sys_remake_
templates/frontend_theme/adminlte/plugins/datatables/extensions/ColReorder/examples/integration/state_save.html
HTML
mit
17,881
/*before*/"use strict"; /*after*/foo();
zjmiller/babel
packages/babel-plugin-transform-strict-mode/test/fixtures/auxiliary-comment/use-strict-add/expected.js
JavaScript
mit
41
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.xsom.impl.parser; import com.sun.xml.internal.xsom.XSSchemaSet; import com.sun.xml.internal.xsom.impl.ElementDecl; import com.sun.xml.internal.xsom.impl.SchemaImpl; import com.sun.xml.internal.xsom.impl.SchemaSetImpl; import com.sun.xml.internal.xsom.parser.AnnotationParserFactory; import com.sun.xml.internal.xsom.parser.XMLParser; import com.sun.xml.internal.xsom.parser.XSOMParser; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; /** * Provides context information to be used by {@link NGCCRuntimeEx}s. * * <p> * This class does the actual processing for {@link XSOMParser}, * but to hide the details from the public API, this class in * a different package. * * @author Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public class ParserContext { /** SchemaSet to which a newly parsed schema is put in. */ public final SchemaSetImpl schemaSet = new SchemaSetImpl(); private final XSOMParser owner; final XMLParser parser; private final Vector<Patch> patchers = new Vector<Patch>(); private final Vector<Patch> errorCheckers = new Vector<Patch>(); /** * Documents that are parsed already. Used to avoid cyclic inclusion/double * inclusion of schemas. Set of {@link SchemaDocumentImpl}s. * * The actual data structure is map from {@link SchemaDocumentImpl} to itself, * so that we can access the {@link SchemaDocumentImpl} itself. */ public final Map<SchemaDocumentImpl, SchemaDocumentImpl> parsedDocuments = new HashMap<SchemaDocumentImpl, SchemaDocumentImpl>(); public ParserContext( XSOMParser owner, XMLParser parser ) { this.owner = owner; this.parser = parser; try { parse(new InputSource(ParserContext.class.getResource("datatypes.xsd").toExternalForm())); SchemaImpl xs = (SchemaImpl) schemaSet.getSchema("http://www.w3.org/2001/XMLSchema"); xs.addSimpleType(schemaSet.anySimpleType,true); xs.addComplexType(schemaSet.anyType,true); } catch( SAXException e ) { // this must be a bug of XSOM if(e.getException()!=null) e.getException().printStackTrace(); else e.printStackTrace(); throw new InternalError(); } } public EntityResolver getEntityResolver() { return owner.getEntityResolver(); } public AnnotationParserFactory getAnnotationParserFactory() { return owner.getAnnotationParserFactory(); } /** * Parses a new XML Schema document. */ public void parse( InputSource source ) throws SAXException { newNGCCRuntime().parseEntity(source,false,null,null); } public XSSchemaSet getResult() throws SAXException { // run all the patchers for (Patch patcher : patchers) patcher.run(); patchers.clear(); // build the element substitutability map Iterator itr = schemaSet.iterateElementDecls(); while(itr.hasNext()) ((ElementDecl)itr.next()).updateSubstitutabilityMap(); // run all the error checkers for (Patch patcher : errorCheckers) patcher.run(); errorCheckers.clear(); if(hadError) return null; else return schemaSet; } public NGCCRuntimeEx newNGCCRuntime() { return new NGCCRuntimeEx(this); } /** Once an error is detected, this flag is set to true. */ private boolean hadError = false; /** Turns on the error flag. */ void setErrorFlag() { hadError=true; } /** * PatchManager implementation, which is accessible only from * NGCCRuntimEx. */ final PatcherManager patcherManager = new PatcherManager() { public void addPatcher( Patch patch ) { patchers.add(patch); } public void addErrorChecker( Patch patch ) { errorCheckers.add(patch); } public void reportError( String msg, Locator src ) throws SAXException { // set a flag to true to avoid returning a corrupted object. setErrorFlag(); SAXParseException e = new SAXParseException(msg,src); if(errorHandler==null) throw e; else errorHandler.error(e); } }; /** * ErrorHandler proxy to turn on the hadError flag when an error * is found. */ final ErrorHandler errorHandler = new ErrorHandler() { private ErrorHandler getErrorHandler() { if( owner.getErrorHandler()==null ) return noopHandler; else return owner.getErrorHandler(); } public void warning(SAXParseException e) throws SAXException { getErrorHandler().warning(e); } public void error(SAXParseException e) throws SAXException { setErrorFlag(); getErrorHandler().error(e); } public void fatalError(SAXParseException e) throws SAXException { setErrorFlag(); getErrorHandler().fatalError(e); } }; /** * {@link ErrorHandler} that does nothing. */ final ErrorHandler noopHandler = new ErrorHandler() { public void warning(SAXParseException e) { } public void error(SAXParseException e) { } public void fatalError(SAXParseException e) { setErrorFlag(); } }; }
rokn/Count_Words_2015
testing/openjdk2/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/impl/parser/ParserContext.java
Java
mit
6,989
// 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 System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Globalization.Tests { public class NumberFormatInfoMiscTests { public static IEnumerable<object[]> DigitSubstitution_TestData() { yield return new object[] { "ar" , DigitShapes.Context }; yield return new object[] { "ar-001" , DigitShapes.Context }; yield return new object[] { "ar-AE" , DigitShapes.Context }; yield return new object[] { "ar-BH" , DigitShapes.Context }; yield return new object[] { "ar-DJ" , DigitShapes.Context }; yield return new object[] { "ar-EG" , DigitShapes.Context }; yield return new object[] { "ar-ER" , DigitShapes.Context }; yield return new object[] { "ar-IL" , DigitShapes.Context }; yield return new object[] { "ar-IQ" , DigitShapes.Context }; yield return new object[] { "ar-JO" , DigitShapes.Context }; yield return new object[] { "ar-KM" , DigitShapes.Context }; yield return new object[] { "ar-KW" , DigitShapes.Context }; yield return new object[] { "ar-LB" , DigitShapes.Context }; yield return new object[] { "ar-MR" , DigitShapes.Context }; yield return new object[] { "ar-OM" , DigitShapes.Context }; yield return new object[] { "ar-PS" , DigitShapes.Context }; yield return new object[] { "ar-QA" , DigitShapes.Context }; yield return new object[] { "ar-SA" , DigitShapes.Context }; yield return new object[] { "ar-SD" , DigitShapes.Context }; yield return new object[] { "ar-SO" , DigitShapes.Context }; yield return new object[] { "ar-SS" , DigitShapes.Context }; yield return new object[] { "ar-SY" , DigitShapes.Context }; yield return new object[] { "ar-TD" , DigitShapes.Context }; yield return new object[] { "ar-YE" , DigitShapes.Context }; yield return new object[] { "dz" , DigitShapes.NativeNational }; yield return new object[] { "dz-BT" , DigitShapes.NativeNational }; yield return new object[] { "fa" , DigitShapes.Context }; yield return new object[] { "fa-IR" , DigitShapes.Context }; yield return new object[] { "km" , DigitShapes.NativeNational }; yield return new object[] { "km-KH" , DigitShapes.NativeNational }; yield return new object[] { "ks" , DigitShapes.NativeNational }; yield return new object[] { "ks-Arab" , DigitShapes.NativeNational }; yield return new object[] { "ks-Arab-IN", DigitShapes.NativeNational }; yield return new object[] { "ku" , DigitShapes.Context }; yield return new object[] { "ku-Arab" , DigitShapes.Context }; yield return new object[] { "ku-Arab-IQ", DigitShapes.Context }; yield return new object[] { "my" , DigitShapes.NativeNational }; yield return new object[] { "my-MM" , DigitShapes.NativeNational }; yield return new object[] { "ne-IN" , DigitShapes.NativeNational }; yield return new object[] { "nqo" , DigitShapes.NativeNational }; yield return new object[] { "nqo-GN" , DigitShapes.NativeNational }; yield return new object[] { "pa-Arab" , DigitShapes.NativeNational }; yield return new object[] { "pa-Arab-PK", DigitShapes.NativeNational }; yield return new object[] { "prs" , DigitShapes.NativeNational }; yield return new object[] { "prs-AF" , DigitShapes.NativeNational }; yield return new object[] { "ps" , DigitShapes.NativeNational }; yield return new object[] { "ps-AF" , DigitShapes.NativeNational }; yield return new object[] { "sd" , DigitShapes.NativeNational }; yield return new object[] { "sd-Arab" , DigitShapes.NativeNational }; yield return new object[] { "sd-Arab-PK", DigitShapes.NativeNational }; yield return new object[] { "ur-IN" , DigitShapes.NativeNational }; yield return new object[] { "uz-Arab" , DigitShapes.NativeNational }; yield return new object[] { "uz-Arab-AF", DigitShapes.NativeNational }; } [Fact] public void DigitSubstitutionTest() { // DigitSubstitution is not used in number formatting. Assert.Equal(DigitShapes.None, CultureInfo.InvariantCulture.NumberFormat.DigitSubstitution); } [Fact] public void NativeDigitsTest() { string [] nativeDigits = CultureInfo.InvariantCulture.NumberFormat.NativeDigits; Assert.Equal(new string [] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, nativeDigits); NumberFormatInfo nfi = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); string [] newDigits = new string [] { "\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669" }; nfi.NativeDigits = newDigits; Assert.Equal(newDigits, nfi.NativeDigits); } [Theory] [MemberData(nameof(DigitSubstitution_TestData))] public void DigitSubstitutionListTest(string cultureName, DigitShapes shape) { try { CultureInfo ci = CultureInfo.GetCultureInfo(cultureName); Assert.Equal(ci.NumberFormat.DigitSubstitution, shape); } catch (CultureNotFoundException) { // ignore the cultures that we cannot create as it is not supported on the platforms } } } }
shimingsg/corefx
src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoTests.cs
C#
mit
6,144
/* govuk_frontend_toolkit includes */ @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } @font-face { font-family: GDS-Logo; src: local("HelveticaNeue"), local("Helvetica Neue"), local("Arial"), local("Helvetica"); } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } #global-header .header-wrapper, #global-header .header-wrapper .header-global, #global-header .header-wrapper .header-global .header-logo, #global-header .header-proposition #proposition-link, #global-header .header-proposition #proposition-links, #global-header-bar, #global-cookie-message .outer-block, #footer .footer-wrapper, #footer .footer-meta { zoom: 1; } #global-header .header-wrapper:after, #global-header .header-wrapper .header-global:after, #global-header .header-wrapper .header-global .header-logo:after, #global-header .header-proposition #proposition-link:after, #global-header .header-proposition #proposition-links:after, #global-header-bar:after, #global-cookie-message .outer-block:after, #footer .footer-wrapper:after, #footer .footer-meta:after { content: ""; display: block; clear: both; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } #global-header .header-wrapper, #global-header .header-wrapper .header-global, #global-header .header-wrapper .header-global .header-logo, #global-header .header-proposition #proposition-link, #global-header .header-proposition #proposition-links, #global-header-bar, #global-cookie-message .outer-block, #footer .footer-wrapper, #footer .footer-meta { zoom: 1; } #global-header .header-wrapper:after, #global-header .header-wrapper .header-global:after, #global-header .header-wrapper .header-global .header-logo:after, #global-header .header-proposition #proposition-link:after, #global-header .header-proposition #proposition-links:after, #global-header-bar:after, #global-cookie-message .outer-block:after, #footer .footer-wrapper:after, #footer .footer-meta:after { content: ""; display: block; clear: both; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } /* local styleguide includes */ /* Old depricated greys, new things should use the toolkit greys */ html, body, button, input, table, td, th { font-family: "nta", Arial, sans-serif; } html, body, div, h1, h2, h3, h4, h5, h6, article, aside, footer, header, hgroup, nav, section { margin: 0; padding: 0; vertical-align: baseline; } main { display: block; } .group:before, .group:after { content: "\0020"; display: block; height: 0; overflow: hidden; } .group:after { clear: both; } .group { zoom: 1; } .content-fixed { top: 0; position: fixed; } .shim { display: block; } /* * 1. Prevents iOS text size adjust after orientation change, without disabling * user zoom. */ html { -webkit-text-size-adjust: 100%; /* 1 */ -ms-text-size-adjust: 100%; /* 1 */ background-color: #dee0e2; } /* Force the scrollbar to always display in IE10/11 */ html { -ms-overflow-style: scrollbar; } body { background: white; color: #0b0c0c; line-height: 1.5; font-weight: 400; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } ol, ul, nav ol, nav ul { list-style: inherit; } fieldset { border: none; padding: 0; } a:link { color: #005ea5; } a:visited { color: #4c2c92; } a:hover { color: #2e8aca; } a:active { color: #2e8aca; } a[rel="external"]:after { background-image: url(external-links/external-link.png?0.12.0); background-repeat: no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 20 / 10), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) { a[rel="external"]:after { background-image: url(external-links/external-link-24x24.png?0.12.0); background-size: 12px 400px; } } a[rel="external"]:after { content: "\A0\A0\A0\A0"; background-position: right 6px; } a[rel="external"]:hover:after { background-position: right -382px; } .external-link:after { content: "\A0\A0\A0\A0\A0\A0\A0\A0"; background-position: right 0px; } .external-link:hover:after { background-position: right 0px; } .external-link:after { background-image: url(external-links/external-link-black-12x12.png?0.12.0); background-repeat: no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 20 / 10), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) { .external-link:after { background-image: url(external-links/external-link-black-24x24.png?0.12.0); background-size: 12px 400px; } } /* * 1. Corrects text resizing oddly in IE6/7 when body font-size is set using em units * http://clagnut.com/blog/348/#c790 * note - font-size reduced to 62.5% to allow simple rem/px font-sizing and fallback * http://snook.ca/archives/html_and_css/font-size-with-rem * 2. Keeps page centred in all browsers regardless of content height * 3. Removes Android and iOS tap highlight color to prevent entire container being highlighted * www.yuiblog.com/blog/2010/10/01/quick-tip-customizing-the-mobile-safari-tap-highlight-color/ */ html { font-size: 62.5%; /* 1 */ overflow-y: scroll; /* 2 */ -webkit-tap-highlight-color: rgba(0, 0, 0, 0); /* 3 */ } /* * 1. Font-size increased to compensate for change to html element font-size in * order to support beta typography which was set in ems * (62.5% * 160% = 100%) * 2. Addresses margins handled incorrectly in IE6/7 */ body { font-size: 160%; /* 1 */ margin: 0; /* 2 */ } b, strong { font-weight: 600; } img { border: 0; } button { overflow: visible; } abbr[title] { cursor: help; } /* * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome * (include `-moz` to future-proof). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: searchfield-cancel-button; margin-right: 2px; } input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /* For image replacement */ .ir { display: block; text-indent: -999em; overflow: hidden; background-repeat: no-repeat; text-align: left; direction: ltr; } .ir br { display: none; } /* Hide for both screenreaders and browsers */ .hidden { display: none; visibility: hidden; } /* Hide only visually, but have it available for screenreaders */ .visuallyhidden { position: absolute; left: -9999em; /* * Extends the .visuallyhidden class to allow the element to be * focusable when navigated to via the keyboard */ } .visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } /* Hide visually and from screenreaders, but maintain layout */ .invisible { visibility: hidden; } /* Give a strong clear visual idea as to what is currently in focus */ a { -webkit-tap-highlight-color: rgba(0, 0, 0, 0.3); } a:focus { background-color: #ffbf47; outline: 3px solid #ffbf47; } /* Make skiplinks visible when they are tabbed to */ .skiplink { position: absolute; left: -9999em; } .skiplink:focus { position: static; } #skiplink-container { text-align: center; background: #0b0c0c; } #skiplink-container div { text-align: left; margin: 0 auto; max-width: 1020px; } #skiplink-container .skiplink { display: -moz-inline-stack; display: inline-block; zoom: 1; display: inline; margin: 0.75em 0 0 30px; } input:focus, textarea:focus, select:focus, button:focus, #global-header input:focus { outline: 3px solid #ffbf47; } #global-header h1 a:focus { background-color: transparent; outline: none; } #global-header a:focus { color: #0b0c0c; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } #global-header .header-wrapper, #global-header .header-wrapper .header-global, #global-header .header-wrapper .header-global .header-logo, #global-header .header-proposition #proposition-link, #global-header .header-proposition #proposition-links, #global-header-bar, #global-cookie-message .outer-block, #footer .footer-wrapper, #footer .footer-meta { zoom: 1; } #global-header .header-wrapper:after, #global-header .header-wrapper .header-global:after, #global-header .header-wrapper .header-global .header-logo:after, #global-header .header-proposition #proposition-link:after, #global-header .header-proposition #proposition-links:after, #global-header-bar:after, #global-cookie-message .outer-block:after, #footer .footer-wrapper:after, #footer .footer-meta:after { content: ""; display: block; clear: both; } @-ms-viewport { width: device-width; } @-o-viewport { width: device-width; } #global-header { background-color: #0b0c0c; width: 100%; } #global-header .header-wrapper { background-color: #0b0c0c; max-width: 990px; margin: 0 auto; padding-top: 8px; padding-bottom: 8px; padding-left: 15px; padding-right: 15px; width: 990px; } #global-header .header-wrapper .header-global .header-logo { float: left; width: 33.33%; } @media screen and (max-width: 379px) { #global-header .header-wrapper .header-global .header-logo { width: auto; float: none; } } #global-header .header-wrapper .header-global .header-logo .content { margin: 0 15px; } #global-header .header-wrapper .header-global .header-logo { margin: 5px 0 2px; } #global-header.with-proposition .header-wrapper .header-global { float: left; width: 33.33%; } #global-header.with-proposition .header-wrapper .header-global .header-logo, #global-header.with-proposition .header-wrapper .header-global .site-search { width: 100%; } #global-header.with-proposition .header-wrapper .header-proposition { width: 66.66%; float: left; } #global-header.with-proposition .header-wrapper .header-proposition .content { margin: 0 15px; } #global-header #logo { float: left; position: relative; top: 1px; height: 30px; overflow: visible; vertical-align: baseline; color: white; font-weight: bold; font-size: 30px; line-height: 1em; text-decoration: none; text-rendering: optimizeLegibility; margin-bottom: -1px; padding-bottom: 1px; } #global-header #logo img { position: relative; top: -2px; width: 35px; height: 31px; padding-right: 6px; float: left; display: inline; line-height: inherit; border: none; } #global-header #logo:hover, #global-header #logo:focus { text-decoration: none; border-bottom: 1px solid; padding-bottom: 0; } #global-header #logo:active { color: #2b8cc4; } #global-header .header-proposition { padding-top: 10px; padding-top: 0; } #global-header .header-proposition #proposition-name { font-family: "nta", Arial, sans-serif; font-size: 24px; line-height: 1.25; font-weight: 400; text-transform: none; font-weight: bold; color: white; text-decoration: none; } @media (max-width: 640px) { #global-header .header-proposition #proposition-name { font-size: 18px; line-height: 1.2; } } #global-header .header-proposition a#proposition-name:hover { text-decoration: underline; } #global-header .header-proposition a.menu { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; color: white; display: block; float: right; text-decoration: none; padding-top: 6px; display: none; } @media (max-width: 640px) { #global-header .header-proposition a.menu { font-size: 14px; line-height: 1.14286; } } #global-header .header-proposition a.menu:hover { text-decoration: underline; } #global-header .header-proposition a.menu:after { display: inline-block; font-size: 8px; height: 8px; padding-left: 5px; vertical-align: middle; content: " \25BC"; } #global-header .header-proposition a.menu.js-hidden:after { content: " \25B2"; } #global-header .header-proposition #proposition-menu { margin-top: 5px; } #global-header .header-proposition #proposition-menu.no-proposition-name { margin-top: 37px; } #global-header .header-proposition #proposition-link, #global-header .header-proposition #proposition-links { clear: both; margin: 2px 0 0 0; padding: 0; } .js-enabled #global-header .header-proposition #proposition-link, .js-enabled #global-header .header-proposition #proposition-links { display: none; display: block; } .js-enabled #global-header .header-proposition #proposition-link.js-visible, .js-enabled #global-header .header-proposition #proposition-links.js-visible { display: block; } #global-header .header-proposition #proposition-link li, #global-header .header-proposition #proposition-links li { float: left; width: 50%; padding: 3px 0; border-bottom: 1px solid #2e3133; display: block; width: auto; padding: 0 15px 0 0; border-bottom: 0; } #global-header .header-proposition #proposition-link li.clear-child, #global-header .header-proposition #proposition-links li.clear-child { clear: left; } #global-header .header-proposition #proposition-link a, #global-header .header-proposition #proposition-links a { color: white; text-decoration: none; font-family: "nta", Arial, sans-serif; font-size: 14px; line-height: 1.42857; font-weight: 700; text-transform: none; font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 700; text-transform: none; line-height: 23px; } @media (max-width: 640px) { #global-header .header-proposition #proposition-link a, #global-header .header-proposition #proposition-links a { font-size: 12px; line-height: 1.25; } } @media (max-width: 640px) { #global-header .header-proposition #proposition-link a, #global-header .header-proposition #proposition-links a { font-size: 14px; line-height: 1.14286; } } #global-header .header-proposition #proposition-link a:hover, #global-header .header-proposition #proposition-links a:hover { text-decoration: underline; } #global-header .header-proposition #proposition-link a.active, #global-header .header-proposition #proposition-links a.active { color: #1d8feb; } #global-header .header-proposition #proposition-link a:focus, #global-header .header-proposition #proposition-links a:focus { color: #0b0c0c; } #global-header .header-proposition #proposition-link { float: right; line-height: 22px; float: none; } .js-enabled #global-header .header-proposition #proposition-link { display: block; } /* Global header bar */ #global-header-bar { margin: 0 auto; width: auto; max-width: 1020px; width: 1020px; } #global-header-bar .inner-block { padding-left: 15px; padding-right: 15px; padding-left: 30px; padding-right: 30px; } #global-header-bar .header-bar { height: 10px; background-color: #005ea5; font-size: 0; } /* Global cookie message */ .js-enabled #global-cookie-message { display: none; /* shown with JS, always on for non-JS */ } #global-cookie-message { background-color: #d5e8f3; padding-top: 10px; padding-bottom: 10px; } #global-cookie-message .outer-block { margin: 0 auto; width: auto; max-width: 1020px; width: 1020px; } #global-cookie-message .inner-block { padding-left: 15px; padding-right: 15px; padding-left: 30px; padding-right: 30px; } #global-cookie-message p { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; margin: 0; } @media (max-width: 640px) { #global-cookie-message p { font-size: 14px; line-height: 1.14286; } } /* Global footer */ #footer { background-color: #dee0e2; border-top: 1px solid #a1acb2; } #footer .footer-wrapper { margin: 0 auto; width: auto; max-width: 1020px; width: 1020px; padding-top: 20px; padding-top: 60px; background-color: #dee0e2; margin: 0 auto; } #footer a { color: #454a4c; } #footer a:hover { color: #171819; } #footer h2 { font-family: "nta", Arial, sans-serif; font-size: 24px; line-height: 1.25; font-weight: 400; text-transform: none; font-weight: bold; color: #171819; margin: 0; } @media (max-width: 640px) { #footer h2 { font-size: 18px; line-height: 1.2; } } #footer h2 a { color: inherit; } #footer .footer-meta { padding-left: 15px; padding-right: 15px; padding-left: 30px; padding-right: 30px; padding-bottom: 60px; clear: both; font-size: 0; color: #454a4c; } #footer .footer-meta .footer-meta-inner { display: inline-block; vertical-align: bottom; width: 100%; width: 75%; float: left; display: block; } #footer .footer-meta .footer-meta-inner ul { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.5; font-weight: 400; text-transform: none; display: inline-block; list-style: none; margin: 0 0 1.5em 0; padding: 0; margin: 0 0 1em 0; } @media (max-width: 640px) { #footer .footer-meta .footer-meta-inner ul { font-size: 14px; line-height: 1.5; } } #footer .footer-meta .footer-meta-inner ul li { display: inline-block; margin: 0 15px 0 0; display: inline; margin-right: 0; padding-right: 15px; } #footer .footer-meta .footer-meta-inner .open-government-licence { clear: left; position: relative; padding-left: 53px; } #footer .footer-meta .footer-meta-inner .open-government-licence .logo { margin-bottom: 1em; padding-top: 0; position: absolute; left: 0; top: 0; width: 41px; height: 100%; } #footer .footer-meta .footer-meta-inner .open-government-licence .logo a { display: block; width: 41px; height: 17px; overflow: hidden; text-indent: -999em; background: url(images/open-government-licence.png?0.12.0) 0 0 no-repeat; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 20 / 10), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) { #footer .footer-meta .footer-meta-inner .open-government-licence .logo a { background-image: url(images/open-government-licence_2x.png?0.12.0); background-size: 41px 17px; } } #footer .footer-meta .footer-meta-inner .open-government-licence p { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; margin: 0; padding-top: 0.1em; } @media (max-width: 640px) { #footer .footer-meta .footer-meta-inner .open-government-licence p { font-size: 14px; line-height: 1.14286; } } #footer .footer-meta .copyright { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; margin: 30px 0 0 0; width: 100%; display: block; display: inline-block; text-align: inherit; width: 25%; padding-top: 15px; margin-top: 0; float: right; height: 150px; width: 24%; } @media (max-width: 640px) { #footer .footer-meta .copyright { font-size: 14px; line-height: 1.14286; } } #footer .footer-meta .copyright a { display: block; background-image: url(images/govuk-crest.png?0.12.0); background-repeat: no-repeat; background-position: 50% 0%; background-position: 100% 0%; text-align: center; text-decoration: none; text-align: right; padding: 115px 0 0 0; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 20 / 10), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx) { #footer .footer-meta .copyright a { background-image: url(images/govuk-crest-2x.png?0.12.0); background-size: 125px 102px; } }
littlednet/in-progress
node_modules/govuk_template_mustache/assets/stylesheets/govuk-template-ie7.css
CSS
mit
22,249
' 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. Imports System Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class VisualBasicEESymbolProvider Inherits EESymbolProvider(Of TypeSymbol, LocalSymbol) Private ReadOnly _metadataDecoder As MetadataDecoder Private ReadOnly _method As PEMethodSymbol Public Sub New([module] As PEModuleSymbol, method As PEMethodSymbol) _metadataDecoder = New MetadataDecoder([module], method) _method = method End Sub Public Overrides Function GetLocalVariable( name As String, slotIndex As Integer, info As LocalInfo(Of TypeSymbol), dynamicFlagsOpt As ImmutableArray(Of Boolean), tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol ' Custom modifiers can be dropped since binding ignores custom ' modifiers from locals and since we only need to preserve ' the type of the original local in the generated method. Dim kind = If(name = _method.Name, LocalDeclarationKind.FunctionValue, LocalDeclarationKind.Variable) Dim type = IncludeTupleElementNamesIfAny(info.Type, tupleElementNamesOpt) Return New EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, info.IsByRef, info.IsPinned, canScheduleToStack:=False) End Function Public Overrides Function GetLocalConstant( name As String, type As TypeSymbol, value As ConstantValue, dynamicFlagsOpt As ImmutableArray(Of Boolean), tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol type = IncludeTupleElementNamesIfAny(type, tupleElementNamesOpt) Return New EELocalConstantSymbol(_method, name, type, value) End Function ''' <exception cref="BadImageFormatException"></exception> ''' <exception cref="UnsupportedSignatureContent"></exception> Public Overrides Function DecodeLocalVariableType(signature As ImmutableArray(Of Byte)) As TypeSymbol Return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature) End Function Public Overrides Function GetTypeSymbolForSerializedType(typeName As String) As TypeSymbol Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName) End Function ''' <exception cref="BadImageFormatException"></exception> ''' <exception cref="UnsupportedSignatureContent"></exception> Public Overrides Sub DecodeLocalConstant(ByRef reader As BlobReader, ByRef type As TypeSymbol, ByRef value As ConstantValue) _metadataDecoder.DecodeLocalConstantBlobOrThrow(reader, type, value) End Sub ''' <exception cref="BadImageFormatException"></exception> Public Overrides Function GetReferencedAssembly(handle As AssemblyReferenceHandle) As IAssemblySymbolInternal Dim index As Integer = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle) Dim assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index) ' GetReferencedAssemblySymbol should not return Nothing since this method is ' only used for import aliases in the PDB which are not supported from VB. Return assembly End Function ''' <exception cref="UnsupportedSignatureContent"></exception> Public Overrides Function [GetType](handle As EntityHandle) As TypeSymbol Dim isNoPiaLocalType As Boolean Return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, isNoPiaLocalType, allowTypeSpec:=True, requireShortForm:=False) End Function Private Function IncludeTupleElementNamesIfAny(type As TypeSymbol, tupleElementNamesOpt As ImmutableArray(Of String)) As TypeSymbol Return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt) End Function End Class End Namespace
AlekseyTs/roslyn
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb
Visual Basic
mit
4,500
// 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 System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class StringInfoGetTextElementEnumerator { public static IEnumerable<object[]> GetTextElementEnumerator_TestData() { yield return new object[] { "", 0, new string[0] }; // Empty string yield return new object[] { "Hello", 5, new string[0] }; // Index = string.Length // Surrogate pair yield return new object[] { "s\uDBFF\uDFFF$", 0, new string[] { "s", "\uDBFF\uDFFF", "$" } }; yield return new object[] { "s\uDBFF\uDFFF$", 1, new string[] { "\uDBFF\uDFFF", "$" } }; // Combining characters yield return new object[] { "13229^a\u20D1a", 6, new string[] { "a\u20D1", "a" } }; yield return new object[] { "13229^a\u20D1a", 0, new string[] { "1", "3", "2", "2", "9", "^", "a\u20D1", "a" } }; // Single base and combining character yield return new object[] { "a\u0300", 0, new string[] { "a\u0300" } }; yield return new object[] { "a\u0300", 1, new string[] { "\u0300" } }; // Lone combining character yield return new object[] { "\u0300\u0300", 0, new string[] { "\u0300", "\u0300" } }; } [Theory] [MemberData(nameof(GetTextElementEnumerator_TestData))] public void GetTextElementEnumerator(string str, int index, string[] expected) { if (index == 0) { TextElementEnumerator basicEnumerator = StringInfo.GetTextElementEnumerator(str); int basicCounter = 0; while (basicEnumerator.MoveNext()) { Assert.Equal(expected[basicCounter], basicEnumerator.Current.ToString()); basicCounter++; } Assert.Equal(expected.Length, basicCounter); } TextElementEnumerator indexedEnumerator = StringInfo.GetTextElementEnumerator(str, index); int indexedCounter = 0; while (indexedEnumerator.MoveNext()) { Assert.Equal(expected[indexedCounter], indexedEnumerator.Current.ToString()); indexedCounter++; } Assert.Equal(expected.Length, indexedCounter); } [Fact] public void GetTextElementEnumerator_Invalid() { Assert.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null)); // Str is null Assert.Throws<ArgumentNullException>("str", () => StringInfo.GetTextElementEnumerator(null, 0)); // Str is null Assert.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", -1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => StringInfo.GetTextElementEnumerator("abc", 4)); // Index > str.Length } } }
ellismg/corefx
src/System.Globalization/tests/StringInfo/StringInfoGetTextElementEnumerator.cs
C#
mit
3,157
/* 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. * */ /* * Based on the Reverse Engineering work of Christophe Fontanel, * maintainer of the Dungeon Master Encyclopaedia (http://dmweb.free.fr/) */ #include "graphics/surface.h" #include "graphics/thumbnail.h" #include "dm/inventory.h" #include "dm/dungeonman.h" #include "dm/eventman.h" #include "dm/group.h" #include "dm/menus.h" #include "dm/gfx.h" #include "dm/text.h" #include "dm/objectman.h" #include "dm/timeline.h" #include "dm/projexpl.h" #include "dm/sounds.h" namespace DM { void InventoryMan::initConstants() { static const char* skillLevelNamesEN[15] = {"NEOPHYTE", "NOVICE", "APPRENTICE", "JOURNEYMAN", "CRAFTSMAN", "ARTISAN", "ADEPT", "EXPERT", "` MASTER", "a MASTER","b MASTER", "c MASTER", "d MASTER", "e MASTER", "ARCHMASTER"}; static const char* skillLevelNamesDE[15] = {"ANFAENGER", "NEULING", "LEHRLING", "ARBEITER", "GESELLE", "HANDWERKR", "FACHMANN", "EXPERTE", "` MEISTER", "a MEISTER", "b MEISTER", "c MEISTER", "d MEISTER", "e MEISTER", "ERZMEISTR"}; static const char* skillLevelNamesFR[15] = {"NEOPHYTE", "NOVICE", "APPRENTI", "COMPAGNON", "ARTISAN", "PATRON", "ADEPTE", "EXPERT", "MAITRE '", "MAITRE a", "MAITRE b", "MAITRE c", "MAITRE d", "MAITRE e", "SUR-MAITRE"}; const char **translatedSkillLevel; switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: translatedSkillLevel = skillLevelNamesEN; break; case Common::DE_DEU: translatedSkillLevel = skillLevelNamesDE; break; case Common::FR_FRA: translatedSkillLevel = skillLevelNamesFR; break; } for (int i = 0; i < 15; ++i) _skillLevelNames[i] = translatedSkillLevel[i]; _boxPanel = Box(80, 223, 52, 124); // @ G0032_s_Graphic562_Box_Panel } InventoryMan::InventoryMan(DMEngine *vm) : _vm(vm) { _inventoryChampionOrdinal = 0; _panelContent = kDMPanelContentFoodWaterPoisoned; for (uint16 i = 0; i < 8; ++i) _chestSlots[i] = Thing(0); _openChest = _vm->_thingNone; _objDescTextXpos = 0; _objDescTextYpos = 0; for (int i = 0; i < 15; i++) _skillLevelNames[i] = nullptr; initConstants(); } void InventoryMan::toggleInventory(ChampionIndex championIndex) { static Box boxFloppyZzzCross(174, 218, 2, 12); // @ G0041_s_Graphic562_Box_ViewportFloppyZzzCross DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; if ((championIndex != kDMChampionCloseInventory) && !championMan._champions[championIndex]._currHealth) return; if (_vm->_pressingMouth || _vm->_pressingEye) return; _vm->_stopWaitingForPlayerInput = true; uint16 inventoryChampionOrdinal = _inventoryChampionOrdinal; if (_vm->indexToOrdinal(championIndex) == inventoryChampionOrdinal) championIndex = kDMChampionCloseInventory; _vm->_eventMan->showMouse(); if (inventoryChampionOrdinal) { _inventoryChampionOrdinal = _vm->indexToOrdinal(kDMChampionNone); closeChest(); Champion *champion = &championMan._champions[_vm->ordinalToIndex(inventoryChampionOrdinal)]; if (champion->_currHealth && !championMan._candidateChampionOrdinal) { setFlag(champion->_attributes, kDMAttributeStatusBox); championMan.drawChampionState((ChampionIndex)_vm->ordinalToIndex(inventoryChampionOrdinal)); } if (championMan._partyIsSleeping) { _vm->_eventMan->hideMouse(); return; } if (championIndex == kDMChampionCloseInventory) { _vm->_eventMan->_refreshMousePointerInMainLoop = true; _vm->_menuMan->drawMovementArrows(); _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputMovement; _vm->_eventMan->_secondaryKeyboardInput = _vm->_eventMan->_secondaryKeyboardInputMovement; _vm->_eventMan->discardAllInput(); display.drawFloorAndCeiling(); return; } } display._useByteBoxCoordinates = false; _inventoryChampionOrdinal = _vm->indexToOrdinal(championIndex); if (!inventoryChampionOrdinal) display.shadeScreenBox(&display._boxMovementArrows, kDMColorBlack); Champion *champion = &championMan._champions[championIndex]; display.loadIntoBitmap(kDMGraphicIdxInventory, display._bitmapViewport); if (championMan._candidateChampionOrdinal) display.fillBoxBitmap(display._bitmapViewport, boxFloppyZzzCross, kDMColorDarkestGray, k112_byteWidthViewport, k136_heightViewport); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "HEALTH"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "STAMINA"); break; case Common::DE_DEU: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "GESUND"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "KRAFT"); break; case Common::FR_FRA: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "SANTE"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "VIGUEUR"); break; } _vm->_textMan->printToViewport(5, 132, kDMColorLightestGray, "MANA"); for (uint16 i = kDMSlotReadyHand; i < kDMSlotChest1; i++) championMan.drawSlot(championIndex, i); setFlag(champion->_attributes, kDMAttributeViewport | kDMAttributeStatusBox | kDMAttributePanel | kDMAttributeLoad | kDMAttributeStatistics | kDMAttributeNameTitle); championMan.drawChampionState(championIndex); _vm->_eventMan->_mousePointerBitmapUpdated = true; _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputChampionInventory; _vm->_eventMan->_secondaryKeyboardInput = nullptr; _vm->_eventMan->discardAllInput(); } void InventoryMan::drawStatusBoxPortrait(ChampionIndex championIndex) { DisplayMan &dispMan = *_vm->_displayMan; dispMan._useByteBoxCoordinates = false; Box box; box._rect.top = 0; box._rect.bottom = 28; box._rect.left = championIndex * kDMChampionStatusBoxSpacing + 7; box._rect.right = box._rect.left + 31; dispMan.blitToScreen(_vm->_championMan->_champions[championIndex]._portrait, &box, k16_byteWidth, kDMColorNoTransparency, 29); } void InventoryMan::drawPanelHorizontalBar(int16 x, int16 y, int16 pixelWidth, Color color) { DisplayMan &display = *_vm->_displayMan; Box box; box._rect.left = x; box._rect.right = box._rect.left + pixelWidth; box._rect.top = y; box._rect.bottom = box._rect.top + 6; display._useByteBoxCoordinates = false; display.fillBoxBitmap(display._bitmapViewport, box, color, k112_byteWidthViewport, k136_heightViewport); } void InventoryMan::drawPanelFoodOrWaterBar(int16 amount, int16 y, Color color) { if (amount < -512) color = kDMColorRed; else if (amount < 0) color = kDMColorYellow; int16 pixelWidth = amount + 1024; if (pixelWidth == 3072) pixelWidth = 3071; pixelWidth /= 32; drawPanelHorizontalBar(115, y + 2, pixelWidth, kDMColorBlack); drawPanelHorizontalBar(113, y, pixelWidth, color); } void InventoryMan::drawPanelFoodWaterPoisoned() { static Box boxFood(112, 159, 60, 68); // @ G0035_s_Graphic562_Box_Food static Box boxWater(112, 159, 83, 91); // @ G0036_s_Graphic562_Box_Water static Box boxPoisoned(112, 207, 105, 119); // @ G0037_s_Graphic562_Box_Poisoned Champion &champ = _vm->_championMan->_champions[_inventoryChampionOrdinal]; closeChest(); DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k24_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; case Common::DE_DEU: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k32_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k32_byteWidth, kDMColorDarkestGray, 9); break; case Common::FR_FRA: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k48_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; } if (champ._poisonEventCount) dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPoisionedLabel), boxPoisoned, k48_byteWidth, kDMColorDarkestGray, 15); drawPanelFoodOrWaterBar(champ._food, 69, kDMColorLightBrown); drawPanelFoodOrWaterBar(champ._water, 92, kDMColorBlue); } void InventoryMan::drawPanelResurrectReincarnate() { DisplayMan &display = *_vm->_displayMan; _panelContent = kDMPanelContentResurrectReincarnate; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelResurectReincarnate), _boxPanel, k72_byteWidth, kDMColorDarkGreen, 73); } void InventoryMan::drawPanel() { closeChest(); ChampionMan &cm = *_vm->_championMan; if (cm._candidateChampionOrdinal) { drawPanelResurrectReincarnate(); return; } Thing thing = cm._champions[_vm->ordinalToIndex(_inventoryChampionOrdinal)].getSlot(kDMSlotActionHand); _panelContent = kDMPanelContentFoodWaterPoisoned; switch (thing.getType()) { case kDMThingTypeContainer: _panelContent = kDMPanelContentChest; break; case kDMThingTypeScroll: _panelContent = kDMPanelContentScroll; break; default: thing = _vm->_thingNone; break; } if (thing == _vm->_thingNone) drawPanelFoodWaterPoisoned(); else drawPanelObject(thing, false); } void InventoryMan::closeChest() { DungeonMan &dunMan = *_vm->_dungeonMan; bool processFirstChestSlot = true; if (_openChest == _vm->_thingNone) return; Container *container = (Container *)dunMan.getThingData(_openChest); _openChest = _vm->_thingNone; container->getSlot() = _vm->_thingEndOfList; Thing prevThing; for (int16 chestSlotIndex = 0; chestSlotIndex < 8; ++chestSlotIndex) { Thing thing = _chestSlots[chestSlotIndex]; if (thing != _vm->_thingNone) { _chestSlots[chestSlotIndex] = _vm->_thingNone; // CHANGE8_09_FIX if (processFirstChestSlot) { processFirstChestSlot = false; *dunMan.getThingData(thing) = _vm->_thingEndOfList.toUint16(); container->getSlot() = prevThing = thing; } else { dunMan.linkThingToList(thing, prevThing, kDMMapXNotOnASquare, 0); prevThing = thing; } } } } void InventoryMan::drawPanelScrollTextLine(int16 yPos, char *text) { for (char *iter = text; *iter != '\0'; ++iter) { if ((*iter >= 'A') && (*iter <= 'Z')) *iter -= 64; else if (*iter >= '{') // this branch is CHANGE5_03_IMPROVEMENT *iter -= 96; } _vm->_textMan->printToViewport(162 - (6 * strlen(text) / 2), yPos, kDMColorBlack, text, kDMColorWhite); } void InventoryMan::drawPanelScroll(Scroll *scroll) { DisplayMan &dispMan = *_vm->_displayMan; char stringFirstLine[300]; _vm->_dungeonMan->decodeText(stringFirstLine, Thing(scroll->getTextStringThingIndex()), (TextType)(kDMTextTypeScroll | kDMMaskDecodeEvenIfInvisible)); char *charRed = stringFirstLine; while (*charRed && (*charRed != '\n')) charRed++; *charRed = '\0'; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenScroll), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 lineCount = 1; charRed++; char *charGreen = charRed; // first char of the second line while (*charGreen) { /* BUG0_47 Graphical glitch when you open a scroll. If there is a single line of text in a scroll (with no carriage return) then charGreen points to undefined data. This may result in a graphical glitch and also corrupt other memory. This is not an issue in the original dungeons where all scrolls contain at least one carriage return character */ if (*charGreen == '\n') lineCount++; charGreen++; } if (*(charGreen - 1) != '\n') lineCount++; else if (*(charGreen - 2) == '\n') lineCount--; int16 yPos = 92 - (7 * lineCount) / 2; // center the text vertically drawPanelScrollTextLine(yPos, stringFirstLine); charGreen = charRed; while (*charGreen) { yPos += 7; while (*charRed && (*charRed != '\n')) charRed++; if (!(*charRed)) charRed[1] = '\0'; *charRed++ = '\0'; drawPanelScrollTextLine(yPos, charGreen); charGreen = charRed; } } void InventoryMan::openAndDrawChest(Thing thingToOpen, Container *chest, bool isPressingEye) { DisplayMan &dispMan = *_vm->_displayMan; ObjectMan &objMan = *_vm->_objectMan; if (_openChest == thingToOpen) return; if (_openChest != _vm->_thingNone) closeChest(); // CHANGE8_09_FIX _openChest = thingToOpen; if (!isPressingEye) { objMan.drawIconInSlotBox(kDMSlotBoxInventoryActionHand, kDMIconIndiceContainerChestOpen); } dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenChest), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 chestSlotIndex = 0; Thing thing = chest->getSlot(); int16 thingCount = 0; while (thing != _vm->_thingEndOfList) { if (++thingCount > 8) break; // CHANGE8_08_FIX, make sure that no more than the first 8 objects in a chest are drawn objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, objMan.getIconIndex(thing)); _chestSlots[chestSlotIndex++] = thing; thing = _vm->_dungeonMan->getNextThing(thing); } while (chestSlotIndex < 8) { objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, kDMIconIndiceNone); _chestSlots[chestSlotIndex++] = _vm->_thingNone; } } void InventoryMan::drawIconToViewport(IconIndice iconIndex, int16 xPos, int16 yPos) { static byte iconBitmap[16 * 16]; Box boxIcon(xPos, xPos + 15, yPos, yPos + 15); _vm->_objectMan->extractIconFromBitmap(iconIndex, iconBitmap); _vm->_displayMan->blitToViewport(iconBitmap, boxIcon, k8_byteWidth, kDMColorNoTransparency, 16); } void InventoryMan::buildObjectAttributeString(int16 potentialAttribMask, int16 actualAttribMask, const char **attribStrings, char *destString, const char *prefixString, const char *suffixString) { uint16 identicalBitCount = 0; int16 attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) identicalBitCount++; } if (identicalBitCount == 0) { *destString = '\0'; return; } strcpy(destString, prefixString); attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) { strcat(destString, attribStrings[stringIndex]); if (identicalBitCount-- > 2) { strcat(destString, ", "); } else if (identicalBitCount == 1) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: strcat(destString, " AND "); break; case Common::DE_DEU: strcat(destString, " UND "); break; case Common::FR_FRA: strcat(destString, " ET "); break; } } } } strcat(destString, suffixString); } void InventoryMan::drawPanelObjectDescriptionString(const char *descString) { if (descString[0] == '\f') { // form feed descString++; _objDescTextXpos = 108; _objDescTextYpos = 59; } if (descString[0]) { char stringTmpBuff[128]; strcpy(stringTmpBuff, descString); char *stringLine = stringTmpBuff; bool severalLines = false; char *string = nullptr; while (*stringLine) { if (strlen(stringLine) > 18) { // if string is too long to fit on one line string = &stringLine[17]; while (*string != ' ') // go back to the last space character string--; *string = '\0'; // and split the string there severalLines = true; } _vm->_textMan->printToViewport(_objDescTextXpos, _objDescTextYpos, kDMColorLightestGray, stringLine); _objDescTextYpos += 7; if (severalLines) { severalLines = false; stringLine = ++string; } else { *stringLine = '\0'; } } } } void InventoryMan::drawPanelArrowOrEye(bool pressingEye) { static Box boxArrowOrEye(83, 98, 57, 65); // @ G0033_s_Graphic562_Box_ArrowOrEye DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(pressingEye ? kDMGraphicIdxEyeForObjectDescription : kDMGraphicIdxArrowForChestContent), boxArrowOrEye, k8_byteWidth, kDMColorRed, 9); } void InventoryMan::drawPanelObject(Thing thingToDraw, bool pressingEye) { static Box boxObjectDescCircle(105, 136, 53, 79); // @ G0034_s_Graphic562_Box_ObjectDescriptionCircle DungeonMan &dungeon = *_vm->_dungeonMan; ObjectMan &objMan = *_vm->_objectMan; DisplayMan &dispMan = *_vm->_displayMan; ChampionMan &champMan = *_vm->_championMan; TextMan &textMan = *_vm->_textMan; if (_vm->_pressingEye || _vm->_pressingMouth) closeChest(); uint16 *rawThingPtr = dungeon.getThingData(thingToDraw); drawPanelObjectDescriptionString("\f"); // form feed ThingType thingType = thingToDraw.getType(); if (thingType == kDMThingTypeScroll) drawPanelScroll((Scroll *)rawThingPtr); else if (thingType == kDMThingTypeContainer) openAndDrawChest(thingToDraw, (Container *)rawThingPtr, pressingEye); else { IconIndice iconIndex = objMan.getIconIndex(thingToDraw); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxObjectDescCircle), boxObjectDescCircle, k16_byteWidth, kDMColorDarkestGray, 27); Common::String descString; Common::String str; if (iconIndex == kDMIconIndiceJunkChampionBones) { switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug dur to a cut&paste error: string was concatenated then overwritten by the name str = Common::String::format("%s %s", objMan._objectNames[iconIndex], champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name); break; default: // German and English versions are the same str = Common::String::format("%s %s", champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name, objMan._objectNames[iconIndex]); break; } descString = str; } else if ((thingType == kDMThingTypePotion) && (iconIndex != kDMIconIndicePotionWaterFlask) && (champMan.getSkillLevel((ChampionIndex)_vm->ordinalToIndex(_inventoryChampionOrdinal), kDMSkillPriest) > 1)) { str = ('_' + ((Potion *)rawThingPtr)->getPower() / 40); str += " "; str += objMan._objectNames[iconIndex]; descString = str; } else { descString = objMan._objectNames[iconIndex]; } textMan.printToViewport(134, 68, kDMColorLightestGray, descString.c_str()); drawIconToViewport(iconIndex, 111, 59); _objDescTextYpos = 87; uint16 potentialAttribMask = 0; uint16 actualAttribMask = 0; switch (thingType) { case kDMThingTypeWeapon: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskPoisoned | kDMDescriptionMaskBroken; Weapon *weapon = (Weapon *)rawThingPtr; actualAttribMask = (weapon->getCursed() << 3) | (weapon->getPoisoned() << 1) | (weapon->getBroken() << 2); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit) && (weapon->getChargeCount() == 0)) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: drawPanelObjectDescriptionString("(BURNT OUT)"); break; case Common::DE_DEU: drawPanelObjectDescriptionString("(AUSGEBRANNT)"); break; case Common::FR_FRA: drawPanelObjectDescriptionString("(CONSUME)"); break; } } break; } case kDMThingTypeArmour: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskBroken; Armour *armour = (Armour *)rawThingPtr; actualAttribMask = (armour->getCursed() << 3) | (armour->getBroken() << 2); break; } case kDMThingTypePotion: { potentialAttribMask = kDMDescriptionMaskConsumable; Potion *potion = (Potion *)rawThingPtr; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstPotion + potion->getType()].getAllowedSlots(); break; } case kDMThingTypeJunk: { if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { potentialAttribMask = 0; const char *descStringEN[4] = {"(EMPTY)", "(ALMOST EMPTY)", "(ALMOST FULL)", "(FULL)"}; const char *descStringDE[4] = {"(LEER)", "(FAST LEER)", "(FAST VOLL)", "(VOLL)"}; const char *descStringFR[4] = {"(VIDE)", "(PRESQUE VIDE)", "(PRESQUE PLEINE)", "(PLEINE)"}; Junk *junk = (Junk *)rawThingPtr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: descString = descStringDE[junk->getChargeCount()]; break; case Common::FR_FRA: descString = descStringFR[junk->getChargeCount()]; break; default: descString = descStringEN[junk->getChargeCount()]; break; } drawPanelObjectDescriptionString(descString.c_str()); } else if ((iconIndex >= kDMIconIndiceJunkCompassNorth) && (iconIndex <= kDMIconIndiceJunkCompassWest)) { const static char *directionNameEN[4] = {"NORTH", "EAST", "SOUTH", "WEST"}; const static char *directionNameDE[4] = {"NORDEN", "OSTEN", "SUEDEN", "WESTEN"}; const static char *directionNameFR[4] = {"AU NORD", "A L'EST", "AU SUD", "A L'OUEST"}; potentialAttribMask = 0; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "GRUPPE BLICKT NACH "; str += directionNameDE[iconIndex]; break; case Common::FR_FRA: str = "GROUPE FACE "; str += directionNameFR[iconIndex]; break; default: str = "PARTY FACING "; str += directionNameEN[iconIndex]; break; } drawPanelObjectDescriptionString(str.c_str()); } else { Junk *junk = (Junk *)rawThingPtr; potentialAttribMask = kDMDescriptionMaskConsumable; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstJunk + junk->getType()].getAllowedSlots(); } break; } default: break; } // end of switch if (potentialAttribMask) { static const char *attribStringEN[4] = {"CONSUMABLE", "POISONED", "BROKEN", "CURSED"}; static const char *attribStringDE[4] = {"ESSBAR", "VERGIFTET", "DEFEKT", "VERFLUCHT"}; static const char *attribStringFR[4] = {"COMESTIBLE", "EMPOISONNE", "BRISE", "MAUDIT"}; const char **attribString = nullptr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: attribString = attribStringDE; break; case Common::FR_FRA: attribString = attribStringFR; break; default: attribString = attribStringEN; break; } char destString[40]; buildObjectAttributeString(potentialAttribMask, actualAttribMask, attribString, destString, "(", ")"); drawPanelObjectDescriptionString(destString); } uint16 weight = dungeon.getObjectWeight(thingToDraw); switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "WIEGT " + champMan.getStringFromInteger(weight / 10, false, 3) + ","; break; case Common::FR_FRA: str = "PESE " + champMan.getStringFromInteger(weight / 10, false, 3) + "KG,"; break; default: str = "WEIGHS " + champMan.getStringFromInteger(weight / 10, false, 3) + "."; break; } weight -= (weight / 10) * 10; str += champMan.getStringFromInteger(weight, false, 1); switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: str += "."; break; default: str += " KG."; break; } drawPanelObjectDescriptionString(str.c_str()); } drawPanelArrowOrEye(pressingEye); } void InventoryMan::setDungeonViewPalette() { static const int16 palIndexToLightAmmount[6] = {99, 75, 50, 25, 1, 0}; // @ G0040_ai_Graphic562_PaletteIndexToLightAmount DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (dungeon._currMap->_difficulty == 0) { display._dungeonViewPaletteIndex = 0; /* Brightest color palette index */ } else { /* Get torch light power from both hands of each champion in the party */ int16 counter = 4; /* BUG0_01 Coding error without consequence. The hands of four champions are inspected even if there are less champions in the party. No consequence as the data in unused champions is set to 0 and _vm->_objectMan->f32_getObjectType then returns -1 */ Champion *curChampion = championMan._champions; int16 torchesLightPower[8]; int16 *curTorchLightPower = torchesLightPower; while (counter--) { uint16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { Thing slotThing = curChampion->_slots[slotIndex]; if ((_vm->_objectMan->getObjectType(slotThing) >= kDMIconIndiceWeaponTorchUnlit) && (_vm->_objectMan->getObjectType(slotThing) <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(slotThing); *curTorchLightPower = curWeapon->getChargeCount(); } else { *curTorchLightPower = 0; } curTorchLightPower++; } curChampion++; } /* Sort torch light power values so that the four highest values are in the first four entries in the array L1045_ai_TorchesLightPower in decreasing order. The last four entries contain the smallest values but they are not sorted */ curTorchLightPower = torchesLightPower; int16 torchIndex = 0; while (torchIndex != 4) { counter = 7 - torchIndex; int16 *L1041_pi_TorchLightPower = &torchesLightPower[torchIndex + 1]; while (counter--) { if (*L1041_pi_TorchLightPower > *curTorchLightPower) { int16 AL1044_ui_TorchLightPower = *L1041_pi_TorchLightPower; *L1041_pi_TorchLightPower = *curTorchLightPower; *curTorchLightPower = AL1044_ui_TorchLightPower; } L1041_pi_TorchLightPower++; } curTorchLightPower++; torchIndex++; } /* Get total light amount provided by the four torches with the highest light power values and by the fifth torch in the array which may be any one of the four torches with the smallest ligh power values */ uint16 torchLightAmountMultiplier = 6; torchIndex = 5; int16 totalLightAmount = 0; curTorchLightPower = torchesLightPower; while (torchIndex--) { if (*curTorchLightPower) { totalLightAmount += (championMan._lightPowerToLightAmount[*curTorchLightPower] << torchLightAmountMultiplier) >> 6; torchLightAmountMultiplier = MAX(0, torchLightAmountMultiplier - 1); } curTorchLightPower++; } totalLightAmount += championMan._party._magicalLightAmount; /* Select palette corresponding to the total light amount */ const int16 *curLightAmount = palIndexToLightAmmount; int16 paletteIndex; if (totalLightAmount > 0) { paletteIndex = 0; /* Brightest color palette index */ while (*curLightAmount++ > totalLightAmount) paletteIndex++; } else { paletteIndex = 5; /* Darkest color palette index */ } display._dungeonViewPaletteIndex = paletteIndex; } display._refreshDungeonViewPaleteRequested = true; } void InventoryMan::decreaseTorchesLightPower() { ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; bool torchChargeCountChanged = false; int16 championCount = championMan._partyChampionCount; if (championMan._candidateChampionOrdinal) championCount--; Champion *curChampion = championMan._champions; while (championCount--) { int16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { int16 iconIndex = _vm->_objectMan->getIconIndex(curChampion->_slots[slotIndex]); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(curChampion->_slots[slotIndex]); if (curWeapon->getChargeCount()) { if (curWeapon->setChargeCount(curWeapon->getChargeCount() - 1) == 0) { curWeapon->setDoNotDiscard(false); } torchChargeCountChanged = true; } } } curChampion++; } if (torchChargeCountChanged) { setDungeonViewPalette(); championMan.drawChangedObjectIcons(); } } void InventoryMan::drawChampionSkillsAndStatistics() { static const char *statisticNamesEN[7] = {"L", "STRENGTH", "DEXTERITY", "WISDOM", "VITALITY", "ANTI-MAGIC", "ANTI-FIRE"}; static const char *statisticNamesDE[7] = {"L", "STAERKE", "FLINKHEIT", "WEISHEIT", "VITALITAET", "ANTI-MAGIE", "ANTI-FEUER"}; static const char *statisticNamesFR[7] = {"L", "FORCE", "DEXTERITE", "SAGESSE", "VITALITE", "ANTI-MAGIE", "ANTI-FEU"}; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; const char **statisticNames; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: statisticNames = statisticNamesDE; break; case Common::FR_FRA: statisticNames = statisticNamesFR; break; default: statisticNames = statisticNamesEN; break; } closeChest(); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 textPosY = 58; for (uint16 idx = kDMSkillFighter; idx <= kDMSkillWizard; idx++) { int16 skillLevel = MIN((uint16)16, championMan.getSkillLevel(championIndex, idx | kDMIgnoreTemporaryExperience)); if (skillLevel == 1) continue; Common::String displayString; switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug: Due to a copy&paste error, the string was concatenate then overwritten be the last part displayString = Common::String::format("%s %s", championMan._baseSkillName[idx], _skillLevelNames[skillLevel - 2]); break; default: // English and German versions are built the same way displayString = Common::String::format("%s %s", _skillLevelNames[skillLevel - 2], championMan._baseSkillName[idx]); break; } _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } textPosY = 86; for (uint16 idx = kDMStatStrength; idx <= kDMStatAntifire; idx++) { _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, statisticNames[idx]); int16 statisticCurrentValue = curChampion->_statistics[idx][kDMStatCurrent]; uint16 statisticMaximumValue = curChampion->_statistics[idx][kDMStatMaximum]; int16 statisticColor; if (statisticCurrentValue < statisticMaximumValue) statisticColor = kDMColorRed; else if (statisticCurrentValue > statisticMaximumValue) statisticColor = kDMColorLightGreen; else statisticColor = kDMColorLightestGray; _vm->_textMan->printToViewport(174, textPosY, (Color)statisticColor, championMan.getStringFromInteger(statisticCurrentValue, true, 3).c_str()); Common::String displayString = "/" + championMan.getStringFromInteger(statisticMaximumValue, true, 3); _vm->_textMan->printToViewport(192, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } } void InventoryMan::drawStopPressingMouth() { drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); _vm->_eventMan->_hideMousePointerRequestCount = 1; _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::drawStopPressingEye() { drawIconToViewport(kDMIconIndiceEyeNotLooking, 12, 13); drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); Thing leaderHandObject = _vm->_championMan->_leaderHandObject; if (leaderHandObject != _vm->_thingNone) _vm->_objectMan->drawLeaderObjectName(leaderHandObject); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::clickOnMouth() { static int16 foodAmounts[8] = { 500, /* Apple */ 600, /* Corn */ 650, /* Bread */ 820, /* Cheese */ 550, /* Screamer Slice */ 350, /* Worm round */ 990, /* Drumstick / Shank */ 1400 /* Dragon steak */ }; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (championMan._leaderEmptyHanded) { if (_panelContent == kDMPanelContentFoodWaterPoisoned) return; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingMouth = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingMouth = false; _vm->_stopPressingMouth = false; } else { _vm->_eventMan->showMouse(); _vm->_eventMan->_hideMousePointerRequestCount = 1; drawPanelFoodWaterPoisoned(); display.drawViewport(k0_viewportNotDungeonView); } return; } if (championMan._candidateChampionOrdinal) return; Thing handThing = championMan._leaderHandObject; if (!getFlag(dungeon._objectInfos[dungeon.getObjectInfoIndex(handThing)]._allowedSlots, kDMMaskMouth)) return; uint16 iconIndex = _vm->_objectMan->getIconIndex(handThing); uint16 handThingType = handThing.getType(); uint16 handThingWeight = dungeon.getObjectWeight(handThing); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; Junk *junkData = (Junk *)dungeon.getThingData(handThing); bool removeObjectFromLeaderHand; if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { if (!(junkData->getChargeCount())) return; curChampion->_water = MIN(curChampion->_water + 800, 2048); junkData->setChargeCount(junkData->getChargeCount() - 1); removeObjectFromLeaderHand = false; } else if (handThingType == kDMThingTypePotion) removeObjectFromLeaderHand = false; else { junkData->setNextThing(_vm->_thingNone); removeObjectFromLeaderHand = true; } _vm->_eventMan->showMouse(); if (removeObjectFromLeaderHand) championMan.getObjectRemovedFromLeaderHand(); if (handThingType == kDMThingTypePotion) { uint16 potionPower = ((Potion *)junkData)->getPower(); uint16 counter = ((511 - potionPower) / (32 + (potionPower + 1) / 8)) >> 1; uint16 adjustedPotionPower = (potionPower / 25) + 8; /* Value between 8 and 18 */ switch (((Potion *)junkData)->getType()) { case kDMPotionTypeRos: adjustStatisticCurrentValue(curChampion, kDMStatDexterity, adjustedPotionPower); break; case kDMPotionTypeKu: adjustStatisticCurrentValue(curChampion, kDMStatStrength, (((Potion *)junkData)->getPower() / 35) + 5); /* Value between 5 and 12 */ break; case kDMPotionTypeDane: adjustStatisticCurrentValue(curChampion, kDMStatWisdom, adjustedPotionPower); break; case kDMPotionTypeNeta: adjustStatisticCurrentValue(curChampion, kDMStatVitality, adjustedPotionPower); break; case kDMPotionTypeAntivenin: championMan.unpoison(championIndex); break; case kDMPotionTypeMon: curChampion->_currStamina += MIN(curChampion->_maxStamina - curChampion->_currStamina, curChampion->_maxStamina / counter); break; case kDMPotionTypeYa: { adjustedPotionPower += adjustedPotionPower >> 1; if (curChampion->_shieldDefense > 50) adjustedPotionPower >>= 2; curChampion->_shieldDefense += adjustedPotionPower; TimelineEvent newEvent; newEvent._type = kDMEventTypeChampionShield; newEvent._mapTime = _vm->setMapAndTime(dungeon._partyMapIndex, _vm->_gameTime + (adjustedPotionPower * adjustedPotionPower)); newEvent._priority = championIndex; newEvent._Bu._defense = adjustedPotionPower; _vm->_timeline->addEventGetEventIndex(&newEvent); setFlag(curChampion->_attributes, kDMAttributeStatusBox); } break; case kDMPotionTypeEe: { uint16 mana = MIN(900, (curChampion->_currMana + adjustedPotionPower) + (adjustedPotionPower - 8)); if (mana > curChampion->_maxMana) mana -= (mana - MAX(curChampion->_currMana, curChampion->_maxMana)) >> 1; curChampion->_currMana = mana; } break; case kDMPotionTypeVi: { uint16 healWoundIterationCount = MAX(1, (((Potion *)junkData)->getPower() / 42)); curChampion->_currHealth += curChampion->_maxHealth / counter; int16 wounds = curChampion->_wounds; if (wounds) { /* If the champion is wounded */ counter = 10; do { for (uint16 i = 0; i < healWoundIterationCount; i++) curChampion->_wounds &= _vm->getRandomNumber(65536); healWoundIterationCount = 1; } while ((wounds == curChampion->_wounds) && --counter); /* Loop until at least one wound is healed or there are no more heal iterations */ } setFlag(curChampion->_attributes, kDMAttributeLoad | kDMAttributeWounds); } break; case kDMPotionTypeWaterFlask: curChampion->_water = MIN(curChampion->_water + 1600, 2048); break; default: break; } ((Potion *)junkData)->setType(kDMPotionTypeEmptyFlask); } else if ((iconIndex >= kDMIconIndiceJunkApple) && (iconIndex < kDMIconIndiceJunkIronKey)) curChampion->_food = MIN(curChampion->_food + foodAmounts[iconIndex - kDMIconIndiceJunkApple], 2048); if (curChampion->_currStamina > curChampion->_maxStamina) curChampion->_currStamina = curChampion->_maxStamina; if (curChampion->_currHealth > curChampion->_maxHealth) curChampion->_currHealth = curChampion->_maxHealth; if (removeObjectFromLeaderHand) { for (uint16 i = 5; --i; _vm->delay(8)) { /* Animate mouth icon */ _vm->_objectMan->drawIconToScreen(kDMIconIndiceMouthOpen + !(i & 0x0001), 56, 46); _vm->_eventMan->discardAllInput(); if (_vm->_engineShouldQuit) return; display.updateScreen(); } } else { championMan.drawChangedObjectIcons(); championMan._champions[championMan._leaderIndex]._load += dungeon.getObjectWeight(handThing) - handThingWeight; setFlag(championMan._champions[championMan._leaderIndex]._attributes, kDMAttributeLoad); } _vm->_sound->requestPlay(kDMSoundIndexSwallow, dungeon._partyMapX, dungeon._partyMapY, kDMSoundModePlayImmediately); setFlag(curChampion->_attributes, kDMAttributeStatistics); if (_panelContent == kDMPanelContentFoodWaterPoisoned) setFlag(curChampion->_attributes, kDMAttributePanel); championMan.drawChampionState((ChampionIndex)championIndex); _vm->_eventMan->hideMouse(); } void InventoryMan::adjustStatisticCurrentValue(Champion *champ, uint16 statIndex, int16 valueDelta) { int16 delta; if (valueDelta >= 0) { int16 currentValue = champ->_statistics[statIndex][kDMStatCurrent]; if (currentValue > 120) { valueDelta >>= 1; if (currentValue > 150) { valueDelta >>= 1; } valueDelta++; } delta = MIN(valueDelta, (int16)(170 - currentValue)); } else { /* BUG0_00 Useless code. The function is always called with valueDelta having a positive value */ delta = MAX(valueDelta, int16(champ->_statistics[statIndex][kDMStatMinimum] - champ->_statistics[statIndex][kDMStatCurrent])); } champ->_statistics[statIndex][kDMStatCurrent] += delta; } void InventoryMan::clickOnEye() { ChampionMan &championMan = *_vm->_championMan; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingEye = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingEye = false; _vm->_stopPressingEye = false; return; } _vm->_eventMan->discardAllInput(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->delay(8); drawIconToViewport(kDMIconIndiceEyeLooking, 12, 13); if (championMan._leaderEmptyHanded) drawChampionSkillsAndStatistics(); else { _vm->_objectMan->clearLeaderObjectName(); drawPanelObject(championMan._leaderHandObject, true); } _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); } }
alexbevi/scummvm
engines/dm/inventory.cpp
C++
gpl-2.0
40,443
/* Update additional symbol information in symbol table at the given index. Copyright (C) 2000, 2001, 2002 Red Hat, Inc. This file is part of Red Hat elfutils. Written by Ulrich Drepper <drepper@redhat.com>, 2000. Red Hat elfutils 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; version 2 of the License. Red Hat elfutils 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 Red Hat elfutils; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA. In addition, as a special exception, Red Hat, Inc. gives You the additional right to link the code of Red Hat elfutils with code licensed under any Open Source Initiative certified open source license (http://www.opensource.org/licenses/index.php) which requires the distribution of source code with any binary distribution and to distribute linked combinations of the two. Non-GPL Code permitted under this exception must only link to the code of Red Hat elfutils through those well defined interfaces identified in the file named EXCEPTION found in the source code files (the "Approved Interfaces"). The files of Non-GPL Code may instantiate templates or use macros or inline functions from the Approved Interfaces without causing the resulting work to be covered by the GNU General Public License. Only Red Hat, Inc. may make changes or additions to the list of Approved Interfaces. Red Hat's grant of this exception is conditioned upon your not adding any new exceptions. If you wish to add a new Approved Interface or exception, please contact Red Hat. You must obey the GNU General Public License in all respects for all of the Red Hat elfutils code and other code used in conjunction with Red Hat elfutils except the Non-GPL Code covered by this exception. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to provide this exception without modification, you must delete this exception statement from your version and license this file solely under the GPL without exception. Red Hat elfutils is an included package of the Open Invention Network. An included package of the Open Invention Network is a package for which Open Invention Network licensees cross-license their patents. No patent license is granted, either expressly or impliedly, by designation as an included package. Should you wish to participate in the Open Invention Network licensing program, please visit www.openinventionnetwork.com <http://www.openinventionnetwork.com>. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <assert.h> #include <gelf.h> #include <stdlib.h> #include "libelfP.h" int gelf_update_syminfo (data, ndx, src) Elf_Data *data; int ndx; GElf_Syminfo *src; { Elf_Data_Scn *data_scn = (Elf_Data_Scn *) data; Elf_Scn *scn; int result = 0; if (data == NULL) return 0; if (unlikely (ndx < 0)) { __libelf_seterrno (ELF_E_INVALID_INDEX); return 0; } if (unlikely (data_scn->d.d_type != ELF_T_SYMINFO)) { /* The type of the data better should match. */ __libelf_seterrno (ELF_E_DATA_MISMATCH); return 0; } /* The types for 32 and 64 bit are the same. Lucky us. */ assert (sizeof (GElf_Syminfo) == sizeof (Elf32_Syminfo)); assert (sizeof (GElf_Syminfo) == sizeof (Elf64_Syminfo)); scn = data_scn->s; rwlock_wrlock (scn->elf->lock); /* Check whether we have to resize the data buffer. */ if (unlikely ((ndx + 1) * sizeof (GElf_Syminfo) > data_scn->d.d_size)) { __libelf_seterrno (ELF_E_INVALID_INDEX); goto out; } ((GElf_Syminfo *) data_scn->d.d_buf)[ndx] = *src; result = 1; /* Mark the section as modified. */ scn->flags |= ELF_F_DIRTY; out: rwlock_unlock (scn->elf->lock); return result; }
AOKP/external_elfutils
libelf/gelf_update_syminfo.c
C
gpl-2.0
4,328
//===-- DWARFCompileUnit.h --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_DEBUGINFO_DWARFCOMPILEUNIT_H #define LLVM_LIB_DEBUGINFO_DWARFCOMPILEUNIT_H #include "llvm/DebugInfo/DWARF/DWARFUnit.h" namespace llvm { class DWARFCompileUnit : public DWARFUnit { public: DWARFCompileUnit(DWARFContext &Context, const DWARFSection &Section, const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS, StringRef SOS, StringRef AOS, bool LE, const DWARFUnitSectionBase &UnitSection) : DWARFUnit(Context, Section, DA, RS, SS, SOS, AOS, LE, UnitSection) {} void dump(raw_ostream &OS); // VTable anchor. ~DWARFCompileUnit() override; }; } #endif
rutgers-apl/Atomicity-Violation-Detector
tdebug-llvm/llvm/include/llvm/DebugInfo/DWARF/DWARFCompileUnit.h
C
gpl-2.0
988
/* * Functions related to sysfs handling */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/bio.h> #include <linux/blkdev.h> #include <linux/blktrace_api.h> #include "blk.h" struct queue_sysfs_entry { struct attribute attr; ssize_t (*show)(struct request_queue *, char *); ssize_t (*store)(struct request_queue *, const char *, size_t); }; static ssize_t queue_var_show(unsigned long var, char *page) { return sprintf(page, "%lu\n", var); } static ssize_t queue_var_store(unsigned long *var, const char *page, size_t count) { char *p = (char *) page; *var = simple_strtoul(p, &p, 10); return count; } static ssize_t queue_requests_show(struct request_queue *q, char *page) { return queue_var_show(q->nr_requests, (page)); } static ssize_t queue_requests_store(struct request_queue *q, const char *page, size_t count) { struct request_list *rl = &q->rq; unsigned long nr; int ret; if (!q->request_fn) return -EINVAL; ret = queue_var_store(&nr, page, count); if (nr < BLKDEV_MIN_RQ) nr = BLKDEV_MIN_RQ; spin_lock_irq(q->queue_lock); q->nr_requests = nr; blk_queue_congestion_threshold(q); if (rl->count[BLK_RW_SYNC] >= queue_congestion_on_threshold(q)) blk_set_queue_congested(q, BLK_RW_SYNC); else if (rl->count[BLK_RW_SYNC] < queue_congestion_off_threshold(q)) blk_clear_queue_congested(q, BLK_RW_SYNC); if (rl->count[BLK_RW_ASYNC] >= queue_congestion_on_threshold(q)) blk_set_queue_congested(q, BLK_RW_ASYNC); else if (rl->count[BLK_RW_ASYNC] < queue_congestion_off_threshold(q)) blk_clear_queue_congested(q, BLK_RW_ASYNC); if (rl->count[BLK_RW_SYNC] >= q->nr_requests) { blk_set_queue_full(q, BLK_RW_SYNC); } else { blk_clear_queue_full(q, BLK_RW_SYNC); wake_up(&rl->wait[BLK_RW_SYNC]); } if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) { blk_set_queue_full(q, BLK_RW_ASYNC); } else { blk_clear_queue_full(q, BLK_RW_ASYNC); wake_up(&rl->wait[BLK_RW_ASYNC]); } spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_ra_show(struct request_queue *q, char *page) { unsigned long ra_kb = q->backing_dev_info.ra_pages << (PAGE_CACHE_SHIFT - 10); return queue_var_show(ra_kb, (page)); } static ssize_t queue_ra_store(struct request_queue *q, const char *page, size_t count) { unsigned long ra_kb; ssize_t ret = queue_var_store(&ra_kb, page, count); q->backing_dev_info.ra_pages = ra_kb >> (PAGE_CACHE_SHIFT - 10); return ret; } static ssize_t queue_max_sectors_show(struct request_queue *q, char *page) { int max_sectors_kb = queue_max_sectors(q) >> 1; return queue_var_show(max_sectors_kb, (page)); } static ssize_t queue_max_segments_show(struct request_queue *q, char *page) { return queue_var_show(queue_max_segments(q), (page)); } static ssize_t queue_max_integrity_segments_show(struct request_queue *q, char *page) { return queue_var_show(q->limits.max_integrity_segments, (page)); } static ssize_t queue_max_segment_size_show(struct request_queue *q, char *page) { if (blk_queue_cluster(q)) return queue_var_show(queue_max_segment_size(q), (page)); return queue_var_show(PAGE_CACHE_SIZE, (page)); } static ssize_t queue_logical_block_size_show(struct request_queue *q, char *page) { return queue_var_show(queue_logical_block_size(q), page); } static ssize_t queue_physical_block_size_show(struct request_queue *q, char *page) { return queue_var_show(queue_physical_block_size(q), page); } static ssize_t queue_io_min_show(struct request_queue *q, char *page) { return queue_var_show(queue_io_min(q), page); } static ssize_t queue_io_opt_show(struct request_queue *q, char *page) { return queue_var_show(queue_io_opt(q), page); } static ssize_t queue_discard_granularity_show(struct request_queue *q, char *page) { return queue_var_show(q->limits.discard_granularity, page); } static ssize_t queue_discard_max_show(struct request_queue *q, char *page) { return sprintf(page, "%llu\n", (unsigned long long)q->limits.max_discard_sectors << 9); } static ssize_t queue_discard_zeroes_data_show(struct request_queue *q, char *page) { return queue_var_show(queue_discard_zeroes_data(q), page); } static ssize_t queue_max_sectors_store(struct request_queue *q, const char *page, size_t count) { unsigned long max_sectors_kb, max_hw_sectors_kb = queue_max_hw_sectors(q) >> 1, page_kb = 1 << (PAGE_CACHE_SHIFT - 10); ssize_t ret = queue_var_store(&max_sectors_kb, page, count); if (max_sectors_kb > max_hw_sectors_kb || max_sectors_kb < page_kb) return -EINVAL; spin_lock_irq(q->queue_lock); q->limits.max_sectors = max_sectors_kb << 1; spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_max_hw_sectors_show(struct request_queue *q, char *page) { int max_hw_sectors_kb = queue_max_hw_sectors(q) >> 1; return queue_var_show(max_hw_sectors_kb, (page)); } #define QUEUE_SYSFS_BIT_FNS(name, flag, neg) \ static ssize_t \ queue_show_##name(struct request_queue *q, char *page) \ { \ int bit; \ bit = test_bit(QUEUE_FLAG_##flag, &q->queue_flags); \ return queue_var_show(neg ? !bit : bit, page); \ } \ static ssize_t \ queue_store_##name(struct request_queue *q, const char *page, size_t count) \ { \ unsigned long val; \ ssize_t ret; \ ret = queue_var_store(&val, page, count); \ if (neg) \ val = !val; \ \ spin_lock_irq(q->queue_lock); \ if (val) \ queue_flag_set(QUEUE_FLAG_##flag, q); \ else \ queue_flag_clear(QUEUE_FLAG_##flag, q); \ spin_unlock_irq(q->queue_lock); \ return ret; \ } QUEUE_SYSFS_BIT_FNS(nonrot, NONROT, 1); QUEUE_SYSFS_BIT_FNS(random, ADD_RANDOM, 0); QUEUE_SYSFS_BIT_FNS(iostats, IO_STAT, 0); #undef QUEUE_SYSFS_BIT_FNS static ssize_t queue_nomerges_show(struct request_queue *q, char *page) { return queue_var_show((blk_queue_nomerges(q) << 1) | blk_queue_noxmerges(q), page); } static ssize_t queue_nomerges_store(struct request_queue *q, const char *page, size_t count) { unsigned long nm; ssize_t ret = queue_var_store(&nm, page, count); spin_lock_irq(q->queue_lock); queue_flag_clear(QUEUE_FLAG_NOMERGES, q); queue_flag_clear(QUEUE_FLAG_NOXMERGES, q); if (nm == 2) queue_flag_set(QUEUE_FLAG_NOMERGES, q); else if (nm) queue_flag_set(QUEUE_FLAG_NOXMERGES, q); spin_unlock_irq(q->queue_lock); return ret; } static ssize_t queue_rq_affinity_show(struct request_queue *q, char *page) { bool set = test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags); bool force = test_bit(QUEUE_FLAG_SAME_FORCE, &q->queue_flags); return queue_var_show(set << force, page); } static ssize_t queue_rq_affinity_store(struct request_queue *q, const char *page, size_t count) { ssize_t ret = -EINVAL; #if defined(CONFIG_USE_GENERIC_SMP_HELPERS) unsigned long val; ret = queue_var_store(&val, page, count); spin_lock_irq(q->queue_lock); if (val == 2) { queue_flag_set(QUEUE_FLAG_SAME_COMP, q); queue_flag_set(QUEUE_FLAG_SAME_FORCE, q); } else if (val == 1) { queue_flag_set(QUEUE_FLAG_SAME_COMP, q); queue_flag_clear(QUEUE_FLAG_SAME_FORCE, q); } else if (val == 0) { queue_flag_clear(QUEUE_FLAG_SAME_COMP, q); queue_flag_clear(QUEUE_FLAG_SAME_FORCE, q); } spin_unlock_irq(q->queue_lock); #endif return ret; } static struct queue_sysfs_entry queue_requests_entry = { .attr = {.name = "nr_requests", .mode = S_IRUGO | S_IWUSR }, .show = queue_requests_show, .store = queue_requests_store, }; static struct queue_sysfs_entry queue_ra_entry = { .attr = {.name = "read_ahead_kb", .mode = S_IRUGO | S_IWUSR }, .show = queue_ra_show, .store = queue_ra_store, }; static struct queue_sysfs_entry queue_max_sectors_entry = { .attr = {.name = "max_sectors_kb", .mode = S_IRUGO | S_IWUSR }, .show = queue_max_sectors_show, .store = queue_max_sectors_store, }; static struct queue_sysfs_entry queue_max_hw_sectors_entry = { .attr = {.name = "max_hw_sectors_kb", .mode = S_IRUGO }, .show = queue_max_hw_sectors_show, }; static struct queue_sysfs_entry queue_max_segments_entry = { .attr = {.name = "max_segments", .mode = S_IRUGO }, .show = queue_max_segments_show, }; static struct queue_sysfs_entry queue_max_integrity_segments_entry = { .attr = {.name = "max_integrity_segments", .mode = S_IRUGO }, .show = queue_max_integrity_segments_show, }; static struct queue_sysfs_entry queue_max_segment_size_entry = { .attr = {.name = "max_segment_size", .mode = S_IRUGO }, .show = queue_max_segment_size_show, }; static struct queue_sysfs_entry queue_iosched_entry = { .attr = {.name = "scheduler", .mode = S_IRUGO | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH }, .show = elv_iosched_show, .store = elv_iosched_store, }; static struct queue_sysfs_entry queue_hw_sector_size_entry = { .attr = {.name = "hw_sector_size", .mode = S_IRUGO }, .show = queue_logical_block_size_show, }; static struct queue_sysfs_entry queue_logical_block_size_entry = { .attr = {.name = "logical_block_size", .mode = S_IRUGO }, .show = queue_logical_block_size_show, }; static struct queue_sysfs_entry queue_physical_block_size_entry = { .attr = {.name = "physical_block_size", .mode = S_IRUGO }, .show = queue_physical_block_size_show, }; static struct queue_sysfs_entry queue_io_min_entry = { .attr = {.name = "minimum_io_size", .mode = S_IRUGO }, .show = queue_io_min_show, }; static struct queue_sysfs_entry queue_io_opt_entry = { .attr = {.name = "optimal_io_size", .mode = S_IRUGO }, .show = queue_io_opt_show, }; static struct queue_sysfs_entry queue_discard_granularity_entry = { .attr = {.name = "discard_granularity", .mode = S_IRUGO }, .show = queue_discard_granularity_show, }; static struct queue_sysfs_entry queue_discard_max_entry = { .attr = {.name = "discard_max_bytes", .mode = S_IRUGO }, .show = queue_discard_max_show, }; static struct queue_sysfs_entry queue_discard_zeroes_data_entry = { .attr = {.name = "discard_zeroes_data", .mode = S_IRUGO }, .show = queue_discard_zeroes_data_show, }; static struct queue_sysfs_entry queue_nonrot_entry = { .attr = {.name = "rotational", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_nonrot, .store = queue_store_nonrot, }; static struct queue_sysfs_entry queue_nomerges_entry = { .attr = {.name = "nomerges", .mode = S_IRUGO | S_IWUSR }, .show = queue_nomerges_show, .store = queue_nomerges_store, }; static struct queue_sysfs_entry queue_rq_affinity_entry = { .attr = {.name = "rq_affinity", .mode = S_IRUGO | S_IWUSR }, .show = queue_rq_affinity_show, .store = queue_rq_affinity_store, }; static struct queue_sysfs_entry queue_iostats_entry = { .attr = {.name = "iostats", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_iostats, .store = queue_store_iostats, }; static struct queue_sysfs_entry queue_random_entry = { .attr = {.name = "add_random", .mode = S_IRUGO | S_IWUSR }, .show = queue_show_random, .store = queue_store_random, }; static struct attribute *default_attrs[] = { &queue_requests_entry.attr, &queue_ra_entry.attr, &queue_max_hw_sectors_entry.attr, &queue_max_sectors_entry.attr, &queue_max_segments_entry.attr, &queue_max_integrity_segments_entry.attr, &queue_max_segment_size_entry.attr, &queue_iosched_entry.attr, &queue_hw_sector_size_entry.attr, &queue_logical_block_size_entry.attr, &queue_physical_block_size_entry.attr, &queue_io_min_entry.attr, &queue_io_opt_entry.attr, &queue_discard_granularity_entry.attr, &queue_discard_max_entry.attr, &queue_discard_zeroes_data_entry.attr, &queue_nonrot_entry.attr, &queue_nomerges_entry.attr, &queue_rq_affinity_entry.attr, &queue_iostats_entry.attr, &queue_random_entry.attr, NULL, }; #define to_queue(atr) container_of((atr), struct queue_sysfs_entry, attr) static ssize_t queue_attr_show(struct kobject *kobj, struct attribute *attr, char *page) { struct queue_sysfs_entry *entry = to_queue(attr); struct request_queue *q = container_of(kobj, struct request_queue, kobj); ssize_t res; if (!entry->show) return -EIO; mutex_lock(&q->sysfs_lock); if (blk_queue_dead(q)) { mutex_unlock(&q->sysfs_lock); return -ENOENT; } res = entry->show(q, page); mutex_unlock(&q->sysfs_lock); return res; } static ssize_t queue_attr_store(struct kobject *kobj, struct attribute *attr, const char *page, size_t length) { struct queue_sysfs_entry *entry = to_queue(attr); struct request_queue *q; ssize_t res; if (!entry->store) return -EIO; q = container_of(kobj, struct request_queue, kobj); mutex_lock(&q->sysfs_lock); if (blk_queue_dead(q)) { mutex_unlock(&q->sysfs_lock); return -ENOENT; } res = entry->store(q, page, length); mutex_unlock(&q->sysfs_lock); return res; } /** * blk_release_queue: - release a &struct request_queue when it is no longer needed * @kobj: the kobj belonging to the request queue to be released * * Description: * blk_release_queue is the pair to blk_init_queue() or * blk_queue_make_request(). It should be called when a request queue is * being released; typically when a block device is being de-registered. * Currently, its primary task it to free all the &struct request * structures that were allocated to the queue and the queue itself. * * Caveat: * Hopefully the low level driver will have finished any * outstanding requests first... **/ static void blk_release_queue(struct kobject *kobj) { struct request_queue *q = container_of(kobj, struct request_queue, kobj); struct request_list *rl = &q->rq; blk_sync_queue(q); if (q->elevator) { spin_lock_irq(q->queue_lock); ioc_clear_queue(q); spin_unlock_irq(q->queue_lock); elevator_exit(q->elevator); } blk_throtl_exit(q); if (rl->rq_pool) mempool_destroy(rl->rq_pool); if (q->queue_tags) __blk_queue_free_tags(q); blk_throtl_release(q); blk_trace_shutdown(q); bdi_destroy(&q->backing_dev_info); ida_simple_remove(&blk_queue_ida, q->id); kmem_cache_free(blk_requestq_cachep, q); } static const struct sysfs_ops queue_sysfs_ops = { .show = queue_attr_show, .store = queue_attr_store, }; struct kobj_type blk_queue_ktype = { .sysfs_ops = &queue_sysfs_ops, .default_attrs = default_attrs, .release = blk_release_queue, }; int blk_register_queue(struct gendisk *disk) { int ret; struct device *dev = disk_to_dev(disk); struct request_queue *q = disk->queue; if (WARN_ON(!q)) return -ENXIO; ret = blk_trace_init_sysfs(dev); if (ret) return ret; ret = kobject_add(&q->kobj, kobject_get(&dev->kobj), "%s", "queue"); if (ret < 0) { blk_trace_remove_sysfs(dev); return ret; } kobject_uevent(&q->kobj, KOBJ_ADD); if (!q->request_fn) return 0; ret = elv_register_queue(q); if (ret) { kobject_uevent(&q->kobj, KOBJ_REMOVE); kobject_del(&q->kobj); blk_trace_remove_sysfs(dev); kobject_put(&dev->kobj); return ret; } return 0; } void blk_unregister_queue(struct gendisk *disk) { struct request_queue *q = disk->queue; if (WARN_ON(!q)) return; if (q->request_fn) elv_unregister_queue(q); kobject_uevent(&q->kobj, KOBJ_REMOVE); kobject_del(&q->kobj); blk_trace_remove_sysfs(disk_to_dev(disk)); kobject_put(&disk_to_dev(disk)->kobj); }
vinay94185vinay/Hybrid
block/blk-sysfs.c
C
gpl-2.0
15,179
/* * Copyright 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ #include <linux/module.h> static __init int opl_init(void) { return 0; } static void __exit opl_exit(void) { } module_init(opl_init); module_exit(opl_exit); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_DESCRIPTION("OPL Software Rotation/Mirroring"); MODULE_LICENSE("GPL");
WXrock/imx53_kernel
drivers/media/video/mxc/opl/opl_mod.c
C
gpl-2.0
664
/* * lp5521.c - LP5521 LED Driver * * Copyright (C) 2007 Nokia Corporation * * Written by Mathias Nyman <mathias.nyman@nokia.com> * Updated by Felipe Balbi <felipe.balbi@nokia.com> * * 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 */ #include <linux/module.h> #include <linux/init.h> #include <linux/i2c.h> #include <linux/leds.h> #include <linux/mutex.h> #include <linux/workqueue.h> #include <linux/i2c/lp5521.h> #define LP5521_DRIVER_NAME "lp5521" #define LP5521_REG_R_PWM 0x02 #define LP5521_REG_B_PWM 0x04 #define LP5521_REG_ENABLE 0x00 #define LP5521_REG_OP_MODE 0x01 #define LP5521_REG_G_PWM 0x03 #define LP5521_REG_R_CNTRL 0x05 #define LP5521_REG_G_CNTRL 0x06 #define LP5521_REG_B_CNTRL 0x07 #define LP5521_REG_MISC 0x08 #define LP5521_REG_R_CHANNEL_PC 0x09 #define LP5521_REG_G_CHANNEL_PC 0x0a #define LP5521_REG_B_CHANNEL_PC 0x0b #define LP5521_REG_STATUS 0x0c #define LP5521_REG_RESET 0x0d #define LP5521_REG_GPO 0x0e #define LP5521_REG_R_PROG_MEM 0x10 #define LP5521_REG_G_PROG_MEM 0x30 #define LP5521_REG_B_PROG_MEM 0x50 #define LP5521_CURRENT_1m5 0x0f #define LP5521_CURRENT_3m1 0x1f #define LP5521_CURRENT_4m7 0x2f #define LP5521_CURRENT_6m3 0x3f #define LP5521_CURRENT_7m9 0x4f #define LP5521_CURRENT_9m5 0x5f #define LP5521_CURRENT_11m1 0x6f #define LP5521_CURRENT_12m7 0x7f #define LP5521_CURRENT_14m3 0x8f #define LP5521_CURRENT_15m9 0x9f #define LP5521_CURRENT_17m5 0xaf #define LP5521_CURRENT_19m1 0xbf #define LP5521_CURRENT_20m7 0xcf #define LP5521_CURRENT_22m3 0xdf #define LP5521_CURRENT_23m9 0xef #define LP5521_CURRENT_25m5 0xff #define LP5521_PROGRAM_LENGTH 32 /* in bytes */ struct lp5521_chip { /* device lock */ struct mutex lock; struct i2c_client *client; struct work_struct red_work; struct work_struct green_work; struct work_struct blue_work; struct led_classdev ledr; struct led_classdev ledg; struct led_classdev ledb; enum lp5521_mode mode; int red; int green; int blue; }; static int lp5521_set_mode(struct lp5521_chip *chip, enum lp5521_mode mode); static inline int lp5521_write(struct i2c_client *client, u8 reg, u8 value) { return i2c_smbus_write_byte_data(client, reg, value); } static inline int lp5521_read(struct i2c_client *client, u8 reg) { return i2c_smbus_read_byte_data(client, reg); } static int lp5521_configure(struct i2c_client *client) { int ret = 0; /* Enable chip and set light to logarithmic mode*/ ret |= lp5521_write(client, LP5521_REG_ENABLE, 0xc0); /* setting all color pwms to direct control mode */ ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x3f); /* setting current to 4.7 mA for all channels */ ret |= lp5521_write(client, LP5521_REG_R_CNTRL, LP5521_CURRENT_4m7); ret |= lp5521_write(client, LP5521_REG_G_CNTRL, LP5521_CURRENT_4m7); ret |= lp5521_write(client, LP5521_REG_B_CNTRL, LP5521_CURRENT_4m7); /* Enable auto-powersave, set charge pump to auto, red to battery */ ret |= lp5521_write(client, LP5521_REG_MISC, 0x3c); /* initialize all channels pwm to zero */ ret |= lp5521_write(client, LP5521_REG_R_PWM, 0); ret |= lp5521_write(client, LP5521_REG_G_PWM, 0); ret |= lp5521_write(client, LP5521_REG_B_PWM, 0); /* Not much can be done about errors at this point */ return ret; } static int lp5521_load_program(struct lp5521_chip *chip, u8 *pattern) { struct i2c_client *client = chip->client; int ret = 0; /* Enter load program mode for all led channels */ ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x15); /* 0001 0101 */ if (ret) return ret; if (chip->red) ret |= i2c_smbus_write_i2c_block_data(client, LP5521_REG_R_PROG_MEM, LP5521_PROGRAM_LENGTH, pattern); if (chip->green) ret |= i2c_smbus_write_i2c_block_data(client, LP5521_REG_G_PROG_MEM, LP5521_PROGRAM_LENGTH, pattern); if (chip->blue) ret |= i2c_smbus_write_i2c_block_data(client, LP5521_REG_B_PROG_MEM, LP5521_PROGRAM_LENGTH, pattern); return ret; } static int lp5521_run_program(struct lp5521_chip *chip) { struct i2c_client *client = chip->client; int reg; u8 mask = 0xc0; u8 exec_state = 0; reg = lp5521_read(client, LP5521_REG_ENABLE); if (reg < 0) return reg; reg &= mask; /* set all active channels exec state to countinous run*/ exec_state |= (chip->red << 5); exec_state |= (chip->green << 3); exec_state |= (chip->blue << 1); reg |= exec_state; if (lp5521_write(client, LP5521_REG_ENABLE, reg)) dev_dbg(&client->dev, "failed writing to register %02x\n", LP5521_REG_ENABLE); /* set op-mode to run for active channels, disabled for others */ if (lp5521_write(client, LP5521_REG_OP_MODE, exec_state)) dev_dbg(&client->dev, "failed writing to register %02x\n", LP5521_REG_OP_MODE); return 0; } /*--------------------------------------------------------------*/ /* Sysfs interface */ /*--------------------------------------------------------------*/ static ssize_t show_active_channels(struct device *dev, struct device_attribute *attr, char *buf) { struct lp5521_chip *chip = dev_get_drvdata(dev); char channels[4]; int pos = 0; if (chip->red) pos += sprintf(channels + pos, "r"); if (chip->green) pos += sprintf(channels + pos, "g"); if (chip->blue) pos += sprintf(channels + pos, "b"); channels[pos] = '\0'; return sprintf(buf, "%s\n", channels); } static ssize_t store_active_channels(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lp5521_chip *chip = dev_get_drvdata(dev); chip->red = 0; chip->green = 0; chip->blue = 0; if (strchr(buf, 'r') != NULL) chip->red = 1; if (strchr(buf, 'b') != NULL) chip->blue = 1; if (strchr(buf, 'g') != NULL) chip->green = 1; return len; } static ssize_t show_color(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); int r, g, b; r = lp5521_read(client, LP5521_REG_R_PWM); g = lp5521_read(client, LP5521_REG_G_PWM); b = lp5521_read(client, LP5521_REG_B_PWM); if (r < 0 || g < 0 || b < 0) return -EINVAL; return sprintf(buf, "%.2x:%.2x:%.2x\n", r, g, b); } static ssize_t store_color(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct i2c_client *client = to_i2c_client(dev); struct lp5521_chip *chip = i2c_get_clientdata(client); int ret; unsigned r, g, b; ret = sscanf(buf, "%2x:%2x:%2x", &r, &g, &b); if (ret != 3) return -EINVAL; mutex_lock(&chip->lock); ret = lp5521_write(client, LP5521_REG_R_PWM, (u8)r); ret = lp5521_write(client, LP5521_REG_G_PWM, (u8)g); ret = lp5521_write(client, LP5521_REG_B_PWM, (u8)b); mutex_unlock(&chip->lock); return len; } static ssize_t store_load(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lp5521_chip *chip = dev_get_drvdata(dev); int ret, nrchars, offset = 0, i = 0; char c[3]; unsigned cmd; u8 pattern[LP5521_PROGRAM_LENGTH] = {0}; while ((offset < len - 1) && (i < LP5521_PROGRAM_LENGTH)) { /* separate sscanfs because length is working only for %s */ ret = sscanf(buf + offset, "%2s%n ", c, &nrchars); ret = sscanf(c, "%2x", &cmd); if (ret != 1) goto fail; pattern[i] = (u8)cmd; offset += nrchars; i++; } /* pattern commands are always two bytes long */ if (i % 2) goto fail; mutex_lock(&chip->lock); ret = lp5521_load_program(chip, pattern); mutex_unlock(&chip->lock); if (ret) { dev_err(dev, "lp5521 failed loading pattern\n"); return ret; } return len; fail: dev_err(dev, "lp5521 wrong pattern format\n"); return -EINVAL; } static ssize_t show_mode(struct device *dev, struct device_attribute *attr, char *buf) { struct lp5521_chip *chip = dev_get_drvdata(dev); char *mode; mutex_lock(&chip->lock); switch (chip->mode) { case LP5521_MODE_RUN: mode = "run"; break; case LP5521_MODE_LOAD: mode = "load"; break; case LP5521_MODE_DIRECT_CONTROL: mode = "direct"; break; default: mode = "undefined"; } mutex_unlock(&chip->lock); return sprintf(buf, "%s\n", mode); } static ssize_t store_mode(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lp5521_chip *chip = dev_get_drvdata(dev); mutex_lock(&chip->lock); if (sysfs_streq(buf, "run")) lp5521_set_mode(chip, LP5521_MODE_RUN); else if (sysfs_streq(buf, "load")) lp5521_set_mode(chip, LP5521_MODE_LOAD); else if (sysfs_streq(buf, "direct")) lp5521_set_mode(chip, LP5521_MODE_DIRECT_CONTROL); else len = -EINVAL; mutex_unlock(&chip->lock); return len; } static ssize_t show_current(struct device *dev, struct device_attribute *attr, char *buf) { struct i2c_client *client = to_i2c_client(dev); int r, g, b; r = lp5521_read(client, LP5521_REG_R_CNTRL); g = lp5521_read(client, LP5521_REG_G_CNTRL); b = lp5521_read(client, LP5521_REG_B_CNTRL); if (r < 0 || g < 0 || b < 0) return -EINVAL; r >>= 4; g >>= 4; b >>= 4; return sprintf(buf, "%x %x %x\n", r, g, b); } static ssize_t store_current(struct device *dev, struct device_attribute *attr, const char *buf, size_t len) { struct lp5521_chip *chip = dev_get_drvdata(dev); struct i2c_client *client = chip->client; int ret; unsigned curr; ret = sscanf(buf, "%1x", &curr); if (ret != 1) return -EINVAL; /* current level is determined by the 4 upper bits, rest is ones */ curr = (curr << 4) | 0x0f; mutex_lock(&chip->lock); ret |= lp5521_write(client, LP5521_REG_R_CNTRL, (u8)curr); ret |= lp5521_write(client, LP5521_REG_G_CNTRL, (u8)curr); ret |= lp5521_write(client, LP5521_REG_B_CNTRL, (u8)curr); mutex_unlock(&chip->lock); return len; } static DEVICE_ATTR(color, S_IRUGO | S_IWUGO, show_color, store_color); static DEVICE_ATTR(load, S_IWUGO, NULL, store_load); static DEVICE_ATTR(mode, S_IRUGO | S_IWUGO, show_mode, store_mode); static DEVICE_ATTR(active_channels, S_IRUGO | S_IWUGO, show_active_channels, store_active_channels); static DEVICE_ATTR(led_current, S_IRUGO | S_IWUGO, show_current, store_current); static int lp5521_register_sysfs(struct i2c_client *client) { struct device *dev = &client->dev; int ret; ret = device_create_file(dev, &dev_attr_color); if (ret) goto fail1; ret = device_create_file(dev, &dev_attr_load); if (ret) goto fail2; ret = device_create_file(dev, &dev_attr_active_channels); if (ret) goto fail3; ret = device_create_file(dev, &dev_attr_mode); if (ret) goto fail4; ret = device_create_file(dev, &dev_attr_led_current); if (ret) goto fail5; return 0; fail5: device_remove_file(dev, &dev_attr_mode); fail4: device_remove_file(dev, &dev_attr_active_channels); fail3: device_remove_file(dev, &dev_attr_load); fail2: device_remove_file(dev, &dev_attr_color); fail1: return ret; } static void lp5521_unregister_sysfs(struct i2c_client *client) { struct device *dev = &client->dev; device_remove_file(dev, &dev_attr_led_current); device_remove_file(dev, &dev_attr_mode); device_remove_file(dev, &dev_attr_active_channels); device_remove_file(dev, &dev_attr_color); device_remove_file(dev, &dev_attr_load); } /*--------------------------------------------------------------*/ /* Set chip operating mode */ /*--------------------------------------------------------------*/ static int lp5521_set_mode(struct lp5521_chip *chip, enum lp5521_mode mode) { struct i2c_client *client = chip->client ; int ret = 0; /* if in that mode already do nothing, except for run */ if (chip->mode == mode && mode != LP5521_MODE_RUN) return 0; switch (mode) { case LP5521_MODE_RUN: ret = lp5521_run_program(chip); break; case LP5521_MODE_LOAD: ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x15); break; case LP5521_MODE_DIRECT_CONTROL: ret |= lp5521_write(client, LP5521_REG_OP_MODE, 0x3F); break; default: dev_dbg(&client->dev, "unsupported mode %d\n", mode); } chip->mode = mode; return ret; } static void lp5521_red_work(struct work_struct *work) { struct lp5521_chip *chip = container_of(work, struct lp5521_chip, red_work); int ret; ret = lp5521_configure(chip->client); if (ret) { dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n", ret); return; } ret = lp5521_write(chip->client, LP5521_REG_R_PWM, chip->red); if (ret) dev_dbg(&chip->client->dev, "could not set brightness, %d\n", ret); } static void lp5521_red_set(struct led_classdev *led, enum led_brightness value) { struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledr); chip->red = value; schedule_work(&chip->red_work); } static void lp5521_green_work(struct work_struct *work) { struct lp5521_chip *chip = container_of(work, struct lp5521_chip, green_work); int ret; ret = lp5521_configure(chip->client); if (ret) { dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n", ret); return; } ret = lp5521_write(chip->client, LP5521_REG_G_PWM, chip->green); if (ret) dev_dbg(&chip->client->dev, "could not set brightness, %d\n", ret); } static void lp5521_green_set(struct led_classdev *led, enum led_brightness value) { struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledg); chip->green = value; schedule_work(&chip->green_work); } static void lp5521_blue_work(struct work_struct *work) { struct lp5521_chip *chip = container_of(work, struct lp5521_chip, blue_work); int ret; ret = lp5521_configure(chip->client); if (ret) { dev_dbg(&chip->client->dev, "could not configure lp5521, %d\n", ret); return; } ret = lp5521_write(chip->client, LP5521_REG_B_PWM, chip->blue); if (ret) dev_dbg(&chip->client->dev, "could not set brightness, %d\n", ret); } static void lp5521_blue_set(struct led_classdev *led, enum led_brightness value) { struct lp5521_chip *chip = container_of(led, struct lp5521_chip, ledb); chip->blue = value; schedule_work(&chip->blue_work); } /*--------------------------------------------------------------*/ /* Probe, Attach, Remove */ /*--------------------------------------------------------------*/ static int __init lp5521_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct lp5521_platform_data *pdata = client->dev.platform_data; struct lp5521_chip *chip; char name[16]; int ret = 0; if (!pdata) { dev_err(&client->dev, "platform_data is missing\n"); return -EINVAL; } chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; chip->client = client; strncpy(client->name, LP5521_DRIVER_NAME, I2C_NAME_SIZE); i2c_set_clientdata(client, chip); mutex_init(&chip->lock); INIT_WORK(&chip->red_work, lp5521_red_work); INIT_WORK(&chip->green_work, lp5521_green_work); INIT_WORK(&chip->blue_work, lp5521_blue_work); ret = lp5521_configure(client); if (ret < 0) { dev_err(&client->dev, "lp5521 error configuring chip \n"); goto fail1; } /* Set default values */ chip->mode = pdata->mode; chip->red = pdata->red_present; chip->green = pdata->green_present; chip->blue = pdata->blue_present; chip->ledr.brightness_set = lp5521_red_set; chip->ledr.default_trigger = NULL; snprintf(name, sizeof(name), "%s::red", pdata->label); chip->ledr.name = name; ret = led_classdev_register(&client->dev, &chip->ledr); if (ret < 0) { dev_dbg(&client->dev, "failed to register led %s, %d\n", chip->ledb.name, ret); goto fail1; } chip->ledg.brightness_set = lp5521_green_set; chip->ledg.default_trigger = NULL; snprintf(name, sizeof(name), "%s::green", pdata->label); chip->ledg.name = name; ret = led_classdev_register(&client->dev, &chip->ledg); if (ret < 0) { dev_dbg(&client->dev, "failed to register led %s, %d\n", chip->ledb.name, ret); goto fail2; } chip->ledb.brightness_set = lp5521_blue_set; chip->ledb.default_trigger = NULL; snprintf(name, sizeof(name), "%s::blue", pdata->label); chip->ledb.name = name; ret = led_classdev_register(&client->dev, &chip->ledb); if (ret < 0) { dev_dbg(&client->dev, "failed to register led %s, %d\n", chip->ledb.name, ret); goto fail3; } ret = lp5521_register_sysfs(client); if (ret) { dev_err(&client->dev, "lp5521 registering sysfs failed \n"); goto fail4; } return 0; fail4: led_classdev_unregister(&chip->ledb); fail3: led_classdev_unregister(&chip->ledg); fail2: led_classdev_unregister(&chip->ledr); fail1: i2c_set_clientdata(client, NULL); kfree(chip); return ret; } static int __exit lp5521_remove(struct i2c_client *client) { struct lp5521_chip *chip = i2c_get_clientdata(client); lp5521_unregister_sysfs(client); i2c_set_clientdata(client, NULL); led_classdev_unregister(&chip->ledb); led_classdev_unregister(&chip->ledg); led_classdev_unregister(&chip->ledr); kfree(chip); return 0; } static const struct i2c_device_id lp5521_id[] = { { LP5521_DRIVER_NAME, 0}, { }, }; MODULE_DEVICE_TABLE(i2c, lp5521_id); static struct i2c_driver lp5521_driver = { .driver = { .name = LP5521_DRIVER_NAME, }, .probe = lp5521_probe, .remove = __exit_p(lp5521_remove), .id_table = lp5521_id, }; static int __init lp5521_init(void) { return i2c_add_driver(&lp5521_driver); } module_init(lp5521_init); static void __exit lp5521_exit(void) { i2c_del_driver(&lp5521_driver); } module_exit(lp5521_exit); MODULE_AUTHOR("Mathias Nyman <mathias.nyman@nokia.com>"); MODULE_DESCRIPTION("lp5521 LED driver"); MODULE_LICENSE("GPL");
felixhaedicke/nst-kernel
src/drivers/leds/leds-lp5521.c
C
gpl-2.0
18,002
"""generated file, don't modify or your data will be lost""" try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: pass
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/logilab/__init__.py
Python
agpl-3.0
155
/* Copyright 2014 The Kubernetes 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. */ package volume import ( "fmt" "net" "strings" "sync" "github.com/golang/glog" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/resource" "k8s.io/kubernetes/pkg/api/unversioned" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset" "k8s.io/kubernetes/pkg/cloudprovider" "k8s.io/kubernetes/pkg/types" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/io" "k8s.io/kubernetes/pkg/util/mount" "k8s.io/kubernetes/pkg/util/validation" ) // VolumeOptions contains option information about a volume. type VolumeOptions struct { // The attributes below are required by volume.Provisioner // TODO: refactor all of this out of volumes when an admin can configure // many kinds of provisioners. // Capacity is the size of a volume. Capacity resource.Quantity // AccessModes of a volume AccessModes []api.PersistentVolumeAccessMode // Reclamation policy for a persistent volume PersistentVolumeReclaimPolicy api.PersistentVolumeReclaimPolicy // PV.Name of the appropriate PersistentVolume. Used to generate cloud // volume name. PVName string // PVC.Name of the PersistentVolumeClaim; only set during dynamic provisioning. PVCName string // Unique name of Kubernetes cluster. ClusterName string // Tags to attach to the real volume in the cloud provider - e.g. AWS EBS CloudTags *map[string]string // Volume provisioning parameters from StorageClass Parameters map[string]string // Volume selector from PersistentVolumeClaim Selector *unversioned.LabelSelector } // VolumePlugin is an interface to volume plugins that can be used on a // kubernetes node (e.g. by kubelet) to instantiate and manage volumes. type VolumePlugin interface { // Init initializes the plugin. This will be called exactly once // before any New* calls are made - implementations of plugins may // depend on this. Init(host VolumeHost) error // Name returns the plugin's name. Plugins should use namespaced names // such as "example.com/volume". The "kubernetes.io" namespace is // reserved for plugins which are bundled with kubernetes. GetPluginName() string // GetVolumeName returns the name/ID to uniquely identifying the actual // backing device, directory, path, etc. referenced by the specified volume // spec. // For Attachable volumes, this value must be able to be passed back to // volume Detach methods to identify the device to act on. // If the plugin does not support the given spec, this returns an error. GetVolumeName(spec *Spec) (string, error) // CanSupport tests whether the plugin supports a given volume // specification from the API. The spec pointer should be considered // const. CanSupport(spec *Spec) bool // RequiresRemount returns true if this plugin requires mount calls to be // reexecuted. Atomically updating volumes, like Downward API, depend on // this to update the contents of the volume. RequiresRemount() bool // NewMounter creates a new volume.Mounter from an API specification. // Ownership of the spec pointer in *not* transferred. // - spec: The api.Volume spec // - pod: The enclosing pod NewMounter(spec *Spec, podRef *api.Pod, opts VolumeOptions) (Mounter, error) // NewUnmounter creates a new volume.Unmounter from recoverable state. // - name: The volume name, as per the api.Volume spec. // - podUID: The UID of the enclosing pod NewUnmounter(name string, podUID types.UID) (Unmounter, error) // ConstructVolumeSpec constructs a volume spec based on the given volume name // and mountPath. The spec may have incomplete information due to limited // information from input. This function is used by volume manager to reconstruct // volume spec by reading the volume directories from disk ConstructVolumeSpec(volumeName, mountPath string) (*Spec, error) } // PersistentVolumePlugin is an extended interface of VolumePlugin and is used // by volumes that want to provide long term persistence of data type PersistentVolumePlugin interface { VolumePlugin // GetAccessModes describes the ways a given volume can be accessed/mounted. GetAccessModes() []api.PersistentVolumeAccessMode } // RecyclableVolumePlugin is an extended interface of VolumePlugin and is used // by persistent volumes that want to be recycled before being made available // again to new claims type RecyclableVolumePlugin interface { VolumePlugin // NewRecycler creates a new volume.Recycler which knows how to reclaim // this resource after the volume's release from a PersistentVolumeClaim NewRecycler(pvName string, spec *Spec) (Recycler, error) } // DeletableVolumePlugin is an extended interface of VolumePlugin and is used // by persistent volumes that want to be deleted from the cluster after their // release from a PersistentVolumeClaim. type DeletableVolumePlugin interface { VolumePlugin // NewDeleter creates a new volume.Deleter which knows how to delete this // resource in accordance with the underlying storage provider after the // volume's release from a claim NewDeleter(spec *Spec) (Deleter, error) } const ( // Name of a volume in external cloud that is being provisioned and thus // should be ignored by rest of Kubernetes. ProvisionedVolumeName = "placeholder-for-provisioning" ) // ProvisionableVolumePlugin is an extended interface of VolumePlugin and is // used to create volumes for the cluster. type ProvisionableVolumePlugin interface { VolumePlugin // NewProvisioner creates a new volume.Provisioner which knows how to // create PersistentVolumes in accordance with the plugin's underlying // storage provider NewProvisioner(options VolumeOptions) (Provisioner, error) } // AttachableVolumePlugin is an extended interface of VolumePlugin and is used for volumes that require attachment // to a node before mounting. type AttachableVolumePlugin interface { VolumePlugin NewAttacher() (Attacher, error) NewDetacher() (Detacher, error) GetDeviceMountRefs(deviceMountPath string) ([]string, error) } // VolumeHost is an interface that plugins can use to access the kubelet. type VolumeHost interface { // GetPluginDir returns the absolute path to a directory under which // a given plugin may store data. This directory might not actually // exist on disk yet. For plugin data that is per-pod, see // GetPodPluginDir(). GetPluginDir(pluginName string) string // GetPodVolumeDir returns the absolute path a directory which // represents the named volume under the named plugin for the given // pod. If the specified pod does not exist, the result of this call // might not exist. GetPodVolumeDir(podUID types.UID, pluginName string, volumeName string) string // GetPodPluginDir returns the absolute path to a directory under which // a given plugin may store data for a given pod. If the specified pod // does not exist, the result of this call might not exist. This // directory might not actually exist on disk yet. GetPodPluginDir(podUID types.UID, pluginName string) string // GetKubeClient returns a client interface GetKubeClient() clientset.Interface // NewWrapperMounter finds an appropriate plugin with which to handle // the provided spec. This is used to implement volume plugins which // "wrap" other plugins. For example, the "secret" volume is // implemented in terms of the "emptyDir" volume. NewWrapperMounter(volName string, spec Spec, pod *api.Pod, opts VolumeOptions) (Mounter, error) // NewWrapperUnmounter finds an appropriate plugin with which to handle // the provided spec. See comments on NewWrapperMounter for more // context. NewWrapperUnmounter(volName string, spec Spec, podUID types.UID) (Unmounter, error) // Get cloud provider from kubelet. GetCloudProvider() cloudprovider.Interface // Get mounter interface. GetMounter() mount.Interface // Get writer interface for writing data to disk. GetWriter() io.Writer // Returns the hostname of the host kubelet is running on GetHostName() string // Returns host IP or nil in the case of error. GetHostIP() (net.IP, error) // Returns the rootcontext to use when performing mounts for a volume. // This is a temporary measure in order to set the rootContext of tmpfs // mounts correctly. It will be replaced and expanded on by future // SecurityContext work. GetRootContext() string // Returns node allocatable GetNodeAllocatable() (api.ResourceList, error) } // VolumePluginMgr tracks registered plugins. type VolumePluginMgr struct { mutex sync.Mutex plugins map[string]VolumePlugin } // Spec is an internal representation of a volume. All API volume types translate to Spec. type Spec struct { Volume *api.Volume PersistentVolume *api.PersistentVolume ReadOnly bool } // Name returns the name of either Volume or PersistentVolume, one of which must not be nil. func (spec *Spec) Name() string { switch { case spec.Volume != nil: return spec.Volume.Name case spec.PersistentVolume != nil: return spec.PersistentVolume.Name default: return "" } } // VolumeConfig is how volume plugins receive configuration. An instance // specific to the plugin will be passed to the plugin's // ProbeVolumePlugins(config) func. Reasonable defaults will be provided by // the binary hosting the plugins while allowing override of those default // values. Those config values are then set to an instance of VolumeConfig // and passed to the plugin. // // Values in VolumeConfig are intended to be relevant to several plugins, but // not necessarily all plugins. The preference is to leverage strong typing // in this struct. All config items must have a descriptive but non-specific // name (i.e, RecyclerMinimumTimeout is OK but RecyclerMinimumTimeoutForNFS is // !OK). An instance of config will be given directly to the plugin, so // config names specific to plugins are unneeded and wrongly expose plugins in // this VolumeConfig struct. // // OtherAttributes is a map of string values intended for one-off // configuration of a plugin or config that is only relevant to a single // plugin. All values are passed by string and require interpretation by the // plugin. Passing config as strings is the least desirable option but can be // used for truly one-off configuration. The binary should still use strong // typing for this value when binding CLI values before they are passed as // strings in OtherAttributes. type VolumeConfig struct { // RecyclerPodTemplate is pod template that understands how to scrub clean // a persistent volume after its release. The template is used by plugins // which override specific properties of the pod in accordance with that // plugin. See NewPersistentVolumeRecyclerPodTemplate for the properties // that are expected to be overridden. RecyclerPodTemplate *api.Pod // RecyclerMinimumTimeout is the minimum amount of time in seconds for the // recycler pod's ActiveDeadlineSeconds attribute. Added to the minimum // timeout is the increment per Gi of capacity. RecyclerMinimumTimeout int // RecyclerTimeoutIncrement is the number of seconds added to the recycler // pod's ActiveDeadlineSeconds for each Gi of capacity in the persistent // volume. Example: 5Gi volume x 30s increment = 150s + 30s minimum = 180s // ActiveDeadlineSeconds for recycler pod RecyclerTimeoutIncrement int // PVName is name of the PersistentVolume instance that is being recycled. // It is used to generate unique recycler pod name. PVName string // OtherAttributes stores config as strings. These strings are opaque to // the system and only understood by the binary hosting the plugin and the // plugin itself. OtherAttributes map[string]string // ProvisioningEnabled configures whether provisioning of this plugin is // enabled or not. Currently used only in host_path plugin. ProvisioningEnabled bool } // NewSpecFromVolume creates an Spec from an api.Volume func NewSpecFromVolume(vs *api.Volume) *Spec { return &Spec{ Volume: vs, } } // NewSpecFromPersistentVolume creates an Spec from an api.PersistentVolume func NewSpecFromPersistentVolume(pv *api.PersistentVolume, readOnly bool) *Spec { return &Spec{ PersistentVolume: pv, ReadOnly: readOnly, } } // InitPlugins initializes each plugin. All plugins must have unique names. // This must be called exactly once before any New* methods are called on any // plugins. func (pm *VolumePluginMgr) InitPlugins(plugins []VolumePlugin, host VolumeHost) error { pm.mutex.Lock() defer pm.mutex.Unlock() if pm.plugins == nil { pm.plugins = map[string]VolumePlugin{} } allErrs := []error{} for _, plugin := range plugins { name := plugin.GetPluginName() if errs := validation.IsQualifiedName(name); len(errs) != 0 { allErrs = append(allErrs, fmt.Errorf("volume plugin has invalid name: %q: %s", name, strings.Join(errs, ";"))) continue } if _, found := pm.plugins[name]; found { allErrs = append(allErrs, fmt.Errorf("volume plugin %q was registered more than once", name)) continue } err := plugin.Init(host) if err != nil { glog.Errorf("Failed to load volume plugin %s, error: %s", plugin, err.Error()) allErrs = append(allErrs, err) continue } pm.plugins[name] = plugin glog.V(1).Infof("Loaded volume plugin %q", name) } return utilerrors.NewAggregate(allErrs) } // FindPluginBySpec looks for a plugin that can support a given volume // specification. If no plugins can support or more than one plugin can // support it, return error. func (pm *VolumePluginMgr) FindPluginBySpec(spec *Spec) (VolumePlugin, error) { pm.mutex.Lock() defer pm.mutex.Unlock() matches := []string{} for k, v := range pm.plugins { if v.CanSupport(spec) { matches = append(matches, k) } } if len(matches) == 0 { return nil, fmt.Errorf("no volume plugin matched") } if len(matches) > 1 { return nil, fmt.Errorf("multiple volume plugins matched: %s", strings.Join(matches, ",")) } return pm.plugins[matches[0]], nil } // FindPluginByName fetches a plugin by name or by legacy name. If no plugin // is found, returns error. func (pm *VolumePluginMgr) FindPluginByName(name string) (VolumePlugin, error) { pm.mutex.Lock() defer pm.mutex.Unlock() // Once we can get rid of legacy names we can reduce this to a map lookup. matches := []string{} for k, v := range pm.plugins { if v.GetPluginName() == name { matches = append(matches, k) } } if len(matches) == 0 { return nil, fmt.Errorf("no volume plugin matched") } if len(matches) > 1 { return nil, fmt.Errorf("multiple volume plugins matched: %s", strings.Join(matches, ",")) } return pm.plugins[matches[0]], nil } // FindPersistentPluginBySpec looks for a persistent volume plugin that can // support a given volume specification. If no plugin is found, return an // error func (pm *VolumePluginMgr) FindPersistentPluginBySpec(spec *Spec) (PersistentVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, fmt.Errorf("Could not find volume plugin for spec: %#v", spec) } if persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok { return persistentVolumePlugin, nil } return nil, fmt.Errorf("no persistent volume plugin matched") } // FindPersistentPluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindPersistentPluginByName(name string) (PersistentVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok { return persistentVolumePlugin, nil } return nil, fmt.Errorf("no persistent volume plugin matched") } // FindRecyclablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindRecyclablePluginBySpec(spec *Spec) (RecyclableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if recyclableVolumePlugin, ok := volumePlugin.(RecyclableVolumePlugin); ok { return recyclableVolumePlugin, nil } return nil, fmt.Errorf("no recyclable volume plugin matched") } // FindProvisionablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindProvisionablePluginByName(name string) (ProvisionableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok { return provisionableVolumePlugin, nil } return nil, fmt.Errorf("no provisionable volume plugin matched") } // FindDeletablePluginBySppec fetches a persistent volume plugin by spec. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindDeletablePluginBySpec(spec *Spec) (DeletableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok { return deletableVolumePlugin, nil } return nil, fmt.Errorf("no deletable volume plugin matched") } // FindDeletablePluginByName fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindDeletablePluginByName(name string) (DeletableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if deletableVolumePlugin, ok := volumePlugin.(DeletableVolumePlugin); ok { return deletableVolumePlugin, nil } return nil, fmt.Errorf("no deletable volume plugin matched") } // FindCreatablePluginBySpec fetches a persistent volume plugin by name. If // no plugin is found, returns error. func (pm *VolumePluginMgr) FindCreatablePluginBySpec(spec *Spec) (ProvisionableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if provisionableVolumePlugin, ok := volumePlugin.(ProvisionableVolumePlugin); ok { return provisionableVolumePlugin, nil } return nil, fmt.Errorf("no creatable volume plugin matched") } // FindAttachablePluginBySpec fetches a persistent volume plugin by name. // Unlike the other "FindPlugin" methods, this does not return error if no // plugin is found. All volumes require a mounter and unmounter, but not // every volume will have an attacher/detacher. func (pm *VolumePluginMgr) FindAttachablePluginBySpec(spec *Spec) (AttachableVolumePlugin, error) { volumePlugin, err := pm.FindPluginBySpec(spec) if err != nil { return nil, err } if attachableVolumePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok { return attachableVolumePlugin, nil } return nil, nil } // FindAttachablePluginByName fetches an attachable volume plugin by name. // Unlike the other "FindPlugin" methods, this does not return error if no // plugin is found. All volumes require a mounter and unmounter, but not // every volume will have an attacher/detacher. func (pm *VolumePluginMgr) FindAttachablePluginByName(name string) (AttachableVolumePlugin, error) { volumePlugin, err := pm.FindPluginByName(name) if err != nil { return nil, err } if attachablePlugin, ok := volumePlugin.(AttachableVolumePlugin); ok { return attachablePlugin, nil } return nil, nil } // NewPersistentVolumeRecyclerPodTemplate creates a template for a recycler // pod. By default, a recycler pod simply runs "rm -rf" on a volume and tests // for emptiness. Most attributes of the template will be correct for most // plugin implementations. The following attributes can be overridden per // plugin via configuration: // // 1. pod.Spec.Volumes[0].VolumeSource must be overridden. Recycler // implementations without a valid VolumeSource will fail. // 2. pod.GenerateName helps distinguish recycler pods by name. Recommended. // Default is "pv-recycler-". // 3. pod.Spec.ActiveDeadlineSeconds gives the recycler pod a maximum timeout // before failing. Recommended. Default is 60 seconds. // // See HostPath and NFS for working recycler examples func NewPersistentVolumeRecyclerPodTemplate() *api.Pod { timeout := int64(60) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ GenerateName: "pv-recycler-", Namespace: api.NamespaceDefault, }, Spec: api.PodSpec{ ActiveDeadlineSeconds: &timeout, RestartPolicy: api.RestartPolicyNever, Volumes: []api.Volume{ { Name: "vol", // IMPORTANT! All plugins using this template MUST // override pod.Spec.Volumes[0].VolumeSource Recycler // implementations without a valid VolumeSource will fail. VolumeSource: api.VolumeSource{}, }, }, Containers: []api.Container{ { Name: "pv-recycler", Image: "gcr.io/google_containers/busybox", Command: []string{"/bin/sh"}, Args: []string{"-c", "test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"}, VolumeMounts: []api.VolumeMount{ { Name: "vol", MountPath: "/scrub", }, }, }, }, }, } return pod }
jprukner/origin
vendor/k8s.io/kubernetes/pkg/volume/plugins.go
GO
apache-2.0
21,701
<html> <body> <span> This intention used to specify type for expression in docstring. </span> </body> </html>
asedunov/intellij-community
python/resources/intentionDescriptions/SpecifyTypeInDocstringIntention/description.html
HTML
apache-2.0
111
/* * 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.kafka.connect.runtime.standalone; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.connect.runtime.WorkerConfig; import java.util.Map; public class StandaloneConfig extends WorkerConfig { private static final ConfigDef CONFIG; /** * <code>offset.storage.file.filename</code> */ public static final String OFFSET_STORAGE_FILE_FILENAME_CONFIG = "offset.storage.file.filename"; private static final String OFFSET_STORAGE_FILE_FILENAME_DOC = "File to store offset data in"; static { CONFIG = baseConfigDef() .define(OFFSET_STORAGE_FILE_FILENAME_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, OFFSET_STORAGE_FILE_FILENAME_DOC); } public StandaloneConfig(Map<String, String> props) { super(CONFIG, props); } }
wangcy6/storm_app
frame/kafka-0.11.0/kafka-0.11.0.1-src/connect/runtime/src/main/java/org/apache/kafka/connect/runtime/standalone/StandaloneConfig.java
Java
apache-2.0
1,709
/** * Update: 15-5-11 * Editor: qihongye */ var fs = require('fs'); var path = require('path'); var fis = require('../lib/fis.js'); var _ = fis.file; var defaultSettings = (require('../lib/config.js')).DEFALUT_SETTINGS; var expect = require('chai').expect; var u = fis.util; var config = null; describe('config: config',function(){ beforeEach(function(){ fis.project.setProjectRoot(__dirname); fis.config.init(defaultSettings); process.env.NODE_ENV = 'dev'; }); it('set / get', function () { fis.set('namespace', 'common'); expect(fis.get('namespace')).to.equal('common'); fis.set('obj', {a:'a'}); fis.set('obj.b', 'b'); expect(fis.get('obj')).to.deep.equal({a:'a', b:'b'}); expect(fis.get('obj.c', {c: 'c'})).to.deep.equal({c:'c'}); expect(fis.get('obj.a')).to.equal('a'); expect(fis.get('obj.b')).to.equal('b'); }); it('media', function () { fis.set('a', 'a'); fis.set('b', 'b'); fis.media('prod').set('a', 'aa'); expect(fis.get('a')).to.equal('a'); expect(fis.media('prod').get('a')).to.equal('aa'); expect(fis.media('prod').get('b')).to.equal('b'); expect(fis.media('prod').get('project.charset')).to.equal('utf8'); }); it('fis.match',function(){ fis.match('**', { release: 'static/$&' }); // fis.config.match fis.match('**/js.js', { domain: 'www.baidu.com', useHash: false }, 1); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); //without domain // useDomain 已经去除,所以应该不收其影响了 fis.match('**/js.js', { useDomain: false }, 2); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js.js?__inline'); fis.match('**/js.js', { release: null }, 3); //without path path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with () fis.match('**/v1.0-(*)/(*).html', { release: '/$1/$2' }); path = __dirname+'/file/ext/v1.0-layout/test.html?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/layout/test.html?__inline'); fis.match('!**/js.js', { release: '/static/$&', useHash: true, domain: 'www.baidu.com' }); //with ! path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/file/ext/modular/js.js?__inline'); // with ! but not match path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('www.baidu.com/static/file/ext/modular/js_'+ f.getHash() +'.less?__inline'); }); it('match ${}', function() { fis.match('**/*.js', { release: null, useHash: false }) fis.set('coffee', 'js'); fis.match('**/js.js', { release: '/static/$&' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/j.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/file/ext/modular/j.js?__inline'); }); it('match 混合用法', function() { fis.set('ROOT', 'js'); fis.match('**', { useHash: false }); fis.match('(**/${ROOT}.js)', { release: '/static/js/$1' }); fis.match('(**/${ROOT}.less)', { release: '/static/js/$1' }); path = __dirname+'/file/ext/modular/js.js?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.js?__inline'); path = __dirname+'/file/ext/modular/js.less?__inline'; var f = _.wrap(path); var url = f.getUrl(); expect(url).to.equal('/static/js/file/ext/modular/js.less?__inline'); }); it('del', function(){ fis.config.del(); var origin = fis.config.get(); fis.set('a.b', 'b'); fis.media('pro').set('a.b', 'b'); fis.config.del('a.b'); expect(fis.get('a')).to.deep.equal({}); expect(fis.media('pro').get('a.b')).to.equal('b'); fis.config.del('a'); expect(fis.get()).to.deep.equal(origin); fis.media('pro').del('a'); expect(fis.media('pro').get()).to.deep.equal({}); }); it('getSortedMatches', function() { fis.media('prod').match('a', { name: '' }); var matches = fis.media('prod')._matches.concat(); var initIndex = matches[matches.length - 1].index; fis.match('b', { name: '' }, 1) fis.match('c', { name: '' }, 2) fis.media('prod').match('b', { name: 'prod' }, 1) fis.media('prod').match('c', { name: 'prod' }, 2); var result_gl = [ { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 } ], result_prod = [ { raw: 'a', reg: u.glob('a'), negate: false, properties: {name: ''}, media: 'prod', weight: 0, index: initIndex + 0 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 1, index: initIndex + 1 }, { raw: 'b', reg: u.glob('b'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 1, index: initIndex + 3 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: ''}, media: 'GLOBAL', weight: 2, index: initIndex + 2 }, { raw: 'c', reg: u.glob('c'), negate: false, properties: {name: 'prod'}, media: 'prod', weight: 2, index: initIndex + 4 }, ]; var xp = fis.config.getSortedMatches(); expect(xp).to.deep.equal(result_gl); var xp2 = fis.media('prod').getSortedMatches(); expect(xp2).to.deep.equal(result_prod); }); it("hook",function(){ fis.config.hook("module"); expect(fis.env().parent.data.modules.hook[1]['__plugin']).to.equal('module'); }); it("unhook",function(){ fis.config.unhook("module"); expect(fis.env().parent.data.modules.hook.length).to.equal(1); }); });
richard-chen-1985/fis3
test/config.js
JavaScript
bsd-2-clause
6,959
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_QUIC_QUIC_DATA_WRITER_H_ #define NET_QUIC_QUIC_DATA_WRITER_H_ #include <string> #include "base/basictypes.h" #include "base/logging.h" #include "base/port.h" #include "base/strings/string_piece.h" #include "net/base/int128.h" #include "net/base/net_export.h" #include "net/quic/quic_protocol.h" namespace net { // This class provides facilities for packing QUIC data. // // The QuicDataWriter supports appending primitive values (int, string, etc) // to a frame instance. The QuicDataWriter grows its internal memory buffer // dynamically to hold the sequence of primitive values. The internal memory // buffer is exposed as the "data" of the QuicDataWriter. class NET_EXPORT_PRIVATE QuicDataWriter { public: explicit QuicDataWriter(size_t length); ~QuicDataWriter(); // Returns the size of the QuicDataWriter's data. size_t length() const { return length_; } // Takes the buffer from the QuicDataWriter. char* take(); // Methods for adding to the payload. These values are appended to the end // of the QuicDataWriter payload. Note - binary integers are written in // host byte order (little endian) not network byte order (big endian). bool WriteUInt8(uint8 value); bool WriteUInt16(uint16 value); bool WriteUInt32(uint32 value); bool WriteUInt48(uint64 value); bool WriteUInt64(uint64 value); bool WriteUInt128(uint128 value); bool WriteStringPiece16(base::StringPiece val); bool WriteBytes(const void* data, size_t data_len); bool WriteRepeatedByte(uint8 byte, size_t count); // Fills the remaining buffer with null characters. void WritePadding(); // Methods for editing the payload at a specific offset, where the // offset must be within the writer's capacity. // Return true if there is enough space at that offset, false otherwise. bool WriteUInt8ToOffset(uint8 value, size_t offset); bool WriteUInt32ToOffset(uint32 value, size_t offset); bool WriteUInt48ToOffset(uint64 value, size_t offset); size_t capacity() const { return capacity_; } protected: const char* end_of_payload() const { return buffer_ + length_; } private: // Returns the location that the data should be written at, or NULL if there // is not enough room. Call EndWrite with the returned offset and the given // length to pad out for the next write. char* BeginWrite(size_t length); char* buffer_; size_t capacity_; // Allocation size of payload (or -1 if buffer is const). size_t length_; // Current length of the buffer. }; } // namespace net #endif // NET_QUIC_QUIC_DATA_WRITER_H_
aospx-kitkat/platform_external_chromium_org
net/quic/quic_data_writer.h
C
bsd-3-clause
2,749
/* Global Settings ------------------------------------------------------------------------------------------------------ */ h1, h2, h3, h4, h5 { font-weight: bold; } p, ol, ul, dl { margin: 0; } /* Headings ------------------------------------------------------------------------------------------------------ */ h1 { position: relative; z-index: 800; margin: 26px 0 10px; font-size: 16px; line-height: 20px; } .pretitle + h1 { margin-top: 0; } h2 { font-size: 16px; } h3 { font-size: 14px; } h4 { font-size: 12px; } h5 { font-size: 10px; } /* Links ------------------------------------------------------------------------------------------------------ */ a { text-decoration: none; outline: none; } a:link, a:visited { color: #309bbf; } a:hover, a:active { color: #444; } a.inverse:link, a.inverse:visited { color: #444 !important; } a.inverse:hover, a.inverse:active { color: #309bbf !important; } /* Images in Links ........................................... */ a img { border: none; outline: none; } a:link img.preview, a:visited img.preview { margin-top: 5px; padding: 5px; border: 1px solid #309bbf; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; background: #fff; } a:hover img.preview, a:active img.preview { border-color: #666; } /* Section ........................................... */ a.section:link, a.section:visited { color: #fff; } /* Pretitle ........................................... */ .pretitle { margin: -16px 0 0; } .pretitle a { font-size: 11px; line-height: 15px; font-weight: bold; } /* Iconic Links ------------------------------------------------------------------------------------------------------ */ a.addlink, a.changelink, a.deletelink, a.add-another, a.related-lookup, a.fb_show { background-repeat: no-repeat; background-color: transparent; } /* Hide Images in Templates ........................................... */ a.add-another img, a.related-lookup img { opacity: 0; } a.related-lookup img { display: none; } /* Add, Change, Delete, Add-Another ........................................... */ a.addlink, a.changelink, a.deletelink { position: relative; top: 0; margin: 0 0 -1px 10px; padding: 1px 0 0 14px; background-position: 0 50%; } a.addlink:link, a.addlink:visited { background-image: url('../img/icons/icon-addlink.png'); } a.addlink:hover, a.addlink:active { background-image: url('../img/icons/icon-addlink-hover.png'); } a.changelink:link, a.changelink:visited { background-image: url('../img/icons/icon-changelink.png'); } a.changelink:hover, a.changelink:active { background-image: url('../img/icons/icon-changelink-hover.png'); } a.deletelink { margin: 0; } a.add-another { position: relative; top: -2px; margin-left: 3px; vertical-align: top; font-size: 11px; line-height: 16px; background-position: 50% 50%; } a.add-another:link, a.add-another:visited { background-image: url('../img/icons/icon-add_another.png'); } a.add-another:hover, a.add-another:active { background-image: url('../img/icons/icon-add_another-hover.png'); } .change-list form table tbody td a.add-another, .change-list form table tbody th a.add-another { position: relative; top: -7px; } .radiolist.inline + a.add-another, .checkboxlist.inline + a.add-another { margin-left: -4px; } .vAutocompleteRawIdAdminField + a.add-another, .vM2MAutocompleteRawIdAdminField + a.add-another { /*margin-left: -8px;*/ } #changelist .result-list .vAutocompleteRawIdAdminField + a.add-another, #changelist .result-list .vM2MAutocompleteRawIdAdminField + a.add-another { /*margin-left: -9px;*/ } /* Related Lookup ........................................... */ a.related-lookup { background-position: 5px 5px; } a.related-lookup:link, a.related-lookup:visited { position: relative; top: 1px; padding: 6px 12px 5px; line-height: 0 !important; background-image: url('../img/icons/icon-related_lookup.png'); } a.related-lookup:hover, a.related-lookup:active { background-image: url('../img/icons/icon-related_lookup-hover.png'); } a.related-lookup + strong { position: relative; top: 1px; left: -6px; color: #555; font-size: 11px; font-weight: bold; } #changelist .result-list a.related-lookup { top: -1px; } /* Filebrowser ........................................... */ a.fb_show img { width: 0; height: 0; opacity: 0; } a.fb_show { background-position: 2px 3px; } a.fb_show:link, a.fb_show:visited { position: relative; padding: 7px 14px; line-height: 0 !important; border: none; background-image: url('../img/icons/icon-fb_show.png'); } a.fb_show:hover, a.fb_show:active { background-image: url('../img/icons/icon-fb_show-hover.png'); } /* Paragraphs ------------------------------------------------------------------------------------------------------ */ p { padding: 0; } h1 + p { margin: 0 0 15px; } .object-history p { padding: 5px 10px; } /* Listings ------------------------------------------------------------------------------------------------------ */ ul li { list-style-type: none; padding: 1px 0; } ul.plainlist { margin-left: 0; } ul.plainlist li { list-style-type: none; } #content ul { font-weight: bold; } #content p + ul, #content ul + ul { margin: 0 0 15px; } #content li ul { margin: 5px 0 0 15px; font-weight: normal; } dt { font-weight: bold; margin-top: 4px; } dd { margin-left: 0; } /* Blockquote, Pre, Code ------------------------------------------------------------------------------------------------------ */ blockquote { margin-left: 2px; padding-left: 4px; color: #777; font-size: 11px; border-left: 5px solid #ddd; } code, pre { color: #666; font-size: 11px; font-family: "Bitstream Vera Sans Mono", Monaco, "Courier New", Courier, monospace; background: inherit; } pre.literal-block { margin-top: 10px; padding: 6px 8px; background: #eee; } code strong { color: #930; } hr { clear: both; margin: 0; padding: 0; height: 1px; color: #eee; font-size: 1px; line-height: 1px; border: none; background-color: #eee; } /* Text Styles & Modifiers ------------------------------------------------------------------------------------------------------ */ .small { font-size: 11px; } .tiny { font-size: 10px; } p.tiny { margin-top: -2px; } .mini { font-size: 9px; } p.mini { margin-top: -3px; } .help, p.help { color: #999; font-size: 10px; } p img, h1 img, h2 img, h3 img, h4 img, td img { vertical-align: middle; } .quiet, a.quiet:link, a.quiet:visited { color: #999 !important; font-weight: normal !important; } .quiet strong { font-weight: bold !important; } .float-right { float: right; } .float-left { float: left; } .clear { clear: both; } .align-left { text-align: left; } .align-right { text-align: right; } .example { margin: 10px 0; padding: 5px 10px; background: #efefef; } .nowrap { white-space: nowrap; }
gladgod/zhiliao
zhiliao/grappellisafe/static/grappelli/css/typography.css
CSS
bsd-3-clause
7,065
(function() { var add, crispedges, feature, flexbox, fullscreen, gradients, logicalProps, prefix, readOnly, resolution, result, sort, writingMode, slice = [].slice; sort = function(array) { return array.sort(function(a, b) { var d; a = a.split(' '); b = b.split(' '); if (a[0] > b[0]) { return 1; } else if (a[0] < b[0]) { return -1; } else { d = parseFloat(a[1]) - parseFloat(b[1]); if (d > 0) { return 1; } else if (d < 0) { return -1; } else { return 0; } } }); }; feature = function(data, opts, callback) { var browser, match, need, ref, ref1, support, version, versions; if (!callback) { ref = [opts, {}], callback = ref[0], opts = ref[1]; } match = opts.match || /\sx($|\s)/; need = []; ref1 = data.stats; for (browser in ref1) { versions = ref1[browser]; for (version in versions) { support = versions[version]; if (support.match(match)) { need.push(browser + ' ' + version); } } } return callback(sort(need)); }; result = {}; prefix = function() { var data, i, j, k, len, name, names, results; names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++]; results = []; for (k = 0, len = names.length; k < len; k++) { name = names[k]; result[name] = {}; results.push((function() { var results1; results1 = []; for (i in data) { results1.push(result[name][i] = data[i]); } return results1; })()); } return results; }; add = function() { var data, j, k, len, name, names, results; names = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), data = arguments[j++]; results = []; for (k = 0, len = names.length; k < len; k++) { name = names[k]; results.push(result[name].browsers = sort(result[name].browsers.concat(data.browsers))); } return results; }; module.exports = result; feature(require('caniuse-db/features-json/border-radius'), function(browsers) { return prefix('border-radius', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius', { mistakes: ['-khtml-', '-ms-', '-o-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-boxshadow'), function(browsers) { return prefix('box-shadow', { mistakes: ['-khtml-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-animation'), function(browsers) { return prefix('animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', 'animation-iteration-count', 'animation-play-state', 'animation-timing-function', '@keyframes', { mistakes: ['-khtml-', '-ms-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-transitions'), function(browsers) { return prefix('transition', 'transition-property', 'transition-duration', 'transition-delay', 'transition-timing-function', { mistakes: ['-khtml-', '-ms-'], browsers: browsers }); }); feature(require('caniuse-db/features-json/transforms2d'), function(browsers) { return prefix('transform', 'transform-origin', { browsers: browsers }); }); feature(require('caniuse-db/features-json/transforms3d'), function(browsers) { prefix('perspective', 'perspective-origin', { browsers: browsers }); return prefix('transform-style', 'backface-visibility', { mistakes: ['-ms-', '-o-'], browsers: browsers }); }); gradients = require('caniuse-db/features-json/css-gradients'); feature(gradients, { match: /y\sx/ }, function(browsers) { return prefix('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], mistakes: ['-ms-'], browsers: browsers }); }); feature(gradients, { match: /a\sx/ }, function(browsers) { browsers = browsers.map(function(i) { if (/op/.test(i)) { return i; } else { return i + " old"; } }); return add('linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-boxsizing'), function(browsers) { return prefix('box-sizing', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-filters'), function(browsers) { return prefix('filter', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-filter-function'), function(browsers) { return prefix('filter-function', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-backdrop-filter'), function(browsers) { return prefix('backdrop-filter', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-element-function'), function(browsers) { return prefix('element', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); feature(require('caniuse-db/features-json/multicolumn'), function(browsers) { prefix('columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width', { browsers: browsers }); return prefix('column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside', { browsers: browsers }); }); feature(require('caniuse-db/features-json/user-select-none'), function(browsers) { return prefix('user-select', { mistakes: ['-khtml-'], browsers: browsers }); }); flexbox = require('caniuse-db/features-json/flexbox'); feature(flexbox, { match: /a\sx/ }, function(browsers) { browsers = browsers.map(function(i) { if (/ie|firefox/.test(i)) { return i; } else { return i + " 2009"; } }); prefix('display-flex', 'inline-flex', { props: ['display'], browsers: browsers }); prefix('flex', 'flex-grow', 'flex-shrink', 'flex-basis', { browsers: browsers }); return prefix('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', { browsers: browsers }); }); feature(flexbox, { match: /y\sx/ }, function(browsers) { add('display-flex', 'inline-flex', { browsers: browsers }); add('flex', 'flex-grow', 'flex-shrink', 'flex-basis', { browsers: browsers }); return add('flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content', { browsers: browsers }); }); feature(require('caniuse-db/features-json/calc'), function(browsers) { return prefix('calc', { props: ['*'], browsers: browsers }); }); feature(require('caniuse-db/features-json/background-img-opts'), function(browsers) { return prefix('background-clip', 'background-origin', 'background-size', { browsers: browsers }); }); feature(require('caniuse-db/features-json/font-feature'), function(browsers) { return prefix('font-feature-settings', 'font-variant-ligatures', 'font-language-override', 'font-kerning', { browsers: browsers }); }); feature(require('caniuse-db/features-json/border-image'), function(browsers) { return prefix('border-image', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-selection'), function(browsers) { return prefix('::selection', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css-placeholder'), function(browsers) { browsers = browsers.map(function(i) { var name, ref, version; ref = i.split(' '), name = ref[0], version = ref[1]; if (name === 'firefox' && parseFloat(version) <= 18) { return i + ' old'; } else { return i; } }); return prefix('::placeholder', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css-hyphens'), function(browsers) { return prefix('hyphens', { browsers: browsers }); }); fullscreen = require('caniuse-db/features-json/fullscreen'); feature(fullscreen, function(browsers) { return prefix(':fullscreen', { selector: true, browsers: browsers }); }); feature(fullscreen, { match: /x(\s#2|$)/ }, function(browsers) { return prefix('::backdrop', { selector: true, browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-tabsize'), function(browsers) { return prefix('tab-size', { browsers: browsers }); }); feature(require('caniuse-db/features-json/intrinsic-width'), function(browsers) { return prefix('max-content', 'min-content', 'fit-content', 'fill-available', { props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-cursors-newer'), function(browsers) { return prefix('zoom-in', 'zoom-out', { props: ['cursor'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css3-cursors-grab'), function(browsers) { return prefix('grab', 'grabbing', { props: ['cursor'], browsers: browsers }); }); feature(require('caniuse-db/features-json/css-sticky'), function(browsers) { return prefix('sticky', { props: ['position'], browsers: browsers }); }); feature(require('caniuse-db/features-json/pointer'), function(browsers) { return prefix('touch-action', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-decoration'), function(browsers) { return prefix('text-decoration-style', 'text-decoration-line', 'text-decoration-color', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-size-adjust'), function(browsers) { return prefix('text-size-adjust', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-masks'), function(browsers) { prefix('mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source', { browsers: browsers }); return prefix('clip-path', 'mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-boxdecorationbreak'), function(brwsrs) { return prefix('box-decoration-break', { browsers: brwsrs }); }); feature(require('caniuse-db/features-json/object-fit'), function(browsers) { return prefix('object-fit', 'object-position', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-shapes'), function(browsers) { return prefix('shape-margin', 'shape-outside', 'shape-image-threshold', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-overflow'), function(browsers) { return prefix('text-overflow', { browsers: browsers }); }); feature(require('caniuse-db/features-json/text-emphasis'), function(browsers) { return prefix('text-emphasis', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-deviceadaptation'), function(browsers) { return prefix('@viewport', { browsers: browsers }); }); resolution = require('caniuse-db/features-json/css-media-resolution'); feature(resolution, { match: /( x($| )|a #3)/ }, function(browsers) { return prefix('@resolution', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-text-align-last'), function(browsers) { return prefix('text-align-last', { browsers: browsers }); }); crispedges = require('caniuse-db/features-json/css-crisp-edges'); feature(crispedges, { match: /y x/ }, function(browsers) { return prefix('pixelated', { props: ['image-rendering'], browsers: browsers }); }); feature(crispedges, { match: /a x #2/ }, function(browsers) { return prefix('image-rendering', { browsers: browsers }); }); logicalProps = require('caniuse-db/features-json/css-logical-props'); feature(logicalProps, function(browsers) { return prefix('border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', { browsers: browsers }); }); feature(logicalProps, { match: /x\s#2/ }, function(browsers) { return prefix('border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-appearance'), function(browsers) { return prefix('appearance', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-snappoints'), function(browsers) { return prefix('scroll-snap-type', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scroll-snap-points-x', 'scroll-snap-points-y', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-regions'), function(browsers) { return prefix('flow-into', 'flow-from', 'region-fragment', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-image-set'), function(browsers) { return prefix('image-set', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); writingMode = require('caniuse-db/features-json/css-writing-mode'); feature(writingMode, { match: /a|x/ }, function(browsers) { return prefix('writing-mode', { browsers: browsers }); }); feature(require('caniuse-db/features-json/css-cross-fade.json'), function(browsers) { return prefix('cross-fade', { props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'], browsers: browsers }); }); readOnly = require('caniuse-db/features-json/css-read-only-write.json'); feature(readOnly, function(browsers) { return prefix(':read-only', ':read-write', { selector: true, browsers: browsers }); }); }).call(this);
yuyang545262477/AfterWork
webpack/LittleTwo/node_modules/autoprefixer/data/prefixes.js
JavaScript
mit
15,271
export interface IGridItem { name: string; } export class Tests { public items: KnockoutObservableArray<IGridItem>; public selectedItems: KnockoutObservableArray<IGridItem>; public gridOptionsAlarms: kg.GridOptions<IGridItem>; constructor() { this.items = ko.observableArray<IGridItem>(); this.selectedItems = ko.observableArray<IGridItem>(); this.gridOptionsAlarms = this.createDefaultGridOptions(this.items, this.selectedItems); } public createDefaultGridOptions<Type>(dataArray: KnockoutObservableArray<Type>, selectedItems: KnockoutObservableArray<Type>): kg.GridOptions<Type> { return { data: dataArray, displaySelectionCheckbox: false, footerVisible: false, multiSelect: false, showColumnMenu: false, plugins: null, selectedItems: selectedItems }; } }
markogresak/DefinitelyTyped
types/knockout.kogrid/knockout.kogrid-tests.ts
TypeScript
mit
917
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Serializer\Mapping; /** * Knows how to get the class discriminator mapping for classes and objects. * * @author Samuel Roze <samuel.roze@gmail.com> */ interface ClassDiscriminatorResolverInterface { /** * @param string $class * * @return ClassDiscriminatorMapping|null */ public function getMappingForClass(string $class): ?ClassDiscriminatorMapping; /** * @param object|string $object * * @return ClassDiscriminatorMapping|null */ public function getMappingForMappedObject($object): ?ClassDiscriminatorMapping; /** * @param object|string $object * * @return string|null */ public function getTypeForMappedObject($object): ?string; }
hacfi/symfony
src/Symfony/Component/Serializer/Mapping/ClassDiscriminatorResolverInterface.php
PHP
mit
991
/* * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * COPYRIGHT AND PERMISSION NOTICE * * Copyright (C) 1991-2007 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of the Unicode data files and any associated documentation (the "Data * Files") or Unicode software and any associated documentation (the * "Software") to deal in the Data Files or Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, and/or sell copies of the Data Files or Software, and * to permit persons to whom the Data Files or Software are furnished to do * so, provided that (a) the above copyright notice(s) and this permission * notice appear with all copies of the Data Files or Software, (b) both the * above copyright notice(s) and this permission notice appear in associated * documentation, and (c) there is clear notice in each modified Data File or * in the Software as well as in the documentation associated with the Data * File(s) or Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR * CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder shall not * be used in advertising or otherwise to promote the sale, use or other * dealings in these Data Files or Software without prior written * authorization of the copyright holder. */ package sun.text.resources.sr; import sun.util.resources.ParallelListResourceBundle; public class FormatData_sr_ME extends ParallelListResourceBundle { protected final Object[][] getContents() { return new Object[][] { }; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/sun/text/resources/sr/FormatData_sr_ME.java
Java
mit
3,546
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @summary Test SoftAudioSynthesizer getFormat method */ import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Patch; import javax.sound.sampled.*; import com.sun.media.sound.*; public class GetFormat { private static void assertEquals(Object a, Object b) throws Exception { if(!a.equals(b)) throw new RuntimeException("assertEquals fails!"); } private static void assertTrue(boolean value) throws Exception { if(!value) throw new RuntimeException("assertTrue fails!"); } public static void main(String[] args) throws Exception { AudioSynthesizer synth = new SoftSynthesizer(); AudioFormat defformat = synth.getFormat(); assertTrue(defformat != null); synth.openStream(null, null); assertTrue(synth.getFormat().toString().equals(defformat.toString())); synth.close(); AudioFormat custformat = new AudioFormat(8000, 16, 1, true, false); synth.openStream(custformat, null); assertTrue(synth.getFormat().toString().equals(custformat.toString())); synth.close(); } }
rokn/Count_Words_2015
testing/openjdk/jdk/test/javax/sound/midi/Gervill/SoftAudioSynthesizer/GetFormat.java
Java
mit
2,359
/* * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang; import java.io.DataInputStream; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.zip.InflaterInputStream; import java.security.AccessController; import java.security.PrivilegedAction; class CharacterName { private static SoftReference<byte[]> refStrPool; private static int[][] lookup; private static synchronized byte[] initNamePool() { byte[] strPool = null; if (refStrPool != null && (strPool = refStrPool.get()) != null) return strPool; DataInputStream dis = null; try { dis = new DataInputStream(new InflaterInputStream( AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run() { return getClass().getResourceAsStream("uniName.dat"); } }))); lookup = new int[(Character.MAX_CODE_POINT + 1) >> 8][]; int total = dis.readInt(); int cpEnd = dis.readInt(); byte ba[] = new byte[cpEnd]; dis.readFully(ba); int nameOff = 0; int cpOff = 0; int cp = 0; do { int len = ba[cpOff++] & 0xff; if (len == 0) { len = ba[cpOff++] & 0xff; // always big-endian cp = ((ba[cpOff++] & 0xff) << 16) | ((ba[cpOff++] & 0xff) << 8) | ((ba[cpOff++] & 0xff)); } else { cp++; } int hi = cp >> 8; if (lookup[hi] == null) { lookup[hi] = new int[0x100]; } lookup[hi][cp&0xff] = (nameOff << 8) | len; nameOff += len; } while (cpOff < cpEnd); strPool = new byte[total - cpEnd]; dis.readFully(strPool); refStrPool = new SoftReference<>(strPool); } catch (Exception x) { throw new InternalError(x.getMessage(), x); } finally { try { if (dis != null) dis.close(); } catch (Exception xx) {} } return strPool; } public static String get(int cp) { byte[] strPool = null; if (refStrPool == null || (strPool = refStrPool.get()) == null) strPool = initNamePool(); int off = 0; if (lookup[cp>>8] == null || (off = lookup[cp>>8][cp&0xff]) == 0) return null; @SuppressWarnings("deprecation") String result = new String(strPool, 0, off >>> 8, off & 0xff); // ASCII return result; } }
rokn/Count_Words_2015
testing/openjdk2/jdk/src/share/classes/java/lang/CharacterName.java
Java
mit
4,017
// Copyright 2016 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include "DolphinWX/Input/InputConfigDiag.h" class WiimoteInputConfigDialog final : public InputConfigDialog { public: WiimoteInputConfigDialog(wxWindow* parent, InputConfig& config, const wxString& name, int port_num = 0); };
degasus/dolphin
Source/Core/DolphinWX/Input/WiimoteInputConfigDiag.h
C
gpl-2.0
383