repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
dmlloyd/openjdk-modules
jaxws/src/jdk.xml.bind/share/classes/com/sun/tools/internal/xjc/reader/xmlschema/ct/ChoiceContentComplexTypeBuilder.java
3137
/* * Copyright (c) 1997, 2012, 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.tools.internal.xjc.reader.xmlschema.ct; import java.util.Collections; import static com.sun.tools.internal.xjc.reader.xmlschema.ct.ComplexTypeBindingMode.NORMAL; import com.sun.xml.internal.xsom.XSComplexType; import com.sun.xml.internal.xsom.XSModelGroup; import com.sun.xml.internal.xsom.XSParticle; /** * Binds a complex type whose immediate child is a choice * model group to a choice content interface. * * @author Kohsuke Kawaguchi */ final class ChoiceContentComplexTypeBuilder extends CTBuilder { public boolean isApplicable(XSComplexType ct) { if( !bgmBuilder.getGlobalBinding().isChoiceContentPropertyEnabled() ) return false; if( ct.getBaseType()!=schemas.getAnyType() ) // My reading of the spec is that if a complex type is // derived from another complex type by extension, // its top level model group is always a sequence // that combines the base type content model and // the extension defined in the new complex type. return false; XSParticle p = ct.getContentType().asParticle(); if(p==null) return false; XSModelGroup mg = getTopLevelModelGroup(p); if( mg.getCompositor()!=XSModelGroup.CHOICE ) return false; if( p.isRepeated() ) return false; return true; } private XSModelGroup getTopLevelModelGroup(XSParticle p) { XSModelGroup mg = p.getTerm().asModelGroup(); if( p.getTerm().isModelGroupDecl() ) mg = p.getTerm().asModelGroupDecl().getModelGroup(); return mg; } public void build(XSComplexType ct) { XSParticle p = ct.getContentType().asParticle(); builder.recordBindingMode(ct,NORMAL); bgmBuilder.getParticleBinder().build(p,Collections.singleton(p)); green.attContainer(ct); } }
gpl-2.0
PitonFoundation/Data-Engine
sites/all/libraries/leaflet/spec/suites/dom/DomEventSpec.js
2698
describe('DomEvent', function() { var el; function simulateClick(el) { if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); return el.dispatchEvent(e); } else if (el.fireEvent) { return el.fireEvent('onclick'); } } beforeEach(function() { el = document.createElement('div'); el.style.position = 'absolute'; el.style.top = el.style.left = '-10000px'; document.body.appendChild(el); }); afterEach(function() { document.body.removeChild(el); }); describe('#addListener', function() { it('should add a listener and call it on event', function() { var listener1 = jasmine.createSpy('listener1'), listener2 = jasmine.createSpy('listener2'); L.DomEvent.addListener(el, 'click', listener1); L.DomEvent.addListener(el, 'click', listener2); simulateClick(el); expect(listener1).toHaveBeenCalled(); expect(listener2).toHaveBeenCalled(); }); it('should have "this" keyword point to the given context', function() { var obj = {foo: 'bar'}, result; L.DomEvent.addListener(el, 'click', function() { result = this; }, obj); simulateClick(el); expect(result).toEqual(obj); }); it('should pass an event object to the listener', function() { var type; L.DomEvent.addListener(el, 'click', function(e) { type = e && e.type; }); simulateClick(el); expect(type).toEqual('click'); }); }); describe('#removeListener', function() { it('should remove prevously added listener', function() { var listener = jasmine.createSpy('listener'); L.DomEvent.addListener(el, 'click', listener); L.DomEvent.removeListener(el, 'click', listener); simulateClick(el); expect(listener).not.toHaveBeenCalled(); }); }); describe('#stopPropagation', function() { it('should stop propagation of the given event', function() { var child = document.createElement('div'), listener = jasmine.createSpy('listener'); el.appendChild(child); L.DomEvent.addListener(child, 'click', L.DomEvent.stopPropagation); L.DomEvent.addListener(el, 'click', listener); simulateClick(child); expect(listener).not.toHaveBeenCalled(); el.removeChild(child); }); }); describe('#preventDefault', function() { it('should prevent the default action of event', function() { L.DomEvent.addListener(el, 'click', L.DomEvent.preventDefault); expect(simulateClick(el)).toBe(false); }); }); });
gpl-2.0
msfuae/bscms-en
sites/all/modules/contrib/ultimate_cron/plugins/ultimate_cron/logger/database.class.php
14492
<?php /** * @file * Database logger for Ultimate Cron. */ define('ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED', 1); define('ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE', 2); define('ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN', 3); /** * Class for using database as log storage. */ class UltimateCronDatabaseLogger extends UltimateCronLogger { public $options = array(); public $log_entry_class = '\UltimateCronDatabaseLogEntry'; /** * Constructor. */ public function __construct($name, $plugin, $log_type = ULTIMATE_CRON_LOG_TYPE_NORMAL) { parent::__construct($name, $plugin, $log_type); $this->options['method'] = array( ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED => t('Disabled'), ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE => t('Remove logs older than a specified age'), ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN => t('Retain only a specific amount of log entries'), ); } /** * Default settings. */ public function defaultSettings() { return array( 'method' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN, 'expire' => 86400 * 14, 'retain' => 1000, ); } /** * Cleanup logs. */ public function cleanup() { $jobs = _ultimate_cron_job_load_all(); $current = 1; $max = 0; foreach ($jobs as $job) { if ($job->getPlugin($this->type)->name === $this->name) { $max++; } } foreach ($jobs as $job) { if ($job->getPlugin($this->type)->name === $this->name) { $this->cleanupJob($job); $class = _ultimate_cron_get_class('job'); if ($class::$currentJob) { $class::$currentJob->setProgress($current / $max); $current++; } } } } /** * Cleanup logs for a single job. */ public function cleanupJob($job) { $settings = $job->getSettings('logger'); switch ($settings['method']) { case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED: return; case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE: $expire = $settings['expire']; // Let's not delete more than ONE BILLION log entries :-o. $max = 10000000000; $chunk = 100; break; case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN: $expire = 0; $max = db_query("SELECT COUNT(lid) FROM {ultimate_cron_log} WHERE name = :name", array( ':name' => $job->name, ))->fetchField(); $max -= $settings['retain']; if ($max <= 0) { return; } $chunk = min($max, 100); break; default: watchdog('ultimate_cron', 'Invalid cleanup method: @method', array( '@method' => $settings['method'], )); return; } // Chunked delete. $count = 0; do { $lids = db_select('ultimate_cron_log', 'l') ->fields('l', array('lid')) ->condition('l.name', $job->name) ->condition('l.start_time', microtime(TRUE) - $expire, '<') ->range(0, $chunk) ->orderBy('l.start_time', 'ASC') ->orderBy('l.end_time', 'ASC') ->execute() ->fetchAll(PDO::FETCH_COLUMN); if ($lids) { $count += count($lids); $max -= count($lids); $chunk = min($max, 100); db_delete('ultimate_cron_log') ->condition('lid', $lids, 'IN') ->execute(); } } while ($lids && $max > 0); if ($count) { watchdog('database_logger', '@count log entries removed for job @name', array( '@count' => $count, '@name' => $job->name, ), WATCHDOG_INFO); } } /** * Label for setting. */ public function settingsLabel($name, $value) { switch ($name) { case 'method': return $this->options[$name][$value]; } return parent::settingsLabel($name, $value); } /** * Settings form. */ public function settingsForm(&$form, &$form_state, $job = NULL) { $elements = &$form['settings'][$this->type][$this->name]; $defaults = &$form_state['default_values']['settings'][$this->type][$this->name]; $values = &$form_state['values']['settings'][$this->type][$this->name]; $elements['method'] = array( '#type' => 'select', '#title' => t('Log entry cleanup method'), '#description' => t('Select which method to use for cleaning up logs.'), '#options' => $this->options['method'], '#default_value' => $values['method'], '#fallback' => TRUE, '#required' => TRUE, ); $states = array('expire' => array(), 'retain' => array()); if ($job) { $states['expire'] = array( '#states' => array( 'visible' => array( ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array( 'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE, ), ), 'enabled' => array( ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array( 'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE, ), ), ), ); $states['retain'] = array( '#states' => array( 'visible' => array( ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array( 'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN, ), ), 'enabled' => array( ':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]' => array( 'value' => ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN, ), ), ), ); } $elements['method_expire'] = array( '#type' => 'fieldset', '#title' => t('Remove logs older than a specified age'), ) + $states['expire']; $elements['method_expire']['expire'] = array( '#parents' => array('settings', $this->type, $this->name, 'expire'), '#type' => 'textfield', '#title' => t('Log entry expiration'), '#description' => t('Remove log entries older than X seconds.'), '#default_value' => $values['expire'], '#fallback' => TRUE, '#required' => TRUE, ) + $states['expire']; $elements['method_retain'] = array( '#type' => 'fieldset', '#title' => t('Retain only a specific amount of log entries'), ) + $states['retain']; $elements['method_retain']['retain'] = array( '#parents' => array('settings', $this->type, $this->name, 'retain'), '#type' => 'textfield', '#title' => t('Retain logs'), '#description' => t('Retain X amount of log entries; this value is per cron job. Setting this to 1000 on sites with 15 cron jobs will store a total of 15000 entries. High values can result in slower log performance.'), '#default_value' => $values['retain'], '#fallback' => TRUE, '#required' => TRUE, ) + $states['retain']; if ($job) { if ($defaults['method'] == ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE) { $elements['method_default'] = $elements['method_expire']; $elements['method_default']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['expire']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['expire']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; } if ($defaults['method'] == ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN) { $elements['method_default'] = $elements['method_retain']; $elements['method_default']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['retain']['#states']['visible'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; $elements['method_default']['retain']['#states']['enabled'][':input[name="settings[' . $this->type . '][' . $this->name . '][method]"]']['value'] = ''; } } } /** * Submit handler. */ public function settingsFormSubmit(&$form, &$form_state, $job = NULL) { $values = &$form_state['values']['settings'][$this->type][$this->name]; $defaults = &$form_state['default_values']['settings'][$this->type][$this->name]; if (!$job) { return; } $method = $values['method'] ? $values['method'] : $defaults['method']; // Cleanup form (can this be done elsewhere?) switch ($method) { case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_DISABLED: unset($values['expire']); unset($values['retain']); break; case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_EXPIRE: unset($values['retain']); break; case ULTIMATE_CRON_DATABASE_LOGGER_CLEANUP_METHOD_RETAIN: unset($values['expire']); break; } } /** * Load log entry. */ public function load($name, $lock_id = NULL, $log_types = array(ULTIMATE_CRON_LOG_TYPE_NORMAL)) { if ($lock_id) { $log_entry = db_select('ultimate_cron_log', 'l') ->fields('l') ->condition('l.lid', $lock_id) ->execute() ->fetchObject($this->log_entry_class, array($name, $this)); } else { $subquery = db_select('ultimate_cron_log', 'l3') ->fields('l3', array('name', 'log_type')) ->groupBy('name') ->groupBy('log_type'); $subquery->addExpression('MAX(l3.start_time)', 'start_time'); $query = db_select('ultimate_cron_log', 'l1') ->fields('l1'); $query->join($subquery, 'l2', 'l1.name = l2.name AND l1.start_time = l2.start_time AND l1.log_type = l2.log_type'); $query->condition('l2.name', $name); $query->condition('l2.log_type', $log_types, 'IN'); $log_entry = $query->execute()->fetchObject($this->log_entry_class, array($name, $this)); } if ($log_entry) { $log_entry->finished = TRUE; } else { $log_entry = new $this->log_entry_class($name, $this); } return $log_entry; } /** * Load latest log entry. */ public function loadLatestLogEntries($jobs, $log_types) { if (Database::getConnection()->databaseType() !== 'mysql') { return parent::loadLatestLogEntries($jobs, $log_types); } $subquery = db_select('ultimate_cron_log', 'l3') ->fields('l3', array('name', 'log_type')) ->groupBy('name') ->groupBy('log_type'); $subquery->addExpression('MAX(l3.start_time)', 'start_time'); $query = db_select('ultimate_cron_log', 'l1') ->fields('l1'); $query->join($subquery, 'l2', 'l1.name = l2.name AND l1.start_time = l2.start_time AND l1.log_type = l2.log_type'); $query->condition('l2.log_type', $log_types, 'IN'); $result = $query->execute(); $log_entries = array(); while ($object = $result->fetchObject()) { if (isset($jobs[$object->name])) { $log_entries[$object->name] = new $this->log_entry_class($object->name, $this); $log_entries[$object->name]->setData((array) $object); } } foreach ($jobs as $name => $job) { if (!isset($log_entries[$name])) { $log_entries[$name] = new $this->log_entry_class($name, $this); } } return $log_entries; } /** * Get log entries. */ public function getLogEntries($name, $log_types, $limit = 10) { $result = db_select('ultimate_cron_log', 'l') ->fields('l') ->extend('PagerDefault') ->condition('l.name', $name) ->condition('l.log_type', $log_types, 'IN') ->limit($limit) ->orderBy('l.start_time', 'DESC') ->execute(); $log_entries = array(); while ($object = $result->fetchObject($this->log_entry_class, array($name, $this))) { $log_entries[$object->lid] = $object; } return $log_entries; } } /** * Class for Ultimate Cron log entries. */ class UltimateCronDatabaseLogEntry extends UltimateCronLogEntry { /** * Save log entry. */ public function save() { if (!$this->lid) { return; } static $retry = 0; try { db_insert('ultimate_cron_log') ->fields(array( 'lid' => $this->lid, 'name' => $this->name, 'log_type' => $this->log_type, 'start_time' => $this->start_time, 'end_time' => $this->end_time, 'uid' => $this->uid, 'init_message' => $this->init_message, 'message' => $this->message, 'severity' => $this->severity, )) ->execute(); } catch (PDOException $e) { // Row already exists. Let's update it, if we can. $updated = db_update('ultimate_cron_log') ->fields(array( 'name' => $this->name, 'log_type' => $this->log_type, 'start_time' => $this->start_time, 'end_time' => $this->end_time, 'init_message' => $this->init_message, 'message' => $this->message, 'severity' => $this->severity, )) ->condition('lid', $this->lid) ->condition('end_time', 0) ->execute(); if (!$updated) { // Row was not updated, someone must have beaten us to it. // Let's create a new log entry. $lid = $this->lid . '-' . uniqid('', TRUE); $this->message = t('Lock #@original_lid was already closed and logged. Creating a new log entry #@lid', array( '@original_lid' => $this->lid, '@lid' => $lid, )) . "\n" . $this->message; $this->severity = $this->severity >= 0 && $this->severity < WATCHDOG_ERROR ? $this->severity : WATCHDOG_ERROR; $this->lid = $lid; $retry++; if ($retry > 3) { $retry = 0; watchdog('database_logger', (string) $e, array(), WATCHDOG_CRITICAL); return; } $this->save(); $retry--; } } } }
gpl-2.0
quantsini/cog
Frameworks/TagLib/taglib/taglib/mpeg/mpegproperties.cpp
7023
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tdebug.h> #include <tstring.h> #include "mpegproperties.h" #include "mpegfile.h" #include "xingheader.h" using namespace TagLib; class MPEG::Properties::PropertiesPrivate { public: PropertiesPrivate(File *f, ReadStyle s) : file(f), xingHeader(0), style(s), length(0), bitrate(0), sampleRate(0), channels(0), layer(0), version(Header::Version1), channelMode(Header::Stereo), protectionEnabled(false), isCopyrighted(false), isOriginal(false) {} ~PropertiesPrivate() { delete xingHeader; } File *file; XingHeader *xingHeader; ReadStyle style; int length; int bitrate; int sampleRate; int channels; int layer; Header::Version version; Header::ChannelMode channelMode; bool protectionEnabled; bool isCopyrighted; bool isOriginal; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// MPEG::Properties::Properties(File *file, ReadStyle style) : AudioProperties(style) { d = new PropertiesPrivate(file, style); if(file && file->isOpen()) read(); } MPEG::Properties::~Properties() { delete d; } int MPEG::Properties::length() const { return d->length; } int MPEG::Properties::bitrate() const { return d->bitrate; } int MPEG::Properties::sampleRate() const { return d->sampleRate; } int MPEG::Properties::channels() const { return d->channels; } const MPEG::XingHeader *MPEG::Properties::xingHeader() const { return d->xingHeader; } MPEG::Header::Version MPEG::Properties::version() const { return d->version; } int MPEG::Properties::layer() const { return d->layer; } bool MPEG::Properties::protectionEnabled() const { return d->protectionEnabled; } MPEG::Header::ChannelMode MPEG::Properties::channelMode() const { return d->channelMode; } bool MPEG::Properties::isCopyrighted() const { return d->isCopyrighted; } bool MPEG::Properties::isOriginal() const { return d->isOriginal; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// void MPEG::Properties::read() { // Since we've likely just looked for the ID3v1 tag, start at the end of the // file where we're least likely to have to have to move the disk head. long last = d->file->lastFrameOffset(); if(last < 0) { debug("MPEG::Properties::read() -- Could not find a valid last MPEG frame in the stream."); return; } d->file->seek(last); Header lastHeader(d->file->readBlock(4)); long first = d->file->firstFrameOffset(); if(first < 0) { debug("MPEG::Properties::read() -- Could not find a valid first MPEG frame in the stream."); return; } if(!lastHeader.isValid()) { long pos = last; while(pos > first) { pos = d->file->previousFrameOffset(pos); if(pos < 0) break; d->file->seek(pos); Header header(d->file->readBlock(4)); if(header.isValid()) { lastHeader = header; last = pos; break; } } } // Now jump back to the front of the file and read what we need from there. d->file->seek(first); Header firstHeader(d->file->readBlock(4)); if(!firstHeader.isValid() || !lastHeader.isValid()) { debug("MPEG::Properties::read() -- Page headers were invalid."); return; } // Check for a Xing header that will help us in gathering information about a // VBR stream. int xingHeaderOffset = MPEG::XingHeader::xingHeaderOffset(firstHeader.version(), firstHeader.channelMode()); d->file->seek(first + xingHeaderOffset); d->xingHeader = new XingHeader(d->file->readBlock(16)); // Read the length and the bitrate from the Xing header. if(d->xingHeader->isValid() && firstHeader.sampleRate() > 0 && d->xingHeader->totalFrames() > 0) { double timePerFrame = double(firstHeader.samplesPerFrame()) / firstHeader.sampleRate(); double length = timePerFrame * d->xingHeader->totalFrames(); d->length = int(length); d->bitrate = d->length > 0 ? d->xingHeader->totalSize() * 8 / length / 1000 : 0; } else { // Since there was no valid Xing header found, we hope that we're in a constant // bitrate file. delete d->xingHeader; d->xingHeader = 0; // TODO: Make this more robust with audio property detection for VBR without a // Xing header. if(firstHeader.frameLength() > 0 && firstHeader.bitrate() > 0) { int frames = (last - first) / firstHeader.frameLength() + 1; d->length = int(float(firstHeader.frameLength() * frames) / float(firstHeader.bitrate() * 125) + 0.5); d->bitrate = firstHeader.bitrate(); } } d->sampleRate = firstHeader.sampleRate(); d->channels = firstHeader.channelMode() == Header::SingleChannel ? 1 : 2; d->version = firstHeader.version(); d->layer = firstHeader.layer(); d->protectionEnabled = firstHeader.protectionEnabled(); d->channelMode = firstHeader.channelMode(); d->isCopyrighted = firstHeader.isCopyrighted(); d->isOriginal = firstHeader.isOriginal(); }
gpl-2.0
sgaluzin/pechki
administrator/components/com_jshopping/models/statictext.php
829
<?php /** * @version 4.6.0 26.06.2014 * @author MAXXmarketing GmbH * @package Jshopping * @copyright Copyright (C) 2010 webdesigner-profi.de. All rights reserved. * @license GNU/GPL */ defined('_JEXEC') or die('Restricted access'); jimport( 'joomla.application.component.model'); class JshoppingModelStaticText extends JModelLegacy{ function getList($use_for_return_policy = 0){ $lang = JSFactory::getLang(); $db = JFactory::getDBO(); $where = $use_for_return_policy?' WHERE use_for_return_policy=1 ':''; $query = "SELECT id, alias, use_for_return_policy FROM `#__jshopping_config_statictext` ".$where." ORDER BY id"; extract(js_add_trigger(get_defined_vars(), "before")); $db->setQuery($query); return $db->loadObjectList(); } } ?>
gpl-2.0
pspanja/ezpublish-kernel
eZ/Publish/API/Repository/Values/ContentType/ContentTypeDraft.php
455
<?php /** * File containing the eZ\Publish\API\Repository\Values\ContentType\ContentTypeDraft class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Publish\API\Repository\Values\ContentType; /** * This class represents a draft of a content type. */ abstract class ContentTypeDraft extends ContentType { }
gpl-2.0
numo16/wesnoth
src/hotkey_handler_sp.hpp
2303
/* Copyright (C) 2014 - 2015 by Chris Beck <render787@gmail.com> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ 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. See the COPYING file for more details. */ /** * @file * An extension of play_controller::hotkey_handler, which has support for * SP wesnoth features like whiteboard, end turn, etc. */ #ifndef HOTKEY_HANDLER_SP_HPP_INCL_ #define HOTKEY_HANDLER_SP_HPP_INCL_ #include "playsingle_controller.hpp" #include "hotkey_handler.hpp" #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> class playsingle_controller::hotkey_handler : public play_controller::hotkey_handler { protected: playsingle_controller & playsingle_controller_; boost::shared_ptr<wb::manager> whiteboard_manager_; bool is_observer() const; public: hotkey_handler(playsingle_controller &, saved_game &); ~hotkey_handler(); virtual void recruit(); virtual void repeat_recruit(); virtual void recall(); virtual bool can_execute_command(const hotkey::hotkey_command& command, int index=-1) const; virtual void toggle_shroud_updates(); virtual void update_shroud_now(); virtual void end_turn(); virtual void rename_unit(); virtual void create_unit(); virtual void change_side(); virtual void kill_unit(); virtual void label_terrain(bool); virtual void clear_labels(); virtual void continue_move(); virtual void unit_hold_position(); virtual void end_unit_turn(); virtual void user_command(); virtual void custom_command(); virtual void ai_formula(); virtual void clear_messages(); // Whiteboard hotkeys virtual void whiteboard_toggle(); virtual void whiteboard_execute_action(); virtual void whiteboard_execute_all_actions(); virtual void whiteboard_delete_action(); virtual void whiteboard_bump_up_action(); virtual void whiteboard_bump_down_action(); virtual void whiteboard_suppose_dead(); virtual hotkey::ACTION_STATE get_action_state(hotkey::HOTKEY_COMMAND command, int index) const; }; #endif
gpl-2.0
Sweetgrassbuffalo/ReactionSweeGrass-v2
imports/plugins/included/shipping-rates/server/hooks/hooks.js
2118
import { check } from "meteor/check"; import { Shipping, Packages } from "/lib/collections"; import { Logger, Reaction, Hooks } from "/server/api"; import { Cart as CartSchema } from "/lib/collections/schemas"; // callback ran on getShippingRates hook function getShippingRates(rates, cart) { check(cart, CartSchema); const shops = []; const products = cart.items; const pkgData = Packages.findOne({ name: "reaction-shipping-rates", shopId: Reaction.getShopId() }); if (!pkgData || !cart.items || pkgData.settings.flatRates.enabled !== true) { return rates; } // default selector is current shop let selector = { "shopId": Reaction.getShopId(), "provider.enabled": true }; // create an array of shops, allowing // the cart to have products from multiple shops for (const product of products) { if (product.shopId) { shops.push(product.shopId); } } // if we have multiple shops in cart if ((shops !== null ? shops.length : void 0) > 0) { selector = { "shopId": { $in: shops }, "provider.enabled": true }; } const shippingCollection = Shipping.find(selector); shippingCollection.forEach(function (doc) { const _results = []; for (const method of doc.methods) { if (!method.enabled) { continue; } if (!method.rate) { method.rate = 0; } if (!method.handling) { method.handling = 0; } // Store shipping provider here in order to have it available in shipmentMethod // for cart and order usage if (!method.carrier) { method.carrier = doc.provider.label; } const rate = method.rate + method.handling; _results.push( rates.push({ carrier: doc.provider.label, method: method, rate: rate, shopId: doc.shopId }) ); } return _results; }); Logger.debug("Flat rate onGetShippingRates", rates); return rates; } // run getShippingRates when the onGetShippingRates event runs Hooks.Events.add("onGetShippingRates", getShippingRates);
gpl-3.0
Git-Host/Android-IMSI-Catcher-Detector
app/src/main/java/com/SecUpwN/AIMSICD/enums/StatesDbViewer.java
1738
/* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project * ----------------------------------------------------------- * LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o * ----------------------------------------------------------- */ package com.SecUpwN.AIMSICD.enums; import android.content.Context; import com.SecUpwN.AIMSICD.R; import java.util.ArrayList; import java.util.Arrays; public enum StatesDbViewer { UNIQUE_BTS_DATA(R.string.unique_bts_data), BTS_MEASUREMENTS(R.string.bts_measurements), IMPORTED_OCID_DATA(R.string.imported_ocid_data), DEFAULT_MCC_LOCATIONS(R.string.default_mmc_locations), SILENT_SMS(R.string.silent_sms), MEASURED_SIGNAL_STRENGTHS(R.string.measured_signal_strengths), EVENT_LOG(R.string.eventlog), DETECTION_STRINGS(R.string.detection_strings); //TODO DetectionFlags // DETECTION_FLAGS(R.string.detection_flags) private final int mStatementValue; StatesDbViewer(int pStatementValue) { mStatementValue = pStatementValue; } public int getStatementValue() { return mStatementValue; } public static ArrayList<StatesDbViewer> getStates() { return new ArrayList<>(Arrays.asList(values())); } public static StatesDbViewer getValueByOrdinal(int pOrdinal) { StatesDbViewer lResult = null; for (StatesDbViewer item : values()) { if (item.ordinal() == pOrdinal) { lResult = item; break; } } return lResult; } public String getDisplayName(Context pContext) { if (pContext == null) { return null; } return pContext.getString(getStatementValue()); } }
gpl-3.0
berfinsari/metricbeat
membeat/vendor/github.com/elastic/beats/packetbeat/flows/flow.go
565
package flows import ( "sync/atomic" "time" ) type biFlow struct { id rawFlowID killed uint32 createTS time.Time ts time.Time dir flowDirection stats [2]*flowStats prev, next *biFlow } type Flow struct { stats *flowStats } func newBiFlow(id rawFlowID, ts time.Time, dir flowDirection) *biFlow { return &biFlow{ id: id, ts: ts, createTS: ts, dir: dir, } } func (f *biFlow) kill() { atomic.StoreUint32(&f.killed, 1) } func (f *biFlow) isAlive() bool { return atomic.LoadUint32(&f.killed) == 0 }
gpl-3.0
SlateScience/MozillaJS
js/src/jit-test/tests/jaeger/recompile/bug676764.js
191
try { with( {"a":1} ) { (function () { for (;;) { t } })() } } catch (e) {} with( {"b":2} ) { (function () { for (b = 0; b < 18; ++b) {} })(); }
mpl-2.0
gody01/SuiteCRM
modules/Emails/vardefs.php
26332
<?php /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } $dictionary['Email'] = array( 'table' => 'emails', 'acl_fields' => false, 'comment' => 'Contains a record of emails sent to and from the Sugar application', 'fields' => array( 'orphaned' => array( 'name' => 'orphaned', 'vname' => 'LBL_ORPHANED', 'type' => 'bool', 'required' => false, 'reportable' => false, 'comment' => 'Emails which exists in the SuiteCRM but have been deleted from the email server', 'inline_edit' => false, ), 'last_synced' => array( 'name' => 'last_synced', 'vname' => 'LBL_LAST_SYNCED', 'type' => 'datetime', 'comment' => 'The last date and time the email was synced with the server', 'inline_edit' => false, 'required' => false, 'reportable' => false, ), 'from_addr_name' => array( 'name' => 'from_addr_name', 'type' => 'varchar', 'source' => 'non-db', 'inline_edit' => false, ), 'reply_to_addr' => array( 'name' => 'reply_to_addr', 'type' => 'varchar', 'vname' => 'reply_to_addr', 'source' => 'non-db', 'inline_edit' => false, ), 'to_addrs_names' => array( 'name' => 'to_addrs_names', 'type' => 'varchar', 'vname' => 'to_addrs_names', 'source' => 'non-db', 'inline_edit' => false, ), 'cc_addrs_names' => array( 'name' => 'cc_addrs_names', 'type' => 'varchar', 'vname' => 'cc_addrs_names', 'source' => 'non-db', 'inline_edit' => false, ), 'bcc_addrs_names' => array( 'name' => 'bcc_addrs_names', 'type' => 'varchar', 'vname' => 'bcc_addrs_names', 'source' => 'non-db', 'inline_edit' => false, ), 'imap_keywords' => array( 'name' => 'imap_keywords', 'type' => 'varchar', 'vname' => 'LBL_IMAP_KEYWORDS', 'source' => 'non-db', 'inline_edit' => false, ), 'raw_source' => array( 'name' => 'raw_source', 'type' => 'varchar', 'vname' => 'raw_source', 'source' => 'non-db', 'inline_edit' => false, ), 'description_html' => array( 'name' => 'description_html', 'type' => 'emailbody', 'vname' => 'description_html', 'source' => 'non-db', 'inline_edit' => false, ), 'description' => array( 'name' => 'description', 'type' => 'text', 'vname' => 'description', 'source' => 'non-db', 'inline_edit' => false, ), 'date_sent_received' => array( 'name' => 'date_sent_received', 'vname' => 'LBL_DATE_SENT_RECEIVED', 'type' => 'datetime', 'inline_edit' => false, ), 'message_id' => array( 'name' => 'message_id', 'vname' => 'LBL_MESSAGE_ID', 'type' => 'varchar', 'len' => 255, 'comment' => 'ID of the email item obtained from the email transport system', 'inline_edit' => false, ), 'name' => array( 'name' => 'name', 'vname' => 'LBL_SUBJECT', 'type' => 'name', 'dbType' => 'varchar', 'required' => false, 'len' => '255', 'comment' => 'The subject of the email', 'inline_edit' => false, ), 'type' => array( 'name' => 'type', 'vname' => 'LBL_LIST_TYPE', 'type' => 'enum', 'options' => 'dom_email_types', 'len' => 100, 'massupdate' => false, 'comment' => 'Type of email (ex: draft)', 'inline_edit' => false, ), 'status' => array( 'name' => 'status', 'vname' => 'LBL_STATUS', 'type' => 'enum', 'len' => 100, 'options' => 'dom_email_status', 'inline_edit' => false, ), 'flagged' => array( 'name' => 'flagged', 'vname' => 'LBL_EMAIL_FLAGGED', 'type' => 'bool', 'required' => false, 'reportable' => false, 'comment' => 'flagged status', 'inline_edit' => false, ), 'reply_to_status' => array( 'name' => 'reply_to_status', 'vname' => 'LBL_EMAIL_REPLY_TO_STATUS', 'type' => 'bool', 'required' => false, 'reportable' => false, 'comment' => 'I you reply to an email then reply to status of original email is set', 'inline_edit' => false, ), 'intent' => array( 'name' => 'intent', 'vname' => 'LBL_INTENT', 'type' => 'varchar', 'len' => 100, 'default' => 'pick', 'comment' => 'Target of action used in Inbound Email assignment', 'inline_edit' => false, ), 'mailbox_id' => array( 'name' => 'mailbox_id', 'vname' => 'LBL_MAILBOX_ID', 'type' => 'id', 'len' => '36', 'reportable' => false, 'inline_edit' => false, ), 'created_by_link' => array( 'name' => 'created_by_link', 'type' => 'link', 'relationship' => 'emails_created_by', 'vname' => 'LBL_CREATED_BY_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', 'inline_edit' => false, ), 'modified_user_link' => array( 'name' => 'modified_user_link', 'type' => 'link', 'relationship' => 'emails_modified_user', 'vname' => 'LBL_MODIFIED_BY_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', 'inline_edit' => false, ), 'assigned_user_link' => array( 'name' => 'assigned_user_link', 'type' => 'link', 'relationship' => 'emails_assigned_user', 'vname' => 'LBL_ASSIGNED_TO_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', 'inline_edit' => false, ), 'parent_name' => array( 'name'=> 'parent_name', 'parent_type'=>'record_type_display' , 'type_name'=>'parent_type', 'id_name'=>'parent_id', 'vname'=>'LBL_EMAIL_RELATE', 'type'=>'parent', 'source'=>'non-db', 'options'=> 'record_type_display', 'inline_edit' => false, ), 'parent_type' => array( 'name' => 'parent_type', 'vname' => 'LBL_PARENT_TYPE', 'type' => 'varchar', 'reportable' => false, 'len' => 100, 'comment' => 'Identifier of Sugar module to which this email is associated (deprecated as of 4.2)', 'inline_edit' => false, ), 'parent_id' => array( 'name' => 'parent_id', 'vname' => 'LBL_PARENT_ID', 'type' => 'id', 'len' => '36', 'reportable' => false, 'comment' => 'ID of Sugar object referenced by parent_type (deprecated as of 4.2)', 'inline_edit' => false, ), 'indicator' => array( 'name' => 'indicator', 'vname' => 'LBL_INDICATOR', 'type' => 'function', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => 'visible', 'inline_edit' => false, 'function' => array( 'name' => 'displayIndicatorField', 'returns' => 'html', 'include' => 'modules/Emails/include/displayIndicatorField.php', 'onListView' => true ), ), 'subject' => array( 'name' => 'subject', 'vname' => 'LBL_SUBJECT', 'type' => 'function', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => 'visible', 'inline_edit' => false, 'function' => array( 'name' => 'displaySubjectField', 'returns' => 'html', 'include' => 'modules/Emails/include/displaySubjectField.php', 'onListView' => true ), ), 'attachment' => array( 'name' => 'attachment', 'vname' => 'LBL_ATTACHMENTS', 'type' => 'function', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => 'visible', 'inline_edit' => false, 'function' => array( 'name' => 'displayAttachmentField', 'returns' => 'html', 'include' => 'modules/Emails/include/displayAttachmentField.php', 'onListView' => true ), ), 'uid' => array( 'name' => 'uid', 'type' => 'varchar', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'msgno' => array( 'name' => 'msgno', 'type' => 'varchar', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'folder' => array( 'name' => 'folder', 'type' => 'varchar', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'folder_type' => array( 'name' => 'folder_type', 'type' => 'varchar', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'inbound_email_record' => array( 'name' => 'inbound_email_record', 'type' => 'varchar', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'is_imported' => array( 'name' => 'is_imported', 'type' => 'varchar', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, ), 'has_attachment' => array( 'name' => 'has_attachment', 'vname' => 'LBL_HAS_ATTACHMENT_INDICATOR', 'type' => 'function', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => 'visible', 'inline_edit' => false, 'function' => array( 'name' => 'displayHasAttachmentField', 'returns' => 'html', 'include' => 'modules/Emails/include/displayHasAttachmentField.php', 'onListView' => true ), ), 'is_only_plain_text' => array( 'name' => 'is_only_plain_text', 'type' => 'bool', 'default' => false, 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'inline_edit' => false, 'source' => 'non-db', ), /* relationship collection attributes */ /* added to support InboundEmail */ 'accounts' => array( 'name' => 'accounts', 'vname' => 'LBL_EMAILS_ACCOUNTS_REL', 'type' => 'link', 'relationship' => 'emails_accounts_rel', 'module' => 'Accounts', 'bean_name' => 'Account', 'source' => 'non-db', ), 'bugs' => array( 'name' => 'bugs', 'vname' => 'LBL_EMAILS_BUGS_REL', 'type' => 'link', 'relationship' => 'emails_bugs_rel', 'module' => 'Bugs', 'bean_name' => 'Bug', 'source' => 'non-db', ), 'cases' => array( 'name' => 'cases', 'vname' => 'LBL_EMAILS_CASES_REL', 'type' => 'link', 'relationship' => 'emails_cases_rel', 'module' => 'Cases', 'bean_name' => 'Case', 'source' => 'non-db', ), 'contacts' => array( 'name' => 'contacts', 'vname' => 'LBL_EMAILS_CONTACTS_REL', 'type' => 'link', 'relationship' => 'emails_contacts_rel', 'module' => 'Contacts', 'bean_name' => 'Contact', 'source' => 'non-db', ), 'leads' => array( 'name' => 'leads', 'vname' => 'LBL_EMAILS_LEADS_REL', 'type' => 'link', 'relationship' => 'emails_leads_rel', 'module' => 'Leads', 'bean_name' => 'Lead', 'source' => 'non-db', ), 'opportunities' => array( 'name' => 'opportunities', 'vname' => 'LBL_EMAILS_OPPORTUNITIES_REL', 'type' => 'link', 'relationship' => 'emails_opportunities_rel', 'module' => 'Opportunities', 'bean_name' => 'Opportunity', 'source' => 'non-db', ), 'project' => array( 'name' => 'project', 'vname' => 'LBL_EMAILS_PROJECT_REL', 'type' => 'link', 'relationship' => 'emails_projects_rel', 'module' => 'Project', 'bean_name' => 'Project', 'source' => 'non-db', ), 'projecttask' => array( 'name' => 'projecttask', 'vname' => 'LBL_EMAILS_PROJECT_TASK_REL', 'type' => 'link', 'relationship' => 'emails_project_task_rel', 'module' => 'ProjectTask', 'bean_name' => 'ProjectTask', 'source' => 'non-db', ), 'prospects' => array( 'name' => 'prospects', 'vname' => 'LBL_EMAILS_PROSPECT_REL', 'type' => 'link', 'relationship' => 'emails_prospects_rel', 'module' => 'Prospects', 'bean_name' => 'Prospect', 'source' => 'non-db', ), 'aos_contracts' => array( 'name' => 'aos_contracts', 'vname' => 'LBL_EMAILS_CONTRACTS_REL', 'type' => 'link', 'relationship' => 'emails_aos_contracts_rel', 'module' => 'AOS_Contracts', 'bean_name' => 'AOS_Contracts', 'source' => 'non-db', ), 'tasks' => array( 'name' => 'tasks', 'vname' => 'LBL_EMAILS_TASKS_REL', 'type' => 'link', 'relationship' => 'emails_tasks_rel', 'module' => 'Tasks', 'bean_name' => 'Task', 'source' => 'non-db', ), 'users' => array( 'name' => 'users', 'vname' => 'LBL_EMAILS_USERS_REL', 'type' => 'link', 'relationship' => 'emails_users_rel', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', ), 'notes' => array( 'name' => 'notes', 'vname' => 'LBL_EMAILS_NOTES_REL', 'type' => 'link', 'relationship' => 'emails_notes_rel', 'module' => 'Notes', 'bean_name' => 'Note', 'source' => 'non-db', ), // SNIP 'meetings' => array( 'name' => 'meetings', 'vname' => 'LBL_EMAILS_MEETINGS_REL', 'type' => 'link', 'relationship' => 'emails_meetings_rel', 'module' => 'Meetings', 'bean_name' => 'Meeting', 'source' => 'non-db', ), /* end relationship collections */ 'category_id' => array( 'name' => 'category_id', 'vname' => 'LBL_CATEGORY', 'type' => 'enum', 'len' => 100, 'options' => 'email_category_dom', 'reportable' => true, ), "emails_email_templates" => array( 'name' => 'emails_email_templates', 'type' => 'link', 'relationship' => 'emails_email_templates', 'source' => 'non-db', 'module' => 'EmailTemplates', 'bean_name' => 'EmailTemplate', 'vname' => 'LBL_EMAIL_TEMPLATE', 'id_name' => 'emails_email_templates_idb', ), "emails_email_templates_name" => array( 'name' => 'emails_email_templates_name', 'type' => 'relate', 'source' => 'non-db', 'vname' => 'LBL_EMAIL_TEMPLATE', 'save' => true, 'id_name' => 'emails_email_templates_idb', 'link' => 'emails_email_templates', 'table' => 'email_templates', 'module' => 'EmailTemplates', 'rname' => 'name', ), "emails_email_templates_idb" => array( 'name' => 'emails_email_templates_idb', 'type' => 'link', 'relationship' => 'emails_email_templates', 'source' => 'non-db', 'reportable' => false, 'side' => 'left', 'vname' => 'LBL_EMAIL_TEMPLATE', ), 'opt_in' => array( 'name' => 'opt_in', 'vname' => 'LBL_OPT_IN', 'type' => 'function', 'source' => 'non-db', 'massupdate' => 0, 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => 'visible', 'inline_edit' => false, 'function' => array( 'name' => 'displayEmailAddressOptInField', 'returns' => 'html', 'include' => 'modules/Emails/include/displayEmailAddressOptInField.php', 'onListView' => true ), ), ), /* end fields() array */ 'relationships' => array( 'emails_assigned_user' => array( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Emails', 'rhs_table' => 'emails', 'rhs_key' => 'assigned_user_id', 'relationship_type' => 'one-to-many', ), 'emails_modified_user' => array( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Emails', 'rhs_table' => 'emails', 'rhs_key' => 'modified_user_id', 'relationship_type' => 'one-to-many', ), 'emails_created_by' => array( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Emails', 'rhs_table' => 'emails', 'rhs_key' => 'created_by', 'relationship_type' => 'one-to-many', ), 'emails_notes_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'Notes', 'rhs_table' => 'notes', 'rhs_key' => 'parent_id', 'relationship_type' => 'one-to-many', ), 'emails_contacts_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'Contacts', 'rhs_table' => 'contacts', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'emails_beans', 'join_key_lhs' => 'email_id', 'join_key_rhs' => 'bean_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'Contacts', ), 'emails_accounts_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'Accounts', 'rhs_table' => 'accounts', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'emails_beans', 'join_key_lhs' => 'email_id', 'join_key_rhs' => 'bean_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'Accounts', ), 'emails_leads_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'Leads', 'rhs_table' => 'leads', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'emails_beans', 'join_key_lhs' => 'email_id', 'join_key_rhs' => 'bean_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'Leads', ), 'emails_aos_contracts_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'AOS_Contracts', 'rhs_table' => 'aos_contracts', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'emails_beans', 'join_key_lhs' => 'email_id', 'join_key_rhs' => 'bean_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'AOS_Contracts', ), // SNIP 'emails_meetings_rel' => array( 'lhs_module' => 'Emails', 'lhs_table' => 'emails', 'lhs_key' => 'id', 'rhs_module' => 'Meetings', 'rhs_table' => 'meetings', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'emails_beans', 'join_key_lhs' => 'email_id', 'join_key_rhs' => 'bean_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'Meetings', ), ), // end relationships 'indices' => array( array( 'name' => 'idx_email_name', 'type' => 'index', 'fields' => array('name'), ), array( 'name' => 'idx_message_id', 'type' => 'index', 'fields' => array('message_id'), ), array( 'name' => 'idx_email_parent_id', 'type' => 'index', 'fields' => array('parent_id'), ), array( 'name' => 'idx_email_assigned', 'type' => 'index', 'fields' => array('assigned_user_id', 'type', 'status'), ), array( 'name' => 'idx_email_cat', 'type' => 'index', 'fields' => array('category_id') ), ) // end indices ); VardefManager::createVardef('Emails', 'Email', array('default', 'basic', 'assignable','security_groups', ));
agpl-3.0
kerautret/DGtal0.6-ForIPOL
src/boost-1.75/boost/accumulators/statistics/sum.hpp
3884
/////////////////////////////////////////////////////////////////////////////// // sum.hpp // // Copyright 2005 Eric Niebler. 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) #ifndef BOOST_ACCUMULATORS_STATISTICS_SUM_HPP_EAN_28_10_2005 #define BOOST_ACCUMULATORS_STATISTICS_SUM_HPP_EAN_28_10_2005 #include <boost/mpl/placeholders.hpp> #include <boost/accumulators/framework/accumulator_base.hpp> #include <boost/accumulators/framework/extractor.hpp> #include <boost/accumulators/numeric/functional.hpp> #include <boost/accumulators/framework/parameters/sample.hpp> #include <boost/accumulators/framework/parameters/weight.hpp> #include <boost/accumulators/framework/accumulators/external_accumulator.hpp> #include <boost/accumulators/framework/depends_on.hpp> #include <boost/accumulators/statistics_fwd.hpp> #include <boost/accumulators/statistics/count.hpp> namespace boost { namespace accumulators { namespace impl { /////////////////////////////////////////////////////////////////////////////// // sum_impl template<typename Sample, typename Tag> struct sum_impl : accumulator_base { // for boost::result_of typedef Sample result_type; template<typename Args> sum_impl(Args const &args) : sum(args[parameter::keyword<Tag>::get() | Sample()]) { } template<typename Args> void operator ()(Args const &args) { // what about overflow? this->sum += args[parameter::keyword<Tag>::get()]; } result_type result(dont_care) const { return this->sum; } template<class Archive> void serialize(Archive & ar, const unsigned int file_version) { ar & sum; } private: Sample sum; }; } // namespace impl /////////////////////////////////////////////////////////////////////////////// // tag::sum // tag::sum_of_weights // tag::sum_of_variates // namespace tag { struct sum : depends_on<> { /// INTERNAL ONLY /// typedef accumulators::impl::sum_impl<mpl::_1, tag::sample> impl; }; struct sum_of_weights : depends_on<> { typedef mpl::true_ is_weight_accumulator; /// INTERNAL ONLY /// typedef accumulators::impl::sum_impl<mpl::_2, tag::weight> impl; }; template<typename VariateType, typename VariateTag> struct sum_of_variates : depends_on<> { /// INTERNAL ONLY /// typedef mpl::always<accumulators::impl::sum_impl<VariateType, VariateTag> > impl; }; struct abstract_sum_of_variates : depends_on<> { }; } /////////////////////////////////////////////////////////////////////////////// // extract::sum // extract::sum_of_weights // extract::sum_of_variates // namespace extract { extractor<tag::sum> const sum = {}; extractor<tag::sum_of_weights> const sum_of_weights = {}; extractor<tag::abstract_sum_of_variates> const sum_of_variates = {}; BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum) BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_weights) BOOST_ACCUMULATORS_IGNORE_GLOBAL(sum_of_variates) } using extract::sum; using extract::sum_of_weights; using extract::sum_of_variates; // So that mean can be automatically substituted with // weighted_mean when the weight parameter is non-void. template<> struct as_weighted_feature<tag::sum> { typedef tag::weighted_sum type; }; template<> struct feature_of<tag::weighted_sum> : feature_of<tag::sum> {}; template<typename VariateType, typename VariateTag> struct feature_of<tag::sum_of_variates<VariateType, VariateTag> > : feature_of<tag::abstract_sum_of_variates> { }; }} // namespace boost::accumulators #endif
lgpl-3.0
Phaneendra-Huawei/demo
protocols/ospf/protocol/src/main/java/org/onosproject/ospf/protocol/lsa/linksubtype/LinkSubTypes.java
1358
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.ospf.protocol.lsa.linksubtype; /** * Representation of TE link sub types. */ public enum LinkSubTypes { LINK_TYPE(1), LINK_ID(2), LOCAL_INTERFACE_IP_ADDRESS(3), REMOTE_INTERFACE_IP_ADDRESS(4), TRAFFIC_ENGINEERING_METRIC(5), MAXIMUM_BANDWIDTH(6), MAXIMUM_RESERVABLE_BANDWIDTH(7), UNRESERVED_BANDWIDTH(8), ADMINISTRATIVE_GROUP(9); private int value; /** * Creates an instance of link sub types. * * @param value link sub type value */ LinkSubTypes(int value) { this.value = value; } /** * Gets the link sub type value. * * @return link sub type value */ public int value() { return value; } }
apache-2.0
shahrzadmn/skia
tests/RefDictTest.cpp
2399
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRefDict.h" #include "Test.h" class TestRC : public SkRefCnt { public: private: typedef SkRefCnt INHERITED; }; DEF_TEST(RefDict, reporter) { TestRC data0, data1; SkRefDict dict; REPORTER_ASSERT(reporter, nullptr == dict.find(nullptr)); REPORTER_ASSERT(reporter, nullptr == dict.find("foo")); REPORTER_ASSERT(reporter, nullptr == dict.find("bar")); dict.set("foo", &data0); REPORTER_ASSERT(reporter, &data0 == dict.find("foo")); REPORTER_ASSERT(reporter, !data0.unique()); dict.set("foo", &data0); REPORTER_ASSERT(reporter, &data0 == dict.find("foo")); REPORTER_ASSERT(reporter, !data0.unique()); dict.set("foo", &data1); REPORTER_ASSERT(reporter, &data1 == dict.find("foo")); REPORTER_ASSERT(reporter, data0.unique()); REPORTER_ASSERT(reporter, !data1.unique()); dict.set("foo", nullptr); REPORTER_ASSERT(reporter, nullptr == dict.find("foo")); REPORTER_ASSERT(reporter, data0.unique()); REPORTER_ASSERT(reporter, data1.unique()); dict.set("foo", &data0); dict.set("bar", &data1); REPORTER_ASSERT(reporter, &data0 == dict.find("foo")); REPORTER_ASSERT(reporter, &data1 == dict.find("bar")); REPORTER_ASSERT(reporter, !data0.unique()); REPORTER_ASSERT(reporter, !data1.unique()); dict.set("foo", &data1); REPORTER_ASSERT(reporter, &data1 == dict.find("foo")); REPORTER_ASSERT(reporter, &data1 == dict.find("bar")); REPORTER_ASSERT(reporter, data0.unique()); REPORTER_ASSERT(reporter, !data1.unique()); dict.removeAll(); REPORTER_ASSERT(reporter, nullptr == dict.find("foo")); REPORTER_ASSERT(reporter, nullptr == dict.find("bar")); REPORTER_ASSERT(reporter, data0.unique()); REPORTER_ASSERT(reporter, data1.unique()); { SkRefDict d; REPORTER_ASSERT(reporter, nullptr == d.find("foo")); REPORTER_ASSERT(reporter, data0.unique()); d.set("foo", &data0); REPORTER_ASSERT(reporter, &data0 == d.find("foo")); REPORTER_ASSERT(reporter, !data0.unique()); // let d go out of scope still with a ref on data0 } // be sure d's destructor lowered data0's owner count back to 1 REPORTER_ASSERT(reporter, data0.unique()); }
apache-2.0
zgchizi/oppia-uc
core/templates/dev/head/components/RatingDisplayDirectiveSpec.js
3364
// Copyright 2014 The Oppia Authors. 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. /** * @fileoverview Tests that ratings are being displayed correctly. */ describe('Rating display directive', function() { var elt, scope, $httpBackend, compiledElem, ctrlScope; beforeEach(module('directiveTemplates')); beforeEach(module('oppia', GLOBALS.TRANSLATOR_PROVIDER_FOR_TESTS)); beforeEach(inject(function( $rootScope, $compile, _$httpBackend_, $templateCache) { $httpBackend = _$httpBackend_; var templatesHtml = $templateCache.get( 'core/templates/dev/head/components/rating_display.html'); $compile(templatesHtml)($rootScope); $rootScope.$digest(); scope = $rootScope.$new(); elt = angular.element( '<rating-display rating-value="5" is-editable="true">' + '</rating-display>'); compiledElem = $compile(elt)(scope); scope.$digest(); ctrlScope = elt[0].isolateScope(); })); it('should display the correct number of stars', function() { ctrlScope.ratingValue = 4.2; scope.$digest(); // Note the array here is zero-indexed but ratings are one-indexed. expect(ctrlScope.stars[0].cssClass).toBe('fa-star'); expect(ctrlScope.stars[1].cssClass).toBe('fa-star'); expect(ctrlScope.stars[2].cssClass).toBe('fa-star'); expect(ctrlScope.stars[3].cssClass).toBe('fa-star'); expect(ctrlScope.stars[4].cssClass).toBe('fa-star-o'); ctrlScope.ratingValue = 1.7; scope.$digest(); expect(ctrlScope.stars[0].cssClass).toBe('fa-star'); expect(ctrlScope.stars[1].cssClass).toBe('fa-star-half-o'); expect(ctrlScope.stars[2].cssClass).toBe('fa-star-o'); expect(ctrlScope.stars[3].cssClass).toBe('fa-star-o'); expect(ctrlScope.stars[4].cssClass).toBe('fa-star-o'); ctrlScope.ratingValue = 1.9; scope.$digest(); expect(ctrlScope.stars[0].cssClass).toBe('fa-star'); expect(ctrlScope.stars[1].cssClass).toBe('fa-star'); expect(ctrlScope.stars[2].cssClass).toBe('fa-star-o'); expect(ctrlScope.stars[3].cssClass).toBe('fa-star-o'); expect(ctrlScope.stars[4].cssClass).toBe('fa-star-o'); ctrlScope.ratingValue = 2.25; scope.$digest(); expect(ctrlScope.stars[0].cssClass).toBe('fa-star'); expect(ctrlScope.stars[1].cssClass).toBe('fa-star'); expect(ctrlScope.stars[2].cssClass).toBe('fa-star-half-o'); expect(ctrlScope.stars[3].cssClass).toBe('fa-star-o'); expect(ctrlScope.stars[4].cssClass).toBe('fa-star-o'); ctrlScope.ratingValue = 4.3; scope.$digest(); expect(ctrlScope.stars[0].cssClass).toBe('fa-star'); expect(ctrlScope.stars[1].cssClass).toBe('fa-star'); expect(ctrlScope.stars[2].cssClass).toBe('fa-star'); expect(ctrlScope.stars[3].cssClass).toBe('fa-star'); expect(ctrlScope.stars[4].cssClass).toBe('fa-star-half-o'); }); });
apache-2.0
mbrukman/angular
modules/angular2/src/di/injector.ts
28635
import {Map, List, MapWrapper, ListWrapper} from 'angular2/src/facade/collection'; import {ResolvedBinding, Binding, Dependency, BindingBuilder, bind} from './binding'; import { AbstractBindingError, NoBindingError, CyclicDependencyError, InstantiationError, InvalidBindingError, OutOfBoundsError } from './exceptions'; import {FunctionWrapper, Type, isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Key} from './key'; import {resolveForwardRef} from './forward_ref'; import {SelfMetadata, HostMetadata, SkipSelfMetadata} from './metadata'; // Threshold for the dynamic version const _MAX_CONSTRUCTION_COUNTER = 10; export const UNDEFINED: Object = CONST_EXPR(new Object()); export enum Visibility { Public, Private, PublicAndPrivate } function canSee(src: Visibility, dst: Visibility): boolean { return (src === dst) || (dst === Visibility.PublicAndPrivate || src === Visibility.PublicAndPrivate); } export interface ProtoInjectorStrategy { getBindingAtIndex(index: number): ResolvedBinding; createInjectorStrategy(inj: Injector): InjectorStrategy; } export class ProtoInjectorInlineStrategy implements ProtoInjectorStrategy { binding0: ResolvedBinding = null; binding1: ResolvedBinding = null; binding2: ResolvedBinding = null; binding3: ResolvedBinding = null; binding4: ResolvedBinding = null; binding5: ResolvedBinding = null; binding6: ResolvedBinding = null; binding7: ResolvedBinding = null; binding8: ResolvedBinding = null; binding9: ResolvedBinding = null; keyId0: number = null; keyId1: number = null; keyId2: number = null; keyId3: number = null; keyId4: number = null; keyId5: number = null; keyId6: number = null; keyId7: number = null; keyId8: number = null; keyId9: number = null; visibility0: Visibility = null; visibility1: Visibility = null; visibility2: Visibility = null; visibility3: Visibility = null; visibility4: Visibility = null; visibility5: Visibility = null; visibility6: Visibility = null; visibility7: Visibility = null; visibility8: Visibility = null; visibility9: Visibility = null; constructor(protoEI: ProtoInjector, bwv: BindingWithVisibility[]) { var length = bwv.length; if (length > 0) { this.binding0 = bwv[0].binding; this.keyId0 = bwv[0].getKeyId(); this.visibility0 = bwv[0].visibility; } if (length > 1) { this.binding1 = bwv[1].binding; this.keyId1 = bwv[1].getKeyId(); this.visibility1 = bwv[1].visibility; } if (length > 2) { this.binding2 = bwv[2].binding; this.keyId2 = bwv[2].getKeyId(); this.visibility2 = bwv[2].visibility; } if (length > 3) { this.binding3 = bwv[3].binding; this.keyId3 = bwv[3].getKeyId(); this.visibility3 = bwv[3].visibility; } if (length > 4) { this.binding4 = bwv[4].binding; this.keyId4 = bwv[4].getKeyId(); this.visibility4 = bwv[4].visibility; } if (length > 5) { this.binding5 = bwv[5].binding; this.keyId5 = bwv[5].getKeyId(); this.visibility5 = bwv[5].visibility; } if (length > 6) { this.binding6 = bwv[6].binding; this.keyId6 = bwv[6].getKeyId(); this.visibility6 = bwv[6].visibility; } if (length > 7) { this.binding7 = bwv[7].binding; this.keyId7 = bwv[7].getKeyId(); this.visibility7 = bwv[7].visibility; } if (length > 8) { this.binding8 = bwv[8].binding; this.keyId8 = bwv[8].getKeyId(); this.visibility8 = bwv[8].visibility; } if (length > 9) { this.binding9 = bwv[9].binding; this.keyId9 = bwv[9].getKeyId(); this.visibility9 = bwv[9].visibility; } } getBindingAtIndex(index: number): any { if (index == 0) return this.binding0; if (index == 1) return this.binding1; if (index == 2) return this.binding2; if (index == 3) return this.binding3; if (index == 4) return this.binding4; if (index == 5) return this.binding5; if (index == 6) return this.binding6; if (index == 7) return this.binding7; if (index == 8) return this.binding8; if (index == 9) return this.binding9; throw new OutOfBoundsError(index); } createInjectorStrategy(injector: Injector): InjectorStrategy { return new InjectorInlineStrategy(injector, this); } } export class ProtoInjectorDynamicStrategy implements ProtoInjectorStrategy { bindings: ResolvedBinding[]; keyIds: number[]; visibilities: Visibility[]; constructor(protoInj: ProtoInjector, bwv: BindingWithVisibility[]) { var len = bwv.length; this.bindings = ListWrapper.createFixedSize(len); this.keyIds = ListWrapper.createFixedSize(len); this.visibilities = ListWrapper.createFixedSize(len); for (var i = 0; i < len; i++) { this.bindings[i] = bwv[i].binding; this.keyIds[i] = bwv[i].getKeyId(); this.visibilities[i] = bwv[i].visibility; } } getBindingAtIndex(index: number): any { if (index < 0 || index >= this.bindings.length) { throw new OutOfBoundsError(index); } return this.bindings[index]; } createInjectorStrategy(ei: Injector): InjectorStrategy { return new InjectorDynamicStrategy(this, ei); } } export class ProtoInjector { _strategy: ProtoInjectorStrategy; numberOfBindings: number; constructor(bwv: BindingWithVisibility[]) { this.numberOfBindings = bwv.length; this._strategy = bwv.length > _MAX_CONSTRUCTION_COUNTER ? new ProtoInjectorDynamicStrategy(this, bwv) : new ProtoInjectorInlineStrategy(this, bwv); } getBindingAtIndex(index: number): any { return this._strategy.getBindingAtIndex(index); } } export interface InjectorStrategy { getObjByKeyId(keyId: number, visibility: Visibility): any; getObjAtIndex(index: number): any; getMaxNumberOfObjects(): number; attach(parent: Injector, isHost: boolean): void; resetConstructionCounter(): void; instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any; } export class InjectorInlineStrategy implements InjectorStrategy { obj0: any = UNDEFINED; obj1: any = UNDEFINED; obj2: any = UNDEFINED; obj3: any = UNDEFINED; obj4: any = UNDEFINED; obj5: any = UNDEFINED; obj6: any = UNDEFINED; obj7: any = UNDEFINED; obj8: any = UNDEFINED; obj9: any = UNDEFINED; constructor(public injector: Injector, public protoStrategy: ProtoInjectorInlineStrategy) {} resetConstructionCounter(): void { this.injector._constructionCounter = 0; } instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any { return this.injector._new(binding, visibility); } attach(parent: Injector, isHost: boolean): void { var inj = this.injector; inj._parent = parent; inj._isHost = isHost; } getObjByKeyId(keyId: number, visibility: Visibility): any { var p = this.protoStrategy; var inj = this.injector; if (p.keyId0 === keyId && canSee(p.visibility0, visibility)) { if (this.obj0 === UNDEFINED) { this.obj0 = inj._new(p.binding0, p.visibility0); } return this.obj0; } if (p.keyId1 === keyId && canSee(p.visibility1, visibility)) { if (this.obj1 === UNDEFINED) { this.obj1 = inj._new(p.binding1, p.visibility1); } return this.obj1; } if (p.keyId2 === keyId && canSee(p.visibility2, visibility)) { if (this.obj2 === UNDEFINED) { this.obj2 = inj._new(p.binding2, p.visibility2); } return this.obj2; } if (p.keyId3 === keyId && canSee(p.visibility3, visibility)) { if (this.obj3 === UNDEFINED) { this.obj3 = inj._new(p.binding3, p.visibility3); } return this.obj3; } if (p.keyId4 === keyId && canSee(p.visibility4, visibility)) { if (this.obj4 === UNDEFINED) { this.obj4 = inj._new(p.binding4, p.visibility4); } return this.obj4; } if (p.keyId5 === keyId && canSee(p.visibility5, visibility)) { if (this.obj5 === UNDEFINED) { this.obj5 = inj._new(p.binding5, p.visibility5); } return this.obj5; } if (p.keyId6 === keyId && canSee(p.visibility6, visibility)) { if (this.obj6 === UNDEFINED) { this.obj6 = inj._new(p.binding6, p.visibility6); } return this.obj6; } if (p.keyId7 === keyId && canSee(p.visibility7, visibility)) { if (this.obj7 === UNDEFINED) { this.obj7 = inj._new(p.binding7, p.visibility7); } return this.obj7; } if (p.keyId8 === keyId && canSee(p.visibility8, visibility)) { if (this.obj8 === UNDEFINED) { this.obj8 = inj._new(p.binding8, p.visibility8); } return this.obj8; } if (p.keyId9 === keyId && canSee(p.visibility9, visibility)) { if (this.obj9 === UNDEFINED) { this.obj9 = inj._new(p.binding9, p.visibility9); } return this.obj9; } return UNDEFINED; } getObjAtIndex(index: number): any { if (index == 0) return this.obj0; if (index == 1) return this.obj1; if (index == 2) return this.obj2; if (index == 3) return this.obj3; if (index == 4) return this.obj4; if (index == 5) return this.obj5; if (index == 6) return this.obj6; if (index == 7) return this.obj7; if (index == 8) return this.obj8; if (index == 9) return this.obj9; throw new OutOfBoundsError(index); } getMaxNumberOfObjects(): number { return _MAX_CONSTRUCTION_COUNTER; } } export class InjectorDynamicStrategy implements InjectorStrategy { objs: any[]; constructor(public protoStrategy: ProtoInjectorDynamicStrategy, public injector: Injector) { this.objs = ListWrapper.createFixedSize(protoStrategy.bindings.length); ListWrapper.fill(this.objs, UNDEFINED); } resetConstructionCounter(): void { this.injector._constructionCounter = 0; } instantiateBinding(binding: ResolvedBinding, visibility: Visibility): any { return this.injector._new(binding, visibility); } attach(parent: Injector, isHost: boolean): void { var inj = this.injector; inj._parent = parent; inj._isHost = isHost; } getObjByKeyId(keyId: number, visibility: Visibility): any { var p = this.protoStrategy; for (var i = 0; i < p.keyIds.length; i++) { if (p.keyIds[i] === keyId && canSee(p.visibilities[i], visibility)) { if (this.objs[i] === UNDEFINED) { this.objs[i] = this.injector._new(p.bindings[i], p.visibilities[i]); } return this.objs[i]; } } return UNDEFINED; } getObjAtIndex(index: number): any { if (index < 0 || index >= this.objs.length) { throw new OutOfBoundsError(index); } return this.objs[index]; } getMaxNumberOfObjects(): number { return this.objs.length; } } export class BindingWithVisibility { constructor(public binding: ResolvedBinding, public visibility: Visibility){}; getKeyId(): number { return this.binding.key.id; } } /** * Used to provide dependencies that cannot be easily expressed as bindings. */ export interface DependencyProvider { getDependency(injector: Injector, binding: ResolvedBinding, dependency: Dependency): any; } /** * A dependency injection container used for resolving dependencies. * * An `Injector` is a replacement for a `new` operator, which can automatically resolve the * constructor dependencies. * In typical use, application code asks for the dependencies in the constructor and they are * resolved by the `Injector`. * * ## Example: * * Suppose that we want to inject an `Engine` into class `Car`, we would define it like this: * * ```javascript * class Engine { * } * * class Car { * constructor(@Inject(Engine) engine) { * } * } * * ``` * * Next we need to write the code that creates and instantiates the `Injector`. We then ask for the * `root` object, `Car`, so that the `Injector` can recursively build all of that object's *dependencies. * * ```javascript * main() { * var injector = Injector.resolveAndCreate([Car, Engine]); * * // Get a reference to the `root` object, which will recursively instantiate the tree. * var car = injector.get(Car); * } * ``` * Notice that we don't use the `new` operator because we explicitly want to have the `Injector` * resolve all of the object's dependencies automatically. */ export class Injector { /** * Turns a list of binding definitions into an internal resolved list of resolved bindings. * * A resolution is a process of flattening multiple nested lists and converting individual * bindings into a list of {@link ResolvedBinding}s. The resolution can be cached by `resolve` * for the {@link Injector} for performance-sensitive code. * * @param `bindings` can be a list of `Type`, {@link Binding}, {@link ResolvedBinding}, or a * recursive list of more bindings. * * The returned list is sparse, indexed by `id` for the {@link Key}. It is generally not useful to *application code * other than for passing it to {@link Injector} functions that require resolved binding lists, *such as * `fromResolvedBindings` and `createChildFromResolved`. */ static resolve(bindings: List<Type | Binding | List<any>>): List<ResolvedBinding> { var resolvedBindings = _resolveBindings(bindings); var flatten = _flattenBindings(resolvedBindings, new Map()); return _createListOfBindings(flatten); } /** * Resolves bindings and creates an injector based on those bindings. This function is slower than * the corresponding `fromResolvedBindings` because it needs to resolve bindings first. See *`resolve` * for the {@link Injector}. * * Prefer `fromResolvedBindings` in performance-critical code that creates lots of injectors. * * @param `bindings` can be a list of `Type`, {@link Binding}, {@link ResolvedBinding}, or a *recursive list of more * bindings. * @param `depProvider` */ static resolveAndCreate(bindings: List<Type | Binding | List<any>>, depProvider: DependencyProvider = null): Injector { var resolvedBindings = Injector.resolve(bindings); return Injector.fromResolvedBindings(resolvedBindings, depProvider); } /** * Creates an injector from previously resolved bindings. This bypasses resolution and flattening. * This API is the recommended way to construct injectors in performance-sensitive parts. * * @param `bindings` A sparse list of {@link ResolvedBinding}s. See `resolve` for the * {@link Injector}. * @param `depProvider` */ static fromResolvedBindings(bindings: List<ResolvedBinding>, depProvider: DependencyProvider = null): Injector { var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public)); var proto = new ProtoInjector(bd); var inj = new Injector(proto, null, depProvider); return inj; } _strategy: InjectorStrategy; _isHost: boolean = false; _constructionCounter: number = 0; constructor(public _proto: ProtoInjector, public _parent: Injector = null, private _depProvider: DependencyProvider = null, private _debugContext: Function = null) { this._strategy = _proto._strategy.createInjectorStrategy(this); } /** * Returns debug information about the injector. * * This information is included into exceptions thrown by the injector. */ debugContext(): any { return this._debugContext(); } /** * Retrieves an instance from the injector. * * @param `token`: usually the `Type` of an object. (Same as the token used while setting up a *binding). * @returns an instance represented by the token. Throws if not found. */ get(token: any): any { return this._getByKey(Key.get(token), null, null, false, Visibility.PublicAndPrivate); } /** * Retrieves an instance from the injector. * * @param `token`: usually a `Type`. (Same as the token used while setting up a binding). * @returns an instance represented by the token. Returns `null` if not found. */ getOptional(token: any): any { return this._getByKey(Key.get(token), null, null, true, Visibility.PublicAndPrivate); } /** * Retrieves an instance from the injector. * * @param `index`: index of an instance. * @returns an instance represented by the index. Throws if not found. */ getAt(index: number): any { return this._strategy.getObjAtIndex(index); } /** * Direct parent of this injector. */ get parent(): Injector { return this._parent; } /** * Internal. Do not use. * * We return `any` not to export the InjectorStrategy type. */ get internalStrategy(): any { return this._strategy; } /** * Creates a child injector and loads a new set of bindings into it. * * A resolution is a process of flattening multiple nested lists and converting individual * bindings into a list of {@link ResolvedBinding}s. The resolution can be cached by `resolve` * for the {@link Injector} for performance-sensitive code. * * @param `bindings` can be a list of `Type`, {@link Binding}, {@link ResolvedBinding}, or a * recursive list of more bindings. * @param `depProvider` */ resolveAndCreateChild(bindings: List<Type | Binding | List<any>>, depProvider: DependencyProvider = null): Injector { var resovledBindings = Injector.resolve(bindings); return this.createChildFromResolved(resovledBindings, depProvider); } /** * Creates a child injector and loads a new set of {@link ResolvedBinding}s into it. * * @param `bindings`: A sparse list of {@link ResolvedBinding}s. * See `resolve` for the {@link Injector}. * @param `depProvider` * @returns a new child {@link Injector}. */ createChildFromResolved(bindings: List<ResolvedBinding>, depProvider: DependencyProvider = null): Injector { var bd = bindings.map(b => new BindingWithVisibility(b, Visibility.Public)); var proto = new ProtoInjector(bd); var inj = new Injector(proto, null, depProvider); inj._parent = this; return inj; } /** * Resolves a binding and instantiates an object in the context of the injector. * * @param `binding`: either a type or a binding. * @returns an object created using binding. */ resolveAndInstantiate(binding: Type | Binding): any { return this.instantiateResolved(Injector.resolve([binding])[0]); } /** * Instantiates an object using a resolved bindin in the context of the injector. * * @param `binding`: a resolved binding * @returns an object created using binding. */ instantiateResolved(binding: ResolvedBinding): any { return this._instantiate(binding, Visibility.PublicAndPrivate); } _new(binding: ResolvedBinding, visibility: Visibility): any { if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) { throw new CyclicDependencyError(this, binding.key); } return this._instantiate(binding, visibility); } private _instantiate(binding: ResolvedBinding, visibility: Visibility): any { var factory = binding.factory; var deps = binding.dependencies; var length = deps.length; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19; try { d0 = length > 0 ? this._getByDependency(binding, deps[0], visibility) : null; d1 = length > 1 ? this._getByDependency(binding, deps[1], visibility) : null; d2 = length > 2 ? this._getByDependency(binding, deps[2], visibility) : null; d3 = length > 3 ? this._getByDependency(binding, deps[3], visibility) : null; d4 = length > 4 ? this._getByDependency(binding, deps[4], visibility) : null; d5 = length > 5 ? this._getByDependency(binding, deps[5], visibility) : null; d6 = length > 6 ? this._getByDependency(binding, deps[6], visibility) : null; d7 = length > 7 ? this._getByDependency(binding, deps[7], visibility) : null; d8 = length > 8 ? this._getByDependency(binding, deps[8], visibility) : null; d9 = length > 9 ? this._getByDependency(binding, deps[9], visibility) : null; d10 = length > 10 ? this._getByDependency(binding, deps[10], visibility) : null; d11 = length > 11 ? this._getByDependency(binding, deps[11], visibility) : null; d12 = length > 12 ? this._getByDependency(binding, deps[12], visibility) : null; d13 = length > 13 ? this._getByDependency(binding, deps[13], visibility) : null; d14 = length > 14 ? this._getByDependency(binding, deps[14], visibility) : null; d15 = length > 15 ? this._getByDependency(binding, deps[15], visibility) : null; d16 = length > 16 ? this._getByDependency(binding, deps[16], visibility) : null; d17 = length > 17 ? this._getByDependency(binding, deps[17], visibility) : null; d18 = length > 18 ? this._getByDependency(binding, deps[18], visibility) : null; d19 = length > 19 ? this._getByDependency(binding, deps[19], visibility) : null; } catch (e) { if (e instanceof AbstractBindingError) { e.addKey(this, binding.key); } throw e; } var obj; try { switch (length) { case 0: obj = factory(); break; case 1: obj = factory(d0); break; case 2: obj = factory(d0, d1); break; case 3: obj = factory(d0, d1, d2); break; case 4: obj = factory(d0, d1, d2, d3); break; case 5: obj = factory(d0, d1, d2, d3, d4); break; case 6: obj = factory(d0, d1, d2, d3, d4, d5); break; case 7: obj = factory(d0, d1, d2, d3, d4, d5, d6); break; case 8: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7); break; case 9: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8); break; case 10: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9); break; case 11: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10); break; case 12: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11); break; case 13: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12); break; case 14: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13); break; case 15: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14); break; case 16: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15); break; case 17: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16); break; case 18: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17); break; case 19: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18); break; case 20: obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19); break; } } catch (e) { throw new InstantiationError(this, e, e.stack, binding.key); } return obj; } private _getByDependency(binding: ResolvedBinding, dep: Dependency, bindingVisibility: Visibility): any { var special = isPresent(this._depProvider) ? this._depProvider.getDependency(this, binding, dep) : UNDEFINED; if (special !== UNDEFINED) { return special; } else { return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, dep.optional, bindingVisibility); } } private _getByKey(key: Key, lowerBoundVisibility: Object, upperBoundVisibility: Object, optional: boolean, bindingVisibility: Visibility): any { if (key === INJECTOR_KEY) { return this; } if (upperBoundVisibility instanceof SelfMetadata) { return this._getByKeySelf(key, optional, bindingVisibility); } else if (upperBoundVisibility instanceof HostMetadata) { return this._getByKeyHost(key, optional, bindingVisibility, lowerBoundVisibility); } else { return this._getByKeyDefault(key, optional, bindingVisibility, lowerBoundVisibility); } } _throwOrNull(key: Key, optional: boolean): any { if (optional) { return null; } else { throw new NoBindingError(this, key); } } _getByKeySelf(key: Key, optional: boolean, bindingVisibility: Visibility): any { var obj = this._strategy.getObjByKeyId(key.id, bindingVisibility); return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional); } _getByKeyHost(key: Key, optional: boolean, bindingVisibility: Visibility, lowerBoundVisibility: Object): any { var inj = this; if (lowerBoundVisibility instanceof SkipSelfMetadata) { if (inj._isHost) { return this._getPrivateDependency(key, optional, inj); } else { inj = inj._parent; } } while (inj != null) { var obj = inj._strategy.getObjByKeyId(key.id, bindingVisibility); if (obj !== UNDEFINED) return obj; if (isPresent(inj._parent) && inj._isHost) { return this._getPrivateDependency(key, optional, inj); } else { inj = inj._parent; } } return this._throwOrNull(key, optional); } _getPrivateDependency(key: Key, optional: boolean, inj: Injector): any { var obj = inj._parent._strategy.getObjByKeyId(key.id, Visibility.Private); return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, optional); } _getByKeyDefault(key: Key, optional: boolean, bindingVisibility: Visibility, lowerBoundVisibility: Object): any { var inj = this; if (lowerBoundVisibility instanceof SkipSelfMetadata) { bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public; inj = inj._parent; } while (inj != null) { var obj = inj._strategy.getObjByKeyId(key.id, bindingVisibility); if (obj !== UNDEFINED) return obj; bindingVisibility = inj._isHost ? Visibility.PublicAndPrivate : Visibility.Public; inj = inj._parent; } return this._throwOrNull(key, optional); } get displayName(): string { return `Injector(bindings: [${_mapBindings(this, b => ` "${b.key.displayName}" `).join(", ")}])`; } toString(): string { return this.displayName; } } var INJECTOR_KEY = Key.get(Injector); function _resolveBindings(bindings: List<Type | Binding | List<any>>): List<ResolvedBinding> { var resolvedList = ListWrapper.createFixedSize(bindings.length); for (var i = 0; i < bindings.length; i++) { var unresolved = resolveForwardRef(bindings[i]); var resolved; if (unresolved instanceof ResolvedBinding) { resolved = unresolved; // ha-ha! I'm easily amused } else if (unresolved instanceof Type) { resolved = bind(unresolved).toClass(unresolved).resolve(); } else if (unresolved instanceof Binding) { resolved = unresolved.resolve(); } else if (unresolved instanceof List) { resolved = _resolveBindings(unresolved); } else if (unresolved instanceof BindingBuilder) { throw new InvalidBindingError(unresolved.token); } else { throw new InvalidBindingError(unresolved); } resolvedList[i] = resolved; } return resolvedList; } function _createListOfBindings(flattenedBindings: Map<number, ResolvedBinding>): List<ResolvedBinding> { return MapWrapper.values(flattenedBindings); } function _flattenBindings(bindings: List<ResolvedBinding | List<any>>, res: Map<number, ResolvedBinding>): Map<number, ResolvedBinding> { ListWrapper.forEach(bindings, function(b) { if (b instanceof ResolvedBinding) { res.set(b.key.id, b); } else if (b instanceof List) { _flattenBindings(b, res); } }); return res; } function _mapBindings(injector: Injector, fn: Function): any[] { var res = []; for (var i = 0; i < injector._proto.numberOfBindings; ++i) { res.push(fn(injector._proto.getBindingAtIndex(i))); } return res; }
apache-2.0
mdaniel/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/ConsentConfigurable.java
1362
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.gdpr; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ConfigurableBase; import com.intellij.ui.AppUIUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class ConsentConfigurable extends ConfigurableBase<ConsentSettingsUi, List<Consent>> { private final List<Consent> myConsents; public ConsentConfigurable() { super("consents", IdeBundle.message("consent.configurable"), "preferences.usage.statistics"); myConsents = new ArrayList<>(AppUIUtil.loadConsentsForEditing()); } @NotNull @Override protected List<Consent> getSettings() { return myConsents; } @Override protected ConsentSettingsUi createUi() { ConsentSettingsUi ui = new ConsentSettingsUi(true) { @Override public void apply(@NotNull List<Consent> consents) { super.apply(consents); AppUIUtil.saveConsents(consents); } }; // When building searchable options, ensure we return a non-empty UI if (ApplicationManager.getApplication().isHeadlessEnvironment()) { ui.reset(myConsents); } return ui; } }
apache-2.0
leafclick/intellij-community
platform/util/ui/src/com/intellij/util/ui/MouseEventHandler.java
1454
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui; import javax.swing.event.MouseInputListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; public abstract class MouseEventHandler extends MouseAdapter implements MouseInputListener { /** * The event shouldn't be just delegated to JComponent.processMouseEvent() or processMouseMotionEvent(), check its ID first */ protected abstract void handle(MouseEvent event); @Override public void mousePressed(MouseEvent event) { handle(event); } @Override public void mouseClicked(MouseEvent event) { handle(event); } @Override public void mouseReleased(MouseEvent event) { handle(event); } @Override public void mouseEntered(MouseEvent event) { handle(event); } @Override public void mouseExited(MouseEvent event) { handle(event); } @Override public void mouseMoved(MouseEvent event) { handle(event); } @Override public void mouseDragged(MouseEvent event) { handle(event); } @Override public void mouseWheelMoved(MouseWheelEvent event) { handle(event); } public static final MouseEventHandler CONSUMER = new MouseEventHandler() { @Override protected void handle(MouseEvent event) { event.consume(); } }; }
apache-2.0
mcdan/sling
bundles/jcr/resource/src/main/java/org/apache/sling/jcr/resource/internal/helper/jcr/JcrNodeResourceIterator.java
5194
/* * 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.sling.jcr.resource.internal.helper.jcr; import java.util.Iterator; import java.util.NoSuchElementException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.path.PathSet; import org.apache.sling.jcr.resource.internal.HelperData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <code>JcrNodeResourceIterator</code> class is a resource iterator, * which returns resources for each node of an underlying * <code>NodeIterator</code>. Nodes in the node iterator which cannot be * accessed or for which a resource cannot be created are skipped. */ public class JcrNodeResourceIterator implements Iterator<Resource> { /** default log */ private static final Logger LOGGER = LoggerFactory.getLogger(JcrNodeResourceIterator.class); /** resource resolver used to create resources from nodes */ private final ResourceResolver resourceResolver; /** underlying node iterator to be used for resources */ private final NodeIterator nodes; /** The prefetched next iterator entry, null at the end of iterating */ private Resource nextResult; private final HelperData helper; private final String parentPath; private final String parentVersion; private final PathSet excludedPaths; /** * Creates an instance using the given resource manager and the nodes * provided as a node iterator. Paths of the iterated resources will be * concatenated from the parent path, node name and the version number. * * @param resourceResolver the resolver * @param parentPath the parent path * @param parentVersion the parent version * @param nodes the node iterator * @param helper the helper * @param excludedPaths the set of excluded paths */ public JcrNodeResourceIterator(final ResourceResolver resourceResolver, final String parentPath, final String parentVersion, final NodeIterator nodes, final HelperData helper, final PathSet excludedPaths) { this.resourceResolver = resourceResolver; this.parentPath = parentPath; this.parentVersion = parentVersion; this.nodes = nodes; this.helper = helper; this.excludedPaths = excludedPaths == null ? PathSet.EMPTY_SET : excludedPaths; this.nextResult = seek(); } @Override public boolean hasNext() { return nextResult != null; } @Override public Resource next() { if (!hasNext()) { throw new NoSuchElementException(); } Resource result = nextResult; nextResult = seek(); return result; } /** * Throws <code>UnsupportedOperationException</code> as this method is not * supported by this implementation. */ @Override public void remove() { throw new UnsupportedOperationException(); } private Resource seek() { while (nodes.hasNext()) { try { final Node n = nodes.nextNode(); final String path = getPath(n); if ( path != null && this.excludedPaths.matches(path) == null ) { final Resource resource = new JcrNodeResource(resourceResolver, path, parentVersion, n, helper); LOGGER.debug("seek: Returning Resource {}", resource); return resource; } } catch (final Throwable t) { LOGGER.error( "seek: Problem creating Resource for next node, skipping", t); } } // no more results LOGGER.debug("seek: No more nodes, iterator exhausted"); return null; } private String getPath(final Node node) throws RepositoryException { final String path; if (parentPath == null) { path = node.getPath(); } else { path = "/".equals(parentPath) ? '/' + node.getName() : parentPath + '/' + node.getName(); } return path; } }
apache-2.0
rowanmiller/Demo-MVADec14
StartingSource/CycleSales/src/CycleSales/node_modules/grunt-bower-task/node_modules/es5-ext/array/#/contains.js
185
'use strict'; var indexOf = require('./e-index-of'); module.exports = function (searchElement/*, position*/) { return indexOf.call(this, searchElement, arguments[1]) > -1; };
apache-2.0
tunneln/CarnotKE
jyhton/out/production/jyhton/test323.py
725
""" Tests using a path inside a zip file for zip imports """ import support import zipfile, time def addZipEntry(zip, name, data): entry = zipfile.ZipInfo() entry.filename = name entry.date_time = time.gmtime(time.time()) zip.writestr(entry, data) zip = zipfile.ZipFile("test323.zip", "w", zipfile.ZIP_DEFLATED) addZipEntry(zip, "Lib/test323m.py", """ assert __name__ == 'test323m', " __name__ should've been test323m but was %s" % __name__ from java.io import File expected = "test323.zip%sLib/test323m.py" % (File.separator) assert expected in __file__, "%s should've been in __file__ but was %s" % (expected, __file__) """) zip.close() import sys sys.path.append("test323.zip/Lib") import test323m
apache-2.0
GunoH/intellij-community
plugins/lombok/testData/action/delombok/builder/afterBuilderSimplePredefined.java
1205
public class BuilderSimplePreDefined { private int myInt; private String myString; BuilderSimplePreDefined(int myInt, String myString) { this.myInt = myInt; this.myString = myString; } public static BuilderSimplePreDefinedBuilder builder() { return new BuilderSimplePreDefinedBuilder(); } static class BuilderSimplePreDefinedBuilder { private int myInt; private String myString; BuilderSimplePreDefinedBuilder() { } public BuilderSimplePreDefinedBuilder myString(String myString) { this.myString = myString + "something"; return this; } public BuilderSimplePreDefinedBuilder myInt(int myInt) { this.myInt = myInt; return this; } public BuilderSimplePreDefined build() { return new BuilderSimplePreDefined(myInt, myString); } public String toString() { return "BuilderSimplePreDefined.BuilderSimplePreDefinedBuilder(myInt=" + this.myInt + ", myString=" + this.myString + ")"; } } public static void main(String[] args) { BuilderSimplePreDefined builderSimple = BuilderSimplePreDefined.builder().myInt(123).myString("string").build(); System.out.println(builderSimple); } }
apache-2.0
Maccimo/intellij-community
java/java-tests/testData/inspection/patternVariableCanBeUsed/beforeSimpleNot.java
167
// "Replace 's' with pattern variable" "false" class X { void test(Object obj) { if (!(obj instanceof String)) { String <caret>s = (String)obj; } } }
apache-2.0
christophd/camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvAutospanLineTest.java
3073
/* * 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.camel.dataformat.bindy.csv; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.dataformat.bindy.model.simple.spanLastRecord.SpanLastRecord; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class BindySimpleCsvAutospanLineTest extends CamelTestSupport { @Test public void testUnmarshalNoNeedToSpanLine() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:unmarshal"); mock.expectedMessageCount(1); template.sendBody("direct:unmarshal", "1,hei,kommentar"); assertMockEndpointsSatisfied(); //final List<Map<?, SpanLastRecord>> rows = CastUtils.cast(mock.getReceivedExchanges().get(0).getIn().getBody(List.class)); //final SpanLastRecord order = rows.get(0).get(SpanLastRecord.class.getName()); final SpanLastRecord order = mock.getReceivedExchanges().get(0).getIn().getBody(SpanLastRecord.class); assertEquals(1, order.getRecordId()); assertEquals("hei", order.getName()); assertEquals("kommentar", order.getComment()); } @Test public void testUnmarshalSpanningLine() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:unmarshal"); mock.expectedMessageCount(1); template.sendBody("direct:unmarshal", "1,hei,kommentar,test,noe,hei"); assertMockEndpointsSatisfied(); final SpanLastRecord order = mock.getReceivedExchanges().get(0).getIn().getBody(SpanLastRecord.class); assertEquals(1, order.getRecordId()); assertEquals("hei", order.getName()); assertEquals("kommentar,test,noe,hei", order.getComment()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { final BindyCsvDataFormat bindy = new BindyCsvDataFormat(SpanLastRecord.class); from("direct:unmarshal") .unmarshal(bindy) .to("mock:unmarshal"); } }; } }
apache-2.0
krousey/kube-deploy
imagebuilder/vendor/google.golang.org/api/container/v1/container-gen.go
91179
// Package container provides access to the Google Container Engine API. // // See https://cloud.google.com/container-engine/ // // Usage example: // // import "google.golang.org/api/container/v1" // ... // containerService, err := container.New(oauthHttpClient) package container // import "google.golang.org/api/container/v1" import ( "bytes" "encoding/json" "errors" "fmt" context "golang.org/x/net/context" ctxhttp "golang.org/x/net/context/ctxhttp" gensupport "google.golang.org/api/gensupport" googleapi "google.golang.org/api/googleapi" "io" "net/http" "net/url" "strconv" "strings" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = ctxhttp.Do const apiId = "container:v1" const apiName = "container" const apiVersion = "v1" const basePath = "https://container.googleapis.com/" // OAuth2 scopes used by this API. const ( // View and manage your data across Google Cloud Platform services CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" ) func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Projects = NewProjectsService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Projects *ProjectsService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewProjectsService(s *Service) *ProjectsService { rs := &ProjectsService{s: s} rs.Zones = NewProjectsZonesService(s) return rs } type ProjectsService struct { s *Service Zones *ProjectsZonesService } func NewProjectsZonesService(s *Service) *ProjectsZonesService { rs := &ProjectsZonesService{s: s} rs.Clusters = NewProjectsZonesClustersService(s) rs.Operations = NewProjectsZonesOperationsService(s) return rs } type ProjectsZonesService struct { s *Service Clusters *ProjectsZonesClustersService Operations *ProjectsZonesOperationsService } func NewProjectsZonesClustersService(s *Service) *ProjectsZonesClustersService { rs := &ProjectsZonesClustersService{s: s} rs.NodePools = NewProjectsZonesClustersNodePoolsService(s) return rs } type ProjectsZonesClustersService struct { s *Service NodePools *ProjectsZonesClustersNodePoolsService } func NewProjectsZonesClustersNodePoolsService(s *Service) *ProjectsZonesClustersNodePoolsService { rs := &ProjectsZonesClustersNodePoolsService{s: s} return rs } type ProjectsZonesClustersNodePoolsService struct { s *Service } func NewProjectsZonesOperationsService(s *Service) *ProjectsZonesOperationsService { rs := &ProjectsZonesOperationsService{s: s} return rs } type ProjectsZonesOperationsService struct { s *Service } // AddonsConfig: Configuration for the addons that can be automatically // spun up in the cluster, enabling additional functionality. type AddonsConfig struct { // HorizontalPodAutoscaling: Configuration for the horizontal pod // autoscaling feature, which increases or decreases the number of // replica pods a replication controller has based on the resource usage // of the existing pods. HorizontalPodAutoscaling *HorizontalPodAutoscaling `json:"horizontalPodAutoscaling,omitempty"` // HttpLoadBalancing: Configuration for the HTTP (L7) load balancing // controller addon, which makes it easy to set up HTTP load balancers // for services in a cluster. HttpLoadBalancing *HttpLoadBalancing `json:"httpLoadBalancing,omitempty"` // ForceSendFields is a list of field names (e.g. // "HorizontalPodAutoscaling") to unconditionally include in API // requests. By default, fields with empty values are omitted from API // requests. However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` } func (s *AddonsConfig) MarshalJSON() ([]byte, error) { type noMethod AddonsConfig raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // Cluster: A Google Container Engine cluster. type Cluster struct { // AddonsConfig: Configurations for the various addons available to run // in the cluster. AddonsConfig *AddonsConfig `json:"addonsConfig,omitempty"` // ClusterIpv4Cidr: The IP address range of the container pods in this // cluster, in // [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) // notation (e.g. `10.96.0.0/14`). Leave blank to have one automatically // chosen or specify a `/14` block in `10.0.0.0/8`. ClusterIpv4Cidr string `json:"clusterIpv4Cidr,omitempty"` // CreateTime: [Output only] The time the cluster was created, in // [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. CreateTime string `json:"createTime,omitempty"` // CurrentMasterVersion: [Output only] The current software version of // the master endpoint. CurrentMasterVersion string `json:"currentMasterVersion,omitempty"` // CurrentNodeCount: [Output only] The number of nodes currently in the // cluster. CurrentNodeCount int64 `json:"currentNodeCount,omitempty"` // CurrentNodeVersion: [Output only] The current version of the node // software components. If they are currently at multiple versions // because they're in the process of being upgraded, this reflects the // minimum version of all nodes. CurrentNodeVersion string `json:"currentNodeVersion,omitempty"` // Description: An optional description of this cluster. Description string `json:"description,omitempty"` // Endpoint: [Output only] The IP address of this cluster's master // endpoint. The endpoint can be accessed from the internet at // `https://username:password@endpoint/`. See the `masterAuth` property // of this resource for username and password information. Endpoint string `json:"endpoint,omitempty"` // InitialClusterVersion: [Output only] The software version of the // master endpoint and kubelets used in the cluster when it was first // created. The version can be upgraded over time. InitialClusterVersion string `json:"initialClusterVersion,omitempty"` // InitialNodeCount: The number of nodes to create in this cluster. You // must ensure that your Compute Engine resource quota is sufficient for // this number of instances. You must also have available firewall and // routes quota. For requests, this field should only be used in lieu of // a "node_pool" object, since this configuration (along with the // "node_config") will be used to create a "NodePool" object with an // auto-generated name. Do not use this and a node_pool at the same // time. InitialNodeCount int64 `json:"initialNodeCount,omitempty"` // InstanceGroupUrls: [Output only] The resource URLs of [instance // groups](/compute/docs/instance-groups/) associated with this cluster. InstanceGroupUrls []string `json:"instanceGroupUrls,omitempty"` // Locations: The list of Google Compute Engine // [locations](/compute/docs/zones#available) in which the cluster's // nodes should be located. Locations []string `json:"locations,omitempty"` // LoggingService: The logging service the cluster should use to write // logs. Currently available options: * `logging.googleapis.com` - the // Google Cloud Logging service. * `none` - no logs will be exported // from the cluster. * if left as an empty // string,`logging.googleapis.com` will be used. LoggingService string `json:"loggingService,omitempty"` // MasterAuth: The authentication information for accessing the master // endpoint. MasterAuth *MasterAuth `json:"masterAuth,omitempty"` // MonitoringService: The monitoring service the cluster should use to // write metrics. Currently available options: * // `monitoring.googleapis.com` - the Google Cloud Monitoring service. * // `none` - no metrics will be exported from the cluster. * if left as // an empty string, `monitoring.googleapis.com` will be used. MonitoringService string `json:"monitoringService,omitempty"` // Name: The name of this cluster. The name must be unique within this // project and zone, and can be up to 40 characters with the following // restrictions: * Lowercase letters, numbers, and hyphens only. * Must // start with a letter. * Must end with a number or a letter. Name string `json:"name,omitempty"` // Network: The name of the Google Compute Engine // [network](/compute/docs/networks-and-firewalls#networks) to which the // cluster is connected. If left unspecified, the `default` network will // be used. Network string `json:"network,omitempty"` // NodeConfig: Parameters used in creating the cluster's nodes. See // `nodeConfig` for the description of its properties. For requests, // this field should only be used in lieu of a "node_pool" object, since // this configuration (along with the "initial_node_count") will be used // to create a "NodePool" object with an auto-generated name. Do not use // this and a node_pool at the same time. For responses, this field will // be populated with the node configuration of the first node pool. If // unspecified, the defaults are used. NodeConfig *NodeConfig `json:"nodeConfig,omitempty"` // NodeIpv4CidrSize: [Output only] The size of the address space on each // node for hosting containers. This is provisioned from within the // `container_ipv4_cidr` range. NodeIpv4CidrSize int64 `json:"nodeIpv4CidrSize,omitempty"` // NodePools: The node pools associated with this cluster. When creating // a new cluster, only a single node pool should be specified. This // field should not be set if "node_config" or "initial_node_count" are // specified. NodePools []*NodePool `json:"nodePools,omitempty"` // SelfLink: [Output only] Server-defined URL for the resource. SelfLink string `json:"selfLink,omitempty"` // ServicesIpv4Cidr: [Output only] The IP address range of the // Kubernetes services in this cluster, in // [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) // notation (e.g. `1.2.3.4/29`). Service addresses are typically put in // the last `/16` from the container CIDR. ServicesIpv4Cidr string `json:"servicesIpv4Cidr,omitempty"` // Status: [Output only] The current status of this cluster. // // Possible values: // "STATUS_UNSPECIFIED" // "PROVISIONING" // "RUNNING" // "RECONCILING" // "STOPPING" // "ERROR" Status string `json:"status,omitempty"` // StatusMessage: [Output only] Additional information about the current // status of this cluster, if available. StatusMessage string `json:"statusMessage,omitempty"` // Subnetwork: The name of the Google Compute Engine // [subnetwork](/compute/docs/subnetworks) to which the cluster is // connected. Subnetwork string `json:"subnetwork,omitempty"` // Zone: [Output only] The name of the Google Compute Engine // [zone](/compute/docs/zones#available) in which the cluster resides. Zone string `json:"zone,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "AddonsConfig") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Cluster) MarshalJSON() ([]byte, error) { type noMethod Cluster raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // ClusterUpdate: ClusterUpdate describes an update to the cluster. // Exactly one update can be applied to a cluster with each request, so // at most one field can be provided. type ClusterUpdate struct { // DesiredAddonsConfig: Configurations for the various addons available // to run in the cluster. DesiredAddonsConfig *AddonsConfig `json:"desiredAddonsConfig,omitempty"` // DesiredMasterVersion: The Kubernetes version to change the master to. // The only valid value is the latest supported version. Use "-" to have // the server automatically select the latest version. DesiredMasterVersion string `json:"desiredMasterVersion,omitempty"` // DesiredMonitoringService: The monitoring service the cluster should // use to write metrics. Currently available options: * // "monitoring.googleapis.com" - the Google Cloud Monitoring service * // "none" - no metrics will be exported from the cluster DesiredMonitoringService string `json:"desiredMonitoringService,omitempty"` // DesiredNodePoolId: The node pool to be upgraded. This field is // mandatory if the "desired_node_version" or "desired_image_family" is // specified and there is more than one node pool on the cluster. DesiredNodePoolId string `json:"desiredNodePoolId,omitempty"` // DesiredNodeVersion: The Kubernetes version to change the nodes to // (typically an upgrade). Use `-` to upgrade to the latest version // supported by the server. DesiredNodeVersion string `json:"desiredNodeVersion,omitempty"` // ForceSendFields is a list of field names (e.g. "DesiredAddonsConfig") // to unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ClusterUpdate) MarshalJSON() ([]byte, error) { type noMethod ClusterUpdate raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // CreateClusterRequest: CreateClusterRequest creates a cluster. type CreateClusterRequest struct { // Cluster: A [cluster // resource](/container-engine/reference/rest/v1/projects.zones.clusters) Cluster *Cluster `json:"cluster,omitempty"` // ForceSendFields is a list of field names (e.g. "Cluster") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *CreateClusterRequest) MarshalJSON() ([]byte, error) { type noMethod CreateClusterRequest raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // CreateNodePoolRequest: CreateNodePoolRequest creates a node pool for // a cluster. type CreateNodePoolRequest struct { // NodePool: The node pool to create. NodePool *NodePool `json:"nodePool,omitempty"` // ForceSendFields is a list of field names (e.g. "NodePool") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *CreateNodePoolRequest) MarshalJSON() ([]byte, error) { type noMethod CreateNodePoolRequest raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // HorizontalPodAutoscaling: Configuration options for the horizontal // pod autoscaling feature, which increases or decreases the number of // replica pods a replication controller has based on the resource usage // of the existing pods. type HorizontalPodAutoscaling struct { // Disabled: Whether the Horizontal Pod Autoscaling feature is enabled // in the cluster. When enabled, it ensures that a Heapster pod is // running in the cluster, which is also used by the Cloud Monitoring // service. Disabled bool `json:"disabled,omitempty"` // ForceSendFields is a list of field names (e.g. "Disabled") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *HorizontalPodAutoscaling) MarshalJSON() ([]byte, error) { type noMethod HorizontalPodAutoscaling raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // HttpLoadBalancing: Configuration options for the HTTP (L7) load // balancing controller addon, which makes it easy to set up HTTP load // balancers for services in a cluster. type HttpLoadBalancing struct { // Disabled: Whether the HTTP Load Balancing controller is enabled in // the cluster. When enabled, it runs a small pod in the cluster that // manages the load balancers. Disabled bool `json:"disabled,omitempty"` // ForceSendFields is a list of field names (e.g. "Disabled") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *HttpLoadBalancing) MarshalJSON() ([]byte, error) { type noMethod HttpLoadBalancing raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // ListClustersResponse: ListClustersResponse is the result of // ListClustersRequest. type ListClustersResponse struct { // Clusters: A list of clusters in the project in the specified zone, or // across all ones. Clusters []*Cluster `json:"clusters,omitempty"` // MissingZones: If any zones are listed here, the list of clusters // returned may be missing those zones. MissingZones []string `json:"missingZones,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Clusters") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ListClustersResponse) MarshalJSON() ([]byte, error) { type noMethod ListClustersResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // ListNodePoolsResponse: ListNodePoolsResponse is the result of // ListNodePoolsRequest. type ListNodePoolsResponse struct { // NodePools: A list of node pools for a cluster. NodePools []*NodePool `json:"nodePools,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NodePools") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ListNodePoolsResponse) MarshalJSON() ([]byte, error) { type noMethod ListNodePoolsResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // ListOperationsResponse: ListOperationsResponse is the result of // ListOperationsRequest. type ListOperationsResponse struct { // MissingZones: If any zones are listed here, the list of operations // returned may be missing the operations from those zones. MissingZones []string `json:"missingZones,omitempty"` // Operations: A list of operations in the project in the specified // zone. Operations []*Operation `json:"operations,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "MissingZones") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *ListOperationsResponse) MarshalJSON() ([]byte, error) { type noMethod ListOperationsResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // MasterAuth: The authentication information for accessing the master // endpoint. Authentication can be done using HTTP basic auth or using // client certificates. type MasterAuth struct { // ClientCertificate: [Output only] Base64-encoded public certificate // used by clients to authenticate to the cluster endpoint. ClientCertificate string `json:"clientCertificate,omitempty"` // ClientKey: [Output only] Base64-encoded private key used by clients // to authenticate to the cluster endpoint. ClientKey string `json:"clientKey,omitempty"` // ClusterCaCertificate: [Output only] Base64-encoded public certificate // that is the root of trust for the cluster. ClusterCaCertificate string `json:"clusterCaCertificate,omitempty"` // Password: The password to use for HTTP basic authentication to the // master endpoint. Because the master endpoint is open to the Internet, // you should create a strong password. Password string `json:"password,omitempty"` // Username: The username to use for HTTP basic authentication to the // master endpoint. Username string `json:"username,omitempty"` // ForceSendFields is a list of field names (e.g. "ClientCertificate") // to unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *MasterAuth) MarshalJSON() ([]byte, error) { type noMethod MasterAuth raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // NodeConfig: Parameters that describe the nodes in a cluster. type NodeConfig struct { // DiskSizeGb: Size of the disk attached to each node, specified in GB. // The smallest allowed disk size is 10GB. If unspecified, the default // disk size is 100GB. DiskSizeGb int64 `json:"diskSizeGb,omitempty"` // MachineType: The name of a Google Compute Engine [machine // type](/compute/docs/machine-types) (e.g. `n1-standard-1`). If // unspecified, the default machine type is `n1-standard-1`. MachineType string `json:"machineType,omitempty"` // Metadata: The metadata key/value pairs assigned to instances in the // cluster. Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less // than 128 bytes in length. These are reflected as part of a URL in the // metadata server. Additionally, to avoid ambiguity, keys must not // conflict with any other metadata keys for the project or be one of // the four reserved keys: "instance-template", "kube-env", // "startup-script", and "user-data" Values are free-form strings, and // only have meaning as interpreted by the image running in the // instance. The only restriction placed on them is that each value's // size must be less than or equal to 32 KB. The total size of all keys // and values must be less than 512 KB. Metadata map[string]string `json:"metadata,omitempty"` // OauthScopes: The set of Google API scopes to be made available on all // of the node VMs under the "default" service account. The following // scopes are recommended, but not required, and by default are not // included: * `https://www.googleapis.com/auth/compute` is required for // mounting persistent storage on your nodes. * // `https://www.googleapis.com/auth/devstorage.read_only` is required // for communicating with **gcr.io** (the [Google Container // Registry](/container-registry/)). If unspecified, no scopes are // added, unless Cloud Logging or Cloud Monitoring are enabled, in which // case their required scopes will be added. OauthScopes []string `json:"oauthScopes,omitempty"` // ForceSendFields is a list of field names (e.g. "DiskSizeGb") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *NodeConfig) MarshalJSON() ([]byte, error) { type noMethod NodeConfig raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // NodePool: NodePool contains the name and configuration for a // cluster's node pool. Node pools are a set of nodes (i.e. VM's), with // a common configuration and specification, under the control of the // cluster master. They may have a set of Kubernetes labels applied to // them, which may be used to reference them during pod scheduling. They // may also be resized up or down, to accommodate the workload. type NodePool struct { // Config: The node configuration of the pool. Config *NodeConfig `json:"config,omitempty"` // InitialNodeCount: The initial node count for the pool. You must // ensure that your Compute Engine resource quota is sufficient for this // number of instances. You must also have available firewall and routes // quota. InitialNodeCount int64 `json:"initialNodeCount,omitempty"` // InstanceGroupUrls: [Output only] The resource URLs of [instance // groups](/compute/docs/instance-groups/) associated with this node // pool. InstanceGroupUrls []string `json:"instanceGroupUrls,omitempty"` // Name: The name of the node pool. Name string `json:"name,omitempty"` // SelfLink: Server-defined URL for the resource. SelfLink string `json:"selfLink,omitempty"` // Status: The status of the nodes in this pool instance. // // Possible values: // "STATUS_UNSPECIFIED" // "PROVISIONING" // "RUNNING" // "RUNNING_WITH_ERROR" // "RECONCILING" // "STOPPING" // "ERROR" Status string `json:"status,omitempty"` // StatusMessage: [Output only] Additional information about the current // status of this node pool instance, if available. StatusMessage string `json:"statusMessage,omitempty"` // Version: The version of the Kubernetes of this node. Version string `json:"version,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Config") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *NodePool) MarshalJSON() ([]byte, error) { type noMethod NodePool raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // Operation: This operation resource represents operations that may // have happened or are happening on the cluster. All fields are output // only. type Operation struct { // Detail: Detailed operation progress, if available. Detail string `json:"detail,omitempty"` // Name: The server-assigned ID for the operation. Name string `json:"name,omitempty"` // OperationType: The operation type. // // Possible values: // "TYPE_UNSPECIFIED" // "CREATE_CLUSTER" // "DELETE_CLUSTER" // "UPGRADE_MASTER" // "UPGRADE_NODES" // "REPAIR_CLUSTER" // "UPDATE_CLUSTER" // "CREATE_NODE_POOL" // "DELETE_NODE_POOL" OperationType string `json:"operationType,omitempty"` // SelfLink: Server-defined URL for the resource. SelfLink string `json:"selfLink,omitempty"` // Status: The current status of the operation. // // Possible values: // "STATUS_UNSPECIFIED" // "PENDING" // "RUNNING" // "DONE" Status string `json:"status,omitempty"` // StatusMessage: If an error has occurred, a textual description of the // error. StatusMessage string `json:"statusMessage,omitempty"` // TargetLink: Server-defined URL for the target of the operation. TargetLink string `json:"targetLink,omitempty"` // Zone: The name of the Google Compute Engine // [zone](/compute/docs/zones#available) in which the operation is // taking place. Zone string `json:"zone,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Detail") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *Operation) MarshalJSON() ([]byte, error) { type noMethod Operation raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // ServerConfig: Container Engine service configuration. type ServerConfig struct { // DefaultClusterVersion: Version of Kubernetes the service deploys by // default. DefaultClusterVersion string `json:"defaultClusterVersion,omitempty"` // DefaultImageFamily: Default image family. DefaultImageFamily string `json:"defaultImageFamily,omitempty"` // ValidImageFamilies: List of valid image families. ValidImageFamilies []string `json:"validImageFamilies,omitempty"` // ValidNodeVersions: List of valid node upgrade target versions. ValidNodeVersions []string `json:"validNodeVersions,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. // "DefaultClusterVersion") to unconditionally include in API requests. // By default, fields with empty values are omitted from API requests. // However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` } func (s *ServerConfig) MarshalJSON() ([]byte, error) { type noMethod ServerConfig raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // UpdateClusterRequest: UpdateClusterRequest updates the settings of a // cluster. type UpdateClusterRequest struct { // Update: A description of the update. Update *ClusterUpdate `json:"update,omitempty"` // ForceSendFields is a list of field names (e.g. "Update") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` } func (s *UpdateClusterRequest) MarshalJSON() ([]byte, error) { type noMethod UpdateClusterRequest raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields) } // method id "container.projects.zones.getServerconfig": type ProjectsZonesGetServerconfigCall struct { s *Service projectId string zone string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // GetServerconfig: Returns configuration info about the Container // Engine service. func (r *ProjectsZonesService) GetServerconfig(projectId string, zone string) *ProjectsZonesGetServerconfigCall { c := &ProjectsZonesGetServerconfigCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesGetServerconfigCall) Fields(s ...googleapi.Field) *ProjectsZonesGetServerconfigCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesGetServerconfigCall) IfNoneMatch(entityTag string) *ProjectsZonesGetServerconfigCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesGetServerconfigCall) Context(ctx context.Context) *ProjectsZonesGetServerconfigCall { c.ctx_ = ctx return c } func (c *ProjectsZonesGetServerconfigCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/serverconfig") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.getServerconfig" call. // Exactly one of *ServerConfig or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *ServerConfig.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesGetServerconfigCall) Do(opts ...googleapi.CallOption) (*ServerConfig, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ServerConfig{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Returns configuration info about the Container Engine service.", // "httpMethod": "GET", // "id": "container.projects.zones.getServerconfig", // "parameterOrder": [ // "projectId", // "zone" // ], // "parameters": { // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/serverconfig", // "response": { // "$ref": "ServerConfig" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.create": type ProjectsZonesClustersCreateCall struct { s *Service projectId string zone string createclusterrequest *CreateClusterRequest urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a cluster, consisting of the specified number and // type of Google Compute Engine instances. By default, the cluster is // created in the project's [default // network](/compute/docs/networks-and-firewalls#networks). One firewall // is added for the cluster. After cluster creation, the cluster creates // routes for each node to allow the containers on that node to // communicate with all other instances in the cluster. Finally, an // entry is added to the project's global metadata indicating which CIDR // range is being used by the cluster. func (r *ProjectsZonesClustersService) Create(projectId string, zone string, createclusterrequest *CreateClusterRequest) *ProjectsZonesClustersCreateCall { c := &ProjectsZonesClustersCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.createclusterrequest = createclusterrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersCreateCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersCreateCall) Context(ctx context.Context) *ProjectsZonesClustersCreateCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.createclusterrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.create" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a cluster, consisting of the specified number and type of Google Compute Engine instances. By default, the cluster is created in the project's [default network](/compute/docs/networks-and-firewalls#networks). One firewall is added for the cluster. After cluster creation, the cluster creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project's global metadata indicating which CIDR range is being used by the cluster.", // "httpMethod": "POST", // "id": "container.projects.zones.clusters.create", // "parameterOrder": [ // "projectId", // "zone" // ], // "parameters": { // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters", // "request": { // "$ref": "CreateClusterRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.delete": type ProjectsZonesClustersDeleteCall struct { s *Service projectId string zone string clusterId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes the cluster, including the Kubernetes endpoint and // all worker nodes. Firewalls and routes that were configured during // cluster creation are also deleted. Other Google Compute Engine // resources that might be in use by the cluster (e.g. load balancer // resources) will not be deleted if they weren't present at the initial // create time. func (r *ProjectsZonesClustersService) Delete(projectId string, zone string, clusterId string) *ProjectsZonesClustersDeleteCall { c := &ProjectsZonesClustersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersDeleteCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersDeleteCall) Context(ctx context.Context) *ProjectsZonesClustersDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.delete" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resources that might be in use by the cluster (e.g. load balancer resources) will not be deleted if they weren't present at the initial create time.", // "httpMethod": "DELETE", // "id": "container.projects.zones.clusters.delete", // "parameterOrder": [ // "projectId", // "zone", // "clusterId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster to delete.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.get": type ProjectsZonesClustersGetCall struct { s *Service projectId string zone string clusterId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets the details of a specific cluster. func (r *ProjectsZonesClustersService) Get(projectId string, zone string, clusterId string) *ProjectsZonesClustersGetCall { c := &ProjectsZonesClustersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersGetCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesClustersGetCall) IfNoneMatch(entityTag string) *ProjectsZonesClustersGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersGetCall) Context(ctx context.Context) *ProjectsZonesClustersGetCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.get" call. // Exactly one of *Cluster or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Cluster.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsZonesClustersGetCall) Do(opts ...googleapi.CallOption) (*Cluster, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Cluster{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets the details of a specific cluster.", // "httpMethod": "GET", // "id": "container.projects.zones.clusters.get", // "parameterOrder": [ // "projectId", // "zone", // "clusterId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster to retrieve.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}", // "response": { // "$ref": "Cluster" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.list": type ProjectsZonesClustersListCall struct { s *Service projectId string zone string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists all clusters owned by a project in either the specified // zone or all zones. func (r *ProjectsZonesClustersService) List(projectId string, zone string) *ProjectsZonesClustersListCall { c := &ProjectsZonesClustersListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersListCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesClustersListCall) IfNoneMatch(entityTag string) *ProjectsZonesClustersListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersListCall) Context(ctx context.Context) *ProjectsZonesClustersListCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.list" call. // Exactly one of *ListClustersResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListClustersResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsZonesClustersListCall) Do(opts ...googleapi.CallOption) (*ListClustersResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListClustersResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists all clusters owned by a project in either the specified zone or all zones.", // "httpMethod": "GET", // "id": "container.projects.zones.clusters.list", // "parameterOrder": [ // "projectId", // "zone" // ], // "parameters": { // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides, or \"-\" for all zones.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters", // "response": { // "$ref": "ListClustersResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.update": type ProjectsZonesClustersUpdateCall struct { s *Service projectId string zone string clusterId string updateclusterrequest *UpdateClusterRequest urlParams_ gensupport.URLParams ctx_ context.Context } // Update: Updates the settings of a specific cluster. func (r *ProjectsZonesClustersService) Update(projectId string, zone string, clusterId string, updateclusterrequest *UpdateClusterRequest) *ProjectsZonesClustersUpdateCall { c := &ProjectsZonesClustersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId c.updateclusterrequest = updateclusterrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersUpdateCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersUpdateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersUpdateCall) Context(ctx context.Context) *ProjectsZonesClustersUpdateCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.updateclusterrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("PUT", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.update" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersUpdateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Updates the settings of a specific cluster.", // "httpMethod": "PUT", // "id": "container.projects.zones.clusters.update", // "parameterOrder": [ // "projectId", // "zone", // "clusterId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster to upgrade.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}", // "request": { // "$ref": "UpdateClusterRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.nodePools.create": type ProjectsZonesClustersNodePoolsCreateCall struct { s *Service projectId string zone string clusterId string createnodepoolrequest *CreateNodePoolRequest urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a node pool for a cluster. func (r *ProjectsZonesClustersNodePoolsService) Create(projectId string, zone string, clusterId string, createnodepoolrequest *CreateNodePoolRequest) *ProjectsZonesClustersNodePoolsCreateCall { c := &ProjectsZonesClustersNodePoolsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId c.createnodepoolrequest = createnodepoolrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersNodePoolsCreateCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersNodePoolsCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersNodePoolsCreateCall) Context(ctx context.Context) *ProjectsZonesClustersNodePoolsCreateCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersNodePoolsCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.createnodepoolrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.nodePools.create" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersNodePoolsCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a node pool for a cluster.", // "httpMethod": "POST", // "id": "container.projects.zones.clusters.nodePools.create", // "parameterOrder": [ // "projectId", // "zone", // "clusterId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools", // "request": { // "$ref": "CreateNodePoolRequest" // }, // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.nodePools.delete": type ProjectsZonesClustersNodePoolsDeleteCall struct { s *Service projectId string zone string clusterId string nodePoolId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a node pool from a cluster. func (r *ProjectsZonesClustersNodePoolsService) Delete(projectId string, zone string, clusterId string, nodePoolId string) *ProjectsZonesClustersNodePoolsDeleteCall { c := &ProjectsZonesClustersNodePoolsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId c.nodePoolId = nodePoolId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersNodePoolsDeleteCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersNodePoolsDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersNodePoolsDeleteCall) Context(ctx context.Context) *ProjectsZonesClustersNodePoolsDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersNodePoolsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, "nodePoolId": c.nodePoolId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.nodePools.delete" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersNodePoolsDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a node pool from a cluster.", // "httpMethod": "DELETE", // "id": "container.projects.zones.clusters.nodePools.delete", // "parameterOrder": [ // "projectId", // "zone", // "clusterId", // "nodePoolId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster.", // "location": "path", // "required": true, // "type": "string" // }, // "nodePoolId": { // "description": "The name of the node pool to delete.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.nodePools.get": type ProjectsZonesClustersNodePoolsGetCall struct { s *Service projectId string zone string clusterId string nodePoolId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Retrieves the node pool requested. func (r *ProjectsZonesClustersNodePoolsService) Get(projectId string, zone string, clusterId string, nodePoolId string) *ProjectsZonesClustersNodePoolsGetCall { c := &ProjectsZonesClustersNodePoolsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId c.nodePoolId = nodePoolId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersNodePoolsGetCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersNodePoolsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesClustersNodePoolsGetCall) IfNoneMatch(entityTag string) *ProjectsZonesClustersNodePoolsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersNodePoolsGetCall) Context(ctx context.Context) *ProjectsZonesClustersNodePoolsGetCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersNodePoolsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, "nodePoolId": c.nodePoolId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.nodePools.get" call. // Exactly one of *NodePool or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *NodePool.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesClustersNodePoolsGetCall) Do(opts ...googleapi.CallOption) (*NodePool, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &NodePool{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Retrieves the node pool requested.", // "httpMethod": "GET", // "id": "container.projects.zones.clusters.nodePools.get", // "parameterOrder": [ // "projectId", // "zone", // "clusterId", // "nodePoolId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster.", // "location": "path", // "required": true, // "type": "string" // }, // "nodePoolId": { // "description": "The name of the node pool.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools/{nodePoolId}", // "response": { // "$ref": "NodePool" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.clusters.nodePools.list": type ProjectsZonesClustersNodePoolsListCall struct { s *Service projectId string zone string clusterId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists the node pools for a cluster. func (r *ProjectsZonesClustersNodePoolsService) List(projectId string, zone string, clusterId string) *ProjectsZonesClustersNodePoolsListCall { c := &ProjectsZonesClustersNodePoolsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.clusterId = clusterId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesClustersNodePoolsListCall) Fields(s ...googleapi.Field) *ProjectsZonesClustersNodePoolsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesClustersNodePoolsListCall) IfNoneMatch(entityTag string) *ProjectsZonesClustersNodePoolsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesClustersNodePoolsListCall) Context(ctx context.Context) *ProjectsZonesClustersNodePoolsListCall { c.ctx_ = ctx return c } func (c *ProjectsZonesClustersNodePoolsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "clusterId": c.clusterId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.clusters.nodePools.list" call. // Exactly one of *ListNodePoolsResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListNodePoolsResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsZonesClustersNodePoolsListCall) Do(opts ...googleapi.CallOption) (*ListNodePoolsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListNodePoolsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists the node pools for a cluster.", // "httpMethod": "GET", // "id": "container.projects.zones.clusters.nodePools.list", // "parameterOrder": [ // "projectId", // "zone", // "clusterId" // ], // "parameters": { // "clusterId": { // "description": "The name of the cluster.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}/nodePools", // "response": { // "$ref": "ListNodePoolsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.operations.get": type ProjectsZonesOperationsGetCall struct { s *Service projectId string zone string operationId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets the specified operation. func (r *ProjectsZonesOperationsService) Get(projectId string, zone string, operationId string) *ProjectsZonesOperationsGetCall { c := &ProjectsZonesOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone c.operationId = operationId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesOperationsGetCall) Fields(s ...googleapi.Field) *ProjectsZonesOperationsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesOperationsGetCall) IfNoneMatch(entityTag string) *ProjectsZonesOperationsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesOperationsGetCall) Context(ctx context.Context) *ProjectsZonesOperationsGetCall { c.ctx_ = ctx return c } func (c *ProjectsZonesOperationsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/operations/{operationId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, "operationId": c.operationId, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.operations.get" call. // Exactly one of *Operation or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *Operation.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsZonesOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Operation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets the specified operation.", // "httpMethod": "GET", // "id": "container.projects.zones.operations.get", // "parameterOrder": [ // "projectId", // "zone", // "operationId" // ], // "parameters": { // "operationId": { // "description": "The server-assigned `name` of the operation.", // "location": "path", // "required": true, // "type": "string" // }, // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/operations/{operationId}", // "response": { // "$ref": "Operation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "container.projects.zones.operations.list": type ProjectsZonesOperationsListCall struct { s *Service projectId string zone string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists all operations in a project in a specific zone or all // zones. func (r *ProjectsZonesOperationsService) List(projectId string, zone string) *ProjectsZonesOperationsListCall { c := &ProjectsZonesOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectId = projectId c.zone = zone return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsZonesOperationsListCall) Fields(s ...googleapi.Field) *ProjectsZonesOperationsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsZonesOperationsListCall) IfNoneMatch(entityTag string) *ProjectsZonesOperationsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsZonesOperationsListCall) Context(ctx context.Context) *ProjectsZonesOperationsListCall { c.ctx_ = ctx return c } func (c *ProjectsZonesOperationsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1/projects/{projectId}/zones/{zone}/operations") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectId": c.projectId, "zone": c.zone, }) if c.ctx_ != nil { return ctxhttp.Do(c.ctx_, c.s.client, req) } return c.s.client.Do(req) } // Do executes the "container.projects.zones.operations.list" call. // Exactly one of *ListOperationsResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListOperationsResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsZonesOperationsListCall) Do(opts ...googleapi.CallOption) (*ListOperationsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListOperationsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists all operations in a project in a specific zone or all zones.", // "httpMethod": "GET", // "id": "container.projects.zones.operations.list", // "parameterOrder": [ // "projectId", // "zone" // ], // "parameters": { // "projectId": { // "description": "The Google Developers Console [project ID or project number](https://support.google.com/cloud/answer/6158840).", // "location": "path", // "required": true, // "type": "string" // }, // "zone": { // "description": "The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or `-` for all zones.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1/projects/{projectId}/zones/{zone}/operations", // "response": { // "$ref": "ListOperationsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } }
apache-2.0
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/VcsConfigurationChangeListener.java
1059
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.messages.Topic; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public interface VcsConfigurationChangeListener { Topic<Notification> BRANCHES_CHANGED = new Topic<>("branch mapping changed", Notification.class); Topic<DetailedNotification> BRANCHES_CHANGED_RESPONSE = new Topic<>("branch mapping changed (detailed)", DetailedNotification.class); interface Notification { void execute(@NotNull Project project, @NotNull VirtualFile vcsRoot); } interface DetailedNotification { void execute(@NotNull Project project, @Nullable VirtualFile vcsRoot, @NotNull List<CommittedChangeList> cachedList); } }
apache-2.0
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/data/request/GithubLabelsCollectionRequest.java
537
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.data.request; import org.jetbrains.annotations.NotNull; import java.util.Collection; @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) public class GithubLabelsCollectionRequest { @NotNull private final Collection<String> labels; public GithubLabelsCollectionRequest(@NotNull Collection<String> labels) { this.labels = labels; } }
apache-2.0
adessaigne/camel
core/camel-core/src/test/java/org/apache/camel/impl/StartStopAndShutdownRouteTest.java
2308
/* * 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.camel.impl; import org.apache.camel.ContextTestSupport; import org.apache.camel.Route; import org.apache.camel.builder.RouteBuilder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; /** * This test stops a route, mutates it then restarts it */ public class StartStopAndShutdownRouteTest extends ContextTestSupport { @Test public void testStartStopAndShutdownRoute() throws Exception { // there should still be 2 services on the route Route myRoute = context.getRoute("foo"); int services = myRoute.getServices().size(); assertTrue(services > 0); // stop the route context.getRouteController().stopRoute("foo"); // there should still be the same number of services on the route assertEquals(services, myRoute.getServices().size()); // shutting down the route, by stop and remove context.getRouteController().stopRoute("foo"); context.removeRoute("foo"); // and now no more services as the route is shutdown assertEquals(0, myRoute.getServices().size()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("foo").to("mock:foo"); } }; } }
apache-2.0
Kwangseob/graphhopper-ios
dependencies/trove/src/gnu/trove/impl/sync/TSynchronizedCharCollection.java
4841
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 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 General Public License for more details. // // You should have received a copy of the GNU Lesser 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. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronizedCharCollection implements TCharCollection, Serializable { private static final long serialVersionUID = 3053995032091335093L; final TCharCollection c; // Backing Collection final Object mutex; // Object on which to synchronize public TSynchronizedCharCollection( TCharCollection c ) { if ( c == null ) throw new NullPointerException(); this.c = c; mutex = this; } public TSynchronizedCharCollection( TCharCollection c, Object mutex ) { this.c = c; this.mutex = mutex; } public int size() { synchronized( mutex ) { return c.size(); } } public boolean isEmpty() { synchronized( mutex ) { return c.isEmpty(); } } public boolean contains( char o ) { synchronized( mutex ) { return c.contains( o ); } } public char[] toArray() { synchronized( mutex ) { return c.toArray(); } } public char[] toArray( char[] a ) { synchronized( mutex ) { return c.toArray( a ); } } public TCharIterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add( char e ) { synchronized (mutex ) { return c.add( e ); } } public boolean remove( char o ) { synchronized( mutex ) { return c.remove( o ); } } public boolean containsAll( Collection<?> coll ) { synchronized( mutex ) { return c.containsAll( coll );} } public boolean containsAll( TCharCollection coll ) { synchronized( mutex ) { return c.containsAll( coll );} } public boolean containsAll( char[] array ) { synchronized( mutex ) { return c.containsAll( array );} } public boolean addAll( Collection<? extends Character> coll ) { synchronized( mutex ) { return c.addAll( coll ); } } public boolean addAll( TCharCollection coll ) { synchronized( mutex ) { return c.addAll( coll ); } } public boolean addAll( char[] array ) { synchronized( mutex ) { return c.addAll( array ); } } public boolean removeAll( Collection<?> coll ) { synchronized( mutex ) { return c.removeAll( coll ); } } public boolean removeAll( TCharCollection coll ) { synchronized( mutex ) { return c.removeAll( coll ); } } public boolean removeAll( char[] array ) { synchronized( mutex ) { return c.removeAll( array ); } } public boolean retainAll( Collection<?> coll ) { synchronized( mutex ) { return c.retainAll( coll ); } } public boolean retainAll( TCharCollection coll ) { synchronized( mutex ) { return c.retainAll( coll ); } } public boolean retainAll( char[] array ) { synchronized( mutex ) { return c.retainAll( array ); } } public char getNoEntryValue() { return c.getNoEntryValue(); } public boolean forEach( TCharProcedure procedure ) { synchronized( mutex ) { return c.forEach( procedure ); } } public void clear() { synchronized( mutex ) { c.clear(); } } public String toString() { synchronized( mutex ) { return c.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } }
apache-2.0
lvdongr/spark
common/unsafe/src/test/java/org/apache/spark/unsafe/memory/MemoryBlockSuite.java
6238
/* * 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.unsafe.memory; import org.apache.spark.unsafe.Platform; import org.junit.Assert; import org.junit.Test; import java.nio.ByteOrder; import static org.hamcrest.core.StringContains.containsString; public class MemoryBlockSuite { private static final boolean bigEndianPlatform = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN); private void check(MemoryBlock memory, Object obj, long offset, int length) { memory.setPageNumber(1); memory.fill((byte)-1); memory.putBoolean(0, true); memory.putByte(1, (byte)127); memory.putShort(2, (short)257); memory.putInt(4, 0x20000002); memory.putLong(8, 0x1234567089ABCDEFL); memory.putFloat(16, 1.0F); memory.putLong(20, 0x1234567089ABCDEFL); memory.putDouble(28, 2.0); MemoryBlock.copyMemory(memory, 0L, memory, 36, 4); int[] a = new int[2]; a[0] = 0x12345678; a[1] = 0x13579BDF; memory.copyFrom(a, Platform.INT_ARRAY_OFFSET, 40, 8); byte[] b = new byte[8]; memory.writeTo(40, b, Platform.BYTE_ARRAY_OFFSET, 8); Assert.assertEquals(obj, memory.getBaseObject()); Assert.assertEquals(offset, memory.getBaseOffset()); Assert.assertEquals(length, memory.size()); Assert.assertEquals(1, memory.getPageNumber()); Assert.assertEquals(true, memory.getBoolean(0)); Assert.assertEquals((byte)127, memory.getByte(1 )); Assert.assertEquals((short)257, memory.getShort(2)); Assert.assertEquals(0x20000002, memory.getInt(4)); Assert.assertEquals(0x1234567089ABCDEFL, memory.getLong(8)); Assert.assertEquals(1.0F, memory.getFloat(16), 0); Assert.assertEquals(0x1234567089ABCDEFL, memory.getLong(20)); Assert.assertEquals(2.0, memory.getDouble(28), 0); Assert.assertEquals(true, memory.getBoolean(36)); Assert.assertEquals((byte)127, memory.getByte(37 )); Assert.assertEquals((short)257, memory.getShort(38)); Assert.assertEquals(a[0], memory.getInt(40)); Assert.assertEquals(a[1], memory.getInt(44)); if (bigEndianPlatform) { Assert.assertEquals(a[0], ((int)b[0] & 0xff) << 24 | ((int)b[1] & 0xff) << 16 | ((int)b[2] & 0xff) << 8 | ((int)b[3] & 0xff)); Assert.assertEquals(a[1], ((int)b[4] & 0xff) << 24 | ((int)b[5] & 0xff) << 16 | ((int)b[6] & 0xff) << 8 | ((int)b[7] & 0xff)); } else { Assert.assertEquals(a[0], ((int)b[3] & 0xff) << 24 | ((int)b[2] & 0xff) << 16 | ((int)b[1] & 0xff) << 8 | ((int)b[0] & 0xff)); Assert.assertEquals(a[1], ((int)b[7] & 0xff) << 24 | ((int)b[6] & 0xff) << 16 | ((int)b[5] & 0xff) << 8 | ((int)b[4] & 0xff)); } for (int i = 48; i < memory.size(); i++) { Assert.assertEquals((byte) -1, memory.getByte(i)); } assert(memory.subBlock(0, memory.size()) == memory); try { memory.subBlock(-8, 8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("non-negative")); } try { memory.subBlock(0, -8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("non-negative")); } try { memory.subBlock(0, length + 8); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } try { memory.subBlock(8, length - 4); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } try { memory.subBlock(length + 8, 4); Assert.fail(); } catch (Exception expected) { Assert.assertThat(expected.getMessage(), containsString("should not be larger than")); } memory.setPageNumber(MemoryBlock.NO_PAGE_NUMBER); } @Test public void testByteArrayMemoryBlock() { byte[] obj = new byte[56]; long offset = Platform.BYTE_ARRAY_OFFSET; int length = obj.length; MemoryBlock memory = new ByteArrayMemoryBlock(obj, offset, length); check(memory, obj, offset, length); memory = ByteArrayMemoryBlock.fromArray(obj); check(memory, obj, offset, length); obj = new byte[112]; memory = new ByteArrayMemoryBlock(obj, offset, length); check(memory, obj, offset, length); } @Test public void testOnHeapMemoryBlock() { long[] obj = new long[7]; long offset = Platform.LONG_ARRAY_OFFSET; int length = obj.length * 8; MemoryBlock memory = new OnHeapMemoryBlock(obj, offset, length); check(memory, obj, offset, length); memory = OnHeapMemoryBlock.fromArray(obj); check(memory, obj, offset, length); obj = new long[14]; memory = new OnHeapMemoryBlock(obj, offset, length); check(memory, obj, offset, length); } @Test public void testOffHeapArrayMemoryBlock() { MemoryAllocator memoryAllocator = new UnsafeMemoryAllocator(); MemoryBlock memory = memoryAllocator.allocate(56); Object obj = memory.getBaseObject(); long offset = memory.getBaseOffset(); int length = 56; check(memory, obj, offset, length); memoryAllocator.free(memory); long address = Platform.allocateMemory(112); memory = new OffHeapMemoryBlock(address, length); obj = memory.getBaseObject(); offset = memory.getBaseOffset(); check(memory, obj, offset, length); Platform.freeMemory(address); } }
apache-2.0
sae-bom/rust
src/libstd/sync/mutex.rs
18111
// Copyright 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. use prelude::v1::*; use cell::UnsafeCell; use fmt; use marker; use ops::{Deref, DerefMut}; use sys_common::mutex as sys; use sys_common::poison::{self, TryLockError, TryLockResult, LockResult}; /// A mutual exclusion primitive useful for protecting shared data /// /// This mutex will block threads waiting for the lock to become available. The /// mutex can also be statically initialized or created via a `new` /// constructor. Each mutex has a type parameter which represents the data that /// it is protecting. The data can only be accessed through the RAII guards /// returned from `lock` and `try_lock`, which guarantees that the data is only /// ever accessed when the mutex is locked. /// /// # Poisoning /// /// The mutexes in this module implement a strategy called "poisoning" where a /// mutex is considered poisoned whenever a thread panics while holding the /// lock. Once a mutex is poisoned, all other threads are unable to access the /// data by default as it is likely tainted (some invariant is not being /// upheld). /// /// For a mutex, this means that the `lock` and `try_lock` methods return a /// `Result` which indicates whether a mutex has been poisoned or not. Most /// usage of a mutex will simply `unwrap()` these results, propagating panics /// among threads to ensure that a possibly invalid invariant is not witnessed. /// /// A poisoned mutex, however, does not prevent all access to the underlying /// data. The `PoisonError` type has an `into_inner` method which will return /// the guard that would have otherwise been returned on a successful lock. This /// allows access to the data, despite the lock being poisoned. /// /// # Examples /// /// ``` /// use std::sync::{Arc, Mutex}; /// use std::thread; /// use std::sync::mpsc::channel; /// /// const N: usize = 10; /// /// // Spawn a few threads to increment a shared variable (non-atomically), and /// // let the main thread know once all increments are done. /// // /// // Here we're using an Arc to share memory among threads, and the data inside /// // the Arc is protected with a mutex. /// let data = Arc::new(Mutex::new(0)); /// /// let (tx, rx) = channel(); /// for _ in 0..10 { /// let (data, tx) = (data.clone(), tx.clone()); /// thread::spawn(move || { /// // The shared static can only be accessed once the lock is held. /// // Our non-atomic increment is safe because we're the only thread /// // which can access the shared state when the lock is held. /// // /// // We unwrap() the return value to assert that we are not expecting /// // threads to ever fail while holding the lock. /// let mut data = data.lock().unwrap(); /// *data += 1; /// if *data == N { /// tx.send(()).unwrap(); /// } /// // the lock is unlocked here when `data` goes out of scope. /// }); /// } /// /// rx.recv().unwrap(); /// ``` /// /// To recover from a poisoned mutex: /// /// ``` /// # #![feature(std_misc)] /// use std::sync::{Arc, Mutex}; /// use std::thread; /// /// let lock = Arc::new(Mutex::new(0_u32)); /// let lock2 = lock.clone(); /// /// let _ = thread::spawn(move || -> () { /// // This thread will acquire the mutex first, unwrapping the result of /// // `lock` because the lock has not been poisoned. /// let _lock = lock2.lock().unwrap(); /// /// // This panic while holding the lock (`_guard` is in scope) will poison /// // the mutex. /// panic!(); /// }).join(); /// /// // The lock is poisoned by this point, but the returned result can be /// // pattern matched on to return the underlying guard on both branches. /// let mut guard = match lock.lock() { /// Ok(guard) => guard, /// Err(poisoned) => poisoned.into_inner(), /// }; /// /// *guard += 1; /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub struct Mutex<T: ?Sized> { // Note that this static mutex is in a *box*, not inlined into the struct // itself. Once a native mutex has been used once, its address can never // change (it can't be moved). This mutex type can be safely moved at any // time, so to ensure that the native mutex is used correctly we box the // inner lock to give it a constant address. inner: Box<StaticMutex>, data: UnsafeCell<T>, } // these are the only places where `T: Send` matters; all other // functionality works fine on a single thread. unsafe impl<T: ?Sized + Send> Send for Mutex<T> { } unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { } /// The static mutex type is provided to allow for static allocation of mutexes. /// /// Note that this is a separate type because using a Mutex correctly means that /// it needs to have a destructor run. In Rust, statics are not allowed to have /// destructors. As a result, a `StaticMutex` has one extra method when compared /// to a `Mutex`, a `destroy` method. This method is unsafe to call, and /// documentation can be found directly on the method. /// /// # Examples /// /// ``` /// # #![feature(std_misc)] /// use std::sync::{StaticMutex, MUTEX_INIT}; /// /// static LOCK: StaticMutex = MUTEX_INIT; /// /// { /// let _g = LOCK.lock().unwrap(); /// // do some productive work /// } /// // lock is unlocked here. /// ``` #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub struct StaticMutex { lock: sys::Mutex, poison: poison::Flag, } /// An RAII implementation of a "scoped lock" of a mutex. When this structure is /// dropped (falls out of scope), the lock will be unlocked. /// /// The data protected by the mutex can be access through this guard via its /// `Deref` and `DerefMut` implementations #[must_use] #[stable(feature = "rust1", since = "1.0.0")] pub struct MutexGuard<'a, T: ?Sized + 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). __lock: &'a StaticMutex, __data: &'a UnsafeCell<T>, __poison: poison::Guard, } impl<'a, T: ?Sized> !marker::Send for MutexGuard<'a, T> {} /// Static initialization of a mutex. This constant can be used to initialize /// other mutex constants. #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub const MUTEX_INIT: StaticMutex = StaticMutex::new(); impl<T> Mutex<T> { /// Creates a new mutex in an unlocked state ready for use. #[stable(feature = "rust1", since = "1.0.0")] pub fn new(t: T) -> Mutex<T> { Mutex { inner: box StaticMutex::new(), data: UnsafeCell::new(t), } } } impl<T: ?Sized> Mutex<T> { /// Acquires a mutex, blocking the current thread until it is able to do so. /// /// This function will block the local thread until it is available to acquire /// the mutex. Upon returning, the thread is the only thread with the mutex /// held. An RAII guard is returned to allow scoped unlock of the lock. When /// the guard goes out of scope, the mutex will be unlocked. /// /// # Failure /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return an error once the mutex is acquired. #[stable(feature = "rust1", since = "1.0.0")] pub fn lock(&self) -> LockResult<MutexGuard<T>> { unsafe { self.inner.lock.lock() } MutexGuard::new(&*self.inner, &self.data) } /// Attempts to acquire this lock. /// /// If the lock could not be acquired at this time, then `Err` is returned. /// Otherwise, an RAII guard is returned. The lock will be unlocked when the /// guard is dropped. /// /// This function does not block. /// /// # Failure /// /// If another user of this mutex panicked while holding the mutex, then /// this call will return failure if the mutex would otherwise be /// acquired. #[stable(feature = "rust1", since = "1.0.0")] pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> { if unsafe { self.inner.lock.try_lock() } { Ok(try!(MutexGuard::new(&*self.inner, &self.data))) } else { Err(TryLockError::WouldBlock) } } /// Determines whether the lock is poisoned. /// /// If another thread is active, the lock can still become poisoned at any /// time. You should not trust a `false` value for program correctness /// without additional synchronization. #[inline] #[unstable(feature = "std_misc")] pub fn is_poisoned(&self) -> bool { self.inner.poison.get() } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized> Drop for Mutex<T> { fn drop(&mut self) { // This is actually safe b/c we know that there is no further usage of // this mutex (it's up to the user to arrange for a mutex to get // dropped, that's not our job) unsafe { self.inner.lock.destroy() } } } #[stable(feature = "rust1", since = "1.0.0")] impl<T: ?Sized + fmt::Debug + 'static> fmt::Debug for Mutex<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.try_lock() { Ok(guard) => write!(f, "Mutex {{ data: {:?} }}", &*guard), Err(TryLockError::Poisoned(err)) => { write!(f, "Mutex {{ data: Poisoned({:?}) }}", &**err.get_ref()) }, Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}") } } } struct Dummy(UnsafeCell<()>); unsafe impl Sync for Dummy {} static DUMMY: Dummy = Dummy(UnsafeCell::new(())); impl StaticMutex { /// Creates a new mutex in an unlocked state ready for use. #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub const fn new() -> StaticMutex { StaticMutex { lock: sys::Mutex::new(), poison: poison::Flag::new(), } } /// Acquires this lock, see `Mutex::lock` #[inline] #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub fn lock(&'static self) -> LockResult<MutexGuard<()>> { unsafe { self.lock.lock() } MutexGuard::new(self, &DUMMY.0) } /// Attempts to grab this lock, see `Mutex::try_lock` #[inline] #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> { if unsafe { self.lock.try_lock() } { Ok(try!(MutexGuard::new(self, &DUMMY.0))) } else { Err(TryLockError::WouldBlock) } } /// Deallocates resources associated with this static mutex. /// /// This method is unsafe because it provides no guarantees that there are /// no active users of this mutex, and safety is not guaranteed if there are /// active users of this mutex. /// /// This method is required to ensure that there are no memory leaks on /// *all* platforms. It may be the case that some platforms do not leak /// memory if this method is not called, but this is not guaranteed to be /// true on all platforms. #[unstable(feature = "std_misc", reason = "may be merged with Mutex in the future")] pub unsafe fn destroy(&'static self) { self.lock.destroy() } } impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>) -> LockResult<MutexGuard<'mutex, T>> { poison::map_result(lock.poison.borrow(), |guard| { MutexGuard { __lock: lock, __data: data, __poison: guard, } }) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> { type Target = T; fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__data.get() } } } #[stable(feature = "rust1", since = "1.0.0")] impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self.__data.get() } } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { #[inline] fn drop(&mut self) { unsafe { self.__lock.poison.done(&self.__poison); self.__lock.lock.unlock(); } } } pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { &guard.__lock.lock } pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { &guard.__lock.poison } #[cfg(test)] mod tests { use prelude::v1::*; use sync::mpsc::channel; use sync::{Arc, Mutex, StaticMutex, Condvar}; use thread; struct Packet<T: Send>(Arc<(Mutex<T>, Condvar)>); unsafe impl<T: Send> Send for Packet<T> {} unsafe impl<T> Sync for Packet<T> {} #[test] fn smoke() { let m = Mutex::new(()); drop(m.lock().unwrap()); drop(m.lock().unwrap()); } #[test] fn smoke_static() { static M: StaticMutex = StaticMutex::new(); unsafe { drop(M.lock().unwrap()); drop(M.lock().unwrap()); M.destroy(); } } #[test] fn lots_and_lots() { static M: StaticMutex = StaticMutex::new(); static mut CNT: u32 = 0; const J: u32 = 1000; const K: u32 = 3; fn inc() { for _ in 0..J { unsafe { let _g = M.lock().unwrap(); CNT += 1; } } } let (tx, rx) = channel(); for _ in 0..K { let tx2 = tx.clone(); thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }); } drop(tx); for _ in 0..2 * K { rx.recv().unwrap(); } assert_eq!(unsafe {CNT}, J * K * 2); unsafe { M.destroy(); } } #[test] fn try_lock() { let m = Mutex::new(()); *m.try_lock().unwrap() = (); } #[test] fn test_mutex_arc_condvar() { let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); let _t = thread::spawn(move|| { // wait until parent gets in rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let mut lock = lock.lock().unwrap(); *lock = true; cvar.notify_one(); }); let &(ref lock, ref cvar) = &*packet.0; let mut lock = lock.lock().unwrap(); tx.send(()).unwrap(); assert!(!*lock); while !*lock { lock = cvar.wait(lock).unwrap(); } } #[test] fn test_arc_condvar_poison() { let packet = Packet(Arc::new((Mutex::new(1), Condvar::new()))); let packet2 = Packet(packet.0.clone()); let (tx, rx) = channel(); let _t = thread::spawn(move || -> () { rx.recv().unwrap(); let &(ref lock, ref cvar) = &*packet2.0; let _g = lock.lock().unwrap(); cvar.notify_one(); // Parent should fail when it wakes up. panic!(); }); let &(ref lock, ref cvar) = &*packet.0; let mut lock = lock.lock().unwrap(); tx.send(()).unwrap(); while *lock == 1 { match cvar.wait(lock) { Ok(l) => { lock = l; assert_eq!(*lock, 1); } Err(..) => break, } } } #[test] fn test_mutex_arc_poison() { let arc = Arc::new(Mutex::new(1)); assert!(!arc.is_poisoned()); let arc2 = arc.clone(); let _ = thread::spawn(move|| { let lock = arc2.lock().unwrap(); assert_eq!(*lock, 2); }).join(); assert!(arc.lock().is_err()); assert!(arc.is_poisoned()); } #[test] fn test_mutex_arc_nested() { // Tests nested mutexes and access // to underlying data. let arc = Arc::new(Mutex::new(1)); let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); let _t = thread::spawn(move|| { let lock = arc2.lock().unwrap(); let lock2 = lock.lock().unwrap(); assert_eq!(*lock2, 1); tx.send(()).unwrap(); }); rx.recv().unwrap(); } #[test] fn test_mutex_arc_access_in_unwind() { let arc = Arc::new(Mutex::new(1)); let arc2 = arc.clone(); let _ = thread::spawn(move|| -> () { struct Unwinder { i: Arc<Mutex<i32>>, } impl Drop for Unwinder { fn drop(&mut self) { *self.i.lock().unwrap() += 1; } } let _u = Unwinder { i: arc2 }; panic!(); }).join(); let lock = arc.lock().unwrap(); assert_eq!(*lock, 2); } // FIXME(#25351) needs deeply nested coercions of DST structs. // #[test] // fn test_mutex_unsized() { // let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); // { // let b = &mut *mutex.lock().unwrap(); // b[0] = 4; // b[2] = 5; // } // let comp: &[i32] = &[4, 2, 5]; // assert_eq!(&*mutex.lock().unwrap(), comp); // } }
apache-2.0
crazyin2009/moquette-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/PubAckEvent.java
1093
/* * Copyright (c) 2012-2014 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dna.mqtt.moquette.messaging.spi.impl.events; /** * Used to send the ack message back to the client after a publish */ public class PubAckEvent extends MessagingEvent { int m_messageId; String m_clientID; public PubAckEvent(int messageID, String clientID) { m_messageId = messageID ; m_clientID = clientID; } public int getMessageId() { return m_messageId; } public String getClientID() { return m_clientID; } }
apache-2.0
pistol54/SaltarelleCompiler
Runtime/CoreLib.Script/TaskCompletionSource.js
1423
/////////////////////////////////////////////////////////////////////////////// // TaskCompletionSource var ss_TaskCompletionSource = function#? DEBUG TaskCompletionSource$##() { this.task = new ss_Task(); this.task.status = 3; }; ss_TaskCompletionSource.__typeName = 'ss.TaskCompletionSource'; ss.TaskCompletionSource = ss_TaskCompletionSource; ss.initClass(ss_TaskCompletionSource, ss, { setCanceled: function#? DEBUG TaskCompletionSource$setCanceled##() { if (!this.task._cancel()) throw new ss_InvalidOperationException('Task was already completed.'); }, setResult: function#? DEBUG TaskCompletionSource$setResult##(result) { if (!this.task._complete(result)) throw new ss_InvalidOperationException('Task was already completed.'); }, setException: function#? DEBUG TaskCompletionSource$setException##(exception) { if (!this.trySetException(exception)) throw new ss_InvalidOperationException('Task was already completed.'); }, trySetCanceled: function#? DEBUG TaskCompletionSource$trySetCanceled##() { return this.task._cancel(); }, trySetResult: function#? DEBUG TaskCompletionSource$setResult##(result) { return this.task._complete(result); }, trySetException: function#? DEBUG TaskCompletionSource$setException##(exception) { if (ss.isInstanceOfType(exception, ss_Exception)) exception = [exception]; return this.task._fail(new ss_AggregateException(null, exception)); } });
apache-2.0
uschindler/elasticsearch
server/src/main/java/org/elasticsearch/index/reindex/UpdateByQueryRequest.java
6106
/* * 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.index.reindex; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.tasks.TaskId; import java.io.IOException; /** * Request to update some documents. That means you can't change their type, id, index, or anything like that. This implements * CompositeIndicesRequest but in a misleading way. Rather than returning all the subrequests that it will make it tries to return a * representative set of subrequests. This is best-effort but better than {@linkplain ReindexRequest} because scripts can't change the * destination index and things. */ public class UpdateByQueryRequest extends AbstractBulkIndexByScrollRequest<UpdateByQueryRequest> implements IndicesRequest.Replaceable, ToXContentObject { /** * Ingest pipeline to set on index requests made by this action. */ private String pipeline; public UpdateByQueryRequest() { this(new SearchRequest()); } public UpdateByQueryRequest(String... indices) { this(new SearchRequest(indices)); } UpdateByQueryRequest(SearchRequest search) { this(search, true); } public UpdateByQueryRequest(StreamInput in) throws IOException { super(in); pipeline = in.readOptionalString(); } private UpdateByQueryRequest(SearchRequest search, boolean setDefaults) { super(search, setDefaults); } /** * Set the ingest pipeline to set on index requests made by this action. */ public UpdateByQueryRequest setPipeline(String pipeline) { this.pipeline = pipeline; return this; } /** * Set the query for selective update */ public UpdateByQueryRequest setQuery(QueryBuilder query) { if (query != null) { getSearchRequest().source().query(query); } return this; } /** * Set routing limiting the process to the shards that match that routing value */ public UpdateByQueryRequest setRouting(String routing) { if (routing != null) { getSearchRequest().routing(routing); } return this; } /** * The scroll size to control number of documents processed per batch */ public UpdateByQueryRequest setBatchSize(int size) { getSearchRequest().source().size(size); return this; } /** * Set the IndicesOptions for controlling unavailable indices */ public UpdateByQueryRequest setIndicesOptions(IndicesOptions indicesOptions) { getSearchRequest().indicesOptions(indicesOptions); return this; } /** * Gets the batch size for this request */ public int getBatchSize() { return getSearchRequest().source().size(); } /** * Gets the routing value used for this request */ public String getRouting() { return getSearchRequest().routing(); } /** * Ingest pipeline to set on index requests made by this action. */ public String getPipeline() { return pipeline; } @Override protected UpdateByQueryRequest self() { return this; } @Override public UpdateByQueryRequest forSlice(TaskId slicingTask, SearchRequest slice, int totalSlices) { UpdateByQueryRequest request = doForSlice(new UpdateByQueryRequest(slice, false), slicingTask, totalSlices); request.setPipeline(pipeline); return request; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("update-by-query "); searchToString(b); return b.toString(); } //update by query updates all documents that match a query. The indices and indices options that affect how //indices are resolved depend entirely on the inner search request. That's why the following methods delegate to it. @Override public IndicesRequest indices(String... indices) { assert getSearchRequest() != null; getSearchRequest().indices(indices); return this; } @Override public String[] indices() { assert getSearchRequest() != null; return getSearchRequest().indices(); } @Override public IndicesOptions indicesOptions() { assert getSearchRequest() != null; return getSearchRequest().indicesOptions(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(pipeline); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (getScript() != null) { builder.field("script"); getScript().toXContent(builder, params); } getSearchRequest().source().innerToXContent(builder, params); builder.endObject(); return builder; } }
apache-2.0
GunoH/intellij-community
platform/util/ui/src/com/intellij/util/ui/BlockBorder.java
3417
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui; import com.intellij.ui.Gray; import org.jetbrains.annotations.ApiStatus; import javax.swing.border.Border; import java.awt.*; /** @deprecated ancient HiDPI-unfriendly component */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.1") @SuppressWarnings({"UseDPIAwareInsets", "UseJBColor", "unused", "SpellCheckingInspection"}) public class BlockBorder implements Border { private static final Insets DEFAULT_INSETS = new Insets(1, 1, 3, 3); private static final Color DEFAULT_SHADE1 = Gray._203; private static final Color DEFAULT_SHADE2 = Gray._238; private static final Insets EMPTY = new Insets(0, 0, 0, 0); private final Insets myInsets; private final Insets myOuterMargin; private Color myBoundsColor = Color.GRAY; private final Color myShade1; private final Color myShade2; public BlockBorder() { this(null, null, DEFAULT_SHADE1, DEFAULT_SHADE2); } public BlockBorder(Insets outerMargin, Insets innerMargin) { this(outerMargin, innerMargin, DEFAULT_SHADE1, DEFAULT_SHADE2); } public BlockBorder(Insets outerMargin, Insets innerMargin, Color aShade1, Color aShade2) { if (outerMargin == null) { outerMargin = EMPTY; } myOuterMargin = (Insets)outerMargin.clone(); myInsets = (Insets)outerMargin.clone(); myInsets.top += DEFAULT_INSETS.top; myInsets.left += DEFAULT_INSETS.left; myInsets.bottom += DEFAULT_INSETS.bottom; myInsets.right += DEFAULT_INSETS.right; if (innerMargin == null) { innerMargin = EMPTY; } myInsets.top += innerMargin.top; myInsets.left += innerMargin.left; myInsets.bottom += innerMargin.bottom; myInsets.right += innerMargin.right; myShade1 = aShade1; myShade2 = aShade2; } @Override public boolean isBorderOpaque() { return true; } @Override public void paintBorder(Component component, Graphics g, int x, int y, int width, int height) { Graphics2D g2 = (Graphics2D)g; g2.setPaint(getBoundsColor()); int horMargin = myOuterMargin.left + myOuterMargin.right; int vertMargin = myOuterMargin.top + myOuterMargin.bottom; g2.drawRect(x + myOuterMargin.left, y + myOuterMargin.top, x + width - 3 - horMargin, y + height - 3 - vertMargin); g2.setPaint(myShade1); g2.drawLine(x + 1 + myOuterMargin.left, y + height - 2 - myOuterMargin.bottom, x + width - 2 - myOuterMargin.right, y + height - 2 - myOuterMargin.bottom); g2.drawLine(x + width - 2 - myOuterMargin.right, y + 1 + myOuterMargin.bottom, x + width - 2 - myOuterMargin.right, y + height - 2 - myOuterMargin.bottom); g2.setPaint(myShade2); g2.drawLine(x + 2 + myOuterMargin.left, y + height - 1 - myOuterMargin.bottom, x + width - 1 - myOuterMargin.right, y + height - 1 - myOuterMargin.bottom); g2.drawLine(x + width - 1 - myOuterMargin.right, y + 2 + myOuterMargin.top, x + width - 1 - myOuterMargin.right, y + height - 1 - myOuterMargin.bottom); } private Color getBoundsColor() { return myBoundsColor; } public void setBoundsColor(Color aColor) { myBoundsColor = aColor; } @Override public Insets getBorderInsets(Component component) { return (Insets)myInsets.clone(); } }
apache-2.0
tmagomedov/clBLAS
src/library/blas/functor/gcn_sgemm.cc
19182
#include <stdio.h> #include <string.h> #include <clBLAS.h> #include <devinfo.h> #include "clblas-internal.h" #include "solution_seq.h" #include <functor.h> #include <binary_lookup.h> #include <iostream> #include <functor_xgemm.h> #include <tahiti.h> #include <hawaii.h> #include <gcn_sgemm.h> #include "BinaryBuild.h" //for the moment only managing source code and cl binary #if BUILD_KERNEL_FROM_STRING #include "sgemm_gcn.clT" #else #include "sgemm_gcn.clHawaii_64.bin.clT" #include "sgemm_gcn.clBonaire_64.bin.clT" #include "sgemm_gcn.clTahiti_64.bin.clT" #endif // // The name of the 'const char *' providing the kernel OpenCL source // // dgemm_TATB_DIVN_DIVM_DIVK_BS0xBS1_NV0xNV1 // // For instance, DGEMM_SRC_NAME(N,T,32,64,8,8,8,4,8) is dgemm_NT_32_64_8_8x8_4x8 // #define SGEMM_SRC_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) sgemm_##TA##TB##_##DIVN##_##DIVM##_##DIVK##_##BS0##x##BS1##_##NV0##x##NV1##MULT #define SGEMM_SRC_NAME_TAHITI(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT) sgemm_##TA##TB##_##DIVN##_##DIVM##_##DIVK##_##BS0##x##BS1##_##NV0##x##NV1##MULT##_##BITS##_bin_Tahiti #define SGEMM_SRC_NAME_HAWAII(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT) sgemm_##TA##TB##_##DIVN##_##DIVM##_##DIVK##_##BS0##x##BS1##_##NV0##x##NV1##MULT##_##BITS##_bin_Hawaii #define SGEMM_SRC_NAME_BONAIRE(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT) sgemm_##TA##TB##_##DIVN##_##DIVM##_##DIVK##_##BS0##x##BS1##_##NV0##x##NV1##MULT##_##BITS##_bin_Bonaire // // The name of the 'const char []' global variable that contain the SPIR data. // That name is similar to the one produced by DGEMM_SRC_NAME but suffixed by _spir // #define SGEMM_SPIR_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) sgemm_##TA##TB##_##DIVN##_##DIVM##_##DIVK##_##BS0##x##BS1##_##NV0##x##NV1_spir // // The name of the 'const char []' global variable that contain the CL binaries data. // That name is similar to the one produced by DGEMM_SRC_NAME but suffixed by _bin // // The name of the kernel itself. // This is basically the name returned by DGEMM_SRC_NAME but as string // #define SGEMM_KERNEL_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) "sgemm_" #TA #TB "_" #DIVN "_" #DIVM "_" #DIVK "_" #BS0 "x" #BS1 "_" #NV0 "x" #NV1 #MULT // // Helpers to transform N and T in proper clblas values for the macros above // #define trans_N clblasNoTrans #define trans_T clblasTrans // Fill a variant descriptor using OpenCL source #define SGEMM_VARIANT_SRC(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) { \ SGEMM_KERNEL_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) , \ SGEMM_SRC_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) , \ NULL, NULL, 0, \ trans_##TA, trans_##TB, \ DIVN,DIVM,DIVK, \ { BS0, BS1 } , \ { NV0, NV1 } \ } // Fill a variant descriptor using SPIR #define SGEMM_VARIANT_SPIR(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) { \ SGEMM_KERNEL_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1) , \ NULL , "-x spir -spir-std=1.2" \ SGEMM_SPIR_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1), \ sizeof(SGEMM_SPIR_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1)), \ trans_##TA,trans_##TB, \ DIVN,DIVM,DIVK, \ { BS0, BS1 } , \ { NV0, NV1 } \ } // Fill a variant descriptor using CL Binaries #define SGEMM_VARIANT_BIN_CL1(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,DEVICE,MULT) { \ SGEMM_KERNEL_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) , \ NULL , NULL, \ SGEMM_SRC_NAME##_##DEVICE(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT), \ sizeof(SGEMM_SRC_NAME##_##DEVICE(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT)), \ trans_##TA,trans_##TB, \ DIVN,DIVM,DIVK, \ { BS0, BS1 } , \ { NV0, NV1 } \ } #define SGEMM_VARIANT_BIN_CL2(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,DEVICE,MULT) { \ SGEMM_KERNEL_NAME(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,MULT) , \ NULL , "-cl-std=CL2.0", \ SGEMM_SRC_NAME##_##DEVICE(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT), \ sizeof(SGEMM_SRC_NAME##_##DEVICE(TA,TB,DIVN,DIVM,DIVK,BS0,BS1,NV0,NV1,BITS,MULT)), \ trans_##TA,trans_##TB, \ DIVN,DIVM,DIVK, \ { BS0, BS1 } , \ { NV0, NV1 } \ } // Make it 1 to enable additional debug 'print' #define VERB 0 // Just because the full name is too long typedef clblasSgemmFunctorGCN::Variant Variant ; // // The static cache used to store all instances of clblasSgemmFunctorGCN // typedef clblasFunctorCache<clblasSgemmFunctorGCN,const Variant *> Cache ; static Cache cache ; // return true iff a kernel variant is applicable to the specified args static bool applicable( const Variant & var, clblasSgemmFunctor::Args & args ) { #if 0 // Transpose values are tested in select_variant if ( args.transA != var.transA ) return false ; if ( args.transB != var.transB ) return false ; #endif if ( args.N % var.divN != 0 ) return false ; if ( args.M % var.divM != 0 ) return false ; if ( args.K % var.divK != 0 ) return false ; if ( args.beta==0 && var.mult.compare("__ALPHA")!=0) return false ; return true ; } // // The goal of this function is to return the Variant to be used // for the DGEMM specified by 'args'. // // The variants are typically tested sequentially from the more // specific to the more generic. Additional conditions can be // placed into the surrounding 'if' (typically that would be // to perform additional tests on M, N and K). // // static const Variant * select_variant( clblasSgemmFunctor::Args & args, const char* DevName, cl_uint _64BitsUse ) { // if(_64BitsUse!=64) { std::cout<<"we don't support clblas on 32 bits"<< std::endl; assert(1); return NULL; } if ( args.transA == clblasNoTrans ) { if ( args.transB == clblasNoTrans ) { if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(N,N,96,96,16,16,16,6,6,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(N,N,96,96,16,16,16,6,6,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } //For GCN2 devices we will use the splitsgemm functor } if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(N,N,64,64,16,16,16,4,4,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(N,N,64,64,16,16,16,4,4,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Hawaii")) { #ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,N,64,64,16,16,16,4,4,64,HAWAII, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,N,64,64,16,16,16,4,4,64,HAWAII, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Bonaire")) { #ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,N,64,64,16,16,16,4,4,64,BONAIRE, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,N,64,64,16,16,16,4,4,64,BONAIRE, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL } } } else { // ===== sgemm NT ====== if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(N,T,96,96,16,16,16,6,6,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(N,T,96,96,16,16,16,6,6,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } //For GCN2 devices we will use the splitsgemm functor //else if(!strcmp(DevName, "Hawaii")) //{ // static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,T,96,96,16,16,16,6,6,64,HAWAII, __ALPHABETA) ; // if ( applicable(variant,args) ) // return &variant ; // static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,T,96,96,16,16,16,6,6,64,HAWAII, __ALPHA) ; // if ( applicable(variantA,args) ) // return &variantA ; //} //else if(!strcmp(DevName, "Bonaire")) //{ // static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,T,96,96,16,16,16,6,6,64,BONAIRE, __ALPHABETA) ; // if ( applicable(variant,args) ) // return &variant ; // static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,T,96,96,16,16,16,6,6,64,BONAIRE, __ALPHA) ; // if ( applicable(variantA,args) ) // return &variantA ; //} } if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(N,T,64,64,16,16,16,4,4,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(N,T,64,64,16,16,16,4,4,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Hawaii")) { #ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,T,64,64,16,16,16,4,4,64,HAWAII, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,T,64,64,16,16,16,4,4,64,HAWAII, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Bonaire")) { #ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(N,T,64,64,16,16,16,4,4,64,BONAIRE, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(N,T,64,64,16,16,16,4,4,64,BONAIRE, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL } } } } else { if ( args.transB == clblasNoTrans ) { // ===== sgemm TN ====== if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(T,N,96,96,16,16,16,6,6,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(T,N,96,96,16,16,16,6,6,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } //For GCN2 devices we will use the splitsgemm functor } if (true) { //we only manage the binary version here if(!strcmp(DevName, "Tahiti")) { #ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL1(T,N,64,64,16,16,16,4,4,64,TAHITI, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL1(T,N,64,64,16,16,16,4,4,64,TAHITI, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_TAHITI_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Hawaii")) { #ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(T,N,64,64,16,16,16,4,4,64,HAWAII, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(T,N,64,64,16,16,16,4,4,64,HAWAII, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_HAWAII_DYNAMIC_KERNEL } else if(!strcmp(DevName, "Bonaire")) { #ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL static const Variant variant = SGEMM_VARIANT_BIN_CL2(T,N,64,64,16,16,16,4,4,64,BONAIRE, __ALPHABETA) ; if ( applicable(variant,args) ) return &variant ; static const Variant variantA = SGEMM_VARIANT_BIN_CL2(T,N,64,64,16,16,16,4,4,64,BONAIRE, __ALPHA) ; if ( applicable(variantA,args) ) return &variantA ; #endif //#ifndef CLBLAS_BONAIRE_DYNAMIC_KERNEL } } } } return NULL ; // No suitable variant ... will use the fallback } clblasSgemmFunctorGCN::clblasSgemmFunctorGCN(Args & args, const Variant * variant, cl_int & err) : m_program(0) , m_variant(variant) { cl_device_id device; cl_context context; cl_command_queue queue = args.queue; err = getDeviceAndContext(queue, device, context); if( err != CL_SUCCESS ) { return; } if (VERB) printf(" ===> GET KERNEL %s\n", this->m_variant->kernel_name) ; //Ben do I use the correct "kernel_name"? BinaryLookup bl(context, device, "clblasSgemmFunctorGCN"); //clGetDeviceInfo(device, CL_DEVICE_NAME); bl.variantRaw( this->m_variant->kernel_name, strlen(this->m_variant->kernel_name)+1 ) ; if ( !bl.found() ) // may create empty file or may wait until file is ready { if ( this->m_variant->bin != 0 ) { // build from a pre-compiled version of the kernel (SPIR or cl binaries) err = bl.buildFromBinary(this->m_variant->bin, this->m_variant->bin_size, this->m_variant->build_options); } else { // directly build from a char* err = bl.buildFromSource(this->m_variant->source); } if ( err != CL_SUCCESS ) { if (VERB) printf(" ===> BUILD PROBLEM\n") ; return; } } this->m_program = bl.getProgram(); } clblasStatus clblasSgemmFunctorGCN::execute(Args &args) { cl_int err; cl_command_queue queue = args.queue; if (VERB) printf(" ===> EXECUTE KERNEL %s\n", this->m_variant->kernel_name) ; cl_kernel kernel = clCreateKernel( this->m_program, this->m_variant->kernel_name, &err); if (err != CL_SUCCESS) return clblasStatus(err) ; if (VERB) printf(" ===> FOUND %s\n", this->m_variant->kernel_name) ; int M = args.M, N = args.N, K = args.K; int lda = args.lda, ldb = args.ldb, ldc = args.ldc; int offsetA = args.offA; int offsetB = args.offB; int offsetC = args.offC; int arg=0 ; // All dgemm kernels shall have the same arguments: (A,B,C,M,N,K,alpha,beta,lda,ldb,ldc,offa,offb,offc) setKernelArg<cl_mem>(kernel, arg++, args.A); setKernelArg<cl_mem>(kernel, arg++, args.B); setKernelArg<cl_mem>(kernel, arg++, args.C); setKernelArg<int>(kernel, arg++, M); setKernelArg<int>(kernel, arg++, N); setKernelArg<int>(kernel, arg++, K); setKernelArg<cl_float>(kernel, arg++, args.alpha); if (args.beta!=0 && this->m_variant->mult.compare("__ALPHA")!=0) setKernelArg<cl_float>(kernel, arg++, args.beta); setKernelArg<int>(kernel, arg++, lda); setKernelArg<int>(kernel, arg++, ldb); setKernelArg<int>(kernel, arg++, ldc); setKernelArg<int>(kernel, arg++, offsetA); setKernelArg<int>(kernel, arg++, offsetB); setKernelArg<int>(kernel, arg++, offsetC); const size_t * ls = this->m_variant->ls ; // Each work group is made of ls[0] x ls[1] PE const size_t * bwi = this->m_variant->bwi ; // Each PE updates bwi[0] x bwi[1] values size_t globalThreads[2]; unsigned int thx, thy; thx = M/bwi[0] + ((M%bwi[0] != 0) ? 1 : 0); thx = thx/ls[0] + ((thx%ls[0] != 0) ? 1 : 0); thx = ls[0] * thx; thy = N/bwi[1] + ((N%bwi[1] != 0) ? 1 : 0); thy = thy/ls[1] + ((thy%ls[1] != 0) ? 1 : 0); thy = ls[1] * thy; globalThreads[0] = thx; globalThreads[1] = thy; err = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, globalThreads, ls , args.numEventsInWaitList, args.eventWaitList, args.events); clReleaseKernel(kernel) ; if (VERB) printf(" ===> ERR=%d \n",(int)err) ; return clblasStatus(err) ; } clblasSgemmFunctorGCN * clblasSgemmFunctorGCN::provide(clblasSgemmFunctor::Args & args, const char* DevName) { if ( args.order == clblasRowMajor ) return NULL ; // The RowMajor case shall never occur. cl_device_id dev; cl_context ctxt; cl_int err = getDeviceAndContext(args.queue, dev, ctxt); if (err != CL_SUCCESS) { return NULL; } cl_uint bitness = getAddressBits(dev); const Variant * variant = select_variant( args, DevName, bitness ) ; if ( variant == NULL ) return NULL ; Cache::Lookup lookup(cache, ctxt, dev, variant) ; if ( lookup.ok() ) { clblasSgemmFunctorGCN * functor = lookup.get(); functor->retain(); // increment the reference counter to avoid deletion while it is still beeing used return functor; } clblasSgemmFunctorGCN * functor = new clblasSgemmFunctorGCN(args, variant, err); if (err != CL_SUCCESS) { return NULL; } lookup.set(functor) ; return functor; }
apache-2.0
asashour/selenium
java/client/src/org/openqa/selenium/json/JsonType.java
983
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.json; public enum JsonType { BOOLEAN, NAME, NULL, NUMBER, START_MAP, END_MAP, START_COLLECTION, END_COLLECTION, STRING, END ; }
apache-2.0
kaviththiranga/developer-studio
jaggery/org.eclipse.php.core/src/org/eclipse/php/internal/core/format/IFormatterProcessorFactory.java
1532
/******************************************************************************* * Copyright (c) 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Zend Technologies *******************************************************************************/ /** * */ package org.eclipse.php.internal.core.format; import org.eclipse.core.resources.IProject; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.php.internal.core.PHPVersion; /** * Implementors of this interface should supply an * {@link ICodeFormattingProcessor} for PHP code formatting. * * @author shalom */ public interface IFormatterProcessorFactory { /** * Returns an {@link ICodeFormattingProcessor}. * * @param document * @param phpVersion * The PHP version. * @param region * An {@link IRegion} * @return An ICodeFormattingProcessor that will format the PHP code. * @throws Exception */ public ICodeFormattingProcessor getCodeFormattingProcessor( IDocument document, PHPVersion phpVersion, boolean useShortTags, IRegion region) throws Exception; public void setDefaultProject(IProject project); public void setIsPasting(boolean isPasting); }
apache-2.0
spatialdev/onadata
onadata/apps/logger/management/commands/import_briefcase.py
1129
#!/usr/bin/env python from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from optparse import make_option from onadata.libs.utils.briefcase_client import BriefcaseClient class Command(BaseCommand): help = _("Insert all existing parsed instances into MongoDB") option_list = BaseCommand.option_list + ( make_option('--url', help=_("server url to pull forms and submissions")), make_option('-u', '--username', help=_("Username")), make_option('-p', '--password', help=_("Password")), make_option('--to', help=_("username in this server")), ) def handle(self, *args, **kwargs): url = kwargs.get('url') username = kwargs.get('username') password = kwargs.get('password') to = kwargs.get('to') user = User.objects.get(username=to) bc = BriefcaseClient(username=username, password=password, user=user, url=url) bc.push()
bsd-2-clause
ropik/chromium
chrome/installer/test/alternate_version_generator.cc
23805
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // The file contains the implementation of the mini_installer re-versioner. // The main function (GenerateNextVersion) does the following in a temp dir: // - Extracts and unpacks setup.exe and the Chrome-bin folder from // mini_installer.exe. // - Inspects setup.exe to determine the current version. // - Runs through all .dll and .exe files: // - Replacing all occurrences of the Unicode version string in the files' // resources with the updated string. // - For all resources in which the string substitution is made, the binary // form of the version is also replaced. // - Re-packs setup.exe and Chrome-bin. // - Inserts them into the target mini_installer.exe. // // This code assumes that the host program 1) initializes the process-wide // CommandLine instance, and 2) resides in the output directory of a build // tree. When #2 is not the case, the --7za_path command-line switch may be // used to provide the (relative or absolute) path to the directory containing // 7za.exe. #include "chrome/installer/test/alternate_version_generator.h" #include <windows.h> #include <algorithm> #include <sstream> #include <limits> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/platform_file.h" #include "base/process_util.h" #include "base/win/pe_image.h" #include "base/win/scoped_handle.h" #include "chrome/installer/test/pe_image_resources.h" #include "chrome/installer/test/resource_loader.h" #include "chrome/installer/test/resource_updater.h" #include "chrome/installer/util/lzma_util.h" namespace { const wchar_t k7zaExe[] = L"7za.exe"; const wchar_t k7zaPathRelative[] = L"..\\..\\third_party\\lzma_sdk\\Executable"; const wchar_t kB7[] = L"B7"; const wchar_t kBl[] = L"BL"; const wchar_t kChrome7z[] = L"chrome.7z"; const wchar_t kChromeBin[] = L"Chrome-bin"; const wchar_t kChromePacked7z[] = L"chrome.packed.7z"; const wchar_t kExe[] = L"exe"; const wchar_t kExpandExe[] = L"expand.exe"; const wchar_t kExtDll[] = L".dll"; const wchar_t kExtExe[] = L".exe"; const wchar_t kMakeCab[] = L"makecab.exe"; const wchar_t kSetupEx_[] = L"setup.ex_"; const wchar_t kSetupExe[] = L"setup.exe"; const char kSwitch7zaPath[] = "7za_path"; const wchar_t kTempDirPrefix[] = L"mini_installer_test_temp"; // A helper class for creating and cleaning a temporary directory. A temporary // directory is created in Initialize and destroyed (along with all of its // contents) when the guard instance is destroyed. class ScopedTempDirectory { public: ScopedTempDirectory() { } ~ScopedTempDirectory() { if (!directory_.empty() && !file_util::Delete(directory_, true)) { LOG(DFATAL) << "Failed deleting temporary directory \"" << directory_.value() << "\""; } } // Creates a temporary directory. bool Initialize() { DCHECK(directory_.empty()); if (!file_util::CreateNewTempDirectory(&kTempDirPrefix[0], &directory_)) { LOG(DFATAL) << "Failed creating temporary directory."; return false; } return true; } const FilePath& directory() const { DCHECK(!directory_.empty()); return directory_; } private: FilePath directory_; DISALLOW_COPY_AND_ASSIGN(ScopedTempDirectory); }; // class ScopedTempDirectory // A helper class for manipulating a Chrome product version. class ChromeVersion { public: static ChromeVersion FromHighLow(DWORD high, DWORD low) { return ChromeVersion(static_cast<ULONGLONG>(high) << 32 | static_cast<ULONGLONG>(low)); } ChromeVersion() { } explicit ChromeVersion(ULONGLONG value) : version_(value) { } WORD major() const { return static_cast<WORD>(version_ >> 48); } WORD minor() const { return static_cast<WORD>(version_ >> 32); } WORD build() const { return static_cast<WORD>(version_ >> 16); } WORD patch() const { return static_cast<WORD>(version_); } DWORD high() const { return static_cast<DWORD>(version_ >> 32); } DWORD low() const { return static_cast<DWORD>(version_); } ULONGLONG value() const { return version_; } void set_value(ULONGLONG value) { version_ = value; } std::wstring ToString() const; private: ULONGLONG version_; }; // class ChromeVersion std::wstring ChromeVersion::ToString() const { wchar_t buffer[24]; int string_len = swprintf_s(&buffer[0], arraysize(buffer), L"%hu.%hu.%hu.%hu", major(), minor(), build(), patch()); DCHECK_NE(-1, string_len); DCHECK_GT(static_cast<int>(arraysize(buffer)), string_len); return std::wstring(&buffer[0], string_len); } // A read/write mapping of a file. // Note: base::MemoryMappedFile is not used because it doesn't support // read/write mappings. Adding such support across all platforms for this // Windows-only test code seems like overkill. class MappedFile { public: MappedFile() : size_(), mapping_(), view_() { } ~MappedFile(); bool Initialize(base::PlatformFile file); void* data() const { return view_; } size_t size() const { return size_; } private: size_t size_; HANDLE mapping_; void* view_; DISALLOW_COPY_AND_ASSIGN(MappedFile); }; // class MappedFile MappedFile::~MappedFile() { if (view_ != NULL) { if (UnmapViewOfFile(view_) == 0) { PLOG(DFATAL) << "MappedFile failed to unmap view."; } } if (mapping_ != NULL) { if (CloseHandle(mapping_) == 0) { PLOG(DFATAL) << "Could not close file mapping handle."; } } } bool MappedFile::Initialize(base::PlatformFile file) { DCHECK(mapping_ == NULL); bool result = false; base::PlatformFileInfo file_info; if (base::GetPlatformFileInfo(file, &file_info)) { if (file_info.size <= static_cast<int64>(std::numeric_limits<size_t>::max())) { mapping_ = CreateFileMapping(file, NULL, PAGE_READWRITE, 0, static_cast<DWORD>(file_info.size), NULL); if (mapping_ != NULL) { view_ = MapViewOfFile(mapping_, FILE_MAP_WRITE, 0, 0, static_cast<size_t>(file_info.size)); if (view_ != NULL) { result = true; } else { PLOG(DFATAL) << "MapViewOfFile failed"; } } else { PLOG(DFATAL) << "CreateFileMapping failed"; } } else { LOG(DFATAL) << "Files larger than " << std::numeric_limits<size_t>::max() << " are not supported."; } } else { PLOG(DFATAL) << "GetPlatformFileInfo failed"; } return result; } // Calls CreateProcess with good default parameters and waits for the process // to terminate returning the process exit code. bool RunProcessAndWait(const wchar_t* exe_path, const std::wstring& cmdline, int* exit_code) { bool result = true; base::ProcessHandle process; base::LaunchOptions options; options.wait = true; options.start_hidden = true; if (base::LaunchProcess(cmdline, options, &process)) { if (exit_code) { if (!GetExitCodeProcess(process, reinterpret_cast<DWORD*>(exit_code))) { PLOG(DFATAL) << "Failed getting the exit code for \"" << cmdline << "\"."; result = false; } else { DCHECK_NE(*exit_code, STILL_ACTIVE); } } } else { result = false; } CloseHandle(process); return result; } // Retrieves the version number of |pe_file| from its version // resource, placing the value in |version|. Returns true on success. bool GetFileVersion(const FilePath& pe_file, ChromeVersion* version) { DCHECK(version); bool result = false; upgrade_test::ResourceLoader pe_file_loader; std::pair<const uint8*, DWORD> version_info_data; if (pe_file_loader.Initialize(pe_file) && pe_file_loader.Load(VS_VERSION_INFO, reinterpret_cast<WORD>(RT_VERSION), &version_info_data)) { const VS_FIXEDFILEINFO* fixed_file_info; UINT ver_info_len; if (VerQueryValue(version_info_data.first, L"\\", reinterpret_cast<void**>( const_cast<VS_FIXEDFILEINFO**>(&fixed_file_info)), &ver_info_len) != 0) { DCHECK_EQ(sizeof(VS_FIXEDFILEINFO), static_cast<size_t>(ver_info_len)); *version = ChromeVersion::FromHighLow(fixed_file_info->dwFileVersionMS, fixed_file_info->dwFileVersionLS); result = true; } else { LOG(DFATAL) << "VerQueryValue failed to retrieve VS_FIXEDFILEINFO"; } } return result; } // Retrieves the version number of setup.exe in |work_dir| from its version // resource, placing the value in |version|. Returns true on success. bool GetSetupExeVersion(const FilePath& work_dir, ChromeVersion* version) { return GetFileVersion(work_dir.Append(&kSetupExe[0]), version); } // Replace all occurrences in the sequence [|dest_first|, |dest_last) that // equals [|src_first|, |src_last) with the sequence at |replacement_first| of // the same length. Returns true on success. If non-NULL, |replacements_made| // is set to true/false accordingly. bool ReplaceAll(uint8* dest_first, uint8* dest_last, const uint8* src_first, const uint8* src_last, const uint8* replacement_first, bool* replacements_made) { bool result = true; bool changed = false; do { dest_first = std::search(dest_first, dest_last, src_first, src_last); if (dest_first == dest_last) { break; } changed = true; if (memcpy_s(dest_first, dest_last - dest_first, replacement_first, src_last - src_first) != 0) { result = false; break; } dest_first += (src_last - src_first); } while (true); if (replacements_made != NULL) { *replacements_made = changed; } return result; } // A context structure in support of our EnumResource_Fn callback. struct VisitResourceContext { ChromeVersion current_version; std::wstring current_version_str; ChromeVersion new_version; std::wstring new_version_str; }; // struct VisitResourceContext // Replaces the old version with the new in a resource. A first pass is made to // replace the string form (e.g., "9.0.584.0"). If any replacements are made, a // second pass is made to replace the binary form (e.g., 0x0000024800000009). void VisitResource(const upgrade_test::EntryPath& path, uint8* data, DWORD size, DWORD code_page, uintptr_t context) { VisitResourceContext& ctx = *reinterpret_cast<VisitResourceContext*>(context); // Replace all occurrences of current_version_str with new_version_str bool changing_version = false; if (ReplaceAll( data, data + size, reinterpret_cast<const uint8*>(ctx.current_version_str.c_str()), reinterpret_cast<const uint8*>(ctx.current_version_str.c_str() + ctx.current_version_str.size() + 1), reinterpret_cast<const uint8*>(ctx.new_version_str.c_str()), &changing_version) && changing_version) { // Replace all occurrences of current_version with new_version struct VersionPair { DWORD high; DWORD low; }; VersionPair cur_ver = { ctx.current_version.high(), ctx.current_version.low() }; VersionPair new_ver = { ctx.new_version.high(), ctx.new_version.low() }; ReplaceAll(data, data + size, reinterpret_cast<const uint8*>(&cur_ver), reinterpret_cast<const uint8*>(&cur_ver) + sizeof(cur_ver), reinterpret_cast<const uint8*>(&new_ver), NULL); } } // Updates the version strings and numbers in all of |image_file|'s resources. bool UpdateVersionIfMatch(const FilePath& image_file, VisitResourceContext* context) { bool result = false; base::win::ScopedHandle image_handle(base::CreatePlatformFile( image_file, (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_EXCLUSIVE_WRITE), NULL, NULL)); // It turns out that the underlying CreateFile can fail due to unhelpful // security software locking the newly created DLL. So add a few brief // retries to help tests that use this pass on machines thusly encumbered. int retries = 3; while (!image_handle.IsValid() && retries-- > 0) { LOG(WARNING) << "Failed to open \"" << image_file.value() << "\"." << " Retrying " << retries << " more times."; Sleep(1000); image_handle.Set(base::CreatePlatformFile( image_file, (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_EXCLUSIVE_WRITE), NULL, NULL)); } if (image_handle.IsValid()) { MappedFile image_mapping; if (image_mapping.Initialize(image_handle)) { base::win::PEImageAsData image( reinterpret_cast<HMODULE>(image_mapping.data())); // PEImage class does not support other-architecture images. if (image.GetNTHeaders()->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR_MAGIC) { result = upgrade_test::EnumResources( image, &VisitResource, reinterpret_cast<uintptr_t>(context)); } else { result = true; } } } else { PLOG(DFATAL) << "Failed to open \"" << image_file.value() << "\""; } return result; } bool IncrementNewVersion(upgrade_test::Direction direction, VisitResourceContext* ctx) { DCHECK(ctx); // Figure out a past or future version with the same string length as this one // by decrementing or incrementing each component. LONGLONG incrementer = (direction == upgrade_test::PREVIOUS_VERSION ? -1 : 1); do { if (incrementer == 0) { LOG(DFATAL) << "Improbable version at the cusp of complete rollover"; return false; } ctx->new_version.set_value(ctx->current_version.value() + incrementer); ctx->new_version_str = ctx->new_version.ToString(); incrementer <<= 16; } while (ctx->new_version_str.size() != ctx->current_version_str.size()); return true; } // Raises or lowers the version of all .exe and .dll files in |work_dir| as well // as the |work-dir|\Chrome-bin\w.x.y.z directory. |original_version| and // |new_version|, when non-NULL, are given the original and new version numbers // on success. bool ApplyAlternateVersion(const FilePath& work_dir, upgrade_test::Direction direction, std::wstring* original_version, std::wstring* new_version) { VisitResourceContext ctx; if (!GetSetupExeVersion(work_dir, &ctx.current_version)) { return false; } ctx.current_version_str = ctx.current_version.ToString(); if (!IncrementNewVersion(direction, &ctx)) { return false; } // Modify all .dll and .exe files with the current version. bool doing_great = true; file_util::FileEnumerator all_files(work_dir, true, file_util::FileEnumerator::FILES); do { FilePath file = all_files.Next(); if (file.empty()) { break; } std::wstring extension = file.Extension(); if (extension == &kExtExe[0] || extension == &kExtDll[0]) { doing_great = UpdateVersionIfMatch(file, &ctx); } } while (doing_great); // Change the versioned directory. FilePath chrome_bin = work_dir.Append(&kChromeBin[0]); doing_great = file_util::Move(chrome_bin.Append(ctx.current_version_str), chrome_bin.Append(ctx.new_version_str)); if (doing_great) { // Report the version numbers if requested. if (original_version != NULL) original_version->assign(ctx.current_version_str); if (new_version != NULL) new_version->assign(ctx.new_version_str); } return doing_great; } // Returns the path to the directory holding the 7za executable. By default, it // is assumed that the test resides in the tree's output directory, so the // relative path "..\..\third_party\lzma_sdk\Executable" is applied to the host // executable's directory. This can be overridden with the --7za_path // command-line switch. FilePath Get7zaPath() { FilePath l7za_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( &kSwitch7zaPath[0]); if (l7za_path.empty()) { FilePath dir_exe; if (!PathService::Get(base::DIR_EXE, &dir_exe)) LOG(DFATAL) << "Failed getting directory of host executable"; l7za_path = dir_exe.Append(&k7zaPathRelative[0]); } return l7za_path; } bool CreateArchive(const FilePath& output_file, const FilePath& input_path, int compression_level) { DCHECK(compression_level == 0 || compression_level >= 1 && compression_level <= 9 && (compression_level & 0x01) != 0); std::wstring command_line(1, L'"'); command_line .append(Get7zaPath().Append(&k7zaExe[0]).value()) .append(L"\" a -bd -t7z \"") .append(output_file.value()) .append(L"\" \"") .append(input_path.value()) .append(L"\" -mx") .append(1, L'0' + compression_level); int exit_code; if (!RunProcessAndWait(NULL, command_line, &exit_code)) return false; if (exit_code != 0) { LOG(DFATAL) << Get7zaPath().Append(&k7zaExe[0]).value() << " exited with code " << exit_code << " while creating " << output_file.value(); return false; } return true; } } // namespace namespace upgrade_test { bool GenerateAlternateVersion(const FilePath& original_installer_path, const FilePath& target_path, Direction direction, std::wstring* original_version, std::wstring* new_version) { // Create a temporary directory in which we'll do our work. ScopedTempDirectory work_dir; if (!work_dir.Initialize()) return false; // Copy the original mini_installer. FilePath mini_installer = work_dir.directory().Append(original_installer_path.BaseName()); if (!file_util::CopyFile(original_installer_path, mini_installer)) { LOG(DFATAL) << "Failed copying \"" << original_installer_path.value() << "\" to \"" << mini_installer.value() << "\""; return false; } FilePath setup_ex_ = work_dir.directory().Append(&kSetupEx_[0]); FilePath chrome_packed_7z = work_dir.directory().Append(&kChromePacked7z[0]); // Load the original file and extract setup.ex_ and chrome.packed.7z { ResourceLoader resource_loader; std::pair<const uint8*, DWORD> resource_data; if (!resource_loader.Initialize(mini_installer)) return false; // Write out setup.ex_ if (!resource_loader.Load(&kSetupEx_[0], &kBl[0], &resource_data)) return false; int written = file_util::WriteFile(setup_ex_, reinterpret_cast<const char*>(resource_data.first), static_cast<int>(resource_data.second)); if (written != resource_data.second) { LOG(DFATAL) << "Failed writing \"" << setup_ex_.value() << "\""; return false; } // Write out chrome.packed.7z if (!resource_loader.Load(&kChromePacked7z[0], &kB7[0], &resource_data)) return false; written = file_util::WriteFile(chrome_packed_7z, reinterpret_cast<const char*>(resource_data.first), static_cast<int>(resource_data.second)); if (written != resource_data.second) { LOG(DFATAL) << "Failed writing \"" << chrome_packed_7z.value() << "\""; return false; } } // Expand setup.ex_ FilePath setup_exe = setup_ex_.ReplaceExtension(&kExe[0]); std::wstring command_line; command_line.append(1, L'"') .append(&kExpandExe[0]) .append(L"\" \"") .append(setup_ex_.value()) .append(L"\" \"") .append(setup_exe.value()) .append(1, L'\"'); int exit_code; if (!RunProcessAndWait(NULL, command_line, &exit_code)) return false; if (exit_code != 0) { LOG(DFATAL) << &kExpandExe[0] << " exited with code " << exit_code; return false; } // Unpack chrome.packed.7z std::wstring chrome_7z_name; if (LzmaUtil::UnPackArchive(chrome_packed_7z.value(), work_dir.directory().value(), &chrome_7z_name) != NO_ERROR) { LOG(DFATAL) << "Failed unpacking \"" << chrome_packed_7z.value() << "\""; return false; } // Unpack chrome.7z if (LzmaUtil::UnPackArchive(chrome_7z_name, work_dir.directory().value(), NULL) != NO_ERROR) { LOG(DFATAL) << "Failed unpacking \"" << chrome_7z_name << "\""; return false; } // Get rid of intermediate files FilePath chrome_7z(chrome_7z_name); if (!file_util::Delete(chrome_7z, false) || !file_util::Delete(chrome_packed_7z, false) || !file_util::Delete(setup_ex_, false)) { LOG(DFATAL) << "Failed deleting intermediate files"; return false; } // Increment the version in all files. ApplyAlternateVersion(work_dir.directory(), direction, original_version, new_version); // Pack up files into chrome.7z if (!CreateArchive(chrome_7z, work_dir.directory().Append(&kChromeBin[0]), 0)) return false; // Compress chrome.7z into chrome.packed.7z if (!CreateArchive(chrome_packed_7z, chrome_7z, 9)) return false; // Compress setup.exe into setup.ex_ command_line.assign(1, L'"') .append(&kMakeCab[0]) .append(L"\" /D CompressionType=LZX /L \"") .append(work_dir.directory().value()) .append(L"\" \"") .append(setup_exe.value()); if (!RunProcessAndWait(NULL, command_line, &exit_code)) return false; if (exit_code != 0) { LOG(DFATAL) << &kMakeCab[0] << " exited with code " << exit_code; return false; } // Replace the mini_installer's setup.ex_ and chrome.packed.7z resources. ResourceUpdater updater; if (!updater.Initialize(mini_installer) || !updater.Update(&kSetupEx_[0], &kBl[0], MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), setup_ex_) || !updater.Update(&kChromePacked7z[0], &kB7[0], MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), chrome_packed_7z) || !updater.Commit()) { return false; } // Finally, move the updated mini_installer into place. return file_util::Move(mini_installer, target_path); } bool GenerateAlternatePEFileVersion(const FilePath& original_file, const FilePath& target_file, Direction direction) { // First copy original_file to target_file. if (!file_util::CopyFile(original_file, target_file)) { LOG(DFATAL) << "Failed copying \"" << original_file.value() << "\" to \"" << target_file.value() << "\""; return false; } VisitResourceContext ctx; if (!GetFileVersion(target_file, &ctx.current_version)) { LOG(DFATAL) << "Failed reading version from \"" << target_file.value() << "\""; return false; } ctx.current_version_str = ctx.current_version.ToString(); if (!IncrementNewVersion(direction, &ctx) || !UpdateVersionIfMatch(target_file, &ctx)) { LOG(DFATAL) << "Failed to update version in \"" << target_file.value() << "\""; return false; } return true; } } // namespace upgrade_test
bsd-3-clause
ersanliqiao/mlpack
src/mlpack/methods/ann/convolution_rules/naive_convolution.hpp
6134
/** * @file naive_convolution.hpp * @author Shangtong Zhang * @author Marcus Edel * * Implementation of the convolution. */ #ifndef __MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP #define __MLPACK_METHODS_ANN_CONVOLUTION_RULES_NAIVE_CONVOLUTION_HPP #include <mlpack/core.hpp> #include "border_modes.hpp" namespace mlpack { namespace ann /** Artificial Neural Network. */ { /** * Computes the two-dimensional convolution. This class allows specification of * the type of the border type. The convolution can be compute with the valid * border type of the full border type (default). * * FullConvolution: returns the full two-dimensional convolution. * ValidConvolution: returns only those parts of the convolution that are * computed without the zero-padded edges. * * @tparam BorderMode Type of the border mode (FullConvolution or * ValidConvolution). */ template<typename BorderMode = FullConvolution> class NaiveConvolution { public: /* * Perform a convolution (valid mode). * * @param input Input used to perform the convolution. * @param filter Filter used to perform the conolution. * @param output Output data that contains the results of the convolution. */ template<typename eT, typename Border = BorderMode> static typename std::enable_if< std::is_same<Border, ValidConvolution>::value, void>::type Convolution(const arma::Mat<eT>& input, const arma::Mat<eT>& filter, arma::Mat<eT>& output) { output = arma::zeros<arma::Mat<eT> >(input.n_rows - filter.n_rows + 1, input.n_cols - filter.n_cols + 1); // It seems to be about 3.5 times faster to use pointers instead of // filter(ki, kj) * input(leftInput + ki, topInput + kj) and output(i, j). eT* outputPtr = output.memptr(); for (size_t j = 0; j < output.n_cols; ++j) { for (size_t i = 0; i < output.n_rows; ++i, outputPtr++) { const eT* kernelPtr = filter.memptr(); for (size_t kj = 0; kj < filter.n_cols; ++kj) { const eT* inputPtr = input.colptr(kj + j) + i; for (size_t ki = 0; ki < filter.n_rows; ++ki, ++kernelPtr, ++inputPtr) *outputPtr += *kernelPtr * (*inputPtr); } } } } /* * Perform a convolution (full mode). * * @param input Input used to perform the convolution. * @param filter Filter used to perform the conolution. * @param output Output data that contains the results of the convolution. */ template<typename eT, typename Border = BorderMode> static typename std::enable_if< std::is_same<Border, FullConvolution>::value, void>::type Convolution(const arma::Mat<eT>& input, const arma::Mat<eT>& filter, arma::Mat<eT>& output) { const size_t outputRows = input.n_rows + 2 * (filter.n_rows - 1); const size_t outputCols = input.n_cols + 2 * (filter.n_cols - 1); // Pad filter and input to the working output shape. arma::Mat<eT> inputPadded = arma::zeros<arma::Mat<eT> >(outputRows, outputCols); inputPadded.submat(filter.n_rows - 1, filter.n_cols - 1, filter.n_rows - 1 + input.n_rows - 1, filter.n_cols - 1 + input.n_cols - 1) = input; NaiveConvolution<ValidConvolution>::Convolution(inputPadded, filter, output); } /* * Perform a convolution using 3rd order tensors. * * @param input Input used to perform the convolution. * @param filter Filter used to perform the conolution. * @param output Output data that contains the results of the convolution. */ template<typename eT> static void Convolution(const arma::Cube<eT>& input, const arma::Cube<eT>& filter, arma::Cube<eT>& output) { arma::Mat<eT> convOutput; NaiveConvolution<BorderMode>::Convolution(input.slice(0), filter.slice(0), convOutput); output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols, input.n_slices); output.slice(0) = convOutput; for (size_t i = 1; i < input.n_slices; i++) { NaiveConvolution<BorderMode>::Convolution(input.slice(i), filter.slice(i), output.slice(i)); } } /* * Perform a convolution using dense matrix as input and a 3rd order tensors * as filter and output. * * @param input Input used to perform the convolution. * @param filter Filter used to perform the conolution. * @param output Output data that contains the results of the convolution. */ template<typename eT> static void Convolution(const arma::Mat<eT>& input, const arma::Cube<eT>& filter, arma::Cube<eT>& output) { arma::Mat<eT> convOutput; NaiveConvolution<BorderMode>::Convolution(input, filter.slice(0), convOutput); output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols, filter.n_slices); output.slice(0) = convOutput; for (size_t i = 1; i < filter.n_slices; i++) { NaiveConvolution<BorderMode>::Convolution(input, filter.slice(i), output.slice(i)); } } /* * Perform a convolution using a 3rd order tensors as input and output and a * dense matrix as filter. * * @param input Input used to perform the convolution. * @param filter Filter used to perform the conolution. * @param output Output data that contains the results of the convolution. */ template<typename eT> static void Convolution(const arma::Cube<eT>& input, const arma::Mat<eT>& filter, arma::Cube<eT>& output) { arma::Mat<eT> convOutput; NaiveConvolution<BorderMode>::Convolution(input.slice(0), filter, convOutput); output = arma::Cube<eT>(convOutput.n_rows, convOutput.n_cols, input.n_slices); output.slice(0) = convOutput; for (size_t i = 1; i < input.n_slices; i++) { NaiveConvolution<BorderMode>::Convolution(input.slice(i), filter, output.slice(i)); } } }; // class NaiveConvolution }; // namespace ann }; // namespace mlpack #endif
bsd-3-clause
sivaprakashniet/push_pull
p2p/lib/python2.7/site-packages/bleach/__init__.py
15427
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass import re import html5lib from html5lib.sanitizer import HTMLSanitizer from html5lib.serializer.htmlserializer import HTMLSerializer from . import callbacks as linkify_callbacks from .encoding import force_unicode from .sanitizer import BleachSanitizer from .version import __version__, VERSION # flake8: noqa __all__ = ['clean', 'linkify'] log = logging.getLogger(__name__) log.addHandler(NullHandler()) ALLOWED_TAGS = [ 'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul', ] ALLOWED_ATTRIBUTES = { 'a': ['href', 'title'], 'abbr': ['title'], 'acronym': ['title'], } ALLOWED_STYLES = [] ALLOWED_PROTOCOLS = ['http', 'https', 'mailto'] TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat cc cd cf cg ch ci ck cl cm cn co com coop cr cu cv cx cy cz de dj dk dm do dz ec edu ee eg er es et eu fi fj fk fm fo fr ga gb gd ge gf gg gh gi gl gm gn gov gp gq gr gs gt gu gw gy hk hm hn hr ht hu id ie il im in info int io iq ir is it je jm jo jobs jp ke kg kh ki km kn kp kr kw ky kz la lb lc li lk lr ls lt lu lv ly ma mc md me mg mh mil mk ml mm mn mo mobi mp mq mr ms mt mu museum mv mw mx my mz na name nc ne net nf ng ni nl no np nr nu nz om org pa pe pf pg ph pk pl pm pn post pr pro ps pt pw py qa re ro rs ru rw sa sb sc sd se sg sh si sj sk sl sm sn so sr ss st su sv sx sy sz tc td tel tf tg th tj tk tl tm tn to tp tr travel tt tv tw tz ua ug uk us uy uz va vc ve vg vi vn vu wf ws xn xxx ye yt yu za zm zw""".split() # Make sure that .com doesn't get matched by .co first TLDS.reverse() PROTOCOLS = HTMLSanitizer.acceptable_protocols url_re = re.compile( r"""\(* # Match any opening parentheses. \b(?<![@.])(?:(?:{0}):/{{0,3}}(?:(?:\w+:)?\w+@)?)? # http:// ([\w-]+\.)+(?:{1})(?:\:[0-9]+)?(?!\.\w)\b # xx.yy.tld(:##)? (?:[/?][^\s\{{\}}\|\\\^\[\]`<>"]*)? # /path/zz (excluding "unsafe" chars from RFC 1738, # except for # and ~, which happen in practice) """.format('|'.join(PROTOCOLS), '|'.join(TLDS)), re.IGNORECASE | re.VERBOSE | re.UNICODE) proto_re = re.compile(r'^[\w-]+:/{0,3}', re.IGNORECASE) punct_re = re.compile(r'([\.,]+)$') email_re = re.compile( r"""(?<!//) (([-!#$%&'*+/=?^_`{0!s}|~0-9A-Z]+ (\.[-!#$%&'*+/=?^_`{1!s}|~0-9A-Z]+)* # dot-atom |^"([\001-\010\013\014\016-\037!#-\[\]-\177] |\\[\001-011\013\014\016-\177])*" # quoted-string )@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}) # domain """, re.IGNORECASE | re.MULTILINE | re.VERBOSE) NODE_TEXT = 4 # The numeric ID of a text node in simpletree. ETREE_TAG = lambda x: "".join(['{http://www.w3.org/1999/xhtml}', x]) # a simple routine that returns the tag name with the namespace prefix # as returned by etree's Element.tag attribute DEFAULT_CALLBACKS = [linkify_callbacks.nofollow] def clean(text, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES, styles=ALLOWED_STYLES, protocols=ALLOWED_PROTOCOLS, strip=False, strip_comments=True): """Clean an HTML fragment of malicious content and return it This function is a security-focused function whose sole purpose is to remove malicious content from a string such that it can be displayed as content in a web page. This function is not designed to use to transform content to be used in non-web-page contexts. :arg text: the text to clean :arg tags: whitelist of allowed tags; defaults to ``bleach.ALLOWED_TAGS`` :arg attributes: whitelist of allowed attributes; defaults to ``bleach.ALLOWED_ATTRIBUTES`` :arg styles: whitelist of allowed css; defaults to ``bleach.ALLOWED_STYLES`` :arg protocols: whitelist of allowed protocols for links; defaults to ``bleach.ALLOWED_PROTOCOLS`` :arg strip: whether or not to strip disallowed elements :arg strip_comments: whether or not to strip HTML comments """ if not text: return '' text = force_unicode(text) class s(BleachSanitizer): allowed_elements = tags allowed_attributes = attributes allowed_css_properties = styles allowed_protocols = protocols strip_disallowed_elements = strip strip_html_comments = strip_comments parser = html5lib.HTMLParser(tokenizer=s) return _render(parser.parseFragment(text)) def linkify(text, callbacks=DEFAULT_CALLBACKS, skip_pre=False, parse_email=False, tokenizer=HTMLSanitizer): """Convert URL-like strings in an HTML fragment to links ``linkify()`` converts strings that look like URLs, domain names and email addresses in text that may be an HTML fragment to links, while preserving: 1. links already in the string 2. urls found in attributes 3. email addresses ``linkify()`` does a best-effort approach and tries to recover from bad situations due to crazy text. """ text = force_unicode(text) if not text: return '' parser = html5lib.HTMLParser(tokenizer=tokenizer) forest = parser.parseFragment(text) _seen = set([]) def replace_nodes(tree, new_frag, node, index=0): """Doesn't really replace nodes, but inserts the nodes contained in ``new_frag`` into ``tree`` at position ``index`` and returns the number of nodes inserted. If ``node`` is passed in, it is removed from the resulting tree. :arg tree: tree :arg new_frag: fragment of html text to insert :arg node: the node to "replace" :arg index: the index position to focus on :returns: number of nodes inserted so that you can skip ahead """ count = 0 new_tree = parser.parseFragment(new_frag) # capture any non-tag text at the start of the fragment if new_tree.text: if index == 0: tree.text = (tree.text or '') + new_tree.text else: tree[index-1].tail = (tree[index-1].tail or '') + new_tree.text # then put in the tagged elements into the old tree for n in new_tree: if n.tag == ETREE_TAG('a'): _seen.add(n) tree.insert(index + count, n) count += 1 # if we got a node to remove... if node is not None: # first, grab the node tail so we don't lose text if node.tail: if index + count == 0: tree.text = (tree.text or '') + node.tail else: tree[index+count-1].tail = (tree[index+count-1].tail or '') + node.tail tree.remove(node) return count def strip_wrapping_parentheses(fragment): """Strips wrapping parentheses. Returns a tuple of the following format:: (string stripped from wrapping parentheses, count of stripped opening parentheses, count of stripped closing parentheses) """ opening_parentheses = closing_parentheses = 0 # Count consecutive opening parentheses # at the beginning of the fragment (string). for char in fragment: if char == '(': opening_parentheses += 1 else: break if opening_parentheses: newer_frag = '' # Cut the consecutive opening brackets from the fragment. fragment = fragment[opening_parentheses:] # Reverse the fragment for easier detection of parentheses # inside the URL. reverse_fragment = fragment[::-1] skip = False for char in reverse_fragment: # Remove the closing parentheses if it has a matching # opening parentheses (they are balanced). if (char == ')' and closing_parentheses < opening_parentheses and not skip): closing_parentheses += 1 continue # Do not remove ')' from the URL itself. elif char != ')': skip = True newer_frag += char fragment = newer_frag[::-1] return fragment, opening_parentheses, closing_parentheses def apply_callbacks(attrs, new): for cb in callbacks: attrs = cb(attrs, new) if attrs is None: return None return attrs def _render_inner(node): out = ['' if node.text is None else node.text] for subnode in node: out.append(_render(subnode)) if subnode.tail: out.append(subnode.tail) return ''.join(out) def linkify_nodes(tree, parse_text=True): children = len(tree) current_child = -1 # start at -1 to process the parent first while current_child < len(tree): if current_child < 0: node = tree if parse_text and node.text: new_txt = old_txt = node.text if parse_email: new_txt = re.sub(email_re, email_repl, node.text) if new_txt and new_txt != node.text: node.text = '' adj = replace_nodes(tree, new_txt, None, 0) children += adj current_child += adj linkify_nodes(tree, True) continue new_txt = re.sub(url_re, link_repl, new_txt) if new_txt != old_txt: node.text = '' adj = replace_nodes(tree, new_txt, None, 0) children += adj current_child += adj continue else: node = tree[current_child] if parse_text and node.tail: new_tail = old_tail = node.tail if parse_email: new_tail = re.sub(email_re, email_repl, new_tail) if new_tail != node.tail: node.tail = '' adj = replace_nodes(tree, new_tail, None, current_child + 1) # Insert the new nodes made from my tail into # the tree right after me. current_child+1 children += adj continue new_tail = re.sub(url_re, link_repl, new_tail) if new_tail != old_tail: node.tail = '' adj = replace_nodes(tree, new_tail, None, current_child + 1) children += adj if node.tag == ETREE_TAG('a') and not (node in _seen): if not node.get('href', None) is None: attrs = dict(node.items()) _text = attrs['_text'] = _render_inner(node) attrs = apply_callbacks(attrs, False) if attrs is None: # # <a> tag replaced by the text within it adj = replace_nodes(tree, _text, node, current_child) # pull back current_child by 1 to scan the new nodes # again. current_child -= 1 else: text = force_unicode(attrs.pop('_text')) for attr_key, attr_val in attrs.items(): node.set(attr_key, attr_val) for n in reversed(list(node)): node.remove(n) text = parser.parseFragment(text) node.text = text.text for n in text: node.append(n) _seen.add(node) elif current_child >= 0: if node.tag == ETREE_TAG('pre') and skip_pre: linkify_nodes(node, False) elif not (node in _seen): linkify_nodes(node, parse_text) current_child += 1 def email_repl(match): addr = match.group(0).replace('"', '&quot;') link = { '_text': addr, 'href': 'mailto:{0!s}'.format(addr), } link = apply_callbacks(link, True) if link is None: return addr _href = link.pop('href') _text = link.pop('_text') repl = '<a href="{0!s}" {1!s}>{2!s}</a>' attr = '{0!s}="{1!s}"' attribs = ' '.join(attr.format(k, v) for k, v in link.items()) return repl.format(_href, attribs, _text) def link_repl(match): url = match.group(0) open_brackets = close_brackets = 0 if url.startswith('('): _wrapping = strip_wrapping_parentheses(url) url, open_brackets, close_brackets = _wrapping if url.endswith(')') and '(' not in url: # This is a clumsy handling for the case where we have something # like (foo http://example.com) and the ) gets picked up by the # url_re but we don't want it part of the link. new_url = url.rstrip(')') close_brackets += len(url) - len(new_url) url = new_url end = '' m = re.search(punct_re, url) if m: end = m.group(0) url = url[0:m.start()] if re.search(proto_re, url): href = url else: href = ''.join(['http://', url]) link = { '_text': url, 'href': href, } link = apply_callbacks(link, True) if link is None: return '(' * open_brackets + url + ')' * close_brackets _text = link.pop('_text') _href = link.pop('href') repl = '{0!s}<a href="{1!s}" {2!s}>{3!s}</a>{4!s}{5!s}' attr = '{0!s}="{1!s}"' attribs = ' '.join(attr.format(k, v) for k, v in link.items()) return repl.format('(' * open_brackets, _href, attribs, _text, end, ')' * close_brackets) try: linkify_nodes(forest) except RuntimeError as e: # If we hit the max recursion depth, just return what we've got. log.exception('Probable recursion error: {0!r}'.format(e)) return _render(forest) def _render(tree): """Try rendering as HTML, then XML, then give up.""" return force_unicode(_serialize(tree)) def _serialize(domtree): walker = html5lib.treewalkers.getTreeWalker('etree') stream = walker(domtree) serializer = HTMLSerializer(quote_attr_values=True, alphabetical_attributes=True, omit_optional_tags=False) return serializer.render(stream)
bsd-3-clause
bantudevelopment/smis
vendor/gedmo1/doctrine-extensions/lib/Gedmo/Tree/Mapping/Driver/Yaml.php
9652
<?php namespace Gedmo\Tree\Mapping\Driver; use Gedmo\Mapping\Driver\File; use Gedmo\Mapping\Driver; use Gedmo\Exception\InvalidMappingException; use Gedmo\Tree\Mapping\Validator; /** * This is a yaml mapping driver for Tree * behavioral extension. Used for extraction of extended * metadata from yaml specifically for Tree * extension. * * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class Yaml extends File implements Driver { /** * File extension * @var string */ protected $_extension = '.dcm.yml'; /** * List of tree strategies available * * @var array */ private $strategies = array( 'nested', 'closure', 'materializedPath', ); /** * {@inheritDoc} */ public function readExtendedMetadata($meta, array &$config) { $mapping = $this->_getMapping($meta->name); $validator = new Validator(); if (isset($mapping['gedmo'])) { $classMapping = $mapping['gedmo']; if (isset($classMapping['tree']['type'])) { $strategy = $classMapping['tree']['type']; if (!in_array($strategy, $this->strategies)) { throw new InvalidMappingException("Tree type: $strategy is not available."); } $config['strategy'] = $strategy; $config['activate_locking'] = isset($classMapping['tree']['activateLocking']) ? $classMapping['tree']['activateLocking'] : false; $config['locking_timeout'] = isset($classMapping['tree']['lockingTimeout']) ? (int) $classMapping['tree']['lockingTimeout'] : 3; if ($config['locking_timeout'] < 1) { throw new InvalidMappingException("Tree Locking Timeout must be at least of 1 second."); } } if (isset($classMapping['tree']['closure'])) { if (!$class = $this->getRelatedClassName($meta, $classMapping['tree']['closure'])) { throw new InvalidMappingException("Tree closure class: {$classMapping['tree']['closure']} does not exist."); } $config['closure'] = $class; } } if (isset($mapping['fields'])) { foreach ($mapping['fields'] as $field => $fieldMapping) { if (isset($fieldMapping['gedmo'])) { if (in_array('treeLeft', $fieldMapping['gedmo'])) { if (!$validator->isValidField($meta, $field)) { throw new InvalidMappingException("Tree left field - [{$field}] type is not valid and must be 'integer' in class - {$meta->name}"); } $config['left'] = $field; } elseif (in_array('treeRight', $fieldMapping['gedmo'])) { if (!$validator->isValidField($meta, $field)) { throw new InvalidMappingException("Tree right field - [{$field}] type is not valid and must be 'integer' in class - {$meta->name}"); } $config['right'] = $field; } elseif (in_array('treeLevel', $fieldMapping['gedmo'])) { if (!$validator->isValidField($meta, $field)) { throw new InvalidMappingException("Tree level field - [{$field}] type is not valid and must be 'integer' in class - {$meta->name}"); } $config['level'] = $field; } elseif (in_array('treeRoot', $fieldMapping['gedmo'])) { if (!$validator->isValidFieldForRoot($meta, $field)) { throw new InvalidMappingException("Tree root field - [{$field}] type is not valid and must be any of the 'integer' types or 'string' in class - {$meta->name}"); } $config['root'] = $field; } elseif (in_array('treePath', $fieldMapping['gedmo']) || isset($fieldMapping['gedmo']['treePath'])) { if (!$validator->isValidFieldForPath($meta, $field)) { throw new InvalidMappingException("Tree Path field - [{$field}] type is not valid. It must be string or text in class - {$meta->name}"); } $treePathInfo = isset($fieldMapping['gedmo']['treePath']) ? $fieldMapping['gedmo']['treePath'] : $fieldMapping['gedmo'][array_search('treePath', $fieldMapping['gedmo'])]; if (is_array($treePathInfo) && isset($treePathInfo['separator'])) { $separator = $treePathInfo['separator']; } else { $separator = '|'; } if (strlen($separator) > 1) { throw new InvalidMappingException("Tree Path field - [{$field}] Separator {$separator} is invalid. It must be only one character long."); } if (is_array($treePathInfo) && isset($treePathInfo['appendId'])) { $appendId = $treePathInfo['appendId']; } else { $appendId = null; } if (is_array($treePathInfo) && isset($treePathInfo['startsWithSeparator'])) { $startsWithSeparator = $treePathInfo['startsWithSeparator']; } else { $startsWithSeparator = false; } if (is_array($treePathInfo) && isset($treePathInfo['endsWithSeparator'])) { $endsWithSeparator = $treePathInfo['endsWithSeparator']; } else { $endsWithSeparator = true; } $config['path'] = $field; $config['path_separator'] = $separator; $config['path_append_id'] = $appendId; $config['path_starts_with_separator'] = $startsWithSeparator; $config['path_ends_with_separator'] = $endsWithSeparator; } elseif (in_array('treePathSource', $fieldMapping['gedmo'])) { if (!$validator->isValidFieldForPathSource($meta, $field)) { throw new InvalidMappingException("Tree PathSource field - [{$field}] type is not valid. It can be any of the integer variants, double, float or string in class - {$meta->name}"); } $config['path_source'] = $field; } elseif (in_array('treePathHash', $fieldMapping['gedmo'])) { if (!$validator->isValidFieldForPathSource($meta, $field)) { throw new InvalidMappingException("Tree PathHash field - [{$field}] type is not valid and must be 'string' in class - {$meta->name}"); } $config['path_hash'] = $field; } elseif (in_array('treeLockTime', $fieldMapping['gedmo'])) { if (!$validator->isValidFieldForLocktime($meta, $field)) { throw new InvalidMappingException("Tree LockTime field - [{$field}] type is not valid. It must be \"date\" in class - {$meta->name}"); } $config['lock_time'] = $field; } elseif (in_array('treeParent', $fieldMapping['gedmo'])) { $config['parent'] = $field; } } } } if (isset($config['activate_locking']) && $config['activate_locking'] && !isset($config['lock_time'])) { throw new InvalidMappingException("You need to map a date|datetime|timestamp field as the tree lock time field to activate locking support."); } if (isset($mapping['manyToOne'])) { foreach ($mapping['manyToOne'] as $field => $relationMapping) { if (isset($relationMapping['gedmo'])) { if (in_array('treeParent', $relationMapping['gedmo'])) { if (!$rel = $this->getRelatedClassName($meta, $relationMapping['targetEntity'])) { throw new InvalidMappingException("Unable to find ancestor/parent child relation through ancestor field - [{$field}] in class - {$meta->name}"); } $config['parent'] = $field; } } } } if (!$meta->isMappedSuperclass && $config) { if (isset($config['strategy'])) { if (is_array($meta->identifier) && count($meta->identifier) > 1) { throw new InvalidMappingException("Tree does not support composite identifiers in class - {$meta->name}"); } $method = 'validate'.ucfirst($config['strategy']).'TreeMetadata'; $validator->$method($meta, $config); } else { throw new InvalidMappingException("Cannot find Tree type for class: {$meta->name}"); } } } /** * {@inheritDoc} */ protected function _loadMappingFile($file) { return \Symfony\Component\Yaml\Yaml::parse($file); } }
bsd-3-clause
dsebastien/DefinitelyTyped
types/json-schema-traverse/index.d.ts
3622
// Type definitions for json-schema-traverse 0.4 // Project: https://github.com/epoberezkin/json-schema-traverse#readme // Definitions by: Piotr Błażejewicz (Peter Blazejewicz) <https://github.com/peterblazejewicz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * Traverse JSON Schema passing each schema object to callback */ declare function traverse(schema: object, cb: TraverseCallback): void; declare function traverse(schema: object, opts: TraverseOptions, cb?: TraverseCallback): void; // aliases type TraverseCallback = traverse.TraverseCallback; type TraverseOptions = traverse.TraverseOptions; type TraverseCallbackDef = traverse.TraverseCallbackDef; declare namespace traverse { const keywords: { additionalItems: true; items: true; contains: true; additionalProperties: true; propertyNames: true; not: true; if: true; then: true; else: true; }; const arrayKeywords: { items: true; allOf: true; anyOf: true; oneOf: true; }; const propsKeywords: { definitions: true; properties: true; patternProperties: true; dependencies: true; }; const skipKeywords: { default: true; enum: true; const: true; required: true; maximum: true; minimum: true; exclusiveMaximum: true; exclusiveMinimum: true; multipleOf: true; maxLength: true; minLength: true; pattern: true; format: true; maxItems: true; minItems: true; uniqueItems: true; maxProperties: true; minProperties: true; }; interface TraverseOptions { /** * Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), * including the root schema, in pre-order traversal. Schema references (`$ref`) are not resolved, * they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` * will be called before traversing child elements, and `post` will be called * after all child elementshave been traversed. */ cb?: TraverseCallback; /** Without option allKeys: true callback will be called only with root schema. */ allKeys?: boolean; } type TraverseCallback = | TraverseCallbackDef | { pre?: TraverseCallbackDef; post?: TraverseCallbackDef; }; interface TraverseCallbackDef { ( /** the current schema object */ schema: object, /** from the root schema to the current schema object */ jsonPtr: string, /** the schema passed to traverse object */ rootSchema: object, /** from the root schema to the parent schema object */ parentJsonPtr: string, /** the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) */ parentKeyword: string, /** * not necessarily parent `object`/`array`; * in the example above the parent schema for `{type: 'string'}` is the root schema */ parentSchema: object, /** * index or property name in the `array`/`object` containing multiple schemas; * in the example above for `{type: 'string'}` the property name is `foo` */ keyIndex: string | number, ): void; } } export = traverse;
mit
seryl/traefik
integration/vendor/github.com/docker/libcompose/yaml/external.go
947
package yaml import ( "fmt" ) // External represents an external network entry in compose file. // It can be a boolean (true|false) or have a name type External struct { External bool Name string } // MarshalYAML implements the Marshaller interface. func (n External) MarshalYAML() (tag string, value interface{}, err error) { if n.Name == "" { return "", n.External, nil } return "", map[string]interface{}{ "name": n.Name, }, nil } // UnmarshalYAML implements the Unmarshaller interface. func (n *External) UnmarshalYAML(tag string, value interface{}) error { switch v := value.(type) { case bool: n.External = v case map[interface{}]interface{}: for mapKey, mapValue := range v { switch mapKey { case "name": n.Name = mapValue.(string) default: // Ignore unknown keys continue } } n.External = true default: return fmt.Errorf("Failed to unmarshal External: %#v", value) } return nil }
mit
Omegaphora/external_robolectric
src/test/java/com/xtremelabs/robolectric/shadows/ContextTest.java
7904
package com.xtremelabs.robolectric.shadows; import android.app.Activity; import android.content.Context; import com.xtremelabs.robolectric.WithTestDefaultsRunner; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(WithTestDefaultsRunner.class) public class ContextTest { private Context context; @Before public void setUp() throws Exception { context = new Activity(); deleteDir(context.getFilesDir()); deleteDir(context.getCacheDir()); File[] files = context.getFilesDir().listFiles(); assertNotNull(files); assertThat(files.length, is(0)); File[] cachedFiles = context.getFilesDir().listFiles(); assertNotNull(cachedFiles); assertThat(cachedFiles.length, is(0)); } @After public void after() { deleteDir(context.getFilesDir()); deleteDir(context.getCacheDir()); deleteDir(context.getExternalCacheDir()); deleteDir(context.getExternalFilesDir(null)); } public void deleteDir(File path) { if (path.isDirectory()) { File[] files = path.listFiles(); assertNotNull(files); for (File f : files) { deleteDir(f); } } path.delete(); } @Test public void shouldGetApplicationDataDirectory() throws IOException { File dataDir = new File(ShadowContext.FILES_DIR, "data"); assertThat(dataDir.mkdir(), is(true)); dataDir = context.getDir("data", Context.MODE_PRIVATE); assertThat(dataDir, not(nullValue())); assertThat(dataDir.exists(), is(true)); } @Test public void shouldCreateIfDoesNotExistAndGetApplicationDataDirectory() { File dataDir = new File(ShadowContext.FILES_DIR, "data"); assertThat(dataDir.exists(), is(false)); dataDir = context.getDir("data", Context.MODE_PRIVATE); assertThat(dataDir, not(nullValue())); assertThat(dataDir.exists(), is(true)); } @Test public void shouldStubThemeStuff() throws Exception { assertThat(context.obtainStyledAttributes(null), not(nullValue())); assertThat(context.obtainStyledAttributes(0, null), not(nullValue())); assertThat(context.obtainStyledAttributes(null, null), not(nullValue())); assertThat(context.obtainStyledAttributes(null, null, 0, 0), not(nullValue())); } @Test public void getCacheDir_shouldCreateDirectory() throws Exception { assertTrue(context.getCacheDir().exists()); } @Test public void getExternalCacheDir_shouldCreateDirectory() throws Exception { assertTrue(context.getExternalCacheDir().exists()); } @Test public void shouldWriteToCacheDir() throws Exception { assertNotNull(context.getCacheDir()); File cacheTest = new File(context.getCacheDir(), "__test__"); assertThat(cacheTest.getPath(), CoreMatchers.containsString("android-cache")); FileOutputStream fos = null; try { fos = new FileOutputStream(cacheTest); fos.write("test".getBytes()); } finally { if (fos != null) fos.close(); } assertTrue(cacheTest.exists()); } @Test public void shouldWriteToExternalCacheDir() throws Exception { assertNotNull(context.getExternalCacheDir()); File cacheTest = new File(context.getExternalCacheDir(), "__test__"); assertThat(cacheTest.getPath(), containsString("android-external-cache")); FileOutputStream fos = null; try { fos = new FileOutputStream(cacheTest); fos.write("test".getBytes()); } finally { if (fos != null) fos.close(); } assertTrue(cacheTest.exists()); } @Test public void getFilesDir_shouldCreateDirectory() throws Exception { assertTrue(context.getFilesDir().exists()); } @Test public void getExternalFilesDir_shouldCreateDirectory() throws Exception { assertTrue(context.getExternalFilesDir(null).exists()); } @Test public void getExternalFilesDir_shouldCreateNamedDirectory() throws Exception { File f = context.getExternalFilesDir("__test__"); assertTrue(f.exists()); assertTrue(f.getAbsolutePath().endsWith("__test__")); } @Test public void openFileInput_shouldReturnAFileInputStream() throws Exception { String fileContents = "blah"; File file = new File(context.getFilesDir(), "__test__"); FileWriter fileWriter = new FileWriter(file); fileWriter.write(fileContents); fileWriter.close(); FileInputStream fileInputStream = null; try { fileInputStream = context.openFileInput("__test__"); byte[] bytes = new byte[fileContents.length()]; fileInputStream.read(bytes); assertThat(bytes, equalTo(fileContents.getBytes())); } finally { if (fileInputStream != null) fileInputStream.close(); } } @Test(expected = IllegalArgumentException.class) public void openFileInput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception { FileInputStream fileInputStream = null; try { fileInputStream = context.openFileInput("data" + File.separator + "test"); } finally { if (fileInputStream != null) fileInputStream.close(); } } @Test public void openFileOutput_shouldReturnAFileOutputStream() throws Exception { File file = new File("__test__"); String fileContents = "blah"; FileOutputStream fileOutputStream = null; try { fileOutputStream = context.openFileOutput("__test__", -1); fileOutputStream.write(fileContents.getBytes()); } finally { if (fileOutputStream != null) fileOutputStream.close(); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName())); byte[] readBuffer = new byte[fileContents.length()]; fileInputStream.read(readBuffer); assertThat(new String(readBuffer), equalTo(fileContents)); } finally { if (fileInputStream != null) fileInputStream.close(); } } @Test(expected = IllegalArgumentException.class) public void openFileOutput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception { FileOutputStream fos = null; try { fos = context.openFileOutput(File.separator + "data" + File.separator + "test" + File.separator + "hi", 0); } finally { if (fos != null) fos.close(); } } @Test public void deleteFile_shouldReturnTrue() throws IOException { File filesDir = context.getFilesDir(); File file = new File(filesDir, "test.txt"); boolean successfully = file.createNewFile(); assertThat(successfully, is(true)); successfully = context.deleteFile(file.getName()); assertThat(successfully, is(true)); } @Test public void deleteFile_shouldReturnFalse() throws IOException { File filesDir = context.getFilesDir(); File file = new File(filesDir, "test.txt"); boolean successfully = context.deleteFile(file.getName()); assertThat(successfully, is(false)); } }
mit
extend1994/cdnjs
ajax/libs/leaflet.toolbar.js/0.1.2/leaflet.toolbar-src.js
8922
(function(window, document, undefined) { "use strict"; L.Toolbar = L.Class.extend({ statics: { baseClass: 'leaflet-toolbar' }, includes: L.Mixin.Events, options: { className: '', filter: function() { return true; }, actions: [] }, initialize: function(options) { L.setOptions(this, options); this._toolbar_type = this.constructor._toolbar_class_id; }, addTo: function(map) { this._arguments = [].slice.call(arguments); map.addLayer(this); return this; }, onAdd: function(map) { var currentToolbar = map._toolbars[this._toolbar_type]; if (this._calculateDepth() === 0) { if (currentToolbar) { map.removeLayer(currentToolbar); } map._toolbars[this._toolbar_type] = this; } }, onRemove: function(map) { /* * TODO: Cleanup event listeners. * For some reason, this throws: * "Uncaught TypeError: Cannot read property 'dragging' of null" * on this._marker when a toolbar icon is clicked. */ // for (var i = 0, l = this._disabledEvents.length; i < l; i++) { // L.DomEvent.off(this._ul, this._disabledEvents[i], L.DomEvent.stopPropagation); // } if (this._calculateDepth() === 0) { delete map._toolbars[this._toolbar_type]; } }, appendToContainer: function(container) { var baseClass = this.constructor.baseClass + '-' + this._calculateDepth(), className = baseClass + ' ' + this.options.className, Action, action, i, j, l, m; this._container = container; this._ul = L.DomUtil.create('ul', className, container); /* Ensure that clicks, drags, etc. don't bubble up to the map. */ this._disabledEvents = ['click', 'mousemove', 'dblclick']; for (j = 0, m = this._disabledEvents.length; j < m; j++) { L.DomEvent.on(this._ul, this._disabledEvents[j], L.DomEvent.stopPropagation); } /* Instantiate each toolbar action and add its corresponding toolbar icon. */ for (i = 0, l = this.options.actions.length; i < l; i++) { Action = this._getActionConstructor(this.options.actions[i]); action = new Action(); action._createIcon(this, this._ul, this._arguments); } }, _getActionConstructor: function(Action) { var args = this._arguments, toolbar = this; return Action.extend({ initialize: function() { Action.prototype.initialize.apply(this, args); }, enable: function() { /* Ensure that only one action in a toolbar will be active at a time. */ if (toolbar._active) { toolbar._active.disable(); } toolbar._active = this; Action.prototype.enable.call(this); } }); }, /* Used to hide subToolbars without removing them from the map. */ _hide: function() { this._ul.style.display = 'none'; }, /* Used to show subToolbars without removing them from the map. */ _show: function() { this._ul.style.display = 'block'; }, _calculateDepth: function() { var depth = 0, toolbar = this.parentToolbar; while (toolbar) { depth += 1; toolbar = toolbar.parentToolbar; } return depth; } }); L.toolbar = {}; var toolbar_class_id = 0; L.Toolbar.extend = function extend(props) { var statics = L.extend({}, props.statics, { "_toolbar_class_id": toolbar_class_id }); toolbar_class_id += 1; L.extend(props, { statics: statics }); return L.Class.extend.call(this, props); }; L.Map.addInitHook(function() { this._toolbars = {}; }); L.ToolbarAction = L.Handler.extend({ statics: { baseClass: 'leaflet-toolbar-icon' }, options: { toolbarIcon: { html: '', className: '', tooltip: '' }, subToolbar: new L.Toolbar() }, initialize: function(options) { var defaultIconOptions = L.ToolbarAction.prototype.options.toolbarIcon; L.setOptions(this, options); this.options.toolbarIcon = L.extend({}, defaultIconOptions, this.options.toolbarIcon); }, enable: function() { if (this._enabled) { return; } this._enabled = true; if (this.addHooks) { this.addHooks(); } }, disable: function() { if (!this._enabled) { return; } this._enabled = false; if (this.removeHooks) { this.removeHooks(); } }, _createIcon: function(toolbar, container, args) { var iconOptions = this.options.toolbarIcon; this.toolbar = toolbar; this._icon = L.DomUtil.create('li', '', container); this._link = L.DomUtil.create('a', '', this._icon); this._link.innerHTML = iconOptions.html; this._link.setAttribute('href', '#'); this._link.setAttribute('title', iconOptions.tooltip); L.DomUtil.addClass(this._link, this.constructor.baseClass); if (iconOptions.className) { L.DomUtil.addClass(this._link, iconOptions.className); } L.DomEvent.on(this._link, 'click', this.enable, this); /* Add secondary toolbar */ this._addSubToolbar(toolbar, this._icon, args); }, _addSubToolbar: function(toolbar, container, args) { var subToolbar = this.options.subToolbar, addHooks = this.addHooks, removeHooks = this.removeHooks; /* For calculating the nesting depth. */ subToolbar.parentToolbar = toolbar; if (subToolbar.options.actions.length > 0) { /* Make a copy of args so as not to pollute the args array used by other actions. */ args = [].slice.call(args); args.push(this); subToolbar.addTo.apply(subToolbar, args); subToolbar.appendToContainer(container); this.addHooks = function(map) { if (typeof addHooks === 'function') { addHooks.call(this, map); } subToolbar._show(); }; this.removeHooks = function(map) { if (typeof removeHooks === 'function') { removeHooks.call(this, map); } subToolbar._hide(); }; } } }); L.toolbarAction = function toolbarAction(options) { return new L.ToolbarAction(options); }; L.ToolbarAction.extendOptions = function(options) { return this.extend({ options: options }); }; L.Toolbar.Control = L.Toolbar.extend({ statics: { baseClass: 'leaflet-control-toolbar ' + L.Toolbar.baseClass }, initialize: function(options) { L.Toolbar.prototype.initialize.call(this, options); this._control = new L.Control.Toolbar(this.options); }, onAdd: function(map) { this._control.addTo(map); L.Toolbar.prototype.onAdd.call(this, map); this.appendToContainer(this._control.getContainer()); }, onRemove: function(map) { L.Toolbar.prototype.onRemove.call(this, map); this._control.removeFrom(map); } }); L.Control.Toolbar = L.Control.extend({ onAdd: function() { return L.DomUtil.create('div', ''); } }); L.toolbar.control = function(options) { return new L.Toolbar.Control(options); }; // A convenience class for built-in popup toolbars. L.Toolbar.Popup = L.Toolbar.extend({ statics: { baseClass: 'leaflet-popup-toolbar ' + L.Toolbar.baseClass }, options: { anchor: [0, 0] }, initialize: function(latlng, options) { L.Toolbar.prototype.initialize.call(this, options); /* * Developers can't pass a DivIcon in the options for L.Toolbar.Popup * (the use of DivIcons is an implementation detail which may change). */ this._marker = new L.Marker(latlng, { icon : new L.DivIcon({ className: this.options.className, iconAnchor: [0, 0] }) }); }, onAdd: function(map) { this._map = map; this._marker.addTo(map); L.Toolbar.prototype.onAdd.call(this, map); this.appendToContainer(this._marker._icon); this._setStyles(); }, onRemove: function(map) { map.removeLayer(this._marker); L.Toolbar.prototype.onRemove.call(this, map); delete this._map; }, setLatLng: function(latlng) { this._marker.setLatLng(latlng); return this; }, _setStyles: function() { var container = this._container, toolbar = this._ul, anchor = L.point(this.options.anchor), icons = toolbar.querySelectorAll('.leaflet-toolbar-icon'), buttonHeights = [], toolbarWidth = 0, toolbarHeight, tipSize, tipAnchor; /* Calculate the dimensions of the toolbar. */ for (var i = 0, l = icons.length; i < l; i++) { if (icons[i].parentNode.parentNode === toolbar) { buttonHeights.push(parseInt(L.DomUtil.getStyle(icons[i], 'height'), 10)); toolbarWidth += Math.ceil(parseFloat(L.DomUtil.getStyle(icons[i], 'width'))); } } toolbar.style.width = toolbarWidth + 'px'; /* Create and place the toolbar tip. */ this._tipContainer = L.DomUtil.create('div', 'leaflet-toolbar-tip-container', container); this._tipContainer.style.width = toolbarWidth + 'px'; this._tip = L.DomUtil.create('div', 'leaflet-toolbar-tip', this._tipContainer); /* Set the tipAnchor point. */ toolbarHeight = Math.max.apply(undefined, buttonHeights); tipSize = parseInt(L.DomUtil.getStyle(this._tip, 'width'), 10); tipAnchor = new L.Point(toolbarWidth/2, toolbarHeight + 0.7071*tipSize); /* The anchor option allows app developers to adjust the toolbar's position. */ container.style.marginLeft = (anchor.x - tipAnchor.x) + 'px'; container.style.marginTop = (anchor.y - tipAnchor.y) + 'px'; } }); L.toolbar.popup = function(options) { return new L.Toolbar.Popup(options); }; })(window, document);
mit
Phrlog/Geeker
backend/web/js/ckeditor/plugins/placeholder/lang/et.js
351
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("placeholder","et",{title:"Kohahoidja omadused",toolbar:"Kohahoidja loomine",text:"Kohahoidja tekst",edit:"Kohahoidja muutmine",textMissing:"Kohahoidja peab sisaldama teksti."});
mit
hfenton/concurrent-ruby
examples/thread_local_var_bench.rb
606
#!/usr/bin/env ruby #$: << File.expand_path('../../lib', __FILE__) require 'concurrent' require 'concurrent/atomic/thread_local_var' require 'benchmark' include Concurrent N_THREADS = 100 N_VARS = 100 vars = N_VARS.times.collect { ThreadLocalVar.new(0) } def test_threadlocal_perf(vars) threads = N_THREADS.times.collect do Thread.new do 10000.times do index = rand(N_VARS) var = vars[index] var.value = var.value + 1 end end end threads.each(&:join) end Benchmark.bmbm do |bm| bm.report('ThreadLocalVar') { test_threadlocal_perf(vars) } end
mit
Gudii/Rocket.Chat
server/startup/migrations/v067.js
283
RocketChat.Migrations.add({ version: 67, up: function() { if (RocketChat && RocketChat.models && RocketChat.models.LivechatDepartment) { RocketChat.models.LivechatDepartment.model.update({}, { $set: { showOnRegistration: true } }, { multi: true }); } } });
mit
oleg-andreyev/symfony
src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.php
3289
<?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\Form\Tests\Extension\Core\DataTransformer; use PHPUnit\Framework\TestCase; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class ValueToDuplicatesTransformerTest extends TestCase { private $transformer; protected function setUp(): void { $this->transformer = new ValueToDuplicatesTransformer(['a', 'b', 'c']); } protected function tearDown(): void { $this->transformer = null; } public function testTransform() { $output = [ 'a' => 'Foo', 'b' => 'Foo', 'c' => 'Foo', ]; $this->assertSame($output, $this->transformer->transform('Foo')); } public function testTransformEmpty() { $output = [ 'a' => null, 'b' => null, 'c' => null, ]; $this->assertSame($output, $this->transformer->transform(null)); } public function testReverseTransform() { $input = [ 'a' => 'Foo', 'b' => 'Foo', 'c' => 'Foo', ]; $this->assertSame('Foo', $this->transformer->reverseTransform($input)); } public function testReverseTransformCompletelyEmpty() { $input = [ 'a' => '', 'b' => '', 'c' => '', ]; $this->assertNull($this->transformer->reverseTransform($input)); } public function testReverseTransformCompletelyNull() { $input = [ 'a' => null, 'b' => null, 'c' => null, ]; $this->assertNull($this->transformer->reverseTransform($input)); } public function testReverseTransformEmptyArray() { $input = [ 'a' => [], 'b' => [], 'c' => [], ]; $this->assertNull($this->transformer->reverseTransform($input)); } public function testReverseTransformZeroString() { $input = [ 'a' => '0', 'b' => '0', 'c' => '0', ]; $this->assertSame('0', $this->transformer->reverseTransform($input)); } public function testReverseTransformPartiallyNull() { $this->expectException(TransformationFailedException::class); $input = [ 'a' => 'Foo', 'b' => 'Foo', 'c' => null, ]; $this->transformer->reverseTransform($input); } public function testReverseTransformDifferences() { $this->expectException(TransformationFailedException::class); $input = [ 'a' => 'Foo', 'b' => 'Bar', 'c' => 'Foo', ]; $this->transformer->reverseTransform($input); } public function testReverseTransformRequiresArray() { $this->expectException(TransformationFailedException::class); $this->transformer->reverseTransform('12345'); } }
mit
mojo1643/Dalal_v2
vendor/bundle/ruby/gems/redis-3.0.7/lib/redis/connection/ruby.rb
8350
require "redis/connection/registry" require "redis/connection/command_helper" require "redis/errors" require "socket" class Redis module Connection module SocketMixin CRLF = "\r\n".freeze def initialize(*args) super(*args) @timeout = nil @buffer = "" end def timeout=(timeout) if timeout && timeout > 0 @timeout = timeout else @timeout = nil end end def read(nbytes) result = @buffer.slice!(0, nbytes) while result.bytesize < nbytes result << _read_from_socket(nbytes - result.bytesize) end result end def gets crlf = nil while (crlf = @buffer.index(CRLF)) == nil @buffer << _read_from_socket(1024) end @buffer.slice!(0, crlf + CRLF.bytesize) end def _read_from_socket(nbytes) begin read_nonblock(nbytes) rescue Errno::EWOULDBLOCK, Errno::EAGAIN if IO.select([self], nil, nil, @timeout) retry else raise Redis::TimeoutError end end rescue EOFError raise Errno::ECONNRESET end end if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" require "timeout" class TCPSocket < ::TCPSocket include SocketMixin def self.connect(host, port, timeout) Timeout.timeout(timeout) do sock = new(host, port) sock end rescue Timeout::Error raise TimeoutError end end if defined?(::UNIXSocket) class UNIXSocket < ::UNIXSocket include SocketMixin def self.connect(path, timeout) Timeout.timeout(timeout) do sock = new(path) sock end rescue Timeout::Error raise TimeoutError end # JRuby raises Errno::EAGAIN on #read_nonblock even when IO.select # says it is readable (1.6.6, in both 1.8 and 1.9 mode). # Use the blocking #readpartial method instead. def _read_from_socket(nbytes) readpartial(nbytes) rescue EOFError raise Errno::ECONNRESET end end end else class TCPSocket < ::Socket include SocketMixin def self.connect_addrinfo(ai, port, timeout) sock = new(::Socket.const_get(ai[0]), Socket::SOCK_STREAM, 0) sockaddr = ::Socket.pack_sockaddr_in(port, ai[3]) begin sock.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS if IO.select(nil, [sock], nil, timeout) == nil raise TimeoutError end begin sock.connect_nonblock(sockaddr) rescue Errno::EISCONN end end sock end def self.connect(host, port, timeout) # Don't pass AI_ADDRCONFIG as flag to getaddrinfo(3) # # From the man page for getaddrinfo(3): # # If hints.ai_flags includes the AI_ADDRCONFIG flag, then IPv4 # addresses are returned in the list pointed to by res only if the # local system has at least one IPv4 address configured, and IPv6 # addresses are returned only if the local system has at least one # IPv6 address configured. The loopback address is not considered # for this case as valid as a configured address. # # We do want the IPv6 loopback address to be returned if applicable, # even if it is the only configured IPv6 address on the machine. # Also see: https://github.com/redis/redis-rb/pull/394. addrinfo = ::Socket.getaddrinfo(host, nil, Socket::AF_UNSPEC, Socket::SOCK_STREAM) # From the man page for getaddrinfo(3): # # Normally, the application should try using the addresses in the # order in which they are returned. The sorting function used # within getaddrinfo() is defined in RFC 3484 [...]. # addrinfo.each_with_index do |ai, i| begin return connect_addrinfo(ai, port, timeout) rescue SystemCallError # Raise if this was our last attempt. raise if addrinfo.length == i+1 end end end end class UNIXSocket < ::Socket include SocketMixin def self.connect(path, timeout) sock = new(::Socket::AF_UNIX, Socket::SOCK_STREAM, 0) sockaddr = ::Socket.pack_sockaddr_un(path) begin sock.connect_nonblock(sockaddr) rescue Errno::EINPROGRESS if IO.select(nil, [sock], nil, timeout) == nil raise TimeoutError end begin sock.connect_nonblock(sockaddr) rescue Errno::EISCONN end end sock end end end class Ruby include Redis::Connection::CommandHelper MINUS = "-".freeze PLUS = "+".freeze COLON = ":".freeze DOLLAR = "$".freeze ASTERISK = "*".freeze def self.connect(config) if config[:scheme] == "unix" sock = UNIXSocket.connect(config[:path], config[:timeout]) else sock = TCPSocket.connect(config[:host], config[:port], config[:timeout]) end instance = new(sock) instance.timeout = config[:timeout] instance.set_tcp_keepalive config[:tcp_keepalive] instance end if [:SOL_SOCKET, :SO_KEEPALIVE, :SOL_TCP, :TCP_KEEPIDLE, :TCP_KEEPINTVL, :TCP_KEEPCNT].all?{|c| Socket.const_defined? c} def set_tcp_keepalive(keepalive) return unless keepalive.is_a?(Hash) @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) @sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPIDLE, keepalive[:time]) @sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPINTVL, keepalive[:intvl]) @sock.setsockopt(Socket::SOL_TCP, Socket::TCP_KEEPCNT, keepalive[:probes]) end def get_tcp_keepalive { :time => @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPIDLE).int, :intvl => @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPINTVL).int, :probes => @sock.getsockopt(Socket::SOL_TCP, Socket::TCP_KEEPCNT).int, } end else def set_tcp_keepalive(keepalive) end def get_tcp_keepalive { } end end def initialize(sock) @sock = sock end def connected? !! @sock end def disconnect @sock.close rescue ensure @sock = nil end def timeout=(timeout) if @sock.respond_to?(:timeout=) @sock.timeout = timeout end end def write(command) @sock.write(build_command(command)) end def read line = @sock.gets reply_type = line.slice!(0, 1) format_reply(reply_type, line) rescue Errno::EAGAIN raise TimeoutError end def format_reply(reply_type, line) case reply_type when MINUS then format_error_reply(line) when PLUS then format_status_reply(line) when COLON then format_integer_reply(line) when DOLLAR then format_bulk_reply(line) when ASTERISK then format_multi_bulk_reply(line) else raise ProtocolError.new(reply_type) end end def format_error_reply(line) CommandError.new(line.strip) end def format_status_reply(line) line.strip end def format_integer_reply(line) line.to_i end def format_bulk_reply(line) bulklen = line.to_i return if bulklen == -1 reply = encode(@sock.read(bulklen)) @sock.read(2) # Discard CRLF. reply end def format_multi_bulk_reply(line) n = line.to_i return if n == -1 Array.new(n) { read } end end end end Redis::Connection.drivers << Redis::Connection::Ruby
mit
ryantheleach/SpongeAPI
src/main/java/org/spongepowered/api/data/manipulator/mutable/block/RailDirectionData.java
1927
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.manipulator.mutable.block; import org.spongepowered.api.data.manipulator.immutable.block.ImmutableRailDirectionData; import org.spongepowered.api.data.manipulator.mutable.VariantData; import org.spongepowered.api.data.type.RailDirection; import org.spongepowered.api.util.Direction; /** * An {@link VariantData} for the {@link RailDirection} of rails. The * primary difference between a {@link RailDirection} and {@link Direction} is * that a {@link RailDirection} can be ascending in the cardinal directions. */ public interface RailDirectionData extends VariantData<RailDirection, RailDirectionData, ImmutableRailDirectionData> { }
mit
joeyparrish/cdnjs
ajax/libs/highcharts/6.2.0/js/es-modules/modules/variwide.src.js
9656
/** * Highcharts variwide module * * (c) 2010-2018 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import H from '../parts/Globals.js'; import '../parts/AreaSeries.js'; var addEvent = H.addEvent, seriesType = H.seriesType, seriesTypes = H.seriesTypes, each = H.each, pick = H.pick; /** * A variwide chart (related to marimekko chart) is a column chart with a * variable width expressing a third dimension. * * @extends plotOptions.column * @excluding boostThreshold,crisp,depth,edgeColor,edgeWidth,groupZPadding * @product highcharts * @sample {highcharts} highcharts/demo/variwide/ * Variwide chart * @sample {highcharts} highcharts/series-variwide/inverted/ * Inverted variwide chart * @sample {highcharts} highcharts/series-variwide/datetime/ * Variwide columns on a datetime axis * @since 6.0.0 * @optionparent plotOptions.variwide */ seriesType('variwide', 'column', { /** * In a variwide chart, the point padding is 0 in order to express the * horizontal stacking of items. */ pointPadding: 0, /** * In a variwide chart, the group padding is 0 in order to express the * horizontal stacking of items. */ groupPadding: 0 }, { pointArrayMap: ['y', 'z'], parallelArrays: ['x', 'y', 'z'], processData: function () { this.totalZ = 0; this.relZ = []; seriesTypes.column.prototype.processData.call(this); each( this.xAxis.reversed ? this.zData.slice().reverse() : this.zData, function (z, i) { this.relZ[i] = this.totalZ; this.totalZ += z; }, this ); if (this.xAxis.categories) { this.xAxis.variwide = true; this.xAxis.zData = this.zData; // Used for label rank } }, /** * Translate an x value inside a given category index into the distorted * axis translation. * @param {Number} index The category index * @param {Number} x The X pixel position in undistorted axis pixels * @return {Number} Distorted X position */ postTranslate: function (index, x, point) { var axis = this.xAxis, relZ = this.relZ, i = axis.reversed ? relZ.length - index : index, goRight = axis.reversed ? -1 : 1, len = axis.len, totalZ = this.totalZ, linearSlotLeft = i / relZ.length * len, linearSlotRight = (i + goRight) / relZ.length * len, slotLeft = (pick(relZ[i], totalZ) / totalZ) * len, slotRight = (pick(relZ[i + goRight], totalZ) / totalZ) * len, xInsideLinearSlot = x - linearSlotLeft, ret; // Set crosshairWidth for every point (#8173) if (point) { point.crosshairWidth = slotRight - slotLeft; } ret = slotLeft + xInsideLinearSlot * (slotRight - slotLeft) / (linearSlotRight - linearSlotLeft); return ret; }, /** * Extend translation by distoring X position based on Z. */ translate: function () { // Temporarily disable crisping when computing original shapeArgs var crispOption = this.options.crisp, xAxis = this.xAxis; this.options.crisp = false; seriesTypes.column.prototype.translate.call(this); // Reset option this.options.crisp = crispOption; var inverted = this.chart.inverted, crisp = this.borderWidth % 2 / 2; // Distort the points to reflect z dimension each(this.points, function (point, i) { var left, right; if (xAxis.variwide) { left = this.postTranslate( i, point.shapeArgs.x, point ); right = this.postTranslate( i, point.shapeArgs.x + point.shapeArgs.width ); // For linear or datetime axes, the variwide column should start // with X and extend Z units, without modifying the axis. } else { left = point.plotX; right = xAxis.translate( point.x + point.z, 0, 0, 0, 1 ); } if (this.options.crisp) { left = Math.round(left) - crisp; right = Math.round(right) - crisp; } point.shapeArgs.x = left; point.shapeArgs.width = right - left; // Crosshair position (#8083) point.plotX = (left + right) / 2; // Adjust the tooltip position if (!inverted) { point.tooltipPos[0] = point.shapeArgs.x + point.shapeArgs.width / 2; } else { point.tooltipPos[1] = xAxis.len - point.shapeArgs.x - point.shapeArgs.width / 2; } }, this); } // Point functions }, { isValid: function () { return H.isNumber(this.y, true) && H.isNumber(this.z, true); } }); H.Tick.prototype.postTranslate = function (xy, xOrY, index) { var axis = this.axis, pos = xy[xOrY] - axis.pos; if (!axis.horiz) { pos = axis.len - pos; } pos = axis.series[0].postTranslate(index, pos); if (!axis.horiz) { pos = axis.len - pos; } xy[xOrY] = axis.pos + pos; }; // Same width as the category (#8083) addEvent(H.Axis, 'afterDrawCrosshair', function (e) { if (this.variwide && this.cross) { this.cross.attr('stroke-width', e.point && e.point.crosshairWidth); } }); // On a vertical axis, apply anti-collision logic to the labels. addEvent(H.Axis, 'afterRender', function () { var axis = this; if (!this.horiz && this.variwide) { this.chart.labelCollectors.push(function () { return H.map(axis.tickPositions, function (pos, i) { var label = axis.ticks[pos].label; label.labelrank = axis.zData[i]; return label; }); }); } }); addEvent(H.Tick, 'afterGetPosition', function (e) { var axis = this.axis, xOrY = axis.horiz ? 'x' : 'y'; if (axis.variwide) { this[xOrY + 'Orig'] = e.pos[xOrY]; this.postTranslate(e.pos, xOrY, this.pos); } }); H.wrap(H.Tick.prototype, 'getLabelPosition', function ( proceed, x, y, label, horiz, labelOptions, tickmarkOffset, index ) { var args = Array.prototype.slice.call(arguments, 1), xy, xOrY = horiz ? 'x' : 'y'; // Replace the x with the original x if (this.axis.variwide && typeof this[xOrY + 'Orig'] === 'number') { args[horiz ? 0 : 1] = this[xOrY + 'Orig']; } xy = proceed.apply(this, args); // Post-translate if (this.axis.variwide && this.axis.categories) { this.postTranslate(xy, xOrY, index); } return xy; }); /** * A `variwide` series. If the [type](#series.variwide.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @type {Object} * @extends series,plotOptions.variwide * @product highcharts * @apioption series.variwide */ /** * An array of data points for the series. For the `variwide` series type, * points can be given in the following ways: * * 1. An array of arrays with 3 or 2 values. In this case, the values * correspond to `x,y,z`. If the first value is a string, it is applied * as the name of the point, and the `x` value is inferred. The `x` * value can also be omitted, in which case the inner arrays should * be of length 2\. Then the `x` value is automatically calculated, * either starting at 0 and incremented by 1, or from `pointStart` and * `pointInterval` given in the series options. * * ```js * data: [ * [0, 1, 2], * [1, 5, 5], * [2, 0, 2] * ] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of data * points exceeds the series' [turboThreshold](#series.variwide.turboThreshold), * this option is not available. * * ```js * data: [{ * x: 1, * y: 1, * z: 1, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 5, * z: 4, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<Object|Array>} * @extends series.line.data * @excluding marker * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * @product highcharts * @apioption series.variwide.data */ /** * The relative width for each column. On a category axis, the widths are * distributed so they sum up to the X axis length. On linear and datetime axes, * the columns will be laid out from the X value and Z units along the axis. * * @type {Number} * @product highcharts * @apioption series.variwide.data.z */
mit
giangnguyennet/searchkick
test/reindex_v2_job_test.rb
777
require_relative "test_helper" class TestReindexV2Job < Minitest::Test def setup skip unless defined?(ActiveJob) super Searchkick.disable_callbacks end def teardown Searchkick.enable_callbacks end def test_create product = Product.create!(name: "Boom") Product.searchkick_index.refresh assert_search "*", [] Searchkick::ReindexV2Job.perform_later("Product", product.id.to_s) Product.searchkick_index.refresh assert_search "*", ["Boom"] end def test_destroy product = Product.create!(name: "Boom") Product.reindex assert_search "*", ["Boom"] product.destroy Searchkick::ReindexV2Job.perform_later("Product", product.id.to_s) Product.searchkick_index.refresh assert_search "*", [] end end
mit
hyonholee/azure-sdk-for-net
sdk/sqlmanagement/Microsoft.Azure.Management.SqlManagement/src/Generated/Models/RestorePointType.cs
1811
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Sql.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for RestorePointType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum RestorePointType { [EnumMember(Value = "CONTINUOUS")] CONTINUOUS, [EnumMember(Value = "DISCRETE")] DISCRETE } internal static class RestorePointTypeEnumExtension { internal static string ToSerializedValue(this RestorePointType? value) { return value == null ? null : ((RestorePointType)value).ToSerializedValue(); } internal static string ToSerializedValue(this RestorePointType value) { switch( value ) { case RestorePointType.CONTINUOUS: return "CONTINUOUS"; case RestorePointType.DISCRETE: return "DISCRETE"; } return null; } internal static RestorePointType? ParseRestorePointType(this string value) { switch( value ) { case "CONTINUOUS": return RestorePointType.CONTINUOUS; case "DISCRETE": return RestorePointType.DISCRETE; } return null; } } }
mit
afuechsel/openhab2
addons/binding/org.openhab.binding.tado/src/main/java/org/openhab/binding/tado/internal/TadoBindingConstants.java
2883
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.tado.internal; import org.eclipse.smarthome.core.thing.ThingTypeUID; /** * The {@link TadoBinding} class defines common constants, which are * used across the whole binding. * * @author Dennis Frommknecht - Initial contribution */ public class TadoBindingConstants { public static final String BINDING_ID = "tado"; // List of all Thing Type UIDs public final static ThingTypeUID THING_TYPE_HOME = new ThingTypeUID(BINDING_ID, "home"); public final static ThingTypeUID THING_TYPE_ZONE = new ThingTypeUID(BINDING_ID, "zone"); public final static ThingTypeUID THING_TYPE_MOBILE_DEVICE = new ThingTypeUID(BINDING_ID, "mobiledevice"); // List of all Channel IDs public final static String PROPERTY_HOME_TEMPERATURE_UNIT = "temperatureUnit"; public static enum TemperatureUnit { CELSIUS, FAHRENHEIT } public final static String CHANNEL_ZONE_CURRENT_TEMPERATURE = "currentTemperature"; public final static String CHANNEL_ZONE_HUMIDITY = "humidity"; public final static String CHANNEL_ZONE_HEATING_POWER = "heatingPower"; public final static String CHANNEL_ZONE_HVAC_MODE = "hvacMode"; public static enum HvacMode { OFF, HEAT, COOL, DRY, FAN, AUTO } public final static String CHANNEL_ZONE_TARGET_TEMPERATURE = "targetTemperature"; public final static String CHANNEL_ZONE_SWING = "swing"; public final static String CHANNEL_ZONE_FAN_SPEED = "fanspeed"; public static enum FanSpeed { LOW, MIDDLE, HIGH, AUTO } public final static String CHANNEL_ZONE_OPERATION_MODE = "operationMode"; public static enum OperationMode { SCHEDULE, TIMER, MANUAL, UNTIL_CHANGE } public final static String CHANNEL_ZONE_TIMER_DURATION = "timerDuration"; public final static String CHANNEL_ZONE_OVERLAY_EXPIRY = "overlayExpiry"; public final static String CHANNEL_MOBILE_DEVICE_AT_HOME = "atHome"; // Configuration public final static String CONFIG_ZONE_ID = "id"; public final static String CONFIG_MOBILE_DEVICE_ID = "id"; // Properties public final static String PROPERTY_ZONE_NAME = "name"; public final static String PROPERTY_ZONE_TYPE = "type"; public static enum ZoneType { HEATING, AIR_CONDITIONING, HOT_WATER } public final static String PROPERTY_MOBILE_DEVICE_NAME = "name"; }
epl-1.0
vedmaka/Revive-wikibiz-modified
www/admin/account-settings-maintenance.php
5002
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ // Require the initialisation file require_once '../../init.php'; // Required files require_once MAX_PATH . '/lib/OA/Admin/Option.php'; require_once MAX_PATH . '/lib/OA/Admin/Settings.php'; require_once MAX_PATH . '/lib/max/Plugin/Translation.php'; require_once MAX_PATH . '/www/admin/config.php'; require_once LIB_PATH . '/OperationInterval.php'; // Security check OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN); // Create a new option object for displaying the setting's page's HTML form $oOptions = new OA_Admin_Option('settings'); $prefSection = "maintenance"; // Prepare an array for storing error messages $aErrormessage = array(); // If the settings page is a submission, deal with the form data if (isset($_POST['submitok']) && $_POST['submitok'] == 'true') { // Prepare an array of the HTML elements to process, and the // location to save the values in the settings configuration // file $aElements = array(); // Maintenance Settings $aElements += array( 'maintenance_autoMaintenance' => array( 'maintenance' => 'autoMaintenance', 'bool' => true ), 'maintenance_operationInterval' => array('maintenance' => 'operationInterval') ); // Priority Settings $aElements += array( 'priority_instantUpdate' => array( 'priority' => 'instantUpdate', 'bool' => true ), 'priority_intentionalOverdelivery' => array('priority' => 'intentionalOverdelivery') ); // Create a new settings object, and save the settings! $oSettings = new OA_Admin_Settings(); $result = $oSettings->processSettingsFromForm($aElements); if ($result) { // Queue confirmation message $setPref = $oOptions->getSettingsPreferences($prefSection); $title = $setPref[$prefSection]['name']; $translation = new OX_Translation (); $translated_message = $translation->translate($GLOBALS['strXSettingsHaveBeenUpdated'], array(htmlspecialchars($title))); OA_Admin_UI::queueMessage($translated_message, 'local', 'confirm', 0); // The settings configuration file was written correctly, OX_Admin_Redirect::redirect(basename($_SERVER['SCRIPT_NAME'])); } // Could not write the settings configuration file, store this // error message and continue $aErrormessage[0][] = $strUnableToWriteConfig; } // Set the correct section of the settings pages and display the drop-down menu $setPref = $oOptions->getSettingsPreferences($prefSection); $title = $setPref[$prefSection]['name']; // Display the settings page's header and sections $oHeaderModel = new OA_Admin_UI_Model_PageHeaderModel($title); phpAds_PageHeader('account-settings-index', $oHeaderModel); // Prepare an array of HTML elements to display for the form, and // output using the $oOption object $aSettings = array ( array ( 'text' => $strMaintenanceSettings, 'items' => array ( array ( 'type' => 'checkbox', 'name' => 'maintenance_autoMaintenance', 'text' => $strEnableAutoMaintenance ), array ( 'type' => 'break' ), array ( 'type' => 'select', 'name' => 'maintenance_operationInterval', 'text' => $strMaintenanceOI, 'size' => 12, 'items' => array( 60 => 60, 30 => 30, 20 => 20, 15 => 15, 10 => 10, 5 => 5 ) ) ) ), array ( 'text' => $strPrioritySettings, 'items' => array ( array ( 'type' => 'checkbox', 'name' => 'priority_instantUpdate', 'text' => $strPriorityInstantUpdate ), array ( 'type' => 'break' ), array ( 'type' => 'text', 'name' => 'priority_intentionalOverdelivery', 'text' => $strPriorityIntentionalOverdelivery, 'check' => 'wholeNumber' ), ) ) ); $oOptions->show($aSettings, $aErrormessage); // Display the page footer phpAds_PageFooter(); ?>
gpl-2.0
ZephyrSurfer/dolphin
Source/Core/VideoBackends/Software/SWRenderer.cpp
4625
// Copyright 2009 Dolphin Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "VideoBackends/Software/SWRenderer.h" #include <string> #include "Common/CommonTypes.h" #include "Common/GL/GLContext.h" #include "Core/HW/Memmap.h" #include "VideoBackends/Software/EfbCopy.h" #include "VideoBackends/Software/EfbInterface.h" #include "VideoBackends/Software/SWBoundingBox.h" #include "VideoBackends/Software/SWOGLWindow.h" #include "VideoBackends/Software/SWTexture.h" #include "VideoCommon/AbstractPipeline.h" #include "VideoCommon/AbstractShader.h" #include "VideoCommon/AbstractTexture.h" #include "VideoCommon/NativeVertexFormat.h" #include "VideoCommon/VideoBackendBase.h" #include "VideoCommon/VideoCommon.h" namespace SW { SWRenderer::SWRenderer(std::unique_ptr<SWOGLWindow> window) : ::Renderer(static_cast<int>(std::max(window->GetContext()->GetBackBufferWidth(), 1u)), static_cast<int>(std::max(window->GetContext()->GetBackBufferHeight(), 1u)), 1.0f, AbstractTextureFormat::RGBA8), m_window(std::move(window)) { } bool SWRenderer::IsHeadless() const { return m_window->IsHeadless(); } std::unique_ptr<AbstractTexture> SWRenderer::CreateTexture(const TextureConfig& config, [[maybe_unused]] std::string_view name) { return std::make_unique<SWTexture>(config); } std::unique_ptr<AbstractStagingTexture> SWRenderer::CreateStagingTexture(StagingTextureType type, const TextureConfig& config) { return std::make_unique<SWStagingTexture>(type, config); } std::unique_ptr<AbstractFramebuffer> SWRenderer::CreateFramebuffer(AbstractTexture* color_attachment, AbstractTexture* depth_attachment) { return SWFramebuffer::Create(static_cast<SWTexture*>(color_attachment), static_cast<SWTexture*>(depth_attachment)); } void SWRenderer::BindBackbuffer(const ClearColor& clear_color) { // Look for framebuffer resizes if (!m_surface_resized.TestAndClear()) return; GLContext* context = m_window->GetContext(); context->Update(); m_backbuffer_width = context->GetBackBufferWidth(); m_backbuffer_height = context->GetBackBufferHeight(); } class SWShader final : public AbstractShader { public: explicit SWShader(ShaderStage stage) : AbstractShader(stage) {} ~SWShader() = default; BinaryData GetBinary() const override { return {}; } }; std::unique_ptr<AbstractShader> SWRenderer::CreateShaderFromSource(ShaderStage stage, [[maybe_unused]] std::string_view source, [[maybe_unused]] std::string_view name) { return std::make_unique<SWShader>(stage); } std::unique_ptr<AbstractShader> SWRenderer::CreateShaderFromBinary(ShaderStage stage, const void* data, size_t length, [[maybe_unused]] std::string_view name) { return std::make_unique<SWShader>(stage); } class SWPipeline final : public AbstractPipeline { public: SWPipeline() = default; ~SWPipeline() override = default; }; std::unique_ptr<AbstractPipeline> SWRenderer::CreatePipeline(const AbstractPipelineConfig& config, const void* cache_data, size_t cache_data_length) { return std::make_unique<SWPipeline>(); } // Called on the GPU thread void SWRenderer::RenderXFBToScreen(const MathUtil::Rectangle<int>& target_rc, const AbstractTexture* source_texture, const MathUtil::Rectangle<int>& source_rc) { if (!IsHeadless()) m_window->ShowImage(source_texture, source_rc); } u32 SWRenderer::AccessEFB(EFBAccessType type, u32 x, u32 y, u32 InputData) { u32 value = 0; switch (type) { case EFBAccessType::PeekZ: { value = EfbInterface::GetDepth(x, y); break; } case EFBAccessType::PeekColor: { const u32 color = EfbInterface::GetColor(x, y); // rgba to argb value = (color >> 8) | (color & 0xff) << 24; break; } default: break; } return value; } std::unique_ptr<BoundingBox> SWRenderer::CreateBoundingBox() const { return std::make_unique<SWBoundingBox>(); } void SWRenderer::ClearScreen(const MathUtil::Rectangle<int>& rc, bool colorEnable, bool alphaEnable, bool zEnable, u32 color, u32 z) { EfbCopy::ClearEfb(); } std::unique_ptr<NativeVertexFormat> SWRenderer::CreateNativeVertexFormat(const PortableVertexDeclaration& vtx_decl) { return std::make_unique<NativeVertexFormat>(vtx_decl); } } // namespace SW
gpl-2.0
drupalprojects/console
Test/Generator/JsTestGeneratorTest.php
1200
<?php /** * @file * Contains Drupal\Console\Test\Generator\JsTestGeneratorTest. */ namespace Drupal\Console\Test\Generator; use Drupal\Console\Generator\JsTestGenerator; use Drupal\Console\Test\DataProvider\JsTestDataProviderTrait; class JsTestGeneratorTest extends GeneratorTest { use JsTestDataProviderTrait; /** * JavaScript test generator test * * @param $module * @param $class_name * * @dataProvider commandData */ public function testGenerateJsTest( $module, $class_name ) { $generator = new JsTestGenerator(); $this->getRenderHelper()->setSkeletonDirs($this->getSkeletonDirs()); $this->getRenderHelper()->setTranslator($this->getTranslatorHelper()); $generator->setHelperSet($this->getHelperSet()); $generator->generate( $module, $class_name ); $files = [ $generator->getSite()->getJsTestsPath($module) . "/$class_name.php", ]; foreach ($files as $file) { $this->assertTrue( file_exists($file), sprintf('%s does not exist', $file) ); } } }
gpl-2.0
glukolog/xcsoar
src/Util/WCharUtil.hpp
3193
/* * Copyright (C) 2011-2015 Max Kellermann <max@duempel.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WCHAR_UTIL_HPP #define WCHAR_UTIL_HPP #include <wchar.h> constexpr static inline bool IsASCII(const wchar_t ch) { return (ch & ~0x7f) == 0; } constexpr static inline bool IsWhitespaceOrNull(const wchar_t ch) { return (unsigned)ch <= 0x20; } constexpr static inline bool IsWhitespaceNotNull(const wchar_t ch) { return ch > 0 && ch <= 0x20; } /** * Is the given character whitespace? This calls the faster one of * IsWhitespaceOrNull() or IsWhitespaceNotNull(). Use this if you * want the fastest implementation, and you don't care if a null byte * matches. */ constexpr static inline bool IsWhitespaceFast(const wchar_t ch) { return IsWhitespaceOrNull(ch); } constexpr static inline bool IsPrintableASCII(wchar_t ch) { return IsASCII(ch) && ch >= 0x20; } constexpr static inline bool IsDigitASCII(wchar_t ch) { return ch >= '0' && ch <= '9'; } constexpr static inline bool IsUpperAlphaASCII(wchar_t ch) { return ch >= 'A' && ch <= 'Z'; } constexpr static inline bool IsLowerAlphaASCII(wchar_t ch) { return ch >= 'a' && ch <= 'z'; } constexpr static inline bool IsAlphaASCII(wchar_t ch) { return IsUpperAlphaASCII(ch) || IsLowerAlphaASCII(ch); } constexpr static inline bool IsAlphaNumericASCII(wchar_t ch) { return IsAlphaASCII(ch) || IsDigitASCII(ch); } /** * Convert the specified ASCII character (0x00..0x7f) to upper case. * Unlike toupper(), it ignores the system locale. */ constexpr static inline wchar_t ToUpperASCII(wchar_t ch) { return ch >= 'a' && ch <= 'z' ? (ch - ('a' - 'A')) : ch; } /** * Convert the specified ASCII character (0x00..0x7f) to lower case. * Unlike tolower(), it ignores the system locale. */ constexpr static inline wchar_t ToLowerASCII(wchar_t ch) { return ch >= 'A' && ch <= 'Z' ? (ch + ('a' - 'A')) : ch; } #endif
gpl-2.0
bstark-synergy/CCC-drupal8
libraries/jquery.intl-tel-input/src/spec/tests/methods/getNumber.js
1994
"use strict"; describe("getNumber: ", function() { describe("initialising plugin with valid US number and utils.js", function() { beforeEach(function() { intlSetup(true); input = $("<input value='+17024181234'>"); input.intlTelInput(); }); afterEach(function() { input.intlTelInput("destroy"); input = null; }); it("calling getNumber with no args returns the number as E.164", function() { expect(input.intlTelInput("getNumber")).toEqual("+17024181234"); }); it("calling getNumber with format=INTERNATIONAL", function() { expect(input.intlTelInput("getNumber", intlTelInputUtils.numberFormat.INTERNATIONAL)).toEqual("+1 702-418-1234"); }); it("calling getNumber with format=NATIONAL", function() { expect(input.intlTelInput("getNumber", intlTelInputUtils.numberFormat.NATIONAL)).toEqual("(702) 418-1234"); }); }); describe("initialising plugin with utils.js", function() { beforeEach(function() { intlSetup(true); input = $("<input>"); input.intlTelInput(); }); afterEach(function() { input.intlTelInput("destroy"); input = null; }); describe("selecting American Samoa and then typing a national number", function() { beforeEach(function() { selectFlag("as"); input.val("9785585898").keyup(); }); it("getNumber returns the correct number (with full dialcode/area code)", function() { expect(input.intlTelInput("getNumber")).toEqual("+16849785585898"); }); }); describe("typing a full international number for Anguilla", function() { beforeEach(function() { // important that this test contains formatting because that caused a bug before input.val("+1 264-235-1234").keyup(); }); it("getNumber returns the correct number", function() { expect(input.intlTelInput("getNumber")).toEqual("+12642351234"); }); }); }); });
gpl-2.0
itamair/italomairo
sites/all/modules/ckeditor/ckfinder/plugins/fileeditor/codemirror/js/tokenizejavascript.js
6771
/* Tokenizer for JavaScript code */ var tokenizeJavaScript = (function() { // Advance the stream until the given character (not preceded by a // backslash) is encountered, or the end of the line is reached. function nextUntilUnescaped(source, end) { var escaped = false; while (!source.endOfLine()) { var next = source.next(); if (next == end && !escaped) return false; escaped = !escaped && next == "\\"; } return escaped; } // A map of JavaScript's keywords. The a/b/c keyword distinction is // very rough, but it gives the parser enough information to parse // correct code correctly (we don't care that much how we parse // incorrect code). The style information included in these objects // is used by the highlighter to pick the correct CSS style for a // token. var keywords = function(){ function result(type, style){ return {type: type, style: "js-" + style}; } // keywords that take a parenthised expression, and then a // statement (if) var keywordA = result("keyword a", "keyword"); // keywords that take just a statement (else) var keywordB = result("keyword b", "keyword"); // keywords that optionally take an expression, and form a // statement (return) var keywordC = result("keyword c", "keyword"); var operator = result("operator", "keyword"); var atom = result("atom", "atom"); return { "if": keywordA, "while": keywordA, "with": keywordA, "else": keywordB, "do": keywordB, "try": keywordB, "finally": keywordB, "return": keywordC, "break": keywordC, "continue": keywordC, "new": keywordC, "delete": keywordC, "throw": keywordC, "in": operator, "typeof": operator, "instanceof": operator, "var": result("var", "keyword"), "function": result("function", "keyword"), "catch": result("catch", "keyword"), "for": result("for", "keyword"), "switch": result("switch", "keyword"), "case": result("case", "keyword"), "default": result("default", "keyword"), "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom }; }(); // Some helper regexps var isOperatorChar = /[+\-*&%=<>!?|]/; var isHexDigit = /[0-9A-Fa-f]/; var isWordChar = /[\w\$_]/; // Wrapper around jsToken that helps maintain parser state (whether // we are inside of a multi-line comment and whether the next token // could be a regular expression). function jsTokenState(inside, regexp) { return function(source, setState) { var newInside = inside; var type = jsToken(inside, regexp, source, function(c) {newInside = c;}); var newRegexp = type.type == "operator" || type.type == "keyword c" || type.type.match(/^[\[{}\(,;:]$/); if (newRegexp != regexp || newInside != inside) setState(jsTokenState(newInside, newRegexp)); return type; }; } // The token reader, inteded to be used by the tokenizer from // tokenize.js (through jsTokenState). Advances the source stream // over a token, and returns an object containing the type and style // of that token. function jsToken(inside, regexp, source, setInside) { function readHexNumber(){ source.next(); // skip the 'x' source.nextWhileMatches(isHexDigit); return {type: "number", style: "js-atom"}; } function readNumber() { source.nextWhileMatches(/[0-9]/); if (source.equals(".")){ source.next(); source.nextWhileMatches(/[0-9]/); } if (source.equals("e") || source.equals("E")){ source.next(); if (source.equals("-")) source.next(); source.nextWhileMatches(/[0-9]/); } return {type: "number", style: "js-atom"}; } // Read a word, look it up in keywords. If not found, it is a // variable, otherwise it is a keyword of the type found. function readWord() { source.nextWhileMatches(isWordChar); var word = source.get(); var known = keywords.hasOwnProperty(word) && keywords.propertyIsEnumerable(word) && keywords[word]; return known ? {type: known.type, style: known.style, content: word} : {type: "variable", style: "js-variable", content: word}; } function readRegexp() { nextUntilUnescaped(source, "/"); source.nextWhileMatches(/[gi]/); return {type: "regexp", style: "js-string"}; } // Mutli-line comments are tricky. We want to return the newlines // embedded in them as regular newline tokens, and then continue // returning a comment token for every line of the comment. So // some state has to be saved (inside) to indicate whether we are // inside a /* */ sequence. function readMultilineComment(start){ var newInside = "/*"; var maybeEnd = (start == "*"); while (true) { if (source.endOfLine()) break; var next = source.next(); if (next == "/" && maybeEnd){ newInside = null; break; } maybeEnd = (next == "*"); } setInside(newInside); return {type: "comment", style: "js-comment"}; } function readOperator() { source.nextWhileMatches(isOperatorChar); return {type: "operator", style: "js-operator"}; } function readString(quote) { var endBackSlash = nextUntilUnescaped(source, quote); setInside(endBackSlash ? quote : null); return {type: "string", style: "js-string"}; } // Fetch the next token. Dispatches on first character in the // stream, or first two characters when the first is a slash. if (inside == "\"" || inside == "'") return readString(inside); var ch = source.next(); if (inside == "/*") return readMultilineComment(ch); else if (ch == "\"" || ch == "'") return readString(ch); // with punctuation, the type of the token is the symbol itself else if (/[\[\]{}\(\),;\:\.]/.test(ch)) return {type: ch, style: "js-punctuation"}; else if (ch == "0" && (source.equals("x") || source.equals("X"))) return readHexNumber(); else if (/[0-9]/.test(ch)) return readNumber(); else if (ch == "/"){ if (source.equals("*")) { source.next(); return readMultilineComment(ch); } else if (source.equals("/")) { nextUntilUnescaped(source, null); return {type: "comment", style: "js-comment"};} else if (regexp) return readRegexp(); else return readOperator(); } else if (isOperatorChar.test(ch)) return readOperator(); else return readWord(); } // The external interface to the tokenizer. return function(source, startState) { return tokenizer(source, startState || jsTokenState(false, true)); }; })();
gpl-2.0
Gargamel1989/ThreesandUO
Scripts/Mobiles/Vendors/SBInfo/SBButcher.cs
1791
using System; using System.Collections.Generic; using Server.Items; namespace Server.Mobiles { public class SBButcher : SBInfo { private List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo(); private IShopSellInfo m_SellInfo = new InternalSellInfo(); public SBButcher() { } public override IShopSellInfo SellInfo { get { return m_SellInfo; } } public override List<GenericBuyInfo> BuyInfo { get { return m_BuyInfo; } } public class InternalBuyInfo : List<GenericBuyInfo> { public InternalBuyInfo() { Add( new GenericBuyInfo( typeof( Bacon ), 7, 20, 0x979, 0 ) ); Add( new GenericBuyInfo( typeof( Ham ), 26, 20, 0x9C9, 0 ) ); Add( new GenericBuyInfo( typeof( Sausage ), 18, 20, 0x9C0, 0 ) ); Add( new GenericBuyInfo( typeof( RawChickenLeg ), 6, 20, 0x1607, 0 ) ); Add( new GenericBuyInfo( typeof( RawBird ), 9, 20, 0x9B9, 0 ) ); Add( new GenericBuyInfo( typeof( RawLambLeg ), 9, 20, 0x1609, 0 ) ); Add( new GenericBuyInfo( typeof( RawRibs ), 16, 20, 0x9F1, 0 ) ); Add( new GenericBuyInfo( typeof( ButcherKnife ), 13, 20, 0x13F6, 0 ) ); Add( new GenericBuyInfo( typeof( Cleaver ), 13, 20, 0xEC3, 0 ) ); Add( new GenericBuyInfo( typeof( SkinningKnife ), 13, 20, 0xEC4, 0 ) ); } } public class InternalSellInfo : GenericSellInfo { public InternalSellInfo() { Add( typeof( RawRibs ), 8 ); Add( typeof( RawLambLeg ), 4 ); Add( typeof( RawChickenLeg ), 3 ); Add( typeof( RawBird ), 4 ); Add( typeof( Bacon ), 3 ); Add( typeof( Sausage ), 9 ); Add( typeof( Ham ), 13 ); Add( typeof( ButcherKnife ), 7 ); Add( typeof( Cleaver ), 7 ); Add( typeof( SkinningKnife ), 7 ); } } } }
gpl-2.0
Gargamel1989/ThreesandUO
Scripts/Items/Aquarium/AquariumFood.cs
639
using System; using Server; using Server.Mobiles; namespace Server.Items { public class AquariumFood : Item { public override int LabelNumber{ get{ return 1074819; } } // Aquarium food [Constructable] public AquariumFood() : base( 0xEFC ) { } public AquariumFood( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
gpl-2.0
chrjoh/Demo-shop
test/functional/store_controller_test.rb
162
require 'test_helper' class StoreControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success end end
gpl-3.0
SysBind/moodle
mod/lesson/report.php
17317
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Displays the lesson statistics. * * @package mod_lesson * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late **/ require_once('../../config.php'); require_once($CFG->dirroot.'/mod/lesson/locallib.php'); $id = required_param('id', PARAM_INT); // Course Module ID $pageid = optional_param('pageid', null, PARAM_INT); // Lesson Page ID $action = optional_param('action', 'reportoverview', PARAM_ALPHA); // action to take $nothingtodisplay = false; $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST); $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST)); require_login($course, false, $cm); $currentgroup = groups_get_activity_group($cm, true); $context = context_module::instance($cm->id); require_capability('mod/lesson:viewreports', $context); $url = new moodle_url('/mod/lesson/report.php', array('id'=>$id)); $url->param('action', $action); if ($pageid !== null) { $url->param('pageid', $pageid); } $PAGE->set_url($url); if ($action == 'reportdetail') { $PAGE->navbar->add(get_string('report', 'lesson'), $url); } $lessonoutput = $PAGE->get_renderer('mod_lesson'); $reportactionmenu = new \mod_lesson\output\report_action_menu($id, $url); $reportactionarea = $lessonoutput->render($reportactionmenu); if ($action === 'delete') { /// Process any form data before fetching attempts, grades and times if (has_capability('mod/lesson:edit', $context) and $form = data_submitted() and confirm_sesskey()) { /// Cycle through array of userids with nested arrays of tries if (!empty($form->attempts)) { foreach ($form->attempts as $userid => $tries) { // Modifier IS VERY IMPORTANT! What does it do? // Well, it is for when you delete multiple attempts for the same user. // If you delete try 1 and 3 for a user, then after deleting try 1, try 3 then // becomes try 2 (because try 1 is gone and all tries after try 1 get decremented). // So, the modifier makes sure that the submitted try refers to the current try in the // database - hope this all makes sense :) $modifier = 0; foreach ($tries as $try => $junk) { $try -= $modifier; /// Clean up the timer table by removing using the order - this is silly, it should be linked to specific attempt (skodak) $timers = $lesson->get_user_timers($userid, 'starttime', 'id', $try, 1); if ($timers) { $timer = reset($timers); $DB->delete_records('lesson_timer', array('id' => $timer->id)); } $params = array ("userid" => $userid, "lessonid" => $lesson->id); // Remove the grade from the grades tables - this is silly, it should be linked to specific attempt (skodak). $grades = $DB->get_records_sql("SELECT id FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid ORDER BY completed", $params, $try, 1); if ($grades) { $grade = reset($grades); $DB->delete_records('lesson_grades', array('id' => $grade->id)); } /// Remove attempts and update the retry number $DB->delete_records('lesson_attempts', array('userid' => $userid, 'lessonid' => $lesson->id, 'retry' => $try)); $DB->execute("UPDATE {lesson_attempts} SET retry = retry - 1 WHERE userid = ? AND lessonid = ? AND retry > ?", array($userid, $lesson->id, $try)); /// Remove seen branches and update the retry number $DB->delete_records('lesson_branch', array('userid' => $userid, 'lessonid' => $lesson->id, 'retry' => $try)); $DB->execute("UPDATE {lesson_branch} SET retry = retry - 1 WHERE userid = ? AND lessonid = ? AND retry > ?", array($userid, $lesson->id, $try)); /// update central gradebook lesson_update_grades($lesson, $userid); $modifier++; } } } } redirect(new moodle_url($PAGE->url, array('action'=>'reportoverview'))); } else if ($action === 'reportoverview') { /************************************************************************** this action is for default view and overview view **************************************************************************/ // Get the table and data for build statistics. list($table, $data) = lesson_get_overview_report_table_and_data($lesson, $currentgroup); if ($table === false) { echo $lessonoutput->header($lesson, $cm, $action, false, null, get_string('nolessonattempts', 'lesson')); if ($PAGE->has_secondary_navigation()) { echo $reportactionarea; } if (!empty($currentgroup)) { $groupname = groups_get_group_name($currentgroup); echo $OUTPUT->notification(get_string('nolessonattemptsgroup', 'lesson', $groupname)); } else { echo $OUTPUT->notification(get_string('nolessonattempts', 'lesson')); } groups_print_activity_menu($cm, $url); echo $OUTPUT->footer(); exit(); } echo $lessonoutput->header($lesson, $cm, $action, false, null, get_string('overview', 'lesson')); if ($PAGE->has_secondary_navigation()) { echo $reportactionarea; } groups_print_activity_menu($cm, $url); $course_context = context_course::instance($course->id); if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) { $seeallgradeslink = new moodle_url('/grade/report/grader/index.php', array('id'=>$course->id)); $seeallgradeslink = html_writer::link($seeallgradeslink, get_string('seeallcoursegrades', 'grades')); echo $OUTPUT->box($seeallgradeslink, 'allcoursegrades'); } // The attempts table. $attemptstable = html_writer::table($table); // The HTML that we will be displaying which includes the attempts table and bulk actions menu, if necessary. $attemptshtml = $attemptstable; // Show bulk actions when user has capability to edit the lesson. if (has_capability('mod/lesson:edit', $context)) { $reporturl = new moodle_url('/mod/lesson/report.php'); $formid = 'mod-lesson-report-form'; // Sesskey hidden input. $formcontents = html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()]); // CMID hidden input. $formcontents .= html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'id', 'value' => $cm->id]); // Attempts table. $formcontents .= $attemptstable; // Bulk actions menu. $attemptsactions = [ 'delete' => get_string('deleteselected') ]; $bulkactions = new single_select($reporturl, 'action', $attemptsactions, '', ['' => 'choosedots'], $formid); $bulkactions->set_label(get_string('withselectedattempts', 'lesson')); $bulkactions->disabled = true; $bulkactions->attributes = [ 'data-action' => 'toggle', 'data-togglegroup' => 'lesson-attempts', 'data-toggle' => 'action', ]; $bulkactionshtml = $OUTPUT->render($bulkactions); $formcontents .= $OUTPUT->box($bulkactionshtml, 'center'); // Build the attempts form. $formattributes = [ 'id' => $formid, 'method' => 'post', ]; $attemptshtml = html_writer::tag('form', $formcontents, $formattributes); } // Show the attempts HTML. echo $attemptshtml; // Calculate the Statistics. if ($data->avetime == null) { $data->avetime = get_string("notcompleted", "lesson"); } else { $data->avetime = format_float($data->avetime / $data->numofattempts, 0); $data->avetime = format_time($data->avetime); } if ($data->hightime == null) { $data->hightime = get_string("notcompleted", "lesson"); } else { $data->hightime = format_time($data->hightime); } if ($data->lowtime == null) { $data->lowtime = get_string("notcompleted", "lesson"); } else { $data->lowtime = format_time($data->lowtime); } if ($data->lessonscored) { if ($data->numofattempts == 0) { $data->avescore = get_string("notcompleted", "lesson"); } else { $data->avescore = format_float($data->avescore, 2) . '%'; } if ($data->highscore === null) { $data->highscore = get_string("notcompleted", "lesson"); } else { $data->highscore .= '%'; } if ($data->lowscore === null) { $data->lowscore = get_string("notcompleted", "lesson"); } else { $data->lowscore .= '%'; } // Display the full stats for the lesson. echo $OUTPUT->heading(get_string('lessonstats', 'lesson'), 3); $stattable = new html_table(); $stattable->head = array(get_string('averagescore', 'lesson'), get_string('averagetime', 'lesson'), get_string('highscore', 'lesson'), get_string('lowscore', 'lesson'), get_string('hightime', 'lesson'), get_string('lowtime', 'lesson')); $stattable->align = array('center', 'center', 'center', 'center', 'center', 'center'); $stattable->attributes['class'] = 'standardtable generaltable'; $stattable->data[] = array($data->avescore, $data->avetime, $data->highscore, $data->lowscore, $data->hightime, $data->lowtime); } else { // Display simple stats for the lesson. echo $OUTPUT->heading(get_string('lessonstats', 'lesson'), 3); $stattable = new html_table(); $stattable->head = array(get_string('averagetime', 'lesson'), get_string('hightime', 'lesson'), get_string('lowtime', 'lesson')); $stattable->align = array('center', 'center', 'center'); $stattable->attributes['class'] = 'standardtable generaltable'; $stattable->data[] = array($data->avetime, $data->hightime, $data->lowtime); } echo html_writer::table($stattable); } else if ($action === 'reportdetail') { /************************************************************************** this action is for a student detailed view and for the general detailed view General flow of this section of the code 1. Generate a object which holds values for the statistics for each question/answer 2. Cycle through all the pages to create a object. Foreach page, see if the student actually answered the page. Then process the page appropriatly. Display all info about the question, Highlight correct answers, show how the user answered the question, and display statistics about each page 3. Print out info about the try (if needed) 4. Print out the object which contains all the try info **************************************************************************/ echo $lessonoutput->header($lesson, $cm, $action, false, null, get_string('detailedstats', 'lesson')); if ($PAGE->has_secondary_navigation()) { echo $reportactionarea; } groups_print_activity_menu($cm, $url); $course_context = context_course::instance($course->id); if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) { $seeallgradeslink = new moodle_url('/grade/report/grader/index.php', array('id'=>$course->id)); $seeallgradeslink = html_writer::link($seeallgradeslink, get_string('seeallcoursegrades', 'grades')); echo $OUTPUT->box($seeallgradeslink, 'allcoursegrades'); } $formattextdefoptions = new stdClass; $formattextdefoptions->para = false; //I'll use it widely in this page $formattextdefoptions->overflowdiv = true; $userid = optional_param('userid', null, PARAM_INT); // if empty, then will display the general detailed view $try = optional_param('try', null, PARAM_INT); list($answerpages, $userstats) = lesson_get_user_detailed_report_data($lesson, $userid, $try); /// actually start printing something $table = new html_table(); $table->wrap = array(); $table->width = "60%"; if (!empty($userid)) { // if looking at a students try, print out some basic stats at the top // print out users name //$headingobject->lastname = $students[$userid]->lastname; //$headingobject->firstname = $students[$userid]->firstname; //$headingobject->attempt = $try + 1; //print_heading(get_string("studentattemptlesson", "lesson", $headingobject)); echo $OUTPUT->heading(get_string('attempt', 'lesson', $try+1), 3); $table->head = array(); $table->align = array('right', 'left'); $table->attributes['class'] = 'table table-striped'; if (empty($userstats->gradeinfo)) { $table->align = array("center"); $table->data[] = array(get_string("notcompleted", "lesson")); } else { $user = $DB->get_record('user', array('id' => $userid)); $gradeinfo = lesson_grade($lesson, $try, $user->id); $table->data[] = array(get_string('name').':', $OUTPUT->user_picture($user, array('courseid'=>$course->id)).fullname($user, true)); $table->data[] = array(get_string("timetaken", "lesson").":", format_time($userstats->timetotake)); $table->data[] = array(get_string("completed", "lesson").":", userdate($userstats->completed)); $table->data[] = array(get_string('rawgrade', 'lesson').':', $userstats->gradeinfo->earned.'/'.$userstats->gradeinfo->total); $table->data[] = array(get_string("grade", "lesson").":", $userstats->grade."%"); } echo html_writer::table($table); // Don't want this class for later tables $table->attributes['class'] = ''; } foreach ($answerpages as $page) { $table->align = array('left', 'left'); $table->size = array('70%', null); $table->attributes['class'] = 'table table-striped'; unset($table->data); if ($page->grayout) { // set the color of text $fontstart = html_writer::start_tag('span', array('class' => 'dimmed_text')); $fontend = html_writer::end_tag('span'); $fontstart2 = $fontstart; $fontend2 = $fontend; } else { $fontstart = ''; $fontend = ''; $fontstart2 = ''; $fontend2 = ''; } $table->head = array($fontstart2.$page->qtype.": ".format_string($page->title).$fontend2, $fontstart2.get_string("classstats", "lesson").$fontend2); $table->data[] = array($fontstart.get_string("question", "lesson").": <br />".$fontend.$fontstart2.$page->contents.$fontend2, " "); $table->data[] = array($fontstart.get_string("answer", "lesson").":".$fontend, ' '); // apply the font to each answer if (!empty($page->answerdata) && !empty($page->answerdata->answers)) { foreach ($page->answerdata->answers as $answer){ $modified = array(); foreach ($answer as $single) { // need to apply a font to each one $modified[] = $fontstart2.$single.$fontend2; } $table->data[] = $modified; } if (isset($page->answerdata->response)) { $table->data[] = array($fontstart.get_string("response", "lesson").": <br />".$fontend .$fontstart2.$page->answerdata->response.$fontend2, " "); } $table->data[] = array($page->answerdata->score, " "); } else { $table->data[] = array(get_string('didnotanswerquestion', 'lesson'), " "); } echo html_writer::table($table); } } else { print_error('unknowaction'); } /// Finish the page echo $OUTPUT->footer();
gpl-3.0
hernad/easyrec
easyrec-utils/src/main/java/gnu/trove/procedure/TFloatProcedure.java
1608
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 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 General Public License for more details. // // You should have received a copy of the GNU Lesser 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. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures with one float parameter. */ public interface TFloatProcedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param value a value of type <code>float</code> * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( float value ); }
gpl-3.0
softwareanimal/TextSecure-WinterBreak2015
src/org/thoughtcrime/securesms/sms/OutgoingTextMessage.java
1851
package org.thoughtcrime.securesms.sms; import org.thoughtcrime.securesms.database.model.SmsMessageRecord; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.Recipients; public class OutgoingTextMessage { private final Recipients recipients; private final String message; public OutgoingTextMessage(Recipient recipient, String message) { this(new Recipients(recipient), message); } public OutgoingTextMessage(Recipients recipients, String message) { this.recipients = recipients; this.message = message; } protected OutgoingTextMessage(OutgoingTextMessage base, String body) { this.recipients = base.getRecipients(); this.message = body; } public String getMessageBody() { return message; } public Recipients getRecipients() { return recipients; } public boolean isKeyExchange() { return false; } public boolean isSecureMessage() { return false; } public boolean isEndSession() { return false; } public boolean isPreKeyBundle() { return false; } public static OutgoingTextMessage from(SmsMessageRecord record) { if (record.isSecure()) { return new OutgoingEncryptedMessage(record.getIndividualRecipient(), record.getBody().getBody()); } else if (record.isKeyExchange()) { return new OutgoingKeyExchangeMessage(record.getIndividualRecipient(), record.getBody().getBody()); } else if (record.isEndSession()) { return new OutgoingEndSessionMessage(new OutgoingTextMessage(record.getIndividualRecipient(), record.getBody().getBody())); } else { return new OutgoingTextMessage(record.getIndividualRecipient(), record.getBody().getBody()); } } public OutgoingTextMessage withBody(String body) { return new OutgoingTextMessage(this, body); } }
gpl-3.0
Scavenge/darkstar
scripts/zones/Rabao/npcs/Agado-Pugado.lua
5701
----------------------------------- -- Area: Rabao -- NPC: Agado-Pugado -- Starts and Finishes Quest: Trial by Wind -- @pos -17 7 -10 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialByWind = player:getQuestStatus(OUTLANDS,TRIAL_BY_WIND); local WhisperOfGales = player:hasKeyItem(323); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local CarbuncleDebacle = player:getQuestStatus(WINDURST,CARBUNCLE_DEBACLE); local CarbuncleDebacleProgress = player:getVar("CarbuncleDebacleProgress"); --------------------------------------------------------------------- -- Carbuncle Debacle if (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 5 and player:hasKeyItem(DAZEBREAKER_CHARM) == true) then player:startEvent(0x0056); -- get the wind pendulum, lets go to Cloister of Gales elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 6) then if (player:hasItem(1174) == false) then player:startEvent(0x0057,0,1174,0,0,0,0,0,0); -- "lost the pendulum?" This one too~??? else player:startEvent(0x0058); -- reminder to go to Cloister of Gales end; --------------------------------------------------------------------- -- Trial by Wind elseif ((TrialByWind == QUEST_AVAILABLE and player:getFameLevel(RABAO) >= 5) or (TrialByWind == QUEST_COMPLETED and realday ~= player:getVar("TrialByWind_date"))) then player:startEvent(0x0042,0,331); -- Start and restart quest "Trial by Wind" elseif (TrialByWind == QUEST_ACCEPTED and player:hasKeyItem(331) == false and WhisperOfGales == false) then player:startEvent(0x006b,0,331); -- Defeat against Avatar : Need new Fork elseif (TrialByWind == QUEST_ACCEPTED and WhisperOfGales == false) then player:startEvent(0x0043,0,331,3); elseif (TrialByWind == QUEST_ACCEPTED and WhisperOfGales) then numitem = 0; if (player:hasItem(17627)) then numitem = numitem + 1; end -- Garuda's Dagger if (player:hasItem(13243)) then numitem = numitem + 2; end -- Wind Belt if (player:hasItem(13562)) then numitem = numitem + 4; end -- Wind Ring if (player:hasItem(1202)) then numitem = numitem + 8; end -- Bubbly Water if (player:hasSpell(301)) then numitem = numitem + 32; end -- Ability to summon Garuda player:startEvent(0x0045,0,331,3,0,numitem); else player:startEvent(0x0046); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0042 and option == 1) then if (player:getQuestStatus(OUTLANDS,TRIAL_BY_WIND) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,TRIAL_BY_WIND); end player:addQuest(OUTLANDS,TRIAL_BY_WIND); player:setVar("TrialByWind_date", 0); player:addKeyItem(TUNING_FORK_OF_WIND); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WIND); elseif (csid == 0x006b) then player:addKeyItem(TUNING_FORK_OF_WIND); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WIND); elseif (csid == 0x0045) then item = 0; if (option == 1) then item = 17627; -- Garuda's Dagger elseif (option == 2) then item = 13243; -- Wind Belt elseif (option == 3) then item = 13562; -- Wind Ring elseif (option == 4) then item = 1202; -- Bubbly Water end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(301); -- Garuda Spell player:messageSpecial(GARUDA_UNLOCKED,0,0,3); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_WIND); player:delKeyItem(WHISPER_OF_GALES); --Whisper of Gales, as a trade for the above rewards player:setVar("TrialByWind_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(RABAO,30); player:completeQuest(OUTLANDS,TRIAL_BY_WIND); end elseif (csid == 0x0056 or csid == 0x0057) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(1174); player:messageSpecial(ITEM_OBTAINED,1174); player:setVar("CarbuncleDebacleProgress",6); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1174); end; end end;
gpl-3.0
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/testtools/matchers/_doctest.py
3867
# Copyright (c) 2009-2012 testtools developers. See LICENSE for details. __all__ = [ 'DocTestMatches', ] import doctest import re from ..compat import str_is_unicode from ._impl import Mismatch class _NonManglingOutputChecker(doctest.OutputChecker): """Doctest checker that works with unicode rather than mangling strings This is needed because current Python versions have tried to fix string encoding related problems, but regressed the default behaviour with unicode inputs in the process. In Python 2.6 and 2.7 ``OutputChecker.output_difference`` is was changed to return a bytestring encoded as per ``sys.stdout.encoding``, or utf-8 if that can't be determined. Worse, that encoding process happens in the innocent looking `_indent` global function. Because the `DocTestMismatch.describe` result may well not be destined for printing to stdout, this is no good for us. To get a unicode return as before, the method is monkey patched if ``doctest._encoding`` exists. Python 3 has a different problem. For some reason both inputs are encoded to ascii with 'backslashreplace', making an escaped string matches its unescaped form. Overriding the offending ``OutputChecker._toAscii`` method is sufficient to revert this. """ def _toAscii(self, s): """Return ``s`` unchanged rather than mangling it to ascii""" return s # Only do this overriding hackery if doctest has a broken _input function if getattr(doctest, "_encoding", None) is not None: from types import FunctionType as __F __f = doctest.OutputChecker.output_difference.im_func __g = dict(__f.func_globals) def _indent(s, indent=4, _pattern=re.compile("^(?!$)", re.MULTILINE)): """Prepend non-empty lines in ``s`` with ``indent`` number of spaces""" return _pattern.sub(indent*" ", s) __g["_indent"] = _indent output_difference = __F(__f.func_code, __g, "output_difference") del __F, __f, __g, _indent class DocTestMatches(object): """See if a string matches a doctest example.""" def __init__(self, example, flags=0): """Create a DocTestMatches to match example. :param example: The example to match e.g. 'foo bar baz' :param flags: doctest comparison flags to match on. e.g. doctest.ELLIPSIS. """ if not example.endswith('\n'): example += '\n' self.want = example # required variable name by doctest. self.flags = flags self._checker = _NonManglingOutputChecker() def __str__(self): if self.flags: flagstr = ", flags=%d" % self.flags else: flagstr = "" return 'DocTestMatches(%r%s)' % (self.want, flagstr) def _with_nl(self, actual): result = self.want.__class__(actual) if not result.endswith('\n'): result += '\n' return result def match(self, actual): with_nl = self._with_nl(actual) if self._checker.check_output(self.want, with_nl, self.flags): return None return DocTestMismatch(self, with_nl) def _describe_difference(self, with_nl): return self._checker.output_difference(self, with_nl, self.flags) class DocTestMismatch(Mismatch): """Mismatch object for DocTestMatches.""" def __init__(self, matcher, with_nl): self.matcher = matcher self.with_nl = with_nl def describe(self): s = self.matcher._describe_difference(self.with_nl) if str_is_unicode or isinstance(s, unicode): return s # GZ 2011-08-24: This is actually pretty bogus, most C0 codes should # be escaped, in addition to non-ascii bytes. return s.decode("latin1").encode("ascii", "backslashreplace")
agpl-3.0
harterj/moose
modules/tensor_mechanics/src/materials/ComputeDilatationThermalExpansionFunctionEigenstrain.C
1685
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ComputeDilatationThermalExpansionFunctionEigenstrain.h" #include "Function.h" registerMooseObject("TensorMechanicsApp", ComputeDilatationThermalExpansionFunctionEigenstrain); InputParameters ComputeDilatationThermalExpansionFunctionEigenstrain::validParams() { InputParameters params = ComputeDilatationThermalExpansionEigenstrainBase::validParams(); params.addClassDescription("Computes eigenstrain due to thermal expansion using a function that " "describes the total dilatation as a function of temperature"); params.addRequiredParam<FunctionName>( "dilatation_function", "Function describing the thermal dilatation as a function of temperature"); return params; } ComputeDilatationThermalExpansionFunctionEigenstrain:: ComputeDilatationThermalExpansionFunctionEigenstrain(const InputParameters & parameters) : ComputeDilatationThermalExpansionEigenstrainBase(parameters), _dilatation_function(getFunction("dilatation_function")) { } Real ComputeDilatationThermalExpansionFunctionEigenstrain::computeDilatation(const Real & temperature) { return _dilatation_function.value(temperature, Point()); } Real ComputeDilatationThermalExpansionFunctionEigenstrain::computeDilatationDerivative( const Real & temperature) { return _dilatation_function.timeDerivative(temperature, Point()); }
lgpl-2.1
TheProjecter/project-qtcreator
src/libs/3rdparty/botan/src/rng/x931_rng/x931_rng.cpp
2744
/* * ANSI X9.31 RNG * (C) 1999-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/x931_rng.h> #include <botan/xor_buf.h> #include <algorithm> namespace Botan { /** * Generate a buffer of random bytes */ void ANSI_X931_RNG::randomize(byte out[], u32bit length) { if(!is_seeded()) throw PRNG_Unseeded(name()); while(length) { if(position == R.size()) update_buffer(); const u32bit copied = std::min(length, R.size() - position); copy_mem(out, R + position, copied); out += copied; length -= copied; position += copied; } } /** * Refill the internal state */ void ANSI_X931_RNG::update_buffer() { SecureVector<byte> DT(cipher->BLOCK_SIZE); prng->randomize(DT, DT.size()); cipher->encrypt(DT); xor_buf(R, V, DT, cipher->BLOCK_SIZE); cipher->encrypt(R); xor_buf(V, R, DT, cipher->BLOCK_SIZE); cipher->encrypt(V); position = 0; } /** * Reset V and the cipher key with new values */ void ANSI_X931_RNG::rekey() { if(prng->is_seeded()) { SecureVector<byte> key(cipher->MAXIMUM_KEYLENGTH); prng->randomize(key, key.size()); cipher->set_key(key, key.size()); if(V.size() != cipher->BLOCK_SIZE) V.create(cipher->BLOCK_SIZE); prng->randomize(V, V.size()); update_buffer(); } } /** * Reseed the internal state */ void ANSI_X931_RNG::reseed(u32bit poll_bits) { prng->reseed(poll_bits); rekey(); } /** * Add a entropy source to the underlying PRNG */ void ANSI_X931_RNG::add_entropy_source(EntropySource* src) { prng->add_entropy_source(src); } /** * Add some entropy to the underlying PRNG */ void ANSI_X931_RNG::add_entropy(const byte input[], u32bit length) { prng->add_entropy(input, length); rekey(); } /** * Check if the the PRNG is seeded */ bool ANSI_X931_RNG::is_seeded() const { return V.has_items(); } /** * Clear memory of sensitive data */ void ANSI_X931_RNG::clear() throw() { cipher->clear(); prng->clear(); R.clear(); V.destroy(); position = 0; } /** * Return the name of this type */ std::string ANSI_X931_RNG::name() const { return "X9.31(" + cipher->name() + ")"; } /** * ANSI X931 RNG Constructor */ ANSI_X931_RNG::ANSI_X931_RNG(BlockCipher* cipher_in, RandomNumberGenerator* prng_in) { if(!prng_in || !cipher_in) throw Invalid_Argument("ANSI_X931_RNG constructor: NULL arguments"); cipher = cipher_in; prng = prng_in; R.create(cipher->BLOCK_SIZE); position = 0; } /** * ANSI X931 RNG Destructor */ ANSI_X931_RNG::~ANSI_X931_RNG() { delete cipher; delete prng; } }
lgpl-2.1
RomSunZ/StockSharp
Connectors/InteractiveBrokers/Java/Client/IApiEnum.java
289
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package com.ib.client; public interface IApiEnum { String getApiString(); }
lgpl-3.0
TonyChai24/test
gerrit-server/src/main/java/com/google/gerrit/server/git/GarbageCollectionLogFile.java
1698
// 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. package com.google.gerrit.server.git; import com.google.gerrit.extensions.events.LifecycleListener; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.util.SystemLog; import com.google.inject.Inject; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import java.nio.file.Path; public class GarbageCollectionLogFile implements LifecycleListener { @Inject public GarbageCollectionLogFile(SitePaths sitePaths) { if (SystemLog.shouldConfigure()) { initLogSystem(sitePaths.logs_dir); } } @Override public void start() { } @Override public void stop() { LogManager.getLogger(GarbageCollection.LOG_NAME).removeAllAppenders(); } private static void initLogSystem(Path logdir) { Logger gcLogger = LogManager.getLogger(GarbageCollection.LOG_NAME); gcLogger.removeAllAppenders(); gcLogger.addAppender(SystemLog.createAppender(logdir, GarbageCollection.LOG_NAME, new PatternLayout("[%d] %-5p %x: %m%n"))); gcLogger.setAdditivity(false); } }
apache-2.0
gastaldi/wildfly-swarm
testsuite/testsuite-maven-plugin/src/test/resources/testing-project/src/main/java/org/wildfly/swarm/test/HelloServlet.java
1164
/** * Copyright 2016 Red Hat, Inc, and individual contributors. * * 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.wildfly.swarm.test; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/servlet") public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("Hello from servlet"); } }
apache-2.0
leafclick/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/convertToSingleReturn/beforeSynchronized.java
244
// "Transform body to single exit-point form" "true" class Test { String <caret>test(int x) { synchronized(this) { if(x == 0) return "foo"; if(x == 1) return "bar"; return "baz"; } } }
apache-2.0
tiblu/etherpad-lite
src/node/utils/ExportTxt.js
7749
/** * TXT export */ /* * 2013 John McLear * * 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 async = require("async"); var Changeset = require("ep_etherpad-lite/static/js/Changeset"); var padManager = require("../db/PadManager"); var ERR = require("async-stacktrace"); var _analyzeLine = require('./ExportHelper')._analyzeLine; // This is slightly different than the HTML method as it passes the output to getTXTFromAText function getPadTXT(pad, revNum, callback) { var atext = pad.atext; var html; async.waterfall([ // fetch revision atext function (callback) { if (revNum != undefined) { pad.getInternalRevisionAText(revNum, function (err, revisionAtext) { if(ERR(err, callback)) return; atext = revisionAtext; callback(); }); } else { callback(null); } }, // convert atext to html function (callback) { html = getTXTFromAtext(pad, atext); // only this line is different to the HTML function callback(null); }], // run final callback function (err) { if(ERR(err, callback)) return; callback(null, html); }); } exports.getPadTXT = getPadTXT; // This is different than the functionality provided in ExportHtml as it provides formatting // functionality that is designed specifically for TXT exports function getTXTFromAtext(pad, atext, authorColors) { var apool = pad.apool(); var textLines = atext.text.slice(0, -1).split('\n'); var attribLines = Changeset.splitAttributionLines(atext.attribs, atext.text); var props = ['heading1', 'heading2', 'bold', 'italic', 'underline', 'strikethrough']; var anumMap = {}; var css = ""; props.forEach(function (propName, i) { var propTrueNum = apool.putAttrib([propName, true], true); if (propTrueNum >= 0) { anumMap[propTrueNum] = i; } }); function getLineTXT(text, attribs) { var propVals = [false, false, false]; var ENTER = 1; var STAY = 2; var LEAVE = 0; // Use order of tags (b/i/u) as order of nesting, for simplicity // and decent nesting. For example, // <b>Just bold<b> <b><i>Bold and italics</i></b> <i>Just italics</i> // becomes // <b>Just bold <i>Bold and italics</i></b> <i>Just italics</i> var taker = Changeset.stringIterator(text); var assem = Changeset.stringAssembler(); var idx = 0; function processNextChars(numChars) { if (numChars <= 0) { return; } var iter = Changeset.opIterator(Changeset.subattribution(attribs, idx, idx + numChars)); idx += numChars; while (iter.hasNext()) { var o = iter.next(); var propChanged = false; Changeset.eachAttribNumber(o.attribs, function (a) { if (a in anumMap) { var i = anumMap[a]; // i = 0 => bold, etc. if (!propVals[i]) { propVals[i] = ENTER; propChanged = true; } else { propVals[i] = STAY; } } }); for (var i = 0; i < propVals.length; i++) { if (propVals[i] === true) { propVals[i] = LEAVE; propChanged = true; } else if (propVals[i] === STAY) { propVals[i] = true; // set it back } } // now each member of propVal is in {false,LEAVE,ENTER,true} // according to what happens at start of span if (propChanged) { // leaving bold (e.g.) also leaves italics, etc. var left = false; for (var i = 0; i < propVals.length; i++) { var v = propVals[i]; if (!left) { if (v === LEAVE) { left = true; } } else { if (v === true) { propVals[i] = STAY; // tag will be closed and re-opened } } } var tags2close = []; for (var i = propVals.length - 1; i >= 0; i--) { if (propVals[i] === LEAVE) { //emitCloseTag(i); tags2close.push(i); propVals[i] = false; } else if (propVals[i] === STAY) { //emitCloseTag(i); tags2close.push(i); } } for (var i = 0; i < propVals.length; i++) { if (propVals[i] === ENTER || propVals[i] === STAY) { propVals[i] = true; } } // propVals is now all {true,false} again } // end if (propChanged) var chars = o.chars; if (o.lines) { chars--; // exclude newline at end of line, if present } var s = taker.take(chars); // removes the characters with the code 12. Don't know where they come // from but they break the abiword parser and are completly useless // s = s.replace(String.fromCharCode(12), ""); // remove * from s, it's just not needed on a blank line.. This stops // plugins from being able to display * at the beginning of a line // s = s.replace("*", ""); // Then remove it assem.append(s); } // end iteration over spans in line var tags2close = []; for (var i = propVals.length - 1; i >= 0; i--) { if (propVals[i]) { tags2close.push(i); propVals[i] = false; } } } // end processNextChars processNextChars(text.length - idx); return(assem.toString()); } // end getLineHTML var pieces = [css]; // Need to deal with constraints imposed on HTML lists; can // only gain one level of nesting at once, can't change type // mid-list, etc. // People might use weird indenting, e.g. skip a level, // so we want to do something reasonable there. We also // want to deal gracefully with blank lines. // => keeps track of the parents level of indentation for (var i = 0; i < textLines.length; i++) { var line = _analyzeLine(textLines[i], attribLines[i], apool); var lineContent = getLineTXT(line.text, line.aline); if(line.listTypeName == "bullet"){ lineContent = "* " + lineContent; // add a bullet } if(line.listLevel > 0){ for (var j = line.listLevel - 1; j >= 0; j--){ pieces.push('\t'); } if(line.listTypeName == "number"){ pieces.push(line.listLevel + ". "); // This is bad because it doesn't truly reflect what the user // sees because browsers do magic on nested <ol><li>s } pieces.push(lineContent, '\n'); }else{ pieces.push(lineContent, '\n'); } } return pieces.join(''); } exports.getTXTFromAtext = getTXTFromAtext; exports.getPadTXTDocument = function (padId, revNum, callback) { padManager.getPad(padId, function (err, pad) { if(ERR(err, callback)) return; getPadTXT(pad, revNum, function (err, html) { if(ERR(err, callback)) return; callback(null, html); }); }); };
apache-2.0
takeshineshiro/keystone
keystone/common/sql/migrate_repo/versions/062_drop_assignment_role_fk.py
1283
# 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. import sqlalchemy from keystone.common.sql import migration_helpers def list_constraints(migrate_engine): meta = sqlalchemy.MetaData() meta.bind = migrate_engine assignment_table = sqlalchemy.Table('assignment', meta, autoload=True) role_table = sqlalchemy.Table('role', meta, autoload=True) constraints = [{'table': assignment_table, 'fk_column': 'role_id', 'ref_column': role_table.c.id}] return constraints def upgrade(migrate_engine): # SQLite does not support constraints, and querying the constraints # raises an exception if migrate_engine.name == 'sqlite': return migration_helpers.remove_constraints(list_constraints(migrate_engine))
apache-2.0
pragnagopa/azure-mobile-services-test
sdk/managed/test/Microsoft.WindowsAzure.MobileServices.iOS.Test/TestPlatform/PushTestUtility.cs
4640
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using Microsoft.WindowsAzure.MobileServices.TestFramework; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.MobileServices.Test { class PushTestUtility : IPushTestUtility { private const string DefaultDeviceToken = "<f6e7cd2 80fc5b5 d488f8394baf216506bc1bba 864d5b483d>"; const string BodyTemplate = "{\"aps\": {\"alert\":\"boo!\"}, \"extraprop\":\"($message)\"}"; const string DefaultToastTemplateName = "templateForToastApns"; readonly string[] DefaultTags = { "fooApns", "barApns" }; public string GetPushHandle() { return DefaultDeviceToken; } public string GetUpdatedPushHandle() { return DefaultDeviceToken.Replace('b', 'a').Replace('B', 'a'); } public Registration GetTemplateRegistrationForToast() { var deviceToken = GetPushHandle(); return new ApnsTemplateRegistration(deviceToken, BodyTemplate, null, DefaultToastTemplateName, DefaultTags); } public Registration GetUpdatedTemplateRegistrationForToast() { var deviceToken = GetUpdatedPushHandle(); return new ApnsTemplateRegistration(deviceToken, BodyTemplate, null, DefaultToastTemplateName, DefaultTags); } public void ValidateTemplateRegistration(Registration registration) { var apnsTemplateRegistration = (ApnsTemplateRegistration)registration; Assert.AreEqual(apnsTemplateRegistration.BodyTemplate, BodyTemplate); foreach (string tag in DefaultTags) { Assert.IsTrue(registration.Tags.Contains(tag)); } Assert.AreEqual(apnsTemplateRegistration.Name, DefaultToastTemplateName); Assert.AreEqual(apnsTemplateRegistration.TemplateName, DefaultToastTemplateName); } public void ValidateTemplateRegistrationBeforeRegister(Registration registration) { ValidateTemplateRegistration(registration); Assert.AreEqual(registration.Tags.Count(), DefaultTags.Length); Assert.IsNull(registration.RegistrationId); } public void ValidateTemplateRegistrationAfterRegister(Registration registration) { ValidateTemplateRegistration(registration); Assert.IsNotNull(registration.RegistrationId); // TODO: Uncomment when .Net Runtime implements installationID //Assert.IsTrue(registration.Tags.Contains(zumoInstallationId)); //Assert.AreEqual(registration.Tags.Count(), DefaultTags.Length + 1); } public Registration GetNewNativeRegistration(string deviceId, IEnumerable<string> tags) { return new ApnsRegistration(deviceId, tags); } public Registration GetNewTemplateRegistration(string deviceId, string bodyTemplate, string templateName) { return new ApnsTemplateRegistration(deviceId, bodyTemplate, templateName, null); } public string GetListNativeRegistrationResponse() { return "[{\"registrationId\":\"7313155627197174428-6522078074300559092-1\",\"tags\":[\"fooWns\",\"barWns\",\"4de2605e-fd09-4875-a897-c8c4c0a51682\"],\"deviceId\":\"http://channelUri.com/a b\"}]"; } public string GetListTemplateRegistrationResponse() { return "[{\"registrationId\":\"7313155627197174428-6522078074300559092-1\",\"tags\":[\"fooWns\",\"barWns\",\"4de2605e-fd09-4875-a897-c8c4c0a51682\"],\"deviceId\":\"http://channelUri.com/a b\",\"templateBody\":\"cool template body\",\"templateName\":\"cool name\"}]"; } public string GetListMixedRegistrationResponse() { return "[{\"registrationId\":\"7313155627197174428-6522078074300559092-1\",\"tags\":[\"fooWns\",\"barWns\",\"4de2605e-fd09-4875-a897-c8c4c0a51682\"],\"deviceId\":\"http://channelUri.com/a b\"}, " + "{\"registrationId\":\"7313155627197174428-6522078074300559092-1\",\"tags\":[\"fooWns\",\"barWns\",\"4de2605e-fd09-4875-a897-c8c4c0a51682\"],\"deviceId\":\"http://channelUri.com/a b\",\"templateBody\":\"cool template body\",\"templateName\":\"cool name\"}]"; } } }
apache-2.0
mbebenita/shumway.ts
tests/Fidelity/test262/suite/ch07/7.8/7.8.3/S7.8.3_A3.4_T4.js
991
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * DecimalLiteral :: DecimalIntegerLiteral. DecimalDigigts ExponentPart * * @path ch07/7.8/7.8.3/S7.8.3_A3.4_T4.js * @description ExponentPart :: E -DecimalDigits */ //CHECK#0 if (0.0E-1 !== 0) { $ERROR('#0: 0.0E-1 === 0'); } //CHECK#1 if (1.1E-1 !== 0.11) { $ERROR('#1: 1.1E-1 === 0.11'); } //CHECK#2 if (2.2E-1 !== 0.22) { $ERROR('#2: 2.2E-1 === 0.22'); } //CHECK#3 if (3.3E-1 !== 0.33) { $ERROR('#3: 3.3E-1 === 0.33'); } //CHECK#4 if (4.4E-1 !== 0.44) { $ERROR('#4: 4.4E-1 === 0.44'); } //CHECK#5 if (5.5E-1 !== 0.55) { $ERROR('#5: 5.5E-1 === 0.55'); } //CHECK#6 if (6.6E-1 !== 0.66) { $ERROR('#6: 6.E-1 === 0.66'); } //CHECK#7 if (7.7E-1 !== 0.77) { $ERROR('#7: 7.7E-1 === 0.77'); } //CHECK#8 if (8.8E-1 !== 0.88) { $ERROR('#8: 8.8E-1 === 0.88'); } //CHECK#9 if (9.9E-1 !== 0.99) { $ERROR('#9: 9.9E-1 === 0.99'); }
apache-2.0
kyvinh/home-assistant
tests/components/sensor/test_wunderground.py
6144
"""The tests for the WUnderground platform.""" import unittest from homeassistant.components.sensor import wunderground from homeassistant.const import TEMP_CELSIUS from tests.common import get_test_home_assistant VALID_CONFIG_PWS = { 'platform': 'wunderground', 'api_key': 'foo', 'pws_id': 'bar', 'monitored_conditions': [ 'weather', 'feelslike_c', 'alerts', 'elevation', 'location' ] } VALID_CONFIG = { 'platform': 'wunderground', 'api_key': 'foo', 'monitored_conditions': [ 'weather', 'feelslike_c', 'alerts', 'elevation', 'location' ] } INVALID_CONFIG = { 'platform': 'wunderground', 'api_key': 'BOB', 'pws_id': 'bar', 'lang': 'foo', 'monitored_conditions': [ 'weather', 'feelslike_c', 'alerts' ] } FEELS_LIKE = '40' WEATHER = 'Clear' HTTPS_ICON_URL = 'https://icons.wxug.com/i/c/k/clear.gif' ALERT_MESSAGE = 'This is a test alert message' def mocked_requests_get(*args, **kwargs): """Mock requests.get invocations.""" class MockResponse: """Class to represent a mocked response.""" def __init__(self, json_data, status_code): """Initialize the mock response class.""" self.json_data = json_data self.status_code = status_code def json(self): """Return the json of the response.""" return self.json_data if str(args[0]).startswith('http://api.wunderground.com/api/foo/'): return MockResponse({ "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 } }, "current_observation": { "image": { "url": 'http://icons.wxug.com/graphics/wu2/logo_130x80.png', "title": "Weather Underground", "link": "http://www.wunderground.com" }, "feelslike_c": FEELS_LIKE, "weather": WEATHER, "icon_url": 'http://icons.wxug.com/i/c/k/clear.gif', "display_location": { "city": "Holly Springs", "country": "US", "full": "Holly Springs, NC" }, "observation_location": { "elevation": "413 ft", "full": "Twin Lake, Holly Springs, North Carolina" }, }, "alerts": [ { "type": 'FLO', "description": "Areal Flood Warning", "date": "9:36 PM CDT on September 22, 2016", "expires": "10:00 AM CDT on September 23, 2016", "message": ALERT_MESSAGE, }, ], }, 200) else: return MockResponse({ "response": { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": {}, "error": { "type": "keynotfound", "description": "this key does not exist" } } }, 200) class TestWundergroundSetup(unittest.TestCase): """Test the WUnderground platform.""" # pylint: disable=invalid-name DEVICES = [] def add_devices(self, devices): """Mock add devices.""" for device in devices: self.DEVICES.append(device) def setUp(self): """Initialize values for this testcase class.""" self.DEVICES = [] self.hass = get_test_home_assistant() self.key = 'foo' self.config = VALID_CONFIG_PWS self.lat = 37.8267 self.lon = -122.423 self.hass.config.latitude = self.lat self.hass.config.longitude = self.lon def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_setup(self, req_mock): """Test that the component is loaded if passed in PWS Id.""" self.assertTrue( wunderground.setup_platform(self.hass, VALID_CONFIG_PWS, self.add_devices, None)) self.assertTrue( wunderground.setup_platform(self.hass, VALID_CONFIG, self.add_devices, None)) self.assertTrue( wunderground.setup_platform(self.hass, INVALID_CONFIG, self.add_devices, None)) @unittest.mock.patch('requests.get', side_effect=mocked_requests_get) def test_sensor(self, req_mock): """Test the WUnderground sensor class and methods.""" wunderground.setup_platform(self.hass, VALID_CONFIG, self.add_devices, None) for device in self.DEVICES: device.update() self.assertTrue(str(device.name).startswith('PWS_')) if device.name == 'PWS_weather': self.assertEqual(HTTPS_ICON_URL, device.entity_picture) self.assertEqual(WEATHER, device.state) self.assertIsNone(device.unit_of_measurement) elif device.name == 'PWS_alerts': self.assertEqual(1, device.state) self.assertEqual(ALERT_MESSAGE, device.device_state_attributes['Message']) self.assertIsNone(device.entity_picture) elif device.name == 'PWS_location': self.assertEqual('Holly Springs, NC', device.state) elif device.name == 'PWS_elevation': self.assertEqual('413', device.state) else: self.assertIsNone(device.entity_picture) self.assertEqual(FEELS_LIKE, device.state) self.assertEqual(TEMP_CELSIUS, device.unit_of_measurement)
apache-2.0
westerhofffl/appengine-mapreduce
java/src/test/java/com/google/appengine/tools/mapreduce/impl/sort/SortTest.java
13881
package com.google.appengine.tools.mapreduce.impl.sort; import static java.nio.charset.StandardCharsets.US_ASCII; import com.google.appengine.tools.mapreduce.KeyValue; import com.google.appengine.tools.mapreduce.OutputWriter; import com.google.appengine.tools.mapreduce.impl.IncrementalTaskContext; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import junit.framework.TestCase; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.UUID; /** * Tests for {@link SortWorker} */ public class SortTest extends TestCase { private static class StringStringGenerator implements Iterator<KeyValue<ByteBuffer, ByteBuffer>> { private static final int KEY_SIZE = 36; private static final int VALUE_SIZE = 100; private static final byte[] MAX_VALUE = new byte[KEY_SIZE]; private static final byte[] MIN_VALUE = new byte[KEY_SIZE]; static { Arrays.fill(MAX_VALUE, (byte) 0xFF); Arrays.fill(MIN_VALUE, (byte) 0x00); } private int remaining; private final Random sequence = new Random(0); StringStringGenerator(int num) { this.remaining = num; } @Override public boolean hasNext() { return remaining != 0; } @Override public KeyValue<ByteBuffer, ByteBuffer> next() { if (remaining <= 0) { throw new NoSuchElementException(); } String string = new UUID(sequence.nextLong(), sequence.nextLong()).toString(); ByteBuffer key = ByteBuffer.allocate(KEY_SIZE).put(string.getBytes(US_ASCII)); key.limit(key.position()); key.rewind(); ByteBuffer value = ByteBuffer.allocate(VALUE_SIZE); remaining--; return new KeyValue<>(key, value); } @Override public void remove() { throw new UnsupportedOperationException(); } } private static final class MapSortContext extends SortContext { @SuppressWarnings("serial") public MapSortContext() { super(new IncrementalTaskContext("TestJob", 1, 1, "calls", "time"), new OutputWriter<KeyValue<ByteBuffer, List<ByteBuffer>>>() { @Override public void write(KeyValue<ByteBuffer, List<ByteBuffer>> value) { throw new UnsupportedOperationException(); } @Override public void endShard() { throw new UnsupportedOperationException(); } }); } LinkedHashMap<ByteBuffer, List<ByteBuffer>> map = new LinkedHashMap<>(); int sameKeyCount = 0; @Override public void emit(KeyValue<ByteBuffer, List<ByteBuffer>> keyValue) { ByteBuffer key = keyValue.getKey(); List<ByteBuffer> list = map.get(key); if (list == null) { map.put(key, Lists.newArrayList(keyValue.getValue())); } else { list.addAll(keyValue.getValue()); sameKeyCount++; } } } public void testDoesNotRunOutOfMemory() { SortWorker s = new SortWorker(null, Integer.MAX_VALUE); s.prepare(); Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(Integer.MAX_VALUE), null); assertTrue("Map size was: " + map.size(), map.size() > 50000); // Works down to 32mb vm. } public void testThrowsOnOverfill() { final int numberToWrite = 4; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. try { sortUntilFull(s, new StringStringGenerator(numberToWrite), new KeyValue<>(ByteBuffer.allocate(1), ByteBuffer.allocate(1))); fail(); } catch (IllegalArgumentException e) { // expected } } public void testCorrectOrder() { final int numberToWrite = 100000; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(numberToWrite), null); assertTrue(s.isFull()); // Confirms the bufferCapacity setting above. assertEquals(numberToWrite, map.size()); String last = "\0"; for (ByteBuffer key : map.keySet()) { String current = US_ASCII.decode(key).toString(); assertTrue("Last: " + last + " vs " + current, last.compareTo(current) < 0); last = current; } } public void testZeroByteKey() { final int numberToWrite = 40; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(numberToWrite - 1), new KeyValue<>( ByteBuffer.allocate(0), ByteBuffer.allocate(StringStringGenerator.VALUE_SIZE))); assertEquals(numberToWrite, map.size()); String last = null; for (ByteBuffer key : map.keySet()) { String string = US_ASCII.decode(key).toString(); if (last != null) { assertTrue("Last: " + last + " vs " + string, last.compareTo(string) < 0); } last = string; } } public void testLeftOverFirst() { final int numberToWrite = 4000; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(numberToWrite - 1), new KeyValue<>( ByteBuffer.wrap(StringStringGenerator.MIN_VALUE), ByteBuffer.allocate(StringStringGenerator.VALUE_SIZE))); assertTrue(s.isFull()); // Confirms the bufferCapacity setting above. assertEquals(numberToWrite, map.size()); String last = "\0"; for (ByteBuffer key : map.keySet()) { String string = US_ASCII.decode(key).toString(); assertTrue("Last: " + last + " vs " + string, last.compareTo(string) < 0); last = string; } } public void testLeftOverLast() { final int numberToWrite = 4000; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(numberToWrite - 1), new KeyValue<>( ByteBuffer.wrap(StringStringGenerator.MAX_VALUE), ByteBuffer.allocate(StringStringGenerator.VALUE_SIZE))); assertTrue(s.isFull()); // Confirms the bufferCapacity setting above. assertEquals(numberToWrite, map.size()); String last = "\0"; for (ByteBuffer key : map.keySet()) { String string = US_ASCII.decode(key).toString(); assertTrue("Last: " + last + " vs " + string, last.compareTo(string) < 0); last = string; } } public void testLeftOverEqualToMax() { final int numberToWrite = 4000; SortWorker s = createWorker(numberToWrite); // Assumes no collisions. LinkedHashMap<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, new StringStringGenerator(numberToWrite - 1), null); s = createWorker(numberToWrite); ByteBuffer last = map.keySet().toArray(new ByteBuffer[] {})[numberToWrite - 2]; map = sortUntilFull(s, new StringStringGenerator(numberToWrite - 1), new KeyValue<>(last.slice(), ByteBuffer.allocate(StringStringGenerator.VALUE_SIZE))); assertTrue(s.isFull()); // Confirms the bufferCapacity setting above. assertEquals(numberToWrite - 1, map.size()); String previous = "\0"; for (ByteBuffer key : map.keySet()) { String string = US_ASCII.decode(key).toString(); assertTrue("Last: " + previous + " vs " + string, previous.compareTo(string) <= 0); previous = string; } } private SortWorker createWorker(final int numberToWrite) { SortWorker worker = new SortWorker((long) (numberToWrite * ( StringStringGenerator.KEY_SIZE + StringStringGenerator.VALUE_SIZE + SortWorker.POINTER_SIZE_BYTES) - 1), // Set to force the last item to be leftover Integer.MAX_VALUE); worker.prepare(); return worker; } public void testValuesSegmentation() { int uniqueItems = 10; int batchSize = 1000; List<Iterator<KeyValue<ByteBuffer, ByteBuffer>>> iters = new ArrayList<>(); int numDups = 2 * (batchSize / StringStringGenerator.VALUE_SIZE) + 1; for (int i = 0; i < numDups; i++) { iters.add(new StringStringGenerator(uniqueItems)); } Iterator<KeyValue<ByteBuffer, ByteBuffer>> datax = Iterators.concat(iters.iterator()); SortWorker sorter = new SortWorker(64 * 1024 * 1024L, batchSize); sorter.prepare(); sorter.beginSlice(); while (!sorter.isFull() && datax.hasNext()) { KeyValue<ByteBuffer, ByteBuffer> next = datax.next(); sorter.addValue(next.getKey(), next.getValue()); } MapSortContext context = new MapSortContext(); sorter.setContext(context); sorter.endSlice(); assertEquals(2 * uniqueItems, context.sameKeyCount); assertEquals(uniqueItems, context.map.size()); for (List<ByteBuffer> values : context.map.values()) { assertEquals(numDups, values.size()); ByteBuffer previous = null; for (ByteBuffer value : values) { if (previous != null) { assertEquals(previous, value); } previous = value; } } } public void testMultipleValues() { Iterator<KeyValue<ByteBuffer, ByteBuffer>> datax4 = Iterators.concat( new StringStringGenerator(1000), new StringStringGenerator(1000), new StringStringGenerator(1000), new StringStringGenerator(1000)); SortWorker s = new SortWorker(1024 * 1024L, 4 * 136); s.prepare(); Map<ByteBuffer, List<ByteBuffer>> map = sortUntilFull(s, datax4, null); assertEquals(1000, map.size()); for (List<ByteBuffer> values : map.values()) { assertEquals(4, values.size()); ByteBuffer previous = null; for (ByteBuffer value : values) { if (previous != null) { assertEquals(previous, value); } previous = value; } } } public void testPointersFormat() { SortWorker worker = createWorker(1000); worker.addPointer(1, 10, 11, 100); worker.addPointer(111, 10, 121, 200); ByteBuffer pointer = worker.readPointer(0); assertEquals(1, pointer.getInt(0)); assertEquals(11, pointer.getInt(4)); assertEquals(100, pointer.getInt(8)); pointer = worker.readPointer(1); assertEquals(111, pointer.getInt(0)); assertEquals(121, pointer.getInt(4)); assertEquals(200, pointer.getInt(8)); } public void testKeyValuesRoundTrip() { SortWorker worker = createWorker(1000); ByteBuffer key = ByteBuffer.wrap(new byte[] {1, 2, 3, 4, 5, 6, 7}); ByteBuffer value = ByteBuffer.wrap(new byte[] {0, 9, 7, 5, 2, 4}); worker.addValue(key, value); KeyValue<ByteBuffer, ByteBuffer> keyValue = worker.getKeyValueFromPointer(0); assertEquals(key, keyValue.getKey()); assertEquals(value, keyValue.getValue()); ByteBuffer buffer = worker.getKeyFromPointer(0); assertEquals(key, buffer); } public void testSwap() { SortWorker worker = createWorker(1000); ByteBuffer key1 = ByteBuffer.wrap(new byte[] {1, 2, 3}); ByteBuffer value1 = ByteBuffer.wrap(new byte[] {4, 5, 6, 7}); worker.addValue(key1, value1); ByteBuffer key2 = ByteBuffer.wrap(new byte[] {8, 9}); ByteBuffer value2 = ByteBuffer.wrap(new byte[] {10, 11, 12, 13, 14}); worker.addValue(key2, value2); worker.swapPointers(0, 1); KeyValue<ByteBuffer, ByteBuffer> keyValue = worker.getKeyValueFromPointer(0); assertEquals(key2, keyValue.getKey()); assertEquals(value2, keyValue.getValue()); assertEquals(key2, worker.getKeyFromPointer(0)); keyValue = worker.getKeyValueFromPointer(1); assertEquals(key1, keyValue.getKey()); assertEquals(value1, keyValue.getValue()); assertEquals(key1, worker.getKeyFromPointer(1)); } public void testStoredData() { int size = 1000; SortWorker worker = new SortWorker(256 * 1024L, 0); worker.prepare(); worker.beginSlice(); StringStringGenerator gen = new StringStringGenerator(size); List<KeyValue<ByteBuffer, ByteBuffer>> input = new ArrayList<>(size); for (int i = 0; i < 1000; i++) { KeyValue<ByteBuffer, ByteBuffer> next = gen.next(); worker.addValue(next.getKey(), next.getValue()); input.add(next); } assertEquals(size, worker.getValuesHeld()); for (int i = 0; i < size; i++) { assertEquals(input.get(i), worker.getKeyValueFromPointer(i)); } } public void testDetectsFull() { SortWorker worker = new SortWorker(1000L, Integer.MAX_VALUE); worker.prepare(); worker.beginSlice(); ByteBuffer key = ByteBuffer.allocate(100); ByteBuffer value = ByteBuffer.allocate(1000 - 100 - SortWorker.POINTER_SIZE_BYTES); worker.addValue(key, value); assertFalse(worker.isFull()); key = ByteBuffer.allocate(1); value = ByteBuffer.allocate(0); worker.addValue(key, value); assertTrue(worker.isFull()); worker.beginSlice(); assertFalse(worker.isFull()); key = ByteBuffer.allocate(100); value = ByteBuffer.allocate(1000 - 100 - SortWorker.POINTER_SIZE_BYTES + 1); worker.addValue(key, value); assertTrue(worker.isFull()); } private LinkedHashMap<ByteBuffer, List<ByteBuffer>> sortUntilFull(SortWorker sorter, Iterator<KeyValue<ByteBuffer, ByteBuffer>> input, KeyValue<ByteBuffer, ByteBuffer> extra) { sorter.beginSlice(); while (!sorter.isFull() && input.hasNext()) { KeyValue<ByteBuffer, ByteBuffer> next = input.next(); sorter.addValue(next.getKey(), next.getValue()); } if (extra != null) { sorter.addValue(extra.getKey(), extra.getValue()); } SortContext originalContext = sorter.getContext(); MapSortContext context = new MapSortContext(); sorter.setContext(context); sorter.endSlice(); sorter.setContext(originalContext); return context.map; } }
apache-2.0
wpc/cruisecontrol.rb
vendor/rails/actionpack/test/activerecord/pagination_test.rb
5132
require File.dirname(__FILE__) + '/../active_record_unit' class PaginationTest < ActiveRecordTestCase fixtures :topics, :replies, :developers, :projects, :developers_projects class PaginationController < ActionController::Base self.template_root = "#{File.dirname(__FILE__)}/../fixtures/" def simple_paginate @topic_pages, @topics = paginate(:topics) render :nothing => true end def paginate_with_per_page @topic_pages, @topics = paginate(:topics, :per_page => 1) render :nothing => true end def paginate_with_order @topic_pages, @topics = paginate(:topics, :order => 'created_at asc') render :nothing => true end def paginate_with_order_by @topic_pages, @topics = paginate(:topics, :order_by => 'created_at asc') render :nothing => true end def paginate_with_include_and_order @topic_pages, @topics = paginate(:topics, :include => :replies, :order => 'replies.created_at asc, topics.created_at asc') render :nothing => true end def paginate_with_conditions @topic_pages, @topics = paginate(:topics, :conditions => ["created_at > ?", 30.minutes.ago]) render :nothing => true end def paginate_with_class_name @developer_pages, @developers = paginate(:developers, :class_name => "DeVeLoPeR") render :nothing => true end def paginate_with_singular_name @developer_pages, @developers = paginate() render :nothing => true end def paginate_with_joins @developer_pages, @developers = paginate(:developers, :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', :conditions => 'project_id=1') render :nothing => true end def paginate_with_join @developer_pages, @developers = paginate(:developers, :join => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id', :conditions => 'project_id=1') render :nothing => true end def paginate_with_join_and_count @developer_pages, @developers = paginate(:developers, :join => 'd LEFT JOIN developers_projects ON d.id = developers_projects.developer_id', :conditions => 'project_id=1', :count => "d.id") render :nothing => true end def rescue_errors(e) raise e end def rescue_action(e) raise end end def setup @controller = PaginationController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new super end # Single Action Pagination Tests def test_simple_paginate get :simple_paginate assert_equal 1, assigns(:topic_pages).page_count assert_equal 3, assigns(:topics).size end def test_paginate_with_per_page get :paginate_with_per_page assert_equal 1, assigns(:topics).size assert_equal 3, assigns(:topic_pages).page_count end def test_paginate_with_order get :paginate_with_order expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails)] assert_equal expected, assigns(:topics) assert_equal 1, assigns(:topic_pages).page_count end def test_paginate_with_order_by get :paginate_with_order expected = assigns(:topics) get :paginate_with_order_by assert_equal expected, assigns(:topics) assert_equal 1, assigns(:topic_pages).page_count end def test_paginate_with_conditions get :paginate_with_conditions expected = [topics(:rails)] assert_equal expected, assigns(:topics) assert_equal 1, assigns(:topic_pages).page_count end def test_paginate_with_class_name get :paginate_with_class_name assert assigns(:developers).size > 0 assert_equal DeVeLoPeR, assigns(:developers).first.class end def test_paginate_with_joins get :paginate_with_joins assert_equal 2, assigns(:developers).size developer_names = assigns(:developers).map { |d| d.name } assert developer_names.include?('David') assert developer_names.include?('Jamis') end def test_paginate_with_join_and_conditions get :paginate_with_joins expected = assigns(:developers) get :paginate_with_join assert_equal expected, assigns(:developers) end def test_paginate_with_join_and_count get :paginate_with_joins expected = assigns(:developers) get :paginate_with_join_and_count assert_equal expected, assigns(:developers) end def test_paginate_with_include_and_order get :paginate_with_include_and_order expected = Topic.find(:all, :include => 'replies', :order => 'replies.created_at asc, topics.created_at asc', :limit => 10) assert_equal expected, assigns(:topics) end end
apache-2.0
zlcnju/kettle
plugins/pur/core/src/main/java/com/pentaho/di/revision/RevisionResource.java
6649
/*! * Copyright 2010 - 2015 Pentaho Corporation. 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. * */ package com.pentaho.di.revision; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.Response; import org.codehaus.enunciate.jaxrs.ResponseCode; import org.codehaus.enunciate.jaxrs.StatusCodes; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.repository.ObjectRevision; import org.pentaho.di.repository.StringObjectId; import org.pentaho.di.repository.pur.PurObjectRevision; import org.pentaho.di.repository.pur.UnifiedRepositoryRevisionService; import org.pentaho.di.ui.repository.pur.services.IRevisionService; import org.pentaho.platform.api.repository2.unified.IRepositoryVersionManager; import org.pentaho.platform.api.repository2.unified.IUnifiedRepository; import org.pentaho.platform.api.repository2.unified.RepositoryFile; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.repository2.unified.webservices.FileVersioningConfiguration; import org.pentaho.platform.web.http.api.resources.utils.FileUtils; /** * Created by pminutillo on 7/7/14. * * Provide REST endpoints for revision API. These methods will provide the current status of the versioning and version * comments enabled flags */ @Path( "/pur-repository-plugin/api/revision" ) public class RevisionResource { IUnifiedRepository repository; IRevisionService revisionService = null; static IRepositoryVersionManager repositoryVersionManager; /** * * @param unifiedRepository */ public RevisionResource( IUnifiedRepository unifiedRepository ) { this.repository = unifiedRepository; // Is there a better way to get the revisionService this.revisionService = new UnifiedRepositoryRevisionService( unifiedRepository, null ); } /** * Retrieves the version history of a selected repository file * * <p> * <b>Example Request:</b><br> * GET /pur-repository-plugin/api/revision/path:to:file/revisions * </p> * * @param pathId * (colon separated path for the repository file) * * <pre function="syntax.xml"> * :path:to:file:id * </pre> * @return file revisions objects <code> purObjectRevisions </code> * * <pre function="syntax.xml"> * &lt;purObjectRevisions&gt; * &lt;revision&gt; * &lt;versionId&gt;1.0&lt;/versionId&gt; * &lt;creationDate&gt;2014-07-22T14:42:46.029-04:00&lt;/creationDate&gt; * &lt;login&gt;admin&lt;/login&gt; * &lt;comment&gt;JMeter test&lt;/comment&gt; * &lt;/revision&gt; * &lt;/purObjectRevisions&gt; * </pre> */ @GET @Path( "{pathId : .+}/revisions" ) @StatusCodes( { @ResponseCode( code = 200, condition = "Successfully returns list of revisions" ), @ResponseCode( code = 500, condition = "Something failed when attempting to retrieve revisions" ), @ResponseCode( code = 404, condition = "Invalid path" ) } ) @Produces( { APPLICATION_XML, APPLICATION_JSON } ) public Response doGetVersions( @PathParam( "pathId" ) String pathId ) { Serializable fileId = null; List<ObjectRevision> originalRevisions = null; RepositoryFile repositoryFile = repository.getFile( FileUtils.idToPath( pathId ) ); if ( repositoryFile != null ) { fileId = repositoryFile.getId(); } if ( fileId != null ) { try { originalRevisions = revisionService.getRevisions( new StringObjectId( fileId.toString() ) ); } catch ( KettleException e ) { return Response.serverError().build(); } List<PurObjectRevision> revisions = new ArrayList(); for ( ObjectRevision revision : originalRevisions ) { revisions.add( (PurObjectRevision) revision ); } GenericEntity<List<PurObjectRevision>> genericRevisionsEntity = new GenericEntity<List<PurObjectRevision>>( revisions ) { }; return Response.ok( genericRevisionsEntity ).build(); } else { return Response.serverError().build(); } } /** * This method is used to determine whether versioning should be active for the given path * * <p> * <b>Example Request:</b><br /> * GET pentaho/api/repo/files/:jmeter-test:test_file_1.ktr/versioningConfiguration </pre> * </p> * * @param pathId * Colon separated path for the repository file. * * @return The Versioning Configuration applicable to the path submitted * * <p> * <b>Example Response:</b> * </p> * * <pre function="syntax.xml"> * &lt;fileVersioningConfiguration&gt; * &lt;versionCommentEnabled&gt;true&lt;/versionCommentEnabled&gt; * &lt;versioningEnabled&gt;true&lt;/versioningEnabled&gt; * &lt;/fileVersioningConfiguration&gt; * </pre> */ @GET @Path( "{pathId}/versioningConfiguration" ) @Produces( { APPLICATION_XML, APPLICATION_JSON } ) @StatusCodes( { @ResponseCode( code = 200, condition = "Successfully returns the versioning configuation" ) } ) public FileVersioningConfiguration doVersioningConfiguration( @PathParam( "pathId" ) String pathId ) { if ( RevisionResource.repositoryVersionManager == null ) { RevisionResource.repositoryVersionManager = PentahoSystem.get( IRepositoryVersionManager.class ); } return new FileVersioningConfiguration( RevisionResource.repositoryVersionManager.isVersioningEnabled( FileUtils .idToPath( pathId ) ), repositoryVersionManager.isVersionCommentEnabled( FileUtils.idToPath( pathId ) ) ); } /** * For use by junit tests * * @param repositoryVersionManager */ public static void setRepositoryVersionManager( IRepositoryVersionManager repositoryVersionManager ) { RevisionResource.repositoryVersionManager = repositoryVersionManager; } }
apache-2.0
maas-ufcg/manageiq
lib/miq_automation_engine/service_models/miq_ae_service_manageiq-providers-amazon-cloud_manager-provision.rb
161
module MiqAeMethodService class MiqAeServiceManageIQ_Providers_Amazon_CloudManager_Provision < MiqAeServiceManageIQ_Providers_CloudManager_Provision end end
apache-2.0
yzwudi/wonder
vendor/rmrevin/yii2-fontawesome/FontAwesome.php
2181
<?php /** * FontAwesome.php * @author Revin Roman * @link https://rmrevin.ru */ namespace rmrevin\yii\fontawesome; use rmrevin\yii\fontawesome\component; /** * Class FA * @package rmrevin\yii\fontawesome */ class FontAwesome { /** @var string CSS Class prefix */ public static $cssPrefix = 'fa'; /** * Creates an `Icon` component that can be used to FontAwesome html icon * * @param string $name * @param array $options * @return component\Icon */ public static function icon($name, $options = []) { return new component\Icon($name, $options); } /** * Shortcut for `icon()` method * @see icon() * * @param string $name * @param array $options * @return component\Icon */ public static function i($name, $options = []) { return static::icon($name, $options); } /** * Creates an `Stack` component that can be used to FontAwesome html icon * * @param array $options * @return component\Stack */ public static function stack($options = []) { return new component\Stack($options); } /** * Shortcut for `stack()` method * @see stack() * * @param array $options * @return component\Stack */ public static function s($options = []) { return static::stack($options); } /** * @param array $options * @return component\UnorderedList */ public static function ul($options = []) { return new component\UnorderedList($options); } /** * Size values * @see rmrevin\yii\fontawesome\component\Icon::size */ const SIZE_LARGE = 'lg'; const SIZE_2X = '2x'; const SIZE_3X = '3x'; const SIZE_4X = '4x'; const SIZE_5X = '5x'; /** * Rotate values * @see rmrevin\yii\fontawesome\component\Icon::rotate */ const ROTATE_90 = '90'; const ROTATE_180 = '180'; const ROTATE_270 = '270'; /** * Flip values * @see rmrevin\yii\fontawesome\component\Icon::flip */ const FLIP_HORIZONTAL = 'horizontal'; const FLIP_VERTICAL = 'vertical'; }
bsd-3-clause
seem-sky/FrameworkBenchmarks
php-lithium/libraries/lithium/analysis/logger/adapter/Syslog.php
2870
<?php /** * Lithium: the most rad php framework * * @copyright Copyright 2012, Union of RAD (http://union-of-rad.org) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ namespace lithium\analysis\logger\adapter; /** * The Syslog adapter facilitates logging messages to a `syslogd` backend. See the constructor for * information on configuring this adapter. * * @see lithium\analysis\logger\adapter\Syslog::__construct() */ class Syslog extends \lithium\core\Object { /** * Flag indicating whether or not the connection to `syslogd` has been opened yet. * * @var boolean */ protected $_isConnected = false; /** * Array that maps `Logger` message priority names to `syslog`-compatible priority constants. * * @var array */ protected $_priorities = array( 'emergency' => LOG_EMERG, 'alert' => LOG_ALERT, 'critical' => LOG_CRIT, 'error' => LOG_ERR, 'warning' => LOG_WARNING, 'notice' => LOG_NOTICE, 'info' => LOG_INFO, 'debug' => LOG_DEBUG ); /** * Class constructor. Configures the `Syslog` adapter instance with the default settings. For * more information on these settings, see the documentation for * [the `openlog()` function](http://php.net/openlog). * * @param array $config Available configuration settings for this adapter: * - `'identity'` _string_: The identity string to be attached to each message in * the system log. This is usually a string that meaningfully identifies your * application. Defaults to `false`. * - `'options'` _integer_: The flags to use when opening the log. Defaults to * `LOG_ODELAY`. * - `'facility'` _integer_: A flag specifying the program to use to log the * messages. See the `openlog()` documentation for more information. Defaults to * `LOG_USER`. */ public function __construct(array $config = array()) { $defaults = array('identity' => false, 'options' => LOG_ODELAY, 'facility' => LOG_USER); parent::__construct($config + $defaults); } /** * Appends `$message` to the system log. * * @param string $priority The message priority string. Maps to a `syslogd` priority constant. * @param string $message The message to write. * @return closure Function returning boolean `true` on successful write, `false` otherwise. */ public function write($priority, $message) { $config = $this->_config; $_priorities = $this->_priorities; if (!$this->_isConnected) { closelog(); openlog($config['identity'], $config['options'], $config['facility']); $this->_isConnected = true; } return function($self, $params) use ($_priorities) { $priority = $_priorities[$params['priority']]; return syslog($priority, $params['message']); }; } } ?>
bsd-3-clause
hoastoolshop/react-native
ReactAndroid/src/main/java/com/facebook/react/modules/core/PermissionAwareActivity.java
982
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.modules.core; import android.app.Activity; /** * Interface used to denote activities that can forward permission requests and call * {@link PermissionListener}s with the permission request results. */ public interface PermissionAwareActivity { /** * See {@link Activity#checkPermission}. */ int checkPermission(String permission, int pid, int uid); /** * See {@link Activity#checkSelfPermission}. */ int checkSelfPermission(String permission); /** * See {@link Activity#shouldShowRequestPermissionRationale}. */ boolean shouldShowRequestPermissionRationale(String permission); /** * See {@link Activity#requestPermissions}. */ void requestPermissions(String[] permissions, int requestCode, PermissionListener listener); }
bsd-3-clause
rbenech/RiWebApps
mqtt-test/node_modules/browserify/test/pkg.js
457
var browserify = require('../'); var vm = require('vm'); var test = require('tap').test; var path = require('path'); var pkg = require('./pkg/package.json'); pkg.__dirname = path.join(__dirname, 'pkg'); test('package', function (t) { t.plan(2); var b = browserify(__dirname + '/pkg/main.js'); b.on('package', function (pkg_) { t.deepEqual(pkg_, pkg); }); b.bundle(function (err) { t.ifError(err); }); });
unlicense
lujinming1/hejicaoye
node_modules/react-error-overlay/lib/__tests__/get-source-map.js
3847
import _regeneratorRuntime from 'babel-runtime/regenerator'; var _this = this; function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import { getSourceMap } from '../utils/getSourceMap'; import fs from 'fs'; import { resolve } from 'path'; test('finds an external source map', _asyncToGenerator(_regeneratorRuntime.mark(function _callee() { var file, sm; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: file = fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')).toString('utf8'); fetch.mockResponseOnce(fs.readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')).toString('utf8')); _context.next = 4; return getSourceMap('/', file); case 4: sm = _context.sent; expect(sm.getOriginalPosition(26122, 21)).toEqual({ line: 7, column: 0, source: 'webpack:///packages/react-scripts/template/src/App.js' }); case 6: case 'end': return _context.stop(); } } }, _callee, _this); }))); test('find an inline source map', _asyncToGenerator(_regeneratorRuntime.mark(function _callee2() { var sourceName, file, fileO, sm; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: sourceName = 'test.js'; file = fs.readFileSync(resolve(__dirname, '../../fixtures/inline.mjs')).toString('utf8'); fileO = fs.readFileSync(resolve(__dirname, '../../fixtures/inline.es6.mjs')).toString('utf8'); _context2.next = 5; return getSourceMap('/', file); case 5: sm = _context2.sent; expect(sm.getSources()).toEqual([sourceName]); expect(sm.getSource(sourceName)).toBe(fileO); expect(sm.getGeneratedPosition(sourceName, 5, 10)).toEqual({ line: 10, column: 8 }); case 9: case 'end': return _context2.stop(); } } }, _callee2, _this); }))); test('error on a source map with unsupported encoding', _asyncToGenerator(_regeneratorRuntime.mark(function _callee3() { var file; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: expect.assertions(2); file = fs.readFileSync(resolve(__dirname, '../../fixtures/junk-inline.mjs')).toString('utf8'); _context3.prev = 2; _context3.next = 5; return getSourceMap('/', file); case 5: _context3.next = 11; break; case 7: _context3.prev = 7; _context3.t0 = _context3['catch'](2); expect(_context3.t0 instanceof Error).toBe(true); expect(_context3.t0.message).toBe('Sorry, non-base64 inline source-map encoding is not supported.'); case 11: case 'end': return _context3.stop(); } } }, _callee3, _this, [[2, 7]]); })));
mit
elmago79/dgp
vendor/phpdocumentor/phpdocumentor/src/phpDocumentor/Compiler/Linker/Linker.php
13051
<?php /** * phpDocumentor * * PHP Version 5.3 * * @copyright 2010-2014 Mike van Riel / Naenius (http://www.naenius.com) * @license http://www.opensource.org/licenses/mit-license.php MIT * @link http://phpdoc.org */ namespace phpDocumentor\Compiler\Linker; use phpDocumentor\Compiler\CompilerPassInterface; use phpDocumentor\Descriptor\ClassDescriptor; use phpDocumentor\Descriptor\Collection; use phpDocumentor\Descriptor\DescriptorAbstract; use phpDocumentor\Descriptor\FileDescriptor; use phpDocumentor\Descriptor\InterfaceDescriptor; use phpDocumentor\Descriptor\Interfaces\ProjectInterface; use phpDocumentor\Descriptor\NamespaceDescriptor; use phpDocumentor\Descriptor\ProjectDescriptor; use phpDocumentor\Descriptor\TraitDescriptor; use phpDocumentor\Descriptor\Type\UnknownTypeDescriptor; /** * The linker contains all rules to replace FQSENs in the ProjectDescriptor with aliases to objects. * * This object contains a list of class FQCNs for Descriptors and their associated linker rules. * * An example scenario should be: * * The Descriptor ``\phpDocumentor\Descriptor\ClassDescriptor`` has a *Substitute* rule determining that the * contents of the ``Parent`` field should be substituted with another ClassDescriptor with the FQCN * represented by the value of the Parent field. In addition (second element) it has an *Analyse* rule * specifying that the contents of the ``Methods`` field should be interpreted by the linker. Because that field * contains an array or Descriptor Collection will each element be analysed by the linker. * * As can be seen in the above example is it possible to analyse a tree structure and substitute FQSENs where * encountered. */ class Linker implements CompilerPassInterface { const COMPILER_PRIORITY = 10000; const CONTEXT_MARKER = '@context'; /** @var DescriptorAbstract[] */ protected $elementList = array(); /** @var string[][] */ protected $substitutions = array(); /** @var string[] Prevent cycles by tracking which objects have been analyzed */ protected $processedObjects = array(); /** * {@inheritDoc} */ public function getDescription() { return 'Replace textual FQCNs with object aliases'; } /** * Initializes the linker with a series of Descriptors to link to. * * @param array|string[][] $substitutions */ public function __construct(array $substitutions) { $this->substitutions = $substitutions; } /** * Executes the linker. * * @param ProjectDescriptor $project Representation of the Object Graph that can be manipulated. * * @return void */ public function execute(ProjectDescriptor $project) { $this->setObjectAliasesList($project->getIndexes()->elements->getAll()); $this->substitute($project); } /** * Returns the list of substitutions for the linker. * * @return string[] */ public function getSubstitutions() { return $this->substitutions; } /** * Sets the list of object aliases to resolve the FQSENs with. * * @param DescriptorAbstract[] $elementList * * @return void */ public function setObjectAliasesList(array $elementList) { $this->elementList = $elementList; } /** * Substitutes the given item or its children's FQCN with an object alias. * * This method may do either of the following depending on the item's type * * String * If the given item is a string then this method will attempt to find an appropriate Class, Interface or * TraitDescriptor object and return that. See {@see findAlias()} for more information on the normalization * of these strings. * * Array or Traversable * Iterate through each item, pass each key's contents to a new call to substitute and replace the key's * contents if the contents is not an object (objects automatically update and saves performance). * * Object * Determines all eligible substitutions using the substitutions property, construct a getter and retrieve * the field's contents. Pass these contents to a new call of substitute and use a setter to replace the field's * contents if anything other than null is returned. * * This method will return null if no substitution was possible and all of the above should not update the parent * item when null is passed. * * @param string|object|\Traversable|array $item * @param DescriptorAbstract|null $container A descriptor that acts as container for all elements * underneath or null if there is no current container. * * @return null|string|DescriptorAbstract */ public function substitute($item, $container = null) { $result = null; if (is_string($item)) { $result = $this->findAlias($item, $container); } elseif (is_array($item) || ($item instanceof \Traversable && ! $item instanceof ProjectInterface)) { $isModified = false; foreach ($item as $key => $element) { $isModified = true; $element = $this->substitute($element, $container); if ($element !== null) { $item[$key] = $element; } } if ($isModified) { $result = $item; } } elseif (is_object($item) && $item instanceof UnknownTypeDescriptor) { $alias = $this->findAlias($item->getName()); $result = $alias ?: $item; } elseif (is_object($item)) { $hash = spl_object_hash($item); if (isset($this->processedObjects[$hash])) { // if analyzed; just return return null; } $newContainer = ($this->isDescriptorContainer($item)) ? $item : $container; $this->processedObjects[$hash] = true; $objectClassName = get_class($item); $fieldNames = isset($this->substitutions[$objectClassName]) ? $this->substitutions[$objectClassName] : array(); foreach ($fieldNames as $fieldName) { $fieldValue = $this->findFieldValue($item, $fieldName); $response = $this->substitute($fieldValue, $newContainer); // if the returned response is not an object it must be grafted on the calling object if ($response !== null) { $setter = 'set'.ucfirst($fieldName); $item->$setter($response); } } } return $result; } /** * Attempts to find a Descriptor object alias with the FQSEN of the element it represents. * * This method will try to fetch an element after normalizing the provided FQSEN. The FQSEN may contain references * (bindings) that can only be resolved during linking (such as `self`) or it may contain a context marker * {@see CONTEXT_MARKER}. * * If there is a context marker then this method will see if a child of the given container exists that matches the * element following the marker. If such a child does not exist in the current container then the namespace is * queried if a child exists there that matches. * * For example: * * Given the Fqsen `@context::myFunction()` and the lastContainer `\My\Class` will this method first check * to see if `\My\Class::myFunction()` exists; if it doesn't it will then check if `\My\myFunction()` exists. * * If neither element exists then this method assumes it is an undocumented class/trait/interface and change the * given FQSEN by returning the namespaced element name (thus in the example above that would be * `\My\myFunction()`). The calling method {@see substitute()} will then replace the value of the field containing * the context marker with this normalized string. * * @param string $fqsen * @param DescriptorAbstract|null $container * * @return DescriptorAbstract|string|null */ public function findAlias($fqsen, $container = null) { $fqsen = $this->replacePseudoTypes($fqsen, $container); if ($this->isContextMarkerInFqsen($fqsen) && $container instanceof DescriptorAbstract) { // first exchange `@context::element` for `\My\Class::element` and if it exists, return that $classMember = $this->fetchElementByFqsen($this->getTypeWithClassAsContext($fqsen, $container)); if ($classMember) { return $classMember; } // otherwise exchange `@context::element` for `\My\element` and if it exists, return that $namespaceContext = $this->getTypeWithNamespaceAsContext($fqsen, $container); $namespaceMember = $this->fetchElementByFqsen($namespaceContext); if ($namespaceMember) { return $namespaceMember; } // Otherwise we assume it is an undocumented class/interface/trait and return `\My\element` so // that the name containing the marker may be replaced by the class reference as string return $namespaceContext; } return $this->fetchElementByFqsen($fqsen); } /** * Returns the value of a field in the given object. * * @param object $object * @param string $fieldName * * @return string|object */ public function findFieldValue($object, $fieldName) { $getter = 'get'.ucfirst($fieldName); return $object->$getter(); } /** * Returns true if the given Descriptor is a container type. * * @param DescriptorAbstract|mixed $item * * @return bool */ protected function isDescriptorContainer($item) { return $item instanceof FileDescriptor || $item instanceof NamespaceDescriptor || $item instanceof ClassDescriptor || $item instanceof TraitDescriptor || $item instanceof InterfaceDescriptor; } /** * Replaces pseudo-types, such as `self`, into a normalized version based on the last container that was * encountered. * * @param string $fqsen * @param DescriptorAbstract|null $container * * @return string */ protected function replacePseudoTypes($fqsen, $container) { $pseudoTypes = array('self', '$this'); foreach ($pseudoTypes as $pseudoType) { if ((strpos($fqsen, $pseudoType . '::') === 0 || $fqsen === $pseudoType) && $container) { $fqsen = $container->getFullyQualifiedStructuralElementName() . substr($fqsen, strlen($pseudoType)); } } return $fqsen; } /** * Returns true if the context marker is found in the given FQSEN. * * @param string $fqsen * * @return bool */ protected function isContextMarkerInFqsen($fqsen) { return strpos($fqsen, self::CONTEXT_MARKER) !== false; } /** * Normalizes the given FQSEN as if the context marker represents a class/interface/trait as parent. * * @param string $fqsen * @param DescriptorAbstract $container * * @return string */ protected function getTypeWithClassAsContext($fqsen, DescriptorAbstract $container) { if (!$container instanceof ClassDescriptor && !$container instanceof InterfaceDescriptor && !$container instanceof TraitDescriptor ) { return $fqsen; } $containerFqsen = $container->getFullyQualifiedStructuralElementName(); return str_replace(self::CONTEXT_MARKER . '::', $containerFqsen . '::', $fqsen); } /** * Normalizes the given FQSEN as if the context marker represents a class/interface/trait as parent. * * @param string $fqsen * @param DescriptorAbstract $container * * @return string */ protected function getTypeWithNamespaceAsContext($fqsen, DescriptorAbstract $container) { $namespace = $container instanceof NamespaceDescriptor ? $container : $container->getNamespace(); $fqnn = $namespace instanceof NamespaceDescriptor ? $namespace->getFullyQualifiedStructuralElementName() : $namespace; return str_replace(self::CONTEXT_MARKER . '::', $fqnn . '\\', $fqsen); } /** * Attempts to find an element with the given Fqsen in the list of elements for this project and returns null if * it cannot find it. * * @param string $fqsen * * @return DescriptorAbstract|null */ protected function fetchElementByFqsen($fqsen) { return isset($this->elementList[$fqsen]) ? $this->elementList[$fqsen] : null; } }
mit
burnflare/Twillio-node
node_modules/orm/test/integration/property-timezones.js
2830
var should = require('should'); var helper = require('../support/spec_helper'); var common = require('../common'); var ORM = require('../../'); if (common.protocol() == "mongodb") return; if (common.protocol() == "sqlite" && !common.getConfig().pathname) { // sqlite needs a pathname for this test (because of reconnecting) // if using memory, when disconnecting everything is lost and this // test needs it return; } describe("Timezones", function() { var db = null; var Event = null; var setup = function (opts) { return function (done) { helper.connect({ query: opts.query }, function (connection) { db = connection; db.settings.set('instance.cache', false); Event = db.define("event", { name : { type: 'text' }, when : { type: 'date', time: true } }); if (opts.sync) { return helper.dropSync(Event, done); } else { return done(); } }); }; }; describe("specified", function () { var a, zones = [ 'local', '-0734'/*, '+11:22'*/ ]; for (a = 0; a < zones.length; a++ ) { describe(zones[a], function () { before(setup({ sync: true, query: { timezone: zones[a] } })); after(function () { return db.close(); }); it("should get back the same date that was stored", function (done) { var when = new Date(2013, 12, 5, 5, 34, 27); Event.create({ name: "raid fridge", when: when }, function (err) { should.not.exist(err); Event.one({ name: "raid fridge" }, function (err, item) { should.not.exist(err); item.when.should.eql(when); return done(); }); }); }); }); } }); describe("different for each connection", function () { before(setup({ sync : true, query : { timezone: '+0200' } })); after(function () { return db.close(); }); // This isn't consistent accross drivers. Needs more thinking and investigation. it("should get back a correctly offset time", function (done) { var when = new Date(2013, 12, 5, 5, 34, 27); Event.create({ name: "raid fridge", when: when }, function (err, new_event) { should.not.exist(err); Event.one({ name: "raid fridge" }, function (err, item) { should.not.exist(err); new_event.should.not.equal(item); // new_event was not cached should.equal(new_event.when.toISOString(), item.when.toISOString()); db.close(function () { setup({ sync : false, // don't recreate table, don't want to loose previous value query : { timezone: '+0400' } })(function () { Event.one({ name: "raid fridge" }, function (err, item) { var expected = new Date(2013, 12, 5, 3, 34, 27); should.not.exist(err); item.when.should.eql(expected); return done(); }); }); }); }); }); }); }); });
mit
shwnd/angularstarter
API/node_modules/everyauth/lib/modules/vimeo.js
678
var oauthModule = require('./oauth'); var vimeo = module.exports = oauthModule.submodule('vimeo') .apiHost('http://vimeo.com/api/rest/v2') .oauthHost('http://vimeo.com') .entryPath('/auth/vimeo') .callbackPath('/auth/vimeo/callback') .fetchOAuthUser( function (accessToken, accessTokenSecret, params) { var promise = this.Promise(); this.oauth.get(this.apiHost() + '?format=json&method=vimeo.people.getInfo&user_id=' + accessTokenSecret, accessToken, accessTokenSecret, function (err, data) { if (err) return promise.fail(err); var oauthUser = JSON.parse(data); return promise.fulfill(oauthUser.person); }); return promise; });
mit
sweethousecr/house
vendor/yiisoft/yii2/captcha/CaptchaAction.php
12704
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\captcha; use Yii; use yii\base\Action; use yii\base\InvalidConfigException; use yii\helpers\Url; use yii\web\Response; /** * CaptchaAction renders a CAPTCHA image. * * CaptchaAction is used together with [[Captcha]] and [[\yii\captcha\CaptchaValidator]] * to provide the [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) feature. * * By configuring the properties of CaptchaAction, you may customize the appearance of * the generated CAPTCHA images, such as the font color, the background color, etc. * * Note that CaptchaAction requires either GD2 extension or ImageMagick PHP extension. * * Using CAPTCHA involves the following steps: * * 1. Override [[\yii\web\Controller::actions()]] and register an action of class CaptchaAction with ID 'captcha' * 2. In the form model, declare an attribute to store user-entered verification code, and declare the attribute * to be validated by the 'captcha' validator. * 3. In the controller view, insert a [[Captcha]] widget in the form. * * @property string $verifyCode The verification code. This property is read-only. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class CaptchaAction extends Action { /** * The name of the GET parameter indicating whether the CAPTCHA image should be regenerated. */ const REFRESH_GET_VAR = 'refresh'; /** * @var int how many times should the same CAPTCHA be displayed. Defaults to 3. * A value less than or equal to 0 means the test is unlimited (available since version 1.1.2). */ public $testLimit = 3; /** * @var int the width of the generated CAPTCHA image. Defaults to 120. */ public $width = 120; /** * @var int the height of the generated CAPTCHA image. Defaults to 50. */ public $height = 50; /** * @var int padding around the text. Defaults to 2. */ public $padding = 2; /** * @var int the background color. For example, 0x55FF00. * Defaults to 0xFFFFFF, meaning white color. */ public $backColor = 0xFFFFFF; /** * @var int the font color. For example, 0x55FF00. Defaults to 0x2040A0 (blue color). */ public $foreColor = 0x2040A0; /** * @var bool whether to use transparent background. Defaults to false. */ public $transparent = false; /** * @var int the minimum length for randomly generated word. Defaults to 6. */ public $minLength = 6; /** * @var int the maximum length for randomly generated word. Defaults to 7. */ public $maxLength = 7; /** * @var int the offset between characters. Defaults to -2. You can adjust this property * in order to decrease or increase the readability of the captcha. */ public $offset = -2; /** * @var string the TrueType font file. This can be either a file path or [path alias](guide:concept-aliases). */ public $fontFile = '@yii/captcha/SpicyRice.ttf'; /** * @var string the fixed verification code. When this property is set, * [[getVerifyCode()]] will always return the value of this property. * This is mainly used in automated tests where we want to be able to reproduce * the same verification code each time we run the tests. * If not set, it means the verification code will be randomly generated. */ public $fixedVerifyCode; /** * @var string the rendering library to use. Currently supported only 'gd' and 'imagick'. * If not set, library will be determined automatically. * @since 2.0.7 */ public $imageLibrary; /** * Initializes the action. * @throws InvalidConfigException if the font file does not exist. */ public function init() { $this->fontFile = Yii::getAlias($this->fontFile); if (!is_file($this->fontFile)) { throw new InvalidConfigException("The font file does not exist: {$this->fontFile}"); } } /** * Runs the action. */ public function run() { if (Yii::$app->request->getQueryParam(self::REFRESH_GET_VAR) !== null) { // AJAX request for regenerating code $code = $this->getVerifyCode(true); Yii::$app->response->format = Response::FORMAT_JSON; return [ 'hash1' => $this->generateValidationHash($code), 'hash2' => $this->generateValidationHash(strtolower($code)), // we add a random 'v' parameter so that FireFox can refresh the image // when src attribute of image tag is changed 'url' => Url::to([$this->id, 'v' => uniqid()]), ]; } else { $this->setHttpHeaders(); Yii::$app->response->format = Response::FORMAT_RAW; return $this->renderImage($this->getVerifyCode()); } } /** * Generates a hash code that can be used for client-side validation. * @param string $code the CAPTCHA code * @return string a hash code generated from the CAPTCHA code */ public function generateValidationHash($code) { for ($h = 0, $i = strlen($code) - 1; $i >= 0; --$i) { $h += ord($code[$i]); } return $h; } /** * Gets the verification code. * @param bool $regenerate whether the verification code should be regenerated. * @return string the verification code. */ public function getVerifyCode($regenerate = false) { if ($this->fixedVerifyCode !== null) { return $this->fixedVerifyCode; } $session = Yii::$app->getSession(); $session->open(); $name = $this->getSessionKey(); if ($session[$name] === null || $regenerate) { $session[$name] = $this->generateVerifyCode(); $session[$name . 'count'] = 1; } return $session[$name]; } /** * Validates the input to see if it matches the generated code. * @param string $input user input * @param bool $caseSensitive whether the comparison should be case-sensitive * @return bool whether the input is valid */ public function validate($input, $caseSensitive) { $code = $this->getVerifyCode(); $valid = $caseSensitive ? ($input === $code) : strcasecmp($input, $code) === 0; $session = Yii::$app->getSession(); $session->open(); $name = $this->getSessionKey() . 'count'; $session[$name] = $session[$name] + 1; if ($valid || $session[$name] > $this->testLimit && $this->testLimit > 0) { $this->getVerifyCode(true); } return $valid; } /** * Generates a new verification code. * @return string the generated verification code */ protected function generateVerifyCode() { if ($this->minLength > $this->maxLength) { $this->maxLength = $this->minLength; } if ($this->minLength < 3) { $this->minLength = 3; } if ($this->maxLength > 20) { $this->maxLength = 20; } $length = mt_rand($this->minLength, $this->maxLength); $letters = 'bcdfghjklmnpqrstvwxyz'; $vowels = 'aeiou'; $code = ''; for ($i = 0; $i < $length; ++$i) { if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) { $code .= $vowels[mt_rand(0, 4)]; } else { $code .= $letters[mt_rand(0, 20)]; } } return $code; } /** * Returns the session variable name used to store verification code. * @return string the session variable name */ protected function getSessionKey() { return '__captcha/' . $this->getUniqueId(); } /** * Renders the CAPTCHA image. * @param string $code the verification code * @return string image contents * @throws InvalidConfigException if imageLibrary is not supported */ protected function renderImage($code) { if (isset($this->imageLibrary)) { $imageLibrary = $this->imageLibrary; } else { $imageLibrary = Captcha::checkRequirements(); } if ($imageLibrary === 'gd') { return $this->renderImageByGD($code); } elseif ($imageLibrary === 'imagick') { return $this->renderImageByImagick($code); } else { throw new InvalidConfigException("Defined library '{$imageLibrary}' is not supported"); } } /** * Renders the CAPTCHA image based on the code using GD library. * @param string $code the verification code * @return string image contents in PNG format. */ protected function renderImageByGD($code) { $image = imagecreatetruecolor($this->width, $this->height); $backColor = imagecolorallocate( $image, (int) ($this->backColor % 0x1000000 / 0x10000), (int) ($this->backColor % 0x10000 / 0x100), $this->backColor % 0x100 ); imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor); imagecolordeallocate($image, $backColor); if ($this->transparent) { imagecolortransparent($image, $backColor); } $foreColor = imagecolorallocate( $image, (int) ($this->foreColor % 0x1000000 / 0x10000), (int) ($this->foreColor % 0x10000 / 0x100), $this->foreColor % 0x100 ); $length = strlen($code); $box = imagettfbbox(30, 0, $this->fontFile, $code); $w = $box[4] - $box[0] + $this->offset * ($length - 1); $h = $box[1] - $box[5]; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8); $angle = mt_rand(-10, 10); $letter = $code[$i]; $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter); $x = $box[2] + $this->offset; } imagecolordeallocate($image, $foreColor); ob_start(); imagepng($image); imagedestroy($image); return ob_get_clean(); } /** * Renders the CAPTCHA image based on the code using ImageMagick library. * @param string $code the verification code * @return string image contents in PNG format. */ protected function renderImageByImagick($code) { $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT)); $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT)); $image = new \Imagick(); $image->newImage($this->width, $this->height, $backColor); $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize(30); $fontMetrics = $image->queryFontMetrics($draw, $code); $length = strlen($code); $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1); $h = (int) $fontMetrics['textHeight'] - 8; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8)); $draw->setFillColor($foreColor); $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]); $fontMetrics = $image->queryFontMetrics($draw, $code[$i]); $x += (int) $fontMetrics['textWidth'] + $this->offset; } $image->setImageFormat('png'); return $image->getImageBlob(); } /** * Sets the HTTP headers needed by image response. */ protected function setHttpHeaders() { Yii::$app->getResponse()->getHeaders() ->set('Pragma', 'public') ->set('Expires', '0') ->set('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->set('Content-Transfer-Encoding', 'binary') ->set('Content-type', 'image/png'); } }
mit
StudioBOZ/thirdClass
app/code/core/Mage/Adminhtml/Block/Report/Product/Grid.php
3897
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * 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@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Adminhtml * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Adminhtml products report grid block * * @category Mage * @package Mage_Adminhtml * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Adminhtml_Block_Report_Product_Grid extends Mage_Adminhtml_Block_Widget_Grid { public function __construct() { parent::__construct(); $this->setId('productsReportGrid'); $this->setDefaultSort('entity_id'); $this->setDefaultDir('desc'); } protected function _prepareCollection() { $collection = Mage::getResourceModel('reports/product_collection'); $collection->getEntity()->setStore(0); $this->setCollection($collection); return parent::_prepareCollection(); } protected function _afterLoadCollection() { $totalObj = new Mage_Reports_Model_Totals(); $this->setTotals($totalObj->countTotals($this)); } protected function _prepareColumns() { $this->addColumn('entity_id', array( 'header' =>Mage::helper('reports')->__('ID'), 'width' =>'50px', 'index' =>'entity_id', 'total' =>'Total' )); $this->addColumn('name', array( 'header' =>Mage::helper('reports')->__('Name'), 'index' =>'name' )); $this->addColumn('viewed', array( 'header' =>Mage::helper('reports')->__('Number Viewed'), 'width' =>'50px', 'align' =>'right', 'index' =>'viewed', 'total' =>'sum' )); $this->addColumn('added', array( 'header' =>Mage::helper('reports')->__('Number Added'), 'width' =>'50px', 'align' =>'right', 'index' =>'added', 'total' =>'sum' )); $this->addColumn('purchased', array( 'header' =>Mage::helper('reports')->__('Number Purchased'), 'width' =>'50px', 'align' =>'right', 'index' =>'purchased', 'total' =>'sum' )); $this->addColumn('fulfilled', array( 'header' =>Mage::helper('reports')->__('Number Fulfilled'), 'width' =>'50px', 'align' =>'right', 'index' =>'fulfilled', 'total' =>'sum' )); $this->addColumn('revenue', array( 'header' =>Mage::helper('reports')->__('Revenue'), 'width' =>'50px', 'align' =>'right', 'index' =>'revenue', 'total' =>'sum' )); $this->setCountTotals(true); $this->addExportType('*/*/exportProductsCsv', Mage::helper('reports')->__('CSV')); $this->addExportType('*/*/exportProductsExcel', Mage::helper('reports')->__('Excel XML')); return parent::_prepareColumns(); } }
mit
uhoh-itsmaciek/sequel
lib/sequel/plugins/tree.rb
4839
module Sequel module Plugins # The Tree plugin adds additional associations and methods that allow you to # treat a Model as a tree. # # A column for holding the parent key is required and is :parent_id by default. # This may be overridden by passing column name via :key. # # Optionally, a column to control order of nodes returned can be specified # by passing column name via :order. # # If you pass true for the :single_root option, the class will ensure there is # only ever one root in the tree. # # Examples: # # class Node < Sequel::Model # plugin :tree # end # # class Node < Sequel::Model # plugin :tree, :key=>:parentid, :order=>:position # end module Tree # Create parent and children associations. Any options # specified are passed to both associations. You can also # specify options to use for just the parent association # using a :parent option, and options to use for just the # children association using a :children option. def self.apply(model, opts=OPTS) opts = opts.dup opts[:class] = model model.instance_eval do @parent_column = (opts[:key] ||= :parent_id) @tree_order = opts[:order] end par = opts.merge(opts.fetch(:parent, {})) parent = par.fetch(:name, :parent) chi = opts.merge(opts.fetch(:children, {})) children = chi.fetch(:name, :children) par[:reciprocal] = children chi[:reciprocal] = parent model.many_to_one parent, par model.one_to_many children, chi model.plugin SingleRoot if opts[:single_root] end module ClassMethods # The column symbol or array of column symbols on which to order the tree. attr_accessor :tree_order # The symbol for the column containing the value pointing to the # parent of the leaf. attr_accessor :parent_column Plugins.inherited_instance_variables(self, :@parent_column=>nil, :@tree_order=>nil) # Returns list of all root nodes (those with no parent nodes). # # TreeClass.roots # => [root1, root2] def roots roots_dataset.all end # Returns the dataset for retrieval of all root nodes # # TreeClass.roots_dataset # => Sequel::Dataset instance def roots_dataset ds = where(Sequel.or(Array(parent_column).zip([]))) ds = ds.order(*tree_order) if tree_order ds end end module InstanceMethods # Returns list of ancestors, starting from parent until root. # # subchild1.ancestors # => [child1, root] def ancestors node, nodes = self, [] nodes << node = node.parent while node.parent nodes end # Returns list of descendants # # node.descendants # => [child1, child2, subchild1_1, subchild1_2, subchild2_1, subchild2_2] def descendants nodes = children.dup children.each{|child| nodes.concat(child.descendants)} nodes end # Returns the root node of the tree that this node descends from. # This node is returned if it is a root node itself. def root ancestors.last || self end # Returns true if this is a root node, false otherwise. def root? !new? && possible_root? end # Returns all siblings and a reference to the current node. # # subchild1.self_and_siblings # => [subchild1, subchild2] def self_and_siblings parent ? parent.children : model.roots end # Returns all siblings of the current node. # # subchild1.siblings # => [subchild2] def siblings self_and_siblings - [self] end private # True if if all parent columns values are not NULL. def possible_root? !Array(model.parent_column).map{|c| self[c]}.all? end end # Plugin included when :single_root option is passed. module SingleRoot module ClassMethods # Returns the single root node. def root roots_dataset.first end end module InstanceMethods # Hook that prevents a second root from being created. def before_save if possible_root? && (root = model.root) && pk != root.pk raise TreeMultipleRootError, "there is already a root #{model.name} defined" end super end end end class TreeMultipleRootError < Error; end end end end
mit
mono/referencesource
System.Activities/System/Activities/DynamicUpdate/DynamicUpdateMap.cs
24420
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace System.Activities.DynamicUpdate { using System; using System.Activities.DynamicUpdate; using System.Activities.XamlIntegration; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; [DataContract] [TypeConverter(typeof(DynamicUpdateMapConverter))] public class DynamicUpdateMap { static DynamicUpdateMap noChanges = new DynamicUpdateMap(); static DynamicUpdateMap dummyMap = new DynamicUpdateMap(); internal EntryCollection entries; IList<ArgumentInfo> newArguments; IList<ArgumentInfo> oldArguments; internal DynamicUpdateMap() { } public static DynamicUpdateMap NoChanges { get { return noChanges; } } [DataMember(EmitDefaultValue = false, Name = "entries")] internal EntryCollection SerializedEntries { get { return this.entries; } set { this.entries = value; } } [DataMember(EmitDefaultValue = false, Name = "newArguments")] internal IList<ArgumentInfo> SerializedNewArguments { get { return this.newArguments; } set { this.newArguments = value; } } [DataMember(EmitDefaultValue = false, Name = "oldArguments")] internal IList<ArgumentInfo> SerializedOldArguments { get { return this.oldArguments; } set { this.oldArguments = value; } } // this is a dummy map to be used for creating a NativeActivityUpdateContext // for calling UpdateInstance() on activities without map entries. // this should not be used anywhere except for creating NativeActivityUpdateContext. internal static DynamicUpdateMap DummyMap { get { return dummyMap; } } internal IList<ArgumentInfo> NewArguments { get { if (this.newArguments == null) { this.newArguments = new List<ArgumentInfo>(); } return this.newArguments; } set { this.newArguments = value; } } internal IList<ArgumentInfo> OldArguments { get { if (this.oldArguments == null) { this.oldArguments = new List<ArgumentInfo>(); } return this.oldArguments; } set { this.oldArguments = value; } } [DataMember(EmitDefaultValue = false)] internal bool ArgumentsAreUnknown { get; set; } [DataMember(EmitDefaultValue = false)] internal bool IsImplementationAsRoot { get; set; } [DataMember(EmitDefaultValue = false)] internal int NewDefinitionMemberCount { get; set; } internal int OldDefinitionMemberCount { get { return this.Entries.Count; } } [DataMember(EmitDefaultValue = false)] internal bool IsForImplementation { get; set; } // IdSpaces always have at least one member. So a count of 0 means that this is // DynamicUpdateMap.NoChanges, or a serialized equivalent. internal bool IsNoChanges { get { return this.NewDefinitionMemberCount == 0; } } // use the internal method AddEntry() instead private IList<DynamicUpdateMapEntry> Entries { get { if (this.entries == null) { this.entries = new EntryCollection(); } return this.entries; } } public static IDictionary<object, DynamicUpdateMapItem> CalculateMapItems(Activity workflowDefinitionToBeUpdated) { return CalculateMapItems(workflowDefinitionToBeUpdated, null); } public static IDictionary<object, DynamicUpdateMapItem> CalculateMapItems(Activity workflowDefinitionToBeUpdated, LocationReferenceEnvironment environment) { return InternalCalculateMapItems(workflowDefinitionToBeUpdated, environment, false); } public static IDictionary<object, DynamicUpdateMapItem> CalculateImplementationMapItems(Activity activityDefinitionToBeUpdated) { return CalculateImplementationMapItems(activityDefinitionToBeUpdated, null); } public static IDictionary<object, DynamicUpdateMapItem> CalculateImplementationMapItems(Activity activityDefinitionToBeUpdated, LocationReferenceEnvironment environment) { return InternalCalculateMapItems(activityDefinitionToBeUpdated, environment, true); } public static DynamicUpdateMap Merge(params DynamicUpdateMap[] maps) { return Merge((IEnumerable<DynamicUpdateMap>)maps); } public static DynamicUpdateMap Merge(IEnumerable<DynamicUpdateMap> maps) { if (maps == null) { throw FxTrace.Exception.ArgumentNull("maps"); } // We could try to optimize this by merging the entire set at once, but it's simpler // to just do pairwise merging int index = 0; DynamicUpdateMap result = null; foreach (DynamicUpdateMap nextMap in maps) { result = Merge(result, nextMap, new MergeErrorContext { MapIndex = index }); index++; } return result; } static IDictionary<object, DynamicUpdateMapItem> InternalCalculateMapItems(Activity workflowDefinitionToBeUpdated, LocationReferenceEnvironment environment, bool forImplementation) { if (workflowDefinitionToBeUpdated == null) { throw FxTrace.Exception.ArgumentNull("workflowDefinitionToBeUpdated"); } DynamicUpdateMapBuilder.Preparer preparer = new DynamicUpdateMapBuilder.Preparer(workflowDefinitionToBeUpdated, environment, forImplementation); return preparer.Prepare(); } public DynamicUpdateMapQuery Query(Activity updatedWorkflowDefinition, Activity originalWorkflowDefinition) { if (this.IsNoChanges) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.NoChangesMapQueryNotSupported)); } if (this.IsForImplementation) { ValidateDefinitionMatchesImplementationMap(updatedWorkflowDefinition, this.NewDefinitionMemberCount, "updatedWorkflowDefinition"); ValidateDefinitionMatchesImplementationMap(originalWorkflowDefinition, this.OldDefinitionMemberCount, "originalWorkflowDefinition"); } else { ValidateDefinitionMatchesMap(updatedWorkflowDefinition, this.NewDefinitionMemberCount, "updatedWorkflowDefinition"); ValidateDefinitionMatchesMap(originalWorkflowDefinition, this.OldDefinitionMemberCount, "originalWorkflowDefinition"); } return new DynamicUpdateMapQuery(this, updatedWorkflowDefinition, originalWorkflowDefinition); } internal static bool CanUseImplementationMapAsRoot(Activity workflowDefinition) { Fx.Assert(workflowDefinition.IsMetadataCached, "This should only be called for cached definition"); // We can only use the implementation map as a root map if the worklflow has no public children return workflowDefinition.Children.Count == 0 && workflowDefinition.ImportedChildren.Count == 0 && workflowDefinition.Delegates.Count == 0 && workflowDefinition.ImportedDelegates.Count == 0 && workflowDefinition.RuntimeVariables.Count == 0; } internal static DynamicUpdateMap Merge(DynamicUpdateMap first, DynamicUpdateMap second, MergeErrorContext errorContext) { if (first == null || second == null) { return first ?? second; } if (first.IsNoChanges || second.IsNoChanges) { // DynamicUpdateMap.NoChanges has zero members, so we need to special-case it here. return first.IsNoChanges ? second : first; } ThrowIfMapsIncompatible(first, second, errorContext); DynamicUpdateMap result = new DynamicUpdateMap { IsForImplementation = first.IsForImplementation, NewDefinitionMemberCount = second.NewDefinitionMemberCount, ArgumentsAreUnknown = first.ArgumentsAreUnknown && second.ArgumentsAreUnknown, oldArguments = first.ArgumentsAreUnknown ? second.oldArguments : first.oldArguments, newArguments = second.ArgumentsAreUnknown ? first.newArguments : second.newArguments }; foreach (DynamicUpdateMapEntry firstEntry in first.Entries) { DynamicUpdateMapEntry parent = null; if (firstEntry.Parent != null) { result.TryGetUpdateEntry(firstEntry.Parent.OldActivityId, out parent); } if (firstEntry.IsRemoval) { result.AddEntry(firstEntry.Clone(parent)); } else { DynamicUpdateMapEntry secondEntry = second.entries[firstEntry.NewActivityId]; result.AddEntry(DynamicUpdateMapEntry.Merge(firstEntry, secondEntry, parent, errorContext)); } } return result; } internal void AddEntry(DynamicUpdateMapEntry entry) { this.Entries.Add(entry); } // Wrap an implementation map in a dummy map. This allows use of an implementation map as the // root map in the case when the root is an x:Class with no public children. internal DynamicUpdateMap AsRootMap() { Fx.Assert(this.IsForImplementation, "This should only be called on implementation map"); if (!ActivityComparer.ListEquals(this.NewArguments, this.OldArguments)) { throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidImplementationAsWorkflowRootForRuntimeStateBecauseArgumentsChanged)); } DynamicUpdateMap result = new DynamicUpdateMap { IsImplementationAsRoot = true, NewDefinitionMemberCount = 1 }; result.AddEntry(new DynamicUpdateMapEntry(1, 1) { ImplementationUpdateMap = this, }); return result; } internal void ThrowIfInvalid(Activity updatedDefinition) { Fx.Assert(updatedDefinition.IsMetadataCached, "Caller should have ensured cached definition"); Fx.Assert(updatedDefinition.Parent == null && !this.IsForImplementation, "This should only be called on a workflow definition"); this.ThrowIfInvalid(updatedDefinition.MemberOf); } // We verify that the count of all IdSpaces is as expected. // We could choose to be looser, and only check the IdSpaces that have children active; // but realistically, if all provided implementation maps don't match, something is probably wrong. // Conversely, we could check the correctness of every environment map, but it doesn't seem worth // doing that much work. If we find a mismatch on the environment of an executing activity, we'll // throw at that point. void ThrowIfInvalid(IdSpace updatedIdSpace) { if (this.IsNoChanges) { // 0 means this is NoChanges map, since every workflow has at least one member return; } if (this.NewDefinitionMemberCount != updatedIdSpace.MemberCount) { throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap( SR.WrongMemberCount(updatedIdSpace.Owner, updatedIdSpace.MemberCount, this.NewDefinitionMemberCount)))); } foreach (DynamicUpdateMapEntry entry in this.Entries) { if (entry.ImplementationUpdateMap != null) { Activity implementationOwner = updatedIdSpace[entry.NewActivityId]; if (implementationOwner == null) { string expectedId = entry.NewActivityId.ToString(CultureInfo.InvariantCulture); if (updatedIdSpace.Owner != null) { expectedId = updatedIdSpace.Owner.Id + "." + expectedId; } throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap( SR.ActivityNotFound(expectedId)))); } if (implementationOwner.ParentOf == null) { throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap( SR.ActivityHasNoImplementation(implementationOwner)))); } entry.ImplementationUpdateMap.ThrowIfInvalid(implementationOwner.ParentOf); } } } internal bool TryGetUpdateEntryByNewId(int newId, out DynamicUpdateMapEntry entry) { Fx.Assert(!this.IsNoChanges, "This method is never supposed to be called on the NoChanges map."); entry = null; for (int i = 0; i < this.Entries.Count; i++) { DynamicUpdateMapEntry currentEntry = this.Entries[i]; if (currentEntry.NewActivityId == newId) { entry = currentEntry; return true; } } return false; } internal bool TryGetUpdateEntry(int oldId, out DynamicUpdateMapEntry entry) { if (this.entries != null && this.entries.Count > 0) { if (this.entries.Contains(oldId)) { entry = this.entries[oldId]; return true; } } entry = null; return false; } // rootIdSpace is optional. if it's null, result.NewActivity will be null internal UpdatedActivity GetUpdatedActivity(QualifiedId oldQualifiedId, IdSpace rootIdSpace) { UpdatedActivity result = new UpdatedActivity(); int[] oldIdSegments = oldQualifiedId.AsIDArray(); int[] newIdSegments = null; IdSpace currentIdSpace = rootIdSpace; DynamicUpdateMap currentMap = this; Fx.Assert(!this.IsForImplementation, "This method is never supposed to be called on an implementation map."); for (int i = 0; i < oldIdSegments.Length; i++) { if (currentMap == null || currentMap.Entries.Count == 0) { break; } DynamicUpdateMapEntry entry; if (!currentMap.TryGetUpdateEntry(oldIdSegments[i], out entry)) { // UpdateMap should contain entries for all old activities in the IdSpace int[] subIdSegments = new int[i + 1]; Array.Copy(oldIdSegments, subIdSegments, subIdSegments.Length); throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap( SR.MapEntryNotFound(new QualifiedId(subIdSegments))))); } if (entry.IsIdChange) { if (newIdSegments == null) { newIdSegments = new int[oldIdSegments.Length]; Array.Copy(oldIdSegments, newIdSegments, oldIdSegments.Length); } newIdSegments[i] = entry.NewActivityId; } Activity currentActivity = null; if (currentIdSpace != null && !entry.IsRemoval) { currentActivity = currentIdSpace[entry.NewActivityId]; if (currentActivity == null) { // New Activity pointed to by UpdateMap should exist string activityId = currentIdSpace.Owner.Id + "." + entry.NewActivityId.ToString(CultureInfo.InvariantCulture); throw FxTrace.Exception.AsError(new InstanceUpdateException(SR.InvalidUpdateMap( SR.ActivityNotFound(activityId)))); } currentIdSpace = currentActivity.ParentOf; } if (i == oldIdSegments.Length - 1) { result.Map = currentMap; result.MapEntry = entry; result.NewActivity = currentActivity; } else if (entry.IsRuntimeUpdateBlocked || entry.IsUpdateBlockedByUpdateAuthor) { currentMap = null; } else { currentMap = entry.ImplementationUpdateMap; } } result.IdChanged = newIdSegments != null; result.NewId = result.IdChanged ? new QualifiedId(newIdSegments) : oldQualifiedId; return result; } static void ThrowIfMapsIncompatible(DynamicUpdateMap first, DynamicUpdateMap second, MergeErrorContext errorContext) { Fx.Assert(!first.IsNoChanges && !second.IsNoChanges, "This method is never supposed to be called on the NoChanges map."); if (first.IsForImplementation != second.IsForImplementation) { errorContext.Throw(SR.InvalidMergeMapForImplementation(first.IsForImplementation, second.IsForImplementation)); } if (first.NewDefinitionMemberCount != second.OldDefinitionMemberCount) { errorContext.Throw(SR.InvalidMergeMapMemberCount(first.NewDefinitionMemberCount, second.OldDefinitionMemberCount)); } if (!first.ArgumentsAreUnknown && !second.ArgumentsAreUnknown && first.IsForImplementation && !ActivityComparer.ListEquals(first.newArguments, second.oldArguments)) { if (first.NewArguments.Count != second.OldArguments.Count) { errorContext.Throw(SR.InvalidMergeMapArgumentCount(first.NewArguments.Count, second.OldArguments.Count)); } else { errorContext.Throw(SR.InvalidMergeMapArgumentsChanged); } } } static void ValidateDefinitionMatchesMap(Activity activity, int memberCount, string parameterName) { if (activity == null) { throw FxTrace.Exception.ArgumentNull(parameterName); } if (activity.MemberOf == null) { throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsUncached); } if (activity.Parent != null) { throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsNotRoot); } if (activity.MemberOf.MemberCount != memberCount) { throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap( SR.WrongMemberCount(activity.MemberOf.Owner, activity.MemberOf.MemberCount, memberCount))); } } static void ValidateDefinitionMatchesImplementationMap(Activity activity, int memberCount, string parameterName) { if (activity == null) { throw FxTrace.Exception.ArgumentNull(parameterName); } if (activity.MemberOf == null) { throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsUncached); } if (activity.Parent != null) { throw FxTrace.Exception.Argument(parameterName, SR.ActivityIsNotRoot); } if (activity.ParentOf == null) { throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap( SR.ActivityHasNoImplementation(activity))); } if (activity.ParentOf.MemberCount != memberCount) { throw FxTrace.Exception.Argument(parameterName, SR.InvalidUpdateMap( SR.WrongMemberCount(activity.ParentOf.Owner, activity.ParentOf.MemberCount, memberCount))); } if (!CanUseImplementationMapAsRoot(activity)) { throw FxTrace.Exception.Argument(parameterName, SR.InvalidImplementationAsWorkflowRoot); } } internal struct UpdatedActivity { // This can be true even if Map & MapEntry are null, if a parent ID changed. // It can also be false even when Map & MapEntry are non-null, if the update didn't produce an ID shift. public bool IdChanged; public QualifiedId NewId; // Null if the activity's IDSpace wasn't updated. public DynamicUpdateMap Map; public DynamicUpdateMapEntry MapEntry; // Null when we're dealing with just a serialized instance with no definition. public Activity NewActivity; } internal class MergeErrorContext { private Stack<int> currentIdSpace; public int MapIndex { get; set; } public void PushIdSpace(int id) { if (this.currentIdSpace == null) { this.currentIdSpace = new Stack<int>(); } this.currentIdSpace.Push(id); } public void PopIdSpace() { this.currentIdSpace.Pop(); } public void Throw(string detail) { QualifiedId id = null; if (this.currentIdSpace != null && this.currentIdSpace.Count > 0) { int[] idSegments = new int[this.currentIdSpace.Count]; for (int i = idSegments.Length - 1; i >= 0; i--) { idSegments[i] = this.currentIdSpace.Pop(); } id = new QualifiedId(idSegments); } string errorMessage; if (id == null) { errorMessage = SR.InvalidRootMergeMap(this.MapIndex, detail); } else { errorMessage = SR.InvalidMergeMap(this.MapIndex, id, detail); } throw FxTrace.Exception.Argument("maps", errorMessage); } } [CollectionDataContract] internal class EntryCollection : KeyedCollection<int, DynamicUpdateMapEntry> { public EntryCollection() { } protected override int GetKeyForItem(DynamicUpdateMapEntry item) { return item.OldActivityId; } } } }
mit
seogi1004/cdnjs
ajax/libs/waud.js/0.9.15/waud.js
51945
(function (console, $hx_exports, $global) { "use strict"; function $extend(from, fields) { function Inherit() {} Inherit.prototype = from; var proto = new Inherit(); for (var name in fields) proto[name] = fields[name]; if( fields.toString !== Object.prototype.toString ) proto.toString = fields.toString; return proto; } var AudioManager = function() { this.bufferList = new haxe_ds_StringMap(); this.types = new haxe_ds_StringMap(); this.types.set("mp3","audio/mpeg"); this.types.set("ogg","audio/ogg"); this.types.set("wav","audio/wav"); this.types.set("aac","audio/aac"); this.types.set("m4a","audio/x-m4a"); }; AudioManager.__name__ = true; AudioManager.prototype = { checkWebAudioAPISupport: function() { return Reflect.field(window,"AudioContext") != null || Reflect.field(window,"webkitAudioContext") != null; } ,unlockAudio: function() { if(this.audioContext != null) { var bfr = this.audioContext.createBuffer(1,1,Waud.preferredSampleRate); var src = this.audioContext.createBufferSource(); src.buffer = bfr; src.connect(this.audioContext.destination); if(Reflect.field(src,"start") != null) src.start(0); else src.noteOn(0); if(src.onended != null) src.onended = $bind(this,this._unlockCallback); else haxe_Timer.delay($bind(this,this._unlockCallback),1); } else { var audio; var _this = window.document; audio = _this.createElement("audio"); var source; var _this1 = window.document; source = _this1.createElement("source"); source.src = "data:audio/wave;base64,UklGRjIAAABXQVZFZm10IBIAAAABAAEAQB8AAEAfAAABAAgAAABmYWN0BAAAAAAAAABkYXRhAAAAAA=="; audio.appendChild(source); window.document.appendChild(audio); audio.play(); if(Waud.__touchUnlockCallback != null) Waud.__touchUnlockCallback(); Waud.dom.ontouchend = null; } } ,_unlockCallback: function() { if(Waud.__touchUnlockCallback != null) Waud.__touchUnlockCallback(); Waud.dom.ontouchend = null; } ,createAudioContext: function() { if(this.audioContext == null) try { if(Reflect.field(window,"AudioContext") != null) this.audioContext = new AudioContext(); else if(Reflect.field(window,"webkitAudioContext") != null) this.audioContext = new webkitAudioContext(); this.masterGainNode = this.createGain(); } catch( e ) { if (e instanceof js__$Boot_HaxeError) e = e.val; this.audioContext = null; } return this.audioContext; } ,createGain: function() { if(($_=this.audioContext,$bind($_,$_.createGain)) != null) return this.audioContext.createGain(); else return Reflect.callMethod(this.audioContext,Reflect.field(this.audioContext,"createGainNode"),[]); } ,destroy: function() { if(this.audioContext != null && (this.audioContext.close != null && this.audioContext.close != "")) this.audioContext.close(); this.audioContext = null; this.bufferList = null; this.types = null; } ,__class__: AudioManager }; var BaseSound = function(sndUrl,options) { this._b64 = new EReg("(^data:audio).*(;base64,)","i"); if(sndUrl == null || sndUrl == "") { console.log("invalid sound url"); return; } if(Waud.audioManager == null) { console.log("initialise Waud using Waud.init() before loading sounds"); return; } this.isSpriteSound = false; this.url = sndUrl; this._isLoaded = false; this._isPlaying = false; this._muted = false; this._duration = 0; this._options = WaudUtils.setDefaultOptions(options); this.rate = this._options.playbackRate; }; BaseSound.__name__ = true; BaseSound.prototype = { isReady: function() { return this._isLoaded; } ,__class__: BaseSound }; var EReg = function(r,opt) { opt = opt.split("u").join(""); this.r = new RegExp(r,opt); }; EReg.__name__ = true; EReg.prototype = { match: function(s) { if(this.r.global) this.r.lastIndex = 0; this.r.m = this.r.exec(s); this.r.s = s; return this.r.m != null; } ,matched: function(n) { if(this.r.m != null && n >= 0 && n < this.r.m.length) return this.r.m[n]; else throw new js__$Boot_HaxeError("EReg::matched"); } ,__class__: EReg }; var IWaudSound = function() { }; IWaudSound.__name__ = true; IWaudSound.prototype = { __class__: IWaudSound }; var HTML5Sound = function(url,options,src) { BaseSound.call(this,url,options); this._snd = Waud.dom.createElement("audio"); if(src == null) this._addSource(url); else this._snd.appendChild(src); if(this._options.preload) this.load(); if(this._b64.match(url)) url = ""; }; HTML5Sound.__name__ = true; HTML5Sound.__interfaces__ = [IWaudSound]; HTML5Sound.__super__ = BaseSound; HTML5Sound.prototype = $extend(BaseSound.prototype,{ load: function(callback) { var _g = this; if(!this._isLoaded) { this._snd.autoplay = this._options.autoplay; this._snd.loop = this._options.loop; this._snd.volume = this._options.volume; this._snd.playbackRate = this.rate; if(callback != null) this._options.onload = callback; if(this._options.preload) this._snd.preload = "auto"; else this._snd.preload = "metadata"; if(this._options.onload != null) { this._isLoaded = true; this._snd.onloadeddata = function() { _g._options.onload(_g); }; } this._snd.onplaying = function() { _g._isLoaded = true; _g._isPlaying = true; }; this._snd.onended = function() { _g._isPlaying = false; if(_g._options.onend != null) _g._options.onend(_g); }; if(this._options.onerror != null) this._snd.onerror = function() { _g._options.onerror(_g); }; this._snd.load(); } return this; } ,getDuration: function() { if(!this._isLoaded) return 0; this._duration = this._snd.duration; return this._duration; } ,_addSource: function(url) { this.source = Waud.dom.createElement("source"); this.source.src = url; if((function($this) { var $r; var key = $this._getExt(url); $r = Waud.audioManager.types.get(key); return $r; }(this)) != null) { var key1 = this._getExt(url); this.source.type = Waud.audioManager.types.get(key1); } this._snd.appendChild(this.source); return this.source; } ,_getExt: function(filename) { return filename.split(".").pop(); } ,setVolume: function(val,spriteName) { if(val >= 0 && val <= 1) this._options.volume = val; if(!this._isLoaded) return; this._snd.volume = this._options.volume; } ,getVolume: function(spriteName) { return this._options.volume; } ,mute: function(val,spriteName) { if(!this._isLoaded) return; this._snd.muted = val; if(WaudUtils.isiOS()) { if(val && this.isPlaying()) { this._muted = true; this._snd.pause(); } else if(this._muted) { this._muted = false; this._snd.play(); } } } ,toggleMute: function(spriteName) { this.mute(!this._muted); } ,play: function(sprite,soundProps) { var _g = this; this.spriteName = sprite; if(!this._isLoaded || this._snd == null) { console.log("sound not loaded"); return -1; } if(this._isPlaying) { if(this._options.autostop) this.stop(this.spriteName); else { var nsnd; nsnd = js_Boot.__cast(this._snd.cloneNode(true) , HTMLAudioElement); if(nsnd.readyState == 4) { nsnd.currentTime = 0; nsnd.play(); } else nsnd.oncanplay = function() { nsnd.currentTime = 0; nsnd.play(); }; nsnd.onended = function() { Waud.dom.removeChild(nsnd); }; } } if(this._muted) return -1; if(this.isSpriteSound && soundProps != null) { if(this._pauseTime == null) this._snd.currentTime = soundProps.start; else this._snd.currentTime = this._pauseTime; if(this._tmr != null) this._tmr.stop(); this._tmr = haxe_Timer.delay(function() { if(soundProps.loop != null && soundProps.loop) _g.play(_g.spriteName,soundProps); else _g.stop(_g.spriteName); },Math.ceil(soundProps.duration * 1000)); } if(this._snd.readyState == 4) this._snd.play(); else this._snd.oncanplay = function() { _g._snd.play(); }; this._pauseTime = null; return 0; } ,togglePlay: function(spriteName) { if(this._isPlaying) this.pause(); else this.play(); } ,isPlaying: function(spriteName) { return this._isPlaying; } ,loop: function(val) { if(!this._isLoaded || this._snd == null) return; this._snd.loop = val; } ,autoStop: function(val) { this._options.autostop = val; } ,stop: function(spriteName) { if(!this._isLoaded || this._snd == null) return; this._snd.currentTime = 0; this._snd.pause(); this._isPlaying = false; if(this._tmr != null) this._tmr.stop(); } ,pause: function(spriteName) { if(!this._isLoaded || this._snd == null) return; this._snd.pause(); this._pauseTime = this._snd.currentTime; this._isPlaying = false; if(this._tmr != null) this._tmr.stop(); } ,playbackRate: function(val,spriteName) { if(val == null) return this.rate; this._snd.playbackRate = val; return this.rate = val; } ,setTime: function(time) { if(!this._isLoaded || this._snd == null || time > this._snd.duration) return; this._snd.currentTime = time; } ,getTime: function() { if(this._snd == null || !this._isLoaded || !this._isPlaying) return 0; return this._snd.currentTime; } ,onEnd: function(callback,spriteName) { this._options.onend = callback; return this; } ,onLoad: function(callback) { this._options.onload = callback; return this; } ,onError: function(callback) { this._options.onerror = callback; return this; } ,destroy: function() { if(this._snd != null) { this._snd.pause(); this._snd.removeChild(this.source); this.source = null; this._snd = null; } this._isPlaying = false; } ,__class__: HTML5Sound }); var HxOverrides = function() { }; HxOverrides.__name__ = true; HxOverrides.cca = function(s,index) { var x = s.charCodeAt(index); if(x != x) return undefined; return x; }; HxOverrides.indexOf = function(a,obj,i) { var len = a.length; if(i < 0) { i += len; if(i < 0) i = 0; } while(i < len) { if(a[i] === obj) return i; i++; } return -1; }; Math.__name__ = true; var Reflect = function() { }; Reflect.__name__ = true; Reflect.field = function(o,field) { try { return o[field]; } catch( e ) { if (e instanceof js__$Boot_HaxeError) e = e.val; return null; } }; Reflect.callMethod = function(o,func,args) { return func.apply(o,args); }; Reflect.fields = function(o) { var a = []; if(o != null) { var hasOwnProperty = Object.prototype.hasOwnProperty; for( var f in o ) { if(f != "__id__" && f != "hx__closures__" && hasOwnProperty.call(o,f)) a.push(f); } } return a; }; var Std = function() { }; Std.__name__ = true; Std.string = function(s) { return js_Boot.__string_rec(s,""); }; Std.parseInt = function(x) { var v = parseInt(x,10); if(v == 0 && (HxOverrides.cca(x,1) == 120 || HxOverrides.cca(x,1) == 88)) v = parseInt(x); if(isNaN(v)) return null; return v; }; var Waud = $hx_exports.Waud = function() { }; Waud.__name__ = true; Waud.init = function(d) { if(Waud.__audioElement == null) { if(d == null) d = window.document; Waud.dom = d; Waud.__audioElement = Waud.dom.createElement("audio"); if(Waud.audioManager == null) Waud.audioManager = new AudioManager(); Waud.isWebAudioSupported = Waud.audioManager.checkWebAudioAPISupport(); Waud.isHTML5AudioSupported = Reflect.field(window,"Audio") != null; if(Waud.isWebAudioSupported) Waud.audioContext = Waud.audioManager.createAudioContext(); Waud.sounds = new haxe_ds_StringMap(); Waud._volume = 1; Waud._sayHello(); } }; Waud._sayHello = function() { var support; if(Waud.isWebAudioSupported) support = "Web Audio"; else support = "HTML5 Audio"; if(window.navigator.userAgent.toLowerCase().indexOf("chrome") > 1) { var e = ["\n %c %c %c WAUD%c.%cJS%c v" + Waud.version + " - " + support + " %c %c http://www.waudjs.com %c %c %c 📢 \n\n","background: #32BEA6; padding:5px 0;","background: #32BEA6; padding:5px 0;","color: #E70000; background: #29162B; padding:5px 0;","color: #F3B607; background: #29162B; padding:5px 0;","color: #32BEA6; background: #29162B; padding:5px 0;","color: #999999; background: #29162B; padding:5px 0;","background: #32BEA6; padding:5px 0;","background: #B8FCEF; padding:5px 0;","background: #32BEA6; padding:5px 0;","color: #E70000; background: #32BEA6; padding:5px 0;","color: #FF2424; background: #FFFFFF; padding:5px 0;"]; window.console.log.apply(window.console,e); } else window.console.log("WAUD.JS v" + Waud.version + " - " + support + " - http://www.waudjs.com"); }; Waud.autoMute = function() { Waud._focusManager = new WaudFocusManager(); Waud._focusManager.focus = function() { Waud.mute(false); }; Waud._focusManager.blur = function() { Waud.mute(true); }; }; Waud.enableTouchUnlock = function(callback) { Waud.__touchUnlockCallback = callback; Waud.dom.ontouchend = ($_=Waud.audioManager,$bind($_,$_.unlockAudio)); }; Waud.setVolume = function(val) { if((((val | 0) === val) || typeof(val) == "number") && val >= 0 && val <= 1) { Waud._volume = val; if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.setVolume(val); } } } else window.console.warn("Volume should be a number between 0 and 1. Received: " + val); }; Waud.getVolume = function() { return Waud._volume; }; Waud.mute = function(val) { if(val == null) val = true; Waud.isMuted = val; if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.mute(val); } } }; Waud.playbackRate = function(val) { if(val == null) return Waud._playbackRate; else if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.playbackRate(val); } } return Waud._playbackRate = val; }; Waud.stop = function() { if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.stop(); } } }; Waud.pause = function() { if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.pause(); } } }; Waud.playSequence = function(snds,onComplete,onSoundComplete,interval) { if(interval == null) interval = -1; if(snds == null || snds.length == 0) return; var _g1 = 0; var _g = snds.length; while(_g1 < _g) { var i = _g1++; if(Waud.sounds.get(snds[i]) == null) { console.log("Unable to find \"" + snds[i] + "\" in the sequence, skipping it"); snds.splice(i,1); } } var playSound = null; playSound = function() { if(snds.length > 0) { var sndStr = snds.shift(); var sndToPlay = Waud.sounds.get(sndStr); sndToPlay.play(); if(interval > 0) haxe_Timer.delay(function() { if(onSoundComplete != null) onSoundComplete(sndStr); playSound(); },interval); else sndToPlay.onEnd(function(snd) { if(onSoundComplete != null) onSoundComplete(sndStr); playSound(); }); } else if(onComplete != null) onComplete(); }; playSound(); }; Waud.getFormatSupportString = function() { var support = "OGG: " + Waud.__audioElement.canPlayType("audio/ogg; codecs=\"vorbis\""); support += ", WAV: " + Waud.__audioElement.canPlayType("audio/wav; codecs=\"1\""); support += ", MP3: " + Waud.__audioElement.canPlayType("audio/mpeg;"); support += ", AAC: " + Waud.__audioElement.canPlayType("audio/aac;"); support += ", M4A: " + Waud.__audioElement.canPlayType("audio/x-m4a;"); return support; }; Waud.isSupported = function() { if(Waud.isWebAudioSupported == null || Waud.isHTML5AudioSupported == null) { Waud.isWebAudioSupported = Waud.audioManager.checkWebAudioAPISupport(); Waud.isHTML5AudioSupported = Reflect.field(window,"Audio") != null; } return Waud.isWebAudioSupported || Waud.isHTML5AudioSupported; }; Waud.isOGGSupported = function() { var canPlay = Waud.__audioElement.canPlayType("audio/ogg; codecs=\"vorbis\""); return Waud.isHTML5AudioSupported && canPlay != null && (canPlay == "probably" || canPlay == "maybe"); }; Waud.isWAVSupported = function() { var canPlay = Waud.__audioElement.canPlayType("audio/wav; codecs=\"1\""); return Waud.isHTML5AudioSupported && canPlay != null && (canPlay == "probably" || canPlay == "maybe"); }; Waud.isMP3Supported = function() { var canPlay = Waud.__audioElement.canPlayType("audio/mpeg;"); return Waud.isHTML5AudioSupported && canPlay != null && (canPlay == "probably" || canPlay == "maybe"); }; Waud.isAACSupported = function() { var canPlay = Waud.__audioElement.canPlayType("audio/aac;"); return Waud.isHTML5AudioSupported && canPlay != null && (canPlay == "probably" || canPlay == "maybe"); }; Waud.isM4ASupported = function() { var canPlay = Waud.__audioElement.canPlayType("audio/x-m4a;"); return Waud.isHTML5AudioSupported && canPlay != null && (canPlay == "probably" || canPlay == "maybe"); }; Waud.getSampleRate = function() { if(Waud.audioContext != null) return Waud.audioContext.sampleRate; else return 0; }; Waud.destroy = function() { if(Waud.sounds != null) { var $it0 = Waud.sounds.iterator(); while( $it0.hasNext() ) { var sound = $it0.next(); sound.destroy(); } } Waud.sounds = null; if(Waud.audioManager != null) Waud.audioManager.destroy(); Waud.audioManager = null; Waud.audioContext = null; Waud.__audioElement = null; if(Waud._focusManager != null) { Waud._focusManager.clearEvents(); Waud._focusManager.blur = null; Waud._focusManager.focus = null; Waud._focusManager = null; } }; var WaudBase64Pack = $hx_exports.WaudBase64Pack = function(url,onLoaded,onProgress,onError,options,sequentialLoad) { if(sequentialLoad == null) sequentialLoad = false; if(Waud.audioManager == null) { console.log("initialise Waud using Waud.init() before loading sounds"); return; } this._sequentialLoad = sequentialLoad; if(url.indexOf(".json") > 0) { this.progress = 0; this._options = WaudUtils.setDefaultOptions(options); this._totalSize = 0; this._soundCount = 0; this._loadCount = 0; this._onLoaded = onLoaded; this._onProgress = onProgress; this._onError = onError; this._sounds = new haxe_ds_StringMap(); this._loadBase64Json(url); } }; WaudBase64Pack.__name__ = true; WaudBase64Pack.prototype = { _loadBase64Json: function(base64Url) { var _g = this; var m = new EReg("\"meta\":.[0-9]*,[0-9]*.","i"); var xobj = new XMLHttpRequest(); xobj.open("GET",base64Url,true); if(this._onProgress != null) xobj.onprogress = function(e) { var meta = m.match(xobj.responseText); if(meta && _g._totalSize == 0) { var metaInfo = JSON.parse("{" + m.matched(0) + "}"); _g._totalSize = metaInfo.meta[1]; } if(e.lengthComputable) _g.progress = e.loaded / e.total; else _g.progress = e.loaded / _g._totalSize; if(_g.progress > 1) _g.progress = 1; _g._onProgress(0.8 * _g.progress); }; if(this._onError != null) xobj.onerror = function(e1) { _g._onError(); }; xobj.onreadystatechange = function() { if(xobj.readyState == 4) { var _g1 = xobj.status; switch(_g1) { case 200: var res = JSON.parse(xobj.responseText); _g._soundsToLoad = new haxe_ds_StringMap(); _g._soundIds = []; var _g11 = 0; var _g2 = Reflect.fields(res); while(_g11 < _g2.length) { var n = _g2[_g11]; ++_g11; if(n == "meta") continue; if((res instanceof Array) && res.__enum__ == null) { _g._soundIds.push(Reflect.field(res,n).name); var key = Reflect.field(res,n).name; var value = "data:" + Std.string(Reflect.field(res,n).mime) + ";base64," + Std.string(Reflect.field(res,n).data); _g._soundsToLoad.set(key,value); } else { _g._soundIds.push(n); var value1 = Reflect.field(res,n); _g._soundsToLoad.set(n,value1); } } _g._soundCount = _g._soundIds.length; if(!_g._sequentialLoad) while(_g._soundIds.length > 0) _g._createSound(_g._soundIds.shift()); else _g._createSound(_g._soundIds.shift()); break; case 404: _g._onError(); break; } } }; xobj.send(null); } ,_createSound: function(id) { var _g = this; new WaudSound(this._soundsToLoad.get(id),{ onload : function(s) { _g._sounds.set(id,s); Waud.sounds.set(id,s); if(_g._options.onload != null) _g._options.onload(s); _g._checkProgress(); }, onerror : function(s1) { _g._sounds.set(id,null); if(_g._options.onerror != null) _g._options.onerror(s1); if(_g._checkProgress() && _g._onError != null) _g._onError(); }, autoplay : this._options.autoplay, autostop : this._options.autostop, loop : this._options.loop, onend : this._options.onend, playbackRate : this._options.playbackRate, preload : this._options.preload, volume : this._options.volume, webaudio : this._options.webaudio}); } ,_checkProgress: function() { this._loadCount++; if(this._onProgress != null) this._onProgress(0.8 + 0.199999999999999956 * (this._loadCount / this._soundCount)); if(this._loadCount == this._soundCount) { this._soundsToLoad = null; if(this._onLoaded != null) this._onLoaded(this._sounds); return true; } else if(this._sequentialLoad) this._createSound(this._soundIds.shift()); return false; } ,__class__: WaudBase64Pack }; var WaudFocusManager = $hx_exports.WaudFocusManager = function() { var _g = this; this._hidden = ""; this._visibilityChange = ""; this._currentState = ""; if(Reflect.field(window.document,"hidden") != null) { this._hidden = "hidden"; this._visibilityChange = "visibilitychange"; } else if(Reflect.field(window.document,"mozHidden") != null) { this._hidden = "mozHidden"; this._visibilityChange = "mozvisibilitychange"; } else if(Reflect.field(window.document,"msHidden") != null) { this._hidden = "msHidden"; this._visibilityChange = "msvisibilitychange"; } else if(Reflect.field(window.document,"webkitHidden") != null) { this._hidden = "webkitHidden"; this._visibilityChange = "webkitvisibilitychange"; } if(Reflect.field(window,"addEventListener") != null) { window.addEventListener("focus",$bind(this,this._focus)); window.addEventListener("blur",$bind(this,this._blur)); window.addEventListener("pageshow",$bind(this,this._focus)); window.addEventListener("pagehide",$bind(this,this._blur)); document.addEventListener(this._visibilityChange,$bind(this,this._handleVisibilityChange)); } else if(Reflect.field(window,"attachEvent") != null) { window.attachEvent("onfocus",$bind(this,this._focus)); window.attachEvent("onblur",$bind(this,this._blur)); window.attachEvent("pageshow",$bind(this,this._focus)); window.attachEvent("pagehide",$bind(this,this._blur)); document.attachEvent(this._visibilityChange,$bind(this,this._handleVisibilityChange)); } else window.onload = function() { window.onfocus = $bind(_g,_g._focus); window.onblur = $bind(_g,_g._blur); window.onpageshow = $bind(_g,_g._focus); window.onpagehide = $bind(_g,_g._blur); }; }; WaudFocusManager.__name__ = true; WaudFocusManager.prototype = { _handleVisibilityChange: function() { if(Reflect.field(window.document,this._hidden) != null && Reflect.field(window.document,this._hidden) && this.blur != null) this.blur(); else if(this.focus != null) this.focus(); } ,_focus: function() { if(this._currentState != "focus" && this.focus != null) this.focus(); this._currentState = "focus"; } ,_blur: function() { if(this._currentState != "blur" && this.blur != null) this.blur(); this._currentState = "blur"; } ,clearEvents: function() { if(Reflect.field(window,"removeEventListener") != null) { window.removeEventListener("focus",$bind(this,this._focus)); window.removeEventListener("blur",$bind(this,this._blur)); window.removeEventListener("pageshow",$bind(this,this._focus)); window.removeEventListener("pagehide",$bind(this,this._blur)); window.removeEventListener(this._visibilityChange,$bind(this,this._handleVisibilityChange)); } else if(Reflect.field(window,"removeEvent") != null) { window.removeEvent("onfocus",$bind(this,this._focus)); window.removeEvent("onblur",$bind(this,this._blur)); window.removeEvent("pageshow",$bind(this,this._focus)); window.removeEvent("pagehide",$bind(this,this._blur)); window.removeEvent(this._visibilityChange,$bind(this,this._handleVisibilityChange)); } else { window.onfocus = null; window.onblur = null; window.onpageshow = null; window.onpagehide = null; } } ,__class__: WaudFocusManager }; var WaudSound = $hx_exports.WaudSound = function(url,options) { if(Waud.audioManager == null) { console.log("initialise Waud using Waud.init() before loading sounds"); return; } this.rate = 1; this._options = options; if(url.indexOf(".json") > 0) { this.isSpriteSound = true; this._spriteDuration = 0; this._spriteSounds = new haxe_ds_StringMap(); this._spriteSoundEndCallbacks = new haxe_ds_StringMap(); this._loadSpriteJson(url); } else { this.isSpriteSound = false; this._init(url); } if(new EReg("(^data:audio).*(;base64,)","i").match(url)) { var key = "snd" + new Date().getTime(); Waud.sounds.set(key,this); url = ""; } else Waud.sounds.set(url,this); }; WaudSound.__name__ = true; WaudSound.__interfaces__ = [IWaudSound]; WaudSound.prototype = { _loadSpriteJson: function(jsonUrl) { var _g = this; var xobj = new XMLHttpRequest(); xobj.open("GET",jsonUrl,true); xobj.onreadystatechange = function() { if(xobj.readyState == 4 && xobj.status == 200) { _g._spriteData = JSON.parse(xobj.responseText); var src = _g._spriteData.src; if(jsonUrl.indexOf("/") > -1) src = jsonUrl.substring(0,jsonUrl.lastIndexOf("/") + 1) + src; _g._init(src); } }; xobj.send(null); } ,_init: function(soundUrl) { var _g = this; this.url = soundUrl; if(Waud.isWebAudioSupported && Waud.useWebAudio && (this._options == null || this._options.webaudio == null || this._options.webaudio)) { if(this.isSpriteSound) this._loadSpriteSound(this.url); else this._snd = new WebAudioAPISound(this.url,this._options); } else if(Waud.isHTML5AudioSupported) { if(this._spriteData != null && this._spriteData.sprite != null) { var loadCount = 0; var onLoad; if(this._options != null && this._options.onload != null) onLoad = this._options.onload; else onLoad = null; var onLoadSpriteSound = function(snd) { loadCount++; if(loadCount == _g._spriteData.sprite.length && onLoad != null) onLoad(snd); }; var onErrorSpriteSound = function(snd1) { loadCount++; if(loadCount == _g._spriteData.sprite.length && onLoad != null) onLoad(snd1); }; if(this._options == null) this._options = { }; this._options.onload = onLoadSpriteSound; this._options.onerror = onErrorSpriteSound; var _g1 = 0; var _g11 = this._spriteData.sprite; while(_g1 < _g11.length) { var snd2 = _g11[_g1]; ++_g1; var sound = new HTML5Sound(this.url,this._options); sound.isSpriteSound = true; this._spriteSounds.set(snd2.name,sound); } } else this._snd = new HTML5Sound(this.url,this._options); } else { console.log("no audio support in this browser"); return; } } ,getDuration: function() { if(this.isSpriteSound) return this._spriteDuration; if(this._snd == null) return 0; return this._snd.getDuration(); } ,setVolume: function(val,spriteName) { if(((val | 0) === val) || typeof(val) == "number") { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).setVolume(val); return; } if(this._snd == null) return; this._snd.setVolume(val); } else window.console.warn("Volume should be a number between 0 and 1. Received: " + val); } ,getVolume: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) return this._spriteSounds.get(spriteName).getVolume(); return 0; } if(this._snd == null) return 0; return this._snd.getVolume(); } ,mute: function(val,spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).mute(val); else { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.mute(val); } } return; } if(this._snd == null) return; this._snd.mute(val); } ,toggleMute: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).toggleMute(); else { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.toggleMute(); } } return; } if(this._snd == null) return; this._snd.toggleMute(); } ,load: function(callback) { if(this._snd == null || this.isSpriteSound) return null; this._snd.load(callback); return this; } ,isReady: function() { if(this.isSpriteSound) { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); return snd.isReady(); } } return this._snd.isReady(); } ,play: function(spriteName,soundProps) { if(this.isSpriteSound) { if(spriteName != null) { var _g = 0; var _g1 = this._spriteData.sprite; while(_g < _g1.length) { var snd = _g1[_g]; ++_g; if(snd.name == spriteName) { soundProps = snd; break; } } if(soundProps == null) return null; if(this._spriteSounds.get(spriteName) != null) return this._spriteSounds.get(spriteName).play(spriteName,soundProps); } else return null; } if(this._snd == null) return null; return this._snd.play(spriteName,soundProps); } ,togglePlay: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).togglePlay(); return; } if(this._snd == null) return; this._snd.togglePlay(); } ,isPlaying: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) return this._spriteSounds.get(spriteName).isPlaying(); return false; } if(this._snd == null) return false; return this._snd.isPlaying(); } ,loop: function(val) { if(this._snd == null || this.isSpriteSound) return; this._snd.loop(val); } ,autoStop: function(val) { if(this._snd == null) return; this._snd.autoStop(val); } ,stop: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).stop(); else { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.stop(); } } } else if(this._snd != null) this._snd.stop(); } ,pause: function(spriteName) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).pause(); else { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.pause(); } } } else if(this._snd != null) this._snd.pause(); } ,playbackRate: function(val,spriteName) { if(val != null) { if(this.isSpriteSound) { if(spriteName != null && this._spriteSounds.get(spriteName) != null) this._spriteSounds.get(spriteName).playbackRate(val); else { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.playbackRate(val); } } } else if(this._snd != null) this._snd.playbackRate(val); return this.rate = val; } return this.rate; } ,setTime: function(time) { if(this._snd == null || this.isSpriteSound) return; this._snd.setTime(time); } ,getTime: function() { if(this._snd == null || this.isSpriteSound) return 0; return this._snd.getTime(); } ,onEnd: function(callback,spriteName) { if(this.isSpriteSound) { if(spriteName != null) this._spriteSoundEndCallbacks.set(spriteName,callback); return this; } else if(this._snd != null) { this._snd.onEnd(callback); return this; } return null; } ,onLoad: function(callback) { if(this._snd == null || this.isSpriteSound) return null; this._snd.onLoad(callback); return this; } ,onError: function(callback) { if(this._snd == null || this.isSpriteSound) return null; this._snd.onError(callback); return this; } ,destroy: function() { if(this.isSpriteSound) { var $it0 = this._spriteSounds.iterator(); while( $it0.hasNext() ) { var snd = $it0.next(); snd.destroy(); } } else if(this._snd != null) { this._snd.destroy(); this._snd = null; } } ,_loadSpriteSound: function(url) { var request = new XMLHttpRequest(); request.open("GET",url,true); request.responseType = "arraybuffer"; request.onload = $bind(this,this._onSpriteSoundLoaded); request.onerror = $bind(this,this._onSpriteSoundError); request.send(); } ,_onSpriteSoundLoaded: function(evt) { Waud.audioManager.audioContext.decodeAudioData(evt.target.response,$bind(this,this._decodeSuccess),$bind(this,this._onSpriteSoundError)); } ,_onSpriteSoundError: function() { if(this._options != null && this._options.onerror != null) this._options.onerror(this); } ,_decodeSuccess: function(buffer) { if(buffer == null) { this._onSpriteSoundError(); return; } Waud.audioManager.bufferList.set(this.url,buffer); this._spriteDuration = buffer.duration; if(this._options != null && this._options.onload != null) this._options.onload(this); var _g = 0; var _g1 = this._spriteData.sprite; while(_g < _g1.length) { var snd = _g1[_g]; ++_g; var sound = new WebAudioAPISound(this.url,this._options,true,buffer.duration); sound.isSpriteSound = true; this._spriteSounds.set(snd.name,sound); sound.onEnd($bind(this,this._spriteOnEnd),snd.name); } } ,_spriteOnEnd: function(snd) { if(this._spriteSoundEndCallbacks.get(snd.spriteName) != null) this._spriteSoundEndCallbacks.get(snd.spriteName)(snd); } ,__class__: WaudSound }; var WaudUtils = $hx_exports.WaudUtils = function() { }; WaudUtils.__name__ = true; WaudUtils.isAndroid = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("Android","i").match(ua); }; WaudUtils.isiOS = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("(iPad|iPhone|iPod)","i").match(ua); }; WaudUtils.isWindowsPhone = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("(IEMobile|Windows Phone)","i").match(ua); }; WaudUtils.isFirefox = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("Firefox","i").match(ua); }; WaudUtils.isOpera = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("Opera","i").match(ua) || Reflect.field(window,"opera") != null; }; WaudUtils.isChrome = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("Chrome","i").match(ua); }; WaudUtils.isSafari = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("Safari","i").match(ua); }; WaudUtils.isMobile = function(ua) { if(ua == null) ua = window.navigator.userAgent; return new EReg("(iPad|iPhone|iPod|Android|webOS|BlackBerry|Windows Phone|IEMobile)","i").match(ua); }; WaudUtils.getiOSVersion = function(ua) { if(ua == null) ua = window.navigator.userAgent; var v = new EReg("[0-9_]+?[0-9_]+?[0-9_]+","i"); var matched = []; if(v.match(ua)) { var match = v.matched(0).split("_"); var _g = []; var _g1 = 0; while(_g1 < match.length) { var i = match[_g1]; ++_g1; _g.push(Std.parseInt(i)); } matched = _g; } return matched; }; WaudUtils.setDefaultOptions = function(options) { if(options == null) options = { }; if(options.autoplay != null) options.autoplay = options.autoplay; else options.autoplay = Waud.defaults.autoplay; if(options.autostop != null) options.autostop = options.autostop; else options.autostop = Waud.defaults.autostop; if(options.webaudio != null) options.webaudio = options.webaudio; else options.webaudio = Waud.defaults.webaudio; if(options.preload != null) options.preload = options.preload; else options.preload = Waud.defaults.preload; if(options.loop != null) options.loop = options.loop; else options.loop = Waud.defaults.loop; if(options.onload != null) options.onload = options.onload; else options.onload = Waud.defaults.onload; if(options.onend != null) options.onend = options.onend; else options.onend = Waud.defaults.onend; if(options.onerror != null) options.onerror = options.onerror; else options.onerror = Waud.defaults.onerror; if(options.volume == null || options.volume < 0 || options.volume > 1) options.volume = Waud.defaults.volume; if(options.playbackRate == null || options.playbackRate <= 0 || options.playbackRate >= 4) options.playbackRate = Waud.defaults.playbackRate; return options; }; var WebAudioAPISound = function(url,options,loaded,d) { if(d == null) d = 0; if(loaded == null) loaded = false; BaseSound.call(this,url,options); this._playStartTime = 0; this._pauseTime = 0; this._srcNodes = []; this._gainNodes = []; this._currentSoundProps = null; this._isLoaded = loaded; this._duration = d; this._manager = Waud.audioManager; if(this._b64.match(url)) { this._decodeAudio(this._base64ToArrayBuffer(url)); url = ""; } else if(this._options.preload && !loaded) this.load(); }; WebAudioAPISound.__name__ = true; WebAudioAPISound.__interfaces__ = [IWaudSound]; WebAudioAPISound.__super__ = BaseSound; WebAudioAPISound.prototype = $extend(BaseSound.prototype,{ load: function(callback) { if(!this._isLoaded) { var request = new XMLHttpRequest(); request.open("GET",this.url,true); request.responseType = "arraybuffer"; request.onload = $bind(this,this._onSoundLoaded); request.onerror = $bind(this,this._error); request.send(); if(callback != null) this._options.onload = callback; } return this; } ,_base64ToArrayBuffer: function(base64) { var raw = window.atob(base64.split(",")[1]); var rawLength = raw.length; var array = new Uint8Array(new ArrayBuffer(rawLength)); var _g = 0; while(_g < rawLength) { var i = _g++; array[i] = HxOverrides.cca(raw,i); } return array.buffer; } ,_onSoundLoaded: function(evt) { this._manager.audioContext.decodeAudioData(evt.target.response,$bind(this,this._decodeSuccess),$bind(this,this._error)); } ,_decodeAudio: function(data) { this._manager.audioContext.decodeAudioData(data,$bind(this,this._decodeSuccess),$bind(this,this._error)); } ,_error: function() { if(this._options.onerror != null) this._options.onerror(this); } ,_decodeSuccess: function(buffer) { if(buffer == null) { console.log("empty buffer: " + this.url); this._error(); return; } this._manager.bufferList.set(this.url,buffer); this._isLoaded = true; this._duration = buffer.duration; if(this._options.onload != null) this._options.onload(this); if(this._options.autoplay) this.play(); } ,_makeSource: function(buffer) { var bufferSource = this._manager.audioContext.createBufferSource(); bufferSource.buffer = buffer; this._gainNode = this._manager.createGain(); bufferSource.connect(this._gainNode); bufferSource.playbackRate.value = this.rate; this._gainNode.connect(this._manager.masterGainNode); this._manager.masterGainNode.connect(this._manager.audioContext.destination); this._srcNodes.push(bufferSource); this._gainNodes.push(this._gainNode); if(this._muted) this._gainNode.gain.value = 0; else this._gainNode.gain.value = this._options.volume; return bufferSource; } ,getDuration: function() { if(!this._isLoaded) return 0; return this._duration; } ,play: function(sprite,soundProps) { var _g = this; this.spriteName = sprite; if(this._isPlaying && this._options.autostop) this.stop(this.spriteName); if(!this._isLoaded) { console.log("sound not loaded"); return -1; } var start = 0; var end = -1; if(this.isSpriteSound && soundProps != null) { this._currentSoundProps = soundProps; start = soundProps.start + this._pauseTime; end = soundProps.duration; } var buffer; if(this._manager.bufferList != null) buffer = this._manager.bufferList.get(this.url); else buffer = null; if(buffer != null) { this.source = this._makeSource(buffer); if(start >= 0 && end > -1) this._start(0,start,end); else { this._start(0,this._pauseTime,this.source.buffer.duration); this.source.loop = this._options.loop; } this._playStartTime = this._manager.audioContext.currentTime; this._isPlaying = true; this.source.onended = function() { if(_g._isPlaying) _g._pauseTime = 0; _g._isPlaying = false; if(_g.isSpriteSound && soundProps != null && soundProps.loop != null && soundProps.loop && start >= 0 && end > -1) { _g.destroy(); _g.play(_g.spriteName,soundProps); } else if(_g._options.onend != null) _g._options.onend(_g); }; } return HxOverrides.indexOf(this._srcNodes,this.source,0); } ,_start: function(when,offset,duration) { if(Reflect.field(this.source,"start") != null) this.source.start(when,offset,duration); else if(Reflect.field(this.source,"noteGrainOn") != null) Reflect.callMethod(this.source,Reflect.field(this.source,"noteGrainOn"),[when,offset,duration]); else if(Reflect.field(this.source,"noteOn") != null) Reflect.callMethod(this.source,Reflect.field(this.source,"noteOn"),[when,offset,duration]); } ,togglePlay: function(spriteName) { if(this._isPlaying) this.pause(); else this.play(); } ,isPlaying: function(spriteName) { return this._isPlaying; } ,loop: function(val) { this._options.loop = val; if(this.source != null) this.source.loop = val; } ,setVolume: function(val,spriteName) { this._options.volume = val; if(this._gainNode == null || !this._isLoaded || this._muted) return; this._gainNode.gain.value = this._options.volume; } ,getVolume: function(spriteName) { return this._options.volume; } ,mute: function(val,spriteName) { this._muted = val; if(this._gainNode == null || !this._isLoaded) return; if(val) this._gainNode.gain.value = 0; else this._gainNode.gain.value = this._options.volume; } ,toggleMute: function(spriteName) { this.mute(!this._muted); } ,autoStop: function(val) { this._options.autostop = val; } ,stop: function(spriteName) { this._pauseTime = 0; if(this.source == null || !this._isLoaded || !this._isPlaying) return; this.destroy(); } ,pause: function(spriteName) { if(this.source == null || !this._isLoaded || !this._isPlaying) return; this.destroy(); this._pauseTime += this._manager.audioContext.currentTime - this._playStartTime; console.log("pause: " + this._pauseTime); } ,playbackRate: function(val,spriteName) { if(val == null) return this.rate; var _g = 0; var _g1 = this._srcNodes; while(_g < _g1.length) { var src = _g1[_g]; ++_g; src.playbackRate.value = val; } return this.rate = val; } ,setTime: function(time) { if(!this._isLoaded || time > this._duration) return; if(this._isPlaying) { this.stop(); this._pauseTime = time; this.play(); } else this._pauseTime = time; } ,getTime: function() { if(this.source == null || !this._isLoaded || !this._isPlaying) return 0; return this._manager.audioContext.currentTime - this._playStartTime + this._pauseTime; } ,onEnd: function(callback,spriteName) { this._options.onend = callback; return this; } ,onLoad: function(callback) { this._options.onload = callback; return this; } ,onError: function(callback) { this._options.onerror = callback; return this; } ,destroy: function() { var _g = 0; var _g1 = this._srcNodes; while(_g < _g1.length) { var src = _g1[_g]; ++_g; if(Reflect.field(src,"stop") != null) src.stop(0); else if(Reflect.field(src,"noteOff") != null) Reflect.callMethod(src,Reflect.field(src,"noteOff"),[0]); src.disconnect(); src = null; } var _g2 = 0; var _g11 = this._gainNodes; while(_g2 < _g11.length) { var gain = _g11[_g2]; ++_g2; gain.disconnect(); gain = null; } this._srcNodes = []; this._gainNodes = []; this._isPlaying = false; } ,__class__: WebAudioAPISound }); var haxe_IMap = function() { }; haxe_IMap.__name__ = true; var haxe_Timer = function(time_ms) { var me = this; this.id = setInterval(function() { me.run(); },time_ms); }; haxe_Timer.__name__ = true; haxe_Timer.delay = function(f,time_ms) { var t = new haxe_Timer(time_ms); t.run = function() { t.stop(); f(); }; return t; }; haxe_Timer.prototype = { stop: function() { if(this.id == null) return; clearInterval(this.id); this.id = null; } ,run: function() { } ,__class__: haxe_Timer }; var haxe_ds__$StringMap_StringMapIterator = function(map,keys) { this.map = map; this.keys = keys; this.index = 0; this.count = keys.length; }; haxe_ds__$StringMap_StringMapIterator.__name__ = true; haxe_ds__$StringMap_StringMapIterator.prototype = { hasNext: function() { return this.index < this.count; } ,next: function() { return this.map.get(this.keys[this.index++]); } ,__class__: haxe_ds__$StringMap_StringMapIterator }; var haxe_ds_StringMap = function() { this.h = { }; }; haxe_ds_StringMap.__name__ = true; haxe_ds_StringMap.__interfaces__ = [haxe_IMap]; haxe_ds_StringMap.prototype = { set: function(key,value) { if(__map_reserved[key] != null) this.setReserved(key,value); else this.h[key] = value; } ,get: function(key) { if(__map_reserved[key] != null) return this.getReserved(key); return this.h[key]; } ,setReserved: function(key,value) { if(this.rh == null) this.rh = { }; this.rh["$" + key] = value; } ,getReserved: function(key) { if(this.rh == null) return null; else return this.rh["$" + key]; } ,arrayKeys: function() { var out = []; for( var key in this.h ) { if(this.h.hasOwnProperty(key)) out.push(key); } if(this.rh != null) { for( var key in this.rh ) { if(key.charCodeAt(0) == 36) out.push(key.substr(1)); } } return out; } ,iterator: function() { return new haxe_ds__$StringMap_StringMapIterator(this,this.arrayKeys()); } ,__class__: haxe_ds_StringMap }; var js__$Boot_HaxeError = function(val) { Error.call(this); this.val = val; this.message = String(val); if(Error.captureStackTrace) Error.captureStackTrace(this,js__$Boot_HaxeError); }; js__$Boot_HaxeError.__name__ = true; js__$Boot_HaxeError.__super__ = Error; js__$Boot_HaxeError.prototype = $extend(Error.prototype,{ __class__: js__$Boot_HaxeError }); var js_Boot = function() { }; js_Boot.__name__ = true; js_Boot.getClass = function(o) { if((o instanceof Array) && o.__enum__ == null) return Array; else { var cl = o.__class__; if(cl != null) return cl; var name = js_Boot.__nativeClassName(o); if(name != null) return js_Boot.__resolveNativeClass(name); return null; } }; js_Boot.__string_rec = function(o,s) { if(o == null) return "null"; if(s.length >= 5) return "<...>"; var t = typeof(o); if(t == "function" && (o.__name__ || o.__ename__)) t = "object"; switch(t) { case "object": if(o instanceof Array) { if(o.__enum__) { if(o.length == 2) return o[0]; var str2 = o[0] + "("; s += "\t"; var _g1 = 2; var _g = o.length; while(_g1 < _g) { var i1 = _g1++; if(i1 != 2) str2 += "," + js_Boot.__string_rec(o[i1],s); else str2 += js_Boot.__string_rec(o[i1],s); } return str2 + ")"; } var l = o.length; var i; var str1 = "["; s += "\t"; var _g2 = 0; while(_g2 < l) { var i2 = _g2++; str1 += (i2 > 0?",":"") + js_Boot.__string_rec(o[i2],s); } str1 += "]"; return str1; } var tostr; try { tostr = o.toString; } catch( e ) { if (e instanceof js__$Boot_HaxeError) e = e.val; return "???"; } if(tostr != null && tostr != Object.toString && typeof(tostr) == "function") { var s2 = o.toString(); if(s2 != "[object Object]") return s2; } var k = null; var str = "{\n"; s += "\t"; var hasp = o.hasOwnProperty != null; for( var k in o ) { if(hasp && !o.hasOwnProperty(k)) { continue; } if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") { continue; } if(str.length != 2) str += ", \n"; str += s + k + " : " + js_Boot.__string_rec(o[k],s); } s = s.substring(1); str += "\n" + s + "}"; return str; case "function": return "<function>"; case "string": return o; default: return String(o); } }; js_Boot.__interfLoop = function(cc,cl) { if(cc == null) return false; if(cc == cl) return true; var intf = cc.__interfaces__; if(intf != null) { var _g1 = 0; var _g = intf.length; while(_g1 < _g) { var i = _g1++; var i1 = intf[i]; if(i1 == cl || js_Boot.__interfLoop(i1,cl)) return true; } } return js_Boot.__interfLoop(cc.__super__,cl); }; js_Boot.__instanceof = function(o,cl) { if(cl == null) return false; switch(cl) { case Int: return (o|0) === o; case Float: return typeof(o) == "number"; case Bool: return typeof(o) == "boolean"; case String: return typeof(o) == "string"; case Array: return (o instanceof Array) && o.__enum__ == null; case Dynamic: return true; default: if(o != null) { if(typeof(cl) == "function") { if(o instanceof cl) return true; if(js_Boot.__interfLoop(js_Boot.getClass(o),cl)) return true; } else if(typeof(cl) == "object" && js_Boot.__isNativeObj(cl)) { if(o instanceof cl) return true; } } else return false; if(cl == Class && o.__name__ != null) return true; if(cl == Enum && o.__ename__ != null) return true; return o.__enum__ == cl; } }; js_Boot.__cast = function(o,t) { if(js_Boot.__instanceof(o,t)) return o; else throw new js__$Boot_HaxeError("Cannot cast " + Std.string(o) + " to " + Std.string(t)); }; js_Boot.__nativeClassName = function(o) { var name = js_Boot.__toStr.call(o).slice(8,-1); if(name == "Object" || name == "Function" || name == "Math" || name == "JSON") return null; return name; }; js_Boot.__isNativeObj = function(o) { return js_Boot.__nativeClassName(o) != null; }; js_Boot.__resolveNativeClass = function(name) { return $global[name]; }; var $_, $fid = 0; function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; } if(Array.prototype.indexOf) HxOverrides.indexOf = function(a,o,i) { return Array.prototype.indexOf.call(a,o,i); }; String.prototype.__class__ = String; String.__name__ = true; Array.__name__ = true; Date.prototype.__class__ = Date; Date.__name__ = ["Date"]; var Int = { __name__ : ["Int"]}; var Dynamic = { __name__ : ["Dynamic"]}; var Float = Number; Float.__name__ = ["Float"]; var Bool = Boolean; Bool.__ename__ = ["Bool"]; var Class = { __name__ : ["Class"]}; var Enum = { }; var __map_reserved = {} Waud.PROBABLY = "probably"; Waud.MAYBE = "maybe"; Waud.version = "0.9.15"; Waud.useWebAudio = true; Waud.defaults = { autoplay : false, autostop : true, loop : false, preload : true, webaudio : true, volume : 1, playbackRate : 1}; Waud.preferredSampleRate = 44100; Waud.isMuted = false; Waud._playbackRate = 1; WaudBase64Pack.JSON_PER = 0.8; WaudFocusManager.FOCUS_STATE = "focus"; WaudFocusManager.BLUR_STATE = "blur"; WaudFocusManager.ON_FOCUS = "onfocus"; WaudFocusManager.ON_BLUR = "onblur"; WaudFocusManager.PAGE_SHOW = "pageshow"; WaudFocusManager.PAGE_HIDE = "pagehide"; WaudFocusManager.WINDOW = "window"; WaudFocusManager.DOCUMENT = "document"; js_Boot.__toStr = {}.toString; })(typeof console != "undefined" ? console : {log:function(){}}, typeof window != "undefined" ? window : exports, typeof window != "undefined" ? window : typeof global != "undefined" ? global : typeof self != "undefined" ? self : this); //# sourceMappingURL=waud.js.map
mit