repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
giuliojiang/UniSecrets
server/http.js
1312
// ############################################################################# // HTTP PART var fs = require('fs'); var http = require('http'); var https = require('https'); var config = require(__dirname + '/config.js'); var express = require('express'); var routes = require(__dirname + '/routes.js'); var app = express(); var http_port = config.http_port; var https_port = config.https_port; app.use('/', express.static(__dirname + '/../tmp')); app.set('view engine', 'ejs'); routes(app); if (config.use_ssl) { console.log('SSL enabled. Loading certificates...'); var privateKey = fs.readFileSync(config.ssl_privkey); var certificate = fs.readFileSync(config.ssl_certificate); var credentials = { key: privateKey, cert: certificate }; var httpsServer = https.createServer(credentials, app); httpsServer.listen(https_port, function() { console.log('HTTPS server listening on port ' + https_port); }).on('error', function(err) { console.log(err); }); } else { var httpServer = http.createServer(app); httpServer.listen(http_port, function() { console.log('HTTP server listening on port ' + http_port); }).on('error', function(err) { console.log(err); }); } module.exports = { app: app };
gpl-2.0
benkuper/ofxBKUI
src/ofxBKZoomImage.cpp
5413
#include "ofxBKZoomImage.h" #include "ofxBKStyle.h" ofxBKZoomImage::ofxBKZoomImage(float _x, float _y, float _width, float _height) { init(_x, _y, _width, _height); } void ofxBKZoomImage::init(float _x, float _y, float _width, float _height) { isInzoomMode = false; zoomLevel = 2; zoomSensitivity = 0.5; zoomBckColor = ofColor(0,0,0); zoomRecConstSize = true; mouseStartAbsPos.set(0,0); zoomRectMaxSize[0] = 400;// in pixel ! zoomRectMaxSize[1] = 400; ofxBKImage::init(_x,_y,_width,_height); zoomRect.set(0,0,zoomRectMaxSize[0], zoomRectMaxSize[1]); zoomAnchor.set(0,-1); } void ofxBKZoomImage::draw() { ofxBKImage::draw(); if(isPressed && drawedImage != NULL) { if (ofGetMousePressed(0)) zoomLevel = 1; else if (ofGetMousePressed(2)) zoomLevel = 2; int wCropRect = (int)(std::min( zoomRectMaxSize[0], (int)targetImage->getWidth() ) /zoomLevel); int hCropRect = (int)(std::min( zoomRectMaxSize[1], (int)targetImage->getHeight() ) /zoomLevel); // smooth mouse position ofVec2f pointerPos = getSmoothMousePosition(); ofVec2f pointerPosInImage; ofVec2f deltaIm(wCropRect, hCropRect); ofVec2f scaleIm(targetImage->getWidth(), targetImage->getHeight()); // position relative to image coordinate (in percent) ofVec2f deltaDraw(imageRect.x, imageRect.y); ofVec2f scaleDraw(imageRect.width, imageRect.height); ofVec2f pointerRel = (pointerPos - deltaDraw)/scaleDraw; // bound the pointer position if (pointerRel.x<0) pointerRel.x = 0; if (pointerRel.x>1) pointerRel.x = 1; if (pointerRel.y<0) pointerRel.y = 0; if (pointerRel.y>1) pointerRel.y = 1; // bound the pointer location to image bound pointerPos = pointerRel * scaleDraw + deltaDraw; pointerPosInImage = pointerRel * scaleIm; // crop rect in image coordinate ofPoint pTop = pointerPosInImage - deltaIm/2; ofPoint pBot = pointerPosInImage + deltaIm/2; ofVec2f deltaTopFull = pTop - pointerPosInImage; ofVec2f deltaBotFull = pBot - pointerPosInImage; // bound the points if (pTop.x<0) pTop.x = 0; if (pTop.x>scaleIm.x) pTop.x = scaleIm.x; if (pTop.y<0) pTop.y = 0; if (pTop.y>scaleIm.y) pTop.y = scaleIm.y; if (pBot.x<0) pBot.x = 0; if (pBot.x>scaleIm.x ) pBot.x = scaleIm.x; if (pBot.y<0) pBot.y = 0; if (pBot.y>scaleIm.y ) pBot.y = scaleIm.y; // rect is define with delta to the center ofVec2f deltaTop = pTop - pointerPosInImage; ofVec2f deltaBot = pBot - pointerPosInImage; zoomRect.set(pointerPosInImage + deltaTop, pointerPosInImage + deltaBot ); // zoom rectangle limited by image border ofRectangle destRect = ofRectangle( pointerPos + deltaTop * zoomLevel, pointerPos + deltaBot * zoomLevel); // zoom rectangle full size ofRectangle destRectFull = ofRectangle( pointerPos + deltaTopFull * zoomLevel, pointerPos + deltaBotFull * zoomLevel); if (!zoomRecConstSize) destRectFull = destRect;// limit the frame to image border // erase background color ofPushStyle(); ofSetColor(zoomBckColor); ofFill(); ofDrawRectangle(destRectFull); ofPopStyle(); // draw image if (isResizedForDraw){ // memory inefficient crop for big images cropImage.cropFrom( *targetImage, zoomRect.x , zoomRect.y, zoomRect.width, zoomRect.height ); cropImage.draw(destRect.x,destRect.y,destRect.width,destRect.height); } else { // memory efficient drawSubsection for small images targetImage->drawSubsection(destRect.x,destRect.y,destRect.width,destRect.height, zoomRect.x,zoomRect.y,zoomRect.width,zoomRect.height); } //and surrounding frame ofPushStyle(); ofSetColor(ofxBKStyle::normalColor); ofNoFill(); ofSetLineWidth(4); ofDrawRectangle(destRectFull); ofPopStyle(); isInzoomMode = true;; }else { isInzoomMode = false; } } void ofxBKZoomImage::processImageForDrawing() { ofxBKImage::processImageForDrawing(); //originalImage.cropFrom(*image,0,0,image->width,image->height); } void ofxBKZoomImage::mousePressed(ofMouseEventArgs &e) { bringToFront(); } /** @brief getSmoothMousePosition * * @todo: document this function */ ofVec2f ofxBKZoomImage::getSmoothMousePosition() { ofVec2f pointerPos = getMousePosition(); if (!isInzoomMode){ mouseStartAbsPos = pointerPos; lastPos.clear(); //std::cout << "zoom Mode:"<< mouseStartAbsPos << std::endl; } ofVec2f deltaMouse = pointerPos - mouseStartAbsPos; pointerPos = mouseStartAbsPos + deltaMouse * zoomSensitivity; lastPos.push_back(pointerPos); if (lastPos.size()>5) lastPos.erase(lastPos.begin()); pointerPos.set(0); for(unsigned i=0;i<lastPos.size();i++){ pointerPos += lastPos[i]; } pointerPos /= lastPos.size(); return pointerPos; } void ofxBKZoomImage::printInfo() { ofxBKImage::printInfo(); std::cout << " ofxBKZoomImage:" << "" << std::endl; }
gpl-2.0
SmarterApp/DigitalLibrary
docroot/sites/all/modules/custom/sbac_content_types/sbac_resource/templates/smart-search-welcome.tpl.php
499
<div class="smart-search-welcome-main-wrapper"> <div class="ssw-left"> <span class="ssw-icon"></span> </div> <div class="ssw-center"> <p class="legend">We found you resources with these characteristics:</p> <div class="ssw-search-filters"> <?php print $search_filters; ?> </div> <p class="legend">To find resources with different characteristics, click "Edit Filters".</p> </div> <div class="ssw-right"> <?php print $edit_filters_link; ?> </div> </div>
gpl-2.0
atvcaptain/enigma2
lib/python/Plugins/SystemPlugins/PositionerSetup/log.py
949
# logging for XMLTV importer # # One can simply use # import log # print>>log, "Some text" # because the log unit looks enough like a file! import sys import threading from six.moves import cStringIO as StringIO logfile = None # Need to make our operations thread-safe. mutex = None size = None def open(buffersize = 16384): global logfile, mutex, size if logfile is None: logfile = StringIO() mutex = threading.Lock() size = buffersize def write(data): global logfile, mutex mutex.acquire() try: if logfile.tell() > size: # Do a sort of 16k round robin logfile.reset() logfile.write(data) finally: mutex.release() sys.stdout.write(data) def getvalue(): global logfile, mutex mutex.acquire() try: pos = logfile.tell() head = logfile.read() logfile.reset() tail = logfile.read(pos) finally: mutex.release() return head + tail def close(): global logfile if logfile: logfile.close() logfile = None
gpl-2.0
KristofferV/mongo-cluster-tutum
src/server.js
1612
// set up ====================================================================== var express = require('express'); var app = express(); // create our app w/ express var mongoose = require('mongoose'); // mongoose for mongodb var port = process.env.PORT || 3000; // set the port var database = require('./config/database'); // load the database config var morgan = require('morgan'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); var sleep = require('sleep'); // configuration =============================================================== mongoose.connect(database.url); // connect to mongoDB database on modulus.io app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users app.use(morgan('dev')); // log every request to the console app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request // routes ====================================================================== require('./app/routes.js')(app); // listen (start app with node server.js) ====================================== app.listen(port); console.log("App listening on port " + port); console.log("Waiting for mongodb primary"); sleep.sleep(60); console.log("todo-web is up and running");
gpl-2.0
misterbox/NotePost
wp-content/themes/foundation/dayView.php
6430
<?php /* Template Name: dayView Purpose: Views information about that day and user can vote on validity of day */ ?> <?php get_header() ?> <?php session_start(); $readOnlyCheck = $_GET['readOnlyFail']; $isReadOnly = $_SESSION['isReadOnly']; if(!isset($_SESSION['username'])) { header("Location: login"); exit; } $username = $_SESSION['username']; //$day = $_GET['day']; if(isset($wp_query->query_vars["dayview"])){ $day = urldecode($wp_query->query_vars["dayview"]); }else{ } global $wpdb; $classes = $wpdb->get_results($wpdb->prepare("SELECT * FROM classList WHERE username = %s", $username)); ?> <ul class="breadcrumbs"> <li><a href="calendar">Calendar</a></li> <li class="current"><a href="#"><?php echo date("m/d/y", strtotime($day)); ?></a></li> </ul> <h1>Community Submitted Events</h1> <h4><?php echo date("F j, Y", strtotime($day)); ?></h4> <?php if ($readOnlyCheck == TRUE) { ?> <div class="alert-box alert"> <b>Sorry, you can't vote while in Read Only Mode!</b> </div> <?php } ?> <hr> <?php $day .= "%"; foreach($classes as $class) { ?> <table> <?php $titles = $wpdb->get_results($wpdb->prepare("SELECT * FROM Class WHERE classID = %d", $class->class)); foreach($titles as $title){?> <tr> <th colspan="6"><h5 class="text-center"><?php echo $title->classTitle; ?></h5></th> </tr> <tr> <th>Event</th> <th>Importance</th> <th>Time</th> <th>Creator</th> <th>Location</th> <th>Rating</th> <?php if ($_SESSION['role'] > 1) { ?> <th>Delete</th> <?php } ?> </tr> <?php $events = $wpdb->get_results($wpdb->prepare("SELECT * FROM CalEvent WHERE time LIKE %s AND class_id = %d ORDER BY rank DESC", $day, $class->class)); foreach($events as $event){ if($event->rank <= 0) continue; //hide if low rank ?> <tr> <td><?php echo $event->event_name; ?></td> <td><?php for($i=1; $i<=$event->importance; $i++) echo "<i class='step fi-star size-60'></i>";?></td> <td><?php echo date("g:ia", $event->time); ?></td> <td><?php echo $event->username; ?></td> <td><?php echo $event->location; ?></td> <td> <?php echo("<h4>" . $event->rank . "</h4>"); $voted = $wpdb->get_row($wpdb->prepare("SELECT * FROM Activity WHERE username = %s AND eventID = %d", $_SESSION['username'], (int)$event->event_id)); if($voted == FALSE){ ?> <form method="POST" action="<?php $_SERVER['PHP_SELF']?>"> <input type="hidden" name='eventNumber' value ="<?php echo $event->event_id;?>"> <input type="hidden" name='eventRank' value ="<?php echo $event->rank; ?>"> <input type="hidden" name='eventUsername' value ="<?php echo $event->username;?>"> <button type="submit" class="button tiny radius" name="upvote"><i class="step fi-arrow-up size-60"></i></button> <button type="submit" class="button tiny radius" name="downvote"><i class="step fi-arrow-down size-60"></i></button> </form> <?php } else{ echo "You have voted"; }?> </td> <?php if ($_SESSION['role'] > 1) { ?> <td> <form method="POST" action="<?php $_SERVER['PHP_SELF']?>"> <input type="hidden" name="eventdelete" value = "<?php echo $event->event_id;?>"> <input type="submit" class="button tiny radius" name="delete" value="Delete"> </form> </td> <?php } ?> </tr> <?php } ?> <?php } ?> </table> <?php } ?> <?php if(isset($_POST['upvote'])){ if ($isReadOnly != 1) { $_SESSION['voted'] = "true"; $eventNum = $_POST['eventNumber']; $eventRank = $_POST['eventRank']; $rank = $eventRank + 1; $wpdb->update( 'CalEvent', array( 'rank' => $rank ), array( 'event_id' => $eventNum ), array( '%d' ), array( '%d' ) ); //update user's rank +1 for the upvote //get users' current rank $userRank = $wpdb->get_row($wpdb->prepare("SELECT * FROM User WHERE username = %s", $_POST['eventUsername'])); $convert = (int)$userRank->rank; $convert = $convert + 1; //now update the rank plus 1 $updateRank = $wpdb->update('User', array( 'rank' => ($convert)), array( 'username' => $_POST['eventUsername'])); //insert into activity table so user can only vote once $success = $wpdb->insert('Activity', array( 'username' => $_SESSION['username'], 'eventID' => $eventNum, 'date' => date("Y-m-d"))); if($success != NULL) { header('Location: ' .$_SERVER['REQUEST_URI']); } else { echo "Failed to vote, try again later"; } } else { $readOnlyFail = TRUE; header("Location: " .$_SERVER['REQUEST_URI'] . "?readOnlyFail=" .$readOnlyFail); } } if(isset($_POST['downvote'])){ if ($isReadOnly != 1) { $_SESSION['voted'] = "true"; $eventNum = $_POST['eventNumber']; $eventRank = $_POST['eventRank']; $rank = $eventRank - 1; $wpdb->update( 'CalEvent', array( 'rank' => $rank ), array( 'event_id' => $eventNum ), array( '%d' ), array( '%d' ) ); //update user's rank -1 for the downvote $userRank = $wpdb->get_row($wpdb->prepare("SELECT * FROM User WHERE username = %s", $_POST['eventUsername'])); $convert = (int)$userRank->rank; $convert = $convert - 1; //now update the rank plus 1 $updateRank = $wpdb->update('User', array( 'rank' => ($convert)), array( 'username' => $_POST['eventUsername'])); //insert into activity table so user can only vote once $success = $wpdb->insert('Activity', array( 'username' => $_SESSION['username'], 'eventID' => $eventNum, 'date' => date("Y-m-d"))); if($success != NULL) { header('Location: ' .$_SERVER['REQUEST_URI']); } else { echo "Failed to vote, try again later"; } } else { $readOnlyFail = TRUE; header("Location: " .$_SERVER['REQUEST_URI'] . "?readOnlyFail=" .$readOnlyFail); } } if(isset($_POST['delete'])) { $delete = $wpdb->delete('CalEvent', array( 'event_id' => $_POST['eventdelete'])); if($delete == FALSE) { echo "Failed to delete"; echo $_POST['eventdelete']; } else { header('Location: '.$_SERVER['REQUEST_URI']); } } ?> <?php get_footer() ?>
gpl-2.0
Fernando-Marquardt/mcarchitect
MCArchitect/src/klaue/mcschematictool/exceptions/ClassicNotSupportedException.java
224
package klaue.mcschematictool.exceptions; /** * Exception for classic schematics * * @author klaue */ public class ClassicNotSupportedException extends Exception { private static final long serialVersionUID = 1L; }
gpl-2.0
zsjohny/jumpserver
apps/settings/models.py
2741
import json from django.db import models from django.db.utils import ProgrammingError, OperationalError from django.utils.translation import ugettext_lazy as _ from django.core.cache import cache from common.utils import signer class SettingQuerySet(models.QuerySet): def __getattr__(self, item): instances = self.filter(name=item) if len(instances) == 1: return instances[0] else: return Setting() class SettingManager(models.Manager): def get_queryset(self): return SettingQuerySet(self.model, using=self._db) class Setting(models.Model): name = models.CharField(max_length=128, unique=True, verbose_name=_("Name")) value = models.TextField(verbose_name=_("Value")) category = models.CharField(max_length=128, default="default") encrypted = models.BooleanField(default=False) enabled = models.BooleanField(verbose_name=_("Enabled"), default=True) comment = models.TextField(verbose_name=_("Comment")) objects = SettingManager() cache_key_prefix = '_SETTING_' def __str__(self): return self.name @classmethod def get(cls, item): cached = cls.get_from_cache(item) if cached is not None: return cached instances = cls.objects.filter(name=item) if len(instances) == 1: s = instances[0] s.refresh_setting() return s.cleaned_value return None @classmethod def get_from_cache(cls, item): key = cls.cache_key_prefix + item cached = cache.get(key) return cached @property def cleaned_value(self): try: value = self.value if self.encrypted: value = signer.unsign(value) if not value: return None value = json.loads(value) return value except json.JSONDecodeError: return None @cleaned_value.setter def cleaned_value(self, item): try: v = json.dumps(item) if self.encrypted: v = signer.sign(v) self.value = v except json.JSONDecodeError as e: raise ValueError("Json dump error: {}".format(str(e))) @classmethod def refresh_all_settings(cls): try: settings_list = cls.objects.all() for setting in settings_list: setting.refresh_setting() except (ProgrammingError, OperationalError): pass def refresh_setting(self): key = self.cache_key_prefix + self.name cache.set(key, self.cleaned_value, None) class Meta: db_table = "settings_setting" verbose_name = _("Setting")
gpl-2.0
xima-media/xm_tools
Classes/Domain/Repository/CategoryRepository.php
2241
<?php namespace Xima\XmTools\Domain\Repository; use TYPO3\CMS\Extbase\Persistence\QueryInterface; /*************************************************************** * * Copyright notice * * (c) 2017 OpenSource Team, XIMA MEDIA GmbH, osdev@xima.de * Inspird by http://blog.systemfehler.net/erweiterung-des-typo3-kategoriensystems/ * * All rights reserved * * This script is part of the TYPO3 project. The TYPO3 project 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. * * The GNU General Public License can be found at * http://www.gnu.org/copyleft/gpl.html. * * This script 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. * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ /** * Class CategoryRepository * @package Xima\XmTools\Domain\Repository */ class CategoryRepository extends \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository { protected $defaultOrderings = array('sorting' => QueryInterface::ORDER_ASCENDING); /** * Find child categories of a given parent * * @param int $category * @param array $excludeCategories * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException */ public function findChildrenByParent($category = 0, $excludeCategories = array()) { $constraints = array(); $query = $this->createQuery(); $query->getQuerySettings()->setRespectStoragePage(false); $constraints[] = $query->equals('parent', $category); if (count($excludeCategories) > 0) { $constraints[] = $query->logicalNot($query->in('uid', $excludeCategories)); } $query->matching($query->logicalAnd($constraints)); return $query->execute(); } }
gpl-2.0
kurvenschubser/studip-hks
app/views/admin/user/migrate.php
3123
<? # Lifter010: TODO - Quicksearches still lack a label use Studip\Button, Studip\LinkButton; ?> <h2><?= _('Benutzermigration') ?></h2> <form action="<?= $controller->url_for('admin/user/migrate') ?>" method="post"> <?= CSRFProtection::tokenTag() ?> <table class="default"> <colgroup> <col width="250px"> <col> </colgroup> <tbody> <tr> <td> <?= _('Alter Benutzer:') ?> </td> <td> <?= QuickSearch::get('old_id', new StandardSearch('user_id'))->render() ?> </td> </tr> <tr> <td> <?= _('Neuer zusammengeführter Benutzer:') ?> </td> <td> <?= QuickSearch::get('new_id', new StandardSearch('user_id'))->render() ?> </td> </tr> <tr> <td> <label for="convert_ident"> <?= _('Identitätsrelevante Daten migrieren:') ?> </label> </td> <td> <input type="checkbox" name="convert_ident" id="convert_ident" checked> <i> <?= _('(Es werden zusätzlich folgende Daten migriert: ' .'Veranstaltungen, Studiengänge, persönliche ' .'Profildaten inkl. Nutzerbild, Institute, ' .'generische Datenfelder und Buddies.)') ?> </i> </td> </tr> <tr> <td> <label for="delete_old"> <?= _('Den alten Benutzer löschen:') ?> </label> </td> <td> <input type="checkbox" name="delete_old" id="delete_old" value="1"> </td> </tr> </tbody> <tfoot> <tr> <td colspan="2" style="text-align: center;"> <?= Button::create(_('Umwandeln'), 'umwandeln', array('title' => _('Den ersten Benutzer in den zweiten Benutzer migrieren'))) ?> </td> </tr> </tfoot> </table> </form> <? //infobox include '_infobox.php'; $infobox = array( 'picture' => 'sidebar/person-sidebar.png', 'content' => array( array( 'kategorie' => _("Aktionen"), 'eintrag' => $aktionen ), array( 'kategorie' => _("Information"), 'eintrag' => array( array( "text" => _("Folgende Daten werden migriert:<br> Forumsbeiträge, Dateien, Kalender, Archiv, Evaluationen, Kategorien, Literatur, Nachrichten, Ankündigungen, Abstimmungen, Termine, Umfragen, Wiki, Statusgruppen und Adressbuch."), "icon" => "icons/16/black/info.png" ) ) ) ) );
gpl-2.0
psyshush/poker
site/js/main.js
765
require.config({ baseUrl:'js', paths: { jquery: 'lib/jquery', underscore: "lib/underscore", backbone: "lib/backbone", rivets: 'lib/rivets', handlebars: 'lib/handlebars', text: 'lib/text', socketio: 'lib/socket.io', odometer: 'lib/odometer' }, shim: { 'socketio': { exports: 'io' }, 'odometer': { exports: 'odometer' }, backbone: { 'deps': ['jquery', 'underscore'], 'exports': 'Backbone' }, underscore: { 'exports': '_' }, 'handlebars': { exports: 'Handlebars' } } }); require(['app'], function(app){ app.init(); });
gpl-2.0
christianchristensen/resin
modules/jaxstream/src/javax/xml/stream/events/EndElement.java
1216
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.xml.stream.events; import javax.xml.namespace.QName; import java.util.Iterator; public interface EndElement extends XMLEvent { public QName getName(); public Iterator getNamespaces(); }
gpl-2.0
filipesiciliano/al2s
wp-content/themes/al2s/includes/modules/module.blog/templates/mini-carousel/template.php
346
<?php $layout = 'mini'; $template_path = $templates_dir_path . "{$layout}/template.php"; $pagination = false; if ( file_exists($template_path) ) include( $template_path ); else return cloudfw_error_message( sprintf(__( 'Blog template %s cannot found.','cloudfw'), $layout) ); $content_out = cloudfw_make_layout( 'carousel', $content_out );
gpl-2.0
isandlaTech/cohorte-utilities
org.cohorte.utilities/test/test/psem2m/utilities/CTestBannerUtils.java
7701
package test.psem2m.utilities; import java.awt.Font; import org.cohorte.utilities.CXBannerUtils; import org.cohorte.utilities.CXMethodUtils; import org.cohorte.utilities.asciiart.CXArtSetting; import org.cohorte.utilities.asciiart.CXAsciiArt; import org.cohorte.utilities.junit.CAbstractJunitTest; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.psem2m.utilities.CXLoremIpsum; import org.psem2m.utilities.CXThreadUtils; /** * @author ogattaz * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CTestBannerUtils extends CAbstractJunitTest { private static final String[] DIMAUTH1 = new String[] { "DIM Auth", "@", "-", "courier", "BOLD,ITALIC", "18", "#", ".", "200", "10" }; private static final String[] DIMAUTH2 = new String[] { "DIM Auth", "@", "-", "courier", "BOLD", "18", "#", "-", "200", "10" }; private static final String[] DIMAUTH3 = new String[] { "DIM Auth", "@", " ", "courier", "", "18", "#", " ", "200", "10" }; private static final String[] QSFAB1 = new String[] { "QS Fab", "*", " ", "SansSerif", "BOLD,ITALIC", "30", "#", ".", "200", "10" }; private static final String[] QSFAB2 = new String[] { "QS Fab", "*", " ", "SansSerif", "BOLD", "30", "#", " ", "200", "10" }; private static final String[] QSFAB3 = new String[] { "QS Fab", "*", " ", "SansSerif", "", "30", "#", " ", "200", "10" }; private static final String[] QSPLANNING1 = new String[] { "QS Planning", "@", "-", "SansSerif", "BOLD,ITALIC", "24", "#", ".", "-1", "0" }; private static final String[] QSPLANNING2 = new String[] { "QS Planning", "@", "-", "SansSerif", "BOLD", "24", "#", "-", "-1", "0" }; private static final String[] QSPLANNING3 = new String[] { "QS Planning", "@", "-", "SansSerif", "", "24", "#", "-", "-1", "0" }; private static final String[][] TESTS_CONFIGS = new String[][] { QSFAB1, QSFAB2, QSFAB3, QSPLANNING1, QSPLANNING2, QSPLANNING3, DIMAUTH1, DIMAUTH2, DIMAUTH3 }; private static final String[] WORDS = CXLoremIpsum.LOREM_IPSUM.split("\\s"); /** * */ @AfterClass public static void destroy() { // log the destroy banner containing the report logBannerDestroy(); } /** * */ @BeforeClass public static void initialize() { // initialise the map of the test method of the current junit test class // de initializeTestsRegistry(); // log the initialization banner logBannerInitialization(); } /** * ATTENTION: a junit test must have only one public constructor */ public CTestBannerUtils() { super(); } /** * @param aConfiguration * @return */ private String buildBanner(final String[] aConfiguration) { String wText = aConfiguration[0]; char wBlackChar = aConfiguration[1].charAt(0); char wWhiteChar = aConfiguration[2].charAt(0); String wFontFamily = aConfiguration[3]; // Font.BOLD; //1 // Font.ITALIC; //2 int wFontStyle = ((aConfiguration[4].contains("BOLD")) ? 1 : 0) + ((aConfiguration[4].contains("ITALIC")) ? 2 : 0); int wFontSize = Integer.parseInt(aConfiguration[5]); CXArtSetting wArtSetting = new CXArtSetting(new Font(wFontFamily, wFontStyle, wFontSize), wWhiteChar, wBlackChar); CXAsciiArt wCXAsciiArt = new CXAsciiArt(wArtSetting); String wAsciiArtContent = wCXAsciiArt.drawString(wText); // getLogger().logInfo(this, "buildBanner", "wAsciiArtContent:\n%s", // wAsciiArtContent); // getLogger().logInfo(this, "buildBanner", "lenMaxOfLines=[%d]", // CXBannerUtils.lenMaxOfLines(wAsciiArtContent)); char wBorderChar = aConfiguration[6].charAt(0); char wWhiteChar2 = aConfiguration[7].charAt(0); int wWidth = Integer.parseInt(aConfiguration[8]); int wTextOffset = Integer.parseInt(aConfiguration[9]); int wModifiers = CXBannerUtils.WITH_BLANK_LINES; String wBanner = CXBannerUtils.build(wBorderChar, wWhiteChar2, wWidth, wTextOffset, wModifiers, wAsciiArtContent); return wBanner; } /** * @return a random int between 10 and 200 */ private int randomNbWord(final int aMin, final int aMax) { return aMin + new Double(Math.random() * (aMax - aMin)).intValue(); } /** * @return */ private String randomWord() { int wRandomIdx = new Double(Math.random() * WORDS.length).intValue(); return WORDS[wRandomIdx]; } /** * @param aLenMaxOfLine * @return */ private String randomWords(final int aLenMaxOfLine) { final StringBuilder wWords = new StringBuilder(); int wNbMax = randomNbWord(10, 80); String wWord; int wWordIdx = 0; StringBuilder wLine = new StringBuilder(); for (int i = 0; i < wNbMax; i++) { if (wWordIdx == CXLoremIpsum.LOREM_IPSUM_WORDS.length) { wWordIdx = 0; } wWord = CXLoremIpsum.LOREM_IPSUM_WORDS[wWordIdx]; if (wLine.length() + wWord.length() > aLenMaxOfLine) { wWords.append('\n').append(wLine); wLine = new StringBuilder(); } wLine.append(wWord); if (i < wNbMax - 1) { wLine.append(' '); } wWordIdx++; } if (wLine.length() > 0) { wWords.append('\n').append(wLine); } return wWords.toString(); } /** * @throws Exception */ @Test public void test10genBanner() throws Exception { String wMethodName = CXMethodUtils.getMethodName(0); String wAction = "Generate different banner "; try { logBegin(this, wMethodName, "%s Begin...", wAction); for (String[] wTestConfig : TESTS_CONFIGS) { getLogger().logInfo(this, wMethodName, "BANNER\n%s", buildBanner(wTestConfig)); } logEndOK(this, wMethodName, "%s End OK.", wAction); } catch (Throwable e) { logEndKO(this, wMethodName, e); throw e; } } /** * @throws Exception */ @Test public void test20genBanner() throws Exception { String wMethodName = CXMethodUtils.getMethodName(0); String wAction = "Generate banner using different fonts "; try { logBegin(this, wMethodName, "%s Begin...", wAction); String[] wTestConfig = new String[] { "???", "@", "-", "???", "", "20", "#", ".", "-1", "0" }; int wMax = CXAsciiArt.FONTS.length; int wIdx = 0; for (String wFont : CXAsciiArt.FONTS) { wIdx++; wTestConfig[0] = String.format("%d/%d:abcdef %s", wIdx, wMax, randomWord()); wTestConfig[3] = wFont; String wBuiltBanner = buildBanner(wTestConfig); getLogger() .logInfo(this, wMethodName, "BANNER [%d/%d] font=[%s]:\n%s", wIdx, wMax, wFont, wBuiltBanner); CXThreadUtils.sleep(100); } logEndOK(this, wMethodName, "%s End OK.", wAction); } catch (Throwable e) { logEndKO(this, wMethodName, e); throw e; } } /** * @throws Exception */ @Test public void test30genBanner() throws Exception { String wMethodName = CXMethodUtils.getMethodName(0); String wAction = "Generate banner using different fonts "; try { logBegin(this, wMethodName, "%s Begin...", wAction); String wlabel = randomWord() + ' ' + randomWord(); CXArtSetting wSetting = new CXArtSetting(new Font(CXAsciiArt.FONT_MONOSPACED, Font.PLAIN, 20), '.', '@'); String wArtContent = new CXAsciiArt(wSetting).drawString(wlabel); int wLenMaxOfLines = CXBannerUtils.lenMaxOfLines(wArtContent); StringBuilder wText = new StringBuilder(wArtContent); wText.append('\n'); wText.append(randomWords(wLenMaxOfLines)); wText.append('\n'); wText.append(randomWords(wLenMaxOfLines)); String wBanner = CXBannerUtils.build('#', '.', -1, 0, CXBannerUtils.WITH_BLANK_LINES, wText.toString()); getLogger().logInfo(this, wMethodName, "BANNER: \n%s", wBanner); logEndOK(this, wMethodName, "%s End OK.", wAction); } catch (Throwable e) { logEndKO(this, wMethodName, e); throw e; } } }
gpl-2.0
cassiomcouto/site
lib/customlayouts.php
1007
<?php // This file handles everything to do with choosing a custom layout file when adding/editing // products, categories, etc from the control panel /** * Get a list of all custom layout files (they are prefixed with an underscore) and return them as <option> tags * * @param string The default layout file * @param string The layout file to select (defaults to first parameter if none) * @return string The list of layout files. */ function GetCustomLayoutFilesAsOptions($defaultLayoutFile, $selectedLayoutFile="") { $options = sprintf("<option value='%s'>%s</option>", $defaultLayoutFile, $defaultLayoutFile); $tplPath = dirname(__FILE__) . "/../templates/" . GetConfig("template"); $files = scandir($tplPath); foreach($files as $file) { if(substr($file, 0, 1) != "_") { continue; } $sel = ''; if($selectedLayoutFile == $file) { $sel = 'selected="selected"'; } $options .= sprintf("<option %s value='%s'>%s</option>\n", $sel, $file, $file); } return $options; }
gpl-2.0
abramhindle/marsyas-fork
src/marsyas/RealvecSink.cpp
4135
/* ** Copyright (C) 1998-2010 George Tzanetakis <gtzan@cs.uvic.ca> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "common_source.h" #include "RealvecSink.h" using namespace std; using namespace Marsyas; RealvecSink::RealvecSink(mrs_string name):MarSystem("RealvecSink",name) { //type_ = "RealvecSink"; //name_ = name; oriName_ = "MARSYAS_EMPTY"; count_= 0; write_ = 0 ; addControls(); } RealvecSink::RealvecSink(const RealvecSink& a):MarSystem(a) { count_ = 0; write_ = 0 ; oriName_ = "MARSYAS_EMPTY"; ctrl_data_ = getctrl("mrs_realvec/data"); } RealvecSink::~RealvecSink() { } MarSystem* RealvecSink::clone() const { return new RealvecSink(*this); } void RealvecSink::addControls() { addctrl("mrs_bool/done", false); setctrlState("mrs_bool/done", true); addctrl("mrs_realvec/data", realvec(), ctrl_data_); setctrlState("mrs_real/israte", true); addctrl("mrs_string/fileName", "MARSYAS_EMPTY"); setctrlState("mrs_string/fileName", true); } void RealvecSink::myUpdate(MarControlPtr sender) { (void) sender; //suppress warning of unused parameter(s) MRSDIAG("RealvecSink.cpp - RealvecSink:myUpdate"); setctrl("mrs_natural/onObservations", getctrl("mrs_natural/inObservations")->to<mrs_natural>()); setctrl("mrs_natural/onSamples", getctrl("mrs_natural/inSamples")->to<mrs_natural>()); setctrl("mrs_real/osrate", getctrl("mrs_real/israte")->to<mrs_real>()); ctrl_onObsNames_->setValue(ctrl_inObsNames_->to<mrs_string>(), NOUPDATE); if( getctrl("mrs_bool/done")->isTrue()){ if(write_) { // closing output file outputFile_.close(); // copy to tmp mrs_string tmp = oriName_.c_str(); tmp+="tmp"; ofstream out; out.open(tmp.c_str(), ios::out); ifstream in; in.open(oriName_.c_str(), ios::in); out << in.rdbuf(); in.close(); out.close(); //reopen out.open(oriName_.c_str(), ios::out); // print header out << "# MARSYAS mrs_realvec" << endl; out << "# Size = " << inObservations_*count_ << endl << endl; out << endl; out << "# type: matrix" << endl; out << "# rows: " << count_ << endl; out << "# columns: " << inObservations_ << endl; // fill core in.open(tmp.c_str(), ios::in); out << in.rdbuf(); in.close(); // remove tmp file #ifdef MARSYAS_WIN32 _unlink(tmp.c_str()); #else unlink(tmp.c_str()); #endif // write bottom out << endl; out << "# Size = " << inObservations_*count_ << endl; out << "# MARSYAS mrs_realvec" << endl; out.close(); } else { MarControlAccessor acc(ctrl_data_, NOUPDATE); realvec& data = acc.to<mrs_realvec>(); data.stretch(0); } count_=0; setctrl("mrs_bool/done", false); } if(getctrl("mrs_string/fileName")->to<mrs_string>().compare(oriName_)) { if(write_) outputFile_.close(); oriName_ = getctrl("mrs_string/fileName")->to<mrs_string>(); outputFile_.open(oriName_.c_str(), ios::out); write_ = 1; } } void RealvecSink::myProcess(realvec& in, realvec& out) { mrs_natural o,t; out=in; if(write_) { for (t=0; t < inSamples_; t++) { for (o=0 ; o<inObservations_ ; o++) outputFile_ << in(o, t) << " " ; outputFile_ << endl; } } else { MarControlAccessor acc(ctrl_data_); realvec& data = acc.to<mrs_realvec>(); data.stretch(inObservations_, count_+inSamples_); for (o=0; o < inObservations_; o++) for (t=0; t < inSamples_; t++) data(o, count_+t) = in(o, t); //out.dump(); } count_+=inSamples_; }
gpl-2.0
HenryYan2012/discourse
app/assets/javascripts/discourse/dialects/category_hashtag_dialect.js
734
/** Supports Discourse's category hashtags (#category-slug) for automatically generating a link to the category. **/ Discourse.Dialect.inlineRegexp({ start: '#', matcher: /^#([A-Za-z0-9][A-Za-z0-9\-]{0,40}[A-Za-z0-9])/, spaceOrTagBoundary: true, emitter: function(matches) { var slug = matches[1], hashtag = matches[0], attributeClass = 'hashtag', categoryHashtagLookup = this.dialect.options.categoryHashtagLookup, result = categoryHashtagLookup && categoryHashtagLookup(slug); if (result && result[0] === "category") { return ['a', { class: attributeClass, href: result[1] }, hashtag]; } else { return ['span', { class: attributeClass }, hashtag]; } } });
gpl-2.0
cgwalters/anaconda
pyanaconda/ui/gui/spokes/software.py
18741
# Software selection spoke classes # # Copyright (C) 2011-2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # # Red Hat Author(s): Chris Lumens <clumens@redhat.com> # from gi.repository import Gtk, Pango from pyanaconda.flags import flags from pyanaconda.i18n import _, C_, CN_ from pyanaconda.packaging import PackagePayload, payloadMgr from pyanaconda.threads import threadMgr, AnacondaThread from pyanaconda import constants, iutil from pyanaconda.ui.communication import hubQ from pyanaconda.ui.gui.spokes import NormalSpoke from pyanaconda.ui.gui.spokes.lib.detailederror import DetailedErrorDialog from pyanaconda.ui.gui.utils import blockedHandler, gtk_action_wait, escape_markup from pyanaconda.ui.categories.software import SoftwareCategory import logging log = logging.getLogger("anaconda") import sys __all__ = ["SoftwareSelectionSpoke"] class SoftwareSelectionSpoke(NormalSpoke): builderObjects = ["addonStore", "environmentStore", "softwareWindow"] mainWidgetName = "softwareWindow" uiFile = "spokes/software.glade" helpFile = "SoftwareSpoke.xml" category = SoftwareCategory icon = "package-x-generic-symbolic" title = CN_("GUI|Spoke", "_SOFTWARE SELECTION") # Add-on selection states # no user interaction with this add-on _ADDON_DEFAULT = 0 # user selected _ADDON_SELECTED = 1 # user de-selected _ADDON_DESELECTED = 2 def __init__(self, *args, **kwargs): NormalSpoke.__init__(self, *args, **kwargs) self._errorMsgs = None self._tx_id = None self._selectFlag = False self.selectedGroups = [] self.excludedGroups = [] self.environment = None self._environmentListBox = self.builder.get_object("environmentListBox") self._addonListBox = self.builder.get_object("addonListBox") # Used to store how the user has interacted with add-ons for the default add-on # selection logic. The dictionary keys are group IDs, and the values are selection # state constants. See refreshAddons for how the values are used. self._addonStates = {} # Used for detecting whether anything's changed in the spoke. self._origAddons = [] self._origEnvironment = None # Register event listeners to update our status on payload events payloadMgr.addListener(payloadMgr.STATE_PACKAGE_MD, self._downloading_package_md) payloadMgr.addListener(payloadMgr.STATE_GROUP_MD, self._downloading_group_md) payloadMgr.addListener(payloadMgr.STATE_FINISHED, self._payload_finished) payloadMgr.addListener(payloadMgr.STATE_ERROR, self._payload_error) # Payload event handlers def _downloading_package_md(self): hubQ.send_message(self.__class__.__name__, _("Downloading package metadata...")) def _downloading_group_md(self): hubQ.send_message(self.__class__.__name__, _("Downloading group metadata...")) def _payload_finished(self): self.environment = self.data.packages.environment def _payload_error(self): hubQ.send_message(self.__class__.__name__, payloadMgr.error) def _apply(self): env = self._get_selected_environment() if not env: return # Not a kickstart with packages, setup the environment and groups if not (flags.automatedInstall and self.data.packages.seen): addons = self._get_selected_addons() for group in addons: if group not in self.selectedGroups: self.selectedGroups.append(group) self._selectFlag = False self.payload.data.packages.groupList = [] self.payload.selectEnvironment(env) self.environment = env for group in self.selectedGroups: self.payload.selectGroup(group) # And then save these values so we can check next time. self._origAddons = addons self._origEnvironment = self.environment hubQ.send_not_ready(self.__class__.__name__) hubQ.send_not_ready("SourceSpoke") threadMgr.add(AnacondaThread(name=constants.THREAD_CHECK_SOFTWARE, target=self.checkSoftwareSelection)) def apply(self): self._apply() self.data.packages.seen = True def checkSoftwareSelection(self): from pyanaconda.packaging import DependencyError hubQ.send_message(self.__class__.__name__, _("Checking software dependencies...")) try: self.payload.checkSoftwareSelection() except DependencyError as e: self._errorMsgs = "\n".join(sorted(e.message)) hubQ.send_message(self.__class__.__name__, _("Error checking software dependencies")) self._tx_id = None else: self._errorMsgs = None self._tx_id = self.payload.txID finally: hubQ.send_ready(self.__class__.__name__, False) hubQ.send_ready("SourceSpoke", False) @property def completed(self): processingDone = bool(not threadMgr.get(constants.THREAD_CHECK_SOFTWARE) and not threadMgr.get(constants.THREAD_PAYLOAD) and not self._errorMsgs and self.txid_valid) # we should always check processingDone before checking the other variables, # as they might be inconsistent until processing is finished if flags.automatedInstall: return processingDone and self.data.packages.seen else: return processingDone and self._get_selected_environment() is not None @property def changed(self): env = self._get_selected_environment() if not env: return True addons = self._get_selected_addons() # Don't redo dep solving if nothing's changed. if env == self._origEnvironment and set(addons) == set(self._origAddons) and \ self.txid_valid: return False return True @property def mandatory(self): return True @property def ready(self): # By default, the software selection spoke is not ready. We have to # wait until the installation source spoke is completed. This could be # because the user filled something out, or because we're done fetching # repo metadata from the mirror list, or we detected a DVD/CD. return bool(not threadMgr.get(constants.THREAD_SOFTWARE_WATCHER) and not threadMgr.get(constants.THREAD_PAYLOAD) and not threadMgr.get(constants.THREAD_CHECK_SOFTWARE) and self.payload.baseRepo is not None) @property def showable(self): return isinstance(self.payload, PackagePayload) @property def status(self): if self._errorMsgs: return _("Error checking software selection") if not self.ready: return _("Installation source not set up") if not self.txid_valid: return _("Source changed - please verify") env = self._get_selected_environment() if not env: # Kickstart installs with %packages will have a row selected, unless # they did an install without a desktop environment. This should # catch that one case. if flags.automatedInstall and self.data.packages.seen: return _("Custom software selected") return _("Nothing selected") return self.payload.environmentDescription(env)[0] def initialize(self): NormalSpoke.initialize(self) threadMgr.add(AnacondaThread(name=constants.THREAD_SOFTWARE_WATCHER, target=self._initialize)) def _initialize(self): threadMgr.wait(constants.THREAD_PAYLOAD) if not flags.automatedInstall or not self.data.packages.seen: # having done all the slow downloading, we need to do the first refresh # of the UI here so there's an environment selected by default. This # happens inside the main thread by necessity. We can't do anything # that takes any real amount of time, or it'll block the UI from # updating. if not self._first_refresh(): return hubQ.send_ready(self.__class__.__name__, False) # If packages were provided by an input kickstart file (or some other means), # we should do dependency solving here. self._apply() def _parseEnvironments(self): # Set all of the add-on selection states to the default self._addonStates = {} for grp in self.payload.groups: self._addonStates[grp] = self._ADDON_DEFAULT @gtk_action_wait def _first_refresh(self): self.refresh() return True def _add_row(self, listbox, name, desc, button, clicked): row = Gtk.ListBoxRow() box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6) button.set_valign(Gtk.Align.START) button.connect("toggled", clicked, row) box.add(button) label = Gtk.Label(label="<b>%s</b>\n%s" % (escape_markup(name), escape_markup(desc)), use_markup=True, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, hexpand=True, xalign=0, yalign=0.5) box.add(label) row.add(box) listbox.insert(row, -1) def refresh(self): NormalSpoke.refresh(self) threadMgr.wait(constants.THREAD_PAYLOAD) if self.environment not in self.payload.environments: self.environment = None # If no environment is selected, use the default from the instclass. # If nothing is set in the instclass, the first environment will be # selected below. if not self.environment and self.payload.instclass: self.environment = self.payload.instclass.defaultPackageEnvironment firstEnvironment = True firstRadio = None self._clear_listbox(self._environmentListBox) for environment in self.payload.environments: (name, desc) = self.payload.environmentDescription(environment) radio = Gtk.RadioButton(group=firstRadio) # automatically select an environment if this is an interactive install active = environment == self.environment or \ not flags.automatedInstall and not self.environment and firstEnvironment radio.set_active(active) if active: self.environment = environment self._add_row(self._environmentListBox, name, desc, radio, self.on_radio_button_toggled) firstRadio = firstRadio or radio firstEnvironment = False self.refreshAddons() self._environmentListBox.show_all() self._addonListBox.show_all() def _addAddon(self, grp): (name, desc) = self.payload.groupDescription(grp) if grp in self._addonStates: # If the add-on was previously selected by the user, select it if self._addonStates[grp] == self._ADDON_SELECTED: selected = True # If the add-on was previously de-selected by the user, de-select it elif self._addonStates[grp] == self._ADDON_DESELECTED: selected = False # Otherwise, use the default state else: selected = self.payload.environmentOptionIsDefault(self.environment, grp) else: selected = self.payload.environmentOptionIsDefault(self.environment, grp) check = Gtk.CheckButton() check.set_active(selected) self._add_row(self._addonListBox, name, desc, check, self.on_checkbox_toggled) def refreshAddons(self): if self.environment and (self.environment in self.payload.environmentAddons): self._clear_listbox(self._addonListBox) # We have two lists: One of addons specific to this environment, # and one of all the others. The environment-specific ones will be displayed # first and then a separator, and then the generic ones. This is to make it # a little more obvious that the thing on the left side of the screen and the # thing on the right side of the screen are related. # # If a particular add-on was previously selected or de-selected by the user, that # state will be used. Otherwise, the add-on will be selected if it is a default # for this environment. addSep = len(self.payload.environmentAddons[self.environment][0]) > 0 and \ len(self.payload.environmentAddons[self.environment][1]) > 0 for grp in self.payload.environmentAddons[self.environment][0]: self._addAddon(grp) # This marks a separator in the view - only add it if there's both environment # specific and generic addons. if addSep: self._addonListBox.insert(Gtk.Separator(), -1) for grp in self.payload.environmentAddons[self.environment][1]: self._addAddon(grp) self._selectFlag = True if self._errorMsgs: self.set_warning(_("Error checking software dependencies. Click for details.")) else: self.clear_info() def _allAddons(self): return self.payload.environmentAddons[self.environment][0] + \ [""] + \ self.payload.environmentAddons[self.environment][1] def _get_selected_addons(self): retval = [] addons = self._allAddons() for (ndx, row) in enumerate(self._addonListBox.get_children()): box = row.get_children()[0] if isinstance(box, Gtk.Separator): continue button = box.get_children()[0] if button.get_active(): retval.append(addons[ndx]) return retval def _get_selected_environment(self): # Returns the currently selected environment (self.environment # is set in both initilize() and apply(), so we don't need to # care about the state of the internal data model at all) return self.environment def _clear_listbox(self, listbox): for child in listbox.get_children(): listbox.remove(child) del(child) @property def txid_valid(self): return self._tx_id == self.payload.txID # Signal handlers def on_checkbox_toggled(self, button, row): row.activate() def on_radio_button_toggled(self, radio, row): # If the radio button toggled to inactive, don't reactivate the row if not radio.get_active(): return row.activate() def on_environment_activated(self, listbox, row): if not self._selectFlag: return box = row.get_children()[0] button = box.get_children()[0] with blockedHandler(button, self.on_radio_button_toggled): button.set_active(True) # Remove all the groups that were selected by the previously # selected environment. if self.environment: for groupid in self.payload.environmentGroups(self.environment): if groupid in self.selectedGroups: self.selectedGroups.remove(groupid) # Then mark the clicked environment as selected and update the screen. self.environment = self.payload.environments[row.get_index()] self.refreshAddons() self._addonListBox.show_all() def on_addon_activated(self, listbox, row): box = row.get_children()[0] if isinstance(box, Gtk.Separator): return button = box.get_children()[0] addons = self._allAddons() group = addons[row.get_index()] wasActive = group in self.selectedGroups with blockedHandler(button, self.on_checkbox_toggled): button.set_active(not wasActive) if wasActive: self.selectedGroups.remove(group) self._addonStates[group] = self._ADDON_DESELECTED else: self.selectedGroups.append(group) if group in self.excludedGroups: self.excludedGroups.remove(group) self._addonStates[group] = self._ADDON_SELECTED def on_info_bar_clicked(self, *args): if not self._errorMsgs: return label = _("The software marked for installation has the following errors. " "This is likely caused by an error with your installation source. " "You can quit the installer, change your software source, or change " "your software selections.") dialog = DetailedErrorDialog(self.data, buttons=[C_("GUI|Software Selection|Error Dialog", "_Quit"), C_("GUI|Software Selection|Error Dialog", "_Modify Software Source"), C_("GUI|Software Selection|Error Dialog", "Modify _Selections")], label=label) with self.main_window.enlightbox(dialog.window): dialog.refresh(self._errorMsgs) rc = dialog.run() dialog.window.destroy() if rc == 0: # Quit. iutil.ipmi_report(constants.IPMI_ABORTED) sys.exit(0) elif rc == 1: # Send the user to the installation source spoke. self.skipTo = "SourceSpoke" self.window.emit("button-clicked") elif rc == 2: # Close the dialog so the user can change selections. pass else: pass
gpl-2.0
amrav/debsoc-mediawiki
skins/strapping/strapping.php
1884
<?php /** * My Skin skin * * @file * @ingroup Skins * @author Garrett LeSage */ if( !defined( 'MEDIAWIKI' ) ) die( "This is an extension to the MediaWiki package and cannot be run standalone." ); $wgExtensionCredits['skin'][] = array( 'path' => __FILE__, 'name' => 'Strapping', 'url' => "https://github.com/OSAS/strapping-mediawiki", 'author' => 'Garrett LeSage', 'descriptionmsg' => 'strapping-desc', ); $wgValidSkinNames['strapping'] = 'Strapping'; $wgAutoloadClasses['SkinStrapping'] = dirname(__FILE__).'/Strapping.skin.php'; $wgExtensionMessagesFiles['SkinStrapping'] = dirname(__FILE__).'/Strapping.i18n.php'; $wgResourceModules['skins.strapping'] = array( 'styles' => array( 'strapping/bootstrap/css/bootstrap.css' => array( 'media' => 'screen' ), 'strapping/bootstrap/awesome/css/font-awesome.css' => array( 'media' => 'screen' ), 'strapping/screen.css' => array( 'media' => 'screen' ), 'strapping/theme.css' => array( 'media' => 'screen' ), ), 'scripts' => array( 'strapping/bootstrap/js/bootstrap.js', 'strapping/strapping.js', ), 'remoteBasePath' => &$GLOBALS['wgStylePath'], 'localBasePath' => &$GLOBALS['wgStyleDirectory'], ); if (file_exists('strapping/fonts.css')) { $wgResourceModules['skins.strapping']['styles'][] = 'strapping/fonts.css'; } # Default options to customize skin $wgStrappingSkinLogoLocation = 'bodycontent'; $wgStrappingSkinLoginLocation = 'footer'; $wgStrappingSkinAnonNavbar = false; $wgStrappingSkinUseStandardLayout = false; $wgStrappingSkinDisplaySidebarNavigation = false; # Show print/export in navbar by default #$wgStrappingSkinSidebarItemsInNavbar = array( 'coll-print_export' ); $wgSearchPlacement['nav'] = true; $wgSearchPlacement['header'] = false; $wgSearchPlacement['footer'] = false;
gpl-2.0
andig/vzero
src/plugins/Plugin.cpp
5133
#include <Arduino.h> #include <MD5Builder.h> #include <FS.h> #include "Plugin.h" #ifdef ESP32 #include <SPIFFS.h> #endif #define MAX_PLUGINS 5 /* * Static */ int8_t Plugin::instances = 0; Plugin* Plugin::plugins[MAX_PLUGINS] = {}; HTTPClient Plugin::http; void Plugin::each(CallbackFunction callback) { for (int8_t i=0; i<Plugin::instances; i++) { callback(Plugin::plugins[i]); } } /* * Virtual */ Plugin::Plugin(int8_t maxDevices = 0, int8_t actualDevices = 0) : _devs(actualDevices), _status(PLUGIN_IDLE), _timestamp(0), _duration(0) { if (Plugin::instances > MAX_PLUGINS) { DEBUG_MSG("plugin", "too many plugins - panic"); PANIC(); } Plugin::plugins[Plugin::instances++] = this; Plugin::http.setReuse(true); // allow reuse (if server supports it) // buffer size _size = maxDevices * sizeof(DeviceStruct); if (maxDevices > 0) { // DEBUG_MSG("plugin", "alloc %d -> %d\n", maxDevices, _size); _devices = (DeviceStruct*)malloc(_size); if (_devices == NULL) PANIC(); } } Plugin::~Plugin() { } String Plugin::getName() { return "abstract"; } int8_t Plugin::getSensors() { return _devs; } int8_t Plugin::getSensorByAddr(const char* addr_c) { return -1; } bool Plugin::getAddr(char* addr_c, int8_t sensor) { return false; } bool Plugin::getUuid(char* uuid_c, int8_t sensor) { if (sensor >= _devs) return false; strcpy(uuid_c, _devices[sensor].uuid); return true; } bool Plugin::setUuid(const char* uuid_c, int8_t sensor) { if (sensor >= _devs) return false; if (strlen(_devices[sensor].uuid) + strlen(uuid_c) != UUID_LENGTH) // erase before update return false; strcpy(_devices[sensor].uuid, uuid_c); return saveConfig(); } String Plugin::getHash(int8_t sensor) { char addr_c[32]; if (getAddr(&addr_c[0], sensor)) { MD5Builder md5 = ::getHashBuilder(); md5.add(getName()); md5.add(addr_c); md5.calculate(); return md5.toString(); } return ""; } float Plugin::getValue(int8_t sensor) { return NAN; } void Plugin::getPluginJson(JsonObject* json) { JsonArray& sensorlist = json->createNestedArray("sensors"); for (int8_t i=0; i<getSensors(); i++) { JsonObject& data = sensorlist.createNestedObject(); getSensorJson(&data, i); } } void Plugin::getSensorJson(JsonObject* json, int8_t sensor) { char buf[UUID_LENGTH+1]; if (getAddr(buf, sensor)) (*json)[F("addr")] = String(buf); if (getUuid(buf, sensor)) (*json)[F("uuid")] = String(buf); float val = getValue(sensor); if (isnan(val)) (*json)[F("value")] = JSON_NULL; else (*json)[F("value")] = val; (*json)[F("hash")] = getHash(sensor); } bool Plugin::loadConfig() { File configFile = SPIFFS.open("/" + getName() + ".config", "r"); if (configFile.size() == _size) { DEBUG_MSG(getName().c_str(), "loading config\n", _size); configFile.read((uint8_t*)_devices, _size); } else if (configFile.size() == 0) DEBUG_MSG(getName().c_str(), "config not found\n", _size); else DEBUG_MSG(getName().c_str(), "config size mismatch\n", _size); for (int8_t sensor = 0; sensor<getSensors(); sensor++) if (strlen(_devices[sensor].uuid) != UUID_LENGTH) _devices[sensor].uuid[0] = '\0'; configFile.close(); return true; } bool Plugin::saveConfig() { DEBUG_MSG(getName().c_str(), "saving config %d\n", _size); File configFile = SPIFFS.open("/" + getName() + ".config", "w"); if (!configFile) { DEBUG_MSG(getName().c_str(), "failed to open config file for writing\n"); return false; } configFile.write((uint8_t*)_devices, _size); configFile.close(); return true; } void Plugin::loop() { // DEBUG_MSG(getName().c_str(), "loop %d\n", _status); } void Plugin::upload() { if (g_middleware == "") return; char uuid_c[UUID_LENGTH+1]; char val_c[16]; for (int8_t i=0; i<getSensors(); i++) { // uuid configured? getUuid(uuid_c, i); if (strlen(uuid_c) > 0) { float val = getValue(i); if (isnan(val)) break; dtostrf(val, -4, 2, val_c); String uri = g_middleware + F("/data/") + String(uuid_c) + F(".json?value=") + String(val_c); http.begin(uri); int httpCode = http.POST(""); if (httpCode > 0) { http.getString(); } DEBUG_MSG(getName().c_str(), "POST %d %s\n", httpCode, uri.c_str()); http.end(); } } } bool Plugin::isUploadSafe() { // no upload in AP mode, no logging if ((WiFi.getMode() & WIFI_STA) == 0) return false; bool isSafe = WiFi.status() == WL_CONNECTED && ESP.getFreeHeap() >= HTTP_MIN_HEAP; if (!isSafe) { DEBUG_MSG(getName().c_str(), "cannot upload (wifi: %d mem:%d)\n", WiFi.status(), ESP.getFreeHeap()); } return isSafe; } bool Plugin::elapsed(uint32_t duration) { if (_timestamp == 0 || millis() - _timestamp >= duration) { _timestamp = millis(); return true; } _duration = duration; return false; } uint32_t Plugin::getMaxSleepDuration() { if (_timestamp == 0) return -1; uint32_t elapsed = millis() - _timestamp; if (elapsed < _duration) return _duration - elapsed; return 0; }
gpl-2.0
AvatarSD/gsmtempcontroller
src/Network/NetworkWorker.cpp
3438
/* * NetworkWorker.cpp * * Created on: 25 вер. 2015 р. * Author: sd */ #include "NetworkWorker.h" #include "avr/interrupt.h" #include "../LOG/debug.h" #include "../init/rtc.h" #include "../config.h" #include <stdio.h> UART * _gsm; ISR(NETWORK_RXINT) { _gsm->rx_byte_int(); } ISR(NETWORK_TXINT) { _gsm->tx_byte_int(); } NetworkWorker::NetworkWorker(DallasTemp & Sensors, HardwareData & data, ROM * buffer) : gsm(NETWORK_PORT), inetIface(gsm), sensors(Sensors), HWdata(data), _romMainBuff( buffer) { errorCount = 0; attemptCount = 0; errorPercent = 0; _gsm = &gsm; } bool NetworkWorker::sendTemp() { #ifdef LEVEL_DEBUG bool retVal = false; attemptCount++; errorPercent = ((float) (errorCount * 100)) / attemptCount; char buff[40]; sprintf(buff, "Error Percent is: %f%%", (double)errorPercent); DEBUG(buff); #endif errorCount++; INFO(F("Starting network procedure...")); if (forceConnectToServer(NETWORK_SERVER_ADDR, NETWORK_SERVER_PORT)) { unsigned long int data = gsm.getUNIXdate(); setUnixTime(data); const char * imei = gsm.getIMEI(); char pktCountStr[6]; static unsigned int pktCount = 0; sprintf(pktCountStr, "%5u", pktCount); if (!inetIface.beginWriteInet()) return false; gsm("$"); gsm(imei); gsm(","); gsm(pktCountStr); gsm(","); gsm(data); gsm(","); gsm(HWdata.getVoltage()); gsm(","); gsm(!HWdata.didHadNoVoltageSupply()); gsm(","); gsm(HWdata.didHadCaseOpen()); gsm(","); gsm(HWdata.getError()); uint16_t sensorsCount = 0, i = 0; for (; ((!_romMainBuff[i].isNull()) && (i < ROM_MAINBFF_SIZE)); i++) { double temp; gsm("\r"); gsm(_romMainBuff[i].toString()); gsm(","); for (uint8_t n = 0; n < NUM_OF_READING_ATEMPT; n++) { if (sensors.readSensor(_romMainBuff[i], temp)) { gsm(temp); sensorsCount++; break; } else if(n == NUM_OF_READING_ATEMPT - 1) gsm(-127); } } #ifdef LEVEL_INFO char charbuf[40]; sprintf(charbuf, "Num of sensors in memory: %d", i); INFO(charbuf); sprintf(charbuf, "Read sensors count: %d", sensorsCount); INFO(charbuf); #endif gsm("&"); if (inetIface.endWriteInet()) { char buf[9]; if (gsm.getString("$", "&", buf, 8)) { long int i; int flag; sscanf(buf, "%ld,%d", &i, &flag); #ifdef LEVEL_INFO sprintf(charbuf, "Package number: %ld", i); INFO(charbuf); #endif if (i == pktCount) { INFO(F("Server answered")); pktCount++; errorCount--; retVal = true; } } } } inetIface.disconnectTCP(); return retVal; } bool NetworkWorker::forceConnectToServer(const char* server, int port) { for (int i = 0; i < NUM_ATTEMP_TO_COMNNECT; i++) if (gsm.forceON()) if (gsm.isRegistered() == GSM::REG_REGISTERED) if (inetIface.attachGPRS(NETWORK_AP, "", "")) if (inetIface.connectTCP(server, port) == 1) return true; CRITICAL(F("Did not connect at 10 attempts")); gsm.forceOFF(); return false; } bool NetworkWorker::disconnectWithPowerDown() { inetIface.disconnectTCP(); inetIface.dettachGPRS(); if (gsm.forceOFF()) return true; else return false; } bool NetworkWorker::refreshTime() { for (int i = 0; i < NUM_ATTEMP_TO_COMNNECT; i++) if (gsm.forceON()) if (gsm.isRegistered() == GSM::REG_REGISTERED) if (inetIface.refreshTime(NETWORK_AP, NTP_ADDR)) return true; CRITICAL(F("Time wasn't connect at 10 attempts")); return false; }
gpl-2.0
Huluzai/DoonSketch
inkscape-0.48.5/src/ui/dialog/extensions.cpp
2989
/** @file * @brief A simple dialog with information about extensions */ /* Authors: * Jon A. Cruz * * Copyright (C) 2005 Jon A. Cruz * * Released under GNU GPL, read the file 'COPYING' for more information */ #include <gtk/gtk.h> //for GTK_RESPONSE* types #include <gtkmm/scrolledwindow.h> #include "extension/db.h" #include "extensions.h" namespace Inkscape { namespace UI { namespace Dialogs { using Inkscape::Extension::Extension; ExtensionsPanel &ExtensionsPanel::getInstance() { ExtensionsPanel &instance = *new ExtensionsPanel(); instance.rescan(); return instance; } /** * Constructor */ ExtensionsPanel::ExtensionsPanel() : _showAll(false) { Gtk::ScrolledWindow* scroller = new Gtk::ScrolledWindow(); _view.set_editable(false); scroller->add(_view); add(*scroller); rescan(); show_all_children(); } void ExtensionsPanel::set_full(bool full) { if ( full != _showAll ) { _showAll = full; rescan(); } } void ExtensionsPanel::listCB( Inkscape::Extension::Extension * in_plug, gpointer in_data ) { ExtensionsPanel * self = (ExtensionsPanel*)in_data; const char* stateStr; Extension::state_t state = in_plug->get_state(); switch ( state ) { case Extension::STATE_LOADED: { stateStr = "loaded"; } break; case Extension::STATE_UNLOADED: { stateStr = "unloaded"; } break; case Extension::STATE_DEACTIVATED: { stateStr = "deactivated"; } break; default: stateStr = "unknown"; } if ( self->_showAll || in_plug->deactivated() ) { // gchar* line = g_strdup_printf( " extension %c %c %s |%s|%s|", // (in_plug->loaded() ? 'X' : '-'), // (in_plug->deactivated() ? 'X' : '-'), // stateStr, in_plug->get_id(), // in_plug->get_name() ); gchar* line = g_strdup_printf( "%s %s\n \"%s\"", stateStr, in_plug->get_name(), in_plug->get_id() ); self->_view.get_buffer()->insert( self->_view.get_buffer()->end(), line ); self->_view.get_buffer()->insert( self->_view.get_buffer()->end(), "\n" ); //g_message( "%s", line ); } return; } void ExtensionsPanel::rescan() { _view.get_buffer()->set_text("Extensions:\n"); // g_message("/------------------"); Inkscape::Extension::db.foreach(listCB, (gpointer)this); // g_message("\\------------------"); } } //namespace Dialogs } //namespace UI } //namespace Inkscape /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :
gpl-2.0
Earslicker/kx-audio-driver
driver/irq.cpp
28536
// kX Driver // Copyright (c) Eugene Gavrilov, 2001-2014. // All rights reserved /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "kx.h" // #define CE_OPTIMIZE void kx_timer_irq_handler(kx_hw *hw); void system_timer_func(void *data,int what); #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif #if defined(_MSC_VER) #pragma code_seg() #endif dword kx_adjust_position(kx_hw *hw,dword qkbca,dword semi_buf); dword kx_adjust_position(kx_hw *hw,dword qkbca,dword semi_buf) { // position is usually 28 or 32 samples behind, due to PCI caching #if 1 if(hw->is_10k2) qkbca+=28; else qkbca+=32; if(qkbca>=semi_buf*2) qkbca-=semi_buf*2; #endif return qkbca; } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif static inline int kx_record_irq_critical_handler(kx_hw *hw,int where) { // this should be @ DIRQl // where: full_buff:1, half_buff:0 // will fill-in buffer: 1; 0 // will use hardware buffer: 1; 0 // actual hardware position: 0; 1 // will set rec_buf: 0; 1 (current hardware position) if(!hw->can_passthru) // 16-bit { size_t user_size=0; // get number of outputs word *outputs_[MAX_ASIO_INPUTS+1]; int i; int cnt=0; for(i=0;i<MAX_ASIO_INPUTS;i++) { if(hw->asio_inputs[i].kernel_addr) { outputs_[cnt]=(word *)hw->asio_inputs[i].kernel_addr; if(where) outputs_[cnt]+=(hw->asio_inputs[i].size>>2); // /2; /2 because of 'word' user_size=hw->asio_inputs[i].size; cnt++; } } outputs_[cnt]=0; word *input=(word *)hw->mtr_buffer.addr; user_size>>=2; if(where) input+=user_size*cnt; word **outputs=outputs_; while(*outputs) { register int ii; register word *out; out = *outputs; for(ii = (int)user_size; --ii >= 0; ) *(out + ii) = *(input + ii*cnt); outputs++; input++; } } else // can_passthru: { if(hw->cur_asio_in_bps!=32) // 16-bit in 32-bit { size_t user_size=0; // get number of outputs word *outputs_[MAX_ASIO_INPUTS+1]; int i; int cnt=0; for(i=0;i<MAX_ASIO_INPUTS;i++) { if(hw->asio_inputs[i].kernel_addr) { outputs_[cnt]=(word *)hw->asio_inputs[i].kernel_addr; if(where) outputs_[cnt]+=(hw->asio_inputs[i].size>>2); // /2; /2 because of 'word' user_size=hw->asio_inputs[i].size; cnt++; } } outputs_[cnt]=0; word *input=(word *)hw->mtr_buffer.addr; cnt<<=1; // multiple *2 user_size>>=2; // /2 /2 because of 'word' if(where) input+=user_size*cnt; // input is 'word', but buffer is 'dword'; cnt is already <<=1 input++; // skip first LSB word **outputs=outputs_; while(*outputs) { register int ii; register word *out; out = *outputs; for(ii = (int)user_size; --ii >= 0; ) *(out + ii) = *(input + ii*cnt); // cnt is already <<=1 outputs++; input+=2; // skip next LSB } } else // true 32-bit in 32-bit { size_t user_size=0; // get number of outputs dword *outputs_[MAX_ASIO_INPUTS+1]; int i; int cnt=0; for(i=0;i<MAX_ASIO_INPUTS;i++) { if(hw->asio_inputs[i].kernel_addr) { outputs_[cnt]=(dword *)hw->asio_inputs[i].kernel_addr; if(where) outputs_[cnt]+=(hw->asio_inputs[i].size>>3); // /4 /2 because of 'dword' user_size=hw->asio_inputs[i].size; cnt++; } } outputs_[cnt]=0; dword *input=(dword *)hw->mtr_buffer.addr; user_size>>=3; // /2 /4 if(where) input+=user_size*cnt; dword **outputs=outputs_; while(*outputs) { register int ii; register dword *out; out = *outputs; for(ii = (int)user_size; --ii >= 0; ) *(out + ii) = *(input + ii*cnt); outputs++; input++; } } } hw->asio_notification_krnl.rec_buf=1-where; // rec_buf: full_buf: 0, half_buf: 1 //debug(DLIB,"IRQ: [rec] where=%d in=%x out=%x phys=%x\n",where,input,outputs[0],kx_readptr(hw,FXIDX,0)); int old_toggle=hw->asio_notification_krnl.toggle; hw->asio_notification_krnl.toggle=kx_get_asio_position(hw,0); // do not read it again if((hw->asio_notification_krnl.asio_method&KXASIO_METHOD_SEND_EVENT) && hw->asio_notification_krnl.toggle!=-1 && (old_toggle!=hw->asio_notification_krnl.toggle)) return 1; // need additional processing return 0; // processed } #if defined(_MSC_VER) #pragma code_seg() #endif static inline int kx_record_irq_dispatch_handler(kx_hw *hw,int where) { if(hw->asio_notification_krnl.asio_method&KXASIO_METHOD_SEND_EVENT) { if(hw->asio_notification_krnl.kevent) hw->cb.notify_func(hw->asio_notification_krnl.kevent,LLA_NOTIFY_EVENT); } return 0; } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif static inline int kx_voice_irq_critical_handler(kx_hw *hw) { // should distinguish between half/full event // set pb_buf=0/1 if(!hw->hw_lock.kx_lock) { dword qkbca; dword ptr_reg=(QKBCA<<16)|(hw->asio_notification_krnl.n_voice); dword old_ptr=inpd(hw->port+PTR); outpd(hw->port+PTR,ptr_reg); qkbca=inpd(hw->port+DATA); outpd(hw->port+PTR,old_ptr); qkbca=kx_calc_position(hw,hw->asio_notification_krnl.n_voice,(qkbca&QKBCA_CURRADDR_MASK)); hw->asio_notification_krnl.cur_pos=qkbca; // for comparison ONLY qkbca=kx_adjust_position(hw,qkbca,hw->asio_notification_krnl.semi_buff); // fullbuff: 0; halfbuf: 1 if(qkbca>=hw->asio_notification_krnl.semi_buff) hw->asio_notification_krnl.pb_buf=1; // current hardware position else hw->asio_notification_krnl.pb_buf=0; } else // lock is acquired; someone is accessing PTR { debug(DLIB,"note: mutual ptr access\n"); if(hw->asio_notification_krnl.pb_buf!=-1) { hw->asio_notification_krnl.pb_buf=1-hw->asio_notification_krnl.pb_buf; if(hw->asio_notification_krnl.pb_buf==1) hw->asio_notification_krnl.cur_pos=hw->asio_notification_krnl.semi_buff; else hw->asio_notification_krnl.cur_pos=0; } else hw->asio_notification_krnl.pb_buf=1; } int old_toggle=hw->asio_notification_krnl.toggle; hw->asio_notification_krnl.toggle=kx_get_asio_position(hw,0); // do not read it again if((hw->asio_notification_krnl.asio_method&KXASIO_METHOD_SEND_EVENT) && hw->asio_notification_krnl.toggle!=-1 && old_toggle!=hw->asio_notification_krnl.toggle) return 1; // need additional processing return 0; // processed } #if defined(_MSC_VER) #pragma code_seg() #endif static inline int kx_voice_irq_dispatch_handler(kx_hw *hw) { if(hw->asio_notification_krnl.asio_method&KXASIO_METHOD_SEND_EVENT) { if(hw->asio_notification_krnl.kevent) hw->cb.notify_func(hw->asio_notification_krnl.kevent,LLA_NOTIFY_EVENT); } return 0; } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif void kx_mpuin_irq_handler(kx_hw *hw,int where); void kx_mpuin_irq_handler(kx_hw *hw,int where) { byte val; unsigned long flags=0; if(hw->have_mpu==0) debug(DLIB,"!!! mpu=0, but MPU interrupt came!\n"); // MPU interrupts disabled in adapter's KX_SYNC_IPR_IRQ handler while(kx_mpu_read_data(hw,&val,where)!=-1) { // debug(DNONE,"[%02d] ",val); kx_lock_acquire(hw,&hw->mpu_lock[where], &flags); struct list *item; for_each_list_entry(item, &hw->mpu_buffers[where]) { kx_mpu_buffer *b; b = list_item(item, kx_mpu_buffer, list); if(!b) continue; if((b->mpu_head==b->mpu_tail+1)||(b->mpu_tail+1-MAX_MPU_BUFFER == b->mpu_head)) { // buffer overflow: nothing to do :( debug(DLIB,"!!! mpu-in buffer overflow!\n"); break; } else { b->mpu_buffer[b->mpu_tail]=val; b->mpu_tail++; if(b->mpu_tail>=MAX_MPU_BUFFER) b->mpu_tail=0; } } kx_lock_release(hw,&hw->mpu_lock[where], &flags); } // debug(DLIB,"\n"); // re-enable MPUIN interrupt (INTE) sync_data s; s.hw=hw; s.what=KX_SYNC_MPUIN; s.ret=where; hw->cb.sync(hw->cb.call_with,&s); } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif void kx_mpuout_irq_handler(kx_hw *hw,int where); void kx_mpuout_irq_handler(kx_hw *hw,int where) { unsigned long flags; extern void write_mpu_data(kx_hw *hw,byte data,int where); extern byte read_mpu_state(kx_hw *hw,int where); // MPU interrupts disabled in adapter's KX_SYNC_IPR_IRQ handler kx_lock_acquire(hw,&hw->uartout_lock, &flags); int turn_on=1; while(1) { if(hw->uart_out_tail[where]==hw->uart_out_head[where]) { turn_on=0; // already done in adapter.cpp/IRQ handler; so, don't turn on break; } else { if((read_mpu_state(hw,where) & (byte)MUSTAT_ORDYN) == 0) { write_mpu_data(hw,hw->uart_out_buffer[where][hw->uart_out_head[where]],where); } else { break; } hw->uart_out_head[where]++; if(hw->uart_out_head[where]>=MAX_UART_BUFFER) hw->uart_out_head[where]=0; } } kx_lock_release(hw,&hw->uartout_lock, &flags); sync_data s; s.hw=hw; s.what=KX_SYNC_MPUOUT; // re-enable MPUOUT interrupt (INTE) s.ret=where; s.turn_on=turn_on; hw->cb.sync(hw->cb.call_with,&s); } #if defined(_MSC_VER) #pragma code_seg() // this is ALSO required, since we call send_message() here #endif void kx_spdif_irq_handler(kx_hw *hw); void kx_spdif_irq_handler(kx_hw *hw) { hw->cb.send_message(hw->cb.call_with,KX_SYSEX_SIZE,KX_SYSEX_SPDIF); debug(DLIB,"SPDIF irq [%x/%s]\n",hw->port,hw->card_name); } #if defined(_MSC_VER) #pragma code_seg() #endif void kx_dsp_irq_handler(kx_hw *hw) { if(hw->ac3_pt_state.method==KX_AC3_PASSTHRU_XTRAM) { if(hw->ac3_pt_state.callback) hw->ac3_pt_state.callback((void *)hw->ac3_pt_state.instance); } else debug(DLIB,"!! invalid DSP irq [unexpected]!\n"); } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif inline KX_API(dword,kx_get_irq_pending(kx_hw *hw)) { if(hw->standalone) return inpd(hw->port + IPR); else return hw->irq_pending; } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif inline KX_API(void,kx_clear_irq_pending(kx_hw *hw,dword pat)) { if(hw->standalone) { outpd(hw->port + IPR,pat); } else { sync_data s; s.what=KX_SYNC_CLEAR_IPR; s.hw=hw; s.irq_mask=pat; hw->cb.sync(hw->cb.call_with,&s); } } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif inline KX_API(int,kx_interrupt_critical(kx_hw *hw)) { // don't use kx_get_irq_pending() and kx_clear_irq_pending() dword ipr=inpd(hw->port + IPR); if(ipr==0) return -1; // not our IRQ // don't use kx_get_irq_pending() and kx_clear_irq_pending() outpd(hw->port + IPR,ipr); // clear IRQ hw->irq_pending|=ipr; if(hw->irq_pending&IPR_EFXBUFFULL) { if(!kx_record_irq_critical_handler(hw,1)) hw->irq_pending&=(~IPR_EFXBUFFULL); } if(hw->irq_pending&IPR_EFXBUFHALFFULL) { if(!kx_record_irq_critical_handler(hw,0)) hw->irq_pending&=(~IPR_EFXBUFHALFFULL); } if(hw->irq_pending&IRQ_VOICE) { if(!kx_voice_irq_critical_handler(hw)) hw->irq_pending&=(~IRQ_VOICE); } // we should clear the particular INTE bit to calm down the chip... // we have some time to process the DPC (depending on the FIFO size) dword mask=0; if(hw->irq_pending&IRQ_MPUIN) mask|=INTE_MIDIRXENABLE; if(hw->irq_pending&IRQ_MPUOUT) mask|=INTE_MIDITXENABLE; if(hw->irq_pending&IRQ_MPUIN2) mask|=INTE_K2_MIDIRXENABLE; if(hw->irq_pending&IRQ_MPUOUT2) mask|=INTE_K2_MIDITXENABLE; if(mask) outpd(hw->port+INTE,inpd(hw->port + INTE)&(~mask)); return 0; } // the following operations -must- always be synchronized // in Windows this is done in ISR context (DIRQ) or with KeSynchronizeExecution #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif void kx_sync(sync_data *s) { kx_hw *hw=s->hw; switch(s->what) { case KX_SYNC_IPR_IRQ: { s->ret=kx_interrupt_critical(hw); // it will clear ipr bits already processed s->irq_mask=hw->irq_pending; } break; case KX_SYNC_CLEAR_IPR: hw->irq_pending&=(~s->irq_mask); break; case KX_SYNC_IRQ_ENABLE: { dword val = inpd(hw->port + INTE) | s->irq_mask; outpd(hw->port + INTE,val); break; } case KX_SYNC_IRQ_DISABLE: { dword val = inpd(hw->port + INTE) & (~s->irq_mask); outpd(hw->port + INTE,val); break; } case KX_SYNC_MPUIN: { // re-enable the interrupt (disabled in kx_interrupt_critical handler) dword old_inte=inpd(hw->port+INTE); if(s->ret) { if(old_inte&INTE_K2_MIDIRXENABLE) debug(DERR,"!!! mpu_in2 IRQ was enabled in irq handler\n"); outpd(hw->port + INTE,old_inte | INTE_K2_MIDIRXENABLE); // kx_clear_irq_pending(hw,IRQ_MPUIN2); hw->irq_pending&=(~IRQ_MPUIN2); } else { if(old_inte&INTE_MIDIRXENABLE) debug(DERR,"!!! mpu_in IRQ was enabled in irq handler\n"); outpd(hw->port + INTE,old_inte | INTE_MIDIRXENABLE); // kx_clear_irq_pending(hw,IRQ_MPUIN); hw->irq_pending&=(~IRQ_MPUIN); } break; } case KX_SYNC_MPUOUT: { dword old_inte=inpd(hw->port+INTE); if(s->ret) { if(old_inte&INTE_K2_MIDITXENABLE) debug(DERR,"!!! mpu_out2 was enabled in the irq handler\n"); } else { if(old_inte&INTE_MIDITXENABLE) debug(DERR,"!!! mpu_out was enabled in the irq handler\n"); } if(s->turn_on) { // turn IRQs ON: if(s->ret) { outpd(hw->port + INTE,old_inte | INTE_K2_MIDITXENABLE); // kx_clear_irq_pending(hw,IRQ_MPUOUT2); hw->irq_pending&=(~IRQ_MPUOUT2); } else { outpd(hw->port + INTE,old_inte | INTE_MIDITXENABLE); // kx_clear_irq_pending(hw,IRQ_MPUOUT); hw->irq_pending&=(~IRQ_MPUOUT); } } else { if(s->ret) hw->irq_pending&=(~IRQ_MPUOUT2); // kx_clear_irq_pending(hw,IRQ_MPUOUT2); else hw->irq_pending&=(~IRQ_MPUOUT); // kx_clear_irq_pending(hw,IRQ_MPUOUT); } break; } default: debug(DERR,"!! fatal error: invalid sync opcode! [%x]\n",s->what); break; } } // returns 1 if irq parsed; 0- if not emu10kx // data - any value #if defined(_MSC_VER) #pragma code_seg() // this is ALSO required, since we call send_message() here #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif KX_API(int,kx_interrupt_deferred(kx_hw *hw)) { dword irq_pending; irq_pending=kx_get_irq_pending(hw); if(irq_pending==0) { return KX_IRQ_NONE; } int ret=0; if(irq_pending&IRQ_TIMER) { // acknowledge interrupt kx_clear_irq_pending(hw, IRQ_TIMER); kx_timer_irq_handler(hw); irq_pending&=~IRQ_TIMER; } /* // never used: if((irq_pending&IPR_ADCBUFFULL)||(irq_pending&IPR_ADCBUFHALFFULL)) { // acknowledge interrupt kx_clear_irq_pending(hw, IPR_ADCBUFFULL|IPR_ADCBUFHALFFULL); debug(DERR,"adcrec irq should not happen\n"); if(hw->cb.timer_func && voice_usage(hw->voicetable[KX_REC_GENERIC].usage)==VOICE_USAGE_PLAYBACK) hw->cb.timer_func(hw->voicetable[KX_REC_GENERIC].buffer.that); irq_pending&=~(IPR_ADCBUFFULL|IPR_ADCBUFHALFFULL); } if((irq_pending&IPR_SPDIFBUFHALFFUL_K2)||(irq_pending&IPR_SPDIFBUFFUL_K2)) { // acknowledge interrupt kx_clear_irq_pending(hw, IPR_SPDIFBUFHALFFUL_K2|IPR_SPDIFBUFFUL_K2); debug(DERR,"spdif_rec irq should not happen\n"); if(hw->cb.timer_func && voice_usage(hw->voicetable[KX_REC_SPDIF].usage)==VOICE_USAGE_PLAYBACK) hw->cb.timer_func(hw->voicetable[KX_REC_SPDIF].buffer.that); irq_pending&=~(IPR_SPDIFBUFHALFFUL_K2|IPR_SPDIFBUFFUL_K2); } */ if(irq_pending&IRQ_MPUIN) { // acknowledge interrupt // kx_clear_irq_pending(hw, IRQ_MPUIN); // (should be done in sync code) kx_mpuin_irq_handler(hw,0); irq_pending&=~IRQ_MPUIN; ret |=KX_IRQ_MPUIN; // more processing required } if(irq_pending&IRQ_MPUIN2) { // acknowledge interrupt // kx_clear_irq_pending(hw, IRQ_MPUIN2); // (should be done in sync code) kx_mpuin_irq_handler(hw,1); irq_pending&=~IRQ_MPUIN2; ret |=KX_IRQ_MPUIN2; // more processing required } if(irq_pending&IRQ_MPUOUT) { // kx_clear_irq_pending(hw, IRQ_MPUOUT); // (should be done in sync code) kx_mpuout_irq_handler(hw,0); irq_pending&=~IRQ_MPUOUT; // 3537rc1: we don't need this // ret |=KX_IRQ_MPUOUT; } if(irq_pending&IRQ_MPUOUT2) { // kx_clear_irq_pending(hw, IRQ_MPUOUT2); // (should be done in sync code) kx_mpuout_irq_handler(hw,1); irq_pending&=~IRQ_MPUOUT2; // 3537rc1: we don't need this // ret |=KX_IRQ_MPUOUT2; } if(irq_pending&IRQ_PCIBUSERROR) { // acknowledge interrupt kx_clear_irq_pending(hw, IRQ_PCIBUSERROR); debug(DERR,"!!! PCI bus error found - and PCI IRQ is disabled now!\n"); hw->cb.send_message(hw->cb.call_with,KX_SYSEX_SIZE,KX_SYSEX_PCIBUSERROR); kx_irq_disable(hw,INTE_PCIERRORENABLE); irq_pending&=~IRQ_PCIBUSERROR; } if(irq_pending&IRQ_DSP) { // acknowledge interrupt kx_clear_irq_pending(hw, IRQ_DSP); kx_dsp_irq_handler(hw); irq_pending&=~IRQ_DSP; } if(irq_pending&IPR_MUTE) { // acknowledge interrupt kx_clear_irq_pending(hw, IPR_MUTE); if(hw->cb.send_message) { debug(DLIB," -- h/w mute\n"); hw->cb.send_message(hw->cb.call_with,KX_SYSEX_REMOTE_SIZE,KX_SYSEX_VOLMUTE); } irq_pending&=~IPR_MUTE; // 3538l: we don't need this // ret|=KX_IRQ_VOLUMES_MUTE; } if(irq_pending&IPR_VOLINCR) { // acknowledge interrupt kx_clear_irq_pending(hw, IPR_VOLINCR); if(hw->cb.send_message) { debug(DLIB," -- h/w volincr\n"); hw->cb.send_message(hw->cb.call_with,KX_SYSEX_REMOTE_SIZE,KX_SYSEX_VOLINCR); } irq_pending&=~IPR_VOLINCR; // 3538l: we don't need this // ret|=KX_IRQ_VOLUMES_VOLINCR; } if(irq_pending&IPR_VOLDECR) { // acknowledge interrupt kx_clear_irq_pending(hw, IPR_VOLDECR); if(hw->cb.send_message) { debug(DLIB," -- h/w voldecr\n"); hw->cb.send_message(hw->cb.call_with,KX_SYSEX_REMOTE_SIZE,KX_SYSEX_VOLDECR); } irq_pending&=~IPR_VOLDECR; // 3538l: we don't need this // ret|=KX_IRQ_VOLUMES_VOLDECR; } if(irq_pending&IRQ_GPIO) { kx_clear_irq_pending(hw, IPR_GPIO_CHANGE); system_timer_func(hw,LLA_NOTIFY_SYSTEM); irq_pending&=~IPR_GPIO_CHANGE; } if(irq_pending&IRQ_SPDIF) { // acknowledge interrupt kx_clear_irq_pending(hw, IRQ_SPDIF); kx_spdif_irq_handler(hw); irq_pending&=~IRQ_SPDIF; } if(irq_pending&IRQ_VOICE) { // acknowledge interrupt kx_clear_irq_pending(hw, IRQ_VOICE); kx_voice_irq_dispatch_handler(hw); irq_pending&=~IRQ_VOICE; // 3538l: we don't need this // ret|=KX_IRQ_VOICE; } if(irq_pending&IPR_EFXBUFFULL) { kx_clear_irq_pending(hw,IPR_EFXBUFFULL); kx_record_irq_dispatch_handler(hw,1); irq_pending&=(~IPR_EFXBUFFULL); } if(irq_pending&IPR_EFXBUFHALFFULL) { kx_clear_irq_pending(hw,IPR_EFXBUFHALFFULL); kx_record_irq_dispatch_handler(hw,0); irq_pending&=(~IPR_EFXBUFHALFFULL); } if(irq_pending) { debug(DERR,"!!! Unhandled IRQ: %x\n",irq_pending); // ret |=KX_IRQ_UNKNOWN; // kx_clear_irq_pending(hw, irq_pending); // (not necessary since not a real h/w access) } return ret; } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif KX_API(void, kx_irq_enable(kx_hw *hw, dword irq_mask)) { sync_data s; s.what=KX_SYNC_IRQ_ENABLE; s.hw=hw; s.irq_mask=irq_mask; hw->cb.sync(hw->cb.call_with,&s); } #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif KX_API(void, kx_irq_disable(kx_hw *hw, dword irq_mask)) { sync_data s; s.what=KX_SYNC_IRQ_DISABLE; s.hw=hw; s.irq_mask=irq_mask; hw->cb.sync(hw->cb.call_with,&s); } #if defined(_MSC_VER) #pragma code_seg() #endif KX_API(void, kx_voice_stop_on_loop_enable(kx_hw *hw, dword voicenum)) { if(voicenum >= 32) kx_writeptr(hw, SOLH | ((0x0100 | (voicenum - 32)) << 16), 0, 1); else kx_writeptr(hw, SOLL | ((0x0100 | voicenum) << 16), 0, 1); } #if defined(_MSC_VER) #pragma code_seg() #endif KX_API(void, kx_voice_stop_on_loop_disable(kx_hw *hw, dword voicenum)) { if(voicenum >= 32) kx_writeptr(hw, SOLH | ((0x0100 | (voicenum - 32)) << 16), 0, 0); else kx_writeptr(hw, SOLL | ((0x0100 | voicenum) << 16), 0, 0); } #if defined(_MSC_VER) #pragma code_seg() #endif KX_API(void, kx_voice_irq_enable(kx_hw *hw, dword voicenum)) { if(voicenum >= 32) kx_writeptr(hw, CLIEH | ((0x0100 | (voicenum - 32)) << 16), 0, 1); else kx_writeptr(hw, CLIEL | ((0x0100 | voicenum) << 16), 0, 1); if(hw->is_10k2) { if(voicenum >= 32) kx_writeptr(hw, HLIEH | ((0x0100 | (voicenum - 32)) << 16), 0, 1); else kx_writeptr(hw, HLIEL | ((0x0100 | voicenum) << 16), 0, 1); } } #if defined(_MSC_VER) #pragma code_seg() #endif KX_API(void, kx_voice_irq_disable(kx_hw *hw, dword voicenum)) { if(voicenum >= 32) kx_writeptr(hw, CLIEH | ((0x0100 | (voicenum - 32)) << 16), 0, 0); else kx_writeptr(hw, CLIEL | ((0x0100 | voicenum) << 16), 0, 0); if(hw->is_10k2) { if(voicenum >= 32) kx_writeptr(hw, HLIEH | ((0x0100 | (voicenum - 32)) << 16), 0, 0); else kx_writeptr(hw, HLIEL | ((0x0100 | voicenum) << 16), 0, 0); } } /* #pragma code_seg() KX_API(void, kx_voice_irq_ack(kx_hw *hw, dword voicenum)) { if(voicenum >= 32) kx_writeptr(hw, CLIPH | ((0x0100 | (voicenum - 32)) << 16), 0, 0); else kx_writeptr(hw, CLIPL | ((0x0100 | voicenum) << 16), 0, 0); } */ #if defined(_MSC_VER) #pragma code_seg() #endif #ifdef CE_OPTIMIZE #pragma optimize("gty", on) #pragma inline_depth(16) #endif KX_API(int,kx_get_asio_position(kx_hw *hw,int reget)) { asio_notification_t *krnl=&hw->asio_notification_krnl; if(krnl->n_voice!=-1 && reget) // note: when running at raised IRQl, set reget=0 { dword qkbca=0; // =kx_calc_position(hw,krnl->n_voice,(kx_readptr(hw,QKBCA,krnl->n_voice)&QKBCA_CURRADDR_MASK)); if(hw->hw_lock.kx_lock) { debug(DLIB,"kx_get_asio_position: shared access\n"); } else { #if defined(__APPLE__) && defined(__MACH__) // MacOSX // in OS X we cannot acquire spinlocks here, or at least should not to dword ptr_reg=(QKBCA<<16)|(hw->asio_notification_krnl.n_voice); dword old_ptr=inpd(hw->port+PTR); outpd(hw->port+PTR,ptr_reg); qkbca=inpd(hw->port+DATA); outpd(hw->port+PTR,old_ptr); #elif defined(_WIN32) || defined(_WINDOWS) || defined(WIN32) qkbca = kx_readptr(hw,QKBCA,krnl->n_voice)&QKBCA_CURRADDR_MASK; #else #error Unsupported architecture #endif qkbca=kx_calc_position(hw,krnl->n_voice,qkbca); // adjust for 28/32 sample delay only in the IRQ handler.. and for comparison only // qkbca=kx_adjust_position(hw,qkbca,hw->asio_notification_krnl.semi_buff); krnl->cur_pos=qkbca; // -hw->voicetable[hw->asio_notification_krnl.n_voice].param.startloop; // 3545b } if(krnl->cur_pos>=krnl->semi_buff) krnl->pb_buf=1; else krnl->pb_buf=0; } if(krnl->rec_buf==-1) // pb only case return krnl->pb_buf; if(krnl->pb_buf==-1) // rec only case return krnl->rec_buf; if(krnl->rec_buf==krnl->pb_buf) return krnl->pb_buf; return -1; }
gpl-2.0
bauwebster/Wordpress-Bootstrap-3-SASS-Starter-Framework
wp-content/themes/bootsass/footer.php
745
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package bootsass */ ?> </div><!-- #site-content --> <footer id="site-footer" role="contentinfo"> <section> <div class="site-info"> <a href="<?php echo esc_url( __( 'http://wordpress.org/', 'bootsass' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'bootsass' ), 'WordPress' ); ?></a> <span class="sep"> | </span> <?php printf( __( 'Theme: %1$s by %2$s.', 'bootsass' ), 'bootsass', '<a href="http://underscores.me/" rel="designer">Underscores.me</a>' ); ?> </div><!-- .site-info --> </section> </footer><!-- #site-footer --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
gpl-2.0
Johny-C/jchat
src/common/db/entity/TestEntity.java
914
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package common.db.entity; import java.io.Serializable; /** * * @author johny */ public class TestEntity implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private Status status; public enum Status { FIRST, SECOND, THIRD } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } }
gpl-2.0
clemsonbds/dasein-cloud-nfv
src/main/java/bds/clemson/nfv/etsi/hypervisor/vm/Save.java
1265
package bds.clemson.nfv.etsi.hypervisor.vm; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.VmState; import bds.clemson.nfv.exception.ConfigurationException; import bds.clemson.nfv.exception.ResourcesException; import bds.clemson.nfv.workflow.compute.VMStateChangeOperation; /** * Maps to ETSI GS NFV-MAN 001 7.6.2 "Save a virtual machine" * uses Dasein's "suspend" * * @author rakurai */ public class Save extends VMStateChangeOperation { public static void main(String[] args) throws UnsupportedOperationException { Save operation = new Save(); operation.execute(); } protected void executeInternal() throws InternalException, CloudException, ResourcesException, ConfigurationException, OperationNotSupportedException { super.executeInternal(); VmState currentState = vmSupport.getVirtualMachine(vmId).getCurrentState(); if (vmSupport.getCapabilities().canSuspend(currentState)) throw new CloudException("VM cannot save from state " + currentState); vmSupport.suspend(vmId); } }
gpl-2.0
kvilhaugsvik/jfcpi
JavaGenerator/src/com/kvilhaugsvik/javaGenerator/typeBridge/willReturn/ALong.java
712
/* * Copyright (c) 2012. Sveinung Kvilhaugsvik * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package com.kvilhaugsvik.javaGenerator.typeBridge.willReturn; /** * Represents the {@see long} value type. */ public interface ALong extends AValue { }
gpl-2.0
piaolinzhi/fight
cxf/ws_eventing/src/main/java/demo/wseventing/eventapi/CatastrophicEventSinkImpl.java
2154
/** * 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 demo.wseventing.eventapi; import java.util.ArrayList; import java.util.List; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; public class CatastrophicEventSinkImpl implements CatastrophicEventSink { private String url; private Server server; private List<Object> receivedEvents = new ArrayList<Object>(); public CatastrophicEventSinkImpl(String url) { JaxWsServerFactoryBean bean = new JaxWsServerFactoryBean(); bean.setServiceBean(this); bean.setAddress(url); this.url = url; server = bean.create(); } @Override public void earthquake(EarthquakeEvent ev) { System.out.println("Event sink received an earthquake notification: " + ev.toString()); receivedEvents.add(ev); } @Override public void fire(FireEvent ev) { System.out.println("Event sink received an fire notification: " + ev.toString()); receivedEvents.add(ev); } public void stop() { server.stop(); } public boolean isRunning() { return server.isStarted(); } public String getFullURL() { return "services" + url; } public String getShortURL() { return url; } public List<Object> getReceivedEvents() { return receivedEvents; } }
gpl-2.0
mclycan/based-dnc-pool
lib/paymentProcessor.js
7020
var fs = require('fs'); var async = require('async'); var apiInterfaces = require('./apiInterfaces.js')(config.daemon, config.wallet); var logSystem = 'payments'; require('./exceptionWriter.js')(logSystem); log('info', logSystem, 'Started'); function runInterval(){ async.waterfall([ //Get worker keys function(callback){ redisClient.keys(config.coin + ':workers:*', function(error, result) { if (error) { log('error', logSystem, 'Error trying to get worker balances from redis %j', [error]); callback(true); return; } callback(null, result); }); }, //Get worker balances function(keys, callback){ var redisCommands = keys.map(function(k){ return ['hget', k, 'balance']; }); redisClient.multi(redisCommands).exec(function(error, replies){ if (error){ log('error', logSystem, 'Error with getting balances from redis %j', [error]); callback(true); return; } var balances = {}; for (var i = 0; i < replies.length; i++){ var parts = keys[i].split(':'); var workerId = parts[parts.length - 1]; balances[workerId] = parseInt(replies[i]) || 0 } callback(null, balances); }); }, //Filter workers under balance threshold for payment function(balances, callback){ var payments = {}; for (var worker in balances){ var balance = balances[worker]; if (balance >= config.payments.minPayment){ var remainder = balance % config.payments.denomination; var payout = balance - remainder; if (payout < 0) continue; payments[worker] = payout; } } if (Object.keys(payments).length === 0){ log('info', logSystem, 'No workers\' balances reached the minimum payment threshold'); callback(true); return; } var transferCommands = []; var transferCommandsLength = Math.ceil(Object.keys(payments).length / config.payments.maxAddresses); for (var i = 0; i < transferCommandsLength; i++){ transferCommands.push({ redis: [], amount : 0, rpc: { destinations: [], fee: config.payments.transferFee, mixin: config.payments.mixin, unlock_time: 0 } }); } var addresses = 0; var commandAmount = 0; var commandIndex = 0; for (var worker in payments){ var amount = parseInt(payments[worker]); if(config.payments.maxTransactionAmount && amount + commandAmount > config.payments.maxTransactionAmount) { amount = config.payments.maxTransactionAmount - commandAmount; } if(!transferCommands[commandIndex]) { transferCommands[commandIndex] = { redis: [], amount : 0, rpc: { destinations: [], fee: config.payments.transferFee, mixin: config.payments.mixin, unlock_time: 0 } }; } transferCommands[commandIndex].rpc.destinations.push({amount: amount, address: worker}); transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'balance', -amount]); transferCommands[commandIndex].redis.push(['hincrby', config.coin + ':workers:' + worker, 'paid', amount]); transferCommands[commandIndex].amount += amount; addresses++; commandAmount += amount; if (addresses >= config.payments.maxAddresses || ( config.payments.maxTransactionAmount && commandAmount >= config.payments.maxTransactionAmount)) { commandIndex++; addresses = 0; commandAmount = 0; } } var timeOffset = 0; async.filter(transferCommands, function(transferCmd, cback){ apiInterfaces.rpcWallet('transfer', transferCmd.rpc, function(error, result){ if (error){ log('error', logSystem, 'Error with transfer RPC request to wallet daemon %j', [error]); log('error', logSystem, 'Payments failed to send to %j', transferCmd.rpc.destinations); cback(false); return; } var now = (timeOffset++) + Date.now() / 1000 | 0; var txHash = result.tx_hash.replace('<', '').replace('>', ''); transferCmd.redis.push(['zadd', config.coin + ':payments:all', now, [ txHash, transferCmd.amount, transferCmd.rpc.fee, transferCmd.rpc.mixin, Object.keys(transferCmd.rpc.destinations).length ].join(':')]); for (var i = 0; i < transferCmd.rpc.destinations.length; i++){ var destination = transferCmd.rpc.destinations[i]; transferCmd.redis.push(['zadd', config.coin + ':payments:' + destination.address, now, [ txHash, destination.amount, transferCmd.rpc.fee, transferCmd.rpc.mixin ].join(':')]); } log('info', logSystem, 'Payments sent via wallet daemon %j', [result]); redisClient.multi(transferCmd.redis).exec(function(error, replies){ if (error){ log('error', logSystem, 'Super critical error! Payments sent yet failing to update balance in redis, double payouts likely to happen %j', [error]); log('error', logSystem, 'Double payments likely to be sent to %j', transferCmd.rpc.destinations); cback(false); return; } cback(true); }); }); }, function(succeeded){ var failedAmount = transferCommands.length - succeeded.length; log('info', logSystem, 'Payments splintered and %d successfully sent, %d failed', [succeeded.length, failedAmount]); callback(null); }); } ], function(error, result){ setTimeout(runInterval, config.payments.interval * 1000); }); } runInterval();
gpl-2.0
bobpuffer/1.9.12-LAE1.3
course/index.php
16024
<?php // $Id: index.php 340 2010-07-16 19:46:56Z dlandau $ // For most people, just lists the course categories // Allows the admin to create, delete and rename course categories require_once("../config.php"); require_once("lib.php"); $categoryedit = optional_param('categoryedit', -1,PARAM_BOOL); $delete = optional_param('delete',0,PARAM_INT); $hide = optional_param('hide',0,PARAM_INT); $show = optional_param('show',0,PARAM_INT); $move = optional_param('move',0,PARAM_INT); $moveto = optional_param('moveto',-1,PARAM_INT); $moveup = optional_param('moveup',0,PARAM_INT); $movedown = optional_param('movedown',0,PARAM_INT); if ($CFG->forcelogin) { require_login(); } if (!$site = get_site()) { error('Site isn\'t defined!'); } $systemcontext = get_context_instance(CONTEXT_SYSTEM); if (update_category_button()) { if ($categoryedit !== -1) { $USER->categoryediting = $categoryedit; } $adminediting = !empty($USER->categoryediting); } else { $adminediting = false; } $stradministration = get_string('administration'); $strcategories = get_string('categories'); $strcategory = get_string('category'); $strcourses = get_string('courses'); $stredit = get_string('edit'); $strdelete = get_string('delete'); $straction = get_string('action'); /// Unless it's an editing admin, just print the regular listing of courses/categories if (!$adminediting) { /// Print form for creating new categories $countcategories = count_records('course_categories'); if ($countcategories > 1 || ($countcategories == 1 && count_records('course') > 200)) { $strcourses = get_string('courses'); $strcategories = get_string('categories'); $navlinks = array(); $navlinks[] = array('name'=>$strcategories,'link'=>'','type'=>'misc'); $navigation = build_navigation($navlinks); print_header("$site->shortname: $strcategories", $strcourses, $navigation, '', '', true, update_category_button()); print_heading($strcategories); // CLAMP # 114 2010-06-23 bobpuffer print_course_search(); // CLAMP # 114 2010-06-23 end echo skip_main_destination(); print_box_start('categorybox'); print_whole_category_list(); print_box_end(); } else { $strfulllistofcourses = get_string('fulllistofcourses'); print_header("$site->shortname: $strfulllistofcourses", $strfulllistofcourses, build_navigation(array(array('name'=>$strfulllistofcourses, 'link'=>'','type'=>'misc'))), '', '', true, update_category_button()); echo skip_main_destination(); print_box_start('courseboxes'); print_courses(0); print_box_end(); } echo '<div class="buttons">'; if (has_capability('moodle/course:create', $systemcontext)) { /// Print link to create a new course /// Get the 1st available category $options = array('category' => $CFG->defaultrequestcategory); print_single_button('edit.php', $options, get_string('addnewcourse'), 'get'); } print_course_request_buttons($systemcontext); echo '</div>'; print_footer(); exit; } /// Everything else is editing on mode. /// Delete a category. if (!empty($delete) and confirm_sesskey()) { if (!$deletecat = get_record('course_categories', 'id', $delete)) { error('Incorrect category id', 'index.php'); } $context = get_context_instance(CONTEXT_COURSECAT, $delete); require_capability('moodle/category:manage', $context); require_capability('moodle/category:manage', get_category_or_system_context($deletecat->parent)); $heading = get_string('deletecategory', '', format_string($deletecat->name)); require_once('delete_category_form.php'); $mform = new delete_category_form(null, $deletecat); $mform->set_data(array('delete'=>$delete)); if ($mform->is_cancelled()) { redirect('index.php'); } else if (!$data= $mform->get_data(false)) { require_once($CFG->libdir . '/questionlib.php'); print_category_edit_header(); print_heading($heading); $mform->display(); admin_externalpage_print_footer(); exit(); } print_category_edit_header(); print_heading($heading); if ($data->fulldelete) { category_delete_full($deletecat, true); } else { category_delete_move($deletecat, $data->newparent, true); } // If we deleted $CFG->defaultrequestcategory, make it point somewhere else. if ($delete == $CFG->defaultrequestcategory) { set_config('defaultrequestcategory', get_field('course_categories', 'MIN(id)', 'parent', 0)); } print_continue('index.php'); admin_externalpage_print_footer(); die; } /// Print headings print_category_edit_header(); print_heading($strcategories); /// Create a default category if necessary if (!$categories = get_categories()) { /// No category yet! // Try and make one unset($tempcat); $tempcat->name = get_string('miscellaneous'); if (!$tempcat->id = insert_record('course_categories', $tempcat)) { error('Serious error: Could not create a default category!'); } $tempcat->context = get_context_instance(CONTEXT_COURSECAT, $tempcat->id); mark_context_dirty('/'.SYSCONTEXTID); fix_course_sortorder(); // Required to build course_categories.depth and .path. } /// Move a category to a new parent if required if (!empty($move) and ($moveto >= 0) and confirm_sesskey()) { if ($cattomove = get_record('course_categories', 'id', $move)) { require_capability('moodle/category:manage', get_category_or_system_context($cattomove->parent)); if ($cattomove->parent != $moveto) { $newparent = get_record('course_categories', 'id', $moveto); require_capability('moodle/category:manage', get_category_or_system_context($moveto)); if (!move_category($cattomove, $newparent)) { notify('Could not update that category!'); } } } } /// Hide or show a category if ((!empty($hide) or !empty($show)) and confirm_sesskey()) { if (!empty($hide)) { $tempcat = get_record('course_categories', 'id', $hide); $visible = 0; } else { $tempcat = get_record('course_categories', 'id', $show); $visible = 1; } require_capability('moodle/category:manage', get_category_or_system_context($tempcat->parent)); if ($tempcat) { if (! set_field('course_categories', 'visible', $visible, 'id', $tempcat->id)) { notify('Could not update that category!'); } if (! set_field('course', 'visible', $visible, 'category', $tempcat->id)) { notify('Could not hide/show any courses in this category !'); } } } /// Move a category up or down if ((!empty($moveup) or !empty($movedown)) and confirm_sesskey()) { $swapcategory = NULL; $movecategory = NULL; if (!empty($moveup)) { require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $moveup)); if ($movecategory = get_record('course_categories', 'id', $moveup)) { $categories = get_categories($movecategory->parent); foreach ($categories as $category) { if ($category->id == $movecategory->id) { break; } $swapcategory = $category; } unset($category); } } if (!empty($movedown)) { require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $movedown)); if ($movecategory = get_record('course_categories', 'id', $movedown)) { $categories = get_categories($movecategory->parent); $choosenext = false; foreach ($categories as $category) { if ($choosenext) { $swapcategory = $category; break; } if ($category->id == $movecategory->id) { $choosenext = true; } } unset($category); } } if ($swapcategory and $movecategory) { // Renumber everything for robustness $count=0; foreach ($categories as $category) { $count++; if ($category->id == $swapcategory->id) { $category = $movecategory; } else if ($category->id == $movecategory->id) { $category = $swapcategory; } if (! set_field('course_categories', 'sortorder', $count, 'id', $category->id)) { notify('Could not update that category!'); } } unset($category); } } /// Find any orphan courses that don't yet have a valid category and set to default fix_coursecategory_orphans(); /// Should be a no-op 99% of the cases fix_course_sortorder(); /// Print out the categories with all the knobs $strcategories = get_string('categories'); $strcourses = get_string('courses'); $strmovecategoryto = get_string('movecategoryto'); $stredit = get_string('edit'); $displaylist = array(); $parentlist = array(); $displaylist[0] = get_string('top'); make_categories_list($displaylist, $parentlist); echo '<table class="generalbox editcourse boxaligncenter"><tr class="header">'; echo '<th class="header" scope="col">'.$strcategories.'</th>'; echo '<th class="header" scope="col">'.$strcourses.'</th>'; echo '<th class="header" scope="col">'.$stredit.'</th>'; echo '<th class="header" scope="col">'.$strmovecategoryto.'</th>'; echo '</tr>'; print_category_edit(NULL, $displaylist, $parentlist); echo '</table>'; echo '<div class="buttons">'; if (has_capability('moodle/course:create', $systemcontext)) { // print create course link to first category $options = array(); $options = array('category' => $CFG->defaultrequestcategory); print_single_button('edit.php', $options, get_string('addnewcourse'), 'get'); } // Print button for creating new categories if (has_capability('moodle/category:manage', $systemcontext)) { $options = array(); $options['parent'] = 0; print_single_button('editcategory.php', $options, get_string('addnewcategory'), 'get'); } print_course_request_buttons($systemcontext); echo '</div>'; admin_externalpage_print_footer(); function print_category_edit($category, $displaylist, $parentslist, $depth=-1, $up=false, $down=false) { /// Recursive function to print all the categories ready for editing global $CFG, $USER; static $str = NULL; if (is_null($str)) { $str = new stdClass; $str->edit = get_string('edit'); $str->delete = get_string('delete'); $str->moveup = get_string('moveup'); $str->movedown = get_string('movedown'); $str->edit = get_string('editthiscategory'); $str->hide = get_string('hide'); $str->show = get_string('show'); $str->spacer = '<img src="'.$CFG->wwwroot.'/pix/spacer.gif" class="iconsmall" alt="" /> '; } if (!empty($category)) { if (!isset($category->context)) { $category->context = get_context_instance(CONTEXT_COURSECAT, $category->id); } echo '<tr><td align="left" class="name">'; for ($i=0; $i<$depth;$i++) { echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; } $linkcss = $category->visible ? '' : ' class="dimmed" '; echo '<a '.$linkcss.' title="'.$str->edit.'" '. ' href="category.php?id='.$category->id.'&amp;categoryedit=on&amp;sesskey='.sesskey().'">'. format_string($category->name).'</a>'; echo '</td>'; echo '<td class="count">'.$category->coursecount.'</td>'; echo '<td class="icons">'; /// Print little icons if (has_capability('moodle/category:manage', $category->context)) { echo '<a title="'.$str->edit.'" href="editcategory.php?id='.$category->id.'"><img'. ' src="'.$CFG->pixpath.'/t/edit.gif" class="iconsmall" alt="'.$str->edit.'" /></a> '; echo '<a title="'.$str->delete.'" href="index.php?delete='.$category->id.'&amp;sesskey='.sesskey().'"><img'. ' src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" alt="'.$str->delete.'" /></a> '; if (!empty($category->visible)) { echo '<a title="'.$str->hide.'" href="index.php?hide='.$category->id.'&amp;sesskey='.sesskey().'"><img'. ' src="'.$CFG->pixpath.'/t/hide.gif" class="iconsmall" alt="'.$str->hide.'" /></a> '; } else { echo '<a title="'.$str->show.'" href="index.php?show='.$category->id.'&amp;sesskey='.sesskey().'"><img'. ' src="'.$CFG->pixpath.'/t/show.gif" class="iconsmall" alt="'.$str->show.'" /></a> '; } if ($up) { echo '<a title="'.$str->moveup.'" href="index.php?moveup='.$category->id.'&amp;sesskey='.sesskey().'"><img'. ' src="'.$CFG->pixpath.'/t/up.gif" class="iconsmall" alt="'.$str->moveup.'" /></a> '; } else { echo $str->spacer; } if ($down) { echo '<a title="'.$str->movedown.'" href="index.php?movedown='.$category->id.'&amp;sesskey='.sesskey().'"><img'. ' src="'.$CFG->pixpath.'/t/down.gif" class="iconsmall" alt="'.$str->movedown.'" /></a> '; } else { echo $str->spacer; } } echo '</td>'; echo '<td align="left">'; if (has_capability('moodle/category:manage', $category->context)) { $tempdisplaylist = $displaylist; unset($tempdisplaylist[$category->id]); foreach ($parentslist as $key => $parents) { if (in_array($category->id, $parents)) { unset($tempdisplaylist[$key]); } } popup_form ("index.php?move=$category->id&amp;sesskey=$USER->sesskey&amp;moveto=", $tempdisplaylist, "moveform$category->id", $category->parent, '', '', '', false); } echo '</td>'; echo '</tr>'; } else { $category->id = '0'; } if ($categories = get_categories($category->id)) { // Print all the children recursively $countcats = count($categories); $count = 0; $first = true; $last = false; foreach ($categories as $cat) { $count++; if ($count == $countcats) { $last = true; } $up = $first ? false : true; $down = $last ? false : true; $first = false; print_category_edit($cat, $displaylist, $parentslist, $depth+1, $up, $down); } } } function print_category_edit_header() { global $CFG; global $SITE; require_once($CFG->libdir.'/adminlib.php'); admin_externalpage_setup('coursemgmt', update_category_button()); admin_externalpage_print_header(); } ?>
gpl-2.0
poelzi/uberclock
external/piston/utils.py
12294
import time from django.http import HttpResponseNotAllowed, HttpResponseForbidden, HttpResponse, HttpResponseBadRequest from django.core.urlresolvers import reverse from django.core.cache import cache from django import get_version as django_version from django.core.mail import send_mail, mail_admins from django.conf import settings from django.utils.translation import ugettext as _ from django.template import loader, TemplateDoesNotExist from django.contrib.sites.models import Site from decorator import decorator from datetime import datetime, timedelta __version__ = '0.2.3rc1' def get_version(): return __version__ def format_error(error): return u"Piston/%s (Django %s) crash report:\n\n%s" % \ (get_version(), django_version(), error) class rc_factory(object): """ Status codes. """ CODES = dict(ALL_OK = ('OK', 200), CREATED = ('Created', 201), DELETED = ('', 204), # 204 says "Don't send a body!" BAD_REQUEST = ('Bad Request', 400), FORBIDDEN = ('Forbidden', 401), NOT_FOUND = ('Not Found', 404), DUPLICATE_ENTRY = ('Conflict/Duplicate', 409), NOT_HERE = ('Gone', 410), INTERNAL_ERROR = ('Internal Error', 500), NOT_IMPLEMENTED = ('Not Implemented', 501), THROTTLED = ('Throttled', 503)) def __getattr__(self, attr): """ Returns a fresh `HttpResponse` when getting an "attribute". This is backwards compatible with 0.2, which is important. """ try: (r, c) = self.CODES.get(attr) except TypeError: raise AttributeError(attr) class HttpResponseWrapper(HttpResponse): """ Wrap HttpResponse and make sure that the internal _is_string flag is updated when the _set_content method (via the content property) is called """ def _set_content(self, content): """ Set the _container and _is_string properties based on the type of the value parameter. This logic is in the construtor for HttpResponse, but doesn't get repeated when setting HttpResponse.content although this bug report (feature request) suggests that it should: http://code.djangoproject.com/ticket/9403 """ if not isinstance(content, basestring) and hasattr(content, '__iter__'): self._container = content self._is_string = False else: self._container = [content] self._is_string = True content = property(HttpResponse._get_content, _set_content) return HttpResponseWrapper(r, content_type='text/plain', status=c) rc = rc_factory() class FormValidationError(Exception): def __init__(self, form): self.form = form class HttpStatusCode(Exception): def __init__(self, response): self.response = response def validate(v_form, operation='POST'): @decorator def wrap(f, self, request, *a, **kwa): form = v_form(getattr(request, operation)) if form.is_valid(): setattr(request, 'form', form) return f(self, request, *a, **kwa) else: raise FormValidationError(form) return wrap def throttle(max_requests, timeout=60*60, extra=''): """ Simple throttling decorator, caches the amount of requests made in cache. If used on a view where users are required to log in, the username is used, otherwise the IP address of the originating request is used. Parameters:: - `max_requests`: The maximum number of requests - `timeout`: The timeout for the cache entry (default: 1 hour) """ @decorator def wrap(f, self, request, *args, **kwargs): if request.user.is_authenticated(): ident = request.user.username else: ident = request.META.get('REMOTE_ADDR', None) if hasattr(request, 'throttle_extra'): """ Since we want to be able to throttle on a per- application basis, it's important that we realize that `throttle_extra` might be set on the request object. If so, append the identifier name with it. """ ident += ':%s' % str(request.throttle_extra) if ident: """ Preferrably we'd use incr/decr here, since they're atomic in memcached, but it's in django-trunk so we can't use it yet. If someone sees this after it's in stable, you can change it here. """ ident += ':%s' % extra now = time.time() count, expiration = cache.get(ident, (1, None)) if expiration is None: expiration = now + timeout if count >= max_requests and expiration > now: t = rc.THROTTLED wait = int(expiration - now) t.content = 'Throttled, wait %d seconds.' % wait t['Retry-After'] = wait return t cache.set(ident, (count+1, expiration), (expiration - now)) return f(self, request, *args, **kwargs) return wrap def coerce_put_post(request): """ Django doesn't particularly understand REST. In case we send data over PUT, Django won't actually look at the data and load it. We need to twist its arm here. The try/except abominiation here is due to a bug in mod_python. This should fix it. """ if request.method == "PUT": # Bug fix: if _load_post_and_files has already been called, for # example by middleware accessing request.POST, the below code to # pretend the request is a POST instead of a PUT will be too late # to make a difference. Also calling _load_post_and_files will result # in the following exception: # AttributeError: You cannot set the upload handlers after the upload has been processed. # The fix is to check for the presence of the _post field which is set # the first time _load_post_and_files is called (both by wsgi.py and # modpython.py). If it's set, the request has to be 'reset' to redo # the query value parsing in POST mode. if hasattr(request, '_post'): del request._post del request._files try: request.method = "POST" request._load_post_and_files() request.method = "PUT" except AttributeError: request.META['REQUEST_METHOD'] = 'POST' request._load_post_and_files() request.META['REQUEST_METHOD'] = 'PUT' request.PUT = request.POST class MimerDataException(Exception): """ Raised if the content_type and data don't match """ pass class Mimer(object): TYPES = dict() def __init__(self, request): self.request = request def is_multipart(self): content_type = self.content_type() if content_type is not None: return content_type.lstrip().startswith('multipart') return False def loader_for_type(self, ctype): """ Gets a function ref to deserialize content for a certain mimetype. """ for loadee, mimes in Mimer.TYPES.iteritems(): for mime in mimes: if ctype == mime: return loadee def content_type(self): """ Returns the content type of the request in all cases where it is different than a submitted form - application/x-www-form-urlencoded """ type_formencoded = "application/x-www-form-urlencoded" ctype = self.request.META.get('CONTENT_TYPE', type_formencoded) ctype = ctype.split(";")[0] if type_formencoded == ctype: return None return ctype def translate(self): """ Will look at the `Content-type` sent by the client, and maybe deserialize the contents into the format they sent. This will work for JSON, YAML, XML and Pickle. Since the data is not just key-value (and maybe just a list), the data will be placed on `request.data` instead, and the handler will have to read from there. It will also set `request.content_type` so the handler has an easy way to tell what's going on. `request.content_type` will always be None for form-encoded and/or multipart form data (what your browser sends.) """ ctype = self.content_type() self.request.content_type = ctype if not self.is_multipart() and ctype: loadee = self.loader_for_type(ctype) if loadee: try: self.request.data = loadee(self.request.raw_post_data) # Reset both POST and PUT from request, as its # misleading having their presence around. self.request.POST = self.request.PUT = dict() except (TypeError, ValueError): # This also catches if loadee is None. raise MimerDataException else: self.request.data = None return self.request @classmethod def register(cls, loadee, types): cls.TYPES[loadee] = types @classmethod def unregister(cls, loadee): return cls.TYPES.pop(loadee) def translate_mime(request): request = Mimer(request).translate() def require_mime(*mimes): """ Decorator requiring a certain mimetype. There's a nifty helper called `require_extended` below which requires everything we support except for post-data via form. """ @decorator def wrap(f, self, request, *args, **kwargs): m = Mimer(request) realmimes = set() rewrite = { 'json': 'application/json', 'yaml': 'application/x-yaml', 'xml': 'text/xml', 'pickle': 'application/python-pickle' } for idx, mime in enumerate(mimes): realmimes.add(rewrite.get(mime, mime)) if not m.content_type() in realmimes: return rc.BAD_REQUEST return f(self, request, *args, **kwargs) return wrap require_extended = require_mime('json', 'yaml', 'xml', 'pickle') def send_consumer_mail(consumer): """ Send a consumer an email depending on what their status is. """ try: subject = settings.PISTON_OAUTH_EMAIL_SUBJECTS[consumer.status] except AttributeError: subject = "Your API Consumer for %s " % Site.objects.get_current().name if consumer.status == "accepted": subject += "was accepted!" elif consumer.status == "canceled": subject += "has been canceled." elif consumer.status == "rejected": subject += "has been rejected." else: subject += "is awaiting approval." template = "piston/mails/consumer_%s.txt" % consumer.status try: body = loader.render_to_string(template, { 'consumer' : consumer, 'user' : consumer.user }) except TemplateDoesNotExist: """ They haven't set up the templates, which means they might not want these emails sent. """ return try: sender = settings.PISTON_FROM_EMAIL except AttributeError: sender = settings.DEFAULT_FROM_EMAIL if consumer.user: send_mail(_(subject), body, sender, [consumer.user.email], fail_silently=True) if consumer.status == 'pending' and len(settings.ADMINS): mail_admins(_(subject), body, fail_silently=True) if settings.DEBUG and consumer.user: print "Mail being sent, to=%s" % consumer.user.email print "Subject: %s" % _(subject) print body
gpl-2.0
ike3/scriptdev2
scripts/northrend/crusaders_coliseum/trial_of_the_crusader/boss_anubarak_trial.cpp
37590
/* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_anubarak_trial SD%Complete: 70% SDComment: by /dev/rsa SDCategory: EndScriptData */ #include "precompiled.h" #include "trial_of_the_crusader.h" enum Yells { SAY_INTRO = -1649038, SAY_AGGRO = -1649064, SAY_SUBMERGE = -1649069, SAY_LOW_HEALTH = -1649070, SAY_SLAY_1 = -1649065, SAY_SLAY_2 = -1649066, SAY_DEATH = -1649067, EMOTE_SUBMERGE = -1649071, EMOTE_PURSUING = -1649072, EMOTE_OUT_OF_THE_GROUND = -1649073, EMOTE_LEECHING_SWARM = -1649074, }; enum Summons { NPC_FROST_SPHERE = 34606, NPC_PERMAFROST = 33184, NPC_NERUBIAN_BURROW_1 = 34862, NPC_NERUBIAN_BURROW_2 = 34863, NPC_NERUBIAN_BURROW_3 = 34864, NPC_NERUBIAN_BURROW_4 = 34865, NPC_BURROWER = 34607, NPC_SCARAB = 34605, NPC_SPIKE = 34660, NPC_SPIKE_TRIGGER = 5672, }; enum BossSpells { SPELL_FROST_VISUAL = 67539, SPELL_PERMAFROST = 66193, SPELL_PERMAFROST_SPAWN = 65882, SPELL_COLD = 66013, SPELL_MARK = 67574, SPELL_LEECHING_SWARM = 66118, SPELL_LEECHING_HEAL = 66125, SPELL_LEECHING_DAMAGE = 66240, SPELL_IMPALE_10 = 65919, SPELL_IMPALE_25 = 67859, SPELL_IMPALE_GROUND = 65921, SPELL_PURSUING_SPIKE_LOW = 65920, SPELL_PURSUING_SPIKE_MED = 65922, SPELL_PURSUING_SPIKE_HIGH = 65923, SPELL_PURSUING_SPIKE_COLD = 66181, SPELL_POUND = 66012, SPELL_SHOUT = 67730, SPELL_SUBMERGE_ANUB = 53421, SPELL_EMERGE_ANUB = 65982, SPELL_SUBMERGE_BURROWER = 53421, // Temporal (Original: 67322) SPELL_EMERGE_BURROWER = 65982, SPELL_SUMMON_BEATLES = 66339, SPELL_DETERMINATION = 66092, SPELL_ACID_MANDIBLE = 65775, SPELL_SPIDER_FRENZY = 66129, SPELL_EXPOSE_WEAKNESS = 67847, SPELL_SUMMON_SCARAB = 66340, SPELL_SHADOW_STRIKE = 66134, SPELL_ACHIEV_TRAITOR_KING_10 = 68186, SPELL_ACHIEV_TRAITOR_KING_25 = 68515, SPELL_BERSERK = 26662, }; struct MANGOS_DLL_DECL boss_anubarak_trialAI : public BSWScriptedAI { boss_anubarak_trialAI(Creature* pCreature) : BSWScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_uiMapDifficulty = pCreature->GetMap()->GetDifficulty(); m_bIsHeroic = m_uiMapDifficulty > RAID_DIFFICULTY_25MAN_NORMAL; m_bIs25Man = (m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_NORMAL || m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_HEROIC); Reset(); } ScriptedInstance* m_pInstance; Difficulty m_uiMapDifficulty; bool intro; bool m_bIsHeroic; bool m_bIs25Man; uint32 m_uiEventStep; uint32 m_uiNextEventTimer; uint32 m_uiPoundTimer; uint32 m_uiColdTimer; uint32 m_uiSummonBurrowerTimer; uint32 m_uiSubmergeAnubTimer; uint32 m_uiNerubianBurrowTimer; uint32 m_uiSubmergePhaseTimer; uint32 m_uiFrostSphereOneTimer; uint32 m_uiFrostSphereTwoTimer; uint32 m_uiSummonScarabTimer; uint32 m_uiPursuingTimer; uint32 m_uiBerserkTimer; Unit* pTarget; void Reset() { if (!m_pInstance) return; intro = true; pTarget = NULL; m_uiEventStep = 0; m_uiNextEventTimer = 0; m_uiPoundTimer = 20000; m_uiColdTimer = 30000; m_uiSummonBurrowerTimer = 10000; m_uiSubmergeAnubTimer = 80000; m_uiNerubianBurrowTimer = 0; m_uiSubmergePhaseTimer = 88000; m_uiFrostSphereOneTimer = urand(5000, 10000); m_uiFrostSphereTwoTimer = 2000; m_uiSummonScarabTimer = 2000; m_uiPursuingTimer = 1000; m_uiBerserkTimer = 570000; m_creature->SetRespawnDelay(DAY); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void NextStep(uint32 uiTime = 1000) { ++m_uiEventStep; m_uiNextEventTimer = uiTime; } void KilledUnit(Unit* pVictim) override { if (pVictim->GetTypeId() != TYPEID_PLAYER) return; DoScriptText(SAY_SLAY_1 - urand(0, 1),m_creature,pVictim); } void MoveInLineOfSight(Unit* pWho) override { if (!intro) return; DoScriptText(SAY_INTRO, m_creature); intro = false; if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_1)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_2)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_3)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_4)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); } void JustReachedHome() override { if (m_pInstance) m_pInstance->SetData(TYPE_ANUBARAK, FAIL); } void JustDied(Unit* pKiller) override { if (!m_pInstance) return; m_pInstance->SetData(TYPE_COUNTER, m_pInstance->GetData(TYPE_COUNTER)); DoScriptText(SAY_DEATH, m_creature); m_pInstance->SetData(TYPE_ANUBARAK, DONE); m_pInstance->SetData(TYPE_EVENT, 6000); } void Aggro(Unit* pWho) { if (!intro) DoScriptText(SAY_AGGRO, m_creature); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); m_creature->SetInCombatWithZone(); m_pInstance->SetData(TYPE_ANUBARAK, IN_PROGRESS); } void UpdateAI(const uint32 uiDiff) override { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiNextEventTimer <= uiDiff) { switch (m_uiEventStep) { case 0: if (m_uiFrostSphereOneTimer <= uiDiff) { if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[29].x + urand(5, 15), SpawnLoc[29].y - urand(10, 20), SpawnLoc[29].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[30].x + urand(5, 15), SpawnLoc[30].y - urand(10, 20), SpawnLoc[30].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[31].x + urand(5, 15), SpawnLoc[31].y - urand(10, 20), SpawnLoc[31].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[32].x + urand(5, 15), SpawnLoc[32].y - urand(10, 20), SpawnLoc[32].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[49].x + urand(5, 15), SpawnLoc[49].y - urand(10, 20), SpawnLoc[49].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[50].x + urand(5, 15), SpawnLoc[50].y - urand(10, 20), SpawnLoc[50].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[51].x + urand(5, 15), SpawnLoc[51].y - urand(10, 20), SpawnLoc[51].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[52].x + urand(5, 15), SpawnLoc[52].y - urand(10, 20), SpawnLoc[52].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); m_uiFrostSphereOneTimer = 40000; } else m_uiFrostSphereOneTimer -= uiDiff; if (m_uiPoundTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_POUND) == CAST_OK) m_uiPoundTimer = 20000; } else m_uiPoundTimer -= uiDiff; if (m_uiColdTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_COLD) == CAST_OK) m_uiColdTimer = 25000; } else m_uiColdTimer -= uiDiff; if (m_uiSummonBurrowerTimer <= uiDiff) { float x, y, z; m_creature->GetPosition(x, y, z); m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); if (m_bIs25Man || m_bIsHeroic) m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); if (m_bIs25Man && m_bIsHeroic) { m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); } m_uiSummonBurrowerTimer = 45000; } else m_uiSummonBurrowerTimer -= uiDiff; if (m_uiSubmergeAnubTimer <= uiDiff) { m_creature->CastSpell(m_creature, SPELL_SUBMERGE_ANUB, false); m_uiSubmergeAnubTimer = 80000; NextStep(); } else m_uiSubmergeAnubTimer -= uiDiff; break; case 1: m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); DoScriptText(SAY_SUBMERGE, m_creature); DoScriptText(EMOTE_SUBMERGE, m_creature); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_1)) pNerubianBurrow->SetVisibility(VISIBILITY_ON); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_2)) pNerubianBurrow->SetVisibility(VISIBILITY_ON); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_3)) pNerubianBurrow->SetVisibility(VISIBILITY_ON); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_4)) pNerubianBurrow->SetVisibility(VISIBILITY_ON); NextStep(2000); break; case 2: if (m_uiPursuingTimer <= uiDiff) { float x, y, z; m_creature->GetPosition(x, y, z); m_creature->SummonCreature(NPC_SPIKE, x, y, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); m_uiPursuingTimer = 90000; } else m_uiPursuingTimer -= uiDiff; if (m_uiFrostSphereTwoTimer <= uiDiff) { if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[29].x + urand(5, 15), SpawnLoc[29].y - urand(10, 20), SpawnLoc[29].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[30].x + urand(5, 15), SpawnLoc[30].y - urand(10, 20), SpawnLoc[30].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 40000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[31].x + urand(5, 15), SpawnLoc[31].y - urand(10, 20), SpawnLoc[31].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[32].x + urand(5, 15), SpawnLoc[32].y - urand(10, 20), SpawnLoc[32].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 40000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[49].x + urand(5, 15), SpawnLoc[49].y - urand(10, 20), SpawnLoc[49].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[50].x + urand(5, 15), SpawnLoc[50].y - urand(10, 20), SpawnLoc[50].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[51].x + urand(5, 15), SpawnLoc[51].y - urand(10, 20), SpawnLoc[51].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); if (Creature *pFrostSphere = m_creature->SummonCreature(NPC_FROST_SPHERE, SpawnLoc[52].x + urand(5, 15), SpawnLoc[52].y - urand(10, 20), SpawnLoc[52].z + 10.0f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) pFrostSphere->CastSpell(m_creature, SPELL_FROST_VISUAL, false); m_uiFrostSphereTwoTimer = 30000; } else m_uiFrostSphereTwoTimer -= uiDiff; if (m_uiSummonScarabTimer <= uiDiff) { if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_1)) pNerubianBurrow->CastSpell(pNerubianBurrow, SPELL_SUMMON_SCARAB, false); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_2)) pNerubianBurrow->CastSpell(pNerubianBurrow, SPELL_SUMMON_SCARAB, false); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_3)) pNerubianBurrow->CastSpell(pNerubianBurrow, SPELL_SUMMON_SCARAB, false); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_4)) pNerubianBurrow->CastSpell(pNerubianBurrow, SPELL_SUMMON_SCARAB, false); m_uiSummonScarabTimer = 8000; } else m_uiSummonScarabTimer -= uiDiff; if (m_uiSubmergePhaseTimer <= uiDiff) { m_uiSubmergePhaseTimer = 90000; NextStep(); } else m_uiSubmergePhaseTimer -= uiDiff; break; case 3: m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_ANUB); m_creature->CastSpell(m_creature, SPELL_EMERGE_ANUB, false); DoScriptText(EMOTE_OUT_OF_THE_GROUND,m_creature); if (Creature *pSpike = m_pInstance->GetSingleCreatureFromStorage(NPC_SPIKE)) pSpike->ForcedDespawn(); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_1)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_2)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_3)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); if (Creature *pNerubianBurrow = m_pInstance->GetSingleCreatureFromStorage(NPC_NERUBIAN_BURROW_4)) pNerubianBurrow->SetVisibility(VISIBILITY_OFF); m_uiEventStep = 0; break; case 4: m_creature->CastSpell(m_creature, SPELL_LEECHING_SWARM, false); DoScriptText(SAY_LOW_HEALTH, m_creature); DoScriptText(EMOTE_LEECHING_SWARM, m_creature); m_uiEventStep = 5; NextStep(3000); break; case 5: if (m_uiPoundTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_POUND) == CAST_OK) m_uiPoundTimer = 20000; } else m_uiPoundTimer -= uiDiff; if (m_uiColdTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_COLD) == CAST_OK) m_uiColdTimer = 25000; } else m_uiColdTimer -= uiDiff; if (m_bIsHeroic) { if (m_uiSummonBurrowerTimer <= uiDiff) { float x, y, z; m_creature->GetPosition(x, y, z); m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); if (m_bIs25Man || m_bIsHeroic) m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); if (m_bIs25Man && m_bIsHeroic) { m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); m_creature->SummonCreature(NPC_BURROWER, x + 3.0f, y + 3.0f, z, 0, TEMPSUMMON_MANUAL_DESPAWN, 60000); } m_uiSummonBurrowerTimer = 45000; } else m_uiSummonBurrowerTimer -= uiDiff; } break; } if (m_uiBerserkTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_BERSERK) == CAST_OK) m_uiBerserkTimer = 570000; } else m_uiBerserkTimer -= uiDiff; if (m_creature->GetHealthPercent() < 30.0f && m_uiEventStep == 0) m_uiEventStep = 4; } else m_uiNextEventTimer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_anubarak_trial(Creature* pCreature) { return new boss_anubarak_trialAI(pCreature); } struct MANGOS_DLL_DECL mob_swarm_scarabAI : public BSWScriptedAI { mob_swarm_scarabAI(Creature* pCreature) : BSWScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_uiMapDifficulty = pCreature->GetMap()->GetDifficulty(); m_bIsHeroic = m_uiMapDifficulty > RAID_DIFFICULTY_25MAN_NORMAL; m_bIs25Man = (m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_NORMAL || m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_HEROIC); Reset(); } ScriptedInstance* m_pInstance; Difficulty m_uiMapDifficulty; bool m_bIsHeroic; bool m_bIs25Man; uint32 m_uiAcidMandibleTimer; uint32 m_uiDeterminationTimer; void Reset() { m_creature->SetInCombatWithZone(); m_creature->SetRespawnDelay(DAY); m_uiAcidMandibleTimer = 2000; m_uiDeterminationTimer = urand(10000, 20000); } void KilledUnit(Unit* pVictim) override { if (pVictim->GetTypeId() != TYPEID_PLAYER) return; } void JustDied(Unit* Killer) { m_pInstance->DoStartTimedAchievement(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_bIs25Man ? SPELL_ACHIEV_TRAITOR_KING_25 : SPELL_ACHIEV_TRAITOR_KING_10); m_pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_bIs25Man ? SPELL_ACHIEV_TRAITOR_KING_25 : SPELL_ACHIEV_TRAITOR_KING_10); m_creature->ForcedDespawn(5000); } void Aggro(Unit *who) { if (!m_pInstance) return; } void UpdateAI(const uint32 uiDiff) override { if (m_pInstance && m_pInstance->GetData(TYPE_ANUBARAK) != IN_PROGRESS) m_creature->ForcedDespawn(); if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiDeterminationTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature, SPELL_DETERMINATION) == CAST_OK) m_uiDeterminationTimer = 30000; } else m_uiDeterminationTimer -= uiDiff; if (m_uiAcidMandibleTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_ACID_MANDIBLE) == CAST_OK) m_uiAcidMandibleTimer = 2000; } else m_uiAcidMandibleTimer -= uiDiff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_swarm_scarab(Creature* pCreature) { return new mob_swarm_scarabAI(pCreature); }; struct MANGOS_DLL_DECL mob_nerubian_borrowerAI : public BSWScriptedAI { mob_nerubian_borrowerAI(Creature* pCreature) : BSWScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_uiMapDifficulty = pCreature->GetMap()->GetDifficulty(); m_bIsHeroic = m_uiMapDifficulty > RAID_DIFFICULTY_25MAN_NORMAL; m_bIs25Man = (m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_NORMAL || m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_HEROIC); Reset(); } ScriptedInstance* m_pInstance; Difficulty m_uiMapDifficulty; bool m_bIsSubmerged; bool m_bIsHeroic; bool m_bIs25Man; uint32 m_uiExposeWeaknessTimer; uint32 m_uiSpiderFrenzyTimer; uint32 m_uiShadowStrikeTimer; uint32 m_uiSubmergeBurrowerTimer; void Reset() { m_creature->SetInCombatWithZone(); m_creature->SetRespawnDelay(DAY); m_bIsSubmerged = false; m_uiExposeWeaknessTimer = 8000; m_uiSpiderFrenzyTimer = 0; m_uiShadowStrikeTimer = 5000; m_uiSubmergeBurrowerTimer = 5000; } void KilledUnit(Unit* pVictim) override { if (pVictim->GetTypeId() != TYPEID_PLAYER) return; } void JustDied(Unit* Killer) { m_creature->ForcedDespawn(5000); if (Creature* pNerubianBurrower = GetClosestCreatureWithEntry(m_creature, NPC_BURROWER, 50.0f)) pNerubianBurrower->RemoveAurasDueToSpell(SPELL_SPIDER_FRENZY); } void Aggro(Unit *who) { if (!m_pInstance) return; } void UpdateAI(const uint32 uiDiff) override { if (m_pInstance && m_pInstance->GetData(TYPE_ANUBARAK) != IN_PROGRESS) m_creature->ForcedDespawn(); if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiExposeWeaknessTimer <= uiDiff) { if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_EXPOSE_WEAKNESS) == CAST_OK) m_uiExposeWeaknessTimer = 8000; } else m_uiExposeWeaknessTimer -= uiDiff; if (m_uiSpiderFrenzyTimer <= uiDiff) { if (Creature* pNerubianBurrower = GetClosestCreatureWithEntry(m_creature, NPC_BURROWER, 50.0f)) { m_creature->_AddAura(SPELL_SPIDER_FRENZY); pNerubianBurrower->_AddAura(SPELL_SPIDER_FRENZY); } m_uiSpiderFrenzyTimer = 1000; } else m_uiSpiderFrenzyTimer -= uiDiff; if (m_bIsHeroic) { if (m_uiShadowStrikeTimer <= uiDiff) { m_creature->CastSpell(m_creature->getVictim(), SPELL_SHADOW_STRIKE, false); m_uiShadowStrikeTimer = 30000; } else m_uiShadowStrikeTimer -= uiDiff; } if (m_creature->GetHealthPercent() < 20.0f && !m_bIsSubmerged && !hasAura(SPELL_PERMAFROST, m_creature)) { m_creature->CastSpell(m_creature, SPELL_SUBMERGE_BURROWER, false); m_creature->RemoveAllAuras(); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); DoScriptText(EMOTE_SUBMERGE, m_creature); m_bIsSubmerged = true; } if (m_bIsSubmerged) { if (m_uiSubmergeBurrowerTimer <= uiDiff) { m_creature->SetHealth(m_creature->GetMaxHealth()); m_uiSubmergeBurrowerTimer = 5000; } else m_uiSubmergeBurrowerTimer -= uiDiff; } if (m_creature->GetHealthPercent() > 50.0f && m_bIsSubmerged) { m_creature->CastSpell(m_creature, SPELL_EMERGE_BURROWER, false); m_creature->RemoveAurasDueToSpell(SPELL_SUBMERGE_BURROWER); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); DoScriptText(EMOTE_OUT_OF_THE_GROUND, m_creature); m_bIsSubmerged = false; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_mob_nerubian_borrower(Creature* pCreature) { return new mob_nerubian_borrowerAI(pCreature); }; struct MANGOS_DLL_DECL mob_frost_sphereAI : public BSWScriptedAI { mob_frost_sphereAI(Creature* pCreature) : BSWScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance* m_pInstance; void Reset() { m_creature->SetRespawnDelay(DAY); m_creature->SetLevitate(true); SetCombatMovement(false); m_creature->GetMotionMaster()->MoveRandom(); } void Aggro(Unit *who) { if (!m_pInstance) return; if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; m_creature->SetVisibility(VISIBILITY_OFF); m_creature->CastSpell(m_creature, SPELL_PERMAFROST_SPAWN, false); float x, y, z; m_creature->GetPosition(x, y, z); if (Creature *pPermafrost = m_creature->SummonCreature(NPC_PERMAFROST, x, y, z - 9.8f, 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) { pPermafrost->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pPermafrost->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); pPermafrost->CastSpell(pPermafrost, SPELL_PERMAFROST, false); } } void UpdateAI(const uint32 uiDiff) override { if (!m_pInstance || m_pInstance->GetData(TYPE_ANUBARAK) != IN_PROGRESS) m_creature->ForcedDespawn(); } }; CreatureAI* GetAI_mob_frost_sphere(Creature* pCreature) { return new mob_frost_sphereAI(pCreature); }; struct MANGOS_DLL_DECL mob_anubarak_spikeAI : public BSWScriptedAI { mob_anubarak_spikeAI(Creature* pCreature) : BSWScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_uiMapDifficulty = pCreature->GetMap()->GetDifficulty(); m_bIsHeroic = m_uiMapDifficulty > RAID_DIFFICULTY_25MAN_NORMAL; m_bIs25Man = (m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_NORMAL || m_uiMapDifficulty == RAID_DIFFICULTY_25MAN_HEROIC); Reset(); } ScriptedInstance* m_pInstance; Difficulty m_uiMapDifficulty; bool m_bIncreaseSpeed; bool m_bIsHeroic; bool m_bIs25Man; uint32 m_uiEventStep; uint32 m_uiNextEventTimer; uint32 m_uiImpaleTimer; uint32 m_uiIncreaseSpeedTimer; uint32 m_uiSpikeCallTimer; uint32 m_uiPermafrostTimer; void Reset() { m_creature->SetRespawnDelay(DAY); m_creature->SetVisibility(VISIBILITY_OFF); m_creature->SetInCombatWithZone(); m_creature->setFaction(14); m_creature->SetSpeedRate(MOVE_RUN, 0.0f); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); m_uiEventStep = 0; m_uiNextEventTimer = 8000; m_uiImpaleTimer = 5000; m_uiIncreaseSpeedTimer = 5000; m_uiSpikeCallTimer = 4500; m_uiPermafrostTimer = 5000; } void NextStep(uint32 uiTime = 1000) { ++m_uiEventStep; m_uiIncreaseSpeedTimer = uiTime; } void Aggro(Unit *who) { if (!m_pInstance) return; } void UpdateAI(const uint32 uiDiff) override { if (m_pInstance && m_pInstance->GetData(TYPE_ANUBARAK) != IN_PROGRESS) m_creature->ForcedDespawn(); if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (m_uiIncreaseSpeedTimer <= uiDiff) { switch (m_uiEventStep) { case 0: m_creature->SetSpeedRate(MOVE_RUN, 0.75f); m_creature->CastSpell(m_creature, SPELL_PURSUING_SPIKE_LOW, false); NextStep(7000); break; case 1: m_creature->SetSpeedRate(MOVE_RUN, 1.0f); m_creature->CastSpell(m_creature, SPELL_PURSUING_SPIKE_MED, false); NextStep(7000); break; case 2: m_creature->SetSpeedRate(MOVE_RUN, 1.5f); m_creature->CastSpell(m_creature, SPELL_PURSUING_SPIKE_HIGH, false); NextStep(7000); break; } } else m_uiIncreaseSpeedTimer -= uiDiff; if (m_uiSpikeCallTimer <= uiDiff) { m_creature->SetVisibility(VISIBILITY_ON); if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0)) { DoScriptText(EMOTE_PURSUING, m_creature, pTarget); m_creature->AddThreat(pTarget, 100000.0f); m_creature->CastSpell(pTarget, SPELL_MARK, false); m_creature->CastSpell(m_creature, SPELL_IMPALE_GROUND, false); } m_uiSpikeCallTimer = 90000; } else m_uiSpikeCallTimer -= uiDiff; if (m_uiImpaleTimer <= uiDiff) { if (m_creature->IsWithinDist(m_creature->getVictim(), 4.0f)) { m_creature->CastSpell(m_creature->getVictim(), m_bIs25Man? SPELL_IMPALE_25 : SPELL_IMPALE_10, false); m_creature->ForcedDespawn(100); float x, y, z; m_creature->GetPosition(x, y, z); m_creature->SummonCreature(NPC_SPIKE, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN, 30000); } m_uiImpaleTimer = 500; } else m_uiImpaleTimer -= uiDiff; if (m_uiPermafrostTimer <= uiDiff) { if (m_creature->HasAura(SPELL_PERMAFROST) || GetClosestCreatureWithEntry(m_creature, NPC_PERMAFROST, 5.0f)) { m_creature->RemoveAllAuras(); m_creature->ForcedDespawn(); float x, y, z; m_creature->GetPosition(x, y, z); m_creature->SummonCreature(NPC_SPIKE, x + urand(5.0f, 10.0f), y + urand(5.0f, 10.0f), z, 0, TEMPSUMMON_TIMED_DESPAWN, 30000); } m_uiPermafrostTimer = 250; } else m_uiPermafrostTimer -= uiDiff; } }; CreatureAI* GetAI_mob_anubarak_spike(Creature* pCreature) { return new mob_anubarak_spikeAI(pCreature); }; void AddSC_boss_anubarak_trial() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "boss_anubarak_trial"; pNewScript->GetAI = &GetAI_boss_anubarak_trial; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_swarm_scarab"; pNewScript->GetAI = &GetAI_mob_swarm_scarab; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_nerubian_borrower"; pNewScript->GetAI = &GetAI_mob_nerubian_borrower; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_anubarak_spike"; pNewScript->GetAI = &GetAI_mob_anubarak_spike; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_frost_sphere"; pNewScript->GetAI = &GetAI_mob_frost_sphere; pNewScript->RegisterSelf(); }
gpl-2.0
Automattic/wp-calypso
client/state/posts/utils/merge-post-edits.js
1638
import { cloneDeep, concat, find, mergeWith, reduce, reject } from 'lodash'; function mergeMetadataEdits( edits, nextEdits ) { // remove existing edits that get updated in `nextEdits` const newEdits = reject( edits, ( edit ) => find( nextEdits, { key: edit.key } ) ); // append the new edits at the end return concat( newEdits, nextEdits ); } /** * Merges an array of post edits (called 'edits log') into one object. Essentially performs * a repeated deep merge of two objects, except: * - arrays are treated as atomic values and overwritten rather than merged. * That's important especially for term removals. * - metadata edits, which are also arrays, are merged with a special algorithm. * * @param {Array<object>} postEditsLog Edits objects to be merged * @returns {object?} Merged edits object with changes from all sources */ export const mergePostEdits = ( ...postEditsLog ) => reduce( postEditsLog, ( mergedEdits, nextEdits ) => { // filter out save markers if ( typeof nextEdits === 'string' ) { return mergedEdits; } // return the input object if it's the first one to merge (optimization that avoids cloning) if ( mergedEdits === null ) { return nextEdits; } // proceed to do the merge return mergeWith( cloneDeep( mergedEdits ), nextEdits, ( objValue, srcValue, key, obj, src, stack ) => { if ( key === 'metadata' && stack.size === 0 ) { // merge metadata specially return mergeMetadataEdits( objValue, srcValue ); } if ( Array.isArray( srcValue ) ) { return srcValue; } } ); }, null );
gpl-2.0
dkrinos/ev3dev-lang-python
docs/conf.py
9439
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ev3dev documentation build configuration file, created by # sphinx-quickstart on Sat May 16 21:08:39 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from git_version import git_version # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'ev3dev' copyright = '2015, Denis Demidov <dennis.demidov@gmail.com>' author = 'Denis Demidov <dennis.demidov@gmail.com>' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.2.0' # The full version, including alpha/beta/rc tags. release = git_version() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'pyramid' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'ev3devdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'ev3dev.tex', 'ev3dev Documentation', 'Denis Demidov \\textless{}dennis.demidov@gmail.com\\textgreater{}', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'ev3dev', 'ev3dev Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'ev3dev', 'ev3dev Documentation', author, 'ev3dev', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
gpl-2.0
AcalephStorage/consul-alerts
Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go
27024
// Package v4 implements signing for AWS V4 signer // // Provides request signing for request that need to be signed with // AWS V4 Signatures. // // Standalone Signer // // Generally using the signer outside of the SDK should not require any additional // logic when using Go v1.5 or higher. The signer does this by taking advantage // of the URL.EscapedPath method. If your request URI requires additional escaping // you many need to use the URL.Opaque to define what the raw URI should be sent // to the service as. // // The signer will first check the URL.Opaque field, and use its value if set. // The signer does require the URL.Opaque field to be set in the form of: // // "//<hostname>/<path>" // // // e.g. // "//example.com/some/path" // // The leading "//" and hostname are required or the URL.Opaque escaping will // not work correctly. // // If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() // method and using the returned value. If you're using Go v1.4 you must set // URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with // Go v1.5 the signer will fallback to URL.Path. // // AWS v4 signature validation requires that the canonical string's URI path // element must be the URI escaped form of the HTTP request's path. // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html // // The Go HTTP client will perform escaping automatically on the request. Some // of these escaping may cause signature validation errors because the HTTP // request differs from the URI path or query that the signature was generated. // https://golang.org/pkg/net/url/#URL.EscapedPath // // Because of this, it is recommended that when using the signer outside of the // SDK that explicitly escaping the request prior to being signed is preferable, // and will help prevent signature validation errors. This can be done by setting // the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then // call URL.EscapedPath() if Opaque is not set. // // If signing a request intended for HTTP2 server, and you're using Go 1.6.2 // through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the // request URL. https://github.com/golang/go/issues/16847 points to a bug in // Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP // message. URL.Opaque generally will force Go to make requests with absolute URL. // URL.RawPath does not do this, but RawPath must be a valid escaping of Path // or url.EscapedPath will ignore the RawPath escaping. // // Test `TestStandaloneSign` provides a complete example of using the signer // outside of the SDK and pre-escaping the URI path. package v4 import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "net/http" "net/url" "sort" "strconv" "strings" "time" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/sdkio" "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/aws/aws-sdk-go/private/protocol/rest" ) const ( authHeaderPrefix = "AWS4-HMAC-SHA256" timeFormat = "20060102T150405Z" shortTimeFormat = "20060102" // emptyStringSHA256 is a SHA256 of an empty string emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` ) var ignoredHeaders = rules{ blacklist{ mapRule{ "Authorization": struct{}{}, "User-Agent": struct{}{}, "X-Amzn-Trace-Id": struct{}{}, }, }, } // requiredSignedHeaders is a whitelist for build canonical headers. var requiredSignedHeaders = rules{ whitelist{ mapRule{ "Cache-Control": struct{}{}, "Content-Disposition": struct{}{}, "Content-Encoding": struct{}{}, "Content-Language": struct{}{}, "Content-Md5": struct{}{}, "Content-Type": struct{}{}, "Expires": struct{}{}, "If-Match": struct{}{}, "If-Modified-Since": struct{}{}, "If-None-Match": struct{}{}, "If-Unmodified-Since": struct{}{}, "Range": struct{}{}, "X-Amz-Acl": struct{}{}, "X-Amz-Copy-Source": struct{}{}, "X-Amz-Copy-Source-If-Match": struct{}{}, "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, "X-Amz-Copy-Source-If-None-Match": struct{}{}, "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, "X-Amz-Copy-Source-Range": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Grant-Full-control": struct{}{}, "X-Amz-Grant-Read": struct{}{}, "X-Amz-Grant-Read-Acp": struct{}{}, "X-Amz-Grant-Write": struct{}{}, "X-Amz-Grant-Write-Acp": struct{}{}, "X-Amz-Metadata-Directive": struct{}{}, "X-Amz-Mfa": struct{}{}, "X-Amz-Request-Payer": struct{}{}, "X-Amz-Server-Side-Encryption": struct{}{}, "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, "X-Amz-Storage-Class": struct{}{}, "X-Amz-Website-Redirect-Location": struct{}{}, "X-Amz-Content-Sha256": struct{}{}, }, }, patterns{"X-Amz-Meta-"}, } // allowedHoisting is a whitelist for build query headers. The boolean value // represents whether or not it is a pattern. var allowedQueryHoisting = inclusiveRules{ blacklist{requiredSignedHeaders}, patterns{"X-Amz-"}, } // Signer applies AWS v4 signing to given request. Use this to sign requests // that need to be signed with AWS V4 Signatures. type Signer struct { // The authentication credentials the request will be signed against. // This value must be set to sign requests. Credentials *credentials.Credentials // Sets the log level the signer should use when reporting information to // the logger. If the logger is nil nothing will be logged. See // aws.LogLevelType for more information on available logging levels // // By default nothing will be logged. Debug aws.LogLevelType // The logger loging information will be written to. If there the logger // is nil, nothing will be logged. Logger aws.Logger // Disables the Signer's moving HTTP header key/value pairs from the HTTP // request header to the request's query string. This is most commonly used // with pre-signed requests preventing headers from being added to the // request's query string. DisableHeaderHoisting bool // Disables the automatic escaping of the URI path of the request for the // siganture's canonical string's path. For services that do not need additional // escaping then use this to disable the signer escaping the path. // // S3 is an example of a service that does not need additional escaping. // // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html DisableURIPathEscaping bool // Disales the automatical setting of the HTTP request's Body field with the // io.ReadSeeker passed in to the signer. This is useful if you're using a // custom wrapper around the body for the io.ReadSeeker and want to preserve // the Body value on the Request.Body. // // This does run the risk of signing a request with a body that will not be // sent in the request. Need to ensure that the underlying data of the Body // values are the same. DisableRequestBodyOverwrite bool // currentTimeFn returns the time value which represents the current time. // This value should only be used for testing. If it is nil the default // time.Now will be used. currentTimeFn func() time.Time // UnsignedPayload will prevent signing of the payload. This will only // work for services that have support for this. UnsignedPayload bool } // NewSigner returns a Signer pointer configured with the credentials and optional // option values provided. If not options are provided the Signer will use its // default configuration. func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { v4 := &Signer{ Credentials: credentials, } for _, option := range options { option(v4) } return v4 } type signingCtx struct { ServiceName string Region string Request *http.Request Body io.ReadSeeker Query url.Values Time time.Time ExpireTime time.Duration SignedHeaderVals http.Header DisableURIPathEscaping bool credValues credentials.Value isPresign bool formattedTime string formattedShortTime string unsignedPayload bool bodyDigest string signedHeaders string canonicalHeaders string canonicalString string credentialString string stringToSign string signature string authorization string } // Sign signs AWS v4 requests with the provided body, service name, region the // request is made to, and time the request is signed at. The signTime allows // you to specify that a request is signed for the future, and cannot be // used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. Generally for signed requests this value // is not needed as the full request context will be captured by the http.Request // value. It is included for reference though. // // Sign will set the request's Body to be the `body` parameter passed in. If // the body is not already an io.ReadCloser, it will be wrapped within one. If // a `nil` body parameter passed to Sign, the request's Body field will be // also set to nil. Its important to note that this functionality will not // change the request's ContentLength of the request. // // Sign differs from Presign in that it will sign the request using HTTP // header values. This type of signing is intended for http.Request values that // will not be shared, or are shared in a way the header values on the request // will not be lost. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, 0, false, signTime) } // Presign signs AWS v4 requests with the provided body, service name, region // the request is made to, and time the request is signed at. The signTime // allows you to specify that a request is signed for the future, and cannot // be used until then. // // Returns a list of HTTP headers that were included in the signature or an // error if signing the request failed. For presigned requests these headers // and their values must be included on the HTTP request when it is made. This // is helpful to know what header values need to be shared with the party the // presigned request will be distributed to. // // Presign differs from Sign in that it will sign the request using query string // instead of header values. This allows you to share the Presigned Request's // URL with third parties, or distribute it throughout your system with minimal // dependencies. // // Presign also takes an exp value which is the duration the // signed request will be valid after the signing time. This is allows you to // set when the request will expire. // // The requests body is an io.ReadSeeker so the SHA256 of the body can be // generated. To bypass the signer computing the hash you can set the // "X-Amz-Content-Sha256" header with a precomputed value. The signer will // only compute the hash if the request header value is empty. // // Presigning a S3 request will not compute the body's SHA256 hash by default. // This is done due to the general use case for S3 presigned URLs is to share // PUT/GET capabilities. If you would like to include the body's SHA256 in the // presigned request's signature you can set the "X-Amz-Content-Sha256" // HTTP header and that will be included in the request's signature. func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { return v4.signWithBody(r, body, service, region, exp, true, signTime) } func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { currentTimeFn := v4.currentTimeFn if currentTimeFn == nil { currentTimeFn = time.Now } ctx := &signingCtx{ Request: r, Body: body, Query: r.URL.Query(), Time: signTime, ExpireTime: exp, isPresign: isPresign, ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, unsignedPayload: v4.UnsignedPayload, } for key := range ctx.Query { sort.Strings(ctx.Query[key]) } if ctx.isRequestSigned() { ctx.Time = currentTimeFn() ctx.handlePresignRemoval() } var err error ctx.credValues, err = v4.Credentials.Get() if err != nil { return http.Header{}, err } ctx.sanitizeHostForHeader() ctx.assignAmzQueryValues() if err := ctx.build(v4.DisableHeaderHoisting); err != nil { return nil, err } // If the request is not presigned the body should be attached to it. This // prevents the confusion of wanting to send a signed request without // the body the request was signed for attached. if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { var reader io.ReadCloser if body != nil { var ok bool if reader, ok = body.(io.ReadCloser); !ok { reader = ioutil.NopCloser(body) } } r.Body = reader } if v4.Debug.Matches(aws.LogDebugWithSigning) { v4.logSigningInfo(ctx) } return ctx.SignedHeaderVals, nil } func (ctx *signingCtx) sanitizeHostForHeader() { request.SanitizeHostForHeader(ctx.Request) } func (ctx *signingCtx) handlePresignRemoval() { if !ctx.isPresign { return } // The credentials have expired for this request. The current signing // is invalid, and needs to be request because the request will fail. ctx.removePresign() // Update the request's query string to ensure the values stays in // sync in the case retrieving the new credentials fails. ctx.Request.URL.RawQuery = ctx.Query.Encode() } func (ctx *signingCtx) assignAmzQueryValues() { if ctx.isPresign { ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) if ctx.credValues.SessionToken != "" { ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } else { ctx.Query.Del("X-Amz-Security-Token") } return } if ctx.credValues.SessionToken != "" { ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) } } // SignRequestHandler is a named request handler the SDK will use to sign // service client request with using the V4 signature. var SignRequestHandler = request.NamedHandler{ Name: "v4.SignRequestHandler", Fn: SignSDKRequest, } // SignSDKRequest signs an AWS request with the V4 signature. This // request handler should only be used with the SDK's built in service client's // API operation requests. // // This function should not be used on its on its own, but in conjunction with // an AWS service client's API operation call. To sign a standalone request // not created by a service client's API operation method use the "Sign" or // "Presign" functions of the "Signer" type. // // If the credentials of the request's config are set to // credentials.AnonymousCredentials the request will not be signed. func SignSDKRequest(req *request.Request) { signSDKRequestWithCurrTime(req, time.Now) } // BuildNamedHandler will build a generic handler for signing. func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { return request.NamedHandler{ Name: name, Fn: func(req *request.Request) { signSDKRequestWithCurrTime(req, time.Now, opts...) }, } } func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { return } region := req.ClientInfo.SigningRegion if region == "" { region = aws.StringValue(req.Config.Region) } name := req.ClientInfo.SigningName if name == "" { name = req.ClientInfo.ServiceName } v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { v4.Debug = req.Config.LogLevel.Value() v4.Logger = req.Config.Logger v4.DisableHeaderHoisting = req.NotHoist v4.currentTimeFn = curTimeFn if name == "s3" { // S3 service should not have any escaping applied v4.DisableURIPathEscaping = true } // Prevents setting the HTTPRequest's Body. Since the Body could be // wrapped in a custom io.Closer that we do not want to be stompped // on top of by the signer. v4.DisableRequestBodyOverwrite = true }) for _, opt := range opts { opt(v4) } signingTime := req.Time if !req.LastSignedAt.IsZero() { signingTime = req.LastSignedAt } signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), name, region, req.ExpireTime, req.ExpireTime > 0, signingTime, ) if err != nil { req.Error = err req.SignedHeaderVals = nil return } req.SignedHeaderVals = signedHeaders req.LastSignedAt = curTimeFn() } const logSignInfoMsg = `DEBUG: Request Signature: ---[ CANONICAL STRING ]----------------------------- %s ---[ STRING TO SIGN ]-------------------------------- %s%s -----------------------------------------------------` const logSignedURLMsg = ` ---[ SIGNED URL ]------------------------------------ %s` func (v4 *Signer) logSigningInfo(ctx *signingCtx) { signedURLMsg := "" if ctx.isPresign { signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) } msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) v4.Logger.Log(msg) } func (ctx *signingCtx) build(disableHeaderHoisting bool) error { ctx.buildTime() // no depends ctx.buildCredentialString() // no depends if err := ctx.buildBodyDigest(); err != nil { return err } unsignedHeaders := ctx.Request.Header if ctx.isPresign { if !disableHeaderHoisting { urlValues := url.Values{} urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends for k := range urlValues { ctx.Query[k] = urlValues[k] } } } ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) ctx.buildCanonicalString() // depends on canon headers / signed headers ctx.buildStringToSign() // depends on canon string ctx.buildSignature() // depends on string to sign if ctx.isPresign { ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature } else { parts := []string{ authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, "SignedHeaders=" + ctx.signedHeaders, "Signature=" + ctx.signature, } ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) } return nil } func (ctx *signingCtx) buildTime() { ctx.formattedTime = ctx.Time.UTC().Format(timeFormat) ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat) if ctx.isPresign { duration := int64(ctx.ExpireTime / time.Second) ctx.Query.Set("X-Amz-Date", ctx.formattedTime) ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) } else { ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime) } } func (ctx *signingCtx) buildCredentialString() { ctx.credentialString = strings.Join([]string{ ctx.formattedShortTime, ctx.Region, ctx.ServiceName, "aws4_request", }, "/") if ctx.isPresign { ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) } } func buildQuery(r rule, header http.Header) (url.Values, http.Header) { query := url.Values{} unsignedHeaders := http.Header{} for k, h := range header { if r.IsValid(k) { query[k] = h } else { unsignedHeaders[k] = h } } return query, unsignedHeaders } func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { var headers []string headers = append(headers, "host") for k, v := range header { canonicalKey := http.CanonicalHeaderKey(k) if !r.IsValid(canonicalKey) { continue // ignored header } if ctx.SignedHeaderVals == nil { ctx.SignedHeaderVals = make(http.Header) } lowerCaseKey := strings.ToLower(k) if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { // include additional values ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) continue } headers = append(headers, lowerCaseKey) ctx.SignedHeaderVals[lowerCaseKey] = v } sort.Strings(headers) ctx.signedHeaders = strings.Join(headers, ";") if ctx.isPresign { ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) } headerValues := make([]string, len(headers)) for i, k := range headers { if k == "host" { if ctx.Request.Host != "" { headerValues[i] = "host:" + ctx.Request.Host } else { headerValues[i] = "host:" + ctx.Request.URL.Host } } else { headerValues[i] = k + ":" + strings.Join(ctx.SignedHeaderVals[k], ",") } } stripExcessSpaces(headerValues) ctx.canonicalHeaders = strings.Join(headerValues, "\n") } func (ctx *signingCtx) buildCanonicalString() { ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) uri := getURIPath(ctx.Request.URL) if !ctx.DisableURIPathEscaping { uri = rest.EscapePath(uri, false) } ctx.canonicalString = strings.Join([]string{ ctx.Request.Method, uri, ctx.Request.URL.RawQuery, ctx.canonicalHeaders + "\n", ctx.signedHeaders, ctx.bodyDigest, }, "\n") } func (ctx *signingCtx) buildStringToSign() { ctx.stringToSign = strings.Join([]string{ authHeaderPrefix, ctx.formattedTime, ctx.credentialString, hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))), }, "\n") } func (ctx *signingCtx) buildSignature() { secret := ctx.credValues.SecretAccessKey date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime)) region := makeHmac(date, []byte(ctx.Region)) service := makeHmac(region, []byte(ctx.ServiceName)) credentials := makeHmac(service, []byte("aws4_request")) signature := makeHmac(credentials, []byte(ctx.stringToSign)) ctx.signature = hex.EncodeToString(signature) } func (ctx *signingCtx) buildBodyDigest() error { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { includeSHA256Header := ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" s3Presign := ctx.isPresign && ctx.ServiceName == "s3" if ctx.unsignedPayload || s3Presign { hash = "UNSIGNED-PAYLOAD" includeSHA256Header = !s3Presign } else if ctx.Body == nil { hash = emptyStringSHA256 } else { if !aws.IsReaderSeekable(ctx.Body) { return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) } hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) } if includeSHA256Header { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } ctx.bodyDigest = hash return nil } // isRequestSigned returns if the request is currently signed or presigned func (ctx *signingCtx) isRequestSigned() bool { if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { return true } if ctx.Request.Header.Get("Authorization") != "" { return true } return false } // unsign removes signing flags for both signed and presigned requests. func (ctx *signingCtx) removePresign() { ctx.Query.Del("X-Amz-Algorithm") ctx.Query.Del("X-Amz-Signature") ctx.Query.Del("X-Amz-Security-Token") ctx.Query.Del("X-Amz-Date") ctx.Query.Del("X-Amz-Expires") ctx.Query.Del("X-Amz-Credential") ctx.Query.Del("X-Amz-SignedHeaders") } func makeHmac(key []byte, data []byte) []byte { hash := hmac.New(sha256.New, key) hash.Write(data) return hash.Sum(nil) } func makeSha256(data []byte) []byte { hash := sha256.New() hash.Write(data) return hash.Sum(nil) } func makeSha256Reader(reader io.ReadSeeker) []byte { hash := sha256.New() start, _ := reader.Seek(0, sdkio.SeekCurrent) defer reader.Seek(start, sdkio.SeekStart) io.Copy(hash, reader) return hash.Sum(nil) } const doubleSpace = " " // stripExcessSpaces will rewrite the passed in slice's string values to not // contain muliple side-by-side spaces. func stripExcessSpaces(vals []string) { var j, k, l, m, spaces int for i, str := range vals { // Trim trailing spaces for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { } // Trim leading spaces for k = 0; k < j && str[k] == ' '; k++ { } str = str[k : j+1] // Strip multiple spaces. j = strings.Index(str, doubleSpace) if j < 0 { vals[i] = str continue } buf := []byte(str) for k, m, l = j, j, len(buf); k < l; k++ { if buf[k] == ' ' { if spaces == 0 { // First space. buf[m] = buf[k] m++ } spaces++ } else { // End of multiple spaces. spaces = 0 buf[m] = buf[k] m++ } } vals[i] = string(buf[:m]) } }
gpl-2.0
adster101/French-Connections-
administrator/components/com_rental/models/fields/tariff_1.php
1841
<?php /** * @package Joomla.Platform * @subpackage Form * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Form Field class for the Joomla Platform. * Supports a one line text field. * * @package Joomla.Platform * @subpackage Form * @link http://www.w3.org/TR/html-markup/input.text.html#input.text * @since 11.1 */ class JFormFieldText extends JFormField { /** * The form field type. * * @var string * * @since 11.1 */ protected $type = 'Text'; /** * Method to get the field input markup. * * @return string The field input markup. * * @since 11.1 */ protected function getInput() { // Initialize some field attributes. $size = $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : ''; $this->multiple = true; $maxLength = $this->element['maxlength'] ? ' maxlength="' . (int) $this->element['maxlength'] . '"' : ''; $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $readonly = ((string) $this->element['readonly'] == 'true') ? ' readonly="readonly"' : ''; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $required = $this->required ? ' required="required" aria-required="true"' : ''; // Initialize JavaScript field attributes. $onchange = $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : ''; return '<input type="text" name="' . $this->name . '[]" id="' . $this->id . '" value="' . htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . $class . $size . $disabled . $readonly . $onchange . $maxLength . $required . '/>'; } }
gpl-2.0
mmacedoeu/adf_gcli
Model/src/br/com/br/gatend/GestaoCliente/v1/model/am/ClientesAMImpl.java
16680
package br.com.br.gatend.GestaoCliente.v1.model.am; import br.com.br.gatend.GestaoCliente.v1.model.am.common.ClientesAM; import br.com.br.gatend.GestaoCliente.v1.model.to.DadosClienteTO; import br.com.br.gatend.GestaoCliente.v1.model.vo.ArLocationValuesVImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.ConsultaClientesVOImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.FndLookUpValuesVLU707GcOrigemClienteVVOImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.FndLookUpValuesVLU707GcPerfilClienteVVOImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.ListaChecklistVOImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.U536BrRolesMenuVVOImpl; import br.com.br.gatend.GestaoCliente.v1.model.vo.U536BrRolesMenuVVORowImpl; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import oracle.jbo.Row; import oracle.jbo.ViewCriteria; import oracle.jbo.server.ApplicationModuleImpl; import oracle.jbo.server.ViewObjectImpl; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Thu Jul 03 15:39:54 BRT 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class ClientesAMImpl extends ApplicationModuleImpl implements ClientesAM { public ClientesAMImpl() { } /** * This is the default constructor (do not remove). */ private static String ROLE_GESTAO_CLIENTE = "Role Gestão de Clientes"; private DadosClienteTO dados; /** * Method responsible for turning on Object Text * * @param objeto * @return String object */ public static String parseTexto(Object objeto) { String texto = ""; try { if (objeto != null) { texto = objeto.toString(); } } catch (Exception e) { return ""; } return texto; } public String localizarPaisCliente(Map parametros) { String pais = ""; ArLocationValuesVImpl vo = this.getArLocationValuesV1(); ViewCriteria viewCriteria = vo.getViewCriteria("ArLocationValuesVCriteria"); vo.applyViewCriteria(viewCriteria); vo.setNamedWhereClauseParam("sigla", parseTexto(parametros.get("siglaPais"))); vo.executeQuery(); if (vo.getRowCount() > 0) { Row row = vo.getRowAtRangeIndex(0); pais = parseTexto(row.getAttribute("LocationSegmentDescription")); } return pais; } /** * Method responsible for locating clients from filter parameters * * @param parametros */ public boolean localizarClientes(Map parametros) { ConsultaClientesVOImpl vo = this.getConsultaClientesVO1(); vo.setWhereClause(filterConsultaCliente(parametros)); vo.executeQuery(); if(vo.getRowCount() <= 0) { return false; } return true; } public Map localizarClientePeloCodigoR3(Map parametros) { String codigoR3 = String.valueOf(parametros.get("codigoR3")); HttpSession session = (HttpSession) parametros.get("session"); Map<String, Object> map = new HashMap<String, Object>(); ConsultaClientesVOImpl vo = this.getConsultaClientesVO1(); vo.setWhereClause("CODIGO_R3 = '"+codigoR3+"'"); vo.executeQuery(); if(vo.getRowCount() == 1) { Row row = vo.getCurrentRow(); session.setAttribute("codigoR3", parseTexto(row.getAttribute("CodigoR3"))); session.setAttribute("razaoSocial", parseTexto(row.getAttribute("RazaoSocial"))); session.setAttribute("tipoCliente", parseTexto(row.getAttribute("TipoCliente"))); session.setAttribute("logradouro", parseTexto(row.getAttribute("Logradouro"))); session.setAttribute("bairro", parseTexto(row.getAttribute("Bairro"))); session.setAttribute("cidade", parseTexto(row.getAttribute("Cidade"))); session.setAttribute("estado", parseTexto(row.getAttribute("Estado"))); session.setAttribute("origem", parseTexto(row.getAttribute("Origem"))); session.setAttribute("perfil", parseTexto(row.getAttribute("Perfil"))); session.setAttribute("principal", parseTexto(row.getAttribute("Principal"))); session.setAttribute("quadra", parseTexto(row.getAttribute("Quadra"))); session.setAttribute("lote", parseTexto(row.getAttribute("Lote"))); session.setAttribute("numero", parseTexto(row.getAttribute("Numero"))); session.setAttribute("complemento", parseTexto(row.getAttribute("Complemento"))); session.setAttribute("cep", parseTexto(row.getAttribute("Cep"))); session.setAttribute("pais", parseTexto(row.getAttribute("Pais"))); session.setAttribute("partySiteId", parseTexto(row.getAttribute("PartySiteId"))); map.put("session", session); } return map; } /** * Method responsible to assemble and execute the Query Guest filter * * @param parametros * @return String object */ public String filterConsultaCliente(Map parametros) { String perfilChoice = (String) parametros.get("perfilChoice"); String perfil = (String) parametros.get("perfil"); String razaoChoice = (String) parametros.get("razaoSocialChoice"); String razaoSocial = (String) parametros.get("razaoSocial"); String tipoChoiceC = (String) parametros.get("tipoClienteChoice"); String tipoCliente = (String) parametros.get("tipoCliente"); String codR3Choice = (String) parametros.get("codigoR3Choice"); String codigoR3 = (String) parametros.get("codigoR3"); String bairroChoice = (String) parametros.get("bairroChoice"); String bairroCliente = (String) parametros.get("bairroCliente"); String cidadeChoice = (String) parametros.get("cidadeChoice"); String cidadeCliente = (String) parametros.get("cidadeCliente"); String enderecoChoice = (String) parametros.get("enderecoChoice"); String enderecoCliente = (String) parametros.get("enderecoCliente"); String estadoChoice = (String) parametros.get("estadoChoice"); String estadoCliente = (String) parametros.get("estadoCliente"); String origemChoice = (String) parametros.get("origemChoice"); String origemCliente = (String) parametros.get("origemCliente"); String principalChoice = (String) parametros.get("principalChoice"); String principalCliente = (String) parametros.get("principalCliente"); StringBuilder query = new StringBuilder(); //Condições Igual a if (perfilChoice.equalsIgnoreCase("0")) { query.append(" PERFIL = '" + perfil + "'"); } if (tipoChoiceC.equalsIgnoreCase("0") && !tipoCliente.isEmpty()) { query.append(" AND TIPO_CLIENTE LIKE '%" + tipoCliente + "%'"); } if (razaoChoice.equalsIgnoreCase("0") && !razaoSocial.isEmpty()) { query.append(" AND RAZAO_SOCIAL LIKE '%" + razaoSocial.toUpperCase() + "%'"); } if (codR3Choice.equalsIgnoreCase("0") && !codigoR3.isEmpty()) { query.append(" AND CODIGO_R3 LIKE '%" + codigoR3 + "%'"); } if (parametros.containsKey("bairroChoice") && bairroChoice.equalsIgnoreCase("0")) { query.append(" AND BAIRRO LIKE '%" + bairroCliente.toUpperCase() + "%'"); } if (parametros.containsKey("cidadeChoice") && cidadeChoice.equalsIgnoreCase("0")) { query.append(" AND CIDADE LIKE '%" + cidadeCliente.toUpperCase() + "%'"); } if (parametros.containsKey("enderecoChoice") && enderecoChoice.equalsIgnoreCase("0")) { query.append(" AND ENDERECO LIKE '%" + enderecoCliente.toUpperCase() + "%'"); } if (parametros.containsKey("estadoChoice") && estadoChoice.equalsIgnoreCase("0")) { query.append(" AND ESTADO LIKE '%" + estadoCliente.toUpperCase() + "%'"); } if (parametros.containsKey("origemChoice") && origemChoice.equalsIgnoreCase("0")) { query.append(" AND ORIGEM LIKE '%" + origemCliente + "%'"); } if (parametros.containsKey("principalChoice") && principalChoice.equalsIgnoreCase("0")) { query.append(" AND PRINCIPAL LIKE '%" + principalCliente + "%'"); } //Condições Começa com if (tipoChoiceC.equalsIgnoreCase("1") && !tipoCliente.isEmpty()) { query.append(" AND TIPO_CLIENTE_BASICO LIKE '" + tipoCliente + "%'"); } if (razaoChoice.equalsIgnoreCase("1") && !razaoSocial.isEmpty()) { query.append(" AND RAZAO_SOCIAL LIKE '" + razaoSocial.toUpperCase() + "%'"); } if (codR3Choice.equalsIgnoreCase("1") && !codigoR3.isEmpty()) { query.append(" AND CODIGO_R3 LIKE '" + codigoR3 + "%'"); } if (parametros.containsKey("bairroChoice") && bairroChoice.equalsIgnoreCase("1")) { query.append(" AND BAIRRO LIKE '" + bairroCliente.toUpperCase() + "%'"); } if (parametros.containsKey("cidadeChoice") && cidadeChoice.equalsIgnoreCase("1")) { query.append(" AND CIDADE LIKE '" + cidadeCliente.toUpperCase() + "%'"); } if (parametros.containsKey("enderecoChoice") && enderecoChoice.equalsIgnoreCase("1")) { query.append(" AND ENDERECO LIKE '" + enderecoCliente.toUpperCase() + "%'"); } if (parametros.containsKey("estadoChoice") && estadoChoice.equalsIgnoreCase("1")) { query.append(" AND ESTADO LIKE '" + estadoCliente.toUpperCase() + "%'"); } if (parametros.containsKey("origemChoice") && origemChoice.equalsIgnoreCase("1")) { query.append(" AND ORIGEM LIKE '" + origemCliente + "%'"); } if (parametros.containsKey("principalChoice") && principalChoice.equalsIgnoreCase("1")) { query.append(" AND PRINCIPAL LIKE '" + principalCliente + "%'"); } //Condições Termina com if (tipoChoiceC.equalsIgnoreCase("2") && !tipoCliente.isEmpty()) { query.append(" AND TIPO_CLIENTE_DIGITO LIKE '%" + tipoCliente + "'"); } if (razaoChoice.equalsIgnoreCase("2") && !razaoSocial.isEmpty()) { query.append(" AND RAZAO_SOCIAL LIKE '%" + razaoSocial.toUpperCase() + "'"); } if (codR3Choice.equalsIgnoreCase("2") && !codigoR3.isEmpty()) { query.append(" AND CODIGO_R3 LIKE '%" + codigoR3 + "'"); } if (parametros.containsKey("bairroChoice") && bairroChoice.equalsIgnoreCase("2")) { query.append(" AND BAIRRO LIKE '%" + bairroCliente.toUpperCase() + "'"); } if (parametros.containsKey("cidadeChoice") && cidadeChoice.equalsIgnoreCase("2")) { query.append(" AND CIDADE LIKE '%" + cidadeCliente.toUpperCase() + "'"); } if (parametros.containsKey("enderecoChoice") && enderecoChoice.equalsIgnoreCase("2")) { query.append(" AND ENDERECO LIKE '%" + enderecoCliente.toUpperCase() + "'"); } if (parametros.containsKey("estadoChoice") && estadoChoice.equalsIgnoreCase("2")) { query.append(" AND ESTADO LIKE '%" + estadoCliente.toUpperCase() + "'"); } if (parametros.containsKey("origemChoice") && origemChoice.equalsIgnoreCase("2")) { query.append(" AND ORIGEM LIKE '%" + origemCliente + "'"); } if (parametros.containsKey("principalChoice") && principalChoice.equalsIgnoreCase("2")) { query.append(" AND PRINCIPAL LIKE '%" + principalCliente + "'"); } return query.toString(); } /** * Method check the source responsible for user from the Role Access * * @return Boolean Object (true or false) */ public boolean consultaOrigem() { FndLookUpValuesVLU707GcOrigemClienteVVOImpl vo = this.getFndLookUpValuesVLU707GcOrigemClienteVVO1(); vo.executeQuery(); while (vo.hasNext()) { U536BrRolesMenuVVORowImpl row = (U536BrRolesMenuVVORowImpl) vo.next(); String roleUsuario = parseTexto(row.getAttribute("RoleName")); if (ROLE_GESTAO_CLIENTE.equalsIgnoreCase(roleUsuario)) { return true; } } return false; } /** * Container's getter for FndLookupValue1. * @return FndLookupValue1 */ public ViewObjectImpl getFndLookupValue1() { return (ViewObjectImpl) findViewObject("FndLookupValue1"); } /** * Container's getter for ConsultaClientesVO1. * @return ConsultaClientesVO1 */ public ConsultaClientesVOImpl getConsultaClientesVO1() { return (ConsultaClientesVOImpl) findViewObject("ConsultaClientesVO1"); } /** * Container's getter for OrigemVo1. * @return OrigemVo1 */ public ViewObjectImpl getOrigemVo1() { return (ViewObjectImpl) findViewObject("OrigemVo1"); } /** * Container's getter for PrincipalVo1. * @return PrincipalVo1 */ public ViewObjectImpl getPrincipalVo1() { return (ViewObjectImpl) findViewObject("PrincipalVo1"); } /** * Container's getter for FndLookUpValuesVLU707GcPerfilClienteVVO1. * @return FndLookUpValuesVLU707GcPerfilClienteVVO1 */ public FndLookUpValuesVLU707GcPerfilClienteVVOImpl getFndLookUpValuesVLU707GcPerfilClienteVVO1() { return (FndLookUpValuesVLU707GcPerfilClienteVVOImpl) findViewObject("FndLookUpValuesVLU707GcPerfilClienteVVO1"); } /** * Container's getter for FndLookUpValuesVLU707GcOrigemClienteVVO1. * @return FndLookUpValuesVLU707GcOrigemClienteVVO1 */ public FndLookUpValuesVLU707GcOrigemClienteVVOImpl getFndLookUpValuesVLU707GcOrigemClienteVVO1() { return (FndLookUpValuesVLU707GcOrigemClienteVVOImpl) findViewObject("FndLookUpValuesVLU707GcOrigemClienteVVO1"); } /** * Container's getter for U536BrRolesMenuVVO1. * @return U536BrRolesMenuVVO1 */ public U536BrRolesMenuVVOImpl getU536BrRolesMenuVVO1() { return (U536BrRolesMenuVVOImpl) findViewObject("U536BrRolesMenuVVO1"); } @Override public boolean validaPrivilegioAcessoClientes(Map parametros) { U536BrRolesMenuVVOImpl vo = this.getU536BrRolesMenuVVO1(); ViewCriteria viewCriteria = vo.getViewCriteria("VerificaPrivilegioCriteria"); vo.applyViewCriteria(viewCriteria); vo.setNamedWhereClauseParam("chaveUsuario", parseTexto(parametros.get("chaveUsuario"))); vo.executeQuery(); try { if (vo.getRowCount() > 0) { Row row = vo.getRowAtRangeIndex(0); if(ROLE_GESTAO_CLIENTE.equalsIgnoreCase(parseTexto(row.getAttribute("RoleName")))) { return true; } } } catch(Exception e) { return false; } return false; } /** * Container's getter for ArLocationValuesV1. * @return ArLocationValuesV1 */ public ArLocationValuesVImpl getArLocationValuesV1() { return (ArLocationValuesVImpl) findViewObject("ArLocationValuesV1"); } /** * Container's getter for ListaChecklistVO1. * @return ListaChecklistVO1 */ public ListaChecklistVOImpl getListaChecklistVO1() { return (ListaChecklistVOImpl) findViewObject("ListaChecklistVO1"); } /** * Container's getter for FndLookupGerDirVO1. * @return FndLookupGerDirVO1 */ public ViewObjectImpl getFndLookupGerDirVO1() { return (ViewObjectImpl) findViewObject("FndLookupGerDirVO1"); } /** * Container's getter for FndFormaTratamentoVO1. * @return FndFormaTratamentoVO1 */ public ViewObjectImpl getFndFormaTratamentoVO1() { return (ViewObjectImpl) findViewObject("FndFormaTratamentoVO1"); } }
gpl-2.0
espertechinc/nesper
src/NEsper.Common/common/internal/epl/expression/time/eval/TimePeriodComputeNCGivenExprEval.cs
4290
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2019 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using com.espertech.esper.common.client; using com.espertech.esper.common.@internal.epl.expression.core; using com.espertech.esper.common.@internal.epl.expression.time.abacus; using com.espertech.esper.common.@internal.epl.expression.time.node; using com.espertech.esper.common.@internal.schedule; namespace com.espertech.esper.common.@internal.epl.expression.time.eval { public class TimePeriodComputeNCGivenExprEval : TimePeriodCompute { private ExprEvaluator secondsEvaluator; private TimeAbacus timeAbacus; public TimePeriodComputeNCGivenExprEval() { } public TimePeriodComputeNCGivenExprEval( ExprEvaluator secondsEvaluator, TimeAbacus timeAbacus) { this.secondsEvaluator = secondsEvaluator; this.timeAbacus = timeAbacus; } public ExprEvaluator SecondsEvaluator { get => secondsEvaluator; set => secondsEvaluator = value; } public TimeAbacus TimeAbacus { get => timeAbacus; set => timeAbacus = value; } public long DeltaAdd( long fromTime, EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext context) { return Eval(eventsPerStream, isNewData, context); } public long DeltaSubtract( long fromTime, EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext context) { return Eval(eventsPerStream, isNewData, context); } public TimePeriodDeltaResult DeltaAddWReference( long fromTime, long reference, EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext context) { var delta = Eval(eventsPerStream, isNewData, context); return new TimePeriodDeltaResult(TimePeriodUtil.DeltaAddWReference(fromTime, reference, delta), reference); } public long DeltaUseRuntimeTime( EventBean[] eventsPerStream, ExprEvaluatorContext context, TimeProvider timeProvider) { return Eval(eventsPerStream, true, context); } public TimePeriodProvide GetNonVariableProvide(ExprEvaluatorContext context) { var msec = Eval(null, true, context); return new TimePeriodComputeConstGivenDeltaEval(msec); } public TimePeriodComputeNCGivenExprEval SetSecondsEvaluator(ExprEvaluator secondsEvaluator) { this.secondsEvaluator = secondsEvaluator; return this; } public TimePeriodComputeNCGivenExprEval SetTimeAbacus(TimeAbacus timeAbacus) { this.timeAbacus = timeAbacus; return this; } private long Eval( EventBean[] eventsPerStream, bool isNewData, ExprEvaluatorContext context) { var time = secondsEvaluator.Evaluate(eventsPerStream, isNewData, context); if (!ExprTimePeriodUtil.ValidateTime(time, timeAbacus)) { throw new EPException( ExprTimePeriodUtil.GetTimeInvalidMsg( "Invalid time computation result", time == null ? "null" : time.ToString(), time)); } return timeAbacus.DeltaForSecondsNumber(time); } } } // end of namespace
gpl-2.0
lamsfoundation/lams
3rdParty_sources/mysql-connector/com/mysql/cj/jdbc/WrapperBase.java
5019
/* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 2.0, as published by the * Free Software Foundation. * * This program is also distributed with certain software (including but not * limited to OpenSSL) that is licensed under separate terms, as designated in a * particular file or component or in included license documentation. The * authors of MySQL hereby grant you an additional permission to link the * program and your derivative works with the separately licensed software that * they have included with MySQL. * * Without limiting anything contained in the foregoing, this file, which is * part of MySQL Connector/J, is also subject to the Universal FOSS Exception, * version 1.0, a copy of which can be found at * http://oss.oracle.com/licenses/universal-foss-exception. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, * for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.cj.jdbc; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.SQLException; import java.util.Map; import com.mysql.cj.exceptions.ExceptionInterceptor; import com.mysql.cj.exceptions.MysqlErrorNumbers; import com.mysql.cj.util.Util; /** * Base class for all wrapped instances created by LogicalHandle */ abstract class WrapperBase { protected MysqlPooledConnection pooledConnection; /** * Fires connection error event if required, before re-throwing exception * * @param sqlEx * the SQLException that has occurred * @throws SQLException * (rethrown) */ protected void checkAndFireConnectionError(SQLException sqlEx) throws SQLException { if (this.pooledConnection != null) { if (MysqlErrorNumbers.SQL_STATE_COMMUNICATION_LINK_FAILURE.equals(sqlEx.getSQLState())) { this.pooledConnection.callConnectionEventListeners(MysqlPooledConnection.CONNECTION_ERROR_EVENT, sqlEx); } } throw sqlEx; } protected Map<Class<?>, Object> unwrappedInterfaces = null; protected ExceptionInterceptor exceptionInterceptor; protected WrapperBase(MysqlPooledConnection pooledConnection) { this.pooledConnection = pooledConnection; this.exceptionInterceptor = this.pooledConnection.getExceptionInterceptor(); } protected class ConnectionErrorFiringInvocationHandler implements InvocationHandler { Object invokeOn = null; public ConnectionErrorFiringInvocationHandler(Object toInvokeOn) { this.invokeOn = toInvokeOn; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("equals".equals(method.getName())) { // Let args[0] "unwrap" to its InvocationHandler if it is a proxy. return args[0].equals(this); } Object result = null; try { result = method.invoke(this.invokeOn, args); if (result != null) { result = proxyIfInterfaceIsJdbc(result, result.getClass()); } } catch (InvocationTargetException e) { if (e.getTargetException() instanceof SQLException) { checkAndFireConnectionError((SQLException) e.getTargetException()); } else { throw e; } } return result; } /** * Recursively checks for interfaces on the given object to determine * if it implements a java.sql interface, and if so, proxies the * instance so that we can catch and fire SQL errors. * * @param toProxy * @param clazz */ private Object proxyIfInterfaceIsJdbc(Object toProxy, Class<?> clazz) { Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> iclass : interfaces) { String packageName = Util.getPackageName(iclass); if ("java.sql".equals(packageName) || "javax.sql".equals(packageName)) { return Proxy.newProxyInstance(toProxy.getClass().getClassLoader(), interfaces, new ConnectionErrorFiringInvocationHandler(toProxy)); } return proxyIfInterfaceIsJdbc(toProxy, iclass); } return toProxy; } } }
gpl-2.0
vjeko/gnome-shell-3.14.4
js/ui/messageTray.js
120198
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const GLib = imports.gi.GLib; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const GnomeDesktop = imports.gi.GnomeDesktop; const Atk = imports.gi.Atk; const Lang = imports.lang; const Mainloop = imports.mainloop; const Meta = imports.gi.Meta; const Pango = imports.gi.Pango; const Shell = imports.gi.Shell; const Signals = imports.signals; const St = imports.gi.St; const Tp = imports.gi.TelepathyGLib; const EdgeDragAction = imports.ui.edgeDragAction; const BoxPointer = imports.ui.boxpointer; const CtrlAltTab = imports.ui.ctrlAltTab; const GnomeSession = imports.misc.gnomeSession; const GrabHelper = imports.ui.grabHelper; const Lightbox = imports.ui.lightbox; const Main = imports.ui.main; const PointerWatcher = imports.ui.pointerWatcher; const PopupMenu = imports.ui.popupMenu; const Params = imports.misc.params; const Tweener = imports.ui.tweener; const Util = imports.misc.util; const ViewSelector = imports.ui.viewSelector; const SHELL_KEYBINDINGS_SCHEMA = 'org.gnome.shell.keybindings'; const ANIMATION_TIME = 0.2; const NOTIFICATION_TIMEOUT = 4; const SUMMARY_TIMEOUT = 1; const LONGER_SUMMARY_TIMEOUT = 4; const HIDE_TIMEOUT = 0.2; const LONGER_HIDE_TIMEOUT = 0.6; // We delay hiding of the tray if the mouse is within MOUSE_LEFT_ACTOR_THRESHOLD // range from the point where it left the tray. const MOUSE_LEFT_ACTOR_THRESHOLD = 20; // Time the user needs to leave the mouse on the bottom pixel row to open the tray const TRAY_DWELL_TIME = 1000; // ms // Time resolution when tracking the mouse to catch the open tray dwell const TRAY_DWELL_CHECK_INTERVAL = 100; // ms const IDLE_TIME = 1000; const State = { HIDDEN: 0, SHOWING: 1, SHOWN: 2, HIDING: 3 }; // These reasons are useful when we destroy the notifications received through // the notification daemon. We use EXPIRED for transient notifications that the // user did not interact with, DISMISSED for all other notifications that were // destroyed as a result of a user action, and SOURCE_CLOSED for the notifications // that were requested to be destroyed by the associated source. const NotificationDestroyedReason = { EXPIRED: 1, DISMISSED: 2, SOURCE_CLOSED: 3 }; // Message tray has its custom Urgency enumeration. LOW, NORMAL and CRITICAL // urgency values map to the corresponding values for the notifications received // through the notification daemon. HIGH urgency value is used for chats received // through the Telepathy client. const Urgency = { LOW: 0, NORMAL: 1, HIGH: 2, CRITICAL: 3 }; function _fixMarkup(text, allowMarkup) { if (allowMarkup) { // Support &amp;, &quot;, &apos;, &lt; and &gt;, escape all other // occurrences of '&'. let _text = text.replace(/&(?!amp;|quot;|apos;|lt;|gt;)/g, '&amp;'); // Support <b>, <i>, and <u>, escape anything else // so it displays as raw markup. _text = _text.replace(/<(?!\/?[biu]>)/g, '&lt;'); try { Pango.parse_markup(_text, -1, ''); return _text; } catch (e) {} } // !allowMarkup, or invalid markup return GLib.markup_escape_text(text, -1); } const FocusGrabber = new Lang.Class({ Name: 'FocusGrabber', _init: function(actor) { this._actor = actor; this._prevKeyFocusActor = null; this._focusActorChangedId = 0; this._focused = false; }, grabFocus: function() { if (this._focused) return; this._prevKeyFocusActor = global.stage.get_key_focus(); this._focusActorChangedId = global.stage.connect('notify::key-focus', Lang.bind(this, this._focusActorChanged)); if (!this._actor.navigate_focus(null, Gtk.DirectionType.TAB_FORWARD, false)) this._actor.grab_key_focus(); this._focused = true; }, _focusUngrabbed: function() { if (!this._focused) return false; if (this._focusActorChangedId > 0) { global.stage.disconnect(this._focusActorChangedId); this._focusActorChangedId = 0; } this._focused = false; return true; }, _focusActorChanged: function() { let focusedActor = global.stage.get_key_focus(); if (!focusedActor || !this._actor.contains(focusedActor)) this._focusUngrabbed(); }, ungrabFocus: function() { if (!this._focusUngrabbed()) return; if (this._prevKeyFocusActor) { global.stage.set_key_focus(this._prevKeyFocusActor); this._prevKeyFocusActor = null; } else { let focusedActor = global.stage.get_key_focus(); if (focusedActor && this._actor.contains(focusedActor)) global.stage.set_key_focus(null); } } }); const URLHighlighter = new Lang.Class({ Name: 'URLHighlighter', _init: function(text, lineWrap, allowMarkup) { if (!text) text = ''; this.actor = new St.Label({ reactive: true, style_class: 'url-highlighter' }); this._linkColor = '#ccccff'; this.actor.connect('style-changed', Lang.bind(this, function() { let [hasColor, color] = this.actor.get_theme_node().lookup_color('link-color', false); if (hasColor) { let linkColor = color.to_string().substr(0, 7); if (linkColor != this._linkColor) { this._linkColor = linkColor; this._highlightUrls(); } } })); if (lineWrap) { this.actor.clutter_text.line_wrap = true; this.actor.clutter_text.line_wrap_mode = Pango.WrapMode.WORD_CHAR; this.actor.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; } this.setMarkup(text, allowMarkup); this.actor.connect('button-press-event', Lang.bind(this, function(actor, event) { // Don't try to URL highlight when invisible. // The MessageTray doesn't actually hide us, so // we need to check for paint opacities as well. if (!actor.visible || actor.get_paint_opacity() == 0) return Clutter.EVENT_PROPAGATE; // Keep Notification.actor from seeing this and taking // a pointer grab, which would block our button-release-event // handler, if an URL is clicked return this._findUrlAtPos(event) != -1; })); this.actor.connect('button-release-event', Lang.bind(this, function (actor, event) { if (!actor.visible || actor.get_paint_opacity() == 0) return Clutter.EVENT_PROPAGATE; let urlId = this._findUrlAtPos(event); if (urlId != -1) { let url = this._urls[urlId].url; if (url.indexOf(':') == -1) url = 'http://' + url; Gio.app_info_launch_default_for_uri(url, global.create_app_launch_context(0, -1)); return Clutter.EVENT_STOP; } return Clutter.EVENT_PROPAGATE; })); this.actor.connect('motion-event', Lang.bind(this, function(actor, event) { if (!actor.visible || actor.get_paint_opacity() == 0) return Clutter.EVENT_PROPAGATE; let urlId = this._findUrlAtPos(event); if (urlId != -1 && !this._cursorChanged) { global.screen.set_cursor(Meta.Cursor.POINTING_HAND); this._cursorChanged = true; } else if (urlId == -1) { global.screen.set_cursor(Meta.Cursor.DEFAULT); this._cursorChanged = false; } return Clutter.EVENT_PROPAGATE; })); this.actor.connect('leave-event', Lang.bind(this, function() { if (!this.actor.visible || this.actor.get_paint_opacity() == 0) return Clutter.EVENT_PROPAGATE; if (this._cursorChanged) { this._cursorChanged = false; global.screen.set_cursor(Meta.Cursor.DEFAULT); } return Clutter.EVENT_PROPAGATE; })); }, setMarkup: function(text, allowMarkup) { text = text ? _fixMarkup(text, allowMarkup) : ''; this._text = text; this.actor.clutter_text.set_markup(text); /* clutter_text.text contain text without markup */ this._urls = Util.findUrls(this.actor.clutter_text.text); this._highlightUrls(); }, _highlightUrls: function() { // text here contain markup let urls = Util.findUrls(this._text); let markup = ''; let pos = 0; for (let i = 0; i < urls.length; i++) { let url = urls[i]; let str = this._text.substr(pos, url.pos - pos); markup += str + '<span foreground="' + this._linkColor + '"><u>' + url.url + '</u></span>'; pos = url.pos + url.url.length; } markup += this._text.substr(pos); this.actor.clutter_text.set_markup(markup); }, _findUrlAtPos: function(event) { let success; let [x, y] = event.get_coords(); [success, x, y] = this.actor.transform_stage_point(x, y); let find_pos = -1; for (let i = 0; i < this.actor.clutter_text.text.length; i++) { let [success, px, py, line_height] = this.actor.clutter_text.position_to_coords(i); if (py > y || py + line_height < y || x < px) continue; find_pos = i; } if (find_pos != -1) { for (let i = 0; i < this._urls.length; i++) if (find_pos >= this._urls[i].pos && this._urls[i].pos + this._urls[i].url.length > find_pos) return i; } return -1; } }); // NotificationPolicy: // An object that holds all bits of configurable policy related to a notification // source, such as whether to play sound or honour the critical bit. // // A notification without a policy object will inherit the default one. const NotificationPolicy = new Lang.Class({ Name: 'NotificationPolicy', _init: function(params) { params = Params.parse(params, { enable: true, enableSound: true, showBanners: true, forceExpanded: false, showInLockScreen: true, detailsInLockScreen: false }); Lang.copyProperties(params, this); }, // Do nothing for the default policy. These methods are only useful for the // GSettings policy. store: function() { }, destroy: function() { } }); Signals.addSignalMethods(NotificationPolicy.prototype); const NotificationGenericPolicy = new Lang.Class({ Name: 'NotificationGenericPolicy', Extends: NotificationPolicy, _init: function() { // Don't chain to parent, it would try setting // our properties to the defaults this.id = 'generic'; this._masterSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.notifications' }); this._masterSettings.connect('changed', Lang.bind(this, this._changed)); }, store: function() { }, destroy: function() { this._masterSettings.run_dispose(); }, _changed: function(settings, key) { this.emit('policy-changed', key); }, get enable() { return true; }, get enableSound() { return true; }, get showBanners() { return this._masterSettings.get_boolean('show-banners'); }, get forceExpanded() { return false; }, get showInLockScreen() { return this._masterSettings.get_boolean('show-in-lock-screen'); }, get detailsInLockScreen() { return false; } }); const NotificationApplicationPolicy = new Lang.Class({ Name: 'NotificationApplicationPolicy', Extends: NotificationPolicy, _init: function(id) { // Don't chain to parent, it would try setting // our properties to the defaults this.id = id; this._canonicalId = this._canonicalizeId(id); this._masterSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.notifications' }); this._settings = new Gio.Settings({ schema_id: 'org.gnome.desktop.notifications.application', path: '/org/gnome/desktop/notifications/application/' + this._canonicalId + '/' }); this._masterSettings.connect('changed', Lang.bind(this, this._changed)); this._settings.connect('changed', Lang.bind(this, this._changed)); }, store: function() { this._settings.set_string('application-id', this.id + '.desktop'); let apps = this._masterSettings.get_strv('application-children'); if (apps.indexOf(this._canonicalId) < 0) { apps.push(this._canonicalId); this._masterSettings.set_strv('application-children', apps); } }, destroy: function() { this._masterSettings.run_dispose(); this._settings.run_dispose(); }, _changed: function(settings, key) { this.emit('policy-changed', key); }, _canonicalizeId: function(id) { // Keys are restricted to lowercase alphanumeric characters and dash, // and two dashes cannot be in succession return id.toLowerCase().replace(/[^a-z0-9\-]/g, '-').replace(/--+/g, '-'); }, get enable() { return this._settings.get_boolean('enable'); }, get enableSound() { return this._settings.get_boolean('enable-sound-alerts'); }, get showBanners() { return this._masterSettings.get_boolean('show-banners') && this._settings.get_boolean('show-banners'); }, get forceExpanded() { return this._settings.get_boolean('force-expanded'); }, get showInLockScreen() { return this._masterSettings.get_boolean('show-in-lock-screen') && this._settings.get_boolean('show-in-lock-screen'); }, get detailsInLockScreen() { return this._settings.get_boolean('details-in-lock-screen'); } }); // Notification: // @source: the notification's Source // @title: the title // @banner: the banner text // @params: optional additional params // // Creates a notification. In the banner mode, the notification // will show an icon, @title (in bold) and @banner, all on a single // line (with @banner ellipsized if necessary). // // The notification will be expandable if either it has additional // elements that were added to it or if the @banner text did not // fit fully in the banner mode. When the notification is expanded, // the @banner text from the top line is always removed. The complete // @banner text is added as the first element in the content section, // unless 'customContent' parameter with the value 'true' is specified // in @params. // // Additional notification content can be added with addActor() and // addBody() methods. The notification content is put inside a // scrollview, so if it gets too tall, the notification will scroll // rather than continue to grow. In addition to this main content // area, there is also a single-row action area, which is not // scrolled and can contain a single actor. The action area can // be set by calling setActionArea() method. There is also a // convenience method addButton() for adding a button to the action // area. // // If @params contains a 'customContent' parameter with the value %true, // then @banner will not be shown in the body of the notification when the // notification is expanded and calls to update() will not clear the content // unless 'clear' parameter with value %true is explicitly specified. // // By default, the icon shown is the same as the source's. // However, if @params contains a 'gicon' parameter, the passed in gicon // will be used. // // You can add a secondary icon to the banner with 'secondaryGIcon'. There // is no fallback for this icon. // // If @params contains 'bannerMarkup', with the value %true, then // the corresponding element is assumed to use pango markup. If the // parameter is not present for an element, then anything that looks // like markup in that element will appear literally in the output. // // If @params contains a 'clear' parameter with the value %true, then // the content and the action area of the notification will be cleared. // The content area is also always cleared if 'customContent' is false // because it might contain the @banner that didn't fit in the banner mode. // // If @params contains 'soundName' or 'soundFile', the corresponding // event sound is played when the notification is shown (if the policy for // @source allows playing sounds). const Notification = new Lang.Class({ Name: 'Notification', ICON_SIZE: 24, IMAGE_SIZE: 125, _init: function(source, title, banner, params) { this.source = source; this.title = title; this.urgency = Urgency.NORMAL; this.resident = false; // 'transient' is a reserved keyword in JS, so we have to use an alternate variable name this.isTransient = false; this.isMusic = false; this.forFeedback = false; this.expanded = false; this.focused = false; this.acknowledged = false; this._destroyed = false; this._customContent = false; this.bannerBodyText = null; this.bannerBodyMarkup = false; this._bannerBodyAdded = false; this._titleFitsInBannerMode = true; this._spacing = 0; this._scrollPolicy = Gtk.PolicyType.AUTOMATIC; this._imageBin = null; this._soundName = null; this._soundFile = null; this._soundPlayed = false; this.actor = new St.Button({ accessible_role: Atk.Role.NOTIFICATION }); this.actor.add_style_class_name('notification-unexpanded'); this.actor._delegate = this; this.actor.connect('clicked', Lang.bind(this, this._onClicked)); this.actor.connect('destroy', Lang.bind(this, this._onDestroy)); this._table = new St.Table({ style_class: 'notification', reactive: true }); this._table.connect('style-changed', Lang.bind(this, this._styleChanged)); this.actor.set_child(this._table); // The first line should have the title, followed by the // banner text, but ellipsized if they won't both fit. We can't // make St.Table or St.BoxLayout do this the way we want (don't // show banner at all if title needs to be ellipsized), so we // use Shell.GenericContainer. this._bannerBox = new Shell.GenericContainer(); this._bannerBox.connect('get-preferred-width', Lang.bind(this, this._bannerBoxGetPreferredWidth)); this._bannerBox.connect('get-preferred-height', Lang.bind(this, this._bannerBoxGetPreferredHeight)); this._bannerBox.connect('allocate', Lang.bind(this, this._bannerBoxAllocate)); this._table.add(this._bannerBox, { row: 0, col: 1, col_span: 2, x_expand: false, y_expand: false, y_fill: false }); // This is an empty cell that overlaps with this._bannerBox cell to ensure // that this._bannerBox cell expands horizontally, while not forcing the // this._imageBin that is also in col: 2 to expand horizontally. this._table.add(new St.Bin(), { row: 0, col: 2, y_expand: false, y_fill: false }); this._titleLabel = new St.Label(); this._bannerBox.add_actor(this._titleLabel); this._bannerUrlHighlighter = new URLHighlighter(); this._bannerLabel = this._bannerUrlHighlighter.actor; this._bannerBox.add_actor(this._bannerLabel); // If called with only one argument we assume the caller // will call .update() later on. This is the case of // NotificationDaemon, which wants to use the same code // for new and updated notifications if (arguments.length != 1) this.update(title, banner, params); }, // update: // @title: the new title // @banner: the new banner // @params: as in the Notification constructor // // Updates the notification by regenerating its icon and updating // the title/banner. If @params.clear is %true, it will also // remove any additional actors/action buttons previously added. update: function(title, banner, params) { params = Params.parse(params, { customContent: false, gicon: null, secondaryGIcon: null, bannerMarkup: false, clear: false, soundName: null, soundFile: null }); this._customContent = params.customContent; let oldFocus = global.stage.key_focus; if (this._icon && (params.gicon || params.clear)) { this._icon.destroy(); this._icon = null; } if (this._secondaryIcon && (params.secondaryGIcon || params.clear)) { this._secondaryIcon.destroy(); this._secondaryIcon = null; } // We always clear the content area if we don't have custom // content because it might contain the @banner that didn't // fit in the banner mode. if (this._scrollArea && (!this._customContent || params.clear)) { if (oldFocus && this._scrollArea.contains(oldFocus)) this.actor.grab_key_focus(); this._scrollArea.destroy(); this._scrollArea = null; this._contentArea = null; } if (this._actionArea && params.clear) { if (oldFocus && this._actionArea.contains(oldFocus)) this.actor.grab_key_focus(); this._actionArea.destroy(); this._actionArea = null; this._buttonBox = null; } if (params.clear) this.unsetImage(); if (!this._scrollArea && !this._actionArea && !this._imageBin) this._table.remove_style_class_name('multi-line-notification'); if (params.gicon) { this._icon = new St.Icon({ gicon: params.gicon, icon_size: this.ICON_SIZE }); } else { this._icon = this.source.createIcon(this.ICON_SIZE); } if (this._icon) { this._table.add(this._icon, { row: 0, col: 0, x_expand: false, y_expand: false, y_fill: false, y_align: St.Align.START }); } if (params.secondaryGIcon) { this._secondaryIcon = new St.Icon({ gicon: params.secondaryGIcon, style_class: 'secondary-icon' }); this._bannerBox.add_actor(this._secondaryIcon); } this.title = title; title = title ? _fixMarkup(title.replace(/\n/g, ' '), false) : ''; this._titleLabel.clutter_text.set_markup('<b>' + title + '</b>'); let titleDirection; if (Pango.find_base_dir(title, -1) == Pango.Direction.RTL) titleDirection = Clutter.TextDirection.RTL; else titleDirection = Clutter.TextDirection.LTR; // Let the title's text direction control the overall direction // of the notification - in case where different scripts are used // in the notification, this is the right thing for the icon, and // arguably for action buttons as well. Labels other than the title // will be allocated at the available width, so that their alignment // is done correctly automatically. this._table.set_text_direction(titleDirection); // Unless the notification has custom content, we save this.bannerBodyText // to add it to the content of the notification if the notification is // expandable due to other elements in its content area or due to the banner // not fitting fully in the single-line mode. this.bannerBodyText = this._customContent ? null : banner; this.bannerBodyMarkup = params.bannerMarkup; this._bannerBodyAdded = false; banner = banner ? banner.replace(/\n/g, ' ') : ''; this._bannerUrlHighlighter.setMarkup(banner, params.bannerMarkup); this._bannerLabel.queue_relayout(); // Add the bannerBody now if we know for sure we'll need it if (this.bannerBodyText && this.bannerBodyText.indexOf('\n') > -1) this._addBannerBody(); if (this._soundName != params.soundName || this._soundFile != params.soundFile) { this._soundName = params.soundName; this._soundFile = params.soundFile; this._soundPlayed = false; } this.updated(); }, setIconVisible: function(visible) { this._icon.visible = visible; }, enableScrolling: function(enableScrolling) { this._scrollPolicy = enableScrolling ? Gtk.PolicyType.AUTOMATIC : Gtk.PolicyType.NEVER; if (this._scrollArea) { this._scrollArea.vscrollbar_policy = this._scrollPolicy; this._scrollArea.enable_mouse_scrolling = enableScrolling; } }, _createScrollArea: function() { this._table.add_style_class_name('multi-line-notification'); this._scrollArea = new St.ScrollView({ style_class: 'notification-scrollview', vscrollbar_policy: this._scrollPolicy, hscrollbar_policy: Gtk.PolicyType.NEVER, visible: this.expanded }); this._table.add(this._scrollArea, { row: 1, col: 2 }); this._updateLastColumnSettings(); this._contentArea = new St.BoxLayout({ style_class: 'notification-body', vertical: true }); this._scrollArea.add_actor(this._contentArea); // If we know the notification will be expandable, we need to add // the banner text to the body as the first element. this._addBannerBody(); }, // addActor: // @actor: actor to add to the body of the notification // // Appends @actor to the notification's body addActor: function(actor, style) { if (!this._scrollArea) { this._createScrollArea(); } this._contentArea.add(actor, style ? style : {}); this.updated(); }, // addBody: // @text: the text // @markup: %true if @text contains pango markup // @style: style to use when adding the actor containing the text // // Adds a multi-line label containing @text to the notification. // // Return value: the newly-added label addBody: function(text, markup, style) { let label = new URLHighlighter(text, true, markup); this.addActor(label.actor, style); return label.actor; }, _addBannerBody: function() { if (this.bannerBodyText && !this._bannerBodyAdded) { this._bannerBodyAdded = true; this.addBody(this.bannerBodyText, this.bannerBodyMarkup); } }, // scrollTo: // @side: St.Side.TOP or St.Side.BOTTOM // // Scrolls the content area (if scrollable) to the indicated edge scrollTo: function(side) { let adjustment = this._scrollArea.vscroll.adjustment; if (side == St.Side.TOP) adjustment.value = adjustment.lower; else if (side == St.Side.BOTTOM) adjustment.value = adjustment.upper; }, // setActionArea: // @actor: the actor // @props: (option) St.Table child properties // // Puts @actor into the action area of the notification, replacing // the previous contents setActionArea: function(actor, props) { if (this._actionArea) { this._actionArea.destroy(); this._actionArea = null; if (this._buttonBox) this._buttonBox = null; } else { this._addBannerBody(); } this._actionArea = actor; this._actionArea.visible = this.expanded; if (!props) props = {}; props.row = 2; props.col = 2; this._table.add_style_class_name('multi-line-notification'); this._table.add(this._actionArea, props); this._updateLastColumnSettings(); this.updated(); }, _updateLastColumnSettings: function() { if (this._scrollArea) this._table.child_set(this._scrollArea, { col: this._imageBin ? 2 : 1, col_span: this._imageBin ? 1 : 2 }); if (this._actionArea) this._table.child_set(this._actionArea, { col: this._imageBin ? 2 : 1, col_span: this._imageBin ? 1 : 2 }); }, setImage: function(image) { this.unsetImage(); if (!image) return; this._imageBin = new St.Bin({ opacity: 230, child: image, visible: this.expanded }); this._table.add_style_class_name('multi-line-notification'); this._table.add_style_class_name('notification-with-image'); this._addBannerBody(); this._updateLastColumnSettings(); this._table.add(this._imageBin, { row: 1, col: 1, row_span: 2, x_expand: false, y_expand: false, x_fill: false, y_fill: false }); }, unsetImage: function() { if (this._imageBin) { this._table.remove_style_class_name('notification-with-image'); this._table.remove_actor(this._imageBin); this._imageBin = null; this._updateLastColumnSettings(); if (!this._scrollArea && !this._actionArea) this._table.remove_style_class_name('multi-line-notification'); } }, addButton: function(button, callback) { if (!this._buttonBox) { let box = new St.BoxLayout({ style_class: 'notification-actions' }); this.setActionArea(box, { x_expand: false, y_expand: false, x_fill: false, y_fill: false, x_align: St.Align.END }); this._buttonBox = box; global.focus_manager.add_group(this._buttonBox); } this._buttonBox.add(button); button.connect('clicked', Lang.bind(this, function() { callback(); if (!this.resident) { // We don't hide a resident notification when the user invokes one of its actions, // because it is common for such notifications to update themselves with new // information based on the action. We'd like to display the updated information // in place, rather than pop-up a new notification. this.emit('done-displaying'); this.destroy(); } })); this.updated(); return button; }, // addAction: // @label: the label for the action's button // @callback: the callback for the action // // Adds a button with the given @label to the notification. All // action buttons will appear in a single row at the bottom of // the notification. addAction: function(label, callback) { let button = new St.Button({ style_class: 'notification-button', label: label, can_focus: true }); return this.addButton(button, callback); }, setUrgency: function(urgency) { this.urgency = urgency; }, setResident: function(resident) { this.resident = resident; }, setTransient: function(isTransient) { this.isTransient = isTransient; }, setForFeedback: function(forFeedback) { this.forFeedback = forFeedback; }, _styleChanged: function() { this._spacing = this._table.get_theme_node().get_length('spacing-columns'); }, _bannerBoxGetPreferredWidth: function(actor, forHeight, alloc) { let [titleMin, titleNat] = this._titleLabel.get_preferred_width(forHeight); let [bannerMin, bannerNat] = this._bannerLabel.get_preferred_width(forHeight); if (this._secondaryIcon) { let [secondaryIconMin, secondaryIconNat] = this._secondaryIcon.get_preferred_width(forHeight); alloc.min_size = secondaryIconMin + this._spacing + titleMin; alloc.natural_size = secondaryIconNat + this._spacing + titleNat + this._spacing + bannerNat; } else { alloc.min_size = titleMin; alloc.natural_size = titleNat + this._spacing + bannerNat; } }, _bannerBoxGetPreferredHeight: function(actor, forWidth, alloc) { [alloc.min_size, alloc.natural_size] = this._titleLabel.get_preferred_height(forWidth); }, _bannerBoxAllocate: function(actor, box, flags) { let availWidth = box.x2 - box.x1; let [titleMinW, titleNatW] = this._titleLabel.get_preferred_width(-1); let [titleMinH, titleNatH] = this._titleLabel.get_preferred_height(availWidth); let [bannerMinW, bannerNatW] = this._bannerLabel.get_preferred_width(availWidth); let rtl = (this._table.text_direction == Clutter.TextDirection.RTL); let x = rtl ? availWidth : 0; if (this._secondaryIcon) { let [iconMinW, iconNatW] = this._secondaryIcon.get_preferred_width(-1); let [iconMinH, iconNatH] = this._secondaryIcon.get_preferred_height(availWidth); let secondaryIconBox = new Clutter.ActorBox(); let secondaryIconBoxW = Math.min(iconNatW, availWidth); // allocate secondary icon box if (rtl) { secondaryIconBox.x1 = x - secondaryIconBoxW; secondaryIconBox.x2 = x; x = x - (secondaryIconBoxW + this._spacing); } else { secondaryIconBox.x1 = x; secondaryIconBox.x2 = x + secondaryIconBoxW; x = x + secondaryIconBoxW + this._spacing; } secondaryIconBox.y1 = 0; // Using titleNatH ensures that the secondary icon is centered vertically secondaryIconBox.y2 = titleNatH; availWidth = availWidth - (secondaryIconBoxW + this._spacing); this._secondaryIcon.allocate(secondaryIconBox, flags); } let titleBox = new Clutter.ActorBox(); let titleBoxW = Math.min(titleNatW, availWidth); if (rtl) { titleBox.x1 = availWidth - titleBoxW; titleBox.x2 = availWidth; } else { titleBox.x1 = x; titleBox.x2 = titleBox.x1 + titleBoxW; } titleBox.y1 = 0; titleBox.y2 = titleNatH; this._titleLabel.allocate(titleBox, flags); this._titleFitsInBannerMode = (titleNatW <= availWidth); let bannerFits = true; if (titleBoxW + this._spacing > availWidth) { this._bannerLabel.opacity = 0; bannerFits = false; } else { let bannerBox = new Clutter.ActorBox(); if (rtl) { bannerBox.x1 = 0; bannerBox.x2 = titleBox.x1 - this._spacing; bannerFits = (bannerBox.x2 - bannerNatW >= 0); } else { bannerBox.x1 = titleBox.x2 + this._spacing; bannerBox.x2 = availWidth; bannerFits = (bannerBox.x1 + bannerNatW <= availWidth); } bannerBox.y1 = 0; bannerBox.y2 = titleNatH; this._bannerLabel.allocate(bannerBox, flags); // Make _bannerLabel visible if the entire notification // fits on one line, or if the notification is currently // unexpanded and only showing one line anyway. if (!this.expanded || (bannerFits && this._table.row_count == 1)) this._bannerLabel.opacity = 255; } // If the banner doesn't fully fit in the banner box, we possibly need to add the // banner to the body. We can't do that from here though since that will force a // relayout, so we add it to the main loop. if (!bannerFits && this._canExpandContent()) Meta.later_add(Meta.LaterType.BEFORE_REDRAW, Lang.bind(this, function() { if (this._destroyed) return false; if (this._canExpandContent()) { this._addBannerBody(); this._table.add_style_class_name('multi-line-notification'); this.updated(); } return false; })); }, _canExpandContent: function() { return (this.bannerBodyText && !this._bannerBodyAdded) || (!this._titleFitsInBannerMode && !this._table.has_style_class_name('multi-line-notification')); }, playSound: function() { if (this._soundPlayed) return; if (!this.source.policy.enableSound) { this._soundPlayed = true; return; } if (this._soundName) { if (this.source.app) { let app = this.source.app; global.play_theme_sound_full(0, this._soundName, this.title, null, app.get_id(), app.get_name()); } else { global.play_theme_sound(0, this._soundName, this.title, null); } } else if (this._soundFile) { if (this.source.app) { let app = this.source.app; global.play_sound_file_full(0, this._soundFile, this.title, null, app.get_id(), app.get_name()); } else { global.play_sound_file(0, this._soundFile, this.title, null); } } }, updated: function() { if (this.expanded) this.expand(false); }, expand: function(animate) { this.expanded = true; this.actor.remove_style_class_name('notification-unexpanded'); // Show additional content that we keep hidden in banner mode if (this._imageBin) this._imageBin.show(); if (this._actionArea) this._actionArea.show(); if (this._scrollArea) this._scrollArea.show(); // The banner is never shown when the title did not fit, so this // can be an if-else statement. if (!this._titleFitsInBannerMode) { // Remove ellipsization from the title label and make it wrap so that // we show the full title when the notification is expanded. this._titleLabel.clutter_text.line_wrap = true; this._titleLabel.clutter_text.line_wrap_mode = Pango.WrapMode.WORD_CHAR; this._titleLabel.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; } else if (this._table.row_count > 1 && this._bannerLabel.opacity != 0) { // We always hide the banner if the notification has additional content. // // We don't need to wrap the banner that doesn't fit the way we wrap the // title that doesn't fit because we won't have a notification with // row_count=1 that has a banner that doesn't fully fit. We'll either add // that banner to the content of the notification in _bannerBoxAllocate() // or the notification will have custom content. if (animate) Tweener.addTween(this._bannerLabel, { opacity: 0, time: ANIMATION_TIME, transition: 'easeOutQuad' }); else this._bannerLabel.opacity = 0; } this.emit('expanded'); }, collapseCompleted: function() { if (this._destroyed) return; this.expanded = false; // Hide additional content that we keep hidden in banner mode if (this._imageBin) this._imageBin.hide(); if (this._actionArea) this._actionArea.hide(); if (this._scrollArea) this._scrollArea.hide(); // Make sure we don't line wrap the title, and ellipsize it instead. this._titleLabel.clutter_text.line_wrap = false; this._titleLabel.clutter_text.ellipsize = Pango.EllipsizeMode.END; // Restore banner opacity in case the notification is shown in the // banner mode again on update. this._bannerLabel.opacity = 255; // Restore height requisition this.actor.add_style_class_name('notification-unexpanded'); }, _onClicked: function() { this.emit('clicked'); // We hide all types of notifications once the user clicks on them because the common // outcome of clicking should be the relevant window being brought forward and the user's // attention switching to the window. this.emit('done-displaying'); if (!this.resident) this.destroy(); }, _onDestroy: function() { if (this._destroyed) return; this._destroyed = true; if (!this._destroyedReason) this._destroyedReason = NotificationDestroyedReason.DISMISSED; this.emit('destroy', this._destroyedReason); }, destroy: function(reason) { this._destroyedReason = reason; this.actor.destroy(); this.actor._delegate = null; } }); Signals.addSignalMethods(Notification.prototype); const SourceActor = new Lang.Class({ Name: 'SourceActor', _init: function(source, size) { this._source = source; this._size = size; this.actor = new Shell.GenericContainer(); this.actor.connect('get-preferred-width', Lang.bind(this, this._getPreferredWidth)); this.actor.connect('get-preferred-height', Lang.bind(this, this._getPreferredHeight)); this.actor.connect('allocate', Lang.bind(this, this._allocate)); this.actor.connect('destroy', Lang.bind(this, function() { this._source.disconnect(this._iconUpdatedId); this._actorDestroyed = true; })); this._actorDestroyed = false; let scale_factor = St.ThemeContext.get_for_stage(global.stage).scale_factor; this._iconBin = new St.Bin({ x_fill: true, height: size * scale_factor, width: size * scale_factor }); this.actor.add_actor(this._iconBin); this._iconUpdatedId = this._source.connect('icon-updated', Lang.bind(this, this._updateIcon)); this._updateIcon(); }, setIcon: function(icon) { this._iconBin.child = icon; this._iconSet = true; }, _getPreferredWidth: function (actor, forHeight, alloc) { let [min, nat] = this._iconBin.get_preferred_width(forHeight); alloc.min_size = min; alloc.nat_size = nat; }, _getPreferredHeight: function (actor, forWidth, alloc) { let [min, nat] = this._iconBin.get_preferred_height(forWidth); alloc.min_size = min; alloc.nat_size = nat; }, _allocate: function(actor, box, flags) { // the iconBin should fill our entire box this._iconBin.allocate(box, flags); }, _updateIcon: function() { if (this._actorDestroyed) return; if (!this._iconSet) this._iconBin.child = this._source.createIcon(this._size); } }); const SourceActorWithLabel = new Lang.Class({ Name: 'SourceActorWithLabel', Extends: SourceActor, _init: function(source, size) { this.parent(source, size); this._counterLabel = new St.Label({ x_align: Clutter.ActorAlign.CENTER, x_expand: true, y_align: Clutter.ActorAlign.CENTER, y_expand: true }); this._counterBin = new St.Bin({ style_class: 'summary-source-counter', child: this._counterLabel, layout_manager: new Clutter.BinLayout() }); this._counterBin.hide(); this._counterBin.connect('style-changed', Lang.bind(this, function() { let themeNode = this._counterBin.get_theme_node(); this._counterBin.translation_x = themeNode.get_length('-shell-counter-overlap-x'); this._counterBin.translation_y = themeNode.get_length('-shell-counter-overlap-y'); })); this.actor.add_actor(this._counterBin); this._countUpdatedId = this._source.connect('count-updated', Lang.bind(this, this._updateCount)); this._updateCount(); this.actor.connect('destroy', function() { this._source.disconnect(this._countUpdatedId); }); }, _allocate: function(actor, box, flags) { this.parent(actor, box, flags); let childBox = new Clutter.ActorBox(); let [minWidth, minHeight, naturalWidth, naturalHeight] = this._counterBin.get_preferred_size(); let direction = this.actor.get_text_direction(); if (direction == Clutter.TextDirection.LTR) { // allocate on the right in LTR childBox.x1 = box.x2 - naturalWidth; childBox.x2 = box.x2; } else { // allocate on the left in RTL childBox.x1 = 0; childBox.x2 = naturalWidth; } childBox.y1 = box.y2 - naturalHeight; childBox.y2 = box.y2; this._counterBin.allocate(childBox, flags); }, _updateCount: function() { if (this._actorDestroyed) return; this._counterBin.visible = this._source.countVisible; let text; if (this._source.count < 100) text = this._source.count.toString(); else text = String.fromCharCode(0x22EF); // midline horizontal ellipsis this._counterLabel.set_text(text); } }); const Source = new Lang.Class({ Name: 'MessageTraySource', SOURCE_ICON_SIZE: 48, _init: function(title, iconName) { this.title = title; this.iconName = iconName; this.isChat = false; this.isMuted = false; this.keepTrayOnSummaryClick = false; this.notifications = []; this.policy = this._createPolicy(); }, get count() { return this.notifications.length; }, get indicatorCount() { let notifications = this.notifications.filter(function(n) { return !n.isTransient && !n.resident; }); return notifications.length; }, get unseenCount() { return this.notifications.filter(function(n) { return !n.acknowledged; }).length; }, get countVisible() { return this.count > 1; }, get isClearable() { return !this.trayIcon && !this.isChat && !this.resident; }, countUpdated: function() { this.emit('count-updated'); }, _createPolicy: function() { return new NotificationPolicy(); }, buildRightClickMenu: function() { let item; let rightClickMenu = new St.BoxLayout({ name: 'summary-right-click-menu', vertical: true }); item = new PopupMenu.PopupMenuItem(_("Open")); item.connect('activate', Lang.bind(this, function() { this.open(); this.emit('done-displaying-content', true); })); rightClickMenu.add(item.actor); item = new PopupMenu.PopupMenuItem(_("Remove")); item.connect('activate', Lang.bind(this, function() { this.destroy(); this.emit('done-displaying-content', false); })); rightClickMenu.add(item.actor); return rightClickMenu; }, setTitle: function(newTitle) { this.title = newTitle; this.emit('title-changed'); }, setMuted: function(muted) { if (!this.isChat || this.isMuted == muted) return; this.isMuted = muted; this.emit('muted-changed'); }, // Called to create a new icon actor. // Provides a sane default implementation, override if you need // something more fancy. createIcon: function(size) { return new St.Icon({ gicon: this.getIcon(), icon_size: size }); }, getIcon: function() { return new Gio.ThemedIcon({ name: this.iconName }); }, _ensureMainIcon: function() { if (this._mainIcon) return; this._mainIcon = new SourceActorWithLabel(this, this.SOURCE_ICON_SIZE); }, // Unlike createIcon, this always returns the same actor; // there is only one summary icon actor for a Source. getSummaryIcon: function() { this._ensureMainIcon(); return this._mainIcon.actor; }, _onNotificationDestroy: function(notification) { let index = this.notifications.indexOf(notification); if (index < 0) return; this.notifications.splice(index, 1); if (this.notifications.length == 0) this._lastNotificationRemoved(); this.countUpdated(); }, pushNotification: function(notification) { if (this.notifications.indexOf(notification) >= 0) return; notification.connect('destroy', Lang.bind(this, this._onNotificationDestroy)); this.notifications.push(notification); this.emit('notification-added', notification); this.countUpdated(); }, notify: function(notification) { notification.acknowledged = false; this.pushNotification(notification); if (!this.isMuted) { // Play the sound now, if banners are disabled. // Otherwise, it will be played when the notification // is next shown. if (this.policy.showBanners) { this.emit('notify', notification); } else { notification.playSound(); } } }, destroy: function(reason) { this.policy.destroy(); let notifications = this.notifications; this.notifications = []; for (let i = 0; i < notifications.length; i++) notifications[i].destroy(reason); this.emit('destroy', reason); }, // A subclass can redefine this to "steal" clicks from the // summaryitem; Use Clutter.get_current_event() to get the // details, return true to prevent the default handling from // ocurring. handleSummaryClick: function() { return false; }, iconUpdated: function() { this.emit('icon-updated'); }, //// Protected methods //// _setSummaryIcon: function(icon) { this._ensureMainIcon(); this._mainIcon.setIcon(icon); this.iconUpdated(); }, // To be overridden by subclasses open: function() { }, destroyNonResidentNotifications: function() { for (let i = this.notifications.length - 1; i >= 0; i--) if (!this.notifications[i].resident) this.notifications[i].destroy(); this.countUpdated(); }, // Default implementation is to destroy this source, but subclasses can override _lastNotificationRemoved: function() { this.destroy(); }, getMusicNotification: function() { for (let i = 0; i < this.notifications.length; i++) { if (this.notifications[i].isMusic) return this.notifications[i]; } return null; }, }); Signals.addSignalMethods(Source.prototype); const SummaryItem = new Lang.Class({ Name: 'SummaryItem', _init: function(source) { this.source = source; this.source.connect('notification-added', Lang.bind(this, this._notificationAddedToSource)); this.actor = new St.Button({ style_class: 'summary-source-button', y_fill: true, reactive: true, button_mask: St.ButtonMask.ONE | St.ButtonMask.TWO | St.ButtonMask.THREE, can_focus: true, track_hover: true }); this.actor.label_actor = new St.Label({ text: source.title }); this.actor.connect('key-press-event', Lang.bind(this, this._onKeyPress)); this._sourceBox = new St.BoxLayout({ style_class: 'summary-source' }); this._sourceIcon = source.getSummaryIcon(); this._sourceBox.add(this._sourceIcon, { y_fill: false }); this.actor.child = this._sourceBox; this.notificationStackWidget = new St.Widget({ layout_manager: new Clutter.BinLayout() }); this.notificationStackView = new St.ScrollView({ style_class: source.isChat ? '' : 'summary-notification-stack-scrollview', vscrollbar_policy: source.isChat ? Gtk.PolicyType.NEVER : Gtk.PolicyType.AUTOMATIC, hscrollbar_policy: Gtk.PolicyType.NEVER }); this.notificationStackView.add_style_class_name('vfade'); this.notificationStack = new St.BoxLayout({ style_class: 'summary-notification-stack', vertical: true }); this.notificationStackView.add_actor(this.notificationStack); this.notificationStackWidget.add_actor(this.notificationStackView); this._closeButton = Util.makeCloseButton(); this._closeButton.connect('clicked', Lang.bind(this, function() { source.destroy(); source.emit('done-displaying-content', false); })); this.notificationStackWidget.add_actor(this._closeButton); this._stackedNotifications = []; this._oldMaxScrollAdjustment = 0; this.notificationStackView.vscroll.adjustment.connect('changed', Lang.bind(this, function(adjustment) { let currentValue = adjustment.value + adjustment.page_size; if (currentValue == this._oldMaxScrollAdjustment) this.scrollTo(St.Side.BOTTOM); this._oldMaxScrollAdjustment = adjustment.upper; })); this.rightClickMenu = source.buildRightClickMenu(); if (this.rightClickMenu) global.focus_manager.add_group(this.rightClickMenu); }, destroy: function() { // remove the actor from the summary item so it doesn't get destroyed // with us this._sourceBox.remove_actor(this._sourceIcon); this.actor.destroy(); }, _onKeyPress: function(actor, event) { if (event.get_key_symbol() == Clutter.KEY_Up) { actor.emit('clicked', 1); return Clutter.EVENT_STOP; } return Clutter.EVENT_PROPAGATE; }, prepareNotificationStackForShowing: function() { if (this.notificationStack.get_n_children() > 0) return; this.source.notifications.forEach(Lang.bind(this, this._appendNotificationToStack)); this.scrollTo(St.Side.BOTTOM); }, doneShowingNotificationStack: function() { this.source.notifications.forEach(Lang.bind(this, function(notification) { notification.collapseCompleted(); notification.setIconVisible(true); notification.enableScrolling(true); this.notificationStack.remove_actor(notification.actor); })); }, _notificationAddedToSource: function(source, notification) { if (this.notificationStack.mapped) this._appendNotificationToStack(notification); }, _contentUpdated: function() { this.source.notifications.forEach(function(notification, i) { notification.setIconVisible(i == 0); }); this.emit('content-updated'); }, _appendNotificationToStack: function(notification) { notification.connect('destroy', Lang.bind(this, this._contentUpdated)); if (!this.source.isChat) notification.enableScrolling(false); notification.expand(false); this.notificationStack.add(notification.actor); this._contentUpdated(); }, // scrollTo: // @side: St.Side.TOP or St.Side.BOTTOM // // Scrolls the notifiction stack to the indicated edge scrollTo: function(side) { let adjustment = this.notificationStackView.vscroll.adjustment; if (side == St.Side.TOP) adjustment.value = adjustment.lower; else if (side == St.Side.BOTTOM) adjustment.value = adjustment.upper; }, }); Signals.addSignalMethods(SummaryItem.prototype); const MessageTrayMenu = new Lang.Class({ Name: 'MessageTrayMenu', Extends: PopupMenu.PopupMenu, _init: function(button, tray) { this.parent(button, 0, St.Side.BOTTOM); this._tray = tray; this._presence = new GnomeSession.Presence(Lang.bind(this, function(proxy, error) { if (error) { logError(error, 'Error while reading gnome-session presence'); return; } this._onStatusChanged(proxy.status); })); this._presence.connectSignal('StatusChanged', Lang.bind(this, function(proxy, senderName, [status]) { this._onStatusChanged(status); })); this._accountManager = Tp.AccountManager.dup(); this._accountManager.connect('most-available-presence-changed', Lang.bind(this, this._onIMPresenceChanged)); this._accountManager.prepare_async(null, Lang.bind(this, this._onIMPresenceChanged)); this.actor.hide(); Main.layoutManager.addChrome(this.actor); this._busyItem = new PopupMenu.PopupSwitchMenuItem(_("Notifications")); this._busyItem.connect('toggled', Lang.bind(this, this._updatePresence)); this.addMenuItem(this._busyItem); let separator = new PopupMenu.PopupSeparatorMenuItem(); this.addMenuItem(separator); this._clearItem = this.addAction(_("Clear Messages"), function() { let toDestroy = tray.getSources().filter(function(source) { return source.isClearable; }); toDestroy.forEach(function(source) { source.destroy(); }); tray.close(); }); tray.connect('source-added', Lang.bind(this, this._updateClearSensitivity)); tray.connect('source-removed', Lang.bind(this, this._updateClearSensitivity)); this._updateClearSensitivity(); let separator = new PopupMenu.PopupSeparatorMenuItem(); this.addMenuItem(separator); let settingsItem = this.addSettingsAction(_("Notification Settings"), 'gnome-notifications-panel.desktop'); settingsItem.connect('activate', function() { tray.close(); }); }, _onStatusChanged: function(status) { this._sessionStatus = status; this._busyItem.setToggleState(status != GnomeSession.PresenceStatus.BUSY); }, _onIMPresenceChanged: function(am, type) { if (type == Tp.ConnectionPresenceType.AVAILABLE && this._sessionStatus == GnomeSession.PresenceStatus.BUSY) this._presence.SetStatusRemote(GnomeSession.PresenceStatus.AVAILABLE); }, _updateClearSensitivity: function() { this._clearItem.setSensitive(this._tray.clearableCount > 0); }, _updatePresence: function(item, state) { let status = state ? GnomeSession.PresenceStatus.AVAILABLE : GnomeSession.PresenceStatus.BUSY; this._presence.SetStatusRemote(status); let [type, s ,msg] = this._accountManager.get_most_available_presence(); let newType = 0; let newStatus; if (status == GnomeSession.PresenceStatus.BUSY && type == Tp.ConnectionPresenceType.AVAILABLE) { newType = Tp.ConnectionPresenceType.BUSY; newStatus = 'busy'; } else if (status == GnomeSession.PresenceStatus.AVAILABLE && type == Tp.ConnectionPresenceType.BUSY) { newType = Tp.ConnectionPresenceType.AVAILABLE; newStatus = 'available'; } if (newType > 0) this._accountManager.set_all_requested_presences(newType, newStatus, msg); } }); const MessageTrayMenuButton = new Lang.Class({ Name: 'MessageTrayMenuButton', _init: function(tray) { this._icon = new St.Icon(); this.actor = new St.Button({ style_class: 'message-tray-menu-button', reactive: true, track_hover: true, can_focus: true, button_mask: St.ButtonMask.ONE | St.ButtonMask.TWO | St.ButtonMask.THREE, accessible_name: _("Tray Menu"), accessible_role: Atk.Role.MENU, child: this._icon }); // Standard hack for ClutterBinLayout. this.actor.set_x_expand(true); this.actor.set_y_expand(true); this.actor.set_x_align(Clutter.ActorAlign.START); this._menu = new MessageTrayMenu(this.actor, tray); this._manager = new PopupMenu.PopupMenuManager({ actor: this.actor }); this._manager.addMenu(this._menu); this._menu.connect('open-state-changed', Lang.bind(this, function(menu, open) { if (open) this.actor.add_style_pseudo_class('active'); else this.actor.remove_style_pseudo_class('active'); })); this.actor.connect('clicked', Lang.bind(this, function() { this._menu.toggle(); })); this._accountManager = Tp.AccountManager.dup(); this._accountManager.connect('most-available-presence-changed', Lang.bind(this, this._sync)); this._accountManager.prepare_async(null, Lang.bind(this, this._sync)); }, _iconForPresence: function(presence) { if (presence == Tp.ConnectionPresenceType.AVAILABLE) return 'user-available-symbolic'; else if (presence == Tp.ConnectionPresenceType.BUSY) return 'user-busy-symbolic'; else if (presence == Tp.ConnectionPresenceType.HIDDEN) return 'user-hidden-symbolic'; else if (presence == Tp.ConnectionPresenceType.AWAY) return 'user-away-symbolic'; else if (presence == Tp.ConnectionPresenceType.EXTENDED_AWAY) return 'user-idle-symbolic'; else return 'emblem-system-symbolic'; }, _sync: function() { let [presence, status, message] = this._accountManager.get_most_available_presence(); this._icon.icon_name = this._iconForPresence(presence); }, }); const MessageTray = new Lang.Class({ Name: 'MessageTray', _init: function() { this._presence = new GnomeSession.Presence(Lang.bind(this, function(proxy, error) { this._onStatusChanged(proxy.status); })); this._busy = false; this._presence.connectSignal('StatusChanged', Lang.bind(this, function(proxy, senderName, [status]) { this._onStatusChanged(status); })); this.actor = new St.Widget({ name: 'message-tray', reactive: true, layout_manager: new Clutter.BinLayout(), x_expand: true, y_expand: true, y_align: Clutter.ActorAlign.START, }); this._notificationWidget = new St.Widget({ name: 'notification-container', reactive: true, track_hover: true, y_align: Clutter.ActorAlign.START, x_align: Clutter.ActorAlign.CENTER, y_expand: true, x_expand: true, layout_manager: new Clutter.BinLayout() }); this._notificationWidget.connect('key-release-event', Lang.bind(this, this._onNotificationKeyRelease)); this._notificationWidget.connect('notify::hover', Lang.bind(this, this._onNotificationHoverChanged)); this._notificationBin = new St.Bin({ y_expand: true }); this._notificationBin.set_y_align(Clutter.ActorAlign.START); this._notificationWidget.add_actor(this._notificationBin); this._notificationWidget.hide(); this._notificationFocusGrabber = new FocusGrabber(this._notificationWidget); this._notificationQueue = []; this._notification = null; this._notificationClickedId = 0; this.actor.connect('button-release-event', Lang.bind(this, function(actor, event) { this._setClickedSummaryItem(null); this._updateState(); actor.grab_key_focus(); return Clutter.EVENT_PROPAGATE; })); global.focus_manager.add_group(this.actor); this._summary = new St.BoxLayout({ style_class: 'message-tray-summary', reactive: true, x_align: Clutter.ActorAlign.END, x_expand: true, y_align: Clutter.ActorAlign.CENTER, y_expand: true }); this.actor.add_actor(this._summary); this._focusTrap = new ViewSelector.FocusTrap({ can_focus: true }); this._focusTrap.connect('key-focus-in', Lang.bind(this, function() { this._messageTrayMenuButton.actor.grab_key_focus(); })); this._summary.add_actor(this._focusTrap); this._summaryMotionId = 0; this._summaryBoxPointer = new BoxPointer.BoxPointer(St.Side.BOTTOM, { reactive: true, track_hover: true }); this._summaryBoxPointer.actor.connect('key-press-event', Lang.bind(this, this._onSummaryBoxPointerKeyPress)); this._summaryBoxPointer.actor.style_class = 'summary-boxpointer'; this._summaryBoxPointer.actor.hide(); Main.layoutManager.addChrome(this._summaryBoxPointer.actor); this._summaryBoxPointerItem = null; this._summaryBoxPointerContentUpdatedId = 0; this._summaryBoxPointerDoneDisplayingId = 0; this._clickedSummaryItem = null; this._clickedSummaryItemMouseButton = -1; this._clickedSummaryItemAllocationChangedId = 0; this._closeButton = Util.makeCloseButton(); this._closeButton.hide(); this._closeButton.connect('clicked', Lang.bind(this, this._closeNotification)); this._notificationWidget.add_actor(this._closeButton); this._userActiveWhileNotificationShown = false; this.idleMonitor = Meta.IdleMonitor.get_core(); this._grabHelper = new GrabHelper.GrabHelper(this.actor, { keybindingMode: Shell.KeyBindingMode.MESSAGE_TRAY }); this._grabHelper.addActor(this._summaryBoxPointer.actor); this._grabHelper.addActor(this.actor); Main.layoutManager.connect('keyboard-visible-changed', Lang.bind(this, this._onKeyboardVisibleChanged)); this._trayState = State.HIDDEN; this._traySummoned = false; this._useLongerNotificationLeftTimeout = false; this._trayLeftTimeoutId = 0; // pointerInNotification is sort of a misnomer -- it tracks whether // a message tray notification should expand. The value is // partially driven by the hover state of the notification, but has // a lot of complex state related to timeouts and the current // state of the pointer when a notification pops up. this._pointerInNotification = false; // This tracks this._notificationWidget.hover and is used to fizzle // out non-changing hover notifications in onNotificationHoverChanged. this._notificationHovered = false; this._keyboardVisible = false; this._notificationState = State.HIDDEN; this._notificationTimeoutId = 0; this._notificationExpandedId = 0; this._summaryBoxPointerState = State.HIDDEN; this._summaryBoxPointerTimeoutId = 0; this._desktopCloneState = State.HIDDEN; this._notificationRemoved = false; this._reNotifyAfterHideNotification = null; this._desktopClone = null; this._inCtrlAltTab = false; this.clearableCount = 0; this._lightboxes = []; let lightboxContainers = [global.window_group, Main.layoutManager.overviewGroup]; for (let i = 0; i < lightboxContainers.length; i++) this._lightboxes.push(new Lightbox.Lightbox(lightboxContainers[i], { inhibitEvents: true, fadeFactor: 0.2 })); Main.layoutManager.trayBox.add_actor(this.actor); Main.layoutManager.trayBox.add_actor(this._notificationWidget); Main.layoutManager.trackChrome(this.actor); Main.layoutManager.trackChrome(this._notificationWidget); Main.layoutManager.trackChrome(this._closeButton); global.screen.connect('in-fullscreen-changed', Lang.bind(this, this._updateState)); Main.layoutManager.connect('hot-corners-changed', Lang.bind(this, this._hotCornersChanged)); // If the overview shows or hides while we're in // the message tray, revert back to normal mode. Main.overview.connect('showing', Lang.bind(this, this._escapeTray)); Main.overview.connect('hiding', Lang.bind(this, this._escapeTray)); Main.sessionMode.connect('updated', Lang.bind(this, this._sessionUpdated)); Main.wm.addKeybinding('toggle-message-tray', new Gio.Settings({ schema_id: SHELL_KEYBINDINGS_SCHEMA }), Meta.KeyBindingFlags.NONE, Shell.KeyBindingMode.NORMAL | Shell.KeyBindingMode.MESSAGE_TRAY | Shell.KeyBindingMode.OVERVIEW, Lang.bind(this, this.toggleAndNavigate)); Main.wm.addKeybinding('focus-active-notification', new Gio.Settings({ schema_id: SHELL_KEYBINDINGS_SCHEMA }), Meta.KeyBindingFlags.NONE, Shell.KeyBindingMode.NORMAL | Shell.KeyBindingMode.MESSAGE_TRAY | Shell.KeyBindingMode.OVERVIEW, Lang.bind(this, this._expandActiveNotification)); this._sources = new Map(); this._chatSummaryItemsCount = 0; this._trayDwellTimeoutId = 0; this._setupTrayDwellIfNeeded(); this._sessionUpdated(); this._hotCornersChanged(); this._noMessages = new St.Label({ text: _("No Messages"), style_class: 'no-messages-label', x_align: Clutter.ActorAlign.CENTER, x_expand: true, y_align: Clutter.ActorAlign.CENTER, y_expand: true }); this.actor.add_actor(this._noMessages); this._updateNoMessagesLabel(); this._messageTrayMenuButton = new MessageTrayMenuButton(this); this.actor.add_actor(this._messageTrayMenuButton.actor); this._messageTrayMenuButton.actor.connect('key-press-event', Lang.bind(this, this._onTrayButtonKeyPress)); let gesture = new EdgeDragAction.EdgeDragAction(St.Side.BOTTOM, Shell.KeyBindingMode.NORMAL | Shell.KeyBindingMode.OVERVIEW); gesture.connect('activated', Lang.bind(this, this.toggle)); global.stage.add_action(gesture); }, close: function() { this._escapeTray(); }, _setupTrayDwellIfNeeded: function() { // If we don't have extended barrier features, then we need // to support the old tray dwelling mechanism. if (!global.display.supports_extended_barriers()) { let pointerWatcher = PointerWatcher.getPointerWatcher(); pointerWatcher.addWatch(TRAY_DWELL_CHECK_INTERVAL, Lang.bind(this, this._checkTrayDwell)); this._trayDwelling = false; this._trayDwellUserTime = 0; } }, _updateNoMessagesLabel: function() { this._noMessages.visible = this._sources.size == 0; }, _sessionUpdated: function() { if (Main.sessionMode.isLocked || Main.sessionMode.isGreeter) { if (this._inCtrlAltTab) Main.ctrlAltTabManager.removeGroup(this._summary); this._inCtrlAltTab = false; } else if (!this._inCtrlAltTab) { Main.ctrlAltTabManager.addGroup(this._summary, _("Message Tray"), 'user-available-symbolic', { focusCallback: Lang.bind(this, this.toggleAndNavigate), sortGroup: CtrlAltTab.SortGroup.BOTTOM }); this._inCtrlAltTab = true; } this._updateState(); }, _checkTrayDwell: function(x, y) { let monitor = Main.layoutManager.bottomMonitor; let shouldDwell = (x >= monitor.x && x <= monitor.x + monitor.width && y == monitor.y + monitor.height - 1); if (shouldDwell) { // We only set up dwell timeout when the user is not hovering over the tray // (!this._notificationHovered). This avoids bringing up the message tray after the // user clicks on a notification with the pointer on the bottom pixel // of the monitor. The _trayDwelling variable is used so that we only try to // fire off one tray dwell - if it fails (because, say, the user has the mouse down), // we don't try again until the user moves the mouse up and down again. if (!this._trayDwelling && !this._notificationHovered && this._trayDwellTimeoutId == 0) { // Save the interaction timestamp so we can detect user input let focusWindow = global.display.focus_window; this._trayDwellUserTime = focusWindow ? focusWindow.user_time : 0; this._trayDwellTimeoutId = Mainloop.timeout_add(TRAY_DWELL_TIME, Lang.bind(this, this._trayDwellTimeout)); GLib.Source.set_name_by_id(this._trayDwellTimeoutId, '[gnome-shell] this._trayDwellTimeout'); } this._trayDwelling = true; } else { this._cancelTrayDwell(); this._trayDwelling = false; } }, _cancelTrayDwell: function() { if (this._trayDwellTimeoutId != 0) { Mainloop.source_remove(this._trayDwellTimeoutId); this._trayDwellTimeoutId = 0; } }, _trayDwellTimeout: function() { this._trayDwellTimeoutId = 0; if (Main.layoutManager.bottomMonitor.inFullscreen) return GLib.SOURCE_REMOVE; // We don't want to open the tray when a modal dialog // is up, so we check the modal count for that. When we are in the // overview we have to take the overview's modal push into account if (Main.modalCount > (Main.overview.visible ? 1 : 0)) return GLib.SOURCE_REMOVE; // If the user interacted with the focus window since we started the tray // dwell (by clicking or typing), don't activate the message tray let focusWindow = global.display.focus_window; let currentUserTime = focusWindow ? focusWindow.user_time : 0; if (currentUserTime != this._trayDwellUserTime) return GLib.SOURCE_REMOVE; this.openTray(); return GLib.SOURCE_REMOVE; }, _onTrayButtonKeyPress: function(actor, event) { if (event.get_key_symbol() == Clutter.ISO_Left_Tab) { this._focusTrap.can_focus = false; this._summary.navigate_focus(null, Gtk.DirectionType.TAB_BACKWARD, false); this._focusTrap.can_focus = true; return Clutter.EVENT_STOP; } return Clutter.EVENT_PROPAGATE; }, _onNotificationKeyRelease: function(actor, event) { if (event.get_key_symbol() == Clutter.KEY_Escape && event.get_state() == 0) { this._expireNotification(); return Clutter.EVENT_STOP; } return Clutter.EVENT_PROPAGATE; }, _expireNotification: function() { this._notificationExpired = true; this._updateState(); }, _closeNotification: function() { if (this._notificationState == State.SHOWN) { this._closeButton.hide(); this._notification.emit('done-displaying'); this._notification.destroy(); } }, contains: function(source) { return this._sources.has(source); }, add: function(source) { if (this.contains(source)) { log('Trying to re-add source ' + source.title); return; } // Register that we got a notification for this source source.policy.store(); source.policy.connect('enable-changed', Lang.bind(this, this._onSourceEnableChanged, source)); source.policy.connect('policy-changed', Lang.bind(this, this._updateState)); this._onSourceEnableChanged(source.policy, source); }, _addSource: function(source) { let obj = { source: source, summaryItem: new SummaryItem(source), notifyId: 0, destroyId: 0, mutedChangedId: 0 }; let summaryItem = obj.summaryItem; if (source.isChat) { this._summary.insert_child_at_index(summaryItem.actor, 0); this._chatSummaryItemsCount++; } else { this._summary.insert_child_at_index(summaryItem.actor, this._chatSummaryItemsCount); } if (source.isClearable) this.clearableCount++; this._sources.set(source, obj); obj.notifyId = source.connect('notify', Lang.bind(this, this._onNotify)); obj.destroyId = source.connect('destroy', Lang.bind(this, this._onSourceDestroy)); obj.mutedChangedId = source.connect('muted-changed', Lang.bind(this, function () { if (source.isMuted) this._notificationQueue = this._notificationQueue.filter(function(notification) { return source != notification.source; }); })); summaryItem.actor.connect('clicked', Lang.bind(this, function(actor, button) { actor.grab_key_focus(); this._onSummaryItemClicked(summaryItem, button); })); summaryItem.actor.connect('popup-menu', Lang.bind(this, function(actor, button) { actor.grab_key_focus(); this._onSummaryItemClicked(summaryItem, 3); })); // We need to display the newly-added summary item, but if the // caller is about to post a notification, we want to show that // *first* and not show the summary item until after it hides. // So postpone calling _updateState() a tiny bit. Meta.later_add(Meta.LaterType.BEFORE_REDRAW, Lang.bind(this, function() { this._updateState(); return false; })); this.emit('source-added', source); this._updateNoMessagesLabel(); }, _removeSource: function(source) { let obj = this._sources.get(source); this._sources.delete(source); let summaryItem = obj.summaryItem; if (source.isChat) this._chatSummaryItemsCount--; if (source.isClearable) this.clearableCount--; source.disconnect(obj.notifyId); source.disconnect(obj.destroyId); source.disconnect(obj.mutedChangedId); summaryItem.destroy(); this.emit('source-removed', source); this._updateNoMessagesLabel(); }, getSources: function() { return [k for (k of this._sources.keys())]; }, _onSourceEnableChanged: function(policy, source) { let wasEnabled = this.contains(source); let shouldBeEnabled = policy.enable; if (wasEnabled != shouldBeEnabled) { if (shouldBeEnabled) this._addSource(source); else this._removeSource(source); } }, _onSourceDestroy: function(source) { this._removeSource(source); }, _onNotificationDestroy: function(notification) { if (this._notification == notification && (this._notificationState == State.SHOWN || this._notificationState == State.SHOWING)) { this._updateNotificationTimeout(0); this._notificationRemoved = true; this._updateState(); return; } let index = this._notificationQueue.indexOf(notification); if (index != -1) this._notificationQueue.splice(index, 1); }, openTray: function() { if (Main.overview.animationInProgress) return; this._traySummoned = true; this._updateState(); }, toggle: function() { if (Main.overview.animationInProgress) return false; this._traySummoned = !this._traySummoned; this._updateState(); return true; }, toggleAndNavigate: function() { if (!this.toggle()) return; if (this._traySummoned) this._summary.navigate_focus(null, Gtk.DirectionType.TAB_FORWARD, false); }, hide: function() { this._traySummoned = false; this._updateState(); }, _onNotify: function(source, notification) { if (this._summaryBoxPointerItem && this._summaryBoxPointerItem.source == source) { if (this._summaryBoxPointerState == State.HIDING) { // We are in the process of hiding the summary box pointer. // If there is an update for one of the notifications or // a new notification to be added to the notification stack // while it is in the process of being hidden, we show it as // a new notification. However, we first wait till the hide // is complete. This is especially important if one of the // notifications in the stack was updated because we will // need to be able to re-parent its actor to a different // part of the stage. this._reNotifyAfterHideNotification = notification; } else { // The summary box pointer is showing or shown (otherwise, // this._summaryBoxPointerItem would be null) // Immediately mark the notification as acknowledged and play its // sound, as it's not going into the queue notification.acknowledged = true; notification.playSound(); } return; } if (this._notification == notification) { // If a notification that is being shown is updated, we update // how it is shown and extend the time until it auto-hides. // If a new notification is updated while it is being hidden, // we stop hiding it and show it again. this._updateShowingNotification(); } else if (this._notificationQueue.indexOf(notification) < 0) { notification.connect('destroy', Lang.bind(this, this._onNotificationDestroy)); this._notificationQueue.push(notification); this._notificationQueue.sort(function(notification1, notification2) { return (notification2.urgency - notification1.urgency); }); } this._updateState(); }, _onSummaryItemClicked: function(summaryItem, button) { if (summaryItem.source.handleSummaryClick(button)) { if (summaryItem.source.keepTrayOnSummaryClick) this._setClickedSummaryItem(null); else this._escapeTray(); } else { if (!this._setClickedSummaryItem(summaryItem, button)) this._setClickedSummaryItem(null); } this._updateState(); }, _hotCornersChanged: function() { let primary = Main.layoutManager.primaryIndex; let corner = Main.layoutManager.hotCorners[primary]; if (corner && corner.actor) this._grabHelper.addActor(corner.actor); }, _resetNotificationLeftTimeout: function() { this._useLongerNotificationLeftTimeout = false; if (this._notificationLeftTimeoutId) { Mainloop.source_remove(this._notificationLeftTimeoutId); this._notificationLeftTimeoutId = 0; this._notificationLeftMouseX = -1; this._notificationLeftMouseY = -1; } }, _onNotificationHoverChanged: function() { if (this._notificationWidget.hover == this._notificationHovered) return; this._notificationHovered = this._notificationWidget.hover; if (this._notificationHovered) { // No dwell inside notifications at the bottom of the screen this._cancelTrayDwell(); this._resetNotificationLeftTimeout(); if (this._showNotificationMouseX >= 0) { let actorAtShowNotificationPosition = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, this._showNotificationMouseX, this._showNotificationMouseY); this._showNotificationMouseX = -1; this._showNotificationMouseY = -1; // Don't set this._pointerInNotification to true if the pointer was initially in the area where the notification // popped up. That way we will not be expanding notifications that happen to pop up over the pointer // automatically. Instead, the user is able to expand the notification by mousing away from it and then // mousing back in. Because this is an expected action, we set the boolean flag that indicates that a longer // timeout should be used before popping down the notification. if (this.actor.contains(actorAtShowNotificationPosition)) { this._useLongerNotificationLeftTimeout = true; return; } } this._pointerInNotification = true; this._updateState(); } else { // We record the position of the mouse the moment it leaves the tray. These coordinates are used in // this._onNotificationLeftTimeout() to determine if the mouse has moved far enough during the initial timeout for us // to consider that the user intended to leave the tray and therefore hide the tray. If the mouse is still // close to its previous position, we extend the timeout once. let [x, y, mods] = global.get_pointer(); this._notificationLeftMouseX = x; this._notificationLeftMouseY = y; // We wait just a little before hiding the message tray in case the user quickly moves the mouse back into it. // We wait for a longer period if the notification popped up where the mouse pointer was already positioned. // That gives the user more time to mouse away from the notification and mouse back in in order to expand it. let timeout = this._useLongerNotificationLeftTimeout ? LONGER_HIDE_TIMEOUT * 1000 : HIDE_TIMEOUT * 1000; this._notificationLeftTimeoutId = Mainloop.timeout_add(timeout, Lang.bind(this, this._onNotificationLeftTimeout)); GLib.Source.set_name_by_id(this._notificationLeftTimeoutId, '[gnome-shell] this._onNotificationLeftTimeout'); } }, _onKeyboardVisibleChanged: function(layoutManager, keyboardVisible) { this._keyboardVisible = keyboardVisible; this._updateState(); }, _onStatusChanged: function(status) { if (status == GnomeSession.PresenceStatus.BUSY) { // remove notification and allow the summary to be closed now this._updateNotificationTimeout(0); this._busy = true; } else if (status != GnomeSession.PresenceStatus.IDLE) { // We preserve the previous value of this._busy if the status turns to IDLE // so that we don't start showing notifications queued during the BUSY state // as the screensaver gets activated. this._busy = false; } this._updateState(); }, _onNotificationLeftTimeout: function() { let [x, y, mods] = global.get_pointer(); // We extend the timeout once if the mouse moved no further than MOUSE_LEFT_ACTOR_THRESHOLD to either side or up. // We don't check how far down the mouse moved because any point above the tray, but below the exit coordinate, // is close to the tray. if (this._notificationLeftMouseX > -1 && y > this._notificationLeftMouseY - MOUSE_LEFT_ACTOR_THRESHOLD && x < this._notificationLeftMouseX + MOUSE_LEFT_ACTOR_THRESHOLD && x > this._notificationLeftMouseX - MOUSE_LEFT_ACTOR_THRESHOLD) { this._notificationLeftMouseX = -1; this._notificationLeftTimeoutId = Mainloop.timeout_add(LONGER_HIDE_TIMEOUT * 1000, Lang.bind(this, this._onNotificationLeftTimeout)); GLib.Source.set_name_by_id(this._notificationLeftTimeoutId, '[gnome-shell] this._onNotificationLeftTimeout'); } else { this._notificationLeftTimeoutId = 0; this._useLongerNotificationLeftTimeout = false; this._pointerInNotification = false; this._updateNotificationTimeout(0); this._updateState(); } return GLib.SOURCE_REMOVE; }, _escapeTray: function() { this._pointerInNotification = false; this._traySummoned = false; this._setClickedSummaryItem(null); this._updateNotificationTimeout(0); this._updateState(); }, // All of the logic for what happens when occurs here; the various // event handlers merely update variables such as // 'this._pointerInNotification', 'this._traySummoned', etc, and // _updateState() figures out what (if anything) needs to be done // at the present time. _updateState: function() { // If our state changes caused _updateState to be called, // just exit now to prevent reentrancy issues. if (this._updatingState) return; this._updatingState = true; // Filter out acknowledged notifications. this._notificationQueue = this._notificationQueue.filter(function(n) { return !n.acknowledged; }); let hasNotifications = Main.sessionMode.hasNotifications; if (this._notificationState == State.HIDDEN) { let shouldShowNotification = (hasNotifications && this._trayState == State.HIDDEN && !this._traySummoned); let nextNotification = this._notificationQueue[0] || null; if (shouldShowNotification && nextNotification) { let limited = this._busy || Main.layoutManager.bottomMonitor.inFullscreen; let showNextNotification = (!limited || nextNotification.forFeedback || nextNotification.urgency == Urgency.CRITICAL); if (showNextNotification) { let len = this._notificationQueue.length; if (len > 1) { this._notificationQueue.length = 0; let source = new SystemNotificationSource(); this.add(source); let notification = new Notification(source, ngettext("%d new message", "%d new messages", len).format(len)); notification.setTransient(true); notification.connect('clicked', Lang.bind(this, function() { this.openTray(); })); source.notify(notification); } else { this._showNotification(); } } } } else if (this._notificationState == State.SHOWN) { let expired = (this._userActiveWhileNotificationShown && this._notificationTimeoutId == 0 && this._notification.urgency != Urgency.CRITICAL && !this._notification.focused && !this._pointerInNotification) || this._notificationExpired; let mustClose = (this._notificationRemoved || !hasNotifications || expired || this._traySummoned); if (mustClose) { let animate = hasNotifications && !this._notificationRemoved; this._hideNotification(animate); } else if (this._pointerInNotification && !this._notification.expanded) { this._expandNotification(false); } else if (this._pointerInNotification) { this._ensureNotificationFocused(); } } // Summary notification let haveClickedSummaryItem = this._clickedSummaryItem != null; let requestedNotificationStackIsEmpty = (haveClickedSummaryItem && this._clickedSummaryItemMouseButton == 1 && this._clickedSummaryItem.source.notifications.length == 0); if (this._summaryBoxPointerState == State.HIDDEN) { if (haveClickedSummaryItem && !requestedNotificationStackIsEmpty) this._showSummaryBoxPointer(); } else if (this._summaryBoxPointerState == State.SHOWN) { if (haveClickedSummaryItem && hasNotifications) { let wrongSummaryNotificationStack = (this._clickedSummaryItemMouseButton == 1 && this._summaryBoxPointer.bin.child != this._clickedSummaryItem.notificationStackWidget && requestedNotificationStackIsEmpty); let wrongSummaryRightClickMenu = (this._clickedSummaryItemMouseButton == 3 && this._clickedSummaryItem.rightClickMenu != null && this._summaryBoxPointer.bin.child != this._clickedSummaryItem.rightClickMenu); let wrongSummaryBoxPointer = (wrongSummaryNotificationStack || wrongSummaryRightClickMenu); if (wrongSummaryBoxPointer) { this._hideSummaryBoxPointer(); this._showSummaryBoxPointer(); } } else { this._hideSummaryBoxPointer(); } } // Tray itself let trayIsVisible = (this._trayState == State.SHOWING || this._trayState == State.SHOWN); let trayShouldBeVisible = this._traySummoned && !this._keyboardVisible && hasNotifications; if (!trayIsVisible && trayShouldBeVisible) trayShouldBeVisible = this._showTray(); else if (trayIsVisible && !trayShouldBeVisible) this._hideTray(); // Desktop clone let desktopCloneIsVisible = (this._desktopCloneState == State.SHOWING || this._desktopCloneState == State.SHOWN); let desktopCloneShouldBeVisible = (trayShouldBeVisible); if (!desktopCloneIsVisible && desktopCloneShouldBeVisible) this._showDesktopClone(); else if (desktopCloneIsVisible && !desktopCloneShouldBeVisible) this._hideDesktopClone(); this._updatingState = false; // Clean transient variables that are used to communicate actions // to updateState() this._notificationExpired = false; }, _tween: function(actor, statevar, value, params) { let onComplete = params.onComplete; let onCompleteScope = params.onCompleteScope; let onCompleteParams = params.onCompleteParams; params.onComplete = this._tweenComplete; params.onCompleteScope = this; params.onCompleteParams = [statevar, value, onComplete, onCompleteScope, onCompleteParams]; // Remove other tweens that could mess with the state machine Tweener.removeTweens(actor); Tweener.addTween(actor, params); let valuing = (value == State.SHOWN) ? State.SHOWING : State.HIDING; this[statevar] = valuing; }, _tweenComplete: function(statevar, value, onComplete, onCompleteScope, onCompleteParams) { this[statevar] = value; if (onComplete) onComplete.apply(onCompleteScope, onCompleteParams); this._updateState(); }, _showTray: function() { if (!this._grabHelper.grab({ actor: this.actor, onUngrab: Lang.bind(this, this._escapeTray) })) { this._traySummoned = false; return false; } this.emit('showing'); this._tween(this.actor, '_trayState', State.SHOWN, { y: -this.actor.height, time: ANIMATION_TIME, transition: 'easeOutQuad' }); for (let i = 0; i < this._lightboxes.length; i++) this._lightboxes[i].show(ANIMATION_TIME); return true; }, _updateDesktopCloneClip: function() { let geometry = this._bottomMonitorGeometry; let progress = -Math.round(this._desktopClone.y); this._desktopClone.set_clip(geometry.x, geometry.y + progress, geometry.width, geometry.height - progress); }, _showDesktopClone: function() { let bottomMonitor = Main.layoutManager.bottomMonitor; this._bottomMonitorGeometry = { x: bottomMonitor.x, y: bottomMonitor.y, width: bottomMonitor.width, height: bottomMonitor.height }; if (this._desktopClone) this._desktopClone.destroy(); let cloneSource = Main.overview.visible ? Main.layoutManager.overviewGroup : global.window_group; this._desktopClone = new Clutter.Clone({ source: cloneSource, clip: new Clutter.Geometry(this._bottomMonitorGeometry) }); Main.uiGroup.insert_child_above(this._desktopClone, cloneSource); this._desktopClone.x = 0; this._desktopClone.y = 0; this._desktopClone.show(); this._tween(this._desktopClone, '_desktopCloneState', State.SHOWN, { y: -this.actor.height, time: ANIMATION_TIME, transition: 'easeOutQuad', onUpdate: Lang.bind(this, this._updateDesktopCloneClip) }); }, _hideTray: function() { // Having the summary item animate out while sliding down the tray // is distracting, so hide it immediately in case it was visible. this._summaryBoxPointer.actor.hide(); this.emit('hiding'); this._tween(this.actor, '_trayState', State.HIDDEN, { y: 0, time: ANIMATION_TIME, transition: 'easeOutQuad' }); // Note that we might have entered here without a grab, // which would happen if GrabHelper ungrabbed for us. // This is a no-op in that case. this._grabHelper.ungrab({ actor: this.actor }); for (let i = 0; i < this._lightboxes.length; i++) this._lightboxes[i].hide(ANIMATION_TIME); }, _hideDesktopClone: function() { this._tween(this._desktopClone, '_desktopCloneState', State.HIDDEN, { y: 0, time: ANIMATION_TIME, transition: 'easeOutQuad', onComplete: Lang.bind(this, function() { this._desktopClone.destroy(); this._desktopClone = null; this._bottomMonitorGeometry = null; }), onUpdate: Lang.bind(this, this._updateDesktopCloneClip) }); }, _onIdleMonitorBecameActive: function() { this._userActiveWhileNotificationShown = true; this._updateNotificationTimeout(2000); this._updateState(); }, _showNotification: function() { this._notification = this._notificationQueue.shift(); this._userActiveWhileNotificationShown = this.idleMonitor.get_idletime() <= IDLE_TIME; if (!this._userActiveWhileNotificationShown) { // If the user isn't active, set up a watch to let us know // when the user becomes active. this.idleMonitor.add_user_active_watch(Lang.bind(this, this._onIdleMonitorBecameActive)); } this._notificationClickedId = this._notification.connect('done-displaying', Lang.bind(this, this._escapeTray)); this._notificationUnfocusedId = this._notification.connect('unfocused', Lang.bind(this, function() { this._updateState(); })); this._notificationBin.child = this._notification.actor; this._notificationWidget.opacity = 0; this._notificationWidget.y = 0; this._notificationWidget.show(); this._updateShowingNotification(); let [x, y, mods] = global.get_pointer(); // We save the position of the mouse at the time when we started showing the notification // in order to determine if the notification popped up under it. We make that check if // the user starts moving the mouse and _onNotificationHoverChanged() gets called. We don't // expand the notification if it just happened to pop up under the mouse unless the user // explicitly mouses away from it and then mouses back in. this._showNotificationMouseX = x; this._showNotificationMouseY = y; // We save the coordinates of the mouse at the time when we started showing the notification // and then we update it in _notificationTimeout(). We don't pop down the notification if // the mouse is moving towards it or within it. this._lastSeenMouseX = x; this._lastSeenMouseY = y; this._resetNotificationLeftTimeout(); }, _updateShowingNotification: function() { this._notification.acknowledged = true; this._notification.playSound(); // We auto-expand notifications with CRITICAL urgency, or for which the relevant setting // is on in the control center. if (this._notification.urgency == Urgency.CRITICAL || this._notification.source.policy.forceExpanded) this._expandNotification(true); // We tween all notifications to full opacity. This ensures that both new notifications and // notifications that might have been in the process of hiding get full opacity. // // We tween any notification showing in the banner mode to the appropriate height // (which is banner height or expanded height, depending on the notification state) // This ensures that both new notifications and notifications in the banner mode that might // have been in the process of hiding are shown with the correct height. // // We use this._showNotificationCompleted() onComplete callback to extend the time the updated // notification is being shown. let tweenParams = { opacity: 255, y: -this._notificationWidget.height, time: ANIMATION_TIME, transition: 'easeOutQuad', onComplete: this._showNotificationCompleted, onCompleteScope: this }; this._tween(this._notificationWidget, '_notificationState', State.SHOWN, tweenParams); }, _showNotificationCompleted: function() { if (this._notification.urgency != Urgency.CRITICAL) this._updateNotificationTimeout(NOTIFICATION_TIMEOUT * 1000); }, _updateNotificationTimeout: function(timeout) { if (this._notificationTimeoutId) { Mainloop.source_remove(this._notificationTimeoutId); this._notificationTimeoutId = 0; } if (timeout > 0) { this._notificationTimeoutId = Mainloop.timeout_add(timeout, Lang.bind(this, this._notificationTimeout)); GLib.Source.set_name_by_id(this._notificationTimeoutId, '[gnome-shell] this._notificationTimeout'); } }, _notificationTimeout: function() { let [x, y, mods] = global.get_pointer(); if (y > this._lastSeenMouseY + 10 && !this._notificationHovered) { // The mouse is moving towards the notification, so don't // hide it yet. (We just create a new timeout (and destroy // the old one) each time because the bookkeeping is // simpler.) this._updateNotificationTimeout(1000); } else if (this._useLongerNotificationLeftTimeout && !this._notificationLeftTimeoutId && (x != this._lastSeenMouseX || y != this._lastSeenMouseY)) { // Refresh the timeout if the notification originally // popped up under the pointer, and the pointer is hovering // inside it. this._updateNotificationTimeout(1000); } else { this._notificationTimeoutId = 0; this._updateState(); } this._lastSeenMouseX = x; this._lastSeenMouseY = y; return GLib.SOURCE_REMOVE; }, _hideNotification: function(animate) { this._notificationFocusGrabber.ungrabFocus(); if (this._notificationExpandedId) { this._notification.disconnect(this._notificationExpandedId); this._notificationExpandedId = 0; } if (this._notificationClickedId) { this._notification.disconnect(this._notificationClickedId); this._notificationClickedId = 0; } if (this._notificationUnfocusedId) { this._notification.disconnect(this._notificationUnfocusedId); this._notificationUnfocusedId = 0; } this._resetNotificationLeftTimeout(); if (animate) { this._tween(this._notificationWidget, '_notificationState', State.HIDDEN, { y: this.actor.height, opacity: 0, time: ANIMATION_TIME, transition: 'easeOutQuad', onComplete: this._hideNotificationCompleted, onCompleteScope: this }); } else { Tweener.removeTweens(this._notificationWidget); this._notificationWidget.y = this.actor.height; this._notificationWidget.opacity = 0; this._notificationState = State.HIDDEN; this._hideNotificationCompleted(); } }, _hideNotificationCompleted: function() { this._notification.collapseCompleted(); let notification = this._notification; this._notification = null; if (notification.isTransient) notification.destroy(NotificationDestroyedReason.EXPIRED); this._closeButton.hide(); this._pointerInNotification = false; this._notificationRemoved = false; this._notificationBin.child = null; this._notificationWidget.hide(); }, _expandActiveNotification: function() { if (!this._notification) return; this._expandNotification(false); }, _expandNotification: function(autoExpanding) { if (!this._notificationExpandedId) this._notificationExpandedId = this._notification.connect('expanded', Lang.bind(this, this._onNotificationExpanded)); // Don't animate changes in notifications that are auto-expanding. this._notification.expand(!autoExpanding); // Don't focus notifications that are auto-expanding. if (!autoExpanding) this._ensureNotificationFocused(); }, _onNotificationExpanded: function() { let expandedY = - this._notificationWidget.height; this._closeButton.show(); // Don't animate the notification to its new position if it has shrunk: // there will be a very visible "gap" that breaks the illusion. if (this._notificationWidget.y < expandedY) { this._notificationWidget.y = expandedY; } else if (this._notification.y != expandedY) { // Tween also opacity here, to override a possible tween that's // currently hiding the notification. Tweener.addTween(this._notificationWidget, { y: expandedY, opacity: 255, time: ANIMATION_TIME, transition: 'easeOutQuad', // HACK: Drive the state machine here better, // instead of overwriting tweens onComplete: Lang.bind(this, function() { this._notificationState = State.SHOWN; }), }); } }, _ensureNotificationFocused: function() { this._notificationFocusGrabber.grabFocus(); }, _onSourceDoneDisplayingContent: function(source, closeTray) { if (closeTray) { this._escapeTray(); } else { this._setClickedSummaryItem(null); this._updateState(); } }, _showSummaryBoxPointer: function() { let child; let summaryItem = this._clickedSummaryItem; if (this._clickedSummaryItemMouseButton == 1) { // Acknowledge all our notifications summaryItem.source.notifications.forEach(function(n) { n.acknowledged = true; }); summaryItem.prepareNotificationStackForShowing(); child = summaryItem.notificationStackWidget; } else if (this._clickedSummaryItemMouseButton == 3) { child = summaryItem.rightClickMenu; } // If the user clicked the middle mouse button, or the item // doesn't have a right-click menu, do nothing. if (!child) return; this._summaryBoxPointerItem = summaryItem; this._summaryBoxPointerContentUpdatedId = this._summaryBoxPointerItem.connect('content-updated', Lang.bind(this, this._onSummaryBoxPointerContentUpdated)); this._sourceDoneDisplayingId = this._summaryBoxPointerItem.source.connect('done-displaying-content', Lang.bind(this, this._onSourceDoneDisplayingContent)); this._summaryBoxPointer.bin.child = child; this._summaryBoxPointer.actor.opacity = 0; this._summaryBoxPointer.actor.show(); this._adjustSummaryBoxPointerPosition(); this._grabHelper.grab({ actor: this._summaryBoxPointer.bin.child, onUngrab: Lang.bind(this, this._onSummaryBoxPointerUngrabbed) }); this._summaryBoxPointerState = State.SHOWING; this._summaryBoxPointer.show(BoxPointer.PopupAnimation.FULL, Lang.bind(this, function() { this._summaryBoxPointerState = State.SHOWN; })); }, _onSummaryBoxPointerContentUpdated: function() { if (this._summaryBoxPointerItem.notificationStack.get_n_children() == 0) this._hideSummaryBoxPointer(); }, _adjustSummaryBoxPointerPosition: function() { this._summaryBoxPointer.setPosition(this._summaryBoxPointerItem.actor, 0); }, _setClickedSummaryItem: function(item, button) { if (item == this._clickedSummaryItem && button == this._clickedSummaryItemMouseButton) return false; if (this._clickedSummaryItem) { this._clickedSummaryItem.actor.remove_style_pseudo_class('selected'); this._clickedSummaryItem.actor.disconnect(this._clickedSummaryItemAllocationChangedId); this._summary.disconnect(this._summaryMotionId); this._clickedSummaryItemAllocationChangedId = 0; this._summaryMotionId = 0; } this._clickedSummaryItem = item; this._clickedSummaryItemMouseButton = button; if (this._clickedSummaryItem) { this._clickedSummaryItem.actor.add_style_pseudo_class('selected'); this._clickedSummaryItem.actor.connect('destroy', Lang.bind(this, function() { this._setClickedSummaryItem(null); this._updateState(); })); this._clickedSummaryItemAllocationChangedId = this._clickedSummaryItem.actor.connect('allocation-changed', Lang.bind(this, this._adjustSummaryBoxPointerPosition)); // _clickedSummaryItem.actor can change absolute position without changing allocation this._summaryMotionId = this._summary.connect('allocation-changed', Lang.bind(this, this._adjustSummaryBoxPointerPosition)); } return true; }, _onSummaryBoxPointerKeyPress: function(actor, event) { switch (event.get_key_symbol()) { case Clutter.KEY_Down: case Clutter.KEY_Escape: this._setClickedSummaryItem(null); this._updateState(); return Clutter.EVENT_STOP; case Clutter.KEY_Delete: this._clickedSummaryItem.source.destroy(); this._escapeTray(); return Clutter.EVENT_STOP; } return Clutter.EVENT_PROPAGATE; }, _onSummaryBoxPointerUngrabbed: function() { this._summaryBoxPointerState = State.HIDING; this._setClickedSummaryItem(null); if (this._summaryBoxPointerContentUpdatedId) { this._summaryBoxPointerItem.disconnect(this._summaryBoxPointerContentUpdatedId); this._summaryBoxPointerContentUpdatedId = 0; } if (this._sourceDoneDisplayingId) { this._summaryBoxPointerItem.source.disconnect(this._sourceDoneDisplayingId); this._sourceDoneDisplayingId = 0; } let animate = (this._summaryBoxPointerItem.source.notifications.length > 0); this._summaryBoxPointer.hide(animate ? BoxPointer.PopupAnimation.FULL : BoxPointer.PopupAnimation.NONE, Lang.bind(this, this._hideSummaryBoxPointerCompleted)); }, _hideSummaryBoxPointer: function() { this._grabHelper.ungrab({ actor: this._summaryBoxPointer.bin.child }); }, _hideSummaryBoxPointerCompleted: function() { let doneShowingNotificationStack = (this._summaryBoxPointer.bin.child == this._summaryBoxPointerItem.notificationStackWidget); this._summaryBoxPointerState = State.HIDDEN; this._summaryBoxPointer.bin.child = null; if (doneShowingNotificationStack) { let source = this._summaryBoxPointerItem.source; this._summaryBoxPointerItem.doneShowingNotificationStack(); this._summaryBoxPointerItem = null; if (this._reNotifyAfterHideNotification) { this._onNotify(this._reNotifyAfterHideNotification.source, this._reNotifyAfterHideNotification); this._reNotifyAfterHideNotification = null; } } if (this._clickedSummaryItem) this._updateState(); } }); Signals.addSignalMethods(MessageTray.prototype); const SystemNotificationSource = new Lang.Class({ Name: 'SystemNotificationSource', Extends: Source, _init: function() { this.parent(_("System Information"), 'dialog-information-symbolic'); }, open: function() { this.destroy(); } });
gpl-2.0
cran/rgl
src/PointSet.cpp
532
#include "PrimitiveSet.h" using namespace rgl; ////////////////////////////////////////////////////////////////////////////// // // CLASS // PointSet // PointSet::PointSet(Material& in_material, int in_nvertices, double* in_vertices, bool in_ignoreExtent, int in_nindices, int* in_indices, bool in_bboxChange) : PrimitiveSet(in_material, in_nvertices, in_vertices, GL_POINTS, 1, in_ignoreExtent, in_nindices, in_indices) { material.lit = false; if (material.point_antialias) blended = true; }
gpl-2.0
AgenceStratis/newsfal
ext_emconf.php
1151
<?php /*************************************************************** * Extension Manager/Repository config file for ext "newsfal". * * Auto generated 22-07-2013 17:51 * * Manual updates: * Only the data in the array - everything else is removed by next * writing. "version" and "dependencies" must not be touched! ***************************************************************/ $EM_CONF[$_EXTKEY] = array ( 'title' => 'News Fal', 'description' => 'Adds a FAL image field to news for further FE usage. Supports media extension.', 'category' => 'be', 'author' => 'Fedir RYKHTIK', 'author_email' => 'fedir@stratis.fr', 'shy' => '', 'dependencies' => 'news', 'conflicts' => NULL, 'priority' => '', 'module' => '', 'state' => 'stable', 'internal' => '', 'uploadfolder' => 1, 'createDirs' => '', 'modify_tables' => '', 'clearCacheOnLoad' => 0, 'lockType' => '', 'author_company' => 'Stratis', 'version' => '0.2.0', 'constraints' => array ( 'depends' => array ( 'news' => '2.1.0-2.1.99', 'typo3' => '6.1.0-6.1.99', ), 'conflicts' => '', 'suggests' => array ( ), ), 'suggests' => array ( ), ); ?>
gpl-2.0
Falcury/java-labs
FirstProject/src/tutorials/Main.java
244
package tutorials; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; public class Main { public static void main(String[] args) { try { Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } } }
gpl-2.0
newera912/WeatherTransportationProject
transWeatherPy/plotMesonetOrgData.py
10717
import matplotlib.pyplot as plt import numpy as np def plot10seperate(): mons=["201603","201604","201605","201606","201607","201608"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] rootpath="F:/workspace/git/TranWeatherProject/data/mesonet_data/" for mon in ["201604"]: for day in days: print mon+day fileName=rootpath+mon+day+".txt" day_data=[] with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[(i*5.0/60.0) for i in range(1,len(day_data[0][2]),1)] fig=plt.figure(1) fig.add_subplot(10,1,1) plt.plot(X,day_data[0][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[0][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,2) plt.plot(X,day_data[1][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[1][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,3) plt.plot(X,day_data[2][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[2][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,4) plt.plot(X,day_data[3][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[3][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,5) plt.plot(X,day_data[4][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[4][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,6) plt.plot(X,day_data[5][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[5][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,7) plt.plot(X,day_data[6][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[6][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,8) plt.plot(X,day_data[7][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[7][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,9) plt.plot(X,day_data[8][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period From 00:00am ~23:59') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[8][0]+" Station Date: "+mon+day +"Temperature") fig.add_subplot(10,1,10) plt.plot(X,day_data[9][2],'b*-',linewidth='2.0', markersize=5,label='Temperature') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) #plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) plt.ylim([-20.0,60.0]) plt.xlabel('time Period') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.title(day_data[9][0]+" Station Date: "+mon+day +"Temperature") plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) plt.show() fig.savefig('F:/workspace/git/TranWeatherProject/outputs/mesonetPlots/'+str(mon+day)+'.png') plt.close() import os def plotSignle(): mons=["201603","201604","201605","201606","201607","201608","201609"] #mons=["201609"] days=['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] sta_names={0:"BATA",1:"SBRI",2:"WATE",3:"JORD",4:"CSQR",5:"WEST",6:"COLD",7:"SPRA",8:"COBL",9:"STEP"} var_type="wind" rootpath="F:/workspace/git/TranWeatherProject/data/mesonet_data/"+var_type+"/" for mon in mons: for day in days: fileName=rootpath+mon+day+".txt" print fileName day_data=[] if not os.path.exists(fileName): continue with open(fileName,"r") as df: for line in df.readlines(): terms=line.strip().split() sta_name=terms[0] data=map(float,terms[1:]) day_data.append((sta_name,mon+day,data)) X=[i for i in range(0,len(day_data[0][2]))] label=[(str(i)+"\n"+str(i*5/60)+"h") for i in range(0,len(day_data[0][2])+1,12)] print sta_names[int(day_data[0][0])] fig=plt.figure(1) plt.plot(X,day_data[0][2],'b-',linewidth='1.0', markersize=5,label=sta_names[int(day_data[0][0])]+day_data[0][0]) plt.plot(X,day_data[1][2],'r-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[1][0])])+day_data[1][0]) plt.plot(X,day_data[2][2],'k-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[2][0])])+day_data[2][0]) plt.plot(X,day_data[3][2],'g-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[3][0])])+day_data[3][0]) plt.plot(X,day_data[4][2],'y-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[4][0])])+day_data[4][0]) plt.plot(X,day_data[5][2],'c-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[5][0])])+day_data[5][0]) plt.plot(X,day_data[6][2],'m-',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[6][0])])+day_data[6][0]) plt.plot(X,day_data[7][2],color ='#B47CC7',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[7][0])])+day_data[7][0]) plt.plot(X,day_data[8][2],color='#FBC15E',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[8][0])])+day_data[8][0]) plt.plot(X,day_data[9][2],color='#e5ee38',linewidth='1.0', markersize=5,label=str(sta_names[int(day_data[9][0])])+day_data[9][0]) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,ncol=1, mode="expand", borderaxespad=0.) plt.plot([0.2,0.1,0.0],[0.5,0.5,0.5]) if var_type=="wind": plt.ylim([-5.0,70.0]) plt.ylabel('Avg. Wind Speed(mph)') plt.title(mon+day +"Every 5min Avg. Wind") else: plt.ylim([-10.0,100.0]) plt.ylabel('Temperature(F)') plt.title(mon+day +"Temperature") #plt.xticks(np.arange(min(X), max(X)+2, 12.0)) plt.xticks(np.arange(min(X), max(X)+2, 12.0),label) plt.tick_params(axis='both', which='major', labelsize=7) plt.xlabel('Time from 00:00 ~23:59,each 5min') #plt.xlim([0.2,0.0]) plt.legend(loc='best',fontsize=8) plt.grid() #plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) #plt.show() fig.savefig('F:/workspace/git/TranWeatherProject/outputs/mesonetPlots/'+var_type+'_plots/'+str(mon+day)+'.png') plt.close() plotSignle()
gpl-2.0
andydunkel/jCryptPad
project/src/daimanager/PasswordGeneratorDialog.java
10765
package daimanager; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import javax.swing.DefaultListModel; import javax.swing.ListSelectionModel; import pwgenerator.PasswordGenerator; /** * PasswordGeneratorDialog.java * * The password generator of the application * * @author Andy Dunkel andy.dunkel"at"ekiwi.de * @author published under the terms and conditions of the * GNU General Public License, * for details see file gpl.txt in the distribution * package of this software * */ public class PasswordGeneratorDialog extends javax.swing.JDialog { /** Creates new form PasswordGeneratorDialog */ public PasswordGeneratorDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); listPasswords.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Create Model for List listPasswords.setModel(new DefaultListModel()); //add popup to list listPasswords.setComponentPopupMenu(mnuPasswords); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); mnuPasswords = new javax.swing.JPopupMenu(); itemCopy = new javax.swing.JMenuItem(); jLabel1 = new javax.swing.JLabel(); edtPasswordLength = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); edtPasswordCount = new javax.swing.JTextField(); chkSpecialChars = new javax.swing.JCheckBox(); chkNumbers = new javax.swing.JCheckBox(); chkCapitals = new javax.swing.JCheckBox(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); listPasswords = new javax.swing.JList(); btGenPW = new javax.swing.JButton(); jButton1.setText("jButton1"); itemCopy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/copy16.png"))); // NOI18N itemCopy.setText("Copy"); itemCopy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { copyPassword(evt); } }); mnuPasswords.add(itemCopy); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setText("Password length"); edtPasswordLength.setText("10"); jLabel2.setText("How many passwords?"); edtPasswordCount.setText("5"); chkSpecialChars.setText("Include special characters"); chkNumbers.setText("Include numbers"); chkCapitals.setText("Include Captitals"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Passwords")); jPanel1.setToolTipText(""); listPasswords.setFont(new java.awt.Font("Courier New", 0, 11)); listPasswords.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane1.setViewportView(listPasswords); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE) ); btGenPW.setText("Generate Passwords"); btGenPW.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { generatePasswords(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(btGenPW, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(edtPasswordCount) .addComponent(edtPasswordLength, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chkNumbers) .addComponent(chkSpecialChars) .addComponent(chkCapitals)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(chkSpecialChars) .addComponent(edtPasswordLength, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(chkNumbers) .addComponent(edtPasswordCount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkCapitals) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btGenPW) .addGap(9, 9, 9) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Generate Passwords * @param evt */ private void generatePasswords(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generatePasswords PasswordGenerator pg = new PasswordGenerator(); pg.setCapitalsAllowed(chkCapitals.isSelected()); pg.setNumbersAllowed(chkNumbers.isSelected()); pg.setSpecialCharsAllowed(chkSpecialChars.isSelected()); ((DefaultListModel)listPasswords.getModel()).clear(); Integer length = new Integer(edtPasswordLength.getText()); Integer count = new Integer(edtPasswordCount.getText()); for (int i = 0; i < count; i++) { DefaultListModel m = (DefaultListModel)listPasswords.getModel(); String pw = pg.generatePassword(length); m.addElement(pw); System.out.println(pw); } }//GEN-LAST:event_generatePasswords private void copyPassword(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyPassword int indexSelected = listPasswords.getSelectedIndex(); if (indexSelected != -1) { String value = (String)(((DefaultListModel)listPasswords.getModel()).getElementAt(indexSelected)); StringSelection ss = new StringSelection(value); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); } }//GEN-LAST:event_copyPassword /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { PasswordGeneratorDialog dialog = new PasswordGeneratorDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btGenPW; private javax.swing.JCheckBox chkCapitals; private javax.swing.JCheckBox chkNumbers; private javax.swing.JCheckBox chkSpecialChars; private javax.swing.JTextField edtPasswordCount; private javax.swing.JTextField edtPasswordLength; private javax.swing.JMenuItem itemCopy; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JList listPasswords; private javax.swing.JPopupMenu mnuPasswords; // End of variables declaration//GEN-END:variables }
gpl-2.0
hackelection/electionhack
test/spec/directives/campaign.js
493
'use strict'; describe('Directive: campaign', function () { // load the directive's module beforeEach(module('electionhackApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<campaign></campaign>'); element = $compile(element)(scope); expect(element.text()).toBe('this is the campaign directive'); })); });
gpl-2.0
sungsoo/esper
esper/src/main/java/com/espertech/esper/epl/agg/service/AggSvcGroupByReclaimAgedImpl.java
12576
/************************************************************************************** * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * **************************************************************************************/ package com.espertech.esper.epl.agg.service; import com.espertech.esper.client.EventBean; import com.espertech.esper.epl.agg.access.AggregationState; import com.espertech.esper.epl.agg.access.AggregationAccessorSlotPair; import com.espertech.esper.epl.agg.aggregator.AggregationMethod; import com.espertech.esper.epl.core.MethodResolutionService; import com.espertech.esper.epl.expression.ExprEvaluator; import com.espertech.esper.epl.expression.ExprEvaluatorContext; import com.espertech.esper.util.ExecutionPathDebugLog; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.*; /** * Implementation for handling aggregation with grouping by group-keys. */ public class AggSvcGroupByReclaimAgedImpl extends AggregationServiceBaseGrouped { private static final Log log = LogFactory.getLog(AggSvcGroupByReclaimAgedImpl.class); private static final long DEFAULT_MAX_AGE_MSEC = 60000L; private final AggregationAccessorSlotPair[] accessors; protected final AggregationStateFactory[] accessAggregations; protected final boolean isJoin; private final AggSvcGroupByReclaimAgedEvalFunc evaluationFunctionMaxAge; private final AggSvcGroupByReclaimAgedEvalFunc evaluationFunctionFrequency; private final MethodResolutionService methodResolutionService; // maintain for each group a row of aggregator states that the expression node canb pull the data from via index protected Map<Object, AggregationMethodRowAged> aggregatorsPerGroup; // maintain a current row for random access into the aggregator state table // (row=groups, columns=expression nodes that have aggregation functions) private AggregationMethod[] currentAggregatorMethods; private AggregationState[] currentAggregatorStates; private List<Object> removedKeys; private Long nextSweepTime = null; private AggregationRowRemovedCallback removedCallback; private volatile long currentMaxAge = DEFAULT_MAX_AGE_MSEC; private volatile long currentReclaimFrequency = DEFAULT_MAX_AGE_MSEC; public AggSvcGroupByReclaimAgedImpl(ExprEvaluator evaluators[], AggregationMethodFactory aggregators[], AggregationAccessorSlotPair[] accessors, AggregationStateFactory[] accessAggregations, boolean join, AggSvcGroupByReclaimAgedEvalFunc evaluationFunctionMaxAge, AggSvcGroupByReclaimAgedEvalFunc evaluationFunctionFrequency, MethodResolutionService methodResolutionService) { super(evaluators, aggregators); this.accessors = accessors; this.accessAggregations = accessAggregations; isJoin = join; this.evaluationFunctionMaxAge = evaluationFunctionMaxAge; this.evaluationFunctionFrequency = evaluationFunctionFrequency; this.methodResolutionService = methodResolutionService; this.aggregatorsPerGroup = new HashMap<Object, AggregationMethodRowAged>(); removedKeys = new ArrayList<Object>(); } public void clearResults(ExprEvaluatorContext exprEvaluatorContext) { aggregatorsPerGroup.clear(); } public void applyEnter(EventBean[] eventsPerStream, Object groupByKey, ExprEvaluatorContext exprEvaluatorContext) { long currentTime = exprEvaluatorContext.getTimeProvider().getTime(); if ((nextSweepTime == null) || (nextSweepTime <= currentTime)) { currentMaxAge = getMaxAge(currentMaxAge); currentReclaimFrequency = getReclaimFrequency(currentReclaimFrequency); if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) { log.debug("Reclaiming groups older then " + currentMaxAge + " msec and every " + currentReclaimFrequency + "msec in frequency"); } nextSweepTime = currentTime + currentReclaimFrequency; sweep(currentTime, currentMaxAge); } handleRemovedKeys(); // we collect removed keys lazily on the next enter to reduce the chance of empty-group queries creating empty aggregators temporarily AggregationMethodRowAged row = aggregatorsPerGroup.get(groupByKey); // The aggregators for this group do not exist, need to create them from the prototypes AggregationMethod[] groupAggregators; AggregationState[] groupStates; if (row == null) { groupAggregators = methodResolutionService.newAggregators(aggregators, exprEvaluatorContext.getAgentInstanceId(), groupByKey); groupStates = methodResolutionService.newAccesses(exprEvaluatorContext.getAgentInstanceId(), isJoin, accessAggregations, groupByKey); row = new AggregationMethodRowAged(methodResolutionService.getCurrentRowCount(groupAggregators, groupStates) + 1, currentTime, groupAggregators, groupStates); aggregatorsPerGroup.put(groupByKey, row); } else { groupAggregators = row.getMethods(); groupStates = row.getStates(); row.increaseRefcount(); row.setLastUpdateTime(currentTime); } currentAggregatorMethods = groupAggregators; currentAggregatorStates = groupStates; // For this row, evaluate sub-expressions, enter result for (int j = 0; j < evaluators.length; j++) { Object columnResult = evaluators[j].evaluate(eventsPerStream, true, exprEvaluatorContext); groupAggregators[j].enter(columnResult); } for (AggregationState state : currentAggregatorStates) { state.applyEnter(eventsPerStream, exprEvaluatorContext); } internalHandleUpdated(groupByKey, row); } private void sweep(long currentTime, long currentMaxAge) { ArrayDeque<Object> removed = new ArrayDeque<Object>(); for (Map.Entry<Object, AggregationMethodRowAged> entry : aggregatorsPerGroup.entrySet()) { long age = currentTime - entry.getValue().getLastUpdateTime(); if (age > currentMaxAge) { removed.add(entry.getKey()); } } for (Object key : removed) { aggregatorsPerGroup.remove(key); internalHandleRemoved(key); removedCallback.removed(key); } } private long getMaxAge(long currentMaxAge) { Double maxAge = evaluationFunctionMaxAge.getLongValue(); if ((maxAge == null) || (maxAge <= 0)) { return currentMaxAge; } return Math.round(maxAge * 1000d); } private long getReclaimFrequency(long currentReclaimFrequency) { Double frequency = evaluationFunctionFrequency.getLongValue(); if ((frequency == null) || (frequency <= 0)) { return currentReclaimFrequency; } return Math.round(frequency * 1000d); } public void applyLeave(EventBean[] eventsPerStream, Object groupByKey, ExprEvaluatorContext exprEvaluatorContext) { AggregationMethodRowAged row = aggregatorsPerGroup.get(groupByKey); long currentTime = exprEvaluatorContext.getTimeProvider().getTime(); // The aggregators for this group do not exist, need to create them from the prototypes AggregationMethod[] groupAggregators; AggregationState[] groupStates; if (row != null) { groupAggregators = row.getMethods(); groupStates = row.getStates(); } else { groupAggregators = methodResolutionService.newAggregators(aggregators, exprEvaluatorContext.getAgentInstanceId(), groupByKey); groupStates = methodResolutionService.newAccesses(exprEvaluatorContext.getAgentInstanceId(), isJoin, accessAggregations, groupByKey); row = new AggregationMethodRowAged(methodResolutionService.getCurrentRowCount(groupAggregators, groupStates) + 1, currentTime, groupAggregators, groupStates); aggregatorsPerGroup.put(groupByKey, row); } currentAggregatorMethods = groupAggregators; currentAggregatorStates = groupStates; // For this row, evaluate sub-expressions, enter result for (int j = 0; j < evaluators.length; j++) { Object columnResult = evaluators[j].evaluate(eventsPerStream, false, exprEvaluatorContext); groupAggregators[j].leave(columnResult); } for (AggregationState state : currentAggregatorStates) { state.applyLeave(eventsPerStream, exprEvaluatorContext); } row.decreaseRefcount(); row.setLastUpdateTime(currentTime); if (row.getRefcount() <= 0) { removedKeys.add(groupByKey); methodResolutionService.removeAggregators(exprEvaluatorContext.getAgentInstanceId(), groupByKey); // allow persistence to remove keys already } internalHandleUpdated(groupByKey, row); } public void setCurrentAccess(Object groupByKey, int agentInstanceId) { AggregationMethodRowAged row = aggregatorsPerGroup.get(groupByKey); if (row != null) { currentAggregatorMethods = row.getMethods(); currentAggregatorStates = row.getStates(); } else { currentAggregatorMethods = null; } if (currentAggregatorMethods == null) { currentAggregatorMethods = methodResolutionService.newAggregators(aggregators, agentInstanceId, groupByKey); currentAggregatorStates = methodResolutionService.newAccesses(agentInstanceId, isJoin, accessAggregations, groupByKey); } } public Object getValue(int column, int agentInstanceId) { if (column < aggregators.length) { return currentAggregatorMethods[column].getValue(); } else { AggregationAccessorSlotPair pair = accessors[column - aggregators.length]; return pair.getAccessor().getValue(currentAggregatorStates[pair.getSlot()]); } } public Collection<EventBean> getCollection(int column, ExprEvaluatorContext context) { if (column < aggregators.length) { return null; } else { AggregationAccessorSlotPair pair = accessors[column - aggregators.length]; return pair.getAccessor().getEnumerableEvents(currentAggregatorStates[pair.getSlot()]); } } public EventBean getEventBean(int column, ExprEvaluatorContext context) { if (column < aggregators.length) { return null; } else { AggregationAccessorSlotPair pair = accessors[column - aggregators.length]; return pair.getAccessor().getEnumerableEvent(currentAggregatorStates[pair.getSlot()]); } } public void setRemovedCallback(AggregationRowRemovedCallback callback) { this.removedCallback = callback; } public void internalHandleUpdated(Object groupByKey, AggregationMethodRowAged row) { // no action required } public void internalHandleRemoved(Object key) { // no action required } protected void handleRemovedKeys() { if (!removedKeys.isEmpty()) // we collect removed keys lazily on the next enter to reduce the chance of empty-group queries creating empty aggregators temporarily { for (Object removedKey : removedKeys) { aggregatorsPerGroup.remove(removedKey); internalHandleRemoved(removedKey); } removedKeys.clear(); } } }
gpl-2.0
htuyen1994/nukeviet-my
modules/page/language/admin_en.php
2442
<?php /** * @Project NUKEVIET 4.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2014 VINADES.,JSC. All rights reserved * @Language English * @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/) * @Createdate Mar 04, 2010, 08:22:00 AM */ if( ! defined( 'NV_ADMIN' ) or ! defined( 'NV_MAINFILE' ) ) die( 'Stop!!!' ); $lang_translator['author'] = 'VINADES.,JSC (contact@vinades.vn)'; $lang_translator['createdate'] = '04/03/2010, 15:22'; $lang_translator['copyright'] = '@Copyright (C) 2010 VINADES.,JSC. All rights reserved'; $lang_translator['info'] = ''; $lang_translator['langtype'] = 'lang_module'; $lang_module['list'] = 'List of articles'; $lang_module['add'] = 'Add a new article'; $lang_module['title'] = 'Title'; $lang_module['order'] = 'Order'; $lang_module['status'] = 'Status'; $lang_module['active'] = 'Active'; $lang_module['inactive'] = 'Inactive'; $lang_module['delete'] = 'Delete article'; $lang_module['empty_title'] = 'Article has not title'; $lang_module['empty_bodytext'] = 'Article has not content'; $lang_module['bodytext'] = 'Content'; $lang_module['edit'] = 'Edit article'; $lang_module['save'] = 'Save article'; $lang_module['errorsave'] = 'System can\'t update content, Please check identical article titles'; $lang_module['saveok'] = 'Update successfully'; $lang_module['alias'] = 'Static Link'; $lang_module['keywords'] = 'keywords'; $lang_module['feature'] = 'Feature'; $lang_module['description'] = 'Description'; $lang_module['image'] = 'Image'; $lang_module['imagealt'] = 'Image note'; $lang_module['socialbutton'] = 'Social button'; $lang_module['socialbuttonnote'] = 'Display Like facebook, G+, Twitter'; $lang_module['activecomm'] = 'Allow comment'; $lang_module['layout_func'] = 'Layout'; $lang_module['layout_default'] = 'Default'; $lang_module['googleplus'] = 'authentication Google+ (copyright)'; $lang_module['googleplus_1'] = 'Not use'; $lang_module['googleplus_0'] = 'Follow configure of module'; $lang_module['config'] = 'Config'; $lang_module['config_view_type'] = 'Display articles type'; $lang_module['config_view_type_0'] = 'Main article'; $lang_module['config_view_type_1'] = 'List article'; $lang_module['config_facebookapi'] = 'Facebook App ID'; $lang_module['config_facebookapi_note'] = '(Form: 1419186468293063, <a href="http://wiki.nukeviet.vn/nukeviet:admin:news:facebookapi" target="_blank">view detail</a>)'; $lang_module['config_save'] = 'Save config';
gpl-2.0
alexbruy/QGIS
tests/src/python/test_qgsvirtuallayerdefinition.py
4379
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsVirtualLayerDefinition .. note:: 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. """ __author__ = 'Hugo Mercier' __date__ = '10/12/2015' __copyright__ = 'Copyright 2015, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import qgis # NOQA from qgis.core import (QgsField, QgsWkbTypes, QgsFields, QgsVirtualLayerDefinition ) from qgis.testing import unittest from qgis.PyQt.QtCore import QVariant, QUrl import os class TestQgsVirtualLayerDefinition(unittest.TestCase): def test1(self): d = QgsVirtualLayerDefinition() self.assertEqual(d.toString(), "") d.setFilePath("/file") self.assertEqual(d.toString(), "file:///file") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).filePath(), "/file") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).filePath(), "/file") d.setFilePath(os.path.join('C:/', 'file')) self.assertEqual(d.toString(), "file:///C:/file") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).filePath(), os.path.join('C:/', 'file')) d.setQuery("SELECT * FROM mytable") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).query(), "SELECT * FROM mytable") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).query(), "SELECT * FROM mytable") q = u"SELECT * FROM tableéé /*:int*/" d.setQuery(q) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).query(), q) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).query(), q) s1 = u"file://foo&bar=okié" d.addSource("name", s1, "provider", "utf8") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).sourceLayers()[0].source(), s1) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).sourceLayers()[0].source(), s1) n1 = u"éé ok" d.addSource(n1, s1, "provider") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).sourceLayers()[1].name(), n1) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).sourceLayers()[1].name(), n1) d.addSource("ref1", "id0001") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).sourceLayers()[2].reference(), "id0001") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).sourceLayers()[2].reference(), "id0001") s = "dbname='C:\\tt' table=\"test\" (geometry) sql=" d.addSource("nn", s, "spatialite") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).sourceLayers()[3].source(), s) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).sourceLayers()[3].source(), s) d.setGeometryField("geom") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).geometryField(), "geom") self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).geometryField(), "geom") d.setGeometryWkbType(QgsWkbTypes.Point) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(d.toUrl()).geometryWkbType(), QgsWkbTypes.Point) self.assertEqual(QgsVirtualLayerDefinition.fromUrl(QUrl.fromEncoded(d.toString())).geometryWkbType(), QgsWkbTypes.Point) f = QgsFields() f.append(QgsField("a", QVariant.Int)) f.append(QgsField("f", QVariant.Double)) f.append(QgsField("s", QVariant.String)) d.setFields(f) f2 = QgsVirtualLayerDefinition.fromUrl(d.toUrl()).fields() self.assertEqual(f[0].name(), f2[0].name()) self.assertEqual(f[0].type(), f2[0].type()) self.assertEqual(f[1].name(), f2[1].name()) self.assertEqual(f[1].type(), f2[1].type()) self.assertEqual(f[2].name(), f2[2].name()) self.assertEqual(f[2].type(), f2[2].type()) if __name__ == '__main__': unittest.main()
gpl-2.0
CarlosAgon/ILP-UPMC
Java/src/com/paracamplus/ilp4/interpreter/ILP9Method.java
2724
/* ***************************************************************** * ILP9 - Implantation d'un langage de programmation. * by Christian.Queinnec@paracamplus.com * See http://mooc.paracamplus.com/ilp9 * GPL version 3 ***************************************************************** */ package com.paracamplus.ilp4.interpreter; import com.paracamplus.ilp1.interfaces.IASTexpression; import com.paracamplus.ilp1.interfaces.IASTvariable; import com.paracamplus.ilp1.interfaces.Inamed; import com.paracamplus.ilp1.interpreter.Function; import com.paracamplus.ilp1.interpreter.interfaces.EvaluationException; import com.paracamplus.ilp4.interpreter.interfaces.IClass; import com.paracamplus.ilp4.interpreter.interfaces.IMethod; import com.paracamplus.ilp4.interpreter.interfaces.ISuperCallInformation; import com.paracamplus.ilp1.interpreter.Interpreter; import com.paracamplus.ilp1.interpreter.interfaces.ILexicalEnvironment; public class ILP9Method extends Function implements IMethod, Inamed { public ILP9Method (String methodName, String definingClassName, IASTvariable[] variables, IASTexpression body ) { super(variables, body, new SuperCallEmptyLexicalEnvironment()); this.methodName = methodName; this.definingClassName = definingClassName; } private final String methodName; private final String definingClassName; private IClass definingClass; @Override public String getName() { return methodName; } public String getDefiningClassName() { return definingClassName; } @Override public IClass getDefiningClass() { return definingClass; } @Override public void setDefiningClass(IClass clazz) { definingClass = clazz; } @Override public int getMethodArity() { return getArity() - 1; } @Override public Object apply(Interpreter interpreter, Object[] arguments) throws EvaluationException { if ( arguments.length != getArity() ) { String msg = "Wrong arity"; throw new EvaluationException(msg); } ILexicalEnvironment lexenv2 = getClosedEnvironment(); ISuperCallInformation isci = new SuperCallInformation(arguments, this); lexenv2 = ((com.paracamplus.ilp4.interpreter.interfaces.ISuperCallLexicalEnvironment)lexenv2).extend(isci); IASTvariable[] variables = getVariables(); for ( int i=0 ; i<arguments.length ; i++ ) { lexenv2 = lexenv2.extend(variables[i], arguments[i]); } return getBody().accept(interpreter, lexenv2); } }
gpl-2.0
rollingthunder/Diversity-Synchronization
MVVMDiversity.DesignServices/Connections.cs
2663
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MVVMDiversity.Interface; using GalaSoft.MvvmLight.Messaging; using MVVMDiversity.Messages; using MVVMDiversity.Model; namespace MVVMDiversity.DesignServices { public class Connections : IConnectionManagementService, IConnectionProvider { public void connectRepositorySqlAuth(Model.ConnectionProfile repo, string user, string password) { State |= Model.ConnectionState.RepositoriesConnected; } public void connectRepositoryWinAuth(Model.ConnectionProfile repo) { State |= Model.ConnectionState.RepositoriesConnected; } public void connectToMobileDB(DBPaths paths) { State |= Model.ConnectionState.MobileConnected; } public void disconnectEverything() { State = Model.ConnectionState.None; } public void disconnectFromMobileDB() { State &= ~Model.ConnectionState.MobileConnected; } public void disconnectFromRepository() { State &= ~Model.ConnectionState.RepositoriesConnected; } Model.ConnectionState _state = Model.ConnectionState.FullyConnected; public Model.ConnectionState State { get { return _state; } private set { _state = value; Messenger.Default.Send<ConnectionStateChanged>(new ConnectionStateChanged(value)); } } public System.Data.IDbConnection MobileDB { get { throw new NotImplementedException(); } } UBT.AI4.Bio.DivMobi.DatabaseConnector.Serializer.Serializer IConnectionProvider.MobileDB { get { throw new NotImplementedException(); } } public UBT.AI4.Bio.DivMobi.DatabaseConnector.Serializer.Serializer MobileTaxa { get { throw new NotImplementedException(); } } public UBT.AI4.Bio.DivMobi.DatabaseConnector.Serializer.Serializer Repository { get { throw new NotImplementedException(); } } public UBT.AI4.Bio.DivMobi.DatabaseConnector.Serializer.Serializer Definitions { get { throw new NotImplementedException(); } } public UBT.AI4.Bio.DivMobi.DatabaseConnector.Serializer.Serializer Synchronization { get { throw new NotImplementedException(); } } public bool truncateSyncTable() { return true; } } }
gpl-2.0
imadkaf/lsdoEZ4
extension/ezcomments/classes/ezcomserverfunctions.php
511
<?php /** * File containing ezcomServerFunctions class * * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/gnu_gpl GNU General Public License v2.0 * */ /* * ezjscServerFunctions for ezcomments */ class ezcomServerFunctions extends ezjscServerFunctions { public static function userData() { unset( $_COOKIE['eZCommentsUserData'] ); $cookie = ezcomCookieManager::instance(); return $cookie->storeCookie(); } }
gpl-2.0
rxu/List_subforums_in_columns
tests/functional/extension_test.php
4168
<?php /** * * List subforums in columns extension for the phpBB Forum Software package. * * @copyright (c) 2020 phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ namespace gfksx\ListSubforumsInColumns\tests\functional; /** * @group functional */ class extension_test extends \phpbb_functional_test_case { static protected function setup_extensions() { return array('gfksx/ListSubforumsInColumns'); } public function test_forum_setting() { $this->login(); $this->admin_login(); $this->add_lang('acp/forums'); $this->add_lang_ext('gfksx/ListSubforumsInColumns', 'info_acp_sflist'); $crawler = self::request('GET', "adm/index.php?i=acp_forums&icat=7&mode=manage&parent_id=1&f=2&action=edit&sid={$this->sid}"); $this->assertContains($this->lang('SUBFORUMSLIST_TYPE'), $crawler->filter('dt > label[for="subforumslist_type"]')->text()); $this->assertContains('0', $crawler->filter('dd > input[name="subforumslist_type"]')->attr('value')); $form = $crawler->selectButton('update')->form([ 'subforumslist_type' => 1, ]); $crawler = self::submit($form); $this->assertContains($this->lang('FORUM_UPDATED'), $crawler->filter('.successbox')->text()); $crawler = self::request('GET', "adm/index.php?i=acp_forums&icat=7&mode=manage&parent_id=1&f=2&action=edit&sid={$this->sid}"); $this->assertContains($this->lang('SUBFORUMSLIST_TYPE'), $crawler->filter('dt > label[for="subforumslist_type"]')->text()); $this->assertContains('1', $crawler->filter('dd > input[name="subforumslist_type"]')->attr('value')); } public function test_subforums_in_columns_enabled() { $this->login(); $this->admin_login(); $this->add_lang('acp/forums'); $this->add_lang_ext('gfksx/ListSubforumsInColumns', 'info_acp_sflist'); $forum_names = ['Subforum #1', 'Subforum #2', 'Subforum #3']; foreach ($forum_names as $forum_name) { $crawler = self::request('GET', "adm/index.php?i=acp_forums&mode=manage&parent_id=2&sid={$this->sid}"); $crawler = self::submit($crawler->selectButton('addforum')->form()); $form = $crawler->selectButton('update')->form([ 'forum_name' => $forum_name, 'forum_parent_id' => 2, 'forum_perm_from' => 2, ]); $crawler = self::submit($form); $this->assertContains($this->lang('FORUM_CREATED'), $crawler->filter('.successbox')->text()); } $crawler = self::request('GET', "index.php?sid={$this->sid}"); $this->assertContains('Subforum #1', $crawler->filter('span[class="list_subforums_in_columns"]')->filter('a[class="subforum read"]')->eq(0)->text()); $this->assertContains('Subforum #2', $crawler->filter('span[class="list_subforums_in_columns"]')->filter('a[class="subforum read"]')->eq(1)->text()); $this->assertContains('Subforum #3', $crawler->filter('span[class="list_subforums_in_columns"]')->filter('a[class="subforum read"]')->eq(2)->text()); } public function test_subforums_in_columns_disabled() { $this->login(); $this->admin_login(); $this->add_lang('acp/forums'); $this->add_lang_ext('gfksx/ListSubforumsInColumns', 'info_acp_sflist'); $crawler = self::request('GET', "adm/index.php?i=acp_forums&icat=7&mode=manage&parent_id=1&f=2&action=edit&sid={$this->sid}"); $this->assertContains($this->lang('SUBFORUMSLIST_TYPE'), $crawler->filter('dt > label[for="subforumslist_type"]')->text()); $this->assertContains('1', $crawler->filter('dd > input[name="subforumslist_type"]')->attr('value')); $form = $crawler->selectButton('update')->form([ 'subforumslist_type' => 0, ]); $crawler = self::submit($form); $this->assertContains($this->lang('FORUM_UPDATED'), $crawler->filter('.successbox')->text()); $crawler = self::request('GET', "index.php?sid={$this->sid}"); $this->assertContains('Subforum #1', $crawler->filter('div[class="list-inner"]')->filter('a[class="subforum read"]')->eq(0)->text()); $this->assertContains('Subforum #2', $crawler->filter('div[class="list-inner"]')->filter('a[class="subforum read"]')->eq(1)->text()); $this->assertContains('Subforum #3', $crawler->filter('div[class="list-inner"]')->filter('a[class="subforum read"]')->eq(2)->text()); } }
gpl-2.0
udhayarajselvan/matrix
wp-content/themes/papercuts/searchform.php
536
<?php /** * The searchform template file. * @package PaperCuts * @since PaperCuts 1.0.0 */ ?> <form id="searchform" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div class="searchform-wrapper"><input type="text" value="<?php echo esc_attr( get_search_query() ); ?>" name="s" id="s" placeholder="<?php esc_attr_e( 'Search here...', 'papercuts' ); ?>" /> <input type="image" src="<?php echo esc_url(get_template_directory_uri()); ?>/images/empty.gif" class="send" name="searchsubmit" alt="send" /></div> </form>
gpl-2.0
njsmith/partiwm
parti/trays/__init__.py
220
# This file is part of Parti. # Copyright (C) 2008, 2009 Nathaniel Smith <njs@pobox.com> # Parti is released under the terms of the GNU GPL v2, or, at your option, any # later version. See the file COPYING for details.
gpl-2.0
tectronics/xenogeddon
src/com/jmex/xml/types/TypesIncompatibleException.java
725
/** * TypesIncompatibleException.java * * This file was generated by XMLSpy 2007sp2 Enterprise Edition. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the XMLSpy Documentation for further details. * http://www.altova.com/xmlspy */ package com.jmex.xml.types; public class TypesIncompatibleException extends SchemaTypeException { protected SchemaType object1; protected SchemaType object2; public TypesIncompatibleException(SchemaType newobj1, SchemaType newobj2) { super("Incompatible schema-types"); object1 = newobj1; object2 = newobj2; } public TypesIncompatibleException(Exception other) { super(other); } }
gpl-2.0
dbenn/cgp
lib/antlr-2.7.0/examples/cpp/IDL/Main.cpp
271
#include "IDLLexer.hpp" #include "IDLParser.hpp" #include <iostream> int main() { ANTLR_USING_NAMESPACE(std) try { IDLLexer lexer(cin); IDLParser parser(lexer); parser.specification(); } catch(exception& e) { cerr << "exception: " << e.what() << endl; } }
gpl-2.0
pliskin2009/AKCore-1
Server/NtlSystem/NtlPerformance.cpp
6046
//*********************************************************************************** // // File : NtlPerformance.cpp // // Begin : 2007-02-08 // // Copyright : ¨Ï NTL-Inc Co., Ltd // // Author : Hyun Woo, Koo ( zeroera@ntl-inc.com ) // // Desc : // //*********************************************************************************** #include "stdAfx.h" #include "NtlPerformance.h" #include "NtlError.h" #include <stdlib.h> #include <stdio.h> #include <psapi.h> #pragma comment(lib, "Psapi") //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- CNtlPerformance::CNtlPerformance(void) { Init(); } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- CNtlPerformance::~CNtlPerformance(void) { Destroy(); } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- void CNtlPerformance::Init() { m_hProcess = NULL; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- int CNtlPerformance::Create(HANDLE hProcess /* = NULL */) { char szLogFilePath[16 + 1] = { 0x00, }; char szLogFileNameFormat[25 + 1] = { 0x00, }; char szProcessFullName[MAX_PATH + 1] = "<unknown>"; char* lpszProcessName = NULL; m_hProcess = hProcess; if( NULL == m_hProcess ) { m_hProcess = GetCurrentProcess(); if( NULL == m_hProcess ) { return GetLastError(); } } ::GetSystemInfo( &m_systemInfo ); GlobalMemoryStatusEx( &m_memoryStatus ); // Initializes 'szLogFileNameFormat'. { SYSTEMTIME localTime; GetLocalTime(&localTime); sprintf_s<sizeof(szLogFileNameFormat)>( szLogFileNameFormat, "%%s\\%04u%02u%02u_%02u%02u%02u_%%s.csv", localTime.wYear, localTime.wMonth, localTime.wDay, localTime.wHour, localTime.wMinute, localTime.wSecond); } // Initializes 'szProcessFullName' and 'lpszProcessName'. { HMODULE hMod = NULL; DWORD cbNeeded = 0; int rc = EnumProcessModules( m_hProcess, &hMod, sizeof(hMod), &cbNeeded ); if ( ERROR_SUCCESS == rc ) { return 0; } DWORD dwSize = GetModuleBaseName( m_hProcess, hMod, szProcessFullName, MAX_PATH ); if( 0 == dwSize ) { return 0; } lpszProcessName = strtok_s( szProcessFullName, ".", &lpszProcessName ); if( NULL == lpszProcessName ) { return 0; } } if (FALSE == ::CreateDirectory("PerformanceLog", NULL)) { DWORD dwLastError = ::GetLastError(); if (ERROR_ALREADY_EXISTS != dwLastError) { strcpy_s<_countof(szLogFilePath)>(szLogFilePath, "."); } else { strcpy_s<_countof(szLogFilePath)>(szLogFilePath, "PerformanceLog"); } } else { strcpy_s<_countof(szLogFilePath)>(szLogFilePath, "PerformanceLog"); } // Now lets PDH objects begin. CNtlString strLogFileName; { char szPdhPath[MAX_PATH + 1] = { 0x00, }; sprintf_s(szPdhPath, MAX_PATH, "\\Process(%s)\\%% Processor Time", lpszProcessName ); strLogFileName.Format(szLogFileNameFormat, szLogFilePath, "ProcessUsage"); m_pdhProcessUsage.Prepare(); m_pdhProcessUsage.RegisterCounter(szPdhPath); m_pdhProcessUsage.Start(strLogFileName.c_str()); } { strLogFileName.Format(szLogFileNameFormat, szLogFilePath, "SystemProcessorUsage"); m_pdhSystemProcessorUsage.Prepare(); m_pdhSystemProcessorUsage.RegisterCounter( "\\Processor(_Total)\\% Processor Time" ); m_pdhSystemProcessorUsage.Start(strLogFileName.c_str()); } return ERROR_SUCCESS; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- void CNtlPerformance::Destroy() { m_pdhProcessUsage.Stop(); m_pdhSystemProcessorUsage.Stop(); } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- MEMORYSTATUSEX * CNtlPerformance::GetMemoryStatus(bool bRefresh /* = true */) { if( bRefresh ) { GlobalMemoryStatusEx( &m_memoryStatus ); } return &m_memoryStatus; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- void CNtlPerformance::UpdateLog() { m_pdhProcessUsage.UpdateLog(); m_pdhSystemProcessorUsage.UpdateLog(); } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- size_t CNtlPerformance::GetProcessMemoryUsage() { if ( NULL == m_hProcess ) { return 0; } PROCESS_MEMORY_COUNTERS pmc; if ( 0 == GetProcessMemoryInfo( m_hProcess, &pmc, sizeof(pmc)) ) { return 0; } return pmc.WorkingSetSize; } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- DWORD CNtlPerformance::GetProcessProcessorLoad() { if( NULL == m_hProcess ) { return 0; } return m_pdhProcessUsage.GetValue(); } //----------------------------------------------------------------------------------- // Purpose : // Return : //----------------------------------------------------------------------------------- DWORD CNtlPerformance::GetSystemProcessorLoad() { if( NULL == m_hProcess ) { return 0; } return m_pdhSystemProcessorUsage.GetValue(); }
gpl-2.0
kyak/gmenu2x
src/dialog.cpp
919
#include <string> #include "dialog.h" #include "gmenu2x.h" #include "font.h" Dialog::Dialog(GMenu2X& gmenu2x) : gmenu2x(gmenu2x) { } void Dialog::drawTitleIcon(Surface& s, const std::string &icon, bool skinRes) { Surface *i = NULL; if (!icon.empty()) { if (skinRes) i = gmenu2x.sc.skinRes(icon); else i = gmenu2x.sc[icon]; } if (i==NULL) i = gmenu2x.sc.skinRes("icons/generic.png"); i->blit(s, 4, (gmenu2x.skinConfInt["topBarHeight"] - 32) / 2); } void Dialog::writeTitle(Surface& s, const std::string &title) { gmenu2x.font->write(s, title, 40, 0, Font::HAlignLeft, Font::VAlignTop); } void Dialog::writeSubTitle(Surface& s, const std::string &subtitle) { std::string wrapped = gmenu2x.font->wordWrap(subtitle, gmenu2x.resX - 48); gmenu2x.font->write(s, wrapped, 40, gmenu2x.skinConfInt["topBarHeight"] - gmenu2x.font->getTextHeight(wrapped), Font::HAlignLeft, Font::VAlignTop); }
gpl-2.0
Tontonitch/icinga2
lib/config/configitem.cpp
18409
/****************************************************************************** * Icinga 2 * * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ #include "config/configitem.hpp" #include "config/configcompilercontext.hpp" #include "config/applyrule.hpp" #include "config/objectrule.hpp" #include "config/configcompiler.hpp" #include "base/application.hpp" #include "base/configtype.hpp" #include "base/objectlock.hpp" #include "base/convert.hpp" #include "base/logger.hpp" #include "base/debug.hpp" #include "base/workqueue.hpp" #include "base/exception.hpp" #include "base/stdiostream.hpp" #include "base/netstring.hpp" #include "base/serializer.hpp" #include "base/json.hpp" #include "base/exception.hpp" #include "base/function.hpp" #include <sstream> #include <fstream> using namespace icinga; boost::mutex ConfigItem::m_Mutex; ConfigItem::TypeMap ConfigItem::m_Items; ConfigItem::TypeMap ConfigItem::m_DefaultTemplates; ConfigItem::ItemList ConfigItem::m_UnnamedItems; ConfigItem::IgnoredItemList ConfigItem::m_IgnoredItems; REGISTER_SCRIPTFUNCTION_NS(Internal, run_with_activation_context, &ConfigItem::RunWithActivationContext, "func"); /** * Constructor for the ConfigItem class. * * @param type The object type. * @param name The name of the item. * @param unit The unit of the item. * @param abstract Whether the item is a template. * @param exprl Expression list for the item. * @param debuginfo Debug information. */ ConfigItem::ConfigItem(const Type::Ptr& type, const String& name, bool abstract, const std::shared_ptr<Expression>& exprl, const std::shared_ptr<Expression>& filter, bool defaultTmpl, bool ignoreOnError, const DebugInfo& debuginfo, const Dictionary::Ptr& scope, const String& zone, const String& package) : m_Type(type), m_Name(name), m_Abstract(abstract), m_Expression(exprl), m_Filter(filter), m_DefaultTmpl(defaultTmpl), m_IgnoreOnError(ignoreOnError), m_DebugInfo(debuginfo), m_Scope(scope), m_Zone(zone), m_Package(package) { } /** * Retrieves the type of the configuration item. * * @returns The type. */ Type::Ptr ConfigItem::GetType(void) const { return m_Type; } /** * Retrieves the name of the configuration item. * * @returns The name. */ String ConfigItem::GetName(void) const { return m_Name; } /** * Checks whether the item is abstract. * * @returns true if the item is abstract, false otherwise. */ bool ConfigItem::IsAbstract(void) const { return m_Abstract; } bool ConfigItem::IsDefaultTemplate(void) const { return m_DefaultTmpl; } bool ConfigItem::IsIgnoreOnError(void) const { return m_IgnoreOnError; } /** * Retrieves the debug information for the configuration item. * * @returns The debug information. */ DebugInfo ConfigItem::GetDebugInfo(void) const { return m_DebugInfo; } Dictionary::Ptr ConfigItem::GetScope(void) const { return m_Scope; } ConfigObject::Ptr ConfigItem::GetObject(void) const { return m_Object; } /** * Retrieves the expression list for the configuration item. * * @returns The expression list. */ std::shared_ptr<Expression> ConfigItem::GetExpression(void) const { return m_Expression; } /** * Retrieves the object filter for the configuration item. * * @returns The filter expression. */ std::shared_ptr<Expression> ConfigItem::GetFilter(void) const { return m_Filter; } class DefaultValidationUtils : public ValidationUtils { public: virtual bool ValidateName(const String& type, const String& name) const override { ConfigItem::Ptr item = ConfigItem::GetByTypeAndName(Type::GetByName(type), name); if (!item || (item && item->IsAbstract())) return false; return true; } }; /** * Commits the configuration item by creating a ConfigObject * object. * * @returns The ConfigObject that was created/updated. */ ConfigObject::Ptr ConfigItem::Commit(bool discard) { #ifdef I2_DEBUG Log(LogDebug, "ConfigItem") << "Commit called for ConfigItem Type=" << GetType() << ", Name=" << GetName(); #endif /* I2_DEBUG */ /* Make sure the type is valid. */ Type::Ptr type = GetType(); if (!type || !ConfigObject::TypeInstance->IsAssignableFrom(type)) BOOST_THROW_EXCEPTION(ScriptError("Type '" + GetType() + "' does not exist.", m_DebugInfo)); if (IsAbstract()) return nullptr; ConfigObject::Ptr dobj = static_pointer_cast<ConfigObject>(type->Instantiate(std::vector<Value>())); dobj->SetDebugInfo(m_DebugInfo); dobj->SetZoneName(m_Zone); dobj->SetPackage(m_Package); dobj->SetName(m_Name); DebugHint debugHints; ScriptFrame frame(dobj); if (m_Scope) m_Scope->CopyTo(frame.Locals); try { m_Expression->Evaluate(frame, &debugHints); } catch (const std::exception& ex) { if (m_IgnoreOnError) { Log(LogNotice, "ConfigObject") << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); { boost::mutex::scoped_lock lock(m_Mutex); m_IgnoredItems.push_back(m_DebugInfo.Path); } return nullptr; } throw; } if (discard) m_Expression.reset(); String item_name; String short_name = dobj->GetShortName(); if (!short_name.IsEmpty()) { item_name = short_name; dobj->SetName(short_name); } else item_name = m_Name; String name = item_name; NameComposer *nc = dynamic_cast<NameComposer *>(type.get()); if (nc) { if (name.IsEmpty()) BOOST_THROW_EXCEPTION(ScriptError("Object name must not be empty.", m_DebugInfo)); name = nc->MakeName(name, dobj); if (name.IsEmpty()) BOOST_THROW_EXCEPTION(std::runtime_error("Could not determine name for object")); } if (name != item_name) dobj->SetShortName(item_name); dobj->SetName(name); Dictionary::Ptr dhint = debugHints.ToDictionary(); try { DefaultValidationUtils utils; dobj->Validate(FAConfig, utils); } catch (ValidationError& ex) { if (m_IgnoreOnError) { Log(LogNotice, "ConfigObject") << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); { boost::mutex::scoped_lock lock(m_Mutex); m_IgnoredItems.push_back(m_DebugInfo.Path); } return nullptr; } ex.SetDebugHint(dhint); throw; } try { dobj->OnConfigLoaded(); } catch (const std::exception& ex) { if (m_IgnoreOnError) { Log(LogNotice, "ConfigObject") << "Ignoring config object '" << m_Name << "' of type '" << m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); { boost::mutex::scoped_lock lock(m_Mutex); m_IgnoredItems.push_back(m_DebugInfo.Path); } return nullptr; } throw; } Dictionary::Ptr persistentItem = new Dictionary(); persistentItem->Set("type", GetType()->GetName()); persistentItem->Set("name", GetName()); persistentItem->Set("properties", Serialize(dobj, FAConfig)); persistentItem->Set("debug_hints", dhint); Array::Ptr di = new Array(); di->Add(m_DebugInfo.Path); di->Add(m_DebugInfo.FirstLine); di->Add(m_DebugInfo.FirstColumn); di->Add(m_DebugInfo.LastLine); di->Add(m_DebugInfo.LastColumn); persistentItem->Set("debug_info", di); ConfigCompilerContext::GetInstance()->WriteObject(persistentItem); persistentItem.reset(); dhint.reset(); dobj->Register(); m_Object = dobj; return dobj; } /** * Registers the configuration item. */ void ConfigItem::Register(void) { m_ActivationContext = ActivationContext::GetCurrentContext(); boost::mutex::scoped_lock lock(m_Mutex); /* If this is a non-abstract object with a composite name * we register it in m_UnnamedItems instead of m_Items. */ if (!m_Abstract && dynamic_cast<NameComposer *>(m_Type.get())) m_UnnamedItems.push_back(this); else { auto& items = m_Items[m_Type]; auto it = items.find(m_Name); if (it != items.end()) { std::ostringstream msgbuf; msgbuf << "A configuration item of type '" << m_Type->GetName() << "' and name '" << GetName() << "' already exists (" << it->second->GetDebugInfo() << "), new declaration: " << GetDebugInfo(); BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str())); } m_Items[m_Type][m_Name] = this; if (m_DefaultTmpl) m_DefaultTemplates[m_Type][m_Name] = this; } } /** * Unregisters the configuration item. */ void ConfigItem::Unregister(void) { if (m_Object) { m_Object->Unregister(); m_Object.reset(); } boost::mutex::scoped_lock lock(m_Mutex); m_UnnamedItems.erase(std::remove(m_UnnamedItems.begin(), m_UnnamedItems.end(), this), m_UnnamedItems.end()); m_Items[m_Type].erase(m_Name); m_DefaultTemplates[m_Type].erase(m_Name); } /** * Retrieves a configuration item by type and name. * * @param type The type of the ConfigItem that is to be looked up. * @param name The name of the ConfigItem that is to be looked up. * @returns The configuration item. */ ConfigItem::Ptr ConfigItem::GetByTypeAndName(const Type::Ptr& type, const String& name) { boost::mutex::scoped_lock lock(m_Mutex); auto it = m_Items.find(type); if (it == m_Items.end()) return nullptr; auto it2 = it->second.find(name); if (it2 == it->second.end()) return nullptr; return it2->second; } bool ConfigItem::CommitNewItems(const ActivationContext::Ptr& context, WorkQueue& upq, std::vector<ConfigItem::Ptr>& newItems) { typedef std::pair<ConfigItem::Ptr, bool> ItemPair; std::vector<ItemPair> items; { boost::mutex::scoped_lock lock(m_Mutex); for (const TypeMap::value_type& kv : m_Items) { for (const ItemMap::value_type& kv2 : kv.second) { if (kv2.second->m_Abstract || kv2.second->m_Object) continue; if (kv2.second->m_ActivationContext != context) continue; items.emplace_back(kv2.second, false); } } ItemList newUnnamedItems; for (const ConfigItem::Ptr& item : m_UnnamedItems) { if (item->m_ActivationContext != context) { newUnnamedItems.push_back(item); continue; } if (item->m_Abstract || item->m_Object) continue; items.emplace_back(item, true); } m_UnnamedItems.swap(newUnnamedItems); } if (items.empty()) return true; for (const ItemPair& ip : items) { newItems.push_back(ip.first); upq.Enqueue([&]() { ip.first->Commit(ip.second); }); } upq.Join(); if (upq.HasExceptions()) return false; std::set<Type::Ptr> types; for (const Type::Ptr& type : Type::GetAllTypes()) { if (ConfigObject::TypeInstance->IsAssignableFrom(type)) types.insert(type); } std::set<Type::Ptr> completed_types; while (types.size() != completed_types.size()) { for (const Type::Ptr& type : types) { if (completed_types.find(type) != completed_types.end()) continue; bool unresolved_dep = false; /* skip this type (for now) if there are unresolved load dependencies */ for (const String& loadDep : type->GetLoadDependencies()) { Type::Ptr pLoadDep = Type::GetByName(loadDep); if (types.find(pLoadDep) != types.end() && completed_types.find(pLoadDep) == completed_types.end()) { unresolved_dep = true; break; } } if (unresolved_dep) continue; for (const ItemPair& ip : items) { const ConfigItem::Ptr& item = ip.first; if (!item->m_Object) continue; if (item->m_Type == type) { upq.Enqueue([&]() { try { item->m_Object->OnAllConfigLoaded(); } catch (const std::exception& ex) { if (item->m_IgnoreOnError) { Log(LogNotice, "ConfigObject") << "Ignoring config object '" << item->m_Name << "' of type '" << item->m_Type->GetName() << "' due to errors: " << DiagnosticInformation(ex); item->Unregister(); { boost::mutex::scoped_lock lock(item->m_Mutex); item->m_IgnoredItems.push_back(item->m_DebugInfo.Path); } return; } throw; } }); } } completed_types.insert(type); upq.Join(); if (upq.HasExceptions()) return false; for (const String& loadDep : type->GetLoadDependencies()) { for (const ItemPair& ip : items) { const ConfigItem::Ptr& item = ip.first; if (!item->m_Object) continue; if (item->m_Type->GetName() == loadDep) { upq.Enqueue([&]() { ActivationScope ascope(item->m_ActivationContext); item->m_Object->CreateChildObjects(type); }); } } } upq.Join(); if (upq.HasExceptions()) return false; if (!CommitNewItems(context, upq, newItems)) return false; } } return true; } bool ConfigItem::CommitItems(const ActivationContext::Ptr& context, WorkQueue& upq, std::vector<ConfigItem::Ptr>& newItems, bool silent) { if (!silent) Log(LogInformation, "ConfigItem", "Committing config item(s)."); if (!CommitNewItems(context, upq, newItems)) { upq.ReportExceptions("config"); for (const ConfigItem::Ptr& item : newItems) { item->Unregister(); } return false; } ApplyRule::CheckMatches(); if (!silent) { /* log stats for external parsers */ typedef std::map<Type::Ptr, int> ItemCountMap; ItemCountMap itemCounts; for (const ConfigItem::Ptr& item : newItems) { if (!item->m_Object) continue; itemCounts[item->m_Object->GetReflectionType()]++; } for (const ItemCountMap::value_type& kv : itemCounts) { Log(LogInformation, "ConfigItem") << "Instantiated " << kv.second << " " << (kv.second != 1 ? kv.first->GetPluralName() : kv.first->GetName()) << "."; } } return true; } bool ConfigItem::ActivateItems(WorkQueue& upq, const std::vector<ConfigItem::Ptr>& newItems, bool runtimeCreated, bool silent, bool withModAttrs) { static boost::mutex mtx; boost::mutex::scoped_lock lock(mtx); if (withModAttrs) { /* restore modified attributes */ if (Utility::PathExists(Application::GetModAttrPath())) { std::unique_ptr<Expression> expression = ConfigCompiler::CompileFile(Application::GetModAttrPath()); if (expression) { try { ScriptFrame frame; expression->Evaluate(frame); } catch (const std::exception& ex) { Log(LogCritical, "config", DiagnosticInformation(ex)); } } } } for (const ConfigItem::Ptr& item : newItems) { if (!item->m_Object) continue; ConfigObject::Ptr object = item->m_Object; if (object->IsActive()) continue; #ifdef I2_DEBUG Log(LogDebug, "ConfigItem") << "Setting 'active' to true for object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'"; #endif /* I2_DEBUG */ upq.Enqueue(std::bind(&ConfigObject::PreActivate, object)); } upq.Join(); if (upq.HasExceptions()) { upq.ReportExceptions("ConfigItem"); return false; } if (!silent) Log(LogInformation, "ConfigItem", "Triggering Start signal for config items"); for (const ConfigItem::Ptr& item : newItems) { if (!item->m_Object) continue; ConfigObject::Ptr object = item->m_Object; #ifdef I2_DEBUG Log(LogDebug, "ConfigItem") << "Activating object '" << object->GetName() << "' of type '" << object->GetReflectionType()->GetName() << "'"; #endif /* I2_DEBUG */ upq.Enqueue(std::bind(&ConfigObject::Activate, object, runtimeCreated)); } upq.Join(); if (upq.HasExceptions()) { upq.ReportExceptions("ConfigItem"); return false; } #ifdef I2_DEBUG for (const ConfigItem::Ptr& item : newItems) { ConfigObject::Ptr object = item->m_Object; if (!object) continue; ASSERT(object && object->IsActive()); } #endif /* I2_DEBUG */ if (!silent) Log(LogInformation, "ConfigItem", "Activated all objects."); return true; } bool ConfigItem::RunWithActivationContext(const Function::Ptr& function) { ActivationScope scope; if (!function) BOOST_THROW_EXCEPTION(ScriptError("'function' argument must not be null.")); function->Invoke(); WorkQueue upq(25000, Application::GetConcurrency()); upq.SetName("ConfigItem::RunWithActivationContext"); std::vector<ConfigItem::Ptr> newItems; if (!CommitItems(scope.GetContext(), upq, newItems, true)) return false; if (!ActivateItems(upq, newItems, false, true)) return false; return true; } std::vector<ConfigItem::Ptr> ConfigItem::GetItems(const Type::Ptr& type) { std::vector<ConfigItem::Ptr> items; boost::mutex::scoped_lock lock(m_Mutex); auto it = m_Items.find(type); if (it == m_Items.end()) return items; items.reserve(it->second.size()); for (const ItemMap::value_type& kv : it->second) { items.push_back(kv.second); } return items; } std::vector<ConfigItem::Ptr> ConfigItem::GetDefaultTemplates(const Type::Ptr& type) { std::vector<ConfigItem::Ptr> items; boost::mutex::scoped_lock lock(m_Mutex); auto it = m_DefaultTemplates.find(type); if (it == m_DefaultTemplates.end()) return items; items.reserve(it->second.size()); for (const ItemMap::value_type& kv : it->second) { items.push_back(kv.second); } return items; } void ConfigItem::RemoveIgnoredItems(const String& allowedConfigPath) { boost::mutex::scoped_lock lock(m_Mutex); for (const String& path : m_IgnoredItems) { if (path.Find(allowedConfigPath) == String::NPos) continue; Log(LogNotice, "ConfigItem") << "Removing ignored item path '" << path << "'."; (void) unlink(path.CStr()); } m_IgnoredItems.clear(); }
gpl-2.0
hanslovsky/em-thickness-estimation
src/main/java/org/janelia/thickness/lut/LUTRealTransform.java
5597
/** * */ package org.janelia.thickness.lut; import ij.ImageJ; import ij.ImagePlus; import net.imglib2.FinalInterval; import net.imglib2.RandomAccessible; import net.imglib2.RandomAccessibleInterval; import net.imglib2.RealLocalizable; import net.imglib2.RealPositionable; import net.imglib2.RealRandomAccess; import net.imglib2.RealRandomAccessible; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.array.ArrayImgs; import net.imglib2.img.basictypeaccess.array.FloatArray; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.interpolation.randomaccess.NLinearInterpolatorFactory; import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory; import net.imglib2.realtransform.InverseRealTransform; import net.imglib2.realtransform.InvertibleRealTransform; import net.imglib2.realtransform.RealTransform; import net.imglib2.realtransform.RealTransformRandomAccessible; import net.imglib2.realtransform.RealViews; import net.imglib2.type.Type; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.view.Views; /** * @author Philipp Hanslovsky <hanslovskyp@janelia.hhmi.org> * @author Stephan Saalfeld <saalfelds@janelia.hhmi.org> */ public class LUTRealTransform extends AbstractLUTRealTransform { public LUTRealTransform( final double[] lut, final int numSourceDimensions, final int numTargetDimensions ) { super( lut, numSourceDimensions, numTargetDimensions ); } @Override public void apply( final double[] source, final double[] target ) { assert source.length == target.length: "Dimensions do not match."; for ( int d = 0; d < source.length; ++d ) target[ d ] = applyChecked( source[ d ] ); } @Override public void apply( final float[] source, final float[] target ) { assert source.length == target.length: "Dimensions do not match."; for ( int d = 0; d < source.length; ++d ) target[ d ] = ( float ) applyChecked( source[ d ] ); } @Override public void apply( final RealLocalizable source, final RealPositionable target ) { assert source.numDimensions() == target.numDimensions(): "Dimensions do not match."; final int n = source.numDimensions(); for ( int d = 0; d < n; ++d ) target.setPosition( applyChecked( source.getDoublePosition( d ) ), d ); } /** * Reuses the LUT. */ @Override public LUTRealTransform copy() { return new LUTRealTransform( lut, numSourceDimensions, numTargetDimensions ); } @Override public void applyInverse( final double[] source, final double[] target ) { assert source.length == target.length: "Dimensions do not match."; for ( int d = 0; d < target.length; ++d ) source[ d ] = applyInverseChecked( target[ d ] ); } @Override public void applyInverse( final float[] source, final float[] target ) { assert source.length == target.length: "Dimensions do not match."; for ( int d = 0; d < target.length; ++d ) source[ d ] = ( float ) applyInverseChecked( target[ d ] ); } @Override public void applyInverse( final RealPositionable source, final RealLocalizable target ) { assert source.numDimensions() == target.numDimensions(): "Dimensions do not match."; final int n = target.numDimensions(); for ( int d = 0; d < n; ++d ) source.setPosition( applyInverseChecked( target.getDoublePosition( d ) ), d ); } /** * TODO create actual inverse */ @Override public InvertibleRealTransform inverse() { return new InverseRealTransform( this ); } public static < T extends Type< T >> void render( final RealRandomAccessible< T > source, final RandomAccessibleInterval< T > target, final RealTransform transform, final double dx ) { final RealRandomAccessible< T > interpolant = Views.interpolate( Views.extendBorder( target ), new NearestNeighborInterpolatorFactory< T >() ); final RealRandomAccess< T > a = source.realRandomAccess(); final RealRandomAccess< T > b = interpolant.realRandomAccess(); for ( double y = 0; y < target.dimension( 1 ); y += dx ) { a.setPosition( y, 1 ); for ( double x = 0; x < target.dimension( 0 ); x += dx ) { a.setPosition( x, 0 ); transform.apply( a, b ); b.get().set( a.get() ); } } } final static public void main( final String[] args ) { new ImageJ(); final ImagePlus imp = new ImagePlus( "http://media.npr.org/images/picture-show-flickr-promo.jpg" ); imp.show(); final float[] pixels = ( float[] )imp.getProcessor().convertToFloat().getPixels(); final ArrayImg<FloatType, FloatArray> img = ArrayImgs.floats(pixels, imp.getWidth(), imp.getHeight()); final double[] lut = new double[Math.max(imp.getWidth(), imp.getHeight())]; for (int i =0; i < lut.length; ++i) lut[i] = i + Math.pow(i, 1.5); final LUTRealTransform transform = new LUTRealTransform(lut, 2, 2); final RealRandomAccessible<FloatType> source = Views.interpolate( Views.extendBorder(img), new NLinearInterpolatorFactory<FloatType>() ); final RandomAccessible<FloatType> target = new RealTransformRandomAccessible<FloatType, RealTransform>(source, transform); final RandomAccessible<FloatType> target2 = RealViews.transform(source, transform); // RealViews.transformReal(source, transform); final ArrayImg<FloatType, FloatArray> targetImg = ArrayImgs.floats(imp.getWidth(), imp.getHeight()); render(source, targetImg, transform, 0.05); ImageJFunctions.show(Views.interval(target, new FinalInterval(imp.getWidth(), imp.getHeight()))); ImageJFunctions.show(Views.interval(target2, new FinalInterval(imp.getWidth(), imp.getHeight()))); ImageJFunctions.show(targetImg); } }
gpl-2.0
suiheilibe/STEP_mid
test/test.cpp
1421
#include <stdio.h> #include <string.h> #include <windows.h> #include <tchar.h> #include "CppUTest/CommandLineTestRunner.h" #include "STEPlugin.h" #include "SMFUtil.h" #include "STEPMidUtil.h" #include "debug.h" static void my_SetValue(FILE_INFO *fi, LPCTSTR str) { DEBUGOUT("FILE_INFO = %p, value = %p\n", fi, str); } TEST_GROUP(STEPMidTestGroup) { void setup() { errno_t err = _tfopen_s(&fp, _T("test_metaevents.mid"), _T("rb")); events = (SMFUtil::MetaEvent *)malloc(sizeof(SMFUtil::MetaEvent) * SMFUtil::META_MAX); } void teardown() { free(events); fclose(fp); } FILE *fp = nullptr; SMFUtil::MetaEvent *events = nullptr; void (*saSetFunc[SMFUtil::META_MAX])(FILE_INFO *, LPCTSTR) = {my_SetValue, my_SetValue, my_SetValue}; }; TEST(STEPMidTestGroup, TestMain) { CHECK_EQUAL(0, SMFUtil::findMetaEvents(fp, events)); // Text Event CHECK_EQUAL(542, events[SMFUtil::MetaEventType::META_COMMENT].length); // Copyright Notice CHECK_EQUAL(1553, events[SMFUtil::MetaEventType::META_COPYRIGHT].length); // Sequence/Track Name CHECK_EQUAL(16361, events[SMFUtil::MetaEventType::META_SEQNAME].length); CHECK_EQUAL(0, STEPMidUtil::readMetaEvent(nullptr, fp, events, saSetFunc)); } int main(int argc, char *argv[]) { return CommandLineTestRunner::RunAllTests(argc, argv); }
gpl-2.0
turnoffthelights/Turn-Off-the-Lights-Chrome-extension
src/js/video-player-status.js
4015
//================================================ /* Turn Off the Lights The entire page will be fading to dark, so you can watch the video as if you were in the cinema. Copyright (C) 2021 Stefan vd www.stefanvd.net www.turnoffthelights.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. To view a copy of this license, visit http://creativecommons.org/licenses/GPL/2.0/ */ //================================================ var ytCinema; (ytCinema = { players: {objs: [], active: 0}, messageEvent: new Event("ytCinemaMessage"), playerStateChange: function(stateId){ var message = document.getElementById("ytCinemaMessage"), stateIO = "playerStateChange:".concat(stateId); // console.log("Debug " + message.textContent + " " +stateIO); if(message && message.textContent !== stateIO){ message.textContent = stateIO; message.dispatchEvent(ytCinema.messageEvent); } }, initialize: function(){ ytCinema.initvideoinject(); var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; if(MutationObserver){ var videolist = document.querySelector("body"), observer = new MutationObserver(function(mutations){ mutations.forEach(function(mutation){ if((mutation.target.tagName == "VIDEO" && mutation.attributeName === "src") || mutation.addedNodes == "VIDEO" || mutation.removedNodes == "VIDEO"){ ytCinema.initvideoinject(); } }); }); observer.observe(videolist, { subtree: true, // observe the subtree rooted at ...videolist... childList: true, // include childNode insertion/removals characterData: false, // include textContent changes attributes: true // include changes to attributes within the subtree }); }else{ // setup DOM event listeners document.addEventListener("DOMNodeRemoved", ytCinema.initvideoinject, false); document.addEventListener("DOMNodeInserted", ytCinema.initvideoinject, false); } }, initvideoinject: function(){ var youtubeplayer = document.getElementById("movie_player") || null, htmlplayer = document.getElementsByTagName("video") || false; if(youtubeplayer !== null){ // YouTube video element var interval = window.setInterval(function(){ if(youtubeplayer.pause || youtubeplayer.pauseVideo){ window.clearInterval(interval); if(youtubeplayer.pauseVideo){ youtubeplayer.addEventListener("onStateChange", "ytCinema.playerStateChange"); } } }, 10); } if(htmlplayer && htmlplayer.length > 0){ // HTML5 video elements var setPlayerEvents = function(players){ var j, l = players.length; for(j = 0; j < l; j++){ (function(o, p){ var ev = {pause: function(){ if(!p.ended){ o.players.active -= 1; }if(o.players.active < 1){ o.playerStateChange(2); } }, play: function(){ o.players.active += 1; o.playerStateChange(1); }, ended: function(){ o.players.active -= 1; if(o.players.active < 1){ o.playerStateChange(0); } }}; p.removeEventListener("pause", ev.pause); p.removeEventListener("play", ev.play); p.removeEventListener("ended", ev.ended); p.addEventListener("pause", ev.pause); p.addEventListener("play", ev.play); p.addEventListener("ended", ev.ended); o.players.objs.push(p); }(this.ytCinema, htmlplayer[j])); } }; setPlayerEvents(htmlplayer); } } }).initialize();
gpl-2.0
OneHundRedOf/kdev-go
duchain/declarations/functiondeclaration.cpp
2835
/************************************************************************************* * Copyright (C) 2014 by Pavel Petrushkov <onehundredof@gmail.com> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "functiondeclaration.h" #include <language/duchain/duchainregister.h> using namespace KDevelop; namespace go { REGISTER_DUCHAIN_ITEM(GoFunctionDeclaration); GoFunctionDeclaration::GoFunctionDeclaration(const go::GoFunctionDeclaration& rhs): FunctionDeclaration(*new GoFunctionDeclarationData(*rhs.d_func())) { } GoFunctionDeclaration::GoFunctionDeclaration(const RangeInRevision& range, DUContext* context): FunctionDeclaration(*new GoFunctionDeclarationData, range) { d_func_dynamic()->setClassId(this); if (context) { setContext(context); } } GoFunctionDeclaration::GoFunctionDeclaration(go::GoFunctionDeclarationData& data): FunctionDeclaration(data) { } GoFunctionDeclaration::GoFunctionDeclaration(go::GoFunctionDeclarationData& data, const RangeInRevision& range): FunctionDeclaration(data, range) { } Declaration* GoFunctionDeclaration::clonePrivate() const { return new GoFunctionDeclaration(*this); } QString GoFunctionDeclaration::toString() const { return KDevelop::FunctionDeclaration::toString(); //return QString("test func declaration"); } void GoFunctionDeclaration::setReturnArgsContext(DUContext* context) { d_func_dynamic()->returnContext = context; } DUContext* GoFunctionDeclaration::returnArgsContext() const { return d_func()->returnContext.context(); } }
gpl-2.0
faithmade/rock
inc/template-tags.php
6555
<?php /** * Custom template tags for this theme. * * @package Rock * @since 1.0.0 */ /** * Display a custom logo. * * @since 1.0.0 */ function rock_the_custom_logo() { /** * For backwards compatibility prior to WordPress 4.5. * * @link https://developer.wordpress.org/reference/functions/the_custom_logo/ * @since 1.0.0 */ if ( function_exists( 'the_custom_logo' ) ) { the_custom_logo(); return; } $custom_logo_id = get_theme_mod( 'custom_logo' ); if ( ! $custom_logo_id && ! is_customize_preview() ) { return; } $args = array( 'class' => 'custom-logo', 'itemprop' => 'logo', ); printf( '<a href="%1$s" class="custom-logo-link" %2$s>%3$s</a>', esc_url( home_url( '/' ) ), $custom_logo_id ? 'rel="home" itemprop="url"' : 'style="display:none;"', $custom_logo_id ? wp_get_attachment_image( $custom_logo_id, 'full', false, $args ) : '<img class="custom-logo"/>' ); } /** * Display the site title. * * @since 1.0.0 */ function rock_the_site_title() { $html = sprintf( '<h1 class="site-title"><a href="%s" rel="home">%s</a></h1>', esc_url( home_url( '/' ) ), get_bloginfo( 'name' ) ); /** * Filter the site title HTML. * * @since 1.0.0 * * @var string */ echo (string) apply_filters( 'rock_the_site_title', $html ); } /** * Display the site description. * * @since 1.0.0 */ function rock_the_site_description() { $html = sprintf( '<div class="site-description">%s</div>', get_bloginfo( 'description' ) ); /** * Filter the site description HTML. * * @since 1.0.0 * * @var string */ echo (string) apply_filters( 'rock_the_site_description', $html ); } /** * Display a page title. * * @since 1.0.0 */ function rock_the_page_title() { if ( $title = rock_get_the_page_title() ) { echo $title; // xss ok } } /** * Display navigation to next/previous set of posts when applicable. * * @global WP_Query $wp_query * @since 1.0.0 */ function rock_paging_nav() { global $wp_query; if ( ! isset( $wp_query->max_num_pages ) || $wp_query->max_num_pages < 2 ) { return; } ?> <nav class="navigation paging-navigation"> <h2 class="screen-reader-text"><?php esc_html_e( 'Posts navigation', 'rock' ); ?></h2> <div class="nav-links"> <?php if ( get_next_posts_link() ) : ?> <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'rock' ) ); ?></div> <?php endif; ?> <?php if ( get_previous_posts_link() ) : ?> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'rock' ) ); ?></div> <?php endif; ?> </div><!-- .nav-links --> </nav><!-- .navigation --> <?php } /** * Display navigation to next/previous post when applicable. * * @global WP_Post $post * @since 1.0.0 */ function rock_post_nav() { global $post; $previous = is_attachment() ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true ); $next = get_adjacent_post( false, '', false ); if ( ! $next && ! $previous ) { return; } ?> <nav class="navigation post-navigation"> <h1 class="screen-reader-text"><?php esc_html_e( 'Post navigation', 'rock' ); ?></h1> <div class="nav-links"> <?php if ( is_rtl() ) : ?> <div class="nav-next"><?php next_post_link( '%link &larr;' ); ?></div> <div class="nav-previous"><?php previous_post_link( '&rarr; %link' ); ?></div> <?php else : ?> <div class="nav-previous"><?php previous_post_link( '&larr; %link' ); ?></div> <div class="nav-next"><?php next_post_link( '%link &rarr;' ); ?></div> <?php endif; ?> </div><!-- .nav-links --> </nav><!-- .navigation --> <?php } /** * Prints HTML with meta information for the current post-date/time and author. * * @since 1.0.0 */ function rock_posted_on() { $time = sprintf( '<time class="entry-date published" datetime="%s">%s</time>', esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ) ); if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) { $time = sprintf( '<time class="updated" datetime="%s">%s</time>', esc_attr( get_the_modified_date( 'c' ) ), esc_html( get_the_modified_date() ) ); } printf( '<span class="posted-on"><a href="%s" rel="bookmark">%s</a><span>', get_permalink(), $time // xss ok ); } /** * Prints the post format for the current post. * * @since 1.0.0 */ function rock_post_format() { $format = get_post_format(); $format = empty( $format ) ? 'standard' : $format; printf( '<span class="post-format">%s</span>', esc_html( $format ) ); } /** * Display very simple breadcrumbs. * * Adapted from Christoph Weil's Really Simple Breadcrumb plugin. * * @global WP_Post $post * @link https://wordpress.org/plugins/really-simple-breadcrumb/ * @since 1.0.0 */ function rock_breadcrumbs() { global $post; $separator = ' <span class="sep"></span> '; echo '<div class="breadcrumbs">'; if ( ! is_front_page() ) { printf( '<a href="%s">%s</a>%s', esc_url( home_url( '/' ) ), esc_html( get_bloginfo( 'name' ) ), $separator // xss ok ); if ( 'page' === get_option( 'show_on_front' ) ) { printf( '<a href="%s">%s</a>%s', esc_url( rock_get_posts_url() ), esc_html__( 'Blog', 'rock' ), $separator // xss ok ); } if ( is_category() || is_single() ) { the_category( ', ' ); if ( is_single() ) { echo $separator; // xss ok the_title(); } } elseif ( is_page() && $post->post_parent ) { $home = get_post( get_option( 'page_on_front' ) ); for ( $i = count( $post->ancestors )-1; $i >= 0; $i-- ) { if ( ( $home->ID ) != ( $post->ancestors[$i] ) ) { echo '<a href="' . get_permalink( $post->ancestors[$i] ) . '">' . get_the_title( $post->ancestors[$i] ) . '</a>' . $separator; } } the_title(); } elseif ( is_page() ) { the_title(); } elseif ( is_404() ) { echo '404'; } } else { bloginfo( 'name' ); } echo '</div>'; } /** * Gets the content template * * @since 1.0 */ function rock_get_content_template() { switch ( get_post_type() ) { case 'ctc_sermon': get_template_part( 'content', 'sermon' ); break; case 'ctc_event': get_template_part( 'content', 'event' ); break; case 'ctc_person': get_template_part( 'content', 'person' ); break; case 'ctc_location': get_template_part( 'content', 'location' ); break; default: get_template_part( 'content', get_post_format() ); break; } }
gpl-2.0
adolli/adxM3
src/MCU_driver/K60/Peripherals/DataFlow/DMA.cpp
1797
#include "DMA.h" using namespace K60; using namespace adxM3; #define DMAx_IRQH(x) \ void DMA ## x ## _IRQHandler(void) \ { \ enum { CH = x }; \ \ typedef ClockGateController<DMA::ClockSourceGate> ClockSource; \ typedef ClockGateController<DMA::MultiplexerClockSourceGate> MultiplexerClockSource; \ \ /* ´«ÊäÍê³Éʼþ´¦Àí */ \ if ((~DMA::ChannelTCEventMask) & _BV(CH)) \ { \ DMA::transferCompleteCBK[CH](); \ \ /* ×¢Ïúº¯Êý²¢ÆÁ±Î */ \ DMA::transferCompleteCBK[CH] = 0; \ DMA::ChannelTCEventMask |= _BV(CH); \ } \ \ /* Çå³ý´«ÊäÍê³É±ê־λ */ \ DMA::BitBandAccess()->INT[CH] = 1; \ \ /* Çå³ýELINKʹÄÜλ */ \ /*DMA::BaseAccess()->TCD[CH].CSR.MAJORELINK = RESET;*/ \ \ /* ¹Ø±ÕʱÖÓ£¬µ±È«²¿Ã»ÓÐͨµÀÕýÔÚ¹¤×÷ʱ²Å»áÕæÕý¹Ø±ÕʱÖÓ */ \ MultiplexerClockSource::ClockOff(); \ ClockSource::ClockOff(); \ DMA::ChannelIdleFlagStatus |= _BV(CH); \ if (DMA::TransferSourceBuffer[CH]) \ { \ /* ÊÍ·Å´«ÊäËùÓûº³åÇø */ \ delete [] DMA::TransferSourceBuffer[CH]; \ DMA::TransferSourceBuffer[CH] = NULL; \ } \ } DMAx_IRQH(0) DMAx_IRQH(1) DMAx_IRQH(2) DMAx_IRQH(3) DMAx_IRQH(4) DMAx_IRQH(5) DMAx_IRQH(6) DMAx_IRQH(7) DMAx_IRQH(8) DMAx_IRQH(9) DMAx_IRQH(10) DMAx_IRQH(11) DMAx_IRQH(12) DMAx_IRQH(13) DMAx_IRQH(14) DMAx_IRQH(15) void DMA_Error_IRQHandler(void) { }
gpl-2.0
evernote/pootle
pootle/apps/pootle_app/management/commands/changed_languages.py
2694
# -*- coding: utf-8 -*- # # Copyright 2014 Evernote Corporation # # This file is part of Pootle. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. import os os.environ['DJANGO_SETTINGS_MODULE'] = 'pootle.settings' from optparse import make_option from django.core.management.base import NoArgsCommand from django.db.models import Max from pootle_app.models import Revision from pootle_store.models import Store, Unit from . import BaseRunCommand class Command(NoArgsCommand): help = "List languages that were changed since last synchronization" option_list = BaseRunCommand.option_list + ( make_option('--after-revision', action='store', dest='after_revision', type=int, help='Show languages changed after any arbitrary revision'), ) def handle_noargs(self, **options): last_known_revision = Revision.objects.last() if options['after_revision'] is not None: after_revision = int(options['after_revision']) else: after_revision = Store.objects.all().aggregate( Max('last_sync_revision') )['last_sync_revision__max'] or -1 self.stderr.write( 'Will show languages changed between revisions %s (exclusive) ' 'and %s (inclusive)' % (after_revision, last_known_revision) ) # if the requested revision is the same or is greater than # the last known one, return nothing if after_revision >= last_known_revision: self.stderr.write('(no known changes)') return q = Unit.objects.filter( revision__gt=after_revision ).values( 'store__translation_project__language__code', ).order_by( 'store__translation_project__language__code', ).distinct() languages = q.values_list('store__translation_project__language__code', flat=True) # list languages separated by comma for easy parsing print ','.join(languages)
gpl-2.0
hjort/cpp-fr-course
devoirs/devoir03/parachutiste.cc
634
#include <iostream> #include <cmath> // pour exp() using namespace std; int main() { double masse(80.0); do { cout << "masse du parachutiste (>= 40) ? "; cin >> masse; } while (masse < 40.0); double h0(39000.0); do { cout << "hauteur de depart du parachutiste (>= 250) ? "; cin >> h0; } while (h0 < 250.0); /******************************************* * Completez le programme a partir d'ici. *******************************************/ /******************************************* * Ne rien modifier apres cette ligne. *******************************************/ return 0; }
gpl-2.0
mathiasbc/EZAlchemy
ezalchemy/constants.py
134
# dialect+driver://username:password@host:port/database SKELETON_URL = '%(dialect_driver)s://%(user)s:%(pass)s@%(host)s/%(database)s'
gpl-2.0
Yellowen/rahyab_rails
lib/rahyab_rails/engine.rb
284
require 'rahyab' module RahyabRails class Engine < ::Rails::Engine isolate_namespace RahyabRails engine_name 'rahyab_rails' # Map `api` to `API` in Rails autoload ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym 'SMS' end end end
gpl-2.0
jtsaito/kanji-meister
spec/models/kanji_spec.rb
1001
require "rails_helper" describe Kanji do describe ".by" do subject { Kanji.by(attribute, value) } context "when looking up by heisig_id" do let(:attribute) { :heisig_id } let(:value) { 1455 } it "finds with kanji" do expect(subject.map(&:kanji)).to eql(["鑑"]) end it "finds with key word " do expect(subject.map(&:key_word)).to eql(["specimen"]) end end context "when looking up by kanji" do let(:attribute) { :kanji } let(:value) { "襲" } it "finds with heisig id" do expect(subject.map(&:heisig_id)).to eql([2025.to_s]) end it "finds with heisig lesson" do expect(subject.map(&:heisig_lesson)).to eql([55.to_s]) end end context "when looking by non-existing attribute" do let(:attribute) { :foo } let(:value) { 1455 } it "raises error" do expect { subject }.to raise_error(Kanji::UnknownAttributeError) end end end end
gpl-2.0
left21wm/webmaster.left21.com
wp-content/plugins/mytory-smooth-scroll/mytory-smooth-scroll.php
568
<?php /* Plugin Name: Mytory internal link smooth scroll Description: Internal link smooth scroll Version: 1.0.0 Author: mytory Author URI: http://mytory.co.kr License: GPL2 */ function mytory_smooth_scroll(){ wp_enqueue_script('jquery-smooth-scroll', plugin_dir_url(__FILE__) . 'jquery.smooth-scroll.min.js', array('jquery'), '', TRUE); wp_enqueue_script('jquery-color'); wp_enqueue_script('mytory-smooth-scroll', plugin_dir_url(__FILE__) . 'js.js', array('jquery', 'jquery-smooth-scroll'), '', TRUE); } add_action('wp_enqueue_scripts', 'mytory_smooth_scroll');
gpl-2.0
syborg101/co2serverclone
wp-content/themes/jupiter/framework/admin/theme-options/params/advanced/manage_theme.php
6915
<?php $advanced_section[] = array( "type" => "sub_group", "id" => "mk_options_manage_theme", "name" => __("Advanced / Manage Theme", "mk_framework") , "desc" => __("", "mk_framework") , "fields" => array( array( "name" => __("Google Page Speed Optimization (Beta feature)", "mk_framework") , "desc" => __("Optimizes your web-site assets for Google in order to get higher points and rankings. Before enabling this option make sure that you have : <br /> 1- Properly formatted coding tags. <br /> 2- Powerful hosting. This option consumes server resources greedily. <br /> 3- Proper Caching and Minifying plug-ins. We also recommend Super Cache and Super Minify plug-ins, which is free.<br /> This feature is yet in beta stage. Do not use this in a production website. ", "mk_framework") , "id" => "pagespeed-optimization", "default" => "false", "type" => "toggle" ) , array( "name" => __("Minify Theme Javascript File", "mk_framework") , "desc" => __("If you enable this option pre-minified theme Java Script files will be renderred in front-end. Minified JS is 30%-40% smaller in file size which will improve page speed.", "mk_framework") , "id" => "minify-js", "default" => "false", "type" => "toggle" ) , array( "name" => __("Minify Theme Styles Files", "mk_framework") , "desc" => __("If you enable this option pre-minified theme CSS files will be renderred in front-end. Minified CSS is 30%-40% smaller in file size which will improve page speed.", "mk_framework") , "id" => "minify-css", "default" => "true", "type" => "toggle" ) , array( "name" => __("Query String From Static Flies", "mk_framework") , "desc" => __("Disabling this option will remove \"ver\" query string from JS and CSS files. For More info Please <a target=\"_blank\" href=\"https://developers.google.com/speed/docs/best-practices/caching#LeverageProxyCaching\">Read Here</a>.", "mk_framework") , "id" => "remove-js-css-ver", "default" => "true", "type" => "toggle" ) , array( "name" => __("Portfolio Post Type", "mk_framework") , "desc" => __("If you will not use Portfolio post type feature simply disable this option.", "mk_framework") , "id" => "portfolio-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("News Post Type", "mk_framework") , "desc" => __("If you will not use News post type feature simply disable this option.", "mk_framework") , "id" => "news-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("FAQ Post Type", "mk_framework") , "desc" => __("If you will not use faq post type feature simply disable this option.", "mk_framework") , "id" => "faq-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Timeline Post Type", "mk_framework") , "desc" => __("If you will not use timeline post type feature simply disable this option.", "mk_framework") , "id" => "timeline-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Photo Album Post Type", "mk_framework") , "desc" => __("If you will not use Photo Album post type feature simply disable this option.", "mk_framework") , "id" => "photo_album-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Pricing Tables Post Type", "mk_framework") , "desc" => __("If you will not use Pricing Tables post type feature simply disable this option.", "mk_framework") , "id" => "pricing-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Clients Post Type", "mk_framework") , "desc" => __("If you will not use Clients post type feature simply disable this option.", "mk_framework") , "id" => "clients-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Employees Post Type", "mk_framework") , "desc" => __("If you will not use Employees post type feature simply disable this option.", "mk_framework") , "id" => "employees-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Testimonial Post Type", "mk_framework") , "desc" => __("If you will not use Testimonial post type feature simply disable this option.", "mk_framework") , "id" => "testimonial-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("FlexSlider Post Type", "mk_framework") , "desc" => __("If you will not use FlexSlider post type feature simply disable this option.", "mk_framework") , "id" => "slideshow-post-type", "default" => "false", "type" => "toggle" ) , array( "name" => __("Edge Slideshow Post Type", "mk_framework") , "desc" => __("If you will not use Edge Slideshow post type feature simply disable this option.", "mk_framework") , "id" => "edge-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Banner Builder Post Type", "mk_framework") , "desc" => __("If you will not use Banner Builder post type feature simply disable this option.", "mk_framework") , "id" => "banner_builder-post-type", "default" => "false", "type" => "toggle" ) , array( "name" => __("Tab Slider Post Type", "mk_framework") , "desc" => __("If you will not use Tab Slider post type feature simply disable this option.", "mk_framework") , "id" => "tab_slider-post-type", "default" => "true", "type" => "toggle" ) , array( "name" => __("Animated Columns Post Type", "mk_framework") , "desc" => __("If you will not use Animated Columns post type feature simply disable this option.", "mk_framework") , "id" => "animated-columns-post-type", "default" => "true", "type" => "toggle" ) , ) , );
gpl-2.0
aj-adl/balsacentral
content/themes/balsacentral/woocommerce/global/breadcrumb.php
7150
<?php /** * Shop breadcrumb * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $post, $wp_query; if ( get_option('woocommerce_prepend_shop_page_to_urls') == "yes" && woocommerce_get_page_id( 'shop' ) && get_option( 'page_on_front' ) !== woocommerce_get_page_id( 'shop' ) ) $prepend = $before . '<a href="' . get_permalink( woocommerce_get_page_id('shop') ) . '">' . get_the_title( woocommerce_get_page_id('shop') ) . '</a> ' . $after . $delimiter; else $prepend = ''; if ( ( ! is_home() && ! is_front_page() && ! ( is_post_type_archive() && get_option( 'page_on_front' ) == woocommerce_get_page_id( 'shop' ) ) ) || is_paged() ) { echo $wrap_before; if ( ! empty( $home ) ) { echo $before . '<a class="home" href="' . apply_filters( 'woocommerce_breadcrumb_home_url', home_url() ) . '">' . $home . '</a>' . $after . $delimiter; } if ( is_category() ) { $cat_obj = $wp_query->get_queried_object(); $this_category = get_category( $cat_obj->term_id ); if ( $this_category->parent != 0 ) { $parent_category = get_category( $this_category->parent ); echo get_category_parents($parent_category, TRUE, $delimiter ); } echo $before . single_cat_title( '', false ) . $after; } elseif ( is_tax('product_cat') ) { echo $prepend; $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); $parents = array(); $parent = $term->parent; while ( $parent ) { $parents[] = $parent; $new_parent = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ) ); $parent = $new_parent->parent; } if ( ! empty( $parents ) ) { $parents = array_reverse( $parents ); foreach ( $parents as $parent ) { $item = get_term_by( 'id', $parent, get_query_var( 'taxonomy' )); echo $before . '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . esc_html( $item->name ) . '</a>' . $after . $delimiter; } } $queried_object = $wp_query->get_queried_object(); echo $before . esc_html( $queried_object->name ) . $after; } elseif ( is_tax('product_tag') ) { $queried_object = $wp_query->get_queried_object(); echo $prepend . $before . __( 'Products tagged &ldquo;', 'woocommerce' ) . $queried_object->name . '&rdquo;' . $after; } elseif ( is_day() ) { echo $before . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $after . $delimiter; echo $before . '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a>' . $after . $delimiter; echo $before . get_the_time('d') . $after; } elseif ( is_month() ) { echo $before . '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $after . $delimiter; echo $before . get_the_time('F') . $after; } elseif ( is_year() ) { echo $before . get_the_time('Y') . $after; } elseif ( is_post_type_archive('product') && get_option('page_on_front') !== woocommerce_get_page_id('shop') ) { $_name = woocommerce_get_page_id( 'shop' ) ? get_the_title( woocommerce_get_page_id( 'shop' ) ) : ''; if ( ! $_name ) { $product_post_type = get_post_type_object( 'product' ); $_name = $product_post_type->labels->singular_name; } if ( is_search() ) { echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . $_name . '</a>' . $delimiter . __( 'Search results for &ldquo;', 'woocommerce' ) . get_search_query() . '&rdquo;' . $after; } elseif ( is_paged() ) { echo $before . '<a href="' . get_post_type_archive_link('product') . '">' . $_name . '</a>' . $after; } else { echo $before . $_name . $after; } } elseif ( is_single() && !is_attachment() ) { if ( get_post_type() == 'product' ) { echo $prepend; if ( $terms = wp_get_object_terms( $post->ID, 'product_cat' ) ) { $term = current( $terms ); $parents = array(); $parent = $term->parent; while ( $parent ) { $parents[] = $parent; $new_parent = get_term_by( 'id', $parent, 'product_cat' ); $parent = $new_parent->parent; } if ( ! empty( $parents ) ) { $parents = array_reverse($parents); foreach ( $parents as $parent ) { $item = get_term_by( 'id', $parent, 'product_cat'); echo $before . '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . $item->name . '</a>' . $after . $delimiter; } } echo $before . '<a href="' . get_term_link( $term->slug, 'product_cat' ) . '">' . $term->name . '</a>' . $after . $delimiter; } echo $before . get_the_title() . $after; } elseif ( get_post_type() != 'post' ) { $post_type = get_post_type_object( get_post_type() ); $slug = $post_type->rewrite; echo $before . '<a href="' . get_post_type_archive_link( get_post_type() ) . '">' . $post_type->labels->singular_name . '</a>' . $after . $delimiter; echo $before . get_the_title() . $after; } else { $cat = current( get_the_category() ); echo get_category_parents( $cat, true, $delimiter ); echo $before . get_the_title() . $after; } } elseif ( is_404() ) { echo $before . __( 'Error 404', 'woocommerce' ) . $after; } elseif ( ! is_single() && ! is_page() && get_post_type() != 'post' ) { $post_type = get_post_type_object( get_post_type() ); if ( $post_type ) echo $before . $post_type->labels->singular_name . $after; } elseif ( is_attachment() ) { $parent = get_post( $post->post_parent ); $cat = get_the_category( $parent->ID ); $cat = $cat[0]; echo get_category_parents( $cat, true, '' . $delimiter ); echo $before . '<a href="' . get_permalink( $parent ) . '">' . $parent->post_title . '</a>' . $after . $delimiter; echo $before . get_the_title() . $after; } elseif ( is_page() && !$post->post_parent ) { echo $before . get_the_title() . $after; } elseif ( is_page() && $post->post_parent ) { $parent_id = $post->post_parent; $breadcrumbs = array(); while ( $parent_id ) { $page = get_page( $parent_id ); $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title( $page->ID ) . '</a>'; $parent_id = $page->post_parent; } $breadcrumbs = array_reverse( $breadcrumbs ); foreach ( $breadcrumbs as $crumb ) echo $crumb . '' . $delimiter; echo $before . get_the_title() . $after; } elseif ( is_search() ) { echo $before . __( 'Search results for &ldquo;', 'woocommerce' ) . get_search_query() . '&rdquo;' . $after; } elseif ( is_tag() ) { echo $before . __( 'Posts tagged &ldquo;', 'woocommerce' ) . single_tag_title('', false) . '&rdquo;' . $after; } elseif ( is_author() ) { $userdata = get_userdata($author); echo $before . __( 'Author:', 'woocommerce' ) . ' ' . $userdata->display_name . $after; } if ( get_query_var( 'paged' ) ) echo ' (' . __( 'Page', 'woocommerce' ) . ' ' . get_query_var( 'paged' ) . ')'; echo $wrap_after; }
gpl-2.0
yukaritan/kawaiirc
system/ircfactory.py
829
from builtins import super, property, dict from collections import deque from twisted.internet.protocol import ServerFactory class IRCFactory(ServerFactory): """ This is where networking is born! It's also where we list all our clients and channels. When a user connects, a ClientConnection is born to cater to them. """ def __init__(self, *args, **kw): super(*args, **kw) self._clients = deque() self._channels = dict() @property def clients(self): """ :rtype : deque """ return self._clients @clients.setter def clients(self, value): """ :type value: deque """ self._clients = value @property def channels(self): """ :rtype : dict """ return self._channels
gpl-2.0
tsh/fun-with-panda3d
main.py
21
""" Panda 1.9dev """
gpl-2.0
appnosteev/behat-vagrant
cookbooks/drupal-cookbooks/drupal/recipes/behat_build.rb
7553
# Deploy an example Drupal site. # TODO Move this to a definition with parameters. include_recipe "mysql" include_recipe "drush" include_recipe "drush_make" #bash aliases # Add an admin user to mysql execute "add-admin-user" do command "/usr/bin/mysql -u root -p#{node[:mysql][:server_root_password]} -e \"" + "GRANT ALL PRIVILEGES ON *.* TO 'myadmin'@'localhost' IDENTIFIED BY 'myadmin' WITH GRANT OPTION;" + "GRANT ALL PRIVILEGES ON *.* TO 'myadmin'@'%' IDENTIFIED BY 'myadmin' WITH GRANT OPTION;\" " + "mysql" action :run end # TODO: Break this out into a vagrant only cookbook? (name: "drupal-vagrant") # create a drupal db execute "add-drupal-db" do command "/usr/bin/mysql -u root -p#{node[:mysql][:server_root_password]} -e \"" + "CREATE DATABASE drupal;\"" action :run ignore_failure true end # drush make a default drupal site example bash "install-default-drupal-makefile" do code <<-EOH (mkdir -p /vagrant/public/drupal.vbox.local) EOH not_if { File.exists?("/vagrant/public/drupal.vbox.local/behat_build.make") } end # Copy make file to site. cookbook_file "/vagrant/public/drupal.vbox.local/behat_build.make" do source "behat_build.make" notifies :restart, resources("service[apache2]"), :delayed end # drush make a default drupal site example bash "install-default-drupal-site" do code <<-EOH cd /vagrant/public/drupal.vbox.local drush make behat_build.make docroot EOH not_if { File.exists?("/vagrant/public/drupal.vbox.local/docroot/index.php") } end #copy correct behat.yml to behat_editor cookbook_file "/vagrant/public/drupal.vbox.local/docroot/sites/all/modules/custom/behat_editor/behat/behat.yml" do source "behat.yml" end # drush make a default drupal site example bash "install-default-drupal-files-and-ctools-directory" do code <<-EOH mkdir -p /vagrant/public/drupal.vbox.local/docroot/sites/default/files/ctools/css chmod -R 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files EOH end cookbook_file "/vagrant/public/drupal.vbox.local/docroot/sites/default/settings.php" do source "settings.php" end bash "open-files-directory-permissions" do code <<-EOH chmod 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/settings.php EOH end bash "install-drupal" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot drush si standard install_configure_form.update_status_module='array(FALSE,FALSE)' --db-url=mysql://root:root@localhost:3306/drupal --account-pass=admin --account-name=admin --site-name=Behat-Vagrant -y EOH end #bash "turn-drupal-errors-on" do # code <<-EOH # cd /vagrant/public/drupal.vbox.local/docroot # drush vset -y error_level 2 # EOH #end # configure the behat software with drush bash "configure-behat-configure-composer-directories" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot mkdir -p /vagrant/public/drupal.vbox.local/docroot/sites/all/modules/contrib/composer_manager/ mkdir -p /vagrant/public/drupal.vbox.local/docroot/sites/all/vendor/ EOH end bash "configure-drupal-modules" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot drush en og jquery_update ctools services libraries views_bulk_operations entity entityreference views features bootstrap devel -y drush en module_filter views_ui og_ui -y drush dis color update comment contextual dashboard search shortcut overlay -y drush vset admin_theme default -y EOH end bash "really-bad-way-to-copy-directories-into-a-vm" do #creates a dummy page (group) else the github editor fails code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot cp -r /vagrant/cookbooks/drupal-cookbooks/drupal/files/default/behat_organic_groups /vagrant/public/drupal.vbox.local/docroot/sites/all/modules/custom cp -r /vagrant/cookbooks/drupal-cookbooks/drupal/files/default/behat_sample_content /vagrant/public/drupal.vbox.local/docroot/sites/all/modules/custom drush en behat_organic_groups behat_sample_content -y drush behat-sample-content -y EOH end bash "enable-simplenoty-module" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot drush en simple_noty -y drush nl -y EOH end bash "configure-composer-module" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot mkdir -p /vagrant/public/drupal.vbox.local/docroot/sites/default/files/composer chmod 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files/composer drush vset composer_manager_file_dir public://composer drush en og composer_manager -y drush vset theme_default bootstrap cd /vagrant/public/drupal.vbox.local/docroot/sites/default/files/composer curl -sS https://getcomposer.org/installer | php php composer.phar install drush composer-manager update EOH end #install drush registry repair for later bash "install-drush-registry-rebuild" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot drush dl registry_rebuild -y EOH end #copy drush aliases fle #cookbook_file "~/.drush/drupal.vbox.local.aliases.drushrc.php" do # source "drupal.vbox.local.aliases.drushrc.php" # ignore_failure true #end bash "configure-behat-library" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot chmod -R 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files drush en behat_lib -y chmod -R 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files drush bl EOH end bash "configure-behat-editor" do # Composer manager may fail and need to be run manually if input is required or use the php cmdline instead code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot chmod -R 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files drush en behat_editor behat_editor_limit_tags behat_editor_services -y drush composer-manager update drush en github_behat_editor -y chmod -R 777 /vagrant/public/drupal.vbox.local/docroot/sites/default/files drush composer-manager update EOH end bash "install-selenium-server" do code <<-EOH cd /home/vagrant/ curl -O http://selenium.googlecode.com/files/selenium-server-standalone-2.31.0.jar EOH end bash "configure-behat-editor-saucelabs-integration" do # this will hose the registry so rebuild it # there is a conflict with the version of behat somewhere which prevents the composer.json # getting rewritten correctly for saucelabs, so nuke the composer.json first and rebuild code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot chmod -R 777 sites/all/libraries rm sites/default/files/composer/composer.json drush en behat_editor_saucelabs -y EOH end bash "final-composer-rebuild" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot sudo chmod -R 777 sites/default/files drush rr drush composer-manager update -y EOH end # update to php 5.4 http://www.barryodonovan.com/index.php/2012/05/22/ubuntu-12-04-precise-pangolin-and-php-5-4-again # dont execute the grub updates as they require input bash "udpate-php54" do code <<-EOH add-apt-repository ppa:ondrej/php5-oldstable # echo 'grub-pc hold' | sudo dpkg --set-selections apt-get update DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install php5 # TODO install apc, xhprof and xdebug EOH end # one final update to remove the manual step if not necessary this time. bash "one-final-composer-manager-update" do code <<-EOH cd /vagrant/public/drupal.vbox.local/docroot drush composer-manager update -y EOH end
gpl-2.0
sushanttripathy/pang_kaiju
uriparse.hpp
1257
#ifndef _URIPARSE_HPP_ #define _URIPARSE_HPP_ #include <string> #include <map> #include <vector> #include <boost/regex.hpp> #include "trim.hpp" #include "tokenize.hpp" class URIParse { private: std::string url; std::map <std::string, std::string> parts; bool isParsed; bool isValidURI; static std::string tld_list; static std::string sld_list; static std::string thld_list; static std::string fld_list; std::vector <std::string> path_parts; public: static const int PROTOCOL_ALL = 7; static const int PROTOCOL_HTTP = 1; static const int PROTOCOL_HTTPS = 2; static const int PROTOCOL_FTP = 4; URIParse(const char* url_); URIParse(std::string url_); bool isValid(int allowed_protocols = URIParse::PROTOCOL_ALL , bool allow_ip_v4add = true); std::map <std::string, std::string>* GetParsedParts(int allowed_protocols = URIParse::PROTOCOL_ALL , bool allow_ip_v4add = true); std::string ReconstructURL(int allowed_protocols = URIParse::PROTOCOL_ALL , bool allow_ip_v4add = true); std::string ReconstructPrettyURL(int allowed_protocols = URIParse::PROTOCOL_ALL , bool allow_ip_v4add = true); std::string MakeAbsoluteURI(std::string relative_uri); }; #endif // _URIPARSE_HPP_
gpl-2.0
aneeshtn/enviornment
Sfa/MPIData.php
7172
<?php class MPIData { ## # # Unformatted purchase amount. It should not contain any special characters such as "$" etc. # # var $mstrPurchaseAmount ; ## # # Formatted purchase amount. This field should contain a currency symbol, with an thousands separator (s), decimal point and ISO minor units defined for the currency specified in the Purchase Currency field. # Ex. $1,234.56 # #/ var $mstrDisplayAmount; ## # # Contains the Standard ISO currency value for the country. The value for India is 356. For details refer: # http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html # #/ var $mstrCurrencyVal; ## # # The number of decimal places used in the amount is specified. Used to distinguish the units of money like Rs and Ps. # Example: Amount 100000 with an exponent value of 2 becomes Rs.1,000 # #/ var $mstrExponent; ## # # Brief description of items purchased, determined by the Merchant. # Example 2 shirts. # # var $mstrOrderDesc; ## # # This field is calculated based on installments and the Recur End and it denotes the frequency of payment. It is optional and must be included if other recurring variables are specified. # # var $mstrRecurFreq; ## # # This field indicates the end date of recurring value. It should be less than the card expiry date. It is also an optional field. # # var $mstrRecurEnd; ## # # MPI supports payment by installments. In order to enable this support to the customer, the following fields have to be set.This field indicates the number of times the payment is done to fulfill the transaction. # # var $mstrInstallment; ## # # This attribute indicates mode of transaction. For an internet based transaction the value to be set is "0". # # var $mstrDeviceCategory; ## # Denotes the browser version of the client. This field can be empty and is used by the MPI to denote the browser version. # # # var $mstrWhatIUse; ## # # The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image. # The server property request.getHeader("Accept") can be used for setting this value. # # var $mstrAcceptHdr; ## # # The User-Agent-header contains information about the user agent #(typically a newsreader) generating the article, for statistical #purposes and tracing of standards violations to specific software #needing correction. Although not one of the mandatory headers, #posting agents SHOULD normally include it. #The server property request.getHeader("User-Agent") can be used for setting this value. # # var $mstrAgentHdr; ## # Any Echo back field value # var $mstrShoppingContext; ## # # Should be set to the result of conducting an MPI transaction # # var $mstrVBVStatus; ## # Should be set to the result of conducting an MPI transaction # # var $mstrCAVV; ## # Should be set to the result of conducting an MPI transaction # # var $mstrECI; ## # Should be set to the result of conducting an MPI transaction # # var $mstrXID; # Default constructor of class MPIData function MPIData() { } function getECI() { return $this->mstrECI; } function getXID() { return $this->mstrXID; } function getVBVStatus() { return $this->mstrVBVStatus; } function setMPIRequestDetails($astrPurchaseAmount, $astrDisplayAmount, $astrCurrencyVal, $astrExponent, $astrOrderDesc, $astrRecurFreq,$astrRecurEnd, $astrInstallment, $astrDeviceCategory, $astrWhatIUse, $astrAcceptHdr, $astrAgentHdr ) { $this->mstrPurchaseAmount = $astrPurchaseAmount; $this->mstrDisplayAmount = $astrDisplayAmount; $this->mstrCurrencyVal = $astrCurrencyVal; $this->mstrExponent = $astrExponent; $this->mstrOrderDesc = $astrOrderDesc; $this->mstrRecurFreq = $astrRecurFreq; $this->mstrRecurEnd = $astrRecurEnd; $this->mstrInstallment = $astrInstallment; $this->mstrDeviceCategory = $astrDeviceCategory; $this->mstrWhatIUse = $astrWhatIUse; $this->mstrAcceptHdr = $astrAcceptHdr; $this->mstrAgentHdr = $astrAgentHdr; } function setMPIResponseDetails( $astrECI,$astrXID,$astrVBVStatus, $astrCAVV,$astrShoppingContext, $astrPurchaseAmount,$astrCurrencyVal) { $this->mstrECI = $astrECI; $this->mstrXID = $astrXID; $this->mstrVBVStatus = $astrVBVStatus; $this->mstrCAVV = $astrCAVV; $this->mstrShoppingContext=$astrShoppingContext; $this->mstrPurchaseAmount =$astrPurchaseAmount; $this->mstrCurrencyVal =$astrCurrencyVal; } function getCAVV() { return $this->mstrCAVV; } function getPurchaseAmount() { return $this->mstrPurchaseAmount; } function getDisplayAmount() { return $this->mstrDisplayAmount; } function getCurrencyVal() { return $this->mstrCurrencyVal; } function getExponent() { return $this->mstrExponent; } function getOrderDesc() { return $this->mstrOrderDesc; } function getRecurFreq() { return $this->mstrRecurFreq; } function getRecurEnd() { return $this->mstrRecurEnd; } function getInstallment() { return $this->mstrInstallment; } function getDeviceCategory() { return $this->mstrDeviceCategory; } function getWhatIUse() { return $this->mstrWhatIUse; } function getAcceptHdr() { return $this->mstrAcceptHdr; } function getAgentHdr() { return $this->mstrAgentHdr; } function getShoppingContext() { return $this->mstrShoppingContext; } function toString() { print "Purchase Amount".$this->mstrPurchaseAmount."\n". "Display Amount". $this->mstrDisplayAmount ."\n". "Currency ". $this->mstrCurrencyVal ."\n". "Exponent ". $this->mstrExponent ."\n". "Order Desc". $this->mstrOrderDesc ."\n". "RecurFreq ". $this->mstrRecurFreq ."\n". "Recur End". $this->mstrRecurEnd ."\n". "Installment". $this->mstrInstallment ."\n". "Device Category". $this->mstrDeviceCategory."\n". "What i use". $this->mstrWhatIUse ."\n". "Accept header". $this->mstrAcceptHdr ."\n". "Header Agent". $this->mstrAgentHdr ."\n" ; } } ?>
gpl-2.0
Vinatorul/notepad-plus-plus
PowerEditor/src/WinControls/DockingWnd/DockingManager.cpp
26802
// this file is part of docking functionality for Notepad++ // Copyright (C)2006 Jens Lorenz <jens.plugin.npp@gmx.de> // // 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. // // Note that the GPL places important restrictions on "derived works", yet // it does not provide a detailed definition of that term. To avoid // misunderstandings, we consider an application to constitute a // "derivative work" for the purpose of this license if it does any of the // following: // 1. Integrates source code from Notepad++. // 2. Integrates/includes/aggregates Notepad++ into a proprietary executable // installer, such as those produced by InstallShield. // 3. Links to a library or executes a program that does any of the above. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "precompiledHeaders.h" #include "DockingManager.h" #include "DockingSplitter.h" #include "DockingCont.h" #include "Gripper.h" #include "parameters.h" BOOL DockingManager::_isRegistered = FALSE; //Window of event handling DockingManager (can only be one) static HWND hWndServer = NULL; //Next hook in line static HHOOK gWinCallHook = NULL; LRESULT CALLBACK FocusWndProc(int nCode, WPARAM wParam, LPARAM lParam); // Callback function that handles messages (to test focus) LRESULT CALLBACK FocusWndProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HC_ACTION && hWndServer) { DockingManager *pDockingManager = (DockingManager *)::GetWindowLongPtr(hWndServer, GWL_USERDATA); if (pDockingManager) { vector<DockingCont*> & vcontainer = pDockingManager->getContainerInfo(); CWPSTRUCT * pCwp = (CWPSTRUCT*)lParam; if (pCwp->message == WM_KILLFOCUS) { for (int i = 0; i < DOCKCONT_MAX; ++i) { vcontainer[i]->SetActive(FALSE); //deactivate all containers } } else if (pCwp->message == WM_SETFOCUS) { for (int i = 0; i < DOCKCONT_MAX; ++i) { vcontainer[i]->SetActive(IsChild(vcontainer[i]->getHSelf(), pCwp->hwnd)); //activate the container that contains the window with focus, this can be none } } } } return CallNextHookEx(gWinCallHook, nCode, wParam, lParam); } DockingManager::DockingManager() { _isInitialized = FALSE; _hImageList = NULL; memset(_iContMap, -1, CONT_MAP_MAX * sizeof(int)); _iContMap[0] = CONT_LEFT; _iContMap[1] = CONT_RIGHT; _iContMap[2] = CONT_TOP; _iContMap[3] = CONT_BOTTOM; // create four containers with splitters for (int i = 0; i < DOCKCONT_MAX; ++i) { DockingCont *_pDockCont = new DockingCont; _vContainer.push_back(_pDockCont); DockingSplitter *_pSplitter = new DockingSplitter; _vSplitter.push_back(_pSplitter); } } DockingManager::~DockingManager() { // delete 4 splitters for (int i = 0; i < DOCKCONT_MAX; ++i) { delete _vSplitter[i]; } } void DockingManager::init(HINSTANCE hInst, HWND hWnd, Window ** ppWin) { Window::init(hInst, hWnd); if (!_isRegistered) { WNDCLASS clz; clz.style = 0; clz.lpfnWndProc = staticWinProc; clz.cbClsExtra = 0; clz.cbWndExtra = 0; clz.hInstance = _hInst; clz.hIcon = NULL; clz.hCursor = ::LoadCursor(NULL, IDC_ARROW); clz.hbrBackground = NULL; clz.lpszMenuName = NULL; clz.lpszClassName = DSPC_CLASS_NAME; if (!::RegisterClass(&clz)) { throw std::runtime_error("DockingManager::init : RegisterClass() function failed"); } _isRegistered = TRUE; } _hSelf = ::CreateWindowEx( 0, DSPC_CLASS_NAME, TEXT(""), WS_CHILD | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, _hParent, NULL, _hInst, (LPVOID)this); if (!_hSelf) { throw std::runtime_error("DockingManager::init : CreateWindowEx() function return null"); } setClientWnd(ppWin); // create docking container for (int iCont = 0; iCont < DOCKCONT_MAX; ++iCont) { _vContainer[iCont]->init(_hInst, _hSelf); _vContainer[iCont]->doDialog(false); ::SetParent(_vContainer[iCont]->getHSelf(), _hParent); if ((iCont == CONT_TOP) || (iCont == CONT_BOTTOM)) _vSplitter[iCont]->init(_hInst, _hParent, _hSelf, DMS_HORIZONTAL); else _vSplitter[iCont]->init(_hInst, _hParent, _hSelf, DMS_VERTICAL); } // register window event hooking if (!hWndServer) hWndServer = _hSelf; CoInitialize(NULL); if (!gWinCallHook) //only set if not already done gWinCallHook = ::SetWindowsHookEx(WH_CALLWNDPROC, FocusWndProc, hInst, GetCurrentThreadId()); if (!gWinCallHook) { throw std::runtime_error("DockingManager::init : SetWindowsHookEx() function return null"); } _dockData.hWnd = _hSelf; _isInitialized = TRUE; } void DockingManager::destroy() { ::DestroyWindow(_hSelf); } LRESULT CALLBACK DockingManager::staticWinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { DockingManager *pDockingManager = NULL; switch (message) { case WM_NCCREATE : pDockingManager = (DockingManager *)(((LPCREATESTRUCT)lParam)->lpCreateParams); pDockingManager->_hSelf = hwnd; ::SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pDockingManager); return TRUE; default : pDockingManager = (DockingManager *)::GetWindowLongPtr(hwnd, GWL_USERDATA); if (!pDockingManager) return ::DefWindowProc(hwnd, message, wParam, lParam); return pDockingManager->runProc(hwnd, message, wParam, lParam); } } void DockingManager::updateContainerInfo(HWND hClient) { for (size_t iCont = 0, len = _vContainer.size(); iCont < len; ++iCont) { if (_vContainer[iCont]->updateInfo(hClient) == TRUE) { break; } } } void DockingManager::showContainer(HWND hCont, BOOL view) { for (size_t iCont = 0, len = _vContainer.size(); iCont < len; ++iCont) { if (_vContainer[iCont]->getHSelf() == hCont) showContainer(iCont, view); } } LRESULT DockingManager::runProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_NCACTIVATE: { // activate/deactivate titlebar of toolbars for (size_t iCont = DOCKCONT_MAX, len = _vContainer.size(); iCont < len; ++iCont) { ::SendMessage(_vContainer[iCont]->getHSelf(), WM_NCACTIVATE, wParam, (LPARAM)-1); } if ((int)lParam != -1) { ::SendMessage(_hParent, WM_NCACTIVATE, wParam, (LPARAM)-1); } break; } case WM_MOVE: case WM_SIZE: { onSize(); break; } case WM_DESTROY: { // unregister window event hooking BEFORE EVERYTHING ELSE if (hWndServer == hwnd) { UnhookWindowsHookEx(gWinCallHook); gWinCallHook = NULL; hWndServer = NULL; } // destroy imagelist if it exists if (_hImageList != NULL) { ::ImageList_Destroy(_hImageList); } // destroy containers for (int i = _vContainer.size(); i > 0; i--) { _vContainer[i-1]->destroy(); delete _vContainer[i-1]; } CoUninitialize(); break; } case DMM_LBUTTONUP: //is this message still relevant? { if (::GetActiveWindow() != _hParent) break; // set respective activate state for (int i = 0; i < DOCKCONT_MAX; ++i) { _vContainer[i]->SetActive(IsChild(_vContainer[i]->getHSelf(), ::GetFocus())); } return TRUE; } case DMM_MOVE: { Gripper *pGripper = new Gripper; pGripper->init(_hInst, _hParent); pGripper->startGrip((DockingCont*)lParam, this); break; } case DMM_MOVE_SPLITTER: { int offset = wParam; for (int iCont = 0; iCont < DOCKCONT_MAX; ++iCont) { if (_vSplitter[iCont]->getHSelf() == (HWND)lParam) { switch (iCont) { case CONT_TOP: _dockData.rcRegion[iCont].bottom -= offset; if (_dockData.rcRegion[iCont].bottom < 0) { _dockData.rcRegion[iCont].bottom = 0; } if ((_rcWork.bottom < (-SPLITTER_WIDTH)) && (offset < 0)) { _dockData.rcRegion[iCont].bottom += offset; } break; case CONT_BOTTOM: _dockData.rcRegion[iCont].bottom += offset; if (_dockData.rcRegion[iCont].bottom < 0) { _dockData.rcRegion[iCont].bottom = 0; } if ((_rcWork.bottom < (-SPLITTER_WIDTH)) && (offset > 0)) { _dockData.rcRegion[iCont].bottom -= offset; } break; case CONT_LEFT: _dockData.rcRegion[iCont].right -= offset; if (_dockData.rcRegion[iCont].right < 0) { _dockData.rcRegion[iCont].right = 0; } if ((_rcWork.right < SPLITTER_WIDTH) && (offset < 0)) { _dockData.rcRegion[iCont].right += offset; } break; case CONT_RIGHT: _dockData.rcRegion[iCont].right += offset; if (_dockData.rcRegion[iCont].right < 0) { _dockData.rcRegion[iCont].right = 0; } if ((_rcWork.right < SPLITTER_WIDTH) && (offset > 0)) { _dockData.rcRegion[iCont].right -= offset; } break; } onSize(); break; } } break; } case DMM_DOCK: case DMM_FLOAT: { toggleActiveTb((DockingCont*)lParam, message); return FALSE; } case DMM_CLOSE: { tTbData TbData = *((DockingCont*)lParam)->getDataOfActiveTb(); LRESULT res = SendNotify(TbData.hClient, DMN_CLOSE); // Be sure the active item is OK with closing if (res == 0) // Item will be closing? ::PostMessage(_hParent, WM_ACTIVATE, WA_ACTIVE, 0); // Tell editor to take back focus return res; } case DMM_FLOATALL: { toggleVisTb((DockingCont*)lParam, DMM_FLOAT); return FALSE; } case DMM_DOCKALL: { toggleVisTb((DockingCont*)lParam, DMM_DOCK); return FALSE; } case DMM_GETIMAGELIST: { return (LPARAM)_hImageList; } case DMM_GETICONPOS: { for (UINT uImageCnt = 0, len = _vImageList.size(); uImageCnt < len; ++uImageCnt) { if ((HWND)lParam == _vImageList[uImageCnt]) { return uImageCnt; } } return -1; } default : break; } return ::DefWindowProc(_hSelf, message, wParam, lParam); } void DockingManager::onSize() { reSizeTo(_rect); } void DockingManager::reSizeTo(RECT & rc) { // store current size of client area _rect = rc; // prepare size of work area _rcWork = rc; if (_isInitialized == FALSE) return; // set top container _dockData.rcRegion[CONT_TOP].left = rc.left; _dockData.rcRegion[CONT_TOP].top = rc.top; _dockData.rcRegion[CONT_TOP].right = rc.right-rc.left; _vSplitter[CONT_TOP]->display(false); if (_vContainer[CONT_TOP]->isVisible()) { _rcWork.top += _dockData.rcRegion[CONT_TOP].bottom + SPLITTER_WIDTH; _rcWork.bottom -= _dockData.rcRegion[CONT_TOP].bottom + SPLITTER_WIDTH; // set size of splitter RECT rc = {_dockData.rcRegion[CONT_TOP].left , _dockData.rcRegion[CONT_TOP].top + _dockData.rcRegion[CONT_TOP].bottom, _dockData.rcRegion[CONT_TOP].right , SPLITTER_WIDTH}; _vSplitter[CONT_TOP]->reSizeTo(rc); } // set bottom container _dockData.rcRegion[CONT_BOTTOM].left = rc.left; _dockData.rcRegion[CONT_BOTTOM].top = rc.top + rc.bottom - _dockData.rcRegion[CONT_BOTTOM].bottom; _dockData.rcRegion[CONT_BOTTOM].right = rc.right-rc.left; // create temporary rect for bottom container RECT rcBottom = _dockData.rcRegion[CONT_BOTTOM]; _vSplitter[CONT_BOTTOM]->display(false); if (_vContainer[CONT_BOTTOM]->isVisible()) { _rcWork.bottom -= _dockData.rcRegion[CONT_BOTTOM].bottom + SPLITTER_WIDTH; // correct the visibility of bottom container when height is NULL if (_rcWork.bottom < rc.top) { rcBottom.top = _rcWork.top + rc.top + SPLITTER_WIDTH; rcBottom.bottom += _rcWork.bottom - rc.top; _rcWork.bottom = rc.top; } if ((rcBottom.bottom + SPLITTER_WIDTH) < 0) { _rcWork.bottom = rc.bottom - _dockData.rcRegion[CONT_TOP].bottom; } // set size of splitter RECT rc = {rcBottom.left, rcBottom.top - SPLITTER_WIDTH, rcBottom.right, SPLITTER_WIDTH}; _vSplitter[CONT_BOTTOM]->reSizeTo(rc); } // set left container _dockData.rcRegion[CONT_LEFT].left = rc.left; _dockData.rcRegion[CONT_LEFT].top = _rcWork.top; _dockData.rcRegion[CONT_LEFT].bottom = _rcWork.bottom; _vSplitter[CONT_LEFT]->display(false); if (_vContainer[CONT_LEFT]->isVisible()) { _rcWork.left += _dockData.rcRegion[CONT_LEFT].right + SPLITTER_WIDTH; _rcWork.right -= _dockData.rcRegion[CONT_LEFT].right + SPLITTER_WIDTH; // set size of splitter RECT rc = {_dockData.rcRegion[CONT_LEFT].right, _dockData.rcRegion[CONT_LEFT].top, SPLITTER_WIDTH, _dockData.rcRegion[CONT_LEFT].bottom}; _vSplitter[CONT_LEFT]->reSizeTo(rc); } // set right container _dockData.rcRegion[CONT_RIGHT].left = rc.right - _dockData.rcRegion[CONT_RIGHT].right; _dockData.rcRegion[CONT_RIGHT].top = _rcWork.top; _dockData.rcRegion[CONT_RIGHT].bottom = _rcWork.bottom; // create temporary rect for right container RECT rcRight = _dockData.rcRegion[CONT_RIGHT]; _vSplitter[CONT_RIGHT]->display(false); if (_vContainer[CONT_RIGHT]->isVisible()) { _rcWork.right -= _dockData.rcRegion[CONT_RIGHT].right + SPLITTER_WIDTH; // correct the visibility of right container when width is NULL if (_rcWork.right < 15) { rcRight.left = _rcWork.left + 15 + SPLITTER_WIDTH; rcRight.right += _rcWork.right - 15; _rcWork.right = 15; } // set size of splitter RECT rc = {rcRight.left - SPLITTER_WIDTH, rcRight.top, SPLITTER_WIDTH, rcRight.bottom}; _vSplitter[CONT_RIGHT]->reSizeTo(rc); } // set window positions of container if (_vContainer[CONT_BOTTOM]->isVisible()) { ::SetWindowPos(_vContainer[CONT_BOTTOM]->getHSelf(), NULL, rcBottom.left , rcBottom.top , rcBottom.right , rcBottom.bottom, SWP_NOZORDER); _vSplitter[CONT_BOTTOM]->display(); } if (_vContainer[CONT_TOP]->isVisible()) { ::SetWindowPos(_vContainer[CONT_TOP]->getHSelf(), NULL, _dockData.rcRegion[CONT_TOP].left , _dockData.rcRegion[CONT_TOP].top , _dockData.rcRegion[CONT_TOP].right , _dockData.rcRegion[CONT_TOP].bottom, SWP_NOZORDER); _vSplitter[CONT_TOP]->display(); } if (_vContainer[CONT_RIGHT]->isVisible()) { ::SetWindowPos(_vContainer[CONT_RIGHT]->getHSelf(), NULL, rcRight.left , rcRight.top , rcRight.right , rcRight.bottom, SWP_NOZORDER); _vSplitter[CONT_RIGHT]->display(); } if (_vContainer[CONT_LEFT]->isVisible()) { ::SetWindowPos(_vContainer[CONT_LEFT]->getHSelf(), NULL, _dockData.rcRegion[CONT_LEFT].left , _dockData.rcRegion[CONT_LEFT].top , _dockData.rcRegion[CONT_LEFT].right , _dockData.rcRegion[CONT_LEFT].bottom, SWP_NOZORDER); _vSplitter[CONT_LEFT]->display(); } (*_ppMainWindow)->reSizeTo(_rcWork); } void DockingManager::createDockableDlg(tTbData data, int iCont, bool isVisible) { // add icons if ((data.uMask & DWS_ICONTAB) && data.hIconTab != NULL) { // create image list if not exist if (_hImageList == NULL) { int iconDpiDynamicalSize = NppParameters::getInstance()->_dpiManager.scaleY(14); _hImageList = ::ImageList_Create(iconDpiDynamicalSize,iconDpiDynamicalSize,ILC_COLOR8, 0, 0); } // add icon ::ImageList_AddIcon(_hImageList, data.hIconTab); // do the reference here to find later the correct position _vImageList.push_back(data.hClient); } // create additional containers if necessary RECT rc = {0,0,0,0}; DockingCont* pCont = NULL; // if floated rect not set if (memcmp(&data.rcFloat, &rc, sizeof(RECT)) == 0) { // set default rect state ::GetWindowRect(data.hClient, &data.rcFloat); // test if dialog is first time created if (iCont == -1) { // set default visible state isVisible = (::IsWindowVisible(data.hClient) == TRUE); if (data.uMask & DWS_DF_FLOATING) { // create new container pCont = new DockingCont; _vContainer.push_back(pCont); // initialize pCont->init(_hInst, _hSelf); pCont->doDialog(isVisible, true); // get previous position and set container id data.iPrevCont = (data.uMask & 0x30000000) >> 28; iCont = _vContainer.size()-1; } else { // set position iCont = (data.uMask & 0x30000000) >> 28; // previous container is not selected data.iPrevCont = -1; } } } // if one of the container was not created before else if ((iCont >= DOCKCONT_MAX) || (data.iPrevCont >= DOCKCONT_MAX)) { // test if current container is in floating state if (iCont >= DOCKCONT_MAX) { // no mapping for available store mapping if (_iContMap[iCont] == -1) { // create new container pCont = new DockingCont; _vContainer.push_back(pCont); // initialize and map container id pCont->init(_hInst, _hSelf); pCont->doDialog(isVisible, true); _iContMap[iCont] = _vContainer.size()-1; } // get current container from map iCont = _iContMap[iCont]; } // previous container is in floating state else { // no mapping for available store mapping if (_iContMap[data.iPrevCont] == -1) { // create new container pCont = new DockingCont; _vContainer.push_back(pCont); // initialize and map container id pCont->init(_hInst, _hSelf); pCont->doDialog(false, true); pCont->reSizeToWH(data.rcFloat); _iContMap[data.iPrevCont] = _vContainer.size()-1; } data.iPrevCont = _iContMap[data.iPrevCont]; } } // attach toolbar if (_vContainer.size() > (size_t)iCont && _vContainer[iCont] != NULL) _vContainer[iCont]->createToolbar(data); // notify client app if (iCont < DOCKCONT_MAX) SendNotify(data.hClient, MAKELONG(DMN_DOCK, iCont)); else SendNotify(data.hClient, MAKELONG(DMN_FLOAT, iCont)); } void DockingManager::setActiveTab(int iCont, int iItem) { if ((iCont == -1) || (_iContMap[iCont] == -1)) return; _vContainer[_iContMap[iCont]]->setActiveTb(iItem); } void DockingManager::showDockableDlg(HWND hDlg, BOOL view) { tTbData *pTbData = NULL; for (size_t i = 0, len = _vContainer.size(); i < len; ++i) { pTbData = _vContainer[i]->findToolbarByWnd(hDlg); if (pTbData != NULL) { _vContainer[i]->showToolbar(pTbData, view); return; } } } void DockingManager::showDockableDlg(TCHAR* pszName, BOOL view) { tTbData *pTbData = NULL; for (size_t i = 0, len = _vContainer.size(); i < len; ++i) { pTbData = _vContainer[i]->findToolbarByName(pszName); if (pTbData != NULL) { _vContainer[i]->showToolbar(pTbData, view); return; } } } LRESULT DockingManager::SendNotify(HWND hWnd, UINT message) { NMHDR nmhdr; nmhdr.code = message; nmhdr.hwndFrom = _hParent; nmhdr.idFrom = ::GetDlgCtrlID(_hParent); ::SendMessage(hWnd, WM_NOTIFY, nmhdr.idFrom, (LPARAM)&nmhdr); return ::GetWindowLongPtr(hWnd, DWL_MSGRESULT); } void DockingManager::setDockedContSize(int iCont, int iSize) { if ((iCont == CONT_TOP) || (iCont == CONT_BOTTOM)) _dockData.rcRegion[iCont].bottom = iSize; else if ((iCont == CONT_LEFT) || (iCont == CONT_RIGHT)) _dockData.rcRegion[iCont].right = iSize; else return; onSize(); } int DockingManager::getDockedContSize(int iCont) { if ((iCont == CONT_TOP) || (iCont == CONT_BOTTOM)) return _dockData.rcRegion[iCont].bottom; else if ((iCont == CONT_LEFT) || (iCont == CONT_RIGHT)) return _dockData.rcRegion[iCont].right; else return -1; } DockingCont* DockingManager::toggleActiveTb(DockingCont* pContSrc, UINT message, BOOL bNew, LPRECT prcFloat) { tTbData TbData = *pContSrc->getDataOfActiveTb(); int iContSrc = GetContainer(pContSrc); int iContPrev = TbData.iPrevCont; BOOL isCont = ContExists(iContPrev); DockingCont* pContTgt = NULL; // if new float position is given if (prcFloat != NULL) { TbData.rcFloat = *prcFloat; } if ((isCont == FALSE) || (bNew == TRUE)) { // find an empty container int iContNew = FindEmptyContainer(); if (iContNew == -1) { // if no free container is available create a new one pContTgt = new DockingCont; pContTgt->init(_hInst, _hSelf); pContTgt->doDialog(true, true); // change only on toggling if ((bNew == FALSE) || (!pContSrc->isFloating())) TbData.iPrevCont = iContSrc; pContTgt->createToolbar(TbData); _vContainer.push_back(pContTgt); } else { // set new target pContTgt = _vContainer[iContNew]; // change only on toggling if ((pContSrc->isFloating()) != (pContTgt->isFloating())) TbData.iPrevCont = iContSrc; pContTgt->createToolbar(TbData); } } else { // set new target pContTgt = _vContainer[iContPrev]; // change data normaly TbData.iPrevCont = iContSrc; pContTgt->createToolbar(TbData); } // notify client app SendNotify(TbData.hClient, MAKELONG(message==DMM_DOCK?DMN_DOCK:DMN_FLOAT, GetContainer(pContTgt))); // remove toolbar from source _vContainer[iContSrc]->removeToolbar(TbData); return pContTgt; } DockingCont* DockingManager::toggleVisTb(DockingCont* pContSrc, UINT message, LPRECT prcFloat) { vector<tTbData*> vTbData = pContSrc->getDataOfVisTb(); tTbData* pTbData = pContSrc->getDataOfActiveTb(); int iContSrc = GetContainer(pContSrc); int iContPrev = pTbData->iPrevCont; BOOL isCont = ContExists(iContPrev); DockingCont* pContTgt = NULL; // at first hide container and resize pContSrc->doDialog(false); onSize(); for (size_t iTb = 0, len = vTbData.size(); iTb < len; ++iTb) { // get data one by another tTbData TbData = *vTbData[iTb]; // if new float position is given if (prcFloat != NULL) { TbData.rcFloat = *prcFloat; } if (isCont == FALSE) { // create new container pContTgt = new DockingCont; pContTgt->init(_hInst, _hSelf); pContTgt->doDialog(true, true); TbData.iPrevCont = iContSrc; pContTgt->createToolbar(TbData); _vContainer.push_back(pContTgt); // now container exists isCont = TRUE; iContPrev = GetContainer(pContTgt); } else { // set new target pContTgt = _vContainer[iContPrev]; TbData.iPrevCont = iContSrc; pContTgt->createToolbar(TbData); } SendNotify(TbData.hClient, MAKELONG(message==DMM_DOCK?DMN_DOCK:DMN_FLOAT, GetContainer(pContTgt))); // remove toolbar from anywhere _vContainer[iContSrc]->removeToolbar(TbData); } _vContainer[iContPrev]->setActiveTb(pTbData); return pContTgt; } void DockingManager::toggleActiveTb(DockingCont* pContSrc, DockingCont* pContTgt) { tTbData TbData = *pContSrc->getDataOfActiveTb(); toggleTb(pContSrc, pContTgt, TbData); } void DockingManager::toggleVisTb(DockingCont* pContSrc, DockingCont* pContTgt) { vector<tTbData*> vTbData = pContSrc->getDataOfVisTb(); tTbData* pTbData = pContSrc->getDataOfActiveTb(); // at first hide container and resize pContSrc->doDialog(false); onSize(); for (size_t iTb = 0, len = vTbData.size(); iTb < len; ++iTb) { // get data one by another tTbData TbData = *vTbData[iTb]; toggleTb(pContSrc, pContTgt, TbData); } pContTgt->setActiveTb(pTbData); } void DockingManager::toggleTb(DockingCont* pContSrc, DockingCont* pContTgt, tTbData TbData) { int iContSrc = GetContainer(pContSrc); int iContTgt = GetContainer(pContTgt); // test if container state changes from docking to floating or vice versa if (((iContSrc < DOCKCONT_MAX) && (iContTgt >= DOCKCONT_MAX)) || ((iContSrc >= DOCKCONT_MAX) && (iContTgt < DOCKCONT_MAX))) { // change states TbData.iPrevCont = iContSrc; } // notify client app if (iContTgt < DOCKCONT_MAX) SendNotify(TbData.hClient, MAKELONG(DMN_DOCK, iContTgt)); else SendNotify(TbData.hClient, MAKELONG(DMN_FLOAT, iContTgt)); // create new toolbar pContTgt->createToolbar(TbData); // remove toolbar from source _vContainer[iContSrc]->removeToolbar(TbData); } BOOL DockingManager::ContExists(size_t iCont) { BOOL bRet = FALSE; if (iCont < _vContainer.size()) { bRet = TRUE; } return bRet; } int DockingManager::GetContainer(DockingCont* pCont) { int iRet = -1; for (size_t iCont = 0, len = _vContainer.size(); iCont < len; ++iCont) { if (_vContainer[iCont] == pCont) { iRet = iCont; break; } } return iRet; } int DockingManager::FindEmptyContainer() { int iRetCont = -1; BOOL* pPrevDockList = (BOOL*) new BOOL[_vContainer.size()+1]; BOOL* pArrayPos = &pPrevDockList[1]; // delete all entries for (size_t iCont = 0, len = _vContainer.size()+1; iCont < len; ++iCont) { pPrevDockList[iCont] = FALSE; } // search for used floated containers for (size_t iCont = 0; iCont < DOCKCONT_MAX; ++iCont) { vector<tTbData*> vTbData = _vContainer[iCont]->getDataOfAllTb(); for (size_t iTb = 0, len = vTbData.size(); iTb < len; ++iTb) { pArrayPos[vTbData[iTb]->iPrevCont] = TRUE; } } // find free container for (size_t iCont = DOCKCONT_MAX, len = _vContainer.size(); iCont < len; ++iCont) { if (pArrayPos[iCont] == FALSE) { // and test if container is hidden if (!_vContainer[iCont]->isVisible()) { iRetCont = iCont; break; } } } delete [] pPrevDockList; // search for empty arrays return iRetCont; }
gpl-2.0
Pursche/ElunaTrinityWotlk
src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp
7543
/* * Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "FleeingMovementGenerator.h" #include "Creature.h" #include "CreatureAI.h" #include "MovementDefines.h" #include "MoveSplineInit.h" #include "MoveSpline.h" #include "ObjectAccessor.h" #include "PathGenerator.h" #include "Player.h" #include "Unit.h" #define MIN_QUIET_DISTANCE 28.0f #define MAX_QUIET_DISTANCE 43.0f template<class T> FleeingMovementGenerator<T>::~FleeingMovementGenerator() { } template<class T> MovementGeneratorType FleeingMovementGenerator<T>::GetMovementGeneratorType() const { return FLEEING_MOTION_TYPE; } template<class T> void FleeingMovementGenerator<T>::DoInitialize(T* owner) { if (!owner) return; owner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); owner->AddUnitState(UNIT_STATE_FLEEING); SetTargetLocation(owner); _path = nullptr; } template<class T> void FleeingMovementGenerator<T>::DoFinalize(T *) { } template<> void FleeingMovementGenerator<Player>::DoFinalize(Player* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); owner->ClearUnitState(UNIT_STATE_FLEEING); owner->StopMoving(); } template<> void FleeingMovementGenerator<Creature>::DoFinalize(Creature* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); owner->ClearUnitState(UNIT_STATE_FLEEING | UNIT_STATE_FLEEING_MOVE); if (owner->GetVictim()) owner->SetTarget(owner->EnsureVictim()->GetGUID()); } template<class T> void FleeingMovementGenerator<T>::DoReset(T* owner) { DoInitialize(owner); } template<class T> bool FleeingMovementGenerator<T>::DoUpdate(T* owner, uint32 diff) { if (!owner || !owner->IsAlive()) return false; if (owner->HasUnitState(UNIT_STATE_NOT_MOVE) || owner->IsMovementPreventedByCasting()) { _interrupt = true; owner->StopMoving(); _path = nullptr; return true; } else _interrupt = false; _timer.Update(diff); if (!_interrupt && _timer.Passed() && owner->movespline->Finalized()) SetTargetLocation(owner); return true; } template<class T> void FleeingMovementGenerator<T>::SetTargetLocation(T* owner) { if (!owner) return; if (owner->HasUnitState(UNIT_STATE_NOT_MOVE) || owner->IsMovementPreventedByCasting()) { _interrupt = true; owner->StopMoving(); _path = nullptr; return; } owner->AddUnitState(UNIT_STATE_FLEEING_MOVE); Position destination = owner->GetPosition(); GetPoint(owner, destination); // Add LOS check for target point if (!owner->IsWithinLOS(destination.GetPositionX(), destination.GetPositionY(), destination.GetPositionZ())) { _timer.Reset(200); return; } if (!_path) { _path = std::make_unique<PathGenerator>(owner); _path->SetPathLengthLimit(30.0f); } bool result = _path->CalculatePath(destination.GetPositionX(), destination.GetPositionY(), destination.GetPositionZ()); if (!result || (_path->GetPathType() & PATHFIND_NOPATH)) { _timer.Reset(100); return; } Movement::MoveSplineInit init(owner); init.MovebyPath(_path->GetPath()); init.SetWalk(false); int32 traveltime = init.Launch(); _timer.Reset(traveltime + urand(800, 1500)); } template<class T> void FleeingMovementGenerator<T>::GetPoint(T* owner, Position &position) { float casterDistance, casterAngle; if (Unit* fleeTarget = ObjectAccessor::GetUnit(*owner, _fleeTargetGUID)) { casterDistance = fleeTarget->GetDistance(owner); if (casterDistance > 0.2f) casterAngle = fleeTarget->GetAbsoluteAngle(owner); else casterAngle = frand(0.0f, 2.0f * float(M_PI)); } else { casterDistance = 0.0f; casterAngle = frand(0.0f, 2.0f * float(M_PI)); } float distance, angle; if (casterDistance < MIN_QUIET_DISTANCE) { distance = frand(0.4f, 1.3f) * (MIN_QUIET_DISTANCE - casterDistance); angle = casterAngle + frand(-float(M_PI) / 8.0f, float(M_PI) / 8.0f); } else if (casterDistance > MAX_QUIET_DISTANCE) { distance = frand(0.4f, 1.0f) * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE); angle = -casterAngle + frand(-float(M_PI) / 4.0f, float(M_PI) / 4.0f); } else // we are inside quiet range { distance = frand(0.6f, 1.2f) * (MAX_QUIET_DISTANCE - MIN_QUIET_DISTANCE); angle = frand(0.0f, 2.0f * float(M_PI)); } owner->MovePositionToFirstCollision(position, distance, angle); } template FleeingMovementGenerator<Player>::~FleeingMovementGenerator(); template FleeingMovementGenerator<Creature>::~FleeingMovementGenerator(); template MovementGeneratorType FleeingMovementGenerator<Player>::GetMovementGeneratorType() const; template MovementGeneratorType FleeingMovementGenerator<Creature>::GetMovementGeneratorType() const; template void FleeingMovementGenerator<Player>::DoInitialize(Player*); template void FleeingMovementGenerator<Creature>::DoInitialize(Creature*); template void FleeingMovementGenerator<Player>::DoReset(Player*); template void FleeingMovementGenerator<Creature>::DoReset(Creature*); template bool FleeingMovementGenerator<Player>::DoUpdate(Player*, uint32); template bool FleeingMovementGenerator<Creature>::DoUpdate(Creature*, uint32); template void FleeingMovementGenerator<Player>::SetTargetLocation(Player*); template void FleeingMovementGenerator<Creature>::SetTargetLocation(Creature*); template void FleeingMovementGenerator<Player>::GetPoint(Player*, Position &); template void FleeingMovementGenerator<Creature>::GetPoint(Creature*, Position &); //---- TimedFleeingMovementGenerator MovementGeneratorType TimedFleeingMovementGenerator::GetMovementGeneratorType() const { return TIMED_FLEEING_MOTION_TYPE; } bool TimedFleeingMovementGenerator::Update(Unit* owner, uint32 time_diff) { if (!owner->IsAlive()) return false; _totalFleeTime.Update(time_diff); if (_totalFleeTime.Passed()) return false; // This calls grant-parent Update method hiden by FleeingMovementGenerator::Update(Creature &, uint32) version // This is done instead of casting Unit& to Creature& and call parent method, then we can use Unit directly return MovementGeneratorMedium< Creature, FleeingMovementGenerator<Creature> >::Update(owner, time_diff); } void TimedFleeingMovementGenerator::Finalize(Unit* owner) { owner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_FLEEING); owner->ClearUnitState(UNIT_STATE_FLEEING); owner->StopMoving(); if (Unit* victim = owner->GetVictim()) { if (owner->IsAlive()) { owner->AttackStop(); owner->ToCreature()->AI()->AttackStart(victim); } } }
gpl-2.0
yucao100/SE_at_UML
G5_Cloud_Computing/Prototype/php/tmp/page.php
895
<?php /** * @File page.php * @Authors Jose Flores * jose.flores.152@gmail.com * * @Description This is the application template * * @changelog * 5/7/14 added obstart for redirect * 2/25/14 Created Template */ // to be able to redirect ob_start() ; echo '<html> <head>' ; include( $A[ 'D_HEAD' ].'index.php' ) ; echo '</head> <body> <div id="page"> <div class="header">'; $WGT[ 'CONFIG' ] = 'main-navigation.php' ; include( $A[ 'D_WGT' ].'navigation-menu/index.php' ) ; echo '</div> <div class="main">' ; include( $A[ 'CONTENT' ] ) ; echo '</div> <div class="footer">'; $footer = 1 ; //include( $A[ 'D_LIB' ].'footer-menu.php' ) ; echo '</div> </div> </body> </html>' ; ?>
gpl-2.0
sloanyang/raspberrry2v8
deps/v8/test/unittests/compiler/node-properties-unittest.cc
1118
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/common-operator.h" #include "src/compiler/node-properties.h" #include "test/unittests/test-utils.h" #include "testing/gmock/include/gmock/gmock.h" using testing::IsNull; namespace v8 { namespace internal { namespace compiler { typedef TestWithZone NodePropertiesTest; TEST_F(NodePropertiesTest, FindProjection) { CommonOperatorBuilder common(zone()); Node* start = Node::New(zone(), 0, common.Start(1), 0, nullptr, false); Node* proj0 = Node::New(zone(), 1, common.Projection(0), 1, &start, false); Node* proj1 = Node::New(zone(), 2, common.Projection(1), 1, &start, false); EXPECT_EQ(proj0, NodeProperties::FindProjection(start, 0)); EXPECT_EQ(proj1, NodeProperties::FindProjection(start, 1)); EXPECT_THAT(NodeProperties::FindProjection(start, 2), IsNull()); EXPECT_THAT(NodeProperties::FindProjection(start, 1234567890), IsNull()); } } // namespace compiler } // namespace internal } // namespace v8
gpl-2.0
wmacibnc/onyx
lista_pagina.php
1164
<?php include("adm/header.php"); include("config.php"); ?> <div id="conteudo_curso"> <?php $res = mysql_query("select * from paginas"); /*Executa o comando SQL, no caso para pegar todos os usuarios do sistema e retorna o valor da consulta em uma variavel ($res) */ /*Enquanto houver dados na tabela para serem mostrados será executado tudo que esta dentro do while */ echo "<h3>P&aacute;ginas Cadastradas</h3>"; echo "<table cellpadding='0' cellspacing='0' border='0' class='display' id='example' align='center'> <thead> <tr> <th>Cod.</th> <th>Nome P&aacute;gina</th> <th>Atualizar</th> </tr> </thead> <tbody>"; while($pagina=mysql_fetch_array($res)){ /*Escreve cada linha da tabela*/ echo " <tr align='center'> <td>".$pagina['id'] ."</td> <td>".$pagina['nomePagina'] ."</td> <td> <form method='post' action='../editar_pagina.php'> <input type='hidden' name='id' value='".$pagina['id']."'/> <input name='Atualizar' type='submit' value='Atualizar' /> </form> </td> </tr> "; } ?> </tbody> </table> <?php include("adm/footer.php"); ?>
gpl-2.0
ashenkar/sanga
wp-content/sumo.js
160
document.write("<scr"+"ipt src=\"//load.sumome.com/\" data-sumo-site-id=\"87e632966629f3a3f34bc8057eb5ba3efd1f5104500108167ac0692383edacfa\"></scr"+"ipt>");
gpl-2.0
leesocrates/Retrofit_Test_Server
src/main/java/com/lee/retrofit/RetrofitServer.java
2981
package com.lee.retrofit; import java.net.InetSocketAddress; import com.lee.retrofit.handler.*; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.codec.http.router.Handler; import io.netty.handler.codec.http.router.Router; public class RetrofitServer { private static final Router router = new Router().POST("/register", RegisterHandler.class) .POST("/login", LoginHandler.class).POST("addAccountRecord", AddAccountRecordHandler.class) .GET("accountRecordList", AccountRecordListHandler.class) .POST("/upload/image", UploadImageHandler.class).POST("/upload/file", UploadFileHandler.class) .GET("/getAccount", GetAccountInfoHandler.class) .GET("/getHtml/:path", GetHtmlHandler.class).GET("/getFile/:path", GetFileHandle.class) .GET("/getJson/:path", GetJsonHandler.class).GET("/getFileDir/:path", FileDownloadHandler.class) .GET("/getImage/:path", GetImageHandler.class).GET("getJs/:path", GetJsHandler.class) .POST("/submitevaluation", SubmitEvaluationHandler.class) .GET("/getverifycode", GetAccountInfoHandler.class).GET("/download/:path", AutoUpdateHandler.class) .GET("/static/file/download/:path", HttpStaticFileServerHandler.class); Handler handler = new Handler(router); public static void main(String[] args) throws Exception { int port = 8080; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { e.printStackTrace(); } } new RetrofitServer().run(port); } public void run(final int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_RCVBUF, 160 * 1024).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // ch.pipeline().addLast(new SocketHandler()); ch.pipeline().addLast(new HttpRequestDecoder()); ch.pipeline().addLast(new HttpResponseEncoder()); ch.pipeline().addLast(handler.name(), handler); } }); ChannelFuture future = b.bind(new InetSocketAddress(port)).sync(); System.out.println("retrofit server start at : " + "http://localhost:" + port); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
gpl-2.0
gxb5443/njba_website
wp-content/plugins/google-maps-widget/google-maps-widget.php
24348
<?php /* Plugin Name: Google Maps Widget Plugin URI: http://www.googlemapswidget.com/ Description: Display a single-image super-fast loading Google map in a widget. A larger, full featured map is available on click in a lightbox. Includes shortcode support and numerous options. Author: Web factory Ltd Version: 2.60 Author URI: http://www.webfactoryltd.com/ Text Domain: google-maps-widget Domain Path: lang Copyright 2012 - 2015 Web factory Ltd (email : gmw@webfactoryltd.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if (!defined('ABSPATH')) { die(); } define('GMW_OPTIONS', 'gmw_options'); define('GMW_CRON', 'gmw_cron'); require_once 'gmw-widget.php'; require_once 'gmw-tracking.php'; class GMW { static $version = 2.60; // hook everything up static function init() { GMW_tracking::init(); if (is_admin()) { // check if minimal required WP version is used self::check_wp_version(3.3); // check some variables self::upgrade(); // aditional links in plugin description add_filter('plugin_action_links_' . basename(dirname(__FILE__)) . '/' . basename(__FILE__), array(__CLASS__, 'plugin_action_links')); add_filter('plugin_row_meta', array(__CLASS__, 'plugin_meta_links'), 10, 2); // enqueue admin scripts add_action('admin_enqueue_scripts', array(__CLASS__, 'admin_enqueue_scripts')); add_action('customize_controls_enqueue_scripts', array(__CLASS__, 'admin_enqueue_scripts')); // JS dialog markup add_action('admin_footer', array(__CLASS__, 'admin_dialogs_markup')); // register AJAX endpoints add_action('wp_ajax_gmw_subscribe', array(__CLASS__, 'email_subscribe')); add_action('wp_ajax_gmw_activate', array(__CLASS__, 'activate_via_code')); // handle dismiss button for all notices add_action('admin_action_gmw_dismiss_notice', array(__CLASS__, 'dismiss_notice')); // display various notices self::add_notices(); } else { // enqueue frontend scripts add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_scripts')); add_action('wp_footer', array(__CLASS__, 'dialogs_markup')); } // add shortcode support self::add_shortcode(); } // init // some things have to be loaded earlier static function plugins_loaded() { load_plugin_textdomain('google-maps-widget', false, basename(dirname(__FILE__)) . '/lang'); add_filter('cron_schedules', array('GMW_tracking', 'register_cron_intervals')); } // plugins_loaded // initialize widgets static function widgets_init() { register_widget('GoogleMapsWidget'); } // widgets_init // add widgets link to plugins page static function plugin_action_links($links) { $settings_link = '<a href="' . admin_url('widgets.php') . '" title="' . __('Configure Google Maps Widget', 'google-maps-widget') . '">' . __('Widgets', 'google-maps-widget') . '</a>'; array_unshift($links, $settings_link); return $links; } // plugin_action_links // add links to plugin's description in plugins table static function plugin_meta_links($links, $file) { $documentation_link = '<a target="_blank" href="http://www.googlemapswidget.com/documentation/" title="' . __('View Google Maps Widget documentation', 'google-maps-widget') . '">'. __('Documentation', 'google-maps-widget') . '</a>'; $support_link = '<a target="_blank" href="http://wordpress.org/support/plugin/google-maps-widget" title="' . __('Problems? We are here to help!', 'google-maps-widget') . '">' . __('Support', 'google-maps-widget') . '</a>'; $review_link = '<a target="_blank" href="http://wordpress.org/support/view/plugin-reviews/google-maps-widget" title="' . __('If you like it, please review the plugin', 'google-maps-widget') . '">' . __('Review the plugin', 'google-maps-widget') . '</a>'; $donate_link = '<a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?business=gordan@webfactoryltd.com&cmd=_xclick&currency_code=USD&amount=&item_name=Google%20Maps%20Widget%20Donation" title="' . __('If you feel we deserve it, buy us coffee', 'google-maps-widget') . '">' . __('Donate', 'google-maps-widget') . '</a>'; $activate_link = '<a href="' . esc_url(admin_url('widgets.php?gmw_open_promo_dialog')) . '">' . __('Activate premium features for <b>FREE</b>', 'google-maps-widget') . '</a>'; if ($file == plugin_basename(__FILE__)) { $links[] = $documentation_link; $links[] = $support_link; $links[] = $review_link; $links[] = $donate_link; if (!self::is_activated()) { $links[] = $activate_link; } } return $links; } // plugin_meta_links // check if user has the minimal WP version required by the plugin static function check_wp_version($min_version) { if (!version_compare(get_bloginfo('version'), $min_version, '>=')) { add_action('admin_notices', array(__CLASS__, 'notice_min_version_error')); } } // check_wp_version // display error message if WP version is too low static function notice_min_version_error() { echo '<div class="error"><p>' . sprintf(__('Google Maps Widget <b>requires WordPress version 3.3</b> or higher to function properly. You are using WordPress version %s. Please <a href="%s">update it</a>.', 'google-maps-widget'), get_bloginfo('version'), admin_url('update-core.php')) . '</p></div>'; } // notice_min_version_error // print dialogs markup in footer static function dialogs_markup() { $out = ''; $widgets = GoogleMapsWidget::$widgets; if (!$widgets) { wp_dequeue_script('gmw'); wp_dequeue_script('gmw-fancybox'); return; } foreach ($widgets as $widget) { if ($widget['bubble']) { $iwloc = 'addr'; } else { $iwloc = 'near'; } if ($widget['ll']) { $ll = '&amp;ll=' . $widget['ll']; } else { $ll = ''; } $lang = substr(@$_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); if (!$lang) { $lang = 'en'; } $map_url = '//maps.google.com/maps?hl=' . $lang . '&amp;ie=utf8&amp;output=embed&amp;iwloc=' . $iwloc . '&amp;iwd=1&amp;mrt=loc&amp;t=' . $widget['type'] . '&amp;q=' . urlencode(remove_accents($widget['address'])) . '&amp;z=' . urlencode($widget['zoom']) . $ll; $out .= '<div class="gmw-dialog" style="display: none;" data-map-height="' . $widget['height'] . '" data-map-width="' . $widget['width'] . '" data-map-skin="' . $widget['skin'] . '" data-map-iframe-url="' . $map_url . '" id="gmw-dialog-' . $widget['id'] . '" title="' . esc_attr($widget['title']) . '">'; if ($widget['header']) { $out .= '<div class="gmw-header">' . wpautop(do_shortcode($widget['header'])) . '</div>'; } $out .= '<div class="gmw-map"></div>'; if ($widget['footer']) { $out .= '<div class="gmw-footer">' . wpautop(do_shortcode($widget['footer'])) . '</div>'; } $out .= "</div>\n"; } // foreach $widgets echo $out; } // dialogs_markup // check availability and register shortcode static function add_shortcode() { global $shortcode_tags; if (isset($shortcode_tags['gmw'])) { add_action('admin_notices', array(__CLASS__, 'notice_sc_conflict_error')); } else { add_shortcode('gmw', array(__CLASS__, 'do_shortcode')); } } // add_shortcode // display notice if shortcode name is already taken static function notice_sc_conflict_error() { if (!self::is_activated()) { return; } echo '<div class="error"><p><strong>' . __('Google Maps Widget shortcode is not active!', 'google-maps-widget') . '</strong>' . __(' Shortcode <i>[gmw]</i> is already in use by another plugin or theme. Please deactivate that theme or plugin.', 'google-maps-widget') . '</p></div>'; } // notice_sc_conflict_error // handle dismiss button for all notices // todo - convert all notices static function dismiss_notice() { $options = get_option(GMW_OPTIONS, array()); if (isset($_GET['notice']) && $_GET['notice'] == 'upgrade') { $options['dismiss_notice_upgrade'] = true; update_option(GMW_OPTIONS, $options); } if (isset($_GET['notice']) && $_GET['notice'] == 'rate') { $options['dismiss_notice_rate'] = true; update_option(GMW_OPTIONS, $options); } if ($_GET['redirect']) { wp_redirect($_GET['redirect']); } else { wp_redirect(admin_url()); } exit; } // dismiss_notice // maybe show some notices static function add_notices() { $options = get_option(GMW_OPTIONS, array()); $notice = false; if ((!isset($options['dismiss_notice_upgrade']) || $options['dismiss_notice_upgrade'] == false) && !self::is_activated() && (GMW_tracking::count_active_widgets() > 0 || (current_time('timestamp') - $options['first_install']) > (DAY_IN_SECONDS * 3))) { add_action('admin_notices', array(__CLASS__, 'notice_activate_extra_features')); $notice = true; } // show upgrade notice if (!$notice && (!isset($options['dismiss_notice_rate']) || $options['dismiss_notice_rate'] == false) && GMW_tracking::count_active_widgets() > 0 && (current_time('timestamp') - $options['first_install']) > (DAY_IN_SECONDS * 20)) { add_action('admin_notices', array(__CLASS__, 'notice_rate_plugin')); } // show rate notice } // add_notices // display message to get extra features for GMW static function notice_activate_extra_features() { $activate_url = admin_url('widgets.php?gmw_open_promo_dialog'); $dismiss_url = add_query_arg(array('action' => 'gmw_dismiss_notice', 'notice' => 'upgrade', 'redirect' => urlencode($_SERVER['REQUEST_URI'])), admin_url('admin.php')); // todo detect WP version and add support for "is-dismissible" // todo remove style from HTML echo '<div id="gmw_activate_notice" class="updated notice"><p>' . __('<b>Google Maps Widget</b> has extra premium features you can get for <b style="color: #d54e21;">FREE</b>. This is a limited time offer so act now!', 'google-maps-widget'); echo '<br /><a href="' . esc_url($activate_url) . '" style="vertical-align: baseline; margin-top: 15px;" class="button-primary">' . __('Activate premium features for <b>FREE</b>', 'google-maps-widget') . '</a>'; echo '&nbsp;&nbsp;<a href="' . esc_url($dismiss_url) . '" class="">' . __('Dismiss notice', 'google-maps-widget') . '</a>'; echo '</p></div>'; } // notice_activate_extra_features // display message to get extra features for GMW static function notice_rate_plugin() { $rate_url = 'https://wordpress.org/support/view/plugin-reviews/google-maps-widget?rate=5#postform'; $dismiss_url = add_query_arg(array('action' => 'gmw_dismiss_notice', 'notice' => 'rate', 'redirect' => urlencode($_SERVER['REQUEST_URI'])), admin_url('admin.php')); // todo detect WP version and add support for "is-dismissible" // todo remove style from HTML echo '<div id="gmw_rate_notice" class="updated notice"><p>' . __('Hi! We saw you\'ve been using <b>Google Maps Widget</b> for some time and wanted to ask for your help to make the plugin even better.<br>We don\'t need money :), just a minute of your time to rate the plugin. Thank you!', 'google-maps-widget'); echo '<br /><a target="_blank" href="' . esc_url($rate_url) . '" style="vertical-align: baseline; margin-top: 15px;" class="button-primary">' . __('Help us out &amp; rate the plugin', 'google-maps-widget') . '</a>'; echo '&nbsp;&nbsp;<a href="' . esc_url($dismiss_url) . '" class="">' . __('Dismiss notice', 'google-maps-widget') . '</a>'; echo '</p></div>'; } // notice_rate_plugin // enqueue frontend scripts if necessary static function enqueue_scripts() { if (is_active_widget(false, false, 'googlemapswidget', true)) { wp_enqueue_style('gmw', plugins_url('/css/gmw.css', __FILE__), array(), GMW::$version); wp_enqueue_script('gmw-colorbox', plugins_url('/js/jquery.colorbox.min.js', __FILE__), array('jquery'), GMW::$version, true); wp_enqueue_script('gmw', plugins_url('/js/gmw.js', __FILE__), array('jquery'), GMW::$version, true); } } // enqueue_scripts // enqueue CSS and JS scripts on widgets page static function admin_enqueue_scripts() { global $wp_customize; if (self::is_plugin_admin_page() || isset($wp_customize)) { wp_enqueue_script('jquery-ui-tabs'); wp_enqueue_script('jquery-ui-dialog'); wp_enqueue_script('gmw-cookie', plugins_url('js/jquery.cookie.js', __FILE__), array('jquery'), GMW::$version, true); wp_enqueue_script('gmw-admin', plugins_url('js/gmw-admin.js', __FILE__), array('jquery'), GMW::$version, true); wp_enqueue_style('wp-jquery-ui-dialog'); wp_enqueue_style('gmw-admin', plugins_url('css/gmw-admin.css', __FILE__), array(), GMW::$version); $js_localize = array('subscribe_ok' => __('Check your inbox. Email with activation code is on its way.', 'google-maps-widget'), 'subscribe_duplicate' => __('You are already subscribed to our list. One activation code is valid for all sites so just use the code you already have.', 'google-maps-widget'), 'subscribe_error' => __('Something is not right on our end. Sorry :( Try again later.', 'google-maps-widget'), 'activate_ok' => __('Superb! Extra features are active ;)', 'google-maps-widget'), 'dialog_title' => __('GOOGLE MAPS WIDGET - Activate Extra Features', 'google-maps-widget'), 'undocumented_error' => __('An undocumented error has occured. Please refresh the page and try again.', 'google-maps-widget'), 'id_base' => 'googlemapswidget'); wp_localize_script('gmw-admin', 'gmw', $js_localize); } // if } // admin_enqueue_scripts // check if plugin's admin page is shown static function is_plugin_admin_page() { $current_screen = get_current_screen(); if ($current_screen->id == 'widgets') { return true; } else { return false; } } // is_plugin_admin_page // check if activate-by-subscribing features have been activated static function is_activated() { $options = get_option(GMW_OPTIONS); if (isset($options['activated']) && $options['activated'] === true) { return true; } else { return false; } } // is_activated // echo markup for promo dialog; only on widgets page static function admin_dialogs_markup() { if (!self::is_plugin_admin_page()) { return false; } $current_user = wp_get_current_user(); if (empty($current_user->user_firstname)) { $name = $current_user->display_name; } else { $name = $current_user->user_firstname; } $out = '<div id="gmw_promo_dialog">'; $out .= '<div id="gmw_dialog_subscribe"><div class="content"><h3 class="center">' . __('Fill out the form and<br>get extra features &amp; options <b>for FREE</b> instantly!', 'google-maps-widget') . '</h3>'; $out .= '<p class="input_row"><input value="' . $name . '" type="text" id="gmw_name" name="gmw_name" placeholder="Your name"><span class="error name" style="display: none;">Please enter your name.</span></p>'; $out .= '<p class="input_row"><input value="' . $current_user->user_email . '" type="text" name="gmw_email" id="gmw_email" placeholder="Your email address"><span style="display: none;" class="error email">Please double check your email address.</span></p>'; $out .= '<p class="center"><a id="gmw_subscribe" href="#" class="button button-primary big-button">Activate extra features</a><br><a href="#" class="" id="gmw_already_subscribed">I already have an activation code</a></p></div>'; $out .= '<div class="footer"><p><b>Why subscribe?</b></p><ul><li>We\'ll never share your email address</li><li>We won\'t spam you or overwhelm with emails</li><li>Be the first to get notified about new features</li><li>You\'ll get all future upgrades for free as well</li><li>You\'ll get discounts for our premium WP plugins</li></ul></div>'; $out .= '</div>'; // dialog subscribe $out .= '<div id="gmw_dialog_activate"><div class="content"><h3 class="center">' . __('Enter your code and activate extra features', 'google-maps-widget') . '</h3>'; $out .= '<p class="input_row"><input type="text" id="gmw_code" name="gmw_code" placeholder="Your activation code"><span style="display: none;" class="error gmw_code">Please double check the activation code.</span></p><p class="center"><a href="#" class="button button-primary big-button" id="gmw_activate">Activate extra features</a></p></div>'; $out .= '<div class="footer"><p><b>FAQ</b></p><ul><li>Already subscribed? Enter your activation code above.</li><li>Didn\'t receive the email? Check your SPAM folder.</li><li>Still not getting the email? Try a different email address.</li><li>Code is valid for an unlimited number of plugin installations.</li></ul></div>'; $out .= '</div>'; // activate screen $out .= '</div>'; // dialog echo $out; } // admin_dialogs_markup // send user's email to MailChimp via our server static function email_subscribe() { $name = trim($_POST['name']); $email = trim($_POST['email']); if (defined('WPLANG')) { $lang = strtolower(substr(WPLANG, 0, 2)); } else { $lang = 'en'; } $res = wp_remote_post('http://www.googlemapswidget.com/subscribe.php', array('body' => array('name' => $name, 'email' => $email, 'lang' => $lang, 'ip' => $_SERVER['REMOTE_ADDR'], 'site' => get_home_url()))); // something's wrong with our server if ($res['response']['code'] != 200 || is_wp_error($res)) { wp_send_json_error('unknown'); } if ($res['body'] == 'ok') { wp_send_json_success(); } elseif ($res['body'] == 'duplicate') { wp_send_json_error('duplicate'); } else { wp_send_json_error('unknown'); } } // email_subscribe // check activation code and save if valid static function activate_via_code() { $code = trim($_POST['code']); if (self::validate_activation_code($code)) { $options = get_option(GMW_OPTIONS); $options['activation_code'] = $code; $options['activated'] = true; update_option(GMW_OPTIONS, $options); wp_send_json_success(); } else { wp_send_json_error(); } } // email_activate // check if activation code for additional features is valid static function validate_activation_code($code) { if (strlen($code) == 6 && ($code[0] + $code[5]) == 9) { return true; } else { return false; } } // validate_activation_code // helper function for creating dropdowns static function create_select_options($options, $selected = null, $output = true) { $out = "\n"; foreach ($options as $tmp) { if ($selected == $tmp['val']) { $out .= "<option selected=\"selected\" value=\"{$tmp['val']}\">{$tmp['label']}&nbsp;</option>\n"; } else { $out .= "<option value=\"{$tmp['val']}\">{$tmp['label']}&nbsp;</option>\n"; } } // foreach if ($output) { echo $out; } else { return $out; } } // create_select_options // fetch coordinates based on the address static function get_coordinates($address, $force_refresh = false) { $address_hash = md5('gmw' . $address); if ($force_refresh || ($coordinates = get_transient($address_hash)) === false) { $url = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' . urlencode($address) . '&sensor=false'; $result = wp_remote_get($url); if (!is_wp_error($result) && $result['response']['code'] == 200) { $data = new SimpleXMLElement($result['body']); if ($data->status == 'OK') { $cache_value['lat'] = (string) $data->result->geometry->location->lat; $cache_value['lng'] = (string) $data->result->geometry->location->lng; $cache_value['address'] = (string) $data->result->formatted_address; // cache coordinates for 3 months set_transient($address_hash, $cache_value, 3600*24*30*3); $data = $cache_value; } elseif (!$data->status) { return false; } else { return false; } } else { return false; } } else { // data is cached, get it $data = get_transient($address_hash); } return $data; } // get_coordinates // shortcode support for any GMW instance static function do_shortcode($atts, $content = null) { if (!self::is_activated()) { return; } global $wp_widget_factory; $atts = shortcode_atts(array('id' => 0), $atts); $id = (int) $atts['id']; $widgets = get_option('widget_googlemapswidget'); if (!$id || !isset($widgets[$id]) || empty($widgets[$id])) { echo '<span class="gmw-error">Google Maps Widget shortcode error - please double-check the widget ID.</span>'; } else { $widget_args = $widgets[$id]; $widget_instance['widget_id'] = 'googlemapswidget-' . $id; $widget_instance['widget_name'] = 'Google Maps Widget'; echo '<span class="gmw-shortcode-widget">'; the_widget('GoogleMapsWidget', $widget_args, $widget_instance); echo '</span>'; } } // do_shortcode // activate doesn't get fired on upgrades so we have to compensate public static function upgrade() { $options = get_option(GMW_OPTIONS); if (!isset($options['first_version']) || !isset($options['first_install'])) { $options['first_version'] = GMW::$version; $options['first_install'] = current_time('timestamp'); update_option(GMW_OPTIONS, $options); } } // upgrade // write down a few things on plugin activation // NO DATA is sent anywhere unless user explicitly agrees to it! static function activate() { $options = get_option(GMW_OPTIONS); if (!isset($options['first_version']) || !isset($options['first_install'])) { $options['first_version'] = GMW::$version; $options['first_install'] = current_time('timestamp'); $options['last_tracking'] = false; update_option(GMW_OPTIONS, $options); } } // activate // clean up on deactivation static function deactivate() { $options = get_option(GMW_OPTIONS); if (isset($options['allow_tracking']) && $options['allow_tracking'] === true) { GMW_tracking::clear_cron(); } } // deactivate // clean up on uninstall / delete static function uninstall() { if (!defined('WP_UNINSTALL_PLUGIN')) { return; } delete_option(GMW_OPTIONS); } // uninstall } // class GMW // hook everything up register_activation_hook(__FILE__, array('GMW', 'activate')); register_deactivation_hook(__FILE__, array('GMW', 'deactivate')); register_uninstall_hook(__FILE__, array('GMW', 'uninstall')); add_action('init', array('GMW', 'init')); add_action('plugins_loaded', array('GMW', 'plugins_loaded')); add_action('widgets_init', array('GMW', 'widgets_init'));
gpl-2.0
delafer/j7project
jasper352/csb-jasperreport-dep/src/net/sf/jasperreports/engine/fill/JRByteIncrementerFactory.java
11205
/* * ============================================================================ * GNU Lesser General Public License * ============================================================================ * * JasperReports - Free Java report-generating library. * Copyright (C) 2001-2009 JasperSoft Corporation http://www.jaspersoft.com * * 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 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. * * JasperSoft Corporation * 539 Bryant Street, Suite 100 * San Francisco, CA 94107 * http://www.jaspersoft.com */ package net.sf.jasperreports.engine.fill; import net.sf.jasperreports.engine.JRVariable; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: JRByteIncrementerFactory.java 2696 2009-03-24 18:35:01Z teodord $ */ public class JRByteIncrementerFactory extends JRAbstractExtendedIncrementerFactory { /** * */ protected static final Byte ZERO = new Byte((byte)0); /** * */ private static JRByteIncrementerFactory mainInstance = new JRByteIncrementerFactory(); /** * */ private JRByteIncrementerFactory() { } /** * */ public static JRByteIncrementerFactory getInstance() { return mainInstance; } /** * */ public JRExtendedIncrementer getExtendedIncrementer(byte calculation) { JRExtendedIncrementer incrementer = null; switch (calculation) { case JRVariable.CALCULATION_COUNT : { incrementer = JRByteCountIncrementer.getInstance(); break; } case JRVariable.CALCULATION_SUM : { incrementer = JRByteSumIncrementer.getInstance(); break; } case JRVariable.CALCULATION_AVERAGE : { incrementer = JRByteAverageIncrementer.getInstance(); break; } case JRVariable.CALCULATION_LOWEST : case JRVariable.CALCULATION_HIGHEST : { incrementer = JRComparableIncrementerFactory.getInstance().getExtendedIncrementer(calculation); break; } case JRVariable.CALCULATION_STANDARD_DEVIATION : { incrementer = JRByteStandardDeviationIncrementer.getInstance(); break; } case JRVariable.CALCULATION_VARIANCE : { incrementer = JRByteVarianceIncrementer.getInstance(); break; } case JRVariable.CALCULATION_DISTINCT_COUNT : { incrementer = JRByteDistinctCountIncrementer.getInstance(); break; } case JRVariable.CALCULATION_SYSTEM : case JRVariable.CALCULATION_NOTHING : case JRVariable.CALCULATION_FIRST : default : { incrementer = JRDefaultIncrementerFactory.getInstance().getExtendedIncrementer(calculation); break; } } return incrementer; } } /** * */ class JRByteCountIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteCountIncrementer mainInstance = new JRByteCountIncrementer(); /** * */ private JRByteCountIncrementer() { } /** * */ public static JRByteCountIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { Number value = (Number)variable.getIncrementedValue(); if (value == null || variable.isInitialized()) { value = JRByteIncrementerFactory.ZERO; } if (expressionValue == null) { return value; } return new Byte((byte)(value.byteValue() + 1)); } public Object combine(JRCalculable calculable, JRCalculable calculableValue, AbstractValueProvider valueProvider) { Number value = (Number)calculable.getIncrementedValue(); Number combineValue = (Number) calculableValue.getValue(); if (value == null || calculable.isInitialized()) { value = JRByteIncrementerFactory.ZERO; } if (combineValue == null) { return value; } return new Byte((byte) (value.byteValue() + combineValue.byteValue())); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } } /** * */ class JRByteDistinctCountIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteDistinctCountIncrementer mainInstance = new JRByteDistinctCountIncrementer(); /** * */ private JRByteDistinctCountIncrementer() { } /** * */ public static JRByteDistinctCountIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { DistinctCountHolder holder = (DistinctCountHolder)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_COUNT)); if (variable.isInitialized()) { holder.init(); } return new Byte((byte)holder.getCount()); } public Object combine(JRCalculable calculable, JRCalculable calculableValue, AbstractValueProvider valueProvider) { DistinctCountHolder holder = (DistinctCountHolder)valueProvider.getValue(calculable.getHelperVariable(JRCalculable.HELPER_COUNT)); return new Byte((byte)holder.getCount()); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } } /** * */ class JRByteSumIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteSumIncrementer mainInstance = new JRByteSumIncrementer(); /** * */ private JRByteSumIncrementer() { } /** * */ public static JRByteSumIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { Number value = (Number)variable.getIncrementedValue(); Number newValue = (Number)expressionValue; if (newValue == null) { if (variable.isInitialized()) { return null; } return value; } if (value == null || variable.isInitialized()) { value = JRByteIncrementerFactory.ZERO; } return new Byte((byte)(value.byteValue() + newValue.byteValue())); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } } /** * */ class JRByteAverageIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteAverageIncrementer mainInstance = new JRByteAverageIncrementer(); /** * */ private JRByteAverageIncrementer() { } /** * */ public static JRByteAverageIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { if (expressionValue == null) { if (variable.isInitialized()) { return null; } return variable.getValue(); } Number countValue = (Number)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_COUNT)); Number sumValue = (Number)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_SUM)); return new Byte((byte)(sumValue.byteValue() / countValue.byteValue())); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } } /** * */ class JRByteStandardDeviationIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteStandardDeviationIncrementer mainInstance = new JRByteStandardDeviationIncrementer(); /** * */ private JRByteStandardDeviationIncrementer() { } /** * */ public static JRByteStandardDeviationIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { if (expressionValue == null) { if (variable.isInitialized()) { return null; } return variable.getValue(); } Number varianceValue = (Number)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_VARIANCE)); return new Byte( (byte)Math.sqrt(varianceValue.doubleValue()) ); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } } /** * */ class JRByteVarianceIncrementer extends JRAbstractExtendedIncrementer { /** * */ private static JRByteVarianceIncrementer mainInstance = new JRByteVarianceIncrementer(); /** * */ private JRByteVarianceIncrementer() { } /** * */ public static JRByteVarianceIncrementer getInstance() { return mainInstance; } /** * */ public Object increment( JRCalculable variable, Object expressionValue, AbstractValueProvider valueProvider ) { Number value = (Number)variable.getIncrementedValue(); Number newValue = (Number)expressionValue; if (newValue == null) { if (variable.isInitialized()) { return null; } return value; } else if (value == null || variable.isInitialized()) { return JRByteIncrementerFactory.ZERO; } else { Number countValue = (Number)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_COUNT)); Number sumValue = (Number)valueProvider.getValue(variable.getHelperVariable(JRCalculable.HELPER_SUM)); return new Byte((byte)( (countValue.byteValue() - 1) * value.byteValue() / countValue.byteValue() + ( sumValue.byteValue() / countValue.byteValue() - newValue.byteValue() ) * ( sumValue.byteValue() / countValue.byteValue() - newValue.byteValue() ) / (countValue.byteValue() - 1) )); } } public Object combine(JRCalculable calculable, JRCalculable calculableValue, AbstractValueProvider valueProvider) { Number value = (Number)calculable.getIncrementedValue(); if (calculableValue.getValue() == null) { if (calculable.isInitialized()) { return null; } return value; } else if (value == null || calculable.isInitialized()) { return new Byte(((Number) calculableValue.getIncrementedValue()).byteValue()); } float v1 = value.floatValue(); float c1 = ((Number) valueProvider.getValue(calculable.getHelperVariable(JRCalculable.HELPER_COUNT))).floatValue(); float s1 = ((Number) valueProvider.getValue(calculable.getHelperVariable(JRCalculable.HELPER_SUM))).floatValue(); float v2 = ((Number) calculableValue.getIncrementedValue()).floatValue(); float c2 = ((Number) valueProvider.getValue(calculableValue.getHelperVariable(JRCalculable.HELPER_COUNT))).floatValue(); float s2 = ((Number) valueProvider.getValue(calculableValue.getHelperVariable(JRCalculable.HELPER_SUM))).floatValue(); c1 -= c2; s1 -= s2; float c = c1 + c2; return new Byte((byte) ( c1 / c * v1 + c2 / c * v2 + c2 / c1 * s1 / c * s1 / c + c1 / c2 * s2 / c * s2 / c - 2 * s1 / c * s2 /c )); } public Object initialValue() { return JRByteIncrementerFactory.ZERO; } }
gpl-2.0
noobieteam/Fantasy-Mod
fallacia/init/Recipes.java
282
package com.noobieteam.fallacia.init; /** * Main Initializers for the mod's recipes * Registers them.. */ public class Recipes { // CREATE ALL RECIPES's INSCANCES IN HERE /** Call the game register in this method * */ public static void init() { } }
gpl-2.0
astridx/joomla-cms
administrator/components/com_contenthistory/Model/CompareModel.php
4984
<?php /** * @package Joomla.Administrator * @subpackage com_contenthistory * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\Component\Contenthistory\Administrator\Model; defined('_JEXEC') or die; use Joomla\CMS\Factory; use Joomla\CMS\HTML\HTMLHelper; use Joomla\CMS\Language\Text; use Joomla\CMS\MVC\Model\ListModel; use Joomla\CMS\Table\ContentHistory; use Joomla\CMS\Table\ContentType; use Joomla\CMS\Table\Table; use Joomla\Component\Contenthistory\Administrator\Helper\ContenthistoryHelper; /** * Methods supporting a list of contenthistory records. * * @since 3.2 */ class CompareModel extends ListModel { /** * Method to get a version history row. * * @return array|boolean On success, array of populated tables. False on failure. * * @since 3.2 */ public function getItems() { $input = Factory::getApplication()->input; /** @var ContentHistory $table1 */ $table1 = $this->getTable('ContentHistory'); /** @var ContentHistory $table2 */ $table2 = $this->getTable('ContentHistory'); $id1 = $input->getInt('id1'); $id2 = $input->getInt('id2'); $result = array(); if ($table1->load($id1) && $table2->load($id2)) { // Get the first history record's content type record so we can check ACL /** @var ContentType $contentTypeTable */ $contentTypeTable = $this->getTable('ContentType'); $ucmTypeId = $table1->ucm_type_id; if (!$contentTypeTable->load($ucmTypeId)) { // Assume a failure to load the content type means broken data, abort mission return false; } $user = Factory::getUser(); // Access check if ($user->authorise('core.edit', $contentTypeTable->type_alias . '.' . (int) $table1->ucm_item_id) || $this->canEdit($table1)) { $return = true; } else { $this->setError(Text::_('JERROR_ALERTNOAUTHOR')); return false; } // All's well, process the records if ($return == true) { $nullDate = $this->getDbo()->getNullDate(); foreach (array($table1, $table2) as $table) { $object = new \stdClass; $object->data = ContenthistoryHelper::prepareData($table); $object->version_note = $table->version_note; // Let's use custom calendars when present $object->save_date = HTMLHelper::_('date', $table->save_date, Text::_('DATE_FORMAT_LC6')); $dateProperties = array ( 'modified_time', 'created_time', 'modified', 'created', 'checked_out_time', 'publish_up', 'publish_down', ); foreach ($dateProperties as $dateProperty) { if (property_exists($object->data, $dateProperty) && $object->data->$dateProperty->value !== null && $object->data->$dateProperty->value !== $nullDate) { $object->data->$dateProperty->value = HTMLHelper::_( 'date', $object->data->$dateProperty->value, Text::_('DATE_FORMAT_LC6') ); } } $result[] = $object; } return $result; } } return false; } /** * Method to get a table object, load it if necessary. * * @param string $type The table name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * * @return Table A Table object * * @since 3.2 */ public function getTable($type = 'Contenthistory', $prefix = 'Joomla\\CMS\\Table\\', $config = array()) { return Table::getInstance($type, $prefix, $config); } /** * Method to test whether a record is editable * * @param ContentHistory $record A \JTable object. * * @return boolean True if allowed to edit the record. Defaults to the permission set in the component. * * @since 3.6 */ protected function canEdit($record) { $result = false; if (!empty($record->ucm_type_id)) { // Check that the type id matches the type alias $typeAlias = Factory::getApplication()->input->get('type_alias'); /** @var ContentType $contentTypeTable */ $contentTypeTable = $this->getTable('ContentType'); if ($contentTypeTable->getTypeId($typeAlias) == $record->ucm_type_id) { /** * Make sure user has edit privileges for this content item. Note that we use edit permissions * for the content item, not delete permissions for the content history row. */ $user = Factory::getUser(); $result = $user->authorise('core.edit', $typeAlias . '.' . (int) $record->ucm_item_id); } // Finally try session (this catches edit.own case too) if (!$result) { $contentTypeTable->load($record->ucm_type_id); $typeEditables = (array) Factory::getApplication()->getUserState(str_replace('.', '.edit.', $contentTypeTable->type_alias) . '.id'); $result = in_array((int) $record->ucm_item_id, $typeEditables); } } return $result; } }
gpl-2.0
UMNLibraries/xml-record-php
src/File/WorldCatMarc.php
182
<?php namespace UmnLib\Core\XmlRecord\File; class WorldCatMarc extends WorldCat { public function recordElementNamespace() { return 'http://www.loc.gov/MARC21/slim'; } }
gpl-2.0
osCmax/oscmax2
catalog/includes/languages/french/affiliate_sales.php
2133
<?php /* $Id$ osCmax e-Commerce http://www.oscmax.com Copyright 2000 - 2011 osCmax Released under the GNU General Public License */ define('NAVBAR_TITLE', 'Programme d\'affiliation'); define('HEADING_TITLE', 'Programme d\'affiliation - Ventes'); define('TABLE_HEADING_DATE','Date'); define('TABLE_HEADING_SALES', 'Val. comm'); define('TABLE_HEADING_VALUE', 'Valeur de vente (excl.)'); define('TABLE_HEADING_PERCENTAGE','Tx de comm'); define('TABLE_HEADING_STATUS', 'Statut'); define('TEXT_DELETED_ORDER_BY_ADMIN', 'Supprim&eacute; (Admin)'); define('TEXT_INFORMATION_SALES_TOTAL', 'Le montant actuel de vos revenus s\'&eacute;l&egrave;ve à :'); define('TEXT_INFORMATION_SALES_TOTAL2', '<br>Seules des ventes finalis&eacute;es sont compt&eacute;es !'); define('TEXT_NO_SALES', 'Aucunes ventes r&eacute;alis&eacute;es actuellement.'); define('TEXT_DISPLAY_NUMBER_OF_SALES', 'Afficher de <b>%d</b> à <b>%d</b> (sur les <b>%d</b> ventes)'); define('TEXT_AFFILIATE_HEADER', 'Ventes venant de votre sit internet :'); define('TEXT_SALES','Cliquez sur [?] pour voir une description de chaque cat&eacute;gorie.'); define('HEADING_SALES_HELP','D\'affiliation Aide'); define('HEADING_DATE_HELP','Date d\'aide'); define('TEXT_DATE_HELP','<i>Date</i> repr&eacute;sentant la date de la vente.'); define('TEXT_TIME_HELP','Repr&eacute;sente le <i>temps</i> de la vente.'); define('HEADING_SALE_VALUE_HELP','Valeur de vente Aide'); define('TEXT_SALE_VALUE_HELP','<i>Valeur de vente</i> repr&eacute;sente la <i>valeur</i> de la vente.'); define('HEADING_COMMISSION_RATE_HELP','Aide taux de commission'); define('TEXT_COMMISSION_RATE_HELP','<i>Commission taux</i> repr&eacute;sente le taux de commission vers&eacute;e sur la vente.'); define('HEADING_COMMISSION_VALUE_HELP','Le b&eacute;n&eacute;fice d\'affiliation Aide'); define('TEXT_COMMISSION_VALUE_HELP','<i>Le b&eacute;n&eacute;fice d\'affiliation</i> repr&eacute;sente la commission perçue sur la vente.'); define('HEADING_STATUS_HELP','Vente &eacute;tat Aide'); define('TEXT_STATUS_HELP','<i>Vente &eacute;tat</i> repr&eacute;sente l\'&eacute;tat de la vente.'); ?>
gpl-2.0
siis/pfwall
tools/pfwall/pftables/modules/target/fuzz_resource.py
1196
from struct import * import ctypes import getopt import pft_c MAX_STRLEN = 256 PFT_NAMELEN = 16 class pft_target_symlink(ctypes.Structure): _fields_ = [ ("target_size", ctypes.c_uint), ("name", ctypes.c_char * PFT_NAMELEN), ("context_mask", ctypes.c_uint), ("target", ctypes.c_void_p), ("flags", ctypes.c_uint), ("check_find", ctypes.c_uint) ] SYMLINK = 0x1 HARDLINK = 0x2 SQUAT = 0x4 # Return a byte array # argv is of the form --message "tag" (this will be logged along with the packet) # It is possible that there is no message, in this case, just log def target_prepare(argv): flags = 0 check_find = 0 optlist, args = getopt.getopt(argv, "f:c") for o, a in optlist: if o == "-f": if a == "SYMLINK": flags |= SYMLINK elif a == "HARDLINK": flags |= HARDLINK elif a == "SQUAT": flags |= SQUAT if o == "-c": check_find = 1 pft_target_entry = pft_target_symlink() pft_target_entry.target_size = ctypes.sizeof(pft_target_entry) pft_target_entry.name = "fuzz_resource" pft_target_entry.context_mask = pft_c.PF_CONTEXT_SYSCALL_FILENAME pft_target_entry.flags = flags pft_target_entry.check_find = check_find return pft_target_entry
gpl-2.0
sibenye/b-unique_web
wp-content/plugins/smart-forms/smartforms.php
6059
<?php /** * Plugin Name: Smart Forms * Plugin URI: http://rednao.com/smart-donations/ * Description: Place diferent form of donations on your blog... * Author: RedNao * Author URI: http://rednao.com * Version: 2.0.2 * Text Domain: SmartDonations * Domain Path: /languages/ * Network: true * License: GPLv3 * License URI: http://www.gnu.org/licenses/gpl-3.0 * Slug: smartforms */ /** * Copyright (C) 2012-2013 RedNao (email: contactus@rednao.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Thanks to: * Jakub Stacho (http://www.iconfinder.com/iconsets/checkout-icons#readme) * Eggib (http://openclipart.org/detail/174878/) * Aha-Soft (http://www.iconfinder.com/iconsets/24x24-free-pixel-icons#readme) * Kevin Liew (http://www.queness.com/post/106/jquery-tabbed-interfacetabbed-structure-menu-tutorial) * Marcis Gasuns (http://led24.de/iconset/) */ require_once('smart-forms-config.php'); require_once(SMART_FORMS_DIR.'integration/smart-donations-integration-ajax.php'); require_once('smart-forms-ajax.php'); require_once(SMART_FORMS_DIR.'widgets/smart-form-widget.php'); add_shortcode('sform','rednao_smart_form_short_code'); add_action('init', 'rednao_smart_forms_init'); add_action( 'wp_ajax_rednao_smart_forms_save', 'rednao_smart_forms_save' ); add_action( 'wp_ajax_rednao_smart_form_list', 'rednao_smart_form_list' ); add_action( 'wp_ajax_rednao_smart_forms_entries_list', 'rednao_smart_forms_entries_list' ); add_action( 'wp_ajax_rednao_smart_forms_save_form_values','rednao_smart_forms_save_form_values'); add_action( 'wp_ajax_nopriv_rednao_smart_forms_save_form_values','rednao_smart_forms_save_form_values'); add_action( 'wp_ajax_rednao_smart_form_send_test_email','rednao_smart_form_send_test_email'); add_action('wp_ajax_rednao_smart_forms_submit_license','rednao_smart_forms_submit_license'); add_action('wp_ajax_rednao_smart_forms_execute_op','rednao_smart_forms_execute_op'); //integration add_action('wp_ajax_rednao_smart_forms_get_campaigns','rednao_smart_forms_get_campaigns'); add_action('admin_init','rednao_smart_forms_plugin_was_activated'); register_activation_hook(__FILE__,'rednao_smart_forms_plugin_was_activated'); add_action('admin_menu','rednao_smart_forms_create_menu'); function rednao_smart_forms_create_menu(){ add_menu_page('Smart Forms','Smart Forms','manage_options',__FILE__,'rednao_forms',plugin_dir_url(__FILE__).'images/smartFormsIcon.png'); add_submenu_page(__FILE__,'Entries','Entries','manage_options',__FILE__.'entries', 'rednao_smart_forms_entries'); add_submenu_page(__FILE__,'Support/Wish List','Support/Wish List','manage_options',__FILE__.'wish_list', 'rednao_smart_forms_wish_list'); add_submenu_page(__FILE__,'Tutorials','Tutorials','manage_options',__FILE__.'tutorials', 'rednao_smart_forms_tutorials'); } function rednao_smart_forms_plugin_was_activated() { $dbversion=get_option(SMART_FORMS_LATEST_DB_VERSION); global $wpdb; if( $dbversion<SMART_FORMS_LATEST_DB_VERSION ) { require_once(ABSPATH.'wp-admin/includes/upgrade.php'); $sql="CREATE TABLE ".SMART_FORMS_TABLE_NAME." ( form_id int AUTO_INCREMENT, form_name VARCHAR(200) NOT NULL, element_options MEDIUMTEXT NOT NULL, client_form_options MEDIUMTEXT NOT NULL, form_options MEDIUMTEXT NOT NULL, donation_email VARCHAR(200), PRIMARY KEY (form_id) );"; dbDelta($sql); $sql="CREATE TABLE ".SMART_FORMS_ENTRY." ( entry_id int AUTO_INCREMENT, form_id int, date datetime NOT NULL, data MEDIUMTEXT NOT NULL, ip VARCHAR(39), reference_id VARCHAR(200), PRIMARY KEY (entry_id) );"; dbDelta($sql); update_option("SMART_FORMS_LATEST_DB_VERSION",$dbversion); } } function rednao_forms() { include(SMART_FORMS_DIR.'main_screens/smart-forms-list.php'); } function rednao_smart_form_short_code($attr,$content) { require_once('smart-forms-helpers.php'); return rednao_smart_forms_load_form(null,$content,true); } function rednao_smart_forms_init() { if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) { return; } if ( get_user_option('rich_editing') == 'true') { add_filter( 'mce_external_plugins', 'rednao_smart_forms_add_plugin' ); add_filter( 'mce_buttons', 'rednao_smart_forms_register_button' ); } } function rednao_smart_forms_add_plugin($plugin_array) { wp_enqueue_script('isolated-slider',plugin_dir_url(__FILE__).'js/rednao-isolated-jq.js'); wp_enqueue_style('smart-forms-Slider',plugin_dir_url(__FILE__).'css/smartFormsSlider/jquery-ui-1.10.2.custom.min.css'); $plugin_array['rednao_smart_forms_button']=plugin_dir_url(__FILE__).'js/shortcode/smartFormsShortCodeButton.js'; return $plugin_array; } function rednao_smart_forms_register_button($buttons) { $buttons[]="rednao_smart_forms_button"; return $buttons; } function rednao_smart_forms_entries() { include(SMART_FORMS_DIR.'main_screens/smart-forms-entries.php'); } function rednao_smart_forms_wish_list() { include(SMART_FORMS_DIR.'main_screens/smart-forms-wishlist.php'); } function rednao_smart_forms_tutorials() { include(SMART_FORMS_DIR.'main_screens/smart-forms-tutorials.php'); } require_once(SMART_FORMS_DIR.'pr/smart-forms-pr.php'); ?>
gpl-2.0
profosure/porogram
TMessagesProj/src/main/java/com/porogram/profosure1/messenger/exoplayer2/ui/SubtitlePainter.java
13443
/* * Copyright (C) 2016 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.porogram.profosure1.messenger.exoplayer2.ui; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.RectF; import android.text.Layout.Alignment; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import com.porogram.profosure1.messenger.exoplayer2.text.CaptionStyleCompat; import com.porogram.profosure1.messenger.exoplayer2.text.Cue; import com.porogram.profosure1.messenger.exoplayer2.util.Util; /** * Paints subtitle {@link Cue}s. */ /* package */ final class SubtitlePainter { private static final String TAG = "SubtitlePainter"; /** * Ratio of inner padding to font size. */ private static final float INNER_PADDING_RATIO = 0.125f; /** * Temporary rectangle used for computing line bounds. */ private final RectF lineBounds = new RectF(); // Styled dimensions. private final float cornerRadius; private final float outlineWidth; private final float shadowRadius; private final float shadowOffset; private final float spacingMult; private final float spacingAdd; private final TextPaint textPaint; private final Paint paint; // Previous input variables. private CharSequence cueText; private Alignment cueTextAlignment; private float cueLine; @Cue.LineType private int cueLineType; @Cue.AnchorType private int cueLineAnchor; private float cuePosition; @Cue.AnchorType private int cuePositionAnchor; private float cueSize; private boolean applyEmbeddedStyles; private int foregroundColor; private int backgroundColor; private int windowColor; private int edgeColor; @CaptionStyleCompat.EdgeType private int edgeType; private float textSizePx; private float bottomPaddingFraction; private int parentLeft; private int parentTop; private int parentRight; private int parentBottom; // Derived drawing variables. private StaticLayout textLayout; private int textLeft; private int textTop; private int textPaddingX; @SuppressWarnings("ResourceType") public SubtitlePainter(Context context) { int[] viewAttr = {android.R.attr.lineSpacingExtra, android.R.attr.lineSpacingMultiplier}; TypedArray styledAttributes = context.obtainStyledAttributes(null, viewAttr, 0, 0); spacingAdd = styledAttributes.getDimensionPixelSize(0, 0); spacingMult = styledAttributes.getFloat(1, 1); styledAttributes.recycle(); Resources resources = context.getResources(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); int twoDpInPx = Math.round((2f * displayMetrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT); cornerRadius = twoDpInPx; outlineWidth = twoDpInPx; shadowRadius = twoDpInPx; shadowOffset = twoDpInPx; textPaint = new TextPaint(); textPaint.setAntiAlias(true); textPaint.setSubpixelText(true); paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Style.FILL); } /** * Draws the provided {@link Cue} into a canvas with the specified styling. * <p> * A call to this method is able to use cached results of calculations made during the previous * call, and so an instance of this class is able to optimize repeated calls to this method in * which the same parameters are passed. * * @param cue The cue to draw. * @param applyEmbeddedStyles Whether styling embedded within the cue should be applied. * @param style The style to use when drawing the cue text. * @param textSizePx The text size to use when drawing the cue text, in pixels. * @param bottomPaddingFraction The bottom padding fraction to apply when {@link Cue#line} is * {@link Cue#DIMEN_UNSET}, as a fraction of the viewport height * @param canvas The canvas into which to draw. * @param cueBoxLeft The left position of the enclosing cue box. * @param cueBoxTop The top position of the enclosing cue box. * @param cueBoxRight The right position of the enclosing cue box. * @param cueBoxBottom The bottom position of the enclosing cue box. */ public void draw(Cue cue, boolean applyEmbeddedStyles, CaptionStyleCompat style, float textSizePx, float bottomPaddingFraction, Canvas canvas, int cueBoxLeft, int cueBoxTop, int cueBoxRight, int cueBoxBottom) { CharSequence cueText = cue.text; if (TextUtils.isEmpty(cueText)) { // Nothing to draw. return; } if (!applyEmbeddedStyles) { // Strip out any embedded styling. cueText = cueText.toString(); } if (areCharSequencesEqual(this.cueText, cueText) && Util.areEqual(this.cueTextAlignment, cue.textAlignment) && this.cueLine == cue.line && this.cueLineType == cue.lineType && Util.areEqual(this.cueLineAnchor, cue.lineAnchor) && this.cuePosition == cue.position && Util.areEqual(this.cuePositionAnchor, cue.positionAnchor) && this.cueSize == cue.size && this.applyEmbeddedStyles == applyEmbeddedStyles && this.foregroundColor == style.foregroundColor && this.backgroundColor == style.backgroundColor && this.windowColor == style.windowColor && this.edgeType == style.edgeType && this.edgeColor == style.edgeColor && Util.areEqual(this.textPaint.getTypeface(), style.typeface) && this.textSizePx == textSizePx && this.bottomPaddingFraction == bottomPaddingFraction && this.parentLeft == cueBoxLeft && this.parentTop == cueBoxTop && this.parentRight == cueBoxRight && this.parentBottom == cueBoxBottom) { // We can use the cached layout. drawLayout(canvas); return; } this.cueText = cueText; this.cueTextAlignment = cue.textAlignment; this.cueLine = cue.line; this.cueLineType = cue.lineType; this.cueLineAnchor = cue.lineAnchor; this.cuePosition = cue.position; this.cuePositionAnchor = cue.positionAnchor; this.cueSize = cue.size; this.applyEmbeddedStyles = applyEmbeddedStyles; this.foregroundColor = style.foregroundColor; this.backgroundColor = style.backgroundColor; this.windowColor = style.windowColor; this.edgeType = style.edgeType; this.edgeColor = style.edgeColor; this.textPaint.setTypeface(style.typeface); this.textSizePx = textSizePx; this.bottomPaddingFraction = bottomPaddingFraction; this.parentLeft = cueBoxLeft; this.parentTop = cueBoxTop; this.parentRight = cueBoxRight; this.parentBottom = cueBoxBottom; int parentWidth = parentRight - parentLeft; int parentHeight = parentBottom - parentTop; textPaint.setTextSize(textSizePx); int textPaddingX = (int) (textSizePx * INNER_PADDING_RATIO + 0.5f); int availableWidth = parentWidth - textPaddingX * 2; if (cueSize != Cue.DIMEN_UNSET) { availableWidth = (int) (availableWidth * cueSize); } if (availableWidth <= 0) { Log.w(TAG, "Skipped drawing subtitle cue (insufficient space)"); return; } Alignment textAlignment = cueTextAlignment == null ? Alignment.ALIGN_CENTER : cueTextAlignment; textLayout = new StaticLayout(cueText, textPaint, availableWidth, textAlignment, spacingMult, spacingAdd, true); int textHeight = textLayout.getHeight(); int textWidth = 0; int lineCount = textLayout.getLineCount(); for (int i = 0; i < lineCount; i++) { textWidth = Math.max((int) Math.ceil(textLayout.getLineWidth(i)), textWidth); } if (cueSize != Cue.DIMEN_UNSET && textWidth < availableWidth) { textWidth = availableWidth; } textWidth += textPaddingX * 2; int textLeft; int textRight; if (cuePosition != Cue.DIMEN_UNSET) { int anchorPosition = Math.round(parentWidth * cuePosition) + parentLeft; textLeft = cuePositionAnchor == Cue.ANCHOR_TYPE_END ? anchorPosition - textWidth : cuePositionAnchor == Cue.ANCHOR_TYPE_MIDDLE ? (anchorPosition * 2 - textWidth) / 2 : anchorPosition; textLeft = Math.max(textLeft, parentLeft); textRight = Math.min(textLeft + textWidth, parentRight); } else { textLeft = (parentWidth - textWidth) / 2; textRight = textLeft + textWidth; } int textTop; if (cueLine != Cue.DIMEN_UNSET) { int anchorPosition; if (cueLineType == Cue.LINE_TYPE_FRACTION) { anchorPosition = Math.round(parentHeight * cueLine) + parentTop; } else { // cueLineType == Cue.LINE_TYPE_NUMBER int firstLineHeight = textLayout.getLineBottom(0) - textLayout.getLineTop(0); if (cueLine >= 0) { anchorPosition = Math.round(cueLine * firstLineHeight) + parentTop; } else { anchorPosition = Math.round(cueLine * firstLineHeight) + parentBottom; } } textTop = cueLineAnchor == Cue.ANCHOR_TYPE_END ? anchorPosition - textHeight : cueLineAnchor == Cue.ANCHOR_TYPE_MIDDLE ? (anchorPosition * 2 - textHeight) / 2 : anchorPosition; if (textTop + textHeight > parentBottom) { textTop = parentBottom - textHeight; } else if (textTop < parentTop) { textTop = parentTop; } } else { textTop = parentBottom - textHeight - (int) (parentHeight * bottomPaddingFraction); } textWidth = textRight - textLeft; // Update the derived drawing variables. this.textLayout = new StaticLayout(cueText, textPaint, textWidth, textAlignment, spacingMult, spacingAdd, true); this.textLeft = textLeft; this.textTop = textTop; this.textPaddingX = textPaddingX; drawLayout(canvas); } /** * Draws {@link #textLayout} into the provided canvas. * * @param canvas The canvas into which to draw. */ private void drawLayout(Canvas canvas) { final StaticLayout layout = textLayout; if (layout == null) { // Nothing to draw. return; } int saveCount = canvas.save(); canvas.translate(textLeft, textTop); if (Color.alpha(windowColor) > 0) { paint.setColor(windowColor); canvas.drawRect(-textPaddingX, 0, layout.getWidth() + textPaddingX, layout.getHeight(), paint); } if (Color.alpha(backgroundColor) > 0) { paint.setColor(backgroundColor); float previousBottom = layout.getLineTop(0); int lineCount = layout.getLineCount(); for (int i = 0; i < lineCount; i++) { lineBounds.left = layout.getLineLeft(i) - textPaddingX; lineBounds.right = layout.getLineRight(i) + textPaddingX; lineBounds.top = previousBottom; lineBounds.bottom = layout.getLineBottom(i); previousBottom = lineBounds.bottom; canvas.drawRoundRect(lineBounds, cornerRadius, cornerRadius, paint); } } if (edgeType == CaptionStyleCompat.EDGE_TYPE_OUTLINE) { textPaint.setStrokeJoin(Join.ROUND); textPaint.setStrokeWidth(outlineWidth); textPaint.setColor(edgeColor); textPaint.setStyle(Style.FILL_AND_STROKE); layout.draw(canvas); } else if (edgeType == CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW) { textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, edgeColor); } else if (edgeType == CaptionStyleCompat.EDGE_TYPE_RAISED || edgeType == CaptionStyleCompat.EDGE_TYPE_DEPRESSED) { boolean raised = edgeType == CaptionStyleCompat.EDGE_TYPE_RAISED; int colorUp = raised ? Color.WHITE : edgeColor; int colorDown = raised ? edgeColor : Color.WHITE; float offset = shadowRadius / 2f; textPaint.setColor(foregroundColor); textPaint.setStyle(Style.FILL); textPaint.setShadowLayer(shadowRadius, -offset, -offset, colorUp); layout.draw(canvas); textPaint.setShadowLayer(shadowRadius, offset, offset, colorDown); } textPaint.setColor(foregroundColor); textPaint.setStyle(Style.FILL); layout.draw(canvas); textPaint.setShadowLayer(0, 0, 0, 0); canvas.restoreToCount(saveCount); } /** * This method is used instead of {@link TextUtils#equals(CharSequence, CharSequence)} because the * latter only checks the text of each sequence, and does not check for equality of styling that * may be embedded within the {@link CharSequence}s. */ private static boolean areCharSequencesEqual(CharSequence first, CharSequence second) { // Some CharSequence implementations don't perform a cheap referential equality check in their // equals methods, so we perform one explicitly here. return first == second || (first != null && first.equals(second)); } }
gpl-2.0
knowlage/survey
components/com_ole/models/ole.php
829
<?php defined('_JEXEC') or die; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ class OleModelOle extends JModelItem{ protected $msg; function getMsg(){ if(!isset($this->msg)){ $input = JFactory::getApplication()->input; $id = $input->get('id',2,'int'); $msg = $input->get('message'); switch ($id){ case 1: $this->msg = $msg; break; default : //$this->msg = "Goodby Message"; break; } } return $this->msg; } }
gpl-2.0
hubzero/hubzero-cms
core/migrations/Migration20130723163332ComCourses.php
1029
<?php /** * @package hubzero-cms * @copyright Copyright (c) 2005-2020 The Regents of the University of California. * @license http://opensource.org/licenses/MIT MIT */ use Hubzero\Content\Migration\Base; // No direct access defined('_HZEXEC_') or die(); /** * Migration script for adding first_visit timestamp **/ class Migration20130723163332ComCourses extends Base { /** * Up **/ public function up() { $query = ""; if (!$this->db->tableHasField('#__courses_members', 'first_visit')) { $query = "ALTER TABLE `#__courses_members` ADD `first_visit` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00';"; } if (!empty($query)) { $this->db->setQuery($query); $this->db->query(); } } /** * Down **/ public function down() { $query = ""; if ($this->db->tableHasField('#__courses_members', 'first_visit')) { $query .= "ALTER TABLE `#__courses_members` DROP `first_visit`;"; } if (!empty($query)) { $this->db->setQuery($query); $this->db->query(); } } }
gpl-2.0
namwoody/kart-zill.com
wp-content/themes/kart/woocommerce/content-product_cat.php
1340
<?php if ( ! defined( 'ABSPATH' ) ) { exit; } global $woocommerce_loop; // Store loop count we're currently on. if ( empty( $woocommerce_loop['loop'] ) ) { $woocommerce_loop['loop'] = 0; } // Store column count for displaying the grid. if ( empty( $woocommerce_loop['columns'] ) ) { $woocommerce_loop['columns'] = apply_filters( 'loop_shop_columns', 4 ); } // Increase loop count. $woocommerce_loop['loop']++; ?> <li <?php wc_product_cat_class( '', $category ); ?>> <?php /** * woocommerce_before_subcategory hook. * * @hooked woocommerce_template_loop_category_link_open - 10 */ do_action( 'woocommerce_before_subcategory', $category ); /** * woocommerce_before_subcategory_title hook. * * @hooked woocommerce_subcategory_thumbnail - 10 */ do_action( 'woocommerce_before_subcategory_title', $category ); /** * woocommerce_shop_loop_subcategory_title hook. * * @hooked woocommerce_template_loop_category_title - 10 */ do_action( 'woocommerce_shop_loop_subcategory_title', $category ); /** * woocommerce_after_subcategory_title hook. */ do_action( 'woocommerce_after_subcategory_title', $category ); /** * woocommerce_after_subcategory hook. * * @hooked woocommerce_template_loop_category_link_close - 10 */ do_action( 'woocommerce_after_subcategory', $category ); ?> </li>
gpl-2.0
sloww/cntslinkgit
app_label/migrations/0003_auto_20150516_2356.py
395
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('app_label', '0002_auto_20150516_2339'), ] operations = [ migrations.AlterField( model_name='label', name='description', field=models.TextField(), ), ]
gpl-2.0
perdisci/WebCapsule
src/third-party/WebKit/Source/core/inspector/CodeGeneratorInstrumentation.py
17192
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import optparse import re import string import sys template_h = string.Template("""// Code generated from InspectorInstrumentation.idl #ifndef ${file_name}_h #define ${file_name}_h ${includes} namespace WebCore { namespace InspectorInstrumentation { $methods } // namespace InspectorInstrumentation } // namespace WebCore #endif // !defined(${file_name}_h) """) template_inline = string.Template(""" inline void ${name}(${params_public}) { ${fast_return} if (${condition}) ${name}Impl(${params_impl}); } """) template_inline_forward = string.Template(""" inline void ${name}(${params_public}) { ${fast_return} ${name}Impl(${params_impl}); } """) template_inline_returns_value = string.Template(""" inline ${return_type} ${name}(${params_public}) { ${fast_return} if (${condition}) return ${name}Impl(${params_impl}); return ${default_return_value}; } """) template_cpp = string.Template("""// Code generated from InspectorInstrumentation.idl #include "config.h" ${includes} namespace WebCore { ${extra_definitions} namespace InspectorInstrumentation { $methods } // namespace InspectorInstrumentation } // namespace WebCore """) template_outofline = string.Template(""" ${return_type} ${name}Impl(${params_impl}) {${impl_lines} }""") template_agent_call = string.Template(""" if (${agent_class}* agent = ${agent_fetch}) ${maybe_return}agent->${name}(${params_agent});""") template_agent_call_timeline_returns_cookie = string.Template(""" int timelineAgentId = 0; if (InspectorTimelineAgent* agent = agents->inspectorTimelineAgent()) { if (agent->${name}(${params_agent})) timelineAgentId = agent->id(); }""") template_instrumenting_agents_h = string.Template("""// Code generated from InspectorInstrumentation.idl #ifndef InstrumentingAgentsInl_h #define InstrumentingAgentsInl_h #include "wtf/FastAllocBase.h" #include "wtf/Noncopyable.h" #include "wtf/PassRefPtr.h" #include "wtf/RefCounted.h" namespace WebCore { ${forward_list} class InstrumentingAgents : public RefCounted<InstrumentingAgents> { WTF_MAKE_NONCOPYABLE(InstrumentingAgents); WTF_MAKE_FAST_ALLOCATED; public: static PassRefPtr<InstrumentingAgents> create() { return adoptRef(new InstrumentingAgents()); } ~InstrumentingAgents() { } void reset(); ${accessor_list} private: InstrumentingAgents(); ${member_list} }; } #endif // !defined(InstrumentingAgentsInl_h) """) template_instrumenting_agent_accessor = string.Template(""" ${class_name}* ${getter_name}() const { return ${member_name}; } void set${class_name}(${class_name}* agent) { ${member_name} = agent; }""") template_instrumenting_agents_cpp = string.Template(""" InstrumentingAgents::InstrumentingAgents() : $init_list { } void InstrumentingAgents::reset() { $reset_list }""") def match_and_consume(pattern, source): match = re.match(pattern, source) if match: return match, source[len(match.group(0)):].strip() return None, source def load_model_from_idl(source): source = re.sub("//.*", "", source) # Remove line comments source = re.sub("/\*(.|\n)*?\*/", "", source, re.MULTILINE) # Remove block comments source = re.sub("\]\s*?\n\s*", "] ", source) # Merge the method annotation with the next line source = source.strip() model = [] while len(source): match, source = match_and_consume("interface\s(\w*)\s?\{([^\{]*)\}", source) if not match: sys.stderr.write("Cannot parse %s\n" % source[:100]) sys.exit(1) model.append(File(match.group(1), match.group(2))) return model class File: def __init__(self, name, source): self.name = name self.header_name = self.name + "Inl" self.includes = [include_inspector_header("InspectorInstrumentation")] self.declarations = [] for line in map(str.strip, source.split("\n")): line = re.sub("\s{2,}", " ", line).strip() # Collapse whitespace if len(line) == 0: continue if line[0] == "#": self.includes.append(line) else: self.declarations.append(Method(line)) self.includes.sort() def generate(self, cpp_lines, used_agents): header_lines = [] for declaration in self.declarations: for agent in set(declaration.agents): used_agents.add(agent) declaration.generate_header(header_lines) declaration.generate_cpp(cpp_lines) return template_h.substitute(None, file_name=self.header_name, includes="\n".join(self.includes), methods="\n".join(header_lines)) class Method: def __init__(self, source): match = re.match("(\[[\w|,|=|\s]*\])?\s?(\w*\*?) (\w*)\((.*)\)\s?;", source) if not match: sys.stderr.write("Cannot parse %s\n" % source) sys.exit(1) self.options = [] if match.group(1): options_str = re.sub("\s", "", match.group(1)[1:-1]) if len(options_str) != 0: self.options = options_str.split(",") self.return_type = match.group(2) self.name = match.group(3) # Splitting parameters by a comma, assuming that attribute lists contain no more than one attribute. self.params = map(Parameter, map(str.strip, match.group(4).split(","))) self.accepts_cookie = len(self.params) and self.params[0].type == "const InspectorInstrumentationCookie&" self.returns_cookie = self.return_type == "InspectorInstrumentationCookie" self.returns_value = self.return_type != "void" if self.return_type == "bool": self.default_return_value = "false" elif self.return_type == "String": self.default_return_value = "\"\"" elif self.return_type.endswith("*"): self.default_return_value = "0" else: self.default_return_value = self.return_type + "()" for param in self.params: if "DefaultReturn" in param.options: self.default_return_value = param.name self.params_impl = self.params if not self.accepts_cookie and not "Inline=Forward" in self.options: if not "Keep" in self.params_impl[0].options: self.params_impl = self.params_impl[1:] self.params_impl = [Parameter("InstrumentingAgents* agents")] + self.params_impl self.agents = filter(lambda option: not "=" in option, self.options) def generate_header(self, header_lines): if "Inline=Custom" in self.options: return header_lines.append("%s %sImpl(%s);" % ( self.return_type, self.name, ", ".join(map(Parameter.to_str_class, self.params_impl)))) if "Inline=FastReturn" in self.options or "Inline=Forward" in self.options: fast_return = "\n FAST_RETURN_IF_NO_FRONTENDS(%s);" % self.default_return_value else: fast_return = "" for param in self.params: if "FastReturn" in param.options: fast_return += "\n if (!%s)\n return %s;" % (param.name, self.default_return_value) if self.accepts_cookie: condition = "%s.isValid()" % self.params_impl[0].name template = template_inline elif "Inline=Forward" in self.options: condition = "" template = template_inline_forward else: condition = "InstrumentingAgents* agents = instrumentingAgentsFor(%s)" % self.params[0].name if self.returns_value: template = template_inline_returns_value else: template = template_inline header_lines.append(template.substitute( None, name=self.name, fast_return=fast_return, return_type=self.return_type, default_return_value=self.default_return_value, params_public=", ".join(map(Parameter.to_str_full, self.params)), params_impl=", ".join(map(Parameter.to_str_name, self.params_impl)), condition=condition)) def generate_cpp(self, cpp_lines): if len(self.agents) == 0: return body_lines = map(self.generate_agent_call, self.agents) if self.returns_cookie: if "Timeline" in self.agents: timeline_agent_id = "timelineAgentId" else: timeline_agent_id = "0" body_lines.append("\n return InspectorInstrumentationCookie(agents, %s);" % timeline_agent_id) elif self.returns_value: body_lines.append("\n return %s;" % self.default_return_value) cpp_lines.append(template_outofline.substitute( None, return_type=self.return_type, name=self.name, params_impl=", ".join(map(Parameter.to_str_class_and_name, self.params_impl)), impl_lines="".join(body_lines))) def generate_agent_call(self, agent): agent_class, agent_getter = agent_getter_signature(agent) leading_param_name = self.params_impl[0].name if not self.accepts_cookie: agent_fetch = "%s->%s()" % (leading_param_name, agent_getter) elif agent == "Timeline": agent_fetch = "retrieveTimelineAgent(%s)" % leading_param_name else: agent_fetch = "%s.instrumentingAgents()->%s()" % (leading_param_name, agent_getter) if agent == "Timeline" and self.returns_cookie: template = template_agent_call_timeline_returns_cookie else: template = template_agent_call if not self.returns_value or self.returns_cookie: maybe_return = "" else: maybe_return = "return " return template.substitute( None, name=self.name, agent_class=agent_class, agent_fetch=agent_fetch, maybe_return=maybe_return, params_agent=", ".join(map(Parameter.to_str_value, self.params_impl)[1:])) class Parameter: def __init__(self, source): self.options = [] match, source = match_and_consume("\[(\w*)\]", source) if match: self.options.append(match.group(1)) parts = map(str.strip, source.split("=")) if len(parts) == 1: self.default_value = None else: self.default_value = parts[1] param_decl = parts[0] if re.match("(const|unsigned long) ", param_decl): min_type_tokens = 2 else: min_type_tokens = 1 if len(param_decl.split(" ")) > min_type_tokens: parts = param_decl.split(" ") self.type = " ".join(parts[:-1]) self.name = parts[-1] else: self.type = param_decl self.name = generate_param_name(self.type) if re.match("PassRefPtr<", param_decl): self.value = "%s.get()" % self.name else: self.value = self.name def to_str_full(self): if self.default_value is None: return self.to_str_class_and_name() return "%s %s = %s" % (self.type, self.name, self.default_value) def to_str_class_and_name(self): return "%s %s" % (self.type, self.name) def to_str_class(self): return self.type def to_str_name(self): return self.name def to_str_value(self): return self.value def generate_param_name(param_type): base_name = re.match("(const |PassRefPtr<)?(\w*)", param_type).group(2) return "param" + base_name def agent_class_name(agent): custom_agent_names = ["PageDebugger", "PageRuntime", "WorkerRuntime"] if agent in custom_agent_names: return "%sAgent" % agent return "Inspector%sAgent" % agent def agent_getter_signature(agent): agent_class = agent_class_name(agent) return agent_class, agent_class[0].lower() + agent_class[1:] def include_header(name): return "#include \"%s.h\"" % name def include_inspector_header(name): return include_header("core/inspector/" + name) def generate_instrumenting_agents(used_agents): agents = list(used_agents) forward_list = [] accessor_list = [] member_list = [] init_list = [] reset_list = [] for agent in agents: class_name, getter_name = agent_getter_signature(agent) member_name = "m_" + getter_name forward_list.append("class %s;" % class_name) accessor_list.append(template_instrumenting_agent_accessor.substitute( None, class_name=class_name, getter_name=getter_name, member_name=member_name)) member_list.append(" %s* %s;" % (class_name, member_name)) init_list.append("%s(0)" % member_name) reset_list.append("%s = 0;" % member_name) forward_list.sort() accessor_list.sort() member_list.sort() init_list.sort() reset_list.sort() header_lines = template_instrumenting_agents_h.substitute( None, forward_list="\n".join(forward_list), accessor_list="\n".join(accessor_list), member_list="\n".join(member_list)) cpp_lines = template_instrumenting_agents_cpp.substitute( None, init_list="\n , ".join(init_list), reset_list="\n ".join(reset_list)) return header_lines, cpp_lines def generate(input_path, output_dir): fin = open(input_path, "r") files = load_model_from_idl(fin.read()) fin.close() cpp_includes = [] cpp_lines = [] used_agents = set() for f in files: cpp_includes.append(include_header(f.header_name)) fout = open(output_dir + "/" + f.header_name + ".h", "w") fout.write(f.generate(cpp_lines, used_agents)) fout.close() for agent in used_agents: cpp_includes.append(include_inspector_header(agent_class_name(agent))) cpp_includes.append(include_header("InstrumentingAgentsInl")) cpp_includes.sort() instrumenting_agents_header, instrumenting_agents_cpp = generate_instrumenting_agents(used_agents) fout = open(output_dir + "/" + "InstrumentingAgentsInl.h", "w") fout.write(instrumenting_agents_header) fout.close() fout = open(output_dir + "/InspectorInstrumentationImpl.cpp", "w") fout.write(template_cpp.substitute(None, includes="\n".join(cpp_includes), extra_definitions=instrumenting_agents_cpp, methods="\n".join(cpp_lines))) fout.close() cmdline_parser = optparse.OptionParser() cmdline_parser.add_option("--output_dir") try: arg_options, arg_values = cmdline_parser.parse_args() if (len(arg_values) != 1): raise Exception("Exactly one plain argument expected (found %s)" % len(arg_values)) input_path = arg_values[0] output_dirpath = arg_options.output_dir if not output_dirpath: raise Exception("Output directory must be specified") except Exception: # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html exc = sys.exc_info()[1] sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc) sys.stderr.write("Usage: <script> --output_dir <output_dir> InspectorInstrumentation.idl\n") exit(1) generate(input_path, output_dirpath)
gpl-2.0