repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
amurrayw/tetrad | tetrad-gui/src/main/java/edu/cmu/tetradapp/app/hpc/action/DeleteHpcJobInfoAction.java | 1973 | package edu.cmu.tetradapp.app.hpc.action;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import edu.cmu.tetradapp.app.TetradDesktop;
import edu.cmu.tetradapp.app.hpc.editor.HpcJobActivityEditor;
import edu.cmu.tetradapp.app.hpc.manager.HpcJobManager;
import edu.cmu.tetradapp.util.DesktopController;
import edu.pitt.dbmi.tetrad.db.entity.HpcJobInfo;
/**
*
* Feb 8, 2017 7:34:03 PM
*
* @author Chirayu (Kong) Wongchokprasitti, PhD
*
*/
public class DeleteHpcJobInfoAction extends AbstractAction {
private static final long serialVersionUID = 7915068087861233608L;
private final Component parentComp;
public DeleteHpcJobInfoAction(final Component parentComp) {
this.parentComp = parentComp;
}
@Override
public void actionPerformed(ActionEvent e) {
JTable table = (JTable) e.getSource();
int modelRow = Integer.valueOf(e.getActionCommand());
DefaultTableModel finishedJobTableModel = (DefaultTableModel) table.getModel();
long jobId = Long.valueOf(finishedJobTableModel.getValueAt(modelRow, HpcJobActivityEditor.ID_COLUMN).toString())
.longValue();
int answer = JOptionPane.showConfirmDialog(parentComp,
"Would you like to delete this HPC job id: " + jobId + "?", "Delete HPC job",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION)
return;
TetradDesktop desktop = (TetradDesktop) DesktopController.getInstance();
final HpcJobManager hpcJobManager = desktop.getHpcJobManager();
HpcJobInfo hpcJobInfo = hpcJobManager.findHpcJobInfoById(
Long.valueOf(finishedJobTableModel.getValueAt(modelRow, HpcJobActivityEditor.ID_COLUMN).toString())
.longValue());
if (hpcJobInfo != null) {
// Update table
finishedJobTableModel.removeRow(modelRow);
table.updateUI();
hpcJobManager.removeHpcJobInfoTransaction(hpcJobInfo);
}
}
}
| gpl-2.0 |
jonthewayne/FanActions | wp-content/themes/showtime/freshwork/functions/freshtour.php | 4606 | <?php
//////////////////////////////////////////////////////////////////////////////
// INIT FUNCTION
//////////////////////////////////////////////////////////////////////////////
$step = 1;
if( isset($_POST['prc_step']) ) $step = $_POST['prc_step'];
function tour_add_init()
{
}
//////////////////////////////////////////////////////////////////////////////
// FRESHPANEL ADD FUNCTION
//////////////////////////////////////////////////////////////////////////////
function tour()
{
global $step;
// echo 'dsdsds';
// step 1
if($step == 1)
{
?>
<div class="wrap">
<h2>Take a Tour Page Generator</h2>
<br /><br />
<form method="post">
<input id="prc_pages" name="prc_pages" value=3> How many sub-pages you want?<br>
<input type="submit" value="Next Step" style="margin:15px 0;">
<input type="hidden" name="prc_step" value="2">
</form>
</div>
<?php
}
else if($step == 2)
{
$pages = $_POST['prc_pages'];
if($pages == '') $pages =1;
?>
<form method="post">
<div class="wrap">
<h2>Insert your data into the boxes and click 'Generate'</h2>
<table cellspacing="20px" style="margin:0 0 0 -20px;">
<tr>
<td> <input type="text" name="prc_title" style="width:300px; margin-bottom:23px;"><label style="padding:4px 4px 9px 7px;">Tour Navigation Title</label> </td>
</tr>
<?php
for($r = 1; $r <= $pages; $r++)
{
echo '<tr>';
echo '<td style="border:1px solid #CCC; background:#EEE; padding:10px; margin-bottom:23px;">';
echo '<input type="text" style="width:310px; margin-bottom:5px;" name="i_r'.$r.'"><label style="padding:4px 4px 9px 7px;">Sub-Page Navigation Title</label><br>';
echo '<textarea style="width:500px; height:400px;" name="ta_r'.$r.'"></textarea>';
echo '</td>';
echo '</tr>';
}
?>
</table>
<input type="submit" value="Generate the code" style="margin:15px 0;">
<input type="hidden" name="prc_step" value="3">
<input type="hidden" name="prc_pages" value="<?php echo $pages; ?>">
</form>
</div>
<?php
}
else if($step==3)
{
$pages = $_POST['prc_pages'];
if($pages == '') $pages =1;
$output = '<div id="tour">';
$nav = '<ul id="tour_nav"><li class="tour_nav_name">'.stripslashes($_POST['prc_title']).'</li>';
$slide = '<div id="tour_slider">';
for($p = 1; $p<=$pages; $p++)
{
$title = $_POST['i_r'.$p];
$content_slide = $_POST['ta_r'.$p];
$title = stripslashes( $title );// str_replace( array('"',"'"), array('"', '''), $title );
$content_slide =stripslashes( $content_slide );// str_replace( array('"',"'"), array('"', '''), $content_slide );
if($p ==1)
{
$nav .= '<li><a href="" rel="'.$p.'" class="tour_nav_active">'.$title.'</a></li>';
$content .= '<li style="">'.$content_slide;
$content .='<div class="tour_pagenavi">
<a href="" class="tour_pagenavi_right" rel="'.($p+1).'">'.stripslashes($_POST['i_r'.($p+1)]).' →</a>
</div></li>';
}
else
{
if($p == $pages)
$nav .= '<li><a href="" class="tour_nav_last" rel="'.$p.'">'.$title.'</a></li>';
else
$nav .= '<li><a href="" rel="'.$p.'">'.$title.'</a></li>';
$content .= '<li style=" height:7px;">'.$content_slide;
$content .='<div class="tour_pagenavi">';
$content .= '<a href="" class="tour_pagenavi_left" rel="'.($p-1).'">←'.stripslashes($_POST['i_r'.($p-1)]).'</a>';
if(($p+1)<= $pages )
$content .='<a href="" class="tour_pagenavi_right" rel="'.($p+1).'">'.stripslashes($_POST['i_r'.($p+1)]).' →</a>';
$content .= '</div></li>';
}
}
$output .= $nav.'</ul><div id="tour_slider"><ul>'.$content.'</ul></div><div class="clear"></div></div>';
echo ' <div class="wrap"><h2>Now copy and paste this code into your fullwidth page</h2>';
echo '<textarea cols=80 rows=20>'.$output.'</textarea>';
echo '<br />* This code is supported only in fullwidth page';
}
}
function tour_add_admin()
{
//add_menu_page('Take a Tour - Generator', 'FreshTour', 'administrator', basename(__FILE__), 'tour');
}
//////////////////////////////////////////////////////////////////////////////
// ACTIONS
//////////////////////////////////////////////////////////////////////////////
add_action('admin_init', 'tour_add_init');
add_action('admin_menu', 'tour_add_admin');
?>
| gpl-2.0 |
Educfor/dev-posi-dalia | views/templates/inscript_content.php | 184 |
<!-- Contenu a l'interieur de la balise <body> -->
<?php
echo $template_content;
// Le footer est obligatoire (minimum : </body> </html>)
//require('inscript_footer.php');
?> | gpl-2.0 |
pudly/styled-ui | wp-content/themes/styledui/404.php | 1730 | <?php
/**
* The template for displaying 404 pages (Not Found).
*
* @package StyledUI
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<article id="post-0" class="post error404 not-found">
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Oops! That page can’t be found.', 'styledui' ); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<p><?php _e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'styledui' ); ?></p>
<?php get_search_form(); ?>
<?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
<?php if ( styledui_categorized_blog() ) : // Only show the widget if site has multiple categories. ?>
<div class="widget widget_categories">
<h2 class="widgettitle"><?php _e( 'Most Used Categories', 'styledui' ); ?></h2>
<ul>
<?php
wp_list_categories( array(
'orderby' => 'count',
'order' => 'DESC',
'show_count' => 1,
'title_li' => '',
'number' => 10,
) );
?>
</ul>
</div><!-- .widget -->
<?php endif; ?>
<?php
/* translators: %1$s: smiley */
$archive_content = '<p>' . sprintf( __( 'Try looking in the monthly archives. %1$s', 'styledui' ), convert_smilies( ':)' ) ) . '</p>';
the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" );
?>
<?php the_widget( 'WP_Widget_Tag_Cloud' ); ?>
</div><!-- .entry-content -->
</article><!-- #post-0 .post .error404 .not-found -->
</div><!-- #content -->
</div><!-- #primary -->
<?php get_footer(); ?> | gpl-2.0 |
joglomedia/masedi.net | wp-content/themes/JobBoard/library/includes/return.php | 1617 | <?php get_header(); ?>
<?php st_before_content($columns=''); ?>
<ul class="page-nav"><li><?php if ( get_option( 'ptthemes_breadcrumbs' ) == 'Yes') { yoast_breadcrumb('',' » '.PAYMENT_SUCCESS_TITLE); } ?></li></ul>
<div id="content" class="eleven columns">
<h1 class="page_head"><?php echo PAYMENT_SUCCESS_TITLE;?></h1>
<?php
global $upload_folder_path;
$destinationfile = stripslashes(get_option('post_payment_success_msg_content'));
if($destinationfile)
{
$filecontent = $destinationfile;
}else
{
$filecontent = __(PAYMENT_SUCCESS_AND_RETURN_MSG);
}
?>
<?php
$store_name = get_option('blogname');
$post_link = get_option('siteurl').'/?page=preview&alook=1&pid='.$_REQUEST['pid'];
$search_array = array('[#site_name#]','[#submited_information_link#]');
$replace_array = array($store_name,$post_link);
$filecontent = str_replace($search_array,$replace_array,$filecontent);
if($filecontent)
{
echo $filecontent;
}else
{
?>
<h4><?php echo PAYMENT_SUCCESS_MSG1; ?></h4>
<h6><?php echo PAYMENT_SUCCESS_MSG2; ?></h6>
<h6><?php echo PAYMENT_SUCCESS_MSG3.' '.get_option(('blogname').'.'); ?></h6>
<?php
}
?>
</div>
<?php st_after_content(); ?>
<?php get_sidebar(); ?> <!-- sidebar #end -->
<?php get_footer(); ?> | gpl-2.0 |
kmatheussen/radium | pluginhost/JuceLibraryCode/modules/juce_core/files/juce_DirectoryIterator.cpp | 5075 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
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
{
StringArray DirectoryIterator::parseWildcards (const String& pattern)
{
StringArray s;
s.addTokens (pattern, ";,", "\"'");
s.trim();
s.removeEmptyStrings();
return s;
}
bool DirectoryIterator::fileMatches (const StringArray& wildcards, const String& filename)
{
for (auto& w : wildcards)
if (filename.matchesWildcard (w, ! File::areFileNamesCaseSensitive()))
return true;
return false;
}
bool DirectoryIterator::next()
{
return next (nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
}
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
bool DirectoryIterator::next (bool* isDirResult, bool* isHiddenResult, int64* fileSize,
Time* modTime, Time* creationTime, bool* isReadOnly)
{
for (;;)
{
hasBeenAdvanced = true;
if (subIterator != nullptr)
{
if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
return true;
subIterator.reset();
}
String filename;
bool isDirectory, isHidden = false, shouldContinue = false;
while (fileFinder.next (filename, &isDirectory,
(isHiddenResult != nullptr || (whatToLookFor & File::ignoreHiddenFiles) != 0) ? &isHidden : nullptr,
fileSize, modTime, creationTime, isReadOnly))
{
++index;
if (! filename.containsOnly ("."))
{
bool matches = false;
if (isDirectory)
{
if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
subIterator.reset (new DirectoryIterator (File::createFileWithoutCheckingPath (path + filename),
true, wildCard, whatToLookFor));
matches = (whatToLookFor & File::findDirectories) != 0;
}
else
{
matches = (whatToLookFor & File::findFiles) != 0;
}
// if we're not relying on the OS iterator to do the wildcard match, do it now..
if (matches && (isRecursive || wildCards.size() > 1))
matches = fileMatches (wildCards, filename);
if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
matches = ! isHidden;
if (matches)
{
currentFile = File::createFileWithoutCheckingPath (path + filename);
if (isHiddenResult != nullptr) *isHiddenResult = isHidden;
if (isDirResult != nullptr) *isDirResult = isDirectory;
return true;
}
if (subIterator != nullptr)
{
shouldContinue = true;
break;
}
}
}
if (! shouldContinue)
return false;
}
}
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
JUCE_END_IGNORE_WARNINGS_MSVC
const File& DirectoryIterator::getFile() const
{
if (subIterator != nullptr && subIterator->hasBeenAdvanced)
return subIterator->getFile();
// You need to call DirectoryIterator::next() before asking it for the file that it found!
jassert (hasBeenAdvanced);
return currentFile;
}
float DirectoryIterator::getEstimatedProgress() const
{
if (totalNumFiles < 0)
totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
if (totalNumFiles <= 0)
return 0.0f;
auto detailedIndex = (subIterator != nullptr) ? (float) index + subIterator->getEstimatedProgress()
: (float) index;
return jlimit (0.0f, 1.0f, detailedIndex / (float) totalNumFiles);
}
} // namespace juce
| gpl-2.0 |
omgbebebe/warzone2100 | data/mp/multiplay/skirmish/semperfi_includes/build.js | 10439 |
// If positive, there are oil derricks that unused due to lack of power generators.
// If negative, we have too many power generator (usually not a problem in itself).
function numUnusedDerricks()
{
return countStruct(derrick) - countStruct(powGen) * 4;
}
function conCanHelp(mydroid, bx, by)
{
return (mydroid.order != DORDER_HELPBUILD
&& mydroid.order != DORDER_BUILD
&& mydroid.order != DORDER_LINEBUILD
&& mydroid.order != DORDER_RECYCLE
&& mydroid.order != DORDER_DEMOLISH
&& droidCanReach(mydroid, bx, by));
}
//Return all trucks that are not doing anything.
function findIdleTrucks()
{
var builders = enumDroid(me, DROID_CONSTRUCT);
var droidlist = [];
for (var i = 0; i < builders.length; i++)
{
if (conCanHelp(builders[i], startPositions[me].x, startPositions[me].y))
{
droidlist.push(builders[i]);
}
}
return droidlist;
}
// Demolish object.
function demolishThis(object)
{
var success = false;
var droidList = findIdleTrucks();
for (var i = 0; i < droidList.length; i++)
{
if(orderDroidObj(droidList[i], DORDER_DEMOLISH, object))
{
success = true;
}
}
return success;
}
// Build something. MaxBlockingTiles is optional.
function grabTrucksAndBuild(structure, maxBlockingTiles)
{
if (!defined(maxBlockingTiles))
{
maxBlockingTiles = 1;
}
var droidList = findIdleTrucks();
var found = false;
for (var i = 0; i < droidList.length; i++)
{
var result = pickStructLocation(droidList[i], structure, startPositions[me].x, startPositions[me].y, maxBlockingTiles);
if (result)
{
//logObj(mydroid, "Construction work");
orderDroidBuild(droidList[i], DORDER_BUILD, structure, result.x, result.y);
found = true;
}
}
return found;
}
// Help finish building some object.
function checkLocalJobs()
{
var trucks = findIdleTrucks();
var success = false;
var structlist = enumStruct(me).filter(function(obj) { return ((obj.status != BUILT) && (obj.stattype != RESOURCE_EXTRACTOR)); });
if (trucks.length > 0 && structlist.length > 0)
{
structlist.sort(sortByDistToBase);
for (var j = 0; j < trucks.length; ++j)
{
if (orderDroidObj(trucks[j], DORDER_HELPBUILD, structlist[0]))
{
//logObj(trucks[j], "Go help construction");
success = true;
}
}
}
return success;
}
function lookForOil()
{
var droids = enumDroid(me, DROID_CONSTRUCT);
var oils = enumFeature(-1, oilRes);
var bestDroid = null;
var bestDist = 99999;
var success = false;
//log("looking for oil... " + oils.length + " available");
if (oils.length > 0)
{
oils.sort(sortByDistToBase); // grab closer oils first
for (var i = 0; i < oils.length; i++)
{
for (var j = 0; j < droids.length; j++)
{
var dist = distBetweenTwoPoints(droids[j].x, droids[j].y, oils[i].x, oils[i].y);
if (droidCanReach(droids[j], oils[i].x, oils[i].y)
&& safeDest(me, oils[i].x, oils[i].y)
&& droids[j].order != DORDER_BUILD // but can snatch from HELPBUILD
&& droids[j].order != DORDER_LINEBUILD
&& bestDist > dist
&& !droids[j].busy)
{
bestDroid = droids[j];
bestDist = dist;
}
}
if (bestDroid)
{
bestDroid.busy = true;
orderDroidBuild(bestDroid, DORDER_BUILD, derrick, oils[i].x, oils[i].y);
bestDist = 99999;
bestDroid = null;
success = true;
}
}
}
return success;
}
// Build anti air rockets. TODO: demolish obsolete antiair structures.
function buildAntiAir()
{
const MAX_DEFENSES = countStruct(factory) * 2;
const MIN_POWER = -200;
const SAM_SITES = ["P0-AASite-SAM2", "P0-AASite-SAM1", "P0-AASite-Sunburst"];
var antiAir = enumStruct(me).filter(function(obj) { return obj.canHitAir == true; });
if ((getRealPower() < MIN_POWER) || (antiAir.length > MAX_DEFENSES))
{
return false;
}
for (var j = 0; j < SAM_SITES.length; ++j)
{
if (isStructureAvailable(SAM_SITES[j]))
{
if (grabTrucksAndBuild(SAM_SITES[j], 1))
{
return true;
}
}
}
return false;
}
// type refers to either a hardpoint like structure or an artillery emplacement.
// returns undefined if no structure it can build can be built.
function returnDefense(type)
{
if(!defined(type))
{
type = random(2);
}
var defenses;
if(type == 0)
{
defenses = [
"Emplacement-MdART-pit",
"WallTower-Atmiss",
"Emplacement-HvyATrocket",
"WallTower06",
"Emplacement-MRL-pit",
"GuardTower6",
];
}
else
{
defenses = [
"Emplacement-HvART-pit",
"Emplacement-Rocket06-IDF",
];
}
var bestDefense;
for(var i = 0; i < defenses.length; ++i)
{
if(isStructureAvailable(defenses[i]))
{
bestDefense = defenses[i];
break;
}
}
return bestDefense;
}
// Immediately try building a defense near this truck.
function buildDefenseNearTruck(truck, type)
{
if(!defined(type))
{
type = 0;
}
var defense = returnDefense(type);
if(defined(defense))
{
var result = pickStructLocation(truck, defense, truck.x, truck.y, 1);
if (result)
{
return orderDroidBuild(truck, DORDER_BUILD, defense, result.x, result.y);
}
}
return false;
}
// Passing a truck will instruct that truck to pick
// a location to build a defense structure near it.
function buildDefenses(truck)
{
if(defined(truck))
{
return buildDefenseNearTruck(truck);
}
var def = returnDefense(1); // Build artillery in base.
if (defined(def) && (getRealPower() > -200))
{
return grabTrucksAndBuild(def, 1);
}
return false;
}
// Basic base design so as to survive in a no bases match.
function buildBasicBase()
{
if (isStructureAvailable(factory) && (countStruct(factory) == 0) && grabTrucksAndBuild(factory, 0))
{
return true;
}
if (!researchDone && isStructureAvailable(resLab))
{
if ((countStruct(resLab) == 0) && grabTrucksAndBuild(resLab, 0))
{
return true;
}
}
// Build HQ if missing
if (isStructureAvailable(playerHQ) && (countStruct(playerHQ) == 0) && grabTrucksAndBuild(playerHQ, 0))
{
return true;
}
return false;
}
function buildFundamentals()
{
//log("build fundamentals");
if(buildBasicBase())
{
return;
}
if(lookForOil())
{
return;
}
// Help build unfinished buildings
if(checkLocalJobs())
{
return;
}
if (maintenance())
{
return;
}
// If we need power generators, try to queue up production of them with any idle trucks
if ((countStruct(powGen) == 0 || numUnusedDerricks() > 0) && isStructureAvailable(powGen) && grabTrucksAndBuild(powGen, 0))
{
return; // exit early
}
buildFundamentals2(); // go on to the next level
}
function buildFundamentals2()
{
//log("build fundamentals2");
var factcount = countStruct(factory);
//Build VTOL pads if needed
var needVtolPads = ((2 * countStruct(vtolPad)) < enumGroup(vtolGroup).length);
if (needVtolPads && isStructureAvailable(vtolPad) && grabTrucksAndBuild(vtolPad, 2))
{
return;
}
// Same amount of research labs as factories.
if (!researchDone && isStructureAvailable(resLab))
{
//After ten minutes, build more labs if power is good enough.
if ((((gameTime > 60000 * 10) && (getRealPower() > -150)) || (countStruct(resLab) < factcount)) && grabTrucksAndBuild(resLab, 0))
{
return; // done here
}
}
// Build as many factories as we can afford
if ((playerPower(me) > factcount * 750) && isStructureAvailable(factory) && grabTrucksAndBuild(factory, 0))
{
return; // done here
}
// Build VTOL factory if we don't have one
if (isStructureAvailable(vtolFactory))
{
var vFacs = countStruct(vtolFactory);
if (((vFacs == 0) || (playerPower(me) > factcount * 550)) && (vFacs < factcount) && grabTrucksAndBuild(vtolFactory, 0))
{
return;
}
}
// Build cyborg factory if we have thermite cyborg weapon (unless it is a sea map)
if (!isSeaMap && isStructureAvailable(cybFactory) && componentAvailable("Cyb-Wpn-Thermite"))
{
var cFacs = countStruct(cybFactory);
if (((cFacs == 0) || (playerPower(me) > factcount * 450)) && (cFacs < factcount) && grabTrucksAndBuild(cybFactory, 0))
{
return;
}
}
// Build CB towers in base.
if (isStructureAvailable(cbTower))
{
// Or try building wide spectrum towers.
if (isStructureAvailable(wideSpecTower))
{
if ((getRealPower() > -200) && (countStruct(wideSpecTower) < 2) && grabTrucksAndBuild(wideSpecTower, 1))
{
return;
}
}
else
{
//Keep maxBlockingTile 0 since there is a possibility the trucks
//could block the path out of base.
if ((getRealPower() > -100) && (countStruct(cbTower) < 2) && grabTrucksAndBuild(cbTower, 0))
{
return;
}
}
}
if (!lookForOil() && buildDefenses())
{
return;
}
//log("All fundamental buildings built -- proceed to military stuff");
}
// Salvage research labs if there is nothing more to research.
function checkResearchCompletion()
{
var reslist = enumResearch();
if (!reslist.length)
{
//log("Done researching - salvage unusable buildings");
researchDone = true; // and do not rebuild them
var lablist = enumStruct(me, resLab);
for (var i = 0; i < lablist.length; i++)
{
if(demolishThis(lablist[i]))
{
break;
}
}
}
}
// Build modules and check research completion.
function maintenance()
{
//log("Maintenance check");
const MODULES = ["A0PowMod1", "A0ResearchModule1", "A0FacMod1", "A0FacMod1"];
const MOD_NUMBER = [1, 1, 2, 2]; //Number of modules paired with list above
var struct = null, module = "", structList = [];
var success = false;
for (var i = 0; i < MODULES.length; ++i)
{
if (isStructureAvailable(MODULES[i]) && (struct === null))
{
switch(i)
{
case 0: { structList = enumStruct(me, powGen); break; }
case 1: { structList = enumStruct(me, resLab); break; }
case 2: { structList = enumStruct(me, factory); break; }
case 3: { structList = enumStruct(me, vtolFactory); break; }
default: { break; }
}
for (var c = 0; c < structList.length; ++c)
{
if (structList[c].modules < MOD_NUMBER[i])
{
struct = structList[c];
module = MODULES[i];
break;
}
}
}
else
{
break;
}
}
if (struct)
{
//log("Found a structure to upgrade");
var builders = enumDroid(me, DROID_CONSTRUCT);
for (var j = 0; j < builders.length; j++)
{
mydroid = builders[j];
if (conCanHelp(mydroid, struct.x, struct.y))
{
if (orderDroidBuild(mydroid, DORDER_BUILD, module, struct.x, struct.y))
{
success = true;
}
}
}
}
if(checkResearchCompletion())
{
success = true;
}
return success;
}
| gpl-2.0 |
yugandhargangu/JspMyAdmin2 | application/jspmyadmin/src/main/java/com/jspmyadmin/app/database/structure/controllers/SuffixController.java | 2238 | /**
*
*/
package com.jspmyadmin.app.database.structure.controllers;
import java.sql.SQLException;
import com.jspmyadmin.app.database.structure.beans.StructureBean;
import com.jspmyadmin.app.database.structure.logic.StructureLogic;
import com.jspmyadmin.framework.constants.AppConstants;
import com.jspmyadmin.framework.constants.Constants;
import com.jspmyadmin.framework.web.annotations.Detect;
import com.jspmyadmin.framework.web.annotations.HandlePost;
import com.jspmyadmin.framework.web.annotations.Model;
import com.jspmyadmin.framework.web.annotations.ValidateToken;
import com.jspmyadmin.framework.web.annotations.WebController;
import com.jspmyadmin.framework.web.utils.RedirectParams;
import com.jspmyadmin.framework.web.utils.RequestLevel;
import com.jspmyadmin.framework.web.utils.View;
import com.jspmyadmin.framework.web.utils.ViewType;
/**
* @author Yugandhar Gangu
* @created_at 2016/02/16
*
*/
@WebController(authentication = true, path = "/database_structure_suffix.html", requestLevel = RequestLevel.DATABASE)
public class SuffixController {
@Detect
private RedirectParams redirectParams;
@Detect
private View view;
@Model
private StructureBean bean;
@HandlePost
@ValidateToken
private void suffixTables() {
StructureLogic structureLogic = null;
try {
structureLogic = new StructureLogic();
if (bean.getType() != null) {
if (Constants.ADD.equalsIgnoreCase(bean.getType())) {
structureLogic.addSuffix(bean);
redirectParams.put(Constants.MSG_KEY, AppConstants.MSG_EXECUTED_SUCCESSFULLY);
} else if (Constants.REPLACE.equalsIgnoreCase(bean.getType())) {
structureLogic.replaceSuffix(bean);
redirectParams.put(Constants.MSG_KEY, AppConstants.MSG_EXECUTED_SUCCESSFULLY);
} else if (Constants.REMOVE.equalsIgnoreCase(bean.getType())) {
structureLogic.removeSuffix(bean);
redirectParams.put(Constants.MSG_KEY, AppConstants.MSG_EXECUTED_SUCCESSFULLY);
} else if (Constants.COPY.equalsIgnoreCase(bean.getType())) {
redirectParams.put(Constants.MSG_KEY, Constants.BLANK);
}
}
} catch (SQLException e) {
redirectParams.put(Constants.ERR, e.getMessage());
}
view.setType(ViewType.REDIRECT);
view.setPath(bean.getAction());
}
}
| gpl-2.0 |
fqybzhangji/Crazy | Core/ACTIVITY100008.cs | 853 | //------------------------------------------------------------------------------
// <auto-generated>
// 此代码已从模板生成。
//
// 手动更改此文件可能导致应用程序出现意外的行为。
// 如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------
namespace Core
{
using System;
using System.Collections.Generic;
public partial class ACTIVITY100008
{
public string PROCINST { get; set; }
public string ACTIVITYINST { get; set; }
public string BelongOrganization { get; set; }
public string BelongOrgCode { get; set; }
public string ManageUnitName { get; set; }
public string ManageUnitCode { get; set; }
}
}
| gpl-2.0 |
N2maniac/springlobby-join-fork | src/qt/battlelistmodel.cpp | 2817 | /**
This file is part of SpringLobby,
Copyright (C) 2007-2010
SpringLobby is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
springsettings 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 SpringLobby. If not, see <http://www.gnu.org/licenses/>.
**/
#include "battlelistmodel.h"
#include <iserverevents.h>
#include <settings.h>
#include <server.h>
BattlelistModel::BattlelistModel(const wxString& modname, QObject *parent)
: QAbstractListModel(parent),
m_modname( modname )
{
QHash<int, QByteArray> roles;
roles[Description] = "description";
roles[Mapname] = "mapname";
roles[Founder] = "founder";
roles[PlayerCurrent] = "playerCurrent";
roles[PlayerMax] = "playerMax";
roles[BattleId] = "battleId";
setRoleNames(roles);
}
BattlelistModel::~BattlelistModel()
{}
int BattlelistModel::rowCount(const QModelIndex&/*parent*/ ) const
{
return m_battles.size();
}
QVariant BattlelistModel::data(const QModelIndex &index, int role ) const
{
int row = index.row();
if ( !index.isValid() || row >= m_battles.size() || !(m_battles[row]) )
return QVariant();
const Battle& battle = *m_battles[row];
switch ( role ) {
case Mapname:{
return FromwxString<QVariant>( battle.GetHostMapName() );
}
case Founder:
return FromwxString<QVariant>( battle.GetFounder().GetNick() );
case PlayerMax:
return QVariant::fromValue( battle.GetMaxPlayers() );
case PlayerCurrent:
return QVariant::fromValue( battle.GetNumPlayers() );
case BattleId:
return QVariant::fromValue( battle.GetID() );
case Description:
default: {
return FromwxString<QVariant>( battle.GetDescription() );
}
}
}
void BattlelistModel::reload()
{
m_battles.clear();
reset();
BattleList_Iter* iter = (serverSelector().GetServer().battles_iter);
if ( !iter )
return;
iter->IteratorBegin();
while( !(iter->EOL()) ) {
Battle* battle = iter->GetBattle();
if ( battle && battle->GetHostModName().Contains( _T("Evolu") ) )
m_battles.append( battle );
}
beginInsertRows(QModelIndex(), 0, m_battles.size() );
endInsertRows();
}
int BattlelistModel::battle_count()
{
BattleList_Iter* iter = (serverSelector().GetServer().battles_iter);
return iter ? iter->GetNumBattles() : -1;
}
| gpl-2.0 |
banjum/DataVisualizer-JAVA | src/com/ghc/foss/ds/List.java | 2341 | /*
* Copyright (C) 2015 banjum
*
* 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 com.ghc.foss.ds;
import java.util.ArrayList;
/**
*
* @author banjum
*/
public class List implements DataStructure{
//Implementinig List operations using ArrayList Container
ArrayList<Integer> list;
public List()
{
}
public void addRandomValues()
{
}
public void add (Integer element)
{
}
public Boolean remove(Integer element)
{
return false;
}
public void removeAll()
{
}
public Integer size()
{
return 0;
}
/**
* Get DISPLAY string, to visualize the List
* @param columns the number of columns in the final display area (TextArea)
* @return a formatted string to display the current state of the List
*/
@Override
public String getDisplayString(int columns)
{
String displayString=addHeadPointer(columns);
if(size()==0)
displayString+=Utility.addSpaces(9);
else
displayString+=Utility.addSpaces(5);
for(int i = 0;i<size();i++)
{
displayString+=list.get(i);
displayString+=Utility.addSpaces(3);
}
return displayString;
}
/***************************
//PRIVITE UTILITY FUNCTIONS
***************************/
//Create a string with appropriate spaces and a representation
//of a TOP arrow, pointing to the top of the Stack
private String addHeadPointer(int x)
{
String head = "\n HEAD\n |\n |\n *\n";
return head;
}
}
| gpl-2.0 |
KasenJ/CommunityPython | code/handler/GetArroundEvent.py | 806 | import tornado.ioloop
import tornado.web
import tornado.httpserver
from tornado.escape import *
import json
class GetArroundEvent(tornado.web.RequestHandler):
def get(self):
self.write("<p>GetArroundEvent</p><form action='/api/getAround' method='post'><input type='submit' value='submit'></form>")
def post(self):
content =self.request.body
j=json.loads(content)
user = self.application.dbapi.getUserInfobyName(j['username'])
if(user is None):
self.write("{'state':2}")
print "username not exist"
return
result = self.application.dbapi.getEventAround(user['longitude'],user['latitude'],5)
print result
for item in result:
item['avatar'] = self.application.util.getAvatar(item['name'],self.application.dbapi)
self.write("{'state':1,aids:"+json_encode(result)+"}")
return
| gpl-2.0 |
Automattic/simplenote-electron | lib/icons/new-note.tsx | 473 | import React from 'react';
export default function NewNoteIcon() {
return (
<svg
className="icon-new-note"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
>
<rect x="0" fill="none" width="24" height="24" />
<path d="M9.707 12.879L19.59 3 21 4.41l-9.879 9.883L9 15 9.707 12.879zM18 18H6V6h7V4H6.002C4.896 4 4 4.896 4 6.002v11.996C4 19.104 4.896 20 6.002 20h11.996C19.104 20 20 19.104 20 17.998V11h-2V18z" />
</svg>
);
}
| gpl-2.0 |
gfrd/modern_egfrd | test/TestGFRD/ParticleContainer_test.cpp | 6305 | #include <iostream>
#include <ParticleContainerImpl.hpp>
#include "ParticleContainer_test.hpp"
// --------------------------------------------------------------------------------------------------------------------------------
int testParticleContainer()
{
ParticleContainerImpl pc;
TINYTEST_EQUAL(pc.world_size().X(), 1.0);
TINYTEST_EQUAL(pc.world_size().Y(), 1.0);
TINYTEST_EQUAL(pc.world_size().Z(), 1.0);
TINYTEST_EQUAL(pc.cell_size(), 1.0 / CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc.matrix_size()[0], CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc.matrix_size()[1], CompileConfigSimulator::MatrixCellsY);
TINYTEST_EQUAL(pc.matrix_size()[2], CompileConfigSimulator::MatrixCellsZ);
TINYTEST_EQUAL(pc.num_particles(), 0);
ParticleID pid(10);
ParticleID pidn(11);
{
auto ir(pc.update_particle(std::make_pair(pid, Particle(SpeciesTypeID(1), Sphere(Vector3(0.2, 0.6, 0.4), 0.05), StructureID(0), 1E-5))));
TINYTEST_EQUAL(true, ir);
}
{
auto ir(pc.update_particle(std::make_pair(pid, Particle(SpeciesTypeID(1), Sphere(Vector3(0.3, 0.7, 0.5), 0.05), StructureID(0), 1E-5, 123.4))));
TINYTEST_EQUAL(false, ir);
}
TINYTEST_ASSERT(pc.has_particle(pid));
TINYTEST_ASSERT(!pc.has_particle(pidn));
auto pip = pc.get_particle(pid);
TINYTEST_EQUAL(pip.first, pid);
TINYTEST_ALMOST_EQUAL(pip.second.D(), 1E-5, 1E-15);
TINYTEST_ALMOST_EQUAL(pip.second.radius(), 0.05, 1E-15);
TINYTEST_ALMOST_EQUAL(pip.second.v(), 123.4, 1E-15);
TINYTEST_EQUAL(pip.second.position(), Vector3(0.3, 0.7, 0.5));
bool found;
auto pip2 = pc.get_particle(pid, found); // returns a copy! not a const ref to the real thing
TINYTEST_ASSERT(found);
TINYTEST_EQUAL(pip2.first, pid);
TINYTEST_ALMOST_EQUAL(pip2.second.D(), 1E-5, 1E-15);
TINYTEST_EQUAL(pip2.second.position(), Vector3(0.3, 0.7, 0.5));
auto pip3 = pc.get_particle(pidn, found);
TINYTEST_ASSERT(!found);
TINYTEST_EQUAL(pip3.first(), 0); // no id
pip2.second.position() = Vector3(13.0, 14.0, 15.0); // modify local copy
auto pip4 = pc.get_particle(pid); // no change in particle container
TINYTEST_ASSERT(pip2.second.position() != pip4.second.position());
return 1;
}
// --------------------------------------------------------------------------------------------------------------------------------
int testParticleContainerIterator()
{
ParticleContainerImpl pc;
TINYTEST_EQUAL(pc.world_size().X(), 1.0);
TINYTEST_EQUAL(pc.world_size().Y(), 1.0);
TINYTEST_EQUAL(pc.world_size().Z(), 1.0);
TINYTEST_EQUAL(pc.cell_size(), 1.0 / CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc.matrix_size()[0], CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc.matrix_size()[1], CompileConfigSimulator::MatrixCellsY);
TINYTEST_EQUAL(pc.matrix_size()[2], CompileConfigSimulator::MatrixCellsZ);
TINYTEST_EQUAL(pc.num_particles(), 0);
SerialIDGenerator<ParticleID> pgen;
const int size = 10;
for (int i = 0; i < size; i++)
{
double d = i / (size - 1.0);
Vector3 pos(0.5 + 0.5*d*std::sin(2.0*M_PI*i / 100), 0.5 + 0.5*d*std::cos(2.0*M_PI*i / 100), d); // spiral
auto ir(pc.update_particle(std::make_pair(pgen(), Particle(SpeciesTypeID(1), Sphere(pos, 0.05), StructureID(0), 1E-5, 99.99))));
TINYTEST_EQUAL(true, ir);
}
for (auto i : pc.get_particles())
{
const auto& particle = i.second;
Particle* pp = const_cast<Particle*>(&particle); // trick const_iterator into non_const, so we can modify the positions
pp->position() = -pp->position(); // not common practice, but just a check
std::cout << particle << std::endl;
}
return 1;
}
// --------------------------------------------------------------------------------------------------------------------------------
int testParticleContainerCopyConstruct()
{
ParticleContainerImpl pc1;
TINYTEST_EQUAL(pc1.world_size().X(), 1.0);
TINYTEST_EQUAL(pc1.world_size().Y(), 1.0);
TINYTEST_EQUAL(pc1.world_size().Z(), 1.0);
TINYTEST_EQUAL(pc1.cell_size(), 1.0 / CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc1.matrix_size()[0], CompileConfigSimulator::MatrixCellsX);
TINYTEST_EQUAL(pc1.matrix_size()[1], CompileConfigSimulator::MatrixCellsY);
TINYTEST_EQUAL(pc1.matrix_size()[2], CompileConfigSimulator::MatrixCellsZ);
TINYTEST_EQUAL(pc1.num_particles(), 0);
ParticleID pid1(10);
ParticleID pid2(11);
ParticleID pid3(12);
auto pc2 = pc1; // assignment
ParticleContainerImpl pc3(pc1); // copy construct
{
auto ir(pc1.update_particle(std::make_pair(pid1, Particle(SpeciesTypeID(1), Sphere(Vector3(0.2, 0.6, 0.4), 0.05), StructureID(0), 1E-5))));
TINYTEST_EQUAL(true, ir);
}
{
auto ir(pc2.update_particle(std::make_pair(pid2, Particle(SpeciesTypeID(1), Sphere(Vector3(0.2, 0.6, 0.4), 0.05), StructureID(0), 1E-5))));
TINYTEST_EQUAL(true, ir);
}
{
auto ir(pc3.update_particle(std::make_pair(pid3, Particle(SpeciesTypeID(1), Sphere(Vector3(0.2, 0.6, 0.4), 0.05), StructureID(0), 1E-5))));
TINYTEST_EQUAL(true, ir);
}
TINYTEST_ASSERT(pc1.has_particle(pid1));
TINYTEST_ASSERT(!pc1.has_particle(pid2));
TINYTEST_ASSERT(!pc1.has_particle(pid3));
TINYTEST_ASSERT(!pc2.has_particle(pid1));
TINYTEST_ASSERT(pc2.has_particle(pid2));
TINYTEST_ASSERT(!pc2.has_particle(pid3));
TINYTEST_ASSERT(!pc3.has_particle(pid1));
TINYTEST_ASSERT(!pc3.has_particle(pid2));
TINYTEST_ASSERT(pc3.has_particle(pid3));
return 1;
}
// --------------------------------------------------------------------------------------------------------------------------------
TINYTEST_START_SUITE(ParticleContainer);
TINYTEST_ADD_TEST(testParticleContainer);
TINYTEST_ADD_TEST(testParticleContainerIterator);
TINYTEST_ADD_TEST(testParticleContainerCopyConstruct);
TINYTEST_END_SUITE();
// -------------------------------------------------------------------------------------------------------------------------------- | gpl-2.0 |
Roma48/moesto | administrator/components/com_acymailing/views/file/tmpl/share.php | 1718 | <?php
/**
* @package AcyMailing for Joomla!
* @version 4.9.3
* @author acyba.com
* @copyright (C) 2009-2015 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><div id="acy_content">
<form action="index.php?tmpl=component&option=<?php echo ACYMAILING_COMPONENT ?>" method="post" name="adminForm" id="adminForm" autocomplete="off">
<fieldset class="acyheaderarea">
<div class="acyheader icon-48-share" style="float: left;"><?php echo JText::_('SHARE').' : '.$this->file->name; ?></div>
<div class="toolbar" id="toolbar" style="float: right;">
<table><tr>
<td><a onclick="if(confirm('<?php echo JText::_('CONFIRM_SHARE_TRANS',true); ?>')){ javascript:submitbutton('send');} return false;" href="#" ><span class="icon-32-share" title="<?php echo JText::_('SHARE',true); ?>"></span><?php echo JText::_('SHARE'); ?></a></td>
</tr></table>
</div>
</fieldset>
<fieldset class="adminform">
<?php acymailing_display(JText::_('SHARE_CONFIRMATION_1').'<br />'.JText::_('SHARE_CONFIRMATION_2').'<br />'.JText::_('SHARE_CONFIRMATION_3'),'info'); ?><br />
<textarea rows="8" name="mailbody" style="width:700px">Hi Acyba team,
Here is a new version of the language file, I translated few more strings...</textarea>
</fieldset>
<div class="clr"></div>
<input type="hidden" name="code" value="<?php echo $this->file->name; ?>" />
<input type="hidden" name="option" value="<?php echo ACYMAILING_COMPONENT; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="ctrl" value="file" />
<?php echo JHTML::_( 'form.token' ); ?>
</form>
</div>
| gpl-2.0 |
shophelfer/shophelfer.com-shop | lang/german/modules/payment/billsafe_2hp.php | 9492 | <?php
/* -----------------------------------------------------------------------------------------
$Id: billsafe_2hp.php 4200 2013-01-10 19:47:11Z Tomcraft1980 $
modified eCommerce Shopsoftware
http://www.modified-shop.org
Copyright (c) 2009 - 2013 [www.modified-shop.org]
-----------------------------------------------------------------------------------------
based on:
Copyright (c) 2013 PayPal SE and Bernd Blazynski
Released under the GNU General Public License
---------------------------------------------------------------------------------------*/
/*
* id = billsafe_2hp.php
* location = /lang/german/modules/payment
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @package BillSAFE_2
* @copyright (C) 2013 Bernd Blazynski
* @license GPLv2
*/
define('MODULE_PAYMENT_BILLSAFE_2HP_TEXT_TITLE', 'Kauf auf Raten');
define('MODULE_PAYMENT_BILLSAFE_2HP_CHECKOUT_TEXT_INFO', 'Kaufen Sie bequem und schnell in %d Raten ab %s Euro/Monat. <br />(eff. Jahreszins: %s%%)');
//define('MODULE_PAYMENT_BILLSAFE_2HP_CHECKOUT_TEXT_INFO', 'Kaufen Sie bequem und schnell in %d Raten ab %s Euro/Monat. <br />(Bearbeitungsgebühr: %s eff. Jahreszins: %s%%)');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_COMMON', 'Leider ist der Kauf auf Raten nicht möglich. Bitte wählen Sie eine andere Zahlungsweise.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_101', 'Der Kauf auf Raten steht derzeit leider nicht zur Verfügung, bitte wählen Sie eine andere Zahlungsweise.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_102', 'Bei der Datenübertragung ist ein Fehler aufgetreten. Bitte kontaktieren Sie uns.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_215', 'Bei der Datenübertragung sind nicht alle erforderlichen Parameter übergeben worden. Bitte kontaktieren Sie uns.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_216', 'Bei der Datenübertragung sind ungültige Parameter übergeben worden. Bitte kontaktieren Sie uns.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_COMPANY', 'Der Kauf auf Raten ist leider nur für Privatpersonen möglich.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ERROR_MESSAGE_ADDRESS', 'Der Kauf auf Raten ist leider nicht bei abweichender Lieferadresse möglich.');
define('MODULE_PAYMENT_BILLSAFE_2HP_STATUS_TEXT', 'Status');
define('MODULE_PAYMENT_BILLSAFE_2HP_TRANSACTIONID', 'BillSAFE Transaktions-ID');
define('MODULE_PAYMENT_BILLSAFE_2HP_CODE_TEXT', 'Code');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_TEXT', 'Message');
define('MODULE_PAYMENT_BILLSAFE_2HP_TEXT_DESCRIPTION', '<img src="images/icon_popup.gif" border="0" /> <a href="https://client.billsafe.de" target="_blank" rel="noopener" style="text-decoration: underline; font-weight: bold;">Zur BillSAFE-Website</a>');
define('MODULE_PAYMENT_BILLSAFE_2HP_STATUS_TITLE', 'BillSAFE Ratenkauf aktivieren');
define('MODULE_PAYMENT_BILLSAFE_2HP_STATUS_DESC', 'Möchten Sie Kauf auf Raten mit BillSAFE anbieten?');
define('MODULE_PAYMENT_BILLSAFE_2HP_MERCHANT_ID_TITLE', 'Merchant-ID');
define('MODULE_PAYMENT_BILLSAFE_2HP_MERCHANT_ID_DESC', 'Die Merchant-ID, die mit der BillSAFE-API genutzt wird.');
define('MODULE_PAYMENT_BILLSAFE_2HP_MERCHANT_LICENSE_TITLE', 'Merchant-License');
define('MODULE_PAYMENT_BILLSAFE_2HP_MERCHANT_LICENSE_DESC', 'Die Merchant-License, die mit der BillSAFE-API genutzt wird.');
define('MODULE_PAYMENT_BILLSAFE_2HP_MIN_ORDER_TITLE', 'Mindest-Bestellwert');
define('MODULE_PAYMENT_BILLSAFE_2HP_MIN_ORDER_DESC', 'Betrag, ab dem Kauf auf Rate mit BillSAFE angeboten wird.');
define('MODULE_PAYMENT_BILLSAFE_2HP_MAX_ORDER_TITLE', 'Höchst-Bestellwert');
define('MODULE_PAYMENT_BILLSAFE_2HP_MAX_ORDER_DESC', 'Betrag, bis zu dem Kauf auf Rate mit BillSAFE angeboten wird.');
define('MODULE_PAYMENT_BILLSAFE_2HP_BILLSAFE_LOGO_URL_TITLE', 'BillSAFE Logo URL');
define('MODULE_PAYMENT_BILLSAFE_2HP_BILLSAFE_LOGO_URL_DESC', 'Speicherort des BillSAFE-Logos.');
define('MODULE_PAYMENT_BILLSAFE_2HP_SHOP_LOGO_URL_TITLE', 'Shop Logo URL');
define('MODULE_PAYMENT_BILLSAFE_2HP_SHOP_LOGO_URL_DESC', 'Speicherort des Shop-Logos.');
define('MODULE_PAYMENT_BILLSAFE_2HP_SERVER_TITLE', 'BillSAFE Server');
define('MODULE_PAYMENT_BILLSAFE_2HP_SERVER_DESC', 'Benutzen Sie das "LIVE"- oder "SANDBOX"-Gateway zur Zahlungsabwicklung?');
define('MODULE_PAYMENT_BILLSAFE_2HP_ZONE_TITLE', 'Zahlungszone');
define('MODULE_PAYMENT_BILLSAFE_2HP_ZONE_DESC', 'Wenn eine Zone ausgewählt ist, gilt die Zahlungsmethode nur für diese Zone.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ORDER_STATUS_ID_TITLE', 'Bestellstatus festlegen');
define('MODULE_PAYMENT_BILLSAFE_2HP_ORDER_STATUS_ID_DESC', 'Bestellungen, welche mit diesem Modul gemacht werden, auf diesen Status setzen.');
define('MODULE_PAYMENT_BILLSAFE_2HP_SORT_ORDER_TITLE', 'Anzeigereihenfolge');
define('MODULE_PAYMENT_BILLSAFE_2HP_SORT_ORDER_DESC', 'Reihenfolge der Anzeige. Kleinste Ziffer wird zuerst angezeigt.');
define('MODULE_PAYMENT_BILLSAFE_2HP_ALLOWED_TITLE', 'Erlaubte Zonen');
define('MODULE_PAYMENT_BILLSAFE_2HP_ALLOWED_DESC', 'Geben Sie <b>einzeln</b> die Zonen an, welche für dieses Modul erlaubt sein sollen. (z. B. AT,DE (wenn leer, werden alle Zonen erlaubt))');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_FSHIPMENT', 'Komplettlieferung war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_PSHIPMENT', 'Teillieferung war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_FSTORNO', 'Komplettstornierung war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_PSTORNO', 'Teilstornierung war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_FRETOURE', 'Komplettretoure war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_PRETOURE', 'Teilretoure war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_VOUCHER', 'Anbietergutschrift war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_MESSAGE_PAUSETRANSACTION', 'Zahlungspause war erfolgreich');
define('MODULE_PAYMENT_BILLSAFE_2HP_DETAILS', 'BillSAFE Details');
define('MODULE_PAYMENT_BILLSAFE_2HP_BADDRESS', 'Rechnungsadresse (BillSAFE)');
define('MODULE_PAYMENT_BILLSAFE_2HP_SADDRESS', 'Versandadresse');
define('MODULE_PAYMENT_BILLSAFE_2HP_EMAIL', 'E-Mail');
define('MODULE_PAYMENT_BILLSAFE_2HP_PDETAILS', 'Ratenkauf Details');
define('MODULE_PAYMENT_BILLSAFE_2HP_NOTE', 'Hinweis');
define('MODULE_PAYMENT_BILLSAFE_2HP_PRODUCTS', 'Artikel');
define('MODULE_PAYMENT_BILLSAFE_2HP_MODEL', 'Artikel-Nr.');
define('MODULE_PAYMENT_BILLSAFE_2HP_TAX', 'MwSt.');
define('MODULE_PAYMENT_BILLSAFE_2HP_PRICE_EX', 'Preis (exkl.)');
define('MODULE_PAYMENT_BILLSAFE_2HP_PRICE_INC', 'Preis (inkl.)');
define('MODULE_PAYMENT_BILLSAFE_2HP_CHECK', 'Auswahl');
define('MODULE_PAYMENT_BILLSAFE_2HP_INC', 'inkl. ');
define('MODULE_PAYMENT_BILLSAFE_2HP_FREPORT_SHIPMENT', 'Komplettlieferung');
define('MODULE_PAYMENT_BILLSAFE_2HP_PREPORT_SHIPMENT', 'Teillieferung');
define('MODULE_PAYMENT_BILLSAFE_2HP_UPDATEARTICLELISTSTORNOFULL', 'Komplettstornierung');
define('MODULE_PAYMENT_BILLSAFE_2HP_UPDATEARTICLELISTSTORNOPART', 'Teilstornierung');
define('MODULE_PAYMENT_BILLSAFE_2HP_UPDATEARTICLELISTRETOUREFULL', 'Komplettretoure');
define('MODULE_PAYMENT_BILLSAFE_2HP_UPDATEARTICLELISTRETOUREPART', 'Teilretoure');
define('MODULE_PAYMENT_BILLSAFE_2HP_UPDATEARTICLELISTVOUCHER', 'Anbietergutschrift');
define('MODULE_PAYMENT_BILLSAFE_2HP_PREPORT_METHOD', 'Methode');
define('MODULE_PAYMENT_BILLSAFE_2HP_PREPORT_DATE', 'Datum');
define('MODULE_PAYMENT_BILLSAFE_2HP_JALERT', 'Bitte wählen Sie mindestens ein Produkt aus.');
define('MODULE_PAYMENT_BILLSAFE_2HP_NO_ORDERID', 'Bestellnummer konnte nicht gefunden werden.');
define('MODULE_PAYMENT_BILLSAFE_2HP_VAT', '% MwSt.');
define('MODULE_PAYMENT_BILLSAFE_2HP_VALUE', 'Warenwert');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_TITLE', 'Log aktivieren');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_DESC', 'BillSAFE-Server Rückmeldungen zur Fehlersuche verwenden.');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_TYPE_TITLE', 'Log-Art auswählen: Echo, per eMail senden lassen oder als Datei im Verzeichnis "/export" speichern lassen.');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_TYPE_DESC', '<b>Achtung</b>: "Echo" ist nur für Testzwecke im Backend des Shops gedacht. <b>Es sind keine Bestellungen möglich!</b>');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_ADDR_TITLE', 'eMail-Adresse(n) für das Log');
define('MODULE_PAYMENT_BILLSAFE_2HP_LOG_ADDR_DESC', 'Mehrere eMail-Adressen mit "," trennen.');
define('MODULE_PAYMENT_BILLSAFE_2HP_MP', 'Händlerportal');
define('MODULE_PAYMENT_BILLSAFE_2HP_BUTTON', 'Zu BillSAFE');
define('MODULE_PAYMENT_BILLSAFE_2HP_LAYER_TITLE', 'Payment Layer');
define('MODULE_PAYMENT_BILLSAFE_2HP_LAYER_DESC', 'Möchten Sie den Layer-Modus für Zahlungen per BillSAFE aktivieren? <b>Achtung: Unbedingt in den <i>Sessions</i>-Einstellungen den Parameter <i>Cookie Benutzung bevorzugen</i> auf <i>False</i> setzen!</b>');
?> | gpl-2.0 |
JensTimmerman/vsc-manage | setup.py | 2328 | ##
# Copyright 2011-2013 Ghent University
#
# This file is part of vsc-manage,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/vsc-manage
#
# vsc-manage 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 v2.
#
# vsc-manage 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 vsc-manage. If not, see <http://www.gnu.org/licenses/>.
# #
# All rights reserved.
#
##
"""
vsc-manage distribution setup.py
@author: Jens Timmerman <[email protected]>
"""
try:
import vsc.install.shared_setup as shared_setup
from vsc.install.shared_setup import jt
except ImportError:
print "vsc.install could not be found, make sure a recent vsc-base is installed"
print "you might want to try 'easy_install [--user] https://github.com/hpcugent/vsc-base/archive/master.tar.gz'"
def remove_bdist_rpm_source_file():
"""List of files to remove from the (source) RPM."""
return ['lib/vsc/__init__.py']
shared_setup.remove_extra_bdist_rpm_files = remove_bdist_rpm_source_file
shared_setup.SHARED_TARGET.update({
'url': 'https://github.ugent.be/hpcugent/vsc-manage',
'download_url': 'https://github.ugent.be/hpcugent/vsc-manage'
})
PACKAGE = {
'name': 'vsc-manage',
'version': '1.6.5',
'author': [jt],
'maintainer': [jt],
'packages': ['vsc', 'vsc.manage'],
'namespace_packages': ['vsc'],
'scripts': ['bin/misty.py'],
'data_files': [('/etc', ['config/manage_defaults.cfg'])],
'install_requires': [
'libxml2-python',
'paramiko',
'pycrypto >= 1.9',
],
}
if __name__ == '__main__':
shared_setup.action_target(PACKAGE)
| gpl-2.0 |
iVerb1/AmazonCloudEncode | Controller/node_modules/network/lib/linux.js | 2335 | "use strict";
//////////////////////////////////////////
// by Tomas Pollak - http://forkhq.com
//////////////////////////////////////////
var os = require('os'),
exec = require('child_process').exec;
/**
* If no wifi, then there is no error but cbed get's a null in second param.
**/
exports.get_active_network_interface_name = function(cb) {
var cmd = "netstat -rn | grep UG | awk '{print $NF}'";
exec(cmd, function(err, stdout) {
if (err) return cb(err);
var raw = stdout.toString().trim().split('\n');
if (raw.length === 0 || raw === [''])
return cb(new Error('No active network interface found.'));
cb(null, raw[0]);
});
};
exports.interface_type_for = function(nic_name, cb) {
exec('cat /proc/net/wireless | grep ' + nic_name, function(err, out) {
return cb(null, err ? 'Wired' : 'Wireless')
})
};
exports.mac_address_for = function(nic_name, cb) {
var cmd = "ifconfig | grep " + nic_name + " | grep 'HWaddr' | awk '{print $5}'";
exec(cmd, cb);
};
exports.gateway_ip_for = function(nic_name, cb) {
exec("ip r | grep " + nic_name + " | grep default | cut -d ' ' -f 3", cb);
};
exports.netmask_for = function(nic_name, cb) {
var cmd = "ifconfig " + nic_name + " 2> /dev/null | grep 'Mask:' | awk '{print $4}'";
exec(cmd, function(err, stdout) {
if (err) return cb(err);
var out = stdout.toString(),
netmask = (out !== '') && out.replace('Mask:', '').split("\n")[0];
cb(null, netmask);
});
};
exports.get_network_interfaces_list = function(cb) {
var count = 0,
list = [],
nics = os.networkInterfaces();
var append_data = function(obj) {
exports.mac_address_for(obj.name, function(err, res) {
if (!err && res)
obj.mac_address = res.trim();
exports.interface_type_for(obj.name, function(err, res) {
if (!err && res)
obj.type = res;
list.push(obj);
--count || cb(null, list);
})
})
}
for (var key in nics) {
if (key != 'lo0' && key != 'lo' && !key.match(/^tun/)) {
count++;
var obj = { name: key };
nics[key].forEach(function(type) {
if (type.family == 'IPv4') {
obj.ip_address = type.address;
}
});
append_data(obj);
}
}
if (count == 0)
cb(new Error('No interfaces found.'))
}
| gpl-2.0 |
indexcosmos/renzi | wp-content/themes/apartvilla/includes/modules/shortcodes/location_address.php | 296 | <?php ob_start(); ?>
<li class="clearfix">
<div class="name">
<h3><?php echo balanceTags($title);?></h3>
<p><?php echo balanceTags($address);?></p>
</div>
<div class="distance">
<?php echo balanceTags($miles);?>
</div>
</li>
<?php return ob_get_clean(); | gpl-2.0 |
adamfranco/polyphony | main/library/GUIWizardComponents/Utilities/GUIComponentUtility.class.php | 6155 | <?php
/**
* @since 8/15/2006
* @package polyphony.guiwizardcomponents
*
* @copyright Copyright © 2006, Middlebury College
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License (GPL)
*
* @version $Id: GUIComponentUtility.class.php,v 1.5 2007/09/19 14:04:46 adamfranco Exp $
*/
/**
* This class allows for the modification of an entire "level" of theme.
*
* @since 8/09/2006
* @package polyphony.guiwizardcomponents
*
* @copyright Copyright © 2006, Middlebury College
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License (GPL)
*
* @version $Id: GUIComponentUtility.class.php,v 1.5 2007/09/19 14:04:46 adamfranco Exp $
*/
class GUIComponentUtility{
/**
*
* Make an array of colors complete with styles. The colors are arranged by hue families.
*
* @param int slices The number of families. 6-15 is probably good.
* @param int trisize Proportional with the square root of the size of each family 4 to 6 is probably good.
* @return array an array with the values at 'options' and styles in 'styles'
*/
function makeColorArrays($slices, $triSize){
$options = array();
$styles = array();
$options[''] = "Default";
$styles[''] = "";
for($dark = 0; $dark <=$triSize; $dark++){
$goalDark = 255.99 * $dark / $triSize;
$arr = GUIComponentUtility::addColor($goalDark,$goalDark,$goalDark);
$val0 = $arr[0];
$val1 = $arr[1];
$options[$val0]=$val0;
$styles[$val0]=$val1;
}
for($rot = 0; $rot<$slices; $rot++){
$angle_R = ($rot /$slices) * 2 * M_PI+M_PI*1/3;
$angle_G = ($rot /$slices) * 2 * M_PI+M_PI*5/3;
$angle_B = ($rot /$slices) * 2 * M_PI+M_PI*3/3;
$baseR = 128+ 127.99*sin($angle_R);
$baseG = 128+ 127.99*sin($angle_G);
$baseB = 128+ 127.99*sin($angle_B);
for($dark = $triSize; $dark > 0; $dark--){
$baseDarknessR = $baseR * $dark / $triSize;
$baseDarknessG = $baseG * $dark / $triSize;
$baseDarknessB = $baseB * $dark / $triSize;
$goalDark = 255.99 * $dark / $triSize;
for($gray = 0; $gray < $dark; $gray++){
$actual_r = $baseDarknessR * ($dark -$gray) + $goalDark*$gray;
$actual_g = $baseDarknessG * ($dark -$gray) + $goalDark*$gray;
$actual_b = $baseDarknessB * ($dark -$gray) + $goalDark*$gray;
$actual_r /= $dark;
$actual_g /= $dark;
$actual_b /= $dark;
$arr = GUIComponentUtility::addColor($actual_r,$actual_g,$actual_b);
$val0 = $arr[0];
$val1 = $arr[1];
$options[$val0] = $val0;
$styles[$val0] = $val1;
}
}
}
//this hack takes care of the fact that I really want to return them both.
$ret = array();
$ret['options'] = $options;
$ret['styles'] = $styles;
return $ret;
}
function addColor($r, $g, $b){
$hexR = strtoupper(dechex(intval($r)));
if($r <16) $hexR = "0".$hexR;
$hexG = strtoupper(dechex(intval($g)));
if($g <16) $hexG = "0".$hexG;
$hexB = strtoupper(dechex(intval($b)));
if($b <16) $hexB = "0".$hexB;
$val = '#'.$hexR.$hexG.$hexB;
//num measures the "brightness" of the color.
//I think green is "brighter" than red and red "brighter" than blue.
$num = $r*2+$g*3+$b;
//Our threshold is 750.
if($num > 750){
$col = "#000000";
}else{
$col = "#FFFFFF";
}
return array($val,"font-family: monospace; color: ".$col."; background-color:".$val.";");
}
function makeFontArray(){
$options = array("serif","sans-serif","cursive","fantasy","monospace");
foreach($options as $option){
$ret[$option]=$option;
}
return $ret;
}
function makeFontSizeArray(){
$options = array("8pt","10pt","12pt","14pt","16pt","18pt","20pt","22pt","24pt","26pt");
foreach($options as $option){
$ret[$option]=$option;
}
return $ret;
}
function makeBorderSizeArrays(){
$arr = array("0px","1px","2px","3px","4px","5px","6px","8px","10px","14px");
foreach($arr as $option){
$options[$option]=$option;
$styles[$option]="border-width: ".$option."; margin 3; padding 3;";
}
$ret = array('options'=>$options,'styles'=>$styles);
return $ret;
}
function makeMarginAndPaddingArray(){
$arr = array("0px","1px","2px","3px","4px","5px","6px","8px","10px","12px","16px","20px","25px","30px","35px","40px","45px","50px","60px","70px","80px","100px","125px","150px","175px","200px","225px","250px","275px","300px","350px","400px","-0px","-1px","-2px","-3px","-4px","-5px","-6px","-8px","-10px","-12px","-16px","-20px","-25px","-30px","-35px","-40px","-45px","-50px","-60px","-70px","-80px","-100px","-125px","-150px","-175px","-200px","-225px","-250px","-275px","-300px","-350px","-400px","2%","5%","10%","15%","20%","25%","30%","35%","40%","50%","60%","75%","-2%","-5%","-10%","-15%","-20%","-25%","-30%","-35%","-40%","-50%","-60%","-75%","-100%","-125%","-150%","-200%","-250%","-300%","-400%");
foreach($arr as $option){
$options[$option]=$option;
}
return $options;
}
function makeBorderStyleArrays(){
$arr = array("none", "dotted", "dashed",
"solid", "groove", "ridge",
"inset", "outset", "double");
foreach($arr as $option){
$options[$option]=$option;
$styles[$option]="margin: 6px 3px; padding: 3px; border-style: ".$option.";";
}
$ret = array('options'=>$options,'styles'=>$styles);
return $ret;
}
function makeSpacingArray(){
$arr = array("normal","-5px", "-3px", "-2px","-1px", "0px","1px", "2px","3px","5px", "7px", "10px");
foreach($arr as $option){
$options[$option]=$option;
}
return $options;
}
function makeLineSpacingArray(){
$options = array("normal","50%","75%","90%","100%","125%","150%","175%","200%","250%");
foreach($options as $option){
$ret[$option]=$option;
}
return $ret;
}
function makeAlignArray(){
$options = array("left","center","right","justified");
foreach($options as $option){
$ret[$option]=$option;
}
return $ret;
}
} | gpl-2.0 |
creasyw/IMTAphy | framework/library/src/ldk/SequentlyCallingLinkHandler.hpp | 3142 | /*******************************************************************************
* This file is part of openWNS (open Wireless Network Simulator)
* _____________________________________________________________________________
*
* Copyright (C) 2004-2007
* Chair of Communication Networks (ComNets)
* Kopernikusstr. 5, D-52074 Aachen, Germany
* phone: ++49-241-80-27910,
* fax: ++49-241-80-22242
* email: [email protected]
* www: http://www.openwns.org
* _____________________________________________________________________________
*
* openWNS is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License version 2 as published by the
* Free Software Foundation;
*
* openWNS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#ifndef WNS_LDK_SEQUENTLYCALLINGLINKHANDLER_HPP
#define WNS_LDK_SEQUENTLYCALLINGLINKHANDLER_HPP
#include <WNS/ldk/LinkHandlerInterface.hpp>
#include <WNS/ldk/Compound.hpp>
#include <WNS/pyconfig/View.hpp>
#include <WNS/logger/Logger.hpp>
#include <list>
namespace wns { namespace ldk {
class FunctionalUnit;
class SequentlyCallingLinkHandler :
virtual public LinkHandlerInterface
{
struct FUCompound
{
FUCompound() :
fu(NULL),
compound(wns::ldk::CompoundPtr())
{} // FUCompound
FUCompound(FunctionalUnit* _fu, const CompoundPtr& _compound) :
fu(_fu),
compound(_compound)
{} // FUCompound
FunctionalUnit* fu;
CompoundPtr compound;
};
typedef std::list<FUCompound> FUCompoundContainer;
typedef std::list<FunctionalUnit*> FUContainer;
public:
SequentlyCallingLinkHandler(const wns::pyconfig::View& _config);
virtual bool
isAcceptingForwarded(FunctionalUnit* fu, const CompoundPtr& compound);
virtual void
sendDataForwarded(FunctionalUnit* fu, const CompoundPtr& compound);
virtual void
wakeupForwarded(FunctionalUnit* fu);
virtual void
onDataForwarded(FunctionalUnit* fu, const CompoundPtr& compound);
private:
void
sendDataHandler(FunctionalUnit* fu, const CompoundPtr& compound);
void
wakeupHandler(FunctionalUnit* fu);
void
onDataHandler(FunctionalUnit* fu, const CompoundPtr& compound);
void
mainHandler();
bool inAction;
FUContainer pendingCompoundsContainingFUs;
int sendDataPending;
FUCompound sendDataFUCompound;
FUContainer wakeupFUs;
bool inWakeup;
FUContainer wakeupFUsInWakeup;
FUCompoundContainer onDataFUCompounds;
bool traceCompoundJourney;
wns::logger::Logger isAcceptingLogger;
wns::logger::Logger sendDataLogger;
wns::logger::Logger wakeupLogger;
wns::logger::Logger onDataLogger;
};
} // ldk
} // wns
#endif // NOT defined WNS_LDK_SEQUENTLYCALLINGLINKHANDLER_HPP
| gpl-2.0 |
rsathishkumar/drupal8 | core/tests/Drupal/Tests/Core/PageCache/CommandLineOrUnsafeMethodTest.php | 2287 | <?php
namespace Drupal\Tests\Core\PageCache;
use Drupal\Core\PageCache\RequestPolicyInterface;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* @coversDefaultClass \Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod
* @group PageCache
*/
class CommandLineOrUnsafeMethodTest extends UnitTestCase {
/**
* The request policy under test.
*
* @var \Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod|\PHPUnit_Framework_MockObject_MockObject
*/
protected $policy;
protected function setUp() {
// Note that it is necessary to partially mock the class under test in
// order to disable the isCli-check.
$this->policy = $this->getMockBuilder('Drupal\Core\PageCache\RequestPolicy\CommandLineOrUnsafeMethod')
->setMethods(['isCli'])
->getMock();
}
/**
* Asserts that check() returns DENY for unsafe HTTP methods.
*
* @dataProvider providerTestHttpMethod
* @covers ::check
*/
public function testHttpMethod($expected_result, $method) {
$this->policy->expects($this->once())
->method('isCli')
->will($this->returnValue(FALSE));
$request = Request::create('/', $method);
$actual_result = $this->policy->check($request);
$this->assertSame($expected_result, $actual_result);
}
/**
* Provides test data and expected results for the HTTP method test.
*
* @return array
* Test data and expected results.
*/
public function providerTestHttpMethod() {
return [
[NULL, 'GET'],
[NULL, 'HEAD'],
[RequestPolicyInterface::DENY, 'POST'],
[RequestPolicyInterface::DENY, 'PUT'],
[RequestPolicyInterface::DENY, 'DELETE'],
[RequestPolicyInterface::DENY, 'OPTIONS'],
[RequestPolicyInterface::DENY, 'TRACE'],
[RequestPolicyInterface::DENY, 'CONNECT'],
];
}
/**
* Asserts that check() returns DENY if running from the command line.
*
* @covers ::check
*/
public function testIsCli() {
$this->policy->expects($this->once())
->method('isCli')
->will($this->returnValue(TRUE));
$request = Request::create('/', 'GET');
$actual_result = $this->policy->check($request);
$this->assertSame(RequestPolicyInterface::DENY, $actual_result);
}
}
| gpl-2.0 |
bayasist/vbox | out/linux.amd64/debug/obj/vboxjxpcom-gen/jxpcomgen/java/glue/IDirectory.java | 2940 |
/*
* Copyright (C) 2010-2014 Oracle Corporation
*
* This file is part of the VirtualBox SDK, as available from
* http://www.virtualbox.org. This library is free software; you can
* redistribute it and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation, in version 2.1
* as it comes in the "COPYING.LIB" file of the VirtualBox SDK distribution.
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* IDirectory.java
*
* DO NOT EDIT! This is a generated file.
* Generated from: src/VBox/Main/idl/VirtualBox.xidl (VirtualBox's interface definitions in XML)
* Generator: src/VBox/Main/glue/glue-java.xsl
*/
package org.virtualbox_4_3;
import org.virtualbox_4_3.xpcom.*;
import org.mozilla.interfaces.*;
import java.util.List;
public class IDirectory extends IUnknown
{
public IDirectory(org.mozilla.interfaces.IDirectory wrapped)
{
super(wrapped);
}
public org.mozilla.interfaces.IDirectory getTypedWrapped()
{
return (org.mozilla.interfaces.IDirectory) getWrapped();
}
public String getDirectoryName()
{
try
{
String retVal = getTypedWrapped().getDirectoryName();
return retVal;
}
catch (org.mozilla.xpcom.XPCOMException e)
{
throw new VBoxException(e.getMessage(), e);
}
}
public String getFilter()
{
try
{
String retVal = getTypedWrapped().getFilter();
return retVal;
}
catch (org.mozilla.xpcom.XPCOMException e)
{
throw new VBoxException(e.getMessage(), e);
}
}
public static IDirectory queryInterface(IUnknown obj)
{
nsISupports nsobj = obj != null ? (nsISupports)obj.getWrapped() : null;
if (nsobj == null) return null;
org.mozilla.interfaces.IDirectory qiobj = Helper.queryInterface(nsobj, "{1b70dd03-26d7-483a-8877-89bbb0f87b70}", org.mozilla.interfaces.IDirectory.class);
return qiobj == null ? null : new IDirectory(qiobj);
}
public void close()
{
try
{
getTypedWrapped().close();
}
catch (org.mozilla.xpcom.XPCOMException e)
{
throw new VBoxException(e.getMessage(), e);
}
}
public org.virtualbox_4_3.IFsObjInfo read()
{
try
{
org.mozilla.interfaces.IFsObjInfo retVal;
retVal = getTypedWrapped().read();
return (retVal != null) ? new org.virtualbox_4_3.IFsObjInfo(retVal) : null;
}
catch (org.mozilla.xpcom.XPCOMException e)
{
throw new VBoxException(e.getMessage(), e);
}
}
}
| gpl-2.0 |
mohittahiliani/adaptive-RED-ns3 | src/network/examples/red_vs_ared.cc | 7290 | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2015 NITK Surathkal
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mohit P. Tahiliani <[email protected]>
* Thanks to: Authors of droptail_vs_red.cc
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/point-to-point-layout-module.h"
#include <iostream>
#include <iomanip>
#include <map>
using namespace ns3;
int main (int argc, char *argv[])
{
uint32_t nLeaf = 10;
uint32_t maxPackets = 100;
uint32_t modeBytes = 0;
double minTh = 5;
double maxTh = 15;
uint32_t pktSize = 512;
std::string appDataRate = "10Mbps";
std::string queueType = "RED";
uint16_t port = 5001;
std::string bottleNeckLinkBw = "1Mbps";
std::string bottleNeckLinkDelay = "50ms";
CommandLine cmd;
cmd.AddValue ("nLeaf", "Number of left and right side leaf nodes", nLeaf);
cmd.AddValue ("maxPackets","Max Packets allowed in the queue", maxPackets);
cmd.AddValue ("queueType", "Set Queue type to RED or ARED", queueType);
cmd.AddValue ("appPktSize", "Set OnOff App Packet Size", pktSize);
cmd.AddValue ("appDataRate", "Set OnOff App DataRate", appDataRate);
cmd.AddValue ("modeBytes", "Set Queue mode to Packets <0> or bytes <1>", modeBytes);
cmd.AddValue ("redMinTh", "RED queue minimum threshold", minTh);
cmd.AddValue ("redMaxTh", "RED queue maximum threshold", maxTh);
cmd.Parse (argc,argv);
if ((queueType != "RED") && (queueType != "ARED"))
{
std::cout << "Invalid queue type: Use --queueType=RED or --queueType=ARED" << std::endl;
exit (1);
}
Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (pktSize));
Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue (appDataRate));
if (queueType == "ARED")
{
// Adaptive RED Configuration
minTh = maxTh = 0;
Config::SetDefault ("ns3::RedQueue::Adaptive", BooleanValue (true));
Config::SetDefault ("ns3::RedQueue::QW", DoubleValue (0.0));
Config::SetDefault ("ns3::RedQueue::LInterm", DoubleValue (10.0));
}
if (!modeBytes)
{
Config::SetDefault ("ns3::RedQueue::Mode", StringValue ("QUEUE_MODE_PACKETS"));
Config::SetDefault ("ns3::RedQueue::QueueLimit", UintegerValue (maxPackets));
}
else
{
Config::SetDefault ("ns3::RedQueue::Mode", StringValue ("QUEUE_MODE_BYTES"));
Config::SetDefault ("ns3::RedQueue::QueueLimit", UintegerValue (maxPackets * pktSize));
minTh *= pktSize;
maxTh *= pktSize;
}
// Create the point-to-point link helpers
PointToPointHelper bottleNeckLink;
bottleNeckLink.SetDeviceAttribute ("DataRate", StringValue (bottleNeckLinkBw));
bottleNeckLink.SetChannelAttribute ("Delay", StringValue (bottleNeckLinkDelay));
bottleNeckLink.SetQueue ("ns3::RedQueue",
"MinTh", DoubleValue (minTh),
"MaxTh", DoubleValue (maxTh),
"LinkBandwidth", StringValue (bottleNeckLinkBw),
"LinkDelay", StringValue (bottleNeckLinkDelay));
PointToPointHelper pointToPointLeaf;
pointToPointLeaf.SetDeviceAttribute ("DataRate", StringValue ("10Mbps"));
pointToPointLeaf.SetChannelAttribute ("Delay", StringValue ("1ms"));
PointToPointDumbbellHelper d (nLeaf, pointToPointLeaf,
nLeaf, pointToPointLeaf,
bottleNeckLink);
// Install Stack
InternetStackHelper stack;
d.InstallStack (stack);
// Assign IP Addresses
d.AssignIpv4Addresses (Ipv4AddressHelper ("10.1.1.0", "255.255.255.0"),
Ipv4AddressHelper ("10.2.1.0", "255.255.255.0"),
Ipv4AddressHelper ("10.3.1.0", "255.255.255.0"));
// Install on/off app on all right side nodes
OnOffHelper clientHelper ("ns3::TcpSocketFactory", Address ());
clientHelper.SetAttribute ("OnTime", StringValue ("ns3::UniformRandomVariable[Min=0.,Max=1.]"));
clientHelper.SetAttribute ("OffTime", StringValue ("ns3::UniformRandomVariable[Min=0.,Max=1.]"));
Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port));
PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress);
ApplicationContainer sinkApps;
for (uint32_t i = 0; i < d.LeftCount (); ++i)
{
sinkApps.Add (packetSinkHelper.Install (d.GetLeft (i)));
}
sinkApps.Start (Seconds (0.0));
sinkApps.Stop (Seconds (30.0));
ApplicationContainer clientApps;
for (uint32_t i = 0; i < d.RightCount (); ++i)
{
// Create an on/off app sending packets to the left side
AddressValue remoteAddress (InetSocketAddress (d.GetLeftIpv4Address (i), port));
clientHelper.SetAttribute ("Remote", remoteAddress);
clientApps.Add (clientHelper.Install (d.GetRight (i)));
}
clientApps.Start (Seconds (1.0)); // Start 1 second after sink
clientApps.Stop (Seconds (15.0)); // Stop before the sink
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
std::cout << "Running the simulation" << std::endl;
Simulator::Run ();
uint32_t totalRxBytesCounter = 0;
for (uint32_t i = 0; i < sinkApps.GetN (); i++)
{
Ptr <Application> app = sinkApps.Get (i);
Ptr <PacketSink> pktSink = DynamicCast <PacketSink> (app);
totalRxBytesCounter += pktSink->GetTotalRx ();
}
if (queueType == "RED")
{
if (totalRxBytesCounter > 2738700)
{
std::cout << "RED Goodput is too high, should be about 9290.57 Bytes/sec" << std::endl;
exit (-1);
}
else if (totalRxBytesCounter < 2322400)
{
std::cout << "RED Goodput is too low, should be about 9290.57 Bytes/sec" << std::endl;
exit (-1);
}
}
else if (queueType == "ARED")
{
if (totalRxBytesCounter > 2756100)
{
std::cout << "ARED Goodput is too high, should be about 10300.5 Bytes/sec" << std::endl;
exit (-1);
}
else if (totalRxBytesCounter < 2317300)
{
std::cout << "ARED Goodput is too low, should be about 10300.5 Bytes/sec" << std::endl;
exit (-1);
}
}
std::cout << "----------------------------\nQueue Type:"
<< queueType
<< "\nGoodput Bytes/sec:"
<< totalRxBytesCounter/Simulator::Now().GetSeconds() << std::endl;
std::cout << "----------------------------" << std::endl;
std::cout << "Destroying the simulation" << std::endl;
Simulator::Destroy ();
return 0;
}
| gpl-2.0 |
Queexie/Feudalism | src/main/java/com/valarmorghulismc/feudalism/chunk/types/ChunkTickRunnable.java | 1664 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.valarmorghulismc.feudalism.chunk.types;
import com.valarmorghulismc.feudalism.chunk.ChunkInfo;
import com.valarmorghulismc.feudalism.chunk.ChunkLocation;
import com.valarmorghulismc.feudalism.house.House;
/**
*
* @author ZNickq
*/
public class ChunkTickRunnable implements Runnable {
private int timeFarmNotTicked = 0;
public ChunkTickRunnable() {
/*for(ChunkType cs : ChunkType.getAll()) {
int tick = cs.getTickIntervalInMins();
if(tick != -1) {
shouldTick.put(cs, cs.getTickIntervalInMins());
}
}*/
timeFarmNotTicked = ChunkType.PASTURE.getTickIntervalInMins();
}
public void run() {
/* - old system, only need farms right now!
Set<ChunkType> cs = new HashSet<ChunkType>();
for(ChunkType ctt : shouldTick.keySet()) {
int howMuch = shouldTick.get(ctt);
howMuch--;
//System.out.println(ctt.getName()+": "+howMuch);
if(howMuch == 0) {
cs.add(ctt);
shouldTick.put(ctt, ctt.getTickIntervalInMins());
} else {
shouldTick.put(ctt, howMuch);
}
}*/
//System.out.println("Ticking that shit! "+cs.size());
timeFarmNotTicked--;
if(timeFarmNotTicked != 0) {
return;
}
timeFarmNotTicked = ChunkType.PASTURE.getTickIntervalInMins();
for (String nname : House.getAllHouses().keySet()) {
House house = House.getAllHouses().get(nname);
for (ChunkLocation cll : house.getAllOwnedChunks()) {
ChunkType ttype = ChunkInfo.getChunkInfo(cll).getType();
if(ttype == null) {
continue;
}
if (ttype == ChunkType.PASTURE) {
ttype.onTick(cll);
}
}
}
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/epo/src/com/mediatek/epo/test/EpoTCRunner.java | 1016 | package com.mediatek.epo.test;
import junit.framework.TestSuite;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.AndroidTestCase;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
import android.util.Log;
import android.app.Activity;
import android.os.Bundle;
public class EpoTCRunner extends InstrumentationTestRunner {
private final String TAG = "epo_test";
@Override
public TestSuite getAllTests() {
log("getAllTests");
TestSuite suite = new InstrumentationTestSuite(this);
suite.addTestSuite(EpoTC.class);
return suite;
}
@Override
public ClassLoader getLoader() {
log("getLoader");
return EpoTCRunner.class.getClassLoader();
}
@Override
public void onCreate(Bundle arguments) {
log("onCreate arg=" + arguments);
super.onCreate(arguments);
}
private void log(String msg) {
Log.d(TAG, msg);
}
} | gpl-2.0 |
ldsc/lib_ldsc | src/AnaliseImagem/Simulacao/ConfiguracaoEquilibrio/CConfiguracoesEquilibrio3D.cpp | 32117 | /**
----------------------------------------------------------------------------
PROJETO: LIB_LDSC
Bibliotecas de Objetos
----------------------------------------------------------------------------
Desenvolvido por: Laboratorio de Desenvolvimento de Software Cientifico.
Programadores: Andre D.Bueno, Celso P.Fernandez, Fabio S.Magnani,
* Liang Zirong, Paulo C. Philippi, Damiani,...
Copyright @1997: Todos os direitos reservados.
Nome deste arquivo: CConfiguracoesEquilibrio3D.h
Nome da classe: CConfiguracoesEquilibrio3D
Arquivos de documentacao do projeto em: path\documentacao\*.doc, path\Help
==================================================================================
Documentacao Classe: CConfiguracoesEquilibrio3D
==================================================================================
Assunto: CConfiguracoesEquilibrio3D
Superclasse:
Descrição: Declara a classe TConfiguracoesEquilibrio.
Acesso:
Cardinalidade:
Abstrata/Concreta:
Arquivo de documentacao auxiliar:
----------------------------------------------------------------------------
*/
#include <iomanip>
#include <string>
#include <sstream>
#include <cstdio>
using namespace std;
#include <AnaliseImagem/Simulacao/ConfiguracaoEquilibrio/CConfiguracoesEquilibrio3D.h>
#include <Base/COperacao.h>
#include <AnaliseImagem/Filtro/FEspacial/FEMorfologiaMatematica/TCFEMMIDFd3453D.h>
#include <AnaliseImagem/Filtro/FEspacial/FEMorfologiaMatematica/TCFEMMIDFEuclidiana3D.h>
/** Metodo construtor.
* Recebe uma ostream os, por default std::cout.
* Seta os atributos da classe,
* e cria alguns objetos dinâmicos, como a camara e os fluidos.
*/
CConfiguracoesEquilibrio3D::CConfiguracoesEquilibrio3D ( /*TCMatriz3D<int> * imagem */ ostream & out) {
os = &out; // temporaria, para saida tela
salvarResultadosParciaisDisco = 0; // temporario
salvarResultadosFinaisDisco = 1; // salvar resultados finais em disco
corrigirAbertura = 0;
visualizar = 0; // temporario
contadorPassosExecutados = 0; // zera o contador de passo executados. (necessário para Next)
idf = nullptr;
rotulador = nullptr;
camara = nullptr;
camara = new CCamara3D (); // Cria objetos agregados
COperacao::TestaAlocacao (camara, "objeto camara, construtor CConfiguracoesEquilibrio3");
fluidoA = new CMFluido (); // que podem ser alterados usando
fluidoB = new CMFluido (); // confEqui->fluidoA->atributo
COperacao::TestaAlocacao (fluidoB, "objeto fluidoB, construtor CConfiguracoesEquilibrio3");
tipoIDF = 345; // usa por default a métrica d345
CConfiguracoesEquilibrio3D::DefineAtributos ();
}
/// Metodo que seta os atributos do objeto.
void CConfiguracoesEquilibrio3D::DefineAtributos () {
// 0=solido ou paredes
// 1=poros
/*
B0 = 4; // 2;// indices das diferentes regiões geométricas
A0 = 5;
B = 4; // magnani=4
A = 5; // magnani=5
Ai = 2; // ?nao usado
G = 3; // 6;
G_ = 6;
// Y0=8;
Yi = 3; // magnani=3
KGB0 = 7;
wbG__U_KGB0 = 10; // verificar?
KwbG__U_KGB0B0 = 9;
*/
// Y0=8;
Yi = 2; //19660
B0 = 3; //26214
B = 3; //26214
G = 4; //19660
G_ = 5; //39321
A0 = 6; //32768
A = 6; //32768
KGB0 = 7; //45875
wbG__U_KGB0 = 8; //52428
KwbG__U_KGB0B0 = 9; // 65535
Ai = 10; //13107 // nao usado????
raioMaximo = 50; // Raio máximo e minimo a ser utilizado no processo
raioMinimo = 1;
}
/// Destrutor, destrói atributos dinâmicos.
CConfiguracoesEquilibrio3D::~CConfiguracoesEquilibrio3D () {
if (camara)
delete camara;
if (idf)
delete idf;
if (rotulador)
delete rotulador;
if (fluidoA)
delete fluidoA;
if (fluidoB)
delete fluidoB;
}
/** Metodo que cria a camara. Usa a idf d345 para determinar o raioMaximo (usa somente a imagem),
Observe que na imagem da camara o raio maximo pode ser maior em do espaço da própria camara.
*/
void CConfiguracoesEquilibrio3D::CriaCamara (TCMatriz3D<int> * &imagem) {
if (camara) {
delete camara;
camara = nullptr;
camara = new CCamara3D ();
}
if (contadorPassosExecutados == 0)
Salvar (imagem, "0-imagemInicial");
{
TCFEMMIDFd3453D<int> idfp (imagem); // BUG: verificar se nao esta deletando a imagem
idfp.Go (imagem);
int maiorValor = idfp.MaiorValor ();
raioMaximo = (maiorValor % 3 == 0) ? maiorValor / 3 : 1 + maiorValor / 3;
// raioMaximo= ( maiorValor % idfp.Getmi() == 0)?
// maiorValor / idfp.Getmi(): 1+maiorValor/idfp.Getmi();// antes idf->Getmi()=3
}
// Define as propriedades da camara
camara->DimensoesPadroes (raioMaximo); // wb=0 // wb=1
camara->CamaraInferior (fluidoB->Molhabilidade () == 0 ? 2 * raioMaximo + 1 : 1); // 5=membrana+2
camara->CamaraSuperior (fluidoB->Molhabilidade () == 0 ? 1 : 2 * raioMaximo + 1); // 5->1
camara->MembranaInferior (fluidoB->Molhabilidade () == 0 ? 0 : 2); // 3->2
camara->MembranaSuperior (fluidoB->Molhabilidade () == 0 ? 2 : 0); // 3->2
// Define os indices das camaras superior e inferior
camara->IndiceCamaraInferior (B0);
camara->IndiceCamaraSuperior (A0);
// Aloca a camara, define as paredes e copia imagem
camara->CriaCamara (imagem);
// *os<<" \nDados objeto camara criacao camara\n";
// *os<<*camara<<endl;
// if(imagem!=nullptr)
// delete imagem;
// imagem=nullptr;// Deleta a imagem recebida, economia.
}
/// Metodo que cria a idf
void CConfiguracoesEquilibrio3D::CriaIDF () {
if (idf)
delete idf; // Se já existe deleta
idf = nullptr;
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
switch (tipoIDF) { // Cria objeto idf selecionado
case 345:
idf = new TCFEMMIDFd3453D<int> (ptr_camara);
break;
default:
idf = new TCFEMMIDFEuclidiana3D<int> (ptr_camara);
break;
}
COperacao::TestaAlocacao (idf, "objeto idf, funcao CConfiguracoesEquilibrio3D::CriaIDF");
idf->Go (ptr_camara); // Calcula a idf
idf->INDICE = G; // Define indice da matriz apos operacao abertura
int maiorValor = idf->MaiorValor (); // Calcula o raioMaximo
// abaixo usava idf->Getmi() = 3, verificar
raioMaximo = (maiorValor % idf->Mi () == 0) ? maiorValor / idf->Mi () : 1 + maiorValor / idf->Mi ();
TCMatriz3D<int> * ptr_idf = static_cast<TCMatriz3D<int> *>(idf); // Salvar recebe TCImagem3D*
Salvar (ptr_idf, string("1-imagemIDF"));
}
/// Metodo que cria objeto de rotulagem
void CConfiguracoesEquilibrio3D::CriaRotulador () {
if (rotulador)
delete rotulador; // Deleta objeto de conectividade anterior
rotulador = nullptr;
rotulador = new CConectividade3D (camara); // Cria novo objeto rotulador
COperacao::TestaAlocacao (rotulador, "objeto rotulador, funcao CConfiguracoesEquilibrio3D::Go");
}
/// Abertura: Calcula a abertura sobre a IDF da camara
void CConfiguracoesEquilibrio3D::CalculaAbertura (int &raio) {
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
idf->Abertura (ptr_camara, raio); // Determina as regiões abertura na camara
Salvar (ptr_camara, "2.0-imagem-%d-G-(4)"); // ....Tem na camara(0,G=4)...
if ( corrigirAbertura ) {
idf->CorrigeAbertura(ptr_camara, G);
Salvar (ptr_camara, "2.1-imagem-%d-G-(corrigida)"); // imagem G corrigida para não apresentar erro físico.
}
//está salvando a máscara somente para estudo. Depois comentar...
TCMatriz3D<int> * ptr_mask = static_cast<TCMatriz3D<int> *>(idf->mask);
ptr_mask->Path(ptr_camara->Path());
Salvar (ptr_mask, "2.2-mask-%d");
// Abaixo só é necessário se for usar G-
// OBS: Como agora só calcula KGB0 ou wbG_U_KGB0 o passo abaixo é desnecesário.
/* if(fluidoB->Molhabilidade()==1) // se wb=1 considera G_
for(int i=0;i<camara->NX();i++) // Usa a propria IDF para armazenar o resultado da abertura.
for(int j=0;j<camara->NY();j++) // se pertence a região verde complementar (G_)
if(camara->data3D[i][j]==G) // inverte o sinal na idf
idf->data3D[i][j]= - idf->data3D[i][j];// idf com sinal negativo indica região G, + G_
int larguraCampoOld=idf->larguraCampo;
idf->larguraCampo=4;
Salvar(idf,"3-imagemIDF-GG_-%d.dgm"); // salva idf_G_G em disco
idf->larguraCampo=larguraCampoOld;
*/
}
/// Metodo que determina conectividade entre K(G,B0)
// é chamada em next quando b for não molhante
void CConfiguracoesEquilibrio3D::ConectividadeKGB0 () {
camara->DefineCamaraInferior (); // Redesenha camara inferior, eliminada na abertura
// ....Tem na camara(0,G=3,B0=4)...
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
rotulador->Go (ptr_camara); // Realiza a rotulagem
TCMatriz3D<int> * ptr_rotulador = static_cast<TCMatriz3D<int> *> (rotulador);
Salvar (ptr_rotulador, "4-imagem-%d-G+B0-Rotulada"); // salva imagem rotulada
// Verifica a conectividade entre B0 e G, e pinta a regiao conexa com KGB0
rotulador->VerificaConectividade (G, B0, KGB0);
// rotulador->VerificaConectividade(G,B0,B);// Verifica a conectividade entre B0 e G, e pinta a regiao conexa com KGB0
Salvar (ptr_camara, "5-imagem-%d-K(G,B0)-(0,3,7)"); // ....Tem na camara(0,G,KGB0)...
indiceParcialB = KGB0; // Define o indiceParcial para B
}
/// Metodo que determina a uniao G_U K(G,B0)]
// é chamada em next quando b for molhante
void CConfiguracoesEquilibrio3D::UniaoG__U_KGB0 () {
for (int i = 0; i < camara->NX (); i++) // Percorre a imagem
for (int j = 0; j < camara->NY (); j++)
for (int k = 0; k < camara->NZ (); k++)
if (idf->data3D[i][j][k] > 0 && camara->data3D[i][j][k] == 0) // complemento da abertura
camara->data3D[i][j][k] = wbG__U_KGB0; // =8, a união pode ser pintada com um único índice wbG-_U_KGB0
else
camara->data3D[i][j][k] = 0; // o restante passa a ser zero
// ....Tem na camara(0,wbG-_U_KGB0)...
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
Salvar (ptr_camara, "6-imagem-%d-wbG__U_K(G,B0)-(0,8)"); // 0,wbG-_U_KGB0=8,
}
/// Metodo que determina a conectividade entre K{ [G_U K(G,B0)],B0)}
// é chamada em next, após UniaoG__U_KGB0 (), quando b for molhante
void CConfiguracoesEquilibrio3D::ConectividadeKwbG__U_KGB0B0 () {
// redesenha camara inferior (B0), eliminada na verificacao da conectividade
camara->DefineCamaraInferior ();
// ....Tem na camara(0,wbG__U_KGB0,B0)...
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
rotulador->Go (ptr_camara); // 2 rotulagem
TCMatriz3D<int> * ptr_rotulador = static_cast<TCMatriz3D<int> *> (rotulador);
// ....Tem na camara(0,wbG__U_KGB0=8,KwbG__U_KGB0B0=9,)...
Salvar (ptr_rotulador, "7.0-imagem-%d-wbG__U_KGB0B0-rotulada");
rotulador->VerificaConectividade (wbG__U_KGB0, B0, KwbG__U_KGB0B0);
indiceParcialB = KwbG__U_KGB0B0; // == 9
Salvar (ptr_camara, "7.1-imagem-%d-KwbG__U_KGB0B0-Omega-(0,8,9)");
// ....Tem na camara(0,wbG__U_KGB0=8,KwbG__U_KGB0B0=9,)...
}
/** Metodo que determina a solução de Omega isto é, os valores de B, o restante e Y
Aqui a imagem tem (B->indiceRegiaoB, 0, A0, um outro indice que representa Y)
*/
void CConfiguracoesEquilibrio3D::SolucaoOmega (int &indiceRegiaoB, TCMatriz3D<int> * &imagem) {
// Marca Yi como sendo os valores que estao na idf e nao pertencem a região B
for (int i = 0; i < camara->NX (); i++)
for (int j = 0; j < camara->NY (); j++) // Transformacao OPCIONAL
for (int k = 0; k < camara->NZ (); k++) // Se pertence a imagem (idf) e nao a região B então é Yi
if (idf->data3D[i][j][k] != 0 && camara->data3D[i][j][k] != indiceRegiaoB)
camara->data3D[i][j][k] = Yi;
else
camara->data3D[i][j][k] = 0;
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
Salvar (ptr_camara, "7.2-imagem-%d-Yi-(0,2)"); // Aqui tem 0,Yi
// Funcao DeterminaA0()
// Aqui determina a regiao conexa a A0, Definindo a forma final (A0,Y,B), sem considerar Yi anterior
camara->DefineCamaraSuperior (); // redesenha camara superior (indices: 0,B,A0,Y)
Salvar (ptr_camara, "7.3-imagem-%d-Yi+camaraSuperior-(0,3,5)"); // Aqui tem 0, B,Yi,A0
// Verificar conectividade (Y,A0,A0)
rotulador->Go (ptr_camara); // precisa re-rotular a imagem,(3 rotulagem)
rotulador->VerificaConectividade (Yi, A0, A0); // verifica a conectividade de Yi com A0 e marca como A0
Salvar (ptr_camara, "8.1-imagem-%d-Yi+A0-(0,3,5)");// Aqui tem 0, Yi,A0
// Funcao DeterminaB()
// 1-Acima, eliminou B da camara,
// 2- recoloca os valores de B na camara
// 3-Ja considera B da imagem anterior.
int DeslocX = camara->DeslocamentoNX (); // obtem deslocamento para posicao
int DeslocY = camara->DeslocamentoNY (); // inicial da imagem na camara
int DeslocZ = camara->DeslocamentoNZ (); //
int ti, tj, tk; // variaveis temporarias otimizacao
for (int i = 0; i < imagem->NX (); i++) { // percorre a imagem
ti = i + DeslocX;
for (int j = 0; j < imagem->NY (); j++) {
tj = j + DeslocY;
for (int k = 0; k < imagem->NZ (); k++) {
tk = k + DeslocZ;
if (idf->data3D[ti][tj][tk] != 0 && // pertence a imagem (IDF) e não é Yi ou A0, entao é B.
camara->data3D[ti][tj][tk] != Yi &&
camara->data3D[ti][tj][tk] != A0 ||
imagem->data3D[i][j][k] == B // ou, se esta na imagem anterior era B
) {
camara->data3D[ti][tj][tk] = B; // pinta de B
}
}
}
}
/* // Recoloca valor de B
for(int i=0;i<camara->NX();i++)
for(int j=0;j<camara->NY();j++) // Transformacao OPCIONAL
for(int k=0;k<camara->NZ();k++) // se pertence a imagem e nao é Yi ou A0
if(idf->data3D[i][j][k]!=0 && camara->data3D[i][j][k]!=Yi && camara->data3D[i][j][k]!=A0)
camara->data3D[i][j][k]=B;
*/
Salvar (ptr_camara, "8.2-imagem-%d-Yi+B+A0-(0,3,4,5)"); // Aqui tem 0, Yi,A0
}
/** Metodo que determina a CorrecaocaxYi
Determinação
da região Yi (ca=1)
Aqui ja tenho a solução da região OMEGA,se ca=1 imcompressivel, precisa considerar ca*Yi
Aqui a camara tem a solucao para Omega no instante de tempo atual,
A imagem tem a solucao no instante anterior
Devo eliminar Yi da solucao de Omega, B=Omega-ca*Yi ~ Omega-ca*(Yi-1)
*/
void CConfiguracoesEquilibrio3D::CorrecaocaxYi (TCMatriz3D<int> * &imagem) {
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
int valorAnteriorPixel;
for (int i = 0; i < imagem->NX (); i++)
for (int j = 0; j < imagem->NY (); j++)
for (int k = 0; k < imagem->NZ (); k++) // Se for Yi,na imagem (instante de tempo anterior)
if (imagem->data3D[i][j][k] == Yi) // pinta como Yi na camara (coisas que eram B passam a ser Yi)
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = Yi;
else if (imagem->data3D[i][j][k] == B) // Novo, pinta B da imagem anterior, visto que B nao retrocede (processo primario)
// corrigindo, erro do codigo original, que permitia retrocesso de fluido B
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = B;
TCMatriz3D<int> * ptr_camara = static_cast<TCMatriz3D<int> *>(camara);
Salvar (ptr_camara, "9-imagem-%d-K{WBxG__U_K(G,B0),B0}-caYi");
// CorrecaoBolas();
}
/// Metodo que determina a SolucaoFinal(), e salva em disco
// Tarefa: Pensar em Criar: SetdeslocX(), SetdeslocY(), Write..
void CConfiguracoesEquilibrio3D::SolucaoFinal (TCMatriz3D<int> * &imagem) {
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
int Va = 0, Vb = 0, Vy = 0; // volume dos fluídos A, B e Y. Para cálculo da saturação.
for (int i = 0; i < imagem->NX (); i++) {
for (int j = 0; j < imagem->NY (); j++) {
for (int k = 0; k < imagem->NZ (); k++) {
// Copia a solucao final para a imagem
imagem->data3D[i][j][k] = camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ];
// Acumula valores de A e B (todos os poros da imagem são A ou Yi ou B)
if (int r = imagem->data3D[i][j][k]) {
if ( r == A ) {
Va++;
} else if ( r == B ) {
Vb++;
} else if ( r == Yi ) {
Vy++;
}
}
}
}
}
saturacaoA = (double)Va / (double)(Va + Vb + Vy);
saturacaoB = (double)Vb / (double)(Va + Vb + Vy);
if (salvarResultadosFinaisDisco) {
ostringstream out;
out << "10-imagemFinal-" << contadorPassosExecutados;
fluidoB->Molhabilidade() == 1 ? out << "-wb1" : out << "-wb0";
fluidoA->Compressibilidade () == 1 ? out <<"-ca1" : out <<"-ca0";
out << ".dgm";
nomeArquivo = out.str(); // não precisa do nomeArquivo, tirar?
// novidade
imagem->SetFormato (D2_X_Y_Z_GRAY_ASCII);
imagem->NumCores( imagem->MaiorValor() );
imagem->Write (nomeArquivo); // A cada passo, deve salvar a configuracao final de equilibrio
}
}
/// Metodo que reestabelece os valores positivos na IDF
void CConfiguracoesEquilibrio3D::RestabeleceIDFPositiva () {
for (int i = 0; i < idf->NX (); i++) { // Percorre a imagem idf
for (int j = 0; j < idf->NY (); j++) { // e restabelece os valores negativos->para positivos,
for (int k = 0; k < idf->NZ (); k++) {
if (idf->data3D[i][j][k] < 0) { // para evitar erro na operção de abertura
idf->data3D[i][j][k] = -idf->data3D[i][j][k];
}
}
}
}
}
/// Metodo que determina a diferença em relação ao artigo
/// AQUI DIFERENÇA DA VERSAO DO ARTIGO PARA O CODIGO:
/// No artigo faz: K(G,B0)
/// No codigo faz: K(G-Yi,B0)
/// APÓS REALIZAR OPERACAO ABERTURA, MARCA PONTOS Y DA IMAGEM ANTERIOR
void CConfiguracoesEquilibrio3D::DiferencaEmRelacaoArtigo (TCMatriz3D<int> *&imagem) {
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
for (int i = 0; i < imagem->NX (); i++)
for (int j = 0; j < imagem->NY (); j++)
for (int k = 0; k < imagem->NZ (); k++)
if (imagem->data3D[i][j][k] == Yi) // Se for Yi,na imagem (instante de tempo anterior)
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = 0; // pinta como Yi na camara (coisas que eram B passam a ser Yi)
}
/// Metodo que salva imagem em disco
/// Note que inclui informações como wb1 wb0 ca0 ca1
void CConfiguracoesEquilibrio3D::Salvar (TCMatriz3D<int> * &imagem, string msg) {
char nomeArquivo[255];
string buffer = msg;
buffer += (fluidoB->Molhabilidade () == 1) ? "-wb1" : "-wb0";
buffer += (fluidoA->Compressibilidade () == 1) ? "-ca1" : "-ca0"; // 2007 estava trocado
buffer += ".dgm";
// Substitue o %d pelo contadorPassosExecutados
// porque nao usar o raio? porque o raio pode estar diminuindo.
sprintf (nomeArquivo, buffer.c_str (), contadorPassosExecutados);
if (salvarResultadosParciaisDisco == 1) {
imagem->SetFormato(D2_X_Y_Z_GRAY_ASCII);
int cores = imagem->MaiorValor();
imagem->NumCores( (cores >= 2) ? cores : cores+2 );
imagem->Write (nomeArquivo);
}
if (visualizar == 1) {
(*os) << "\nTarefa: Arrumar a linha 416 do arquivo CConfiguracoesEquilibrio3D.cpp:\n\n" ;
//(*os) << (*imagem) << "\n" ;
//(*os) << nomeArquivo;
cin.get ();
}
}
// retorna ponteiro para uma CMatriz3D que aponta para uma imagem da região informada, extraída da câmara.
// esta função deve ser chamada após Next ou Go.
TCMatriz3D<int> * CConfiguracoesEquilibrio3D::GetImagem(int regiao) const {
TCMatriz3D<int> * imagem = nullptr;
imagem = new TCMatriz3D<int>(camara->NxImg(), camara->NyImg(), camara->NzImg()); // aloca matriz 3D com as dimensões da imagem da câmara
if ( ! imagem ) return nullptr;
if ( GetImagem( imagem , regiao ) )
return imagem;
else
return nullptr;
}
// Altera os valores da matriz passsada como parametro para corresponder a imagem binária referente a regiao passada como parâmetro.
// esta função deve ser chamada após Next ou Go.
bool CConfiguracoesEquilibrio3D::GetImagem(TCMatriz3D<int> * &imagem, int regiao) const {
if ( ! imagem ) return false;
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
// verifica se as dimensões da imagem passada como parâmetro são as mesmas da imagem na camara
if ( ( imagem->NX() != camara->NxImg() ) || ( imagem->NY() != camara->NyImg() ) || ( imagem->NZ() != camara->NzImg() ) ) {
imagem->Redimensiona(camara->NxImg(), camara->NyImg(), camara->NzImg()); // aloca matriz 3D com as dimensões da imagem da câmara
if ( ! imagem ) return false;
}
int nx = imagem->NX();
int ny = imagem->NY();
int nz = imagem->NZ();
for (int i = 0; i < nx; i++)
for (int j = 0; j < ny; j++)
for (int k = 0; k < nz; k++)
{ // Se o pixel analizado na camara corresponder ao valor da região informada.
if (camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] == regiao)
// Atribui o valor da região ao pixel da imagem.
imagem->data3D[i][j][k] = 1; // Tarefa: verificar se funciona retornar a regiao = regiao
else // Se o pixel analizado não corresponder a região.
// Atribui o valor 0 ao pixel da imagem.
imagem->data3D[i][j][k] = 0;
}
return true;
}
/*
// Usada para inverter o sentido do fluxo
void CConfiguracoesEquilibrio3D::InverterFluxo()
{
camara->SetFormato(WRITEFORM_DI_X_Y_Z_GRAY_ASCII);
int cores = camara->MaiorValor();
camara->NumCores( (cores >= 2) ? cores : cores+2 );
camara->Write ("imagemCamaraAntesInverterFluxo.dgm");
// Pega valores usados no método
int nximg = camara->NxImg();
int nyimg = camara->NyImg();
int nzimg = camara->NzImg();
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
// Faz uma cópia da imagem do meio poroso contida na camara
CMatriz3D pmCopia( nximg, nyimg, nzimg );
for (int i = 0; i < nximg; i++)
for (int j = 0; j < nyimg; j++)
for (int k = 0; k < nzimg; k++)
pmCopia.data3D[i][j][k] = camara->data3D[i+DeslocX][j+DeslocY][k+DeslocZ];
// Inverte as propriedades dos fluidos (compressibilidade e molhabilidade)
bool compressibilidadeTmp = fluidoB->Compressibilidade();
bool molhabilidadeTmp = fluidoB->Molhabilidade();
fluidoB->Compressibilidade( fluidoA->Compressibilidade() );
fluidoB->Molhabilidade( fluidoA->Molhabilidade() );
fluidoA->Compressibilidade( compressibilidadeTmp );
fluidoA->Molhabilidade( molhabilidadeTmp );
// se a molhabilidade do Fluido B foi alterada, redefine valores de dimensões das membranas e camaras inferiores e superiores
// sempre muda : if ( fluidoB->Molhabilidade () != molhabilidadeTmp )
{
//raioMaximo foi setado com outro valor. Não pode usar a mesma regra. Resolvido com a implementação abaixo.
//camara->CamaraInferior (fluidoB->Molhabilidade () == 0 ? 2 * raioMaximo + 1 : 1);
//camara->CamaraSuperior (fluidoB->Molhabilidade () == 0 ? 1 : 2 * raioMaximo + 1);
//camara->MembranaInferior (fluidoB->Molhabilidade () == 0 ? 0 : 2);
//camara->MembranaSuperior (fluidoB->Molhabilidade () == 0 ? 2 : 0);
int camaraInferiorTmp = camara->CamaraInferior();
int membranaInferiorTmp = camara->MembranaInferior();
camara->CamaraInferior ( camara->CamaraSuperior() );
camara->CamaraSuperior ( camaraInferiorTmp );
camara->MembranaInferior ( camara->MembranaSuperior() );
camara->MembranaSuperior ( membranaInferiorTmp );
}
// Zera a camara e redefine...
camara->Constante( 0 );
camara->DefineCamara();
// Atualiza valores de deslocamento
DeslocX = camara->DeslocamentoNX ();
DeslocY = camara->DeslocamentoNY ();
DeslocZ = camara->DeslocamentoNZ ();
// Inverte a Imagem e redefine na nova camara. [ (B vira A) e (A ou Yi vira B) o restante é 0 ]
for (int i = 0; i < nximg; i++)
for (int j = 0; j < nyimg; j++)
for (int k = 0; k < nzimg; k++)
if ( pmCopia.data3D[i][j][k] == B )
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = A;
else if ( ( pmCopia.data3D[i][j][k] == A ) or ( pmCopia.data3D[i][j][k] == Yi ) )
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = B;
//else
// camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = 0;
// Recalcula a IDF da camara
CriaIDF();
CriaRotulador(); // Cria o objeto de rotulagem, passando a camara
// raio = fluidoB->Molhabilidade() == 0 ? raioMaximo : raioMinimo;
//só corrige a abertura na drenagem.
corrigirAbertura = false;
camara->Write ("imagemCamaraDepoisInverterFluxo.dgm");
}
*/
// Usada para inverter o sentido do fluxo
void CConfiguracoesEquilibrio3D::InverterFluxo( TCMatriz3D<int> * &imagem ) {
camara->SetFormato(D2_X_Y_Z_GRAY_ASCII);
int cores = camara->MaiorValor();
camara->NumCores( (cores >= 2) ? cores : cores+2 );
camara->Write ("imagemCamaraAntesInverterFluxo.dgm");
// Pega valores usados no método
int nximg = camara->NxImg();
int nyimg = camara->NyImg();
int nzimg = camara->NzImg();
int DeslocX = camara->DeslocamentoNX ();
int DeslocY = camara->DeslocamentoNY ();
int DeslocZ = camara->DeslocamentoNZ ();
// Faz também uma cópia da imagem do meio poroso contida na camara de forma que o que for diferente de 0 (solido) será 1 (poro)
// esta imagem será usado para recriar a camara, depois de criada a imagem é redefinida (verificar necessidade!).
TCMatriz3D<int> *pmCopiaBin = new TCMatriz3D<int>( nximg, nyimg, nzimg );
pmCopiaBin->Path(camara->Path());
for ( int i = 0; i < nximg; i++ ) {
for ( int j = 0; j < nyimg; j++ ) {
for ( int k = 0; k < nzimg; k++ ) {
if ( imagem->data3D[i][j][k] == 0 ) {
pmCopiaBin->data3D[i][j][k] = 0;
} else {
pmCopiaBin->data3D[i][j][k] = 1;
}
}
}
}
// Inverte as propriedades dos fluidos (compressibilidade e molhabilidade)
bool compressibilidadeTmp = fluidoB->Compressibilidade();
bool molhabilidadeTmp = fluidoB->Molhabilidade();
fluidoB->Compressibilidade( fluidoA->Compressibilidade() );
fluidoB->Molhabilidade( fluidoA->Molhabilidade() );
fluidoA->Compressibilidade( compressibilidadeTmp );
fluidoA->Molhabilidade( molhabilidadeTmp );
// Recria a camara baseada na imagem binária do meio poroso.
CriaCamara( pmCopiaBin );
camara->Path(pmCopiaBin->Path());
// Recalcula a IDF da camara
CriaIDF();
// Cria o objeto de rotulagem, passando a camara
CriaRotulador();
raio = fluidoB->Molhabilidade() == 0 ? raioMaximo : raioMinimo;
// Atualiza valores de deslocamento
DeslocX = camara->DeslocamentoNX ();
DeslocY = camara->DeslocamentoNY ();
DeslocZ = camara->DeslocamentoNZ ();
// Inverte a imagem original e redefine na nova camara. [ (B vira A) e (A ou Yi vira B) o restante é 0 ]
for (int i = 0; i < imagem->NX(); i++) {
for (int j = 0; j < imagem->NY(); j++) {
for (int k = 0; k < imagem->NZ(); k++) {
if ( imagem->data3D[i][j][k] == B ) {
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = A;
imagem->data3D[i][j][k] = A;
} else if ( ( imagem->data3D[i][j][k] == A ) or ( imagem->data3D[i][j][k] == Yi ) ) {
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = B;
imagem->data3D[i][j][k] = B;
} else {
camara->data3D[i + DeslocX][j + DeslocY][k + DeslocZ] = 0;
imagem->data3D[i][j][k] = 0;
}
}
}
}
//só corrige a abertura na drenagem.
corrigirAbertura = false;
camara->SetFormato(D2_X_Y_Z_GRAY_ASCII);
cores = camara->MaiorValor();
camara->NumCores( (cores >= 2) ? cores : cores+2 );
camara->Write ("imagemCamaraDepoisInverterFluxo.dgm");
delete pmCopiaBin;
}
// ====================================
// FUNCAO Next
// ====================================
// Funcao: bool CConfiguracoesEquilibrio2D::Next(TCMatriz2D< int >* imagem)
// Objetivo: Determinar passo-a-passo as configurações de equilíbrio geométricas em um processo de interação entre
// dois fluidos (fluidoA e fluidoB) em uma "camara" de um "porosimetro".
// Comentário: Por uma questão de economia de memória, a imagem idf é usada para armazenar os índices de G e G_
// ou seja, as regiões verde (abertura) e verde complementar. Isto é realizado pintando com valor negativo a região G_
// Next irá retornar verdadeiro enquanto existirem passos a serem executados.
bool CConfiguracoesEquilibrio3D::Next(TCMatriz3D<int> * &imagem) {
if (contadorPassosExecutados == 0) { // só irá entrar na primeira vez
CriaCamara(imagem); // Cria a camara considerando a imagem e a Molhabilidade do fluido B
CriaIDF(); // Cria a IDF, a partir da camara (calcula a idf e o raioMaximo)
CriaRotulador(); // Cria o objeto de rotulagem, passando a camara
raio = fluidoB->Molhabilidade() == 0 ? raioMaximo : raioMinimo;
}
if ( fluidoB->Molhabilidade() == 0 ? raio >= raioMinimo : raio <= raioMaximo ) {
contadorPassosExecutados++; // Incrementa o numero de passos executados (inicialmente=1)
cout << "ConfEq - calculando passo " << contadorPassosExecutados << endl;
CalculaAbertura(raio); // Realiza abertura
// se wb=1 o raio cresce, em função da membrana KGB0 � sempre B0.
if (fluidoB->Molhabilidade() == 0) {
// DiferencaEmRelacaoArtigo(imagem);
ConectividadeKGB0(); // Calcula a relacao K(G,B0)
}
if (fluidoB->Molhabilidade() == 1) {
// se wb=1 considera G_
UniaoG__U_KGB0(); // Realiza a uniao de G_ com K(G,B0)
// DiferencaEmRelacaoArtigo(imagem);
ConectividadeKwbG__U_KGB0B0(); // Calcula a relacao KwbG__U_KGB0B0
}
// Solucao final para Omega, 0,B,Yi,A0
SolucaoOmega(indiceParcialB, imagem); // MarcaYi // DeterminaA0 // ReestabeleceB
// Se ca=1, e nao for a primeira passagem
if (fluidoA->Compressibilidade() == 0 && contadorPassosExecutados != 1) {
cout << "Calculando CorrecaocaxYi..." << endl;
CorrecaocaxYi(imagem); // Se for inCompressivel e nao for a primeira passagem entra
}
cout << "Calculando SolucaoFinal..." << endl;
SolucaoFinal(imagem); // Copia solucao final para imagem e salva em disco
raio += fluidoB->Molhabilidade() == 0 ? -1 : 1; // incrementa ou decrementa o raio.
return true;
} else {
return false;
}
}
/// Metodo que determina toda sequência
/// Determinar as configurações de equilíbrio geométricas em um processo de interação entre dois
/// fluidos (fluidoA e fluidoB) em uma "camara" de um "porosimetro".
/// Comentário: Por uma questão de economia de memória, a imagem idf é usada para armazenar
/// os índices de G e G_ , ou seja, as regiões verde (abertura) e verde complementar.
/// Isto é realizado pintando com valor negativo a região G_
void CConfiguracoesEquilibrio3D::Go (TCMatriz3D<int> * &imagem) {
while ( Next(imagem) ) { } // Next irá executar todo os passos que foram comentados abaixo.
//InverterFluxo();
//while( Next(imagem) ) { }
}
| gpl-2.0 |
yeriomin/YalpStore | app/src/main/java/com/github/yeriomin/yalpstore/fragment/details/GeneralDetails.java | 11731 | /*
* Yalp Store
* Copyright (C) 2018 Sergey Yeriomin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.github.yeriomin.yalpstore.fragment.details;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.text.Html;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.github.yeriomin.yalpstore.CategoryAppsActivity;
import com.github.yeriomin.yalpstore.CategoryManager;
import com.github.yeriomin.yalpstore.DetailsActivity;
import com.github.yeriomin.yalpstore.HistoryActivity;
import com.github.yeriomin.yalpstore.R;
import com.github.yeriomin.yalpstore.SqliteHelper;
import com.github.yeriomin.yalpstore.Util;
import com.github.yeriomin.yalpstore.fragment.Abstract;
import com.github.yeriomin.yalpstore.model.App;
import com.github.yeriomin.yalpstore.model.EventDao;
import com.github.yeriomin.yalpstore.model.ImageSource;
import com.github.yeriomin.yalpstore.task.LoadImageTask;
import com.github.yeriomin.yalpstore.task.playstore.DetailsCategoryTask;
import com.github.yeriomin.yalpstore.view.IntentOnClickListener;
import com.github.yeriomin.yalpstore.widget.Badge;
import com.github.yeriomin.yalpstore.widget.ExpansionPanel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GeneralDetails extends Abstract {
public GeneralDetails(DetailsActivity activity, App app) {
super(activity, app);
}
@Override
public void draw() {
drawAppBadge(app);
activity.findViewById(R.id.availability).setVisibility(View.GONE);
if (app.isInPlayStore()) {
if (!TextUtils.isEmpty(app.getShortDescription())) {
activity.findViewById(R.id.short_description).setVisibility(View.VISIBLE);
setText(R.id.short_description, app.getShortDescription());
} else {
activity.findViewById(R.id.short_description).setVisibility(View.GONE);
}
if (!App.Restriction.NOT_RESTRICTED.equals(app.getRestriction())) {
activity.findViewById(R.id.availability).setVisibility(View.VISIBLE);
setText(R.id.availability, activity.getString(app.getRestriction().getStringResId()));
}
drawGeneralDetails(app);
drawDescription(app);
new GoogleDependency((DetailsActivity) activity, app).draw();
}
}
private void drawAppBadge(App app) {
TextView packageNameView = activity.findViewById(R.id.packageName);
String oldPackageName = (null == packageNameView || TextUtils.isEmpty(packageNameView.getText())) ? "" : packageNameView.getText().toString();
if (!oldPackageName.equals(app.getPackageName())) {
new LoadImageTask((ImageView) activity.findViewById(R.id.icon))
.setPlaceholder(false)
.setImageSource(app.getIconInfo())
.executeOnExecutorIfPossible()
;
}
setText(R.id.displayName, app.getDisplayName());
setText(R.id.packageName, app.getPackageName());
drawVersion((TextView) activity.findViewById(R.id.versionString), app);
}
private void drawGeneralDetails(App app) {
activity.findViewById(R.id.general_details).setVisibility(View.VISIBLE);
setText(R.id.updated, R.string.details_updated, app.getUpdated());
setText(R.id.developer, R.string.details_developer, app.getDeveloperName());
setText(R.id.price_and_ads, (TextUtils.isEmpty(app.getPrice()) ? "" : (app.getPrice() + ", ")) + activity.getString(app.containsAds() ? R.string.details_contains_ads : R.string.details_no_ads));
drawOfferDetails(app);
drawChanges(app);
drawHistoryButton(app);
if (app.getVersionCode() == 0) {
activity.findViewById(R.id.updated).setVisibility(View.GONE);
}
drawBadges();
}
private void drawChanges(App app) {
String changes = app.getChanges();
if (TextUtils.isEmpty(changes)) {
activity.findViewById(R.id.changes_in_details).setVisibility(View.GONE);
activity.findViewById(R.id.changes_title).setVisibility(View.GONE);
activity.findViewById(R.id.changes_panel).setVisibility(View.GONE);
return;
}
if (app.getInstalledVersionCode() == 0) {
setText(R.id.changes_in_details, Html.fromHtml(changes).toString());
activity.findViewById(R.id.changes_in_details).setVisibility(View.VISIBLE);
activity.findViewById(R.id.changes_title).setVisibility(View.VISIBLE);
} else {
setText(R.id.changes_upper, Html.fromHtml(changes).toString());
ExpansionPanel changesPanel = activity.findViewById(R.id.changes_panel);
changesPanel.setVisibility(View.VISIBLE);
changesPanel.toggle();
}
}
private void drawHistoryButton(final App app) {
boolean show = app.getInstalledVersionCode() > 0;
SQLiteDatabase db = new SqliteHelper(activity).getReadableDatabase();
try {
show = show && !new EventDao(db).getByPackageName(app.getPackageName()).isEmpty();
} catch (Throwable e) {
Log.w(getClass().getSimpleName(), "Could not check if the history is empty: " + e.getMessage());
} finally {
db.close();
}
if (show) {
activity.findViewById(R.id.history).setVisibility(View.VISIBLE);
activity.findViewById(R.id.history).setOnClickListener(new IntentOnClickListener(activity) {
@Override
protected Intent buildIntent() {
return HistoryActivity.getHistoryIntent(activity, app.getPackageName());
}
});
} else {
activity.findViewById(R.id.history).setVisibility(View.GONE);
}
}
private void drawOfferDetails(App app) {
List<String> keyList = new ArrayList<>(app.getOfferDetails().keySet());
Collections.reverse(keyList);
((LinearLayout) activity.findViewById(R.id.offer_details)).removeAllViews();
for (String key: keyList) {
addOfferItem(key, app.getOfferDetails().get(key));
}
}
private void addOfferItem(String key, String value) {
if (null == value) {
return;
}
TextView itemView = new TextView(activity);
try {
itemView.setAutoLinkMask(Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS);
} catch (RuntimeException e) {
Log.w(getClass().getSimpleName(), "System WebView missing: " + e.getMessage());
itemView.setAutoLinkMask(0);
} finally {
itemView.setText(activity.getString(R.string.two_items, key, Html.fromHtml(value)));
}
((LinearLayout) activity.findViewById(R.id.offer_details)).addView(itemView);
}
private void drawVersion(TextView textView, App app) {
String versionName = app.getVersionName();
if (TextUtils.isEmpty(versionName)) {
return;
}
textView.setText(activity.getString(R.string.details_versionName, versionName));
textView.setVisibility(View.VISIBLE);
if (!app.isInstalled()) {
return;
}
try {
PackageInfo info = activity.getPackageManager().getPackageInfo(app.getPackageName(), 0);
String currentVersion = info.versionName;
if (info.versionCode == app.getVersionCode() || null == currentVersion) {
return;
}
String newVersion = versionName;
if (currentVersion.equals(newVersion)) {
currentVersion += " (" + info.versionCode;
newVersion = app.getVersionCode() + ")";
}
textView.setText(activity.getString(R.string.details_versionName_updatable, currentVersion, newVersion));
} catch (PackageManager.NameNotFoundException e) {
// We've checked for that already
}
}
private void drawDescription(App app) {
ExpansionPanel descriptionPanel = activity.findViewById(R.id.description_panel);
if (TextUtils.isEmpty(app.getDescription())) {
descriptionPanel.setVisibility(View.GONE);
} else {
descriptionPanel.setVisibility(View.VISIBLE);
setText(R.id.description, Html.fromHtml(app.getDescription()).toString());
if (app.getInstalledVersionCode() == 0 || TextUtils.isEmpty(app.getChanges())) {
descriptionPanel.toggle();
}
}
}
private void drawBadges() {
((Badge) activity.findViewById(R.id.downloads_badge)).setLabel(Util.addSiPrefix(app.getInstalls()));
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(1);
((Badge) activity.findViewById(R.id.rating_badge)).setLabel(app.isEarlyAccess() ? activity.getString(R.string.early_access) : df.format(app.getRating().getAverage()));
((Badge) activity.findViewById(R.id.size_badge)).setLabel(Util.readableFileSize(app.getSize()));
drawCategoryBadge();
}
private void drawCategoryBadge() {
Badge categoryBadge = activity.findViewById(R.id.category_badge);
new LoadImageTask(categoryBadge.getIconView()).setPlaceholder(false).setImageSource(new ImageSource(app.getCategoryIconUrl())).executeOnExecutorIfPossible();
CategoryManager manager = new CategoryManager(activity);
String categoryId = app.getCategoryId();
String categoryLabel = manager.getCategoryName(categoryId);
if (categoryLabel.equals(categoryId)) {
getCategoryTask(manager, categoryId).execute();
} else {
categoryBadge.setLabel(categoryLabel);
}
categoryBadge.setLabel(categoryLabel);
categoryBadge.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CategoryAppsActivity.start(activity, app.getCategoryId());
}
});
ViewGroup.LayoutParams iconParams = categoryBadge.getIconView().getLayoutParams();
int categoryIconSize = Util.getPx(activity, 64);
iconParams.width = categoryIconSize;
iconParams.height = categoryIconSize;
}
private DetailsCategoryTask getCategoryTask(CategoryManager manager, String categoryId) {
DetailsCategoryTask task = new DetailsCategoryTask();
task.setCategoryId(categoryId);
task.setCategoryView((Badge) activity.findViewById(R.id.category_badge));
task.setManager(manager);
task.setContext(activity);
return task;
}
}
| gpl-2.0 |
metno/poseidon-rest | app/api/v1/ForecastSearchParams.java | 467 | package api.v1;
import java.util.Date;
public class ForecastSearchParams {
public String customer_name;
public String met_ref ;
public Date start_date;
public Integer start_term;
public Date end_date;
public Integer end_term;
public String custref_po_calloff ;
public String custref_contractnum;
public String custref_email;
public String customer_contactname;
public String position_name;
public String position_alias;
}
| gpl-2.0 |
laurynasl/gerpgr | game/gamemap.cpp | 22831 | #include "gamemap.hpp"
#include "masks.hpp"
#include "tables.hpp"
#include "triggerquestion.hpp"
#include "triggerplayer.hpp"
#include "actionrandom.hpp"
#include "actiontravel.hpp"
#include "monsters.hpp"
#include "maps.hpp"
#include <assert.h>
#include <math.h>
#include "../algorithms/graph.hpp"
#include "../iterators/lineiterator.hpp"
#include "../iterators/walliterator.hpp"
GameMap:: GameMap() :
_height(0), _width(0), defaultTile(0), squares(0) {
}
void GameMap:: clear() {
foreach (Trigger* trigger, triggers) {
delete trigger;
}
triggers.clear();
triggersMap.clear();
foreach (Monster* monster, monsters) {
if (monster->isMonster()) {
delete monster;
}
}
monsters.clear();
foreach (MapObject* object, objects) {
delete object;
}
objects.clear();
if (squares) {
delete[] squares;
squares = 0;
}
}
void GameMap:: initSquares(int defaultTile) {
clear();
int size = _width * _height;
squares = new MapSquare[size];
for (int i=0; i< size; i++) {
squares[i].background = defaultTile;
squares[i].monster = 0;
}
}
GameMap:: ~GameMap() {
clear();
}
int GameMap:: width() {
return _width;
}
int GameMap:: height() {
return _height;
}
int GameMap:: backgroundAt(int x, int y) {
return squares[x + y * _width].background;
}
void GameMap:: insertMonster(Monster* monster) {
monsters.insert(monster);
MapSquare * square = squareAt(monster->getX(), monster->getY());
square->monster = monster;
emit squareChanged(monster->getX(), monster->getY());
}
void GameMap:: removeMonster(Monster* monster) {
monsters.remove(monster);
if (squares) {
squareAt(monster->getX(), monster->getY())->monster = 0;
}
}
void GameMap:: load(Parser &parser) {
QString backgroundName;
Maps::remove(this);
parser >> name >> _width >> _height >> backgroundName;
Maps::add(this); // name is loaded, can add
defaultTile = Tables::nameToBackground(backgroundName);
initSquares(defaultTile);
int token;
try {
do {
token = (TokenType) parser.nextToken();
switch (token) {
case tktTile:{
QString name;
int x, y;
parser >> name >> x >> y;
squares[x + y * _width].background = Tables::nameToBackground(name);
break;
}
case tktTilesRange:{
QString name;
int x, y, w, h;
parser >> name >> x >> y >> w >> h;
int tile = Tables::nameToBackground(name);
for (int i = x; i<x+w; i++) {
for (int j=y; j<y+h; j++) {
squares[i + j * _width].background = tile;
}
}
break;
}
case tktMonster: {
Monster * monster = new Monster();
monster->setMapName(name);
monster->load(parser);
monster->name = Tables::monsterToClass(monster->getMonsterType()).name;
monster->finishedLoading();
insertMonster(monster);
Monsters::add(monster);
break;
}
/*case tktRandom: {
token = (TokenType)parser.nextToken();
if ((token == tktMonster) || (token == tktMonsters)) {
int monstersCount = 1;
if (token == tktMonsters) {
parser >> monstersCount;
}
QString className;
parser >> className;
int monsterType = Tables::nameToMonster(className);
token = (TokenType) parser.nextToken();
int x, y, w, h;
parser >> x >> y;
if (token == tktAt) {
w = 1;
h = 1;
}
else if (token == tktIn) {
parser >> w >> h;
}
else {
throw EException("UTA: \"random monster(s)\"");
}
//now we have monsters' type and count and all coordinates
for (int i=0; i<monstersCount; i++) {
Monster * monster = new Monster();
monster->setMapName(name);
monster->random(monsterType);
//try to place monster up to 50 times
bool inserted = false;
for (int j=0; j<50; j++) {
int xpos = x + rand() % w;
int ypos = y + rand() % h;
monster->x = xpos;
monster->y = ypos;
MapSquare * square = squareAt(xpos, ypos);
if (square->canAcceptMonster(*monster)) {
insertMonster(monster);
inserted = true;
break;
}
}
if (!inserted) {
delete monster;
}
}
cout << "random OK" << endl;
}
else {
throw EException("gamemap.cpp: UTA: \"random\"");
}
break;
}*/
case tktTrigger: {
int t = parser.nextToken();//trigger name
Trigger* trigger;
switch(t) {
case tktPlayer: {
trigger = new TriggerPlayer();
break;
}
case tktQuestion: {
trigger = new TriggerQuestion();
break;
}
default: {
throw EException("GameMap::load().tktTrigger2: Unexpected token");
}
}
try {
trigger->load(parser);
}
catch (...) {
delete trigger;
throw;
}
triggers.append(trigger);
QList<QIntsPair> points = trigger->getPoints();
foreach (const QIntsPair& point, points){
triggersMap.insert(point, trigger);
}
token = -1;
break;
}
case tktItem: {
int x, y, count;
QString itemName;
parser >> count >> itemName >> x >> y;
Item item(Tables::nameToItem(itemName), count);
MapSquare* square = squareAt(x, y);
if (square) {
square->items.append(item);
}
else {
throw EException(QString("GameMap::load(): tktItem: no such coordinates %1 %2").arg(x).arg(y));
}
break;
}
case tktEnd: break;
default:
throw EException("GameMap::load(): Unexpected token");
}
} while (token != tktEnd);
}
catch (QString& e) {
cout << "[E] GameMap::load(): " << e.toStdString() << endl;
clear();
throw;
}
catch (EException& e) {
cout << "[E] GameMap::load(): " << e.message().toStdString() << endl;
clear();
throw;
}
catch (...) {
cout << "[E] GameMap::load()" << endl;
clear();
throw;
}
}
MapSquare * GameMap:: squareAt(int x, int y) {
if ((x < 0) || (x >= _width) || (y < 0) || (y >= _height)) {
return 0;
}
return &squares[x + y * _width];
}
void GameMap:: save(ofstream& file) {
QString defaultTileName = Tables::backgroundToClass(defaultTile).name;
file << "map \"" << name.toStdString() << "\" ";
file << _width << " " << _height << " ";
file << "\"" << defaultTileName.toStdString() << "\"" << endl;
// save squares
// lame implementation:
for (int j=0; j<_height; j++) {
for (int i=0; i<_width; i++) {
MapSquare* square = squareAt(i, j);
if (square->background != defaultTile) {
file << " tile \"" << Tables::backgroundToClass(square->background).name.toStdString();
file << "\" " << i << " " << j << endl;
}
// save items
if (square->items.count()) {
for (int k=0; k<square->items.count(); k++) {
file << " item " << square->items[k].count() << " \"";
file << square->items[k].name().toStdString();
file << "\" " << i << " " << j << endl;
}
}
}
}
// save monsters
foreach (Monster* monster, monsters) {
if (monster->isMonster()) {
monster->save(file);
}
}
// save triggers
foreach (Trigger* trigger, triggers)
trigger->save(file);
file << "end" << endl << endl;
}
QList<Trigger*> GameMap:: triggersAt(int x, int y) {
return triggersMap.values(QIntsPair(x,y));
}
QString GameMap:: getName() {
return name;
}
bool GameMap:: containsMonster(Monster* monster) {
return monsters.contains(monster);
}
void GameMap:: squareChange(int x, int y) {
emit squareChanged(x, y);
}
void GameMap:: monsterMoved(Monster& monster, int oldX, int oldY) {
squareAt(oldX, oldY)->monster = 0;
squareAt(monster.getX(), monster.getY())->monster = &monster;
emit squareChanged(oldX, oldY);
emit squareChanged(monster.getX(), monster.getY());
QList<Trigger*> t = triggersAt(monster.getX(), monster.getY());
foreach (Trigger* trigger, t) {
if (!trigger->activate(monster)) {
break;
}
}
}
bool GameMap:: canAcceptMonsterAt(int x, int y, const Monster& monster) {
MapSquare* square = squareAt(x, y);
if (!square) return false;
if (!square->canAcceptMonster(monster)) return false;
if (areObjectsAt(x, y)) {
const QList<MapObject*> objects = objectsAt(x, y);
foreach (const MapObject* object, objects) {
if (object->isObstacle()) return false;
}
}
return true;
}
void GameMap:: generate(const World& world) {
Maps::remove(this);
clear();
name = world.name();
Maps::add(this);
_width = world.width();
_height = world.height();
initSquares(0);
for (int i=0; i<_width; i++) {
for (int j=0; j<_height; j++) {
float z = world.heightMap()[i][j];
MapSquare* square = squareAt(i, j);
assert(square != 0);
BackgroundClass bClass;
bClass.flags = bkgFlgForMainmap;
if (z < 0) bClass.flags |= bkgFlgObstacle;
bClass.height = (int)z;
int background = Tables::search(bClass);
assert(background >= 0); /// \todo replace with error
square->background = background;
}
}
foreach (const Ruin& ruin, world.ruins()) {
BackgroundClass criteria;
criteria.height = (int)world.heightMap()[ruin.x][ruin.y];
criteria.flags = bkgFlgForMainmap;
criteria.type = "ruin";
int background = Tables::search(criteria);
assert(background >= 0);
MapSquare* square = squareAt(ruin.x, ruin.y);
assert(square != 0);
square->background = background;
}
}
void GameMap:: generateDungeon(QString name, int awidth, int aheight, int& startx, int& starty, int& endx, int& endy, int background, int wall) {
assert(awidth >= 25);
assert(aheight >= 25);
Maps::remove(this);
clear();
this->name = name;
Maps::add(this);
_width = awidth;
_height = aheight;
initSquares(-1); //invalid background. will be used for room placing
/// room sizes are including walls, so in fact they are smaller by 2
int roomMinW = 6;
int roomMaxW = 10;
int roomMinH = 5;
int roomMaxH = 8;
/// lets say that rooms will occupy 25% of whole space
int roomsCount = awidth * aheight * 4 / (roomMinW + roomMaxW) / (roomMinH + roomMaxH) / 4/*==25%*/;
assert(roomsCount > 1);
QList<Coordinate> roomsList;
for (int index=0; index<roomsCount; index++) {
int x, y, w, h;
bool found = false;
for (int index2=0; index2<50; index2++) {
w = roomMinW + rand() % (roomMaxW - roomMinW + 1);
h = roomMinH + rand() % (roomMaxH - roomMinH + 1);
x = rand() % (_width - w);
y = rand() % (_height - h);
// test whether room can be placed at these coordinates
found = true;
try {
for (int i=0; i<w; i++) {
for (int j=0; j<h; j++) {
MapSquare* square = squareAt(x+i, y+j);
assert(square != 0);
if (square->background != -1) {
throw 0;
}
}
}
}
catch (int value) {
found = false;
}
if (found) {
break;
}
}
Coordinate roomCoordinate(x, y, w, h);
roomsList.append(roomCoordinate);
// now that I have coordinates and size of a room, I place it
for (int i=0; i<w; i++) {
for (int j=0; j<h; j++) {
MapSquare* square = squareAt(x+i, y+j);
assert(square != 0);
if ((i == 0) || (i == (w-1)) || (j == 0) || (j == (h-1))) {
square->background = wall;
}
else {
square->background = background;
}
}
}
}
// start position is in the middle of first room
startx = roomsList[0].w / 2 + roomsList[0].x;
starty = roomsList[0].h / 2 + roomsList[0].y;
// end position is in the middle of second room
endx = roomsList[1].w / 2 + roomsList[1].x;
endy = roomsList[1].h / 2 + roomsList[1].y;
//now fill all invalid space as walls
for (int i=0; i<_width; i++) {
for (int j=0; j<_height; j++) {
MapSquare* square = squareAt(i, j);
assert(square != 0);
if (square->background == -1) {
square->background = wall;
}
}
}
Graph fullGraph;
fullGraph.createDisconnectedGraph(roomsCount);
for (int i=1; i<roomsCount; i++) {
for (int j=0; j<i; j++) {
int dx = roomsList[i].x - roomsList[j].x;
int dy = roomsList[i].y - roomsList[j].y;
int weight = (int) sqrt((double)dx * dx + dy * dy);
fullGraph.connect(i, j, weight);
}
}
Graph graph = fullGraph.getMST();
// now connect rooms with tunnels
for (int i=1; i<roomsCount; i++) {
for (int j=0; j<i; j++) {
if (graph.edgeWeight(i, j) == -1) {
continue;
}
//cout << QString("rooms %1 and %2 are connected").arg(i).arg(j).toStdString() << endl;
// so, connect two rooms from center to center...
int x1 = roomsList[i].x + roomsList[i].w / 2;
int y1 = roomsList[i].y + roomsList[i].h / 2;
int x2 = roomsList[j].x + roomsList[j].w / 2;
int y2 = roomsList[j].y + roomsList[j].h / 2;
//cout << x1 << "," << y1 << " ; " << x2 << "," << y2 << endl;
for (LineIterator line(x1, y1, x2, y2); !line; line++) {
//cout << line.x() << " " << line.y() << endl;
MapSquare* square = squareAt(line.x(), line.y());
assert(square != 0);
square->background = background;
}
}
}
// now create doors
for (int i=0; i<roomsCount; i++) {
const Coordinate& room = roomsList[i];
for (WallIterator wall(room.x, room.y, room.w, room.h); !wall; wall++) {
MapSquare* square = squareAt(wall.x(), wall.y());
assert(square != 0);
if (square->background == background) {
QVariantMap doorCriteria;
doorCriteria["type"] = "door";
doorCriteria["closed"] = true;
int closedTile = Tables::searchObject(doorCriteria);
doorCriteria["closed"] = false;
int openTile = Tables::searchObject(doorCriteria);
// then create door here...
bool isClosed = (rand() % 100) >= 50;
//Door* door = new Door(
assert(createDoor(wall.x(), wall.y(), isClosed, closedTile, openTile, false, Tables::getRandomKeyCode()));
}
}
}
}
bool GameMap:: createStairs(int stairx, int stairy, bool isUp, QString mapName, int x, int y, int tile) {
if (stairsAt(stairx, stairy, isUp)) {
return false;
}
Stair* stair = new Stair(mapName, x, y, isUp, tile);
assert(stair); //crash fast, if out of memory
QIntsPair pair(stairx, stairy);
objects.insert(pair, stair);
return true;
}
const Stair* GameMap:: stairsAt(int x, int y, bool isUp) const {
QIntsPair pair(x, y);
if (!objects.contains(pair)) return 0;
foreach (const MapObject* object, objects.values(pair)) {
if (object->getClassName() == "stair") {
const Stair* stair = (const Stair*) object;
if (stair->isUp() == isUp) {
return stair;
}
}
}
return 0;
}
bool GameMap:: areObjectsAt(int x, int y) const {
QIntsPair pair(x, y);
return objects.contains(pair);
}
QList<MapObject*> GameMap:: objectsAt(int x, int y) const {
QIntsPair pair(x, y);
return objects.values(pair);
}
bool GameMap:: createDoor(int x, int y, bool isClosed, int closedTile, int openTile, bool locked, QString code) {
Door* door = new Door(isClosed, closedTile, openTile, locked, code);
assert(door); //crash fast, if out of memory
QIntsPair pair(x, y);
objects.insert(pair, door);
return true;
}
bool GameMap:: areLockedDoorsAt(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (door->isLocked()) return true;
}
return false;
}
bool GameMap:: areUnlockedDoorsAt(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (!door->isLocked()) return true;
}
return false;
}
bool GameMap:: areClosedDoorsAt(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (door->isClosed()) return true;
}
return false;
}
bool GameMap:: areOpenDoorsAt(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (!door->isClosed()) return true;
}
return false;
}
QString GameMap:: getDoorCode(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
return door->getCode();
}
return "";
}
bool GameMap:: unlockDoor(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (door->isLocked()) {
assert(door->unlock());
// emit squareChanged(x, y);
return true;
}
}
return false;
}
bool GameMap:: lockDoor(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (!door->isLocked()) {
assert(door->lock());
// emit squareChanged(x, y);
return true;
}
}
return false;
}
bool GameMap:: openDoor(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (door->isClosed()) {
assert(door->open());
emit squareChanged(x, y);
return true;
}
}
return false;
}
bool GameMap:: closeDoor(int x, int y) {
if (!areObjectsAt(x, y)) return false;
QList<MapObject*> objects = objectsAt(x, y);
foreach (MapObject* object, objects) {
if (object->getClassName() != "door") continue;
Door* door = (Door*) object;
if (!door->isClosed()) {
assert(door->close());
emit squareChanged(x, y);
return true;
}
}
return false;
}
// ********************** MapSquare *********************
bool MapSquare:: canAcceptMonster(const Monster & monster) {
assert(&monster != 0);
if (this->monster) return false;
/// \todo other tests, like obstacles, monster skills
if (Tables::backgroundToClass(background).isObstacle()) {
return false;
}
return true;
}
MapSquare:: ~MapSquare() {
}
| gpl-2.0 |
UShan89/dosocs2-ui | client/templates/restoken.js | 673 | Template.restoken.helpers({
Token: function(){
return 'REST Token'
}
})
Template.restoken.events({
'click .getToken': function(event, template){
event.preventDefault();
sAlert.warning("Generating token", {effect: 'bouncyflip', position: 'top-right', timeout: 1000, onRouteClose: true, stack: true, offset: '100px'})
Meteor.call('gentoken', Meteor.userId(), function(err, response){
if(err){
sAlert.error("Error in scanning ", {effect: 'bouncyflip', position: 'top-right', timeout: 3000, onRouteClose: true, stack: true, offset: '100px'});
}
if(response){
console.log(response);
}
})
}
})
| gpl-2.0 |
pmoor/bitthief | bitthief/src/ws/moor/bt/util/StringUtil.java | 1717 | /*
* BitThief - A Free Riding BitTorrent Client
* Copyright (C) 2006 Patrick Moor <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package ws.moor.bt.util;
import java.util.Collection;
/**
* TODO(pmoor): Javadoc
*/
public class StringUtil {
public static String join(Collection elements, String separator) {
if (elements == null) {
throw new NullPointerException();
}
if (separator == null) {
separator = "";
}
boolean first = true;
StringBuilder stringBuilder = new StringBuilder();
for (Object element : elements) {
if (!first) {
stringBuilder.append(separator);
} else {
first = false;
}
stringBuilder.append(element);
}
return stringBuilder.toString();
}
public static String repeat(String pattern, int repetitions) {
StringBuilder result = new StringBuilder(repetitions * pattern.length());
for (int i = 0; i < repetitions; i++) {
result.append(pattern);
}
return result.toString();
}
}
| gpl-2.0 |
GeoCat/QGIS | src/app/qgsmaptoolidentifyaction.cpp | 7212 | /***************************************************************************
qgsmaptoolidentify.cpp - map tool for identifying features
---------------------
begin : January 2006
copyright : (C) 2006 by Martin Dobias
email : wonder.sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsapplication.h"
#include "qgisapp.h"
#include "qgsattributetabledialog.h"
#include "qgscursors.h"
#include "qgsdistancearea.h"
#include "qgsfeature.h"
#include "qgsfeaturestore.h"
#include "qgsfields.h"
#include "qgsgeometry.h"
#include "qgslogger.h"
#include "qgsidentifyresultsdialog.h"
#include "qgsidentifymenu.h"
#include "qgsmapcanvas.h"
#include "qgsmaptopixel.h"
#include "qgsmessageviewer.h"
#include "qgsmaptoolidentifyaction.h"
#include "qgsrasterlayer.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsvectordataprovider.h"
#include "qgsvectorlayer.h"
#include "qgsproject.h"
#include "qgsrenderer.h"
#include "qgsunittypes.h"
#include "qgsstatusbar.h"
#include "qgssettings.h"
#include <QMouseEvent>
#include <QCursor>
#include <QPixmap>
#include <QStatusBar>
#include <QVariant>
QgsMapToolIdentifyAction::QgsMapToolIdentifyAction( QgsMapCanvas *canvas )
: QgsMapToolIdentify( canvas )
{
mToolName = tr( "Identify" );
// set cursor
QPixmap myIdentifyQPixmap = QPixmap( ( const char ** ) identify_cursor );
mCursor = QCursor( myIdentifyQPixmap, 1, 1 );
connect( this, &QgsMapToolIdentify::changedRasterResults, this, &QgsMapToolIdentifyAction::handleChangedRasterResults );
mIdentifyMenu->setAllowMultipleReturn( true );
QgsMapLayerAction *attrTableAction = new QgsMapLayerAction( tr( "Show attribute table" ), mIdentifyMenu, QgsMapLayer::VectorLayer, QgsMapLayerAction::MultipleFeatures );
connect( attrTableAction, &QgsMapLayerAction::triggeredForFeatures, this, &QgsMapToolIdentifyAction::showAttributeTable );
identifyMenu()->addCustomAction( attrTableAction );
}
QgsMapToolIdentifyAction::~QgsMapToolIdentifyAction()
{
if ( mResultsDialog )
{
mResultsDialog->done( 0 );
}
}
QgsIdentifyResultsDialog *QgsMapToolIdentifyAction::resultsDialog()
{
if ( !mResultsDialog )
{
mResultsDialog = new QgsIdentifyResultsDialog( mCanvas, mCanvas->window() );
connect( mResultsDialog.data(), static_cast<void ( QgsIdentifyResultsDialog::* )( QgsRasterLayer * )>( &QgsIdentifyResultsDialog::formatChanged ), this, &QgsMapToolIdentify::formatChanged );
connect( mResultsDialog.data(), &QgsIdentifyResultsDialog::copyToClipboard, this, &QgsMapToolIdentifyAction::handleCopyToClipboard );
}
return mResultsDialog;
}
void QgsMapToolIdentifyAction::showAttributeTable( QgsMapLayer *layer, const QList<QgsFeature> &featureList )
{
resultsDialog()->clear();
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
if ( !vl )
return;
QString filter = QStringLiteral( "$id IN (" );
Q_FOREACH ( const QgsFeature &feature, featureList )
{
filter.append( QStringLiteral( "%1," ).arg( feature.id() ) );
}
filter = filter.replace( QRegExp( ",$" ), QStringLiteral( ")" ) );
QgsAttributeTableDialog *tableDialog = new QgsAttributeTableDialog( vl );
tableDialog->setFilterExpression( filter );
tableDialog->show();
}
void QgsMapToolIdentifyAction::canvasMoveEvent( QgsMapMouseEvent *e )
{
Q_UNUSED( e );
}
void QgsMapToolIdentifyAction::canvasPressEvent( QgsMapMouseEvent *e )
{
Q_UNUSED( e );
}
void QgsMapToolIdentifyAction::canvasReleaseEvent( QgsMapMouseEvent *e )
{
resultsDialog()->clear();
connect( this, &QgsMapToolIdentifyAction::identifyProgress, QgisApp::instance(), &QgisApp::showProgress );
connect( this, &QgsMapToolIdentifyAction::identifyMessage, QgisApp::instance(), &QgisApp::showStatusMessage );
identifyMenu()->setResultsIfExternalAction( false );
// enable the right click for extended menu so it behaves as a contextual menu
// this would be removed when a true contextual menu is brought in QGIS
bool extendedMenu = e->modifiers() == Qt::ShiftModifier || e->button() == Qt::RightButton;
identifyMenu()->setExecWithSingleResult( extendedMenu );
identifyMenu()->setShowFeatureActions( extendedMenu );
IdentifyMode mode = extendedMenu ? LayerSelection : DefaultQgsSetting;
QList<IdentifyResult> results = QgsMapToolIdentify::identify( e->x(), e->y(), mode );
disconnect( this, &QgsMapToolIdentifyAction::identifyProgress, QgisApp::instance(), &QgisApp::showProgress );
disconnect( this, &QgsMapToolIdentifyAction::identifyMessage, QgisApp::instance(), &QgisApp::showStatusMessage );
if ( results.isEmpty() )
{
resultsDialog()->clear();
QgisApp::instance()->statusBarIface()->showMessage( tr( "No features at this position found." ) );
}
else
{
// Show the dialog before items are inserted so that items can resize themselves
// according to dialog size also the first time, see also #9377
if ( results.size() != 1 || !QgsSettings().value( QStringLiteral( "/Map/identifyAutoFeatureForm" ), false ).toBool() )
resultsDialog()->QDialog::show();
QList<IdentifyResult>::const_iterator result;
for ( result = results.constBegin(); result != results.constEnd(); ++result )
{
resultsDialog()->addFeature( *result );
}
// Call QgsIdentifyResultsDialog::show() to adjust with items
resultsDialog()->show();
}
// update possible view modes
resultsDialog()->updateViewModes();
}
void QgsMapToolIdentifyAction::handleChangedRasterResults( QList<IdentifyResult> &results )
{
// Add new result after raster format change
QgsDebugMsg( QString( "%1 raster results" ).arg( results.size() ) );
QList<IdentifyResult>::const_iterator rresult;
for ( rresult = results.constBegin(); rresult != results.constEnd(); ++rresult )
{
if ( rresult->mLayer->type() == QgsMapLayer::RasterLayer )
{
resultsDialog()->addFeature( *rresult );
}
}
}
void QgsMapToolIdentifyAction::activate()
{
resultsDialog()->activate();
QgsMapTool::activate();
}
void QgsMapToolIdentifyAction::deactivate()
{
resultsDialog()->deactivate();
QgsMapTool::deactivate();
}
QgsUnitTypes::DistanceUnit QgsMapToolIdentifyAction::displayDistanceUnits() const
{
return QgsProject::instance()->distanceUnits();
}
QgsUnitTypes::AreaUnit QgsMapToolIdentifyAction::displayAreaUnits() const
{
return QgsProject::instance()->areaUnits();
}
void QgsMapToolIdentifyAction::handleCopyToClipboard( QgsFeatureStore &featureStore )
{
QgsDebugMsg( QString( "features count = %1" ).arg( featureStore.features().size() ) );
emit copyToClipboard( featureStore );
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01128.java | 2115 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01128")
public class BenchmarkTest01128 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getHeader("foo");
String bar;
// Simple if statement that assigns param to bar on true condition
int i = 196;
if ( (500/42) + i > 200 )
bar = param;
else bar = "This should never happen";
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing hash - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Hash Test java.security.MessageDigest.getInstance(java.lang.String) executed");
}
}
| gpl-2.0 |
t3easy/surf | src/Task/Neos/Flow/UnitTestTask.php | 1947 | <?php
namespace TYPO3\Surf\Task\Neos\Flow;
/*
* This file is part of TYPO3 Surf.
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
use TYPO3\Surf\Application\Neos\Flow;
use TYPO3\Surf\Domain\Model\Application;
use TYPO3\Surf\Domain\Model\Deployment;
use TYPO3\Surf\Domain\Model\Node;
use TYPO3\Surf\Domain\Model\Task;
use TYPO3\Surf\Domain\Service\ShellCommandServiceAwareInterface;
use TYPO3\Surf\Domain\Service\ShellCommandServiceAwareTrait;
use TYPO3\Surf\Exception\InvalidConfigurationException;
/**
* A Neos Flow task to run unit tests
*/
class UnitTestTask extends Task implements ShellCommandServiceAwareInterface
{
use ShellCommandServiceAwareTrait;
/**
* Execute this task
*
* @param Node $node
* @param Application $application
* @param Deployment $deployment
* @param array $options
* @throws InvalidConfigurationException
*/
public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
{
if (!$application instanceof Flow) {
throw new InvalidConfigurationException(sprintf('Flow application needed for UnitTestTask, got "%s"', get_class($application)), 1358866042);
}
$targetPath = $deployment->getApplicationReleasePath($application);
$this->shell->executeOrSimulate('cd ' . $targetPath . ' && phpunit -c Build/' . $application->getBuildEssentialsDirectoryName() . '/PhpUnit/UnitTests.xml', $node, $deployment);
}
/**
* Simulate this task
*
* @param Node $node
* @param Application $application
* @param Deployment $deployment
* @param array $options
*/
public function simulate(Node $node, Application $application, Deployment $deployment, array $options = [])
{
$this->execute($node, $application, $deployment, $options);
}
}
| gpl-2.0 |
tomolimo/glpi | front/backup.php | 21593 | <?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2018 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
include ('../inc/includes.php');
if (isset($_POST['check_version'])) {
Session::checkRight('backup', Backup::CHECKUPDATE);
Toolbox::checkNewVersionAvailable(0, true);
Html::back();
}
Session::checkRight("backup", READ);
Html::header(__('Maintenance'), $_SERVER['PHP_SELF'], "admin", "backup");
$max_time = min(get_cfg_var("max_execution_time"), get_cfg_var("max_input_time"));
if ($max_time == 0) {
$defaulttimeout = 60;
$defaultrowlimit = 5;
} else if ($max_time > 5) {
$defaulttimeout = $max_time-2;
$defaultrowlimit = 5;
} else {
$defaulttimeout = max(1, $max_time-2);
$defaultrowlimit = 2;
}
/**
* Generate an XML backup file of the database
* @global DB $DB
*/
function xmlbackup() {
global $DB;
//on parcoure la DB et on liste tous les noms des tables dans $table
//on incremente $query[] de "select * from $table" pour chaque occurence de $table
$result = $DB->listTables();
$i = 0;
$query = [];
while ($line = $result->next()) {
$table = $line['TABLE_NAME'];
$query[$i] = "SELECT *
FROM ".$DB->quoteName($table);
$i++;
}
// Filename
$time_file = date("Y-m-d-H-i");
$filename = GLPI_DUMP_DIR . "/glpi-backup-" . GLPI_VERSION . "-$time_file.xml";
$A = new XML();
// Your query
$A->SqlString = $query;
//File path
$A->FilePath = $filename;
// Define layout type
$A->Type = 4;
// Generate the XML file
$A->DoXML();
// In case of error, display it
if ($A->IsError == 1) {
printf(__('ERROR:'), $A->ErrorString);
}
}
/**
* Init time to computer time spend
* @global type $TPSDEB
* @global int $TPSCOUR
*/
function init_time() {
global $TPSDEB, $TPSCOUR;
list($usec,$sec) = explode(" ", microtime());
$TPSDEB = $sec;
$TPSCOUR = 0;
}
/**
* Get current time
* @global type $TPSDEB
* @global type $TPSCOUR
*/
function current_time() {
global $TPSDEB, $TPSCOUR;
list($usec,$sec) = explode(" ", microtime());
$TPSFIN = $sec;
if (round($TPSFIN-$TPSDEB, 1) >= $TPSCOUR+1) {//une seconde de plus
$TPSCOUR = round($TPSFIN-$TPSDEB, 1);
}
}
/**
* Get data of a table
* @param DB $DB
* @param string $table table name
* @param integer $from FROM xxx
* @param integer $limit LIMIT xxx
* @return string SQL query "INSERT INTO..."
*/
function get_content($DB, $table, $from, $limit) {
$content = "";
$iterator = $DB->request($table, ['START' => $from, 'LIMIT' => $limit]);
if ($iterator->count()) {
while ($row = $iterator->next()) {
$insert = "INSERT INTO ".$DB->quoteName($table)." VALUES (";
foreach ($row as $field_val) {
if (is_null($field_val)) {
$insert .= "NULL,";
} else if ($field_val != "") {
$insert .= "'" . addslashes($field_val) . "',";
} else {
$insert .= "'',";
}
}
$insert = preg_replace("/,$/", "", $insert);
$insert .= ");\n";
$content .= $insert;
}
}
return $content;
}
/** Get structure of a table
*
* @param \Glpi\Database\AbstractDatabase $DB DB object
* @param string $table table name
**/
function get_def($DB, $table) {
$def = "### Dump table $table\n\n";
$def .= "DROP TABLE IF EXISTS ".$DB->quoteName($table).";\n";
$query = "SHOW CREATE TABLE ".$DB->quoteName($table);
$result = $DB->rawQuery($query);
$DB->rawQuery("SET SESSION sql_quote_show_create = 1");
$row = $DB->fetchRow($result);
$def .= preg_replace("/AUTO_INCREMENT=\w+/i", "", $row[1]);
$def .= ";";
return $def."\n\n";
}
/** Restore a mysql dump
*
* @param \Glpi\Database\AbstractDatabase $DB DB object
* @param string $dumpFile dump file
* @param integer $duree max delay before refresh
**/
function restoreMySqlDump($DB, $dumpFile, $duree) {
global $DB, $TPSCOUR, $offset, $cpt;
// $dumpFile, fichier source
// $duree=timeout pour changement de page (-1 = aucun)
// Desactivation pour empecher les addslashes au niveau de la creation des tables
// En plus, au niveau du dump on considere qu'on est bon
// set_magic_quotes_runtime(0);
if (!file_exists($dumpFile)) {
echo sprintf(__('File %s not found.'), $dumpFile)."<br>";
return false;
}
if (substr($dumpFile, -2) == "gz") {
$fileHandle = gzopen($dumpFile, "rb");
} else {
$fileHandle = fopen($dumpFile, "rb");
}
if (!$fileHandle) {
//TRASN: %s is the name of the file
echo sprintf(__('Unauthorized access to the file %s'), $dumpFile)."<br>";
return false;
}
if ($offset != 0) {
if (substr($dumpFile, -2) == "gz") {
if (gzseek($fileHandle, $offset, SEEK_SET) != 0) { //erreur
//TRANS: %s is the number of the byte
printf(__("Unable to find the byte %s"), Html::formatNumber($offset, false, 0));
echo "<br>";
return false;
}
} else {
if (fseek($fileHandle, $offset, SEEK_SET) != 0) { //erreur
//TRANS: %s is the number of the byte
printf(__("Unable to find the byte %s"), Html::formatNumber($offset, false, 0));
echo "<br>";
return false;
}
}
Html::glpi_flush();
}
$formattedQuery = "";
if (substr($dumpFile, -2) == "gz") {
while (!gzeof($fileHandle)) {
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
// specify read length to be able to read long lines
$buffer = gzgets($fileHandle, 102400);
// do not strip comments due to problems when # in begin of a data line
$formattedQuery .= $buffer;
if (substr(rtrim($formattedQuery), -1) == ";") {
// Do not use the $DB->query
if ($DB->query($formattedQuery)) { //if no success continue to concatenate
$offset = gztell($fileHandle);
$formattedQuery = "";
$cpt++;
}
}
}
} else {
while (!feof($fileHandle)) {
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
// specify read length to be able to read long lines
$buffer = fgets($fileHandle, 102400);
// do not strip comments due to problems when # in begin of a data line
$formattedQuery .= $buffer;
if (substr(rtrim($formattedQuery), -1) == ";") {
// Do not use the $DB->query
if ($DB->query($formattedQuery)) { //if no success continue to concatenate
$offset = ftell($fileHandle);
$formattedQuery = "";
$cpt++;
}
}
}
}
if ($DB->error()) {
echo "<hr>";
//TRANS: %s is the SQL query which generates the error
printf(__("SQL error starting from %s"), "[$formattedQuery]");
echo "<br>".$DB->error()."<hr>";
}
if (substr($dumpFile, -2) == "gz") {
gzclose($fileHandle);
} else {
fclose($fileHandle);
}
$offset = -1;
return true;
}
/** Backup a glpi DB
*
* @param \Glpi\Database\AbstractDatabase $DB DB object
* @param string $dumpFile dump file
* @param integer $duree max delay before refresh
* @param integer $rowlimit rowlimit to backup in one time
**/
function backupMySql($DB, $dumpFile, $duree, $rowlimit) {
global $TPSCOUR, $offsettable, $offsetrow, $cpt;
// $dumpFile, fichier source
// $duree=timeout pour changement de page (-1 = aucun)
if (function_exists('gzopen')) {
$fileHandle = gzopen($dumpFile, "a");
} else {
$fileHandle = gzopen64($dumpFile, "a");
}
if (!$fileHandle) {
//TRANS: %s is the name of the file
echo sprintf(__('Unauthorized access to the file %s'), $dumpFile)."<br>";
return false;
}
if ($offsettable == 0 && $offsetrow == -1) {
$cur_time = date("Y-m-d H:i");
$todump = "#GLPI Dump database on $cur_time\n";
gzwrite ($fileHandle, $todump);
}
$result = $DB->listTables();
$numtab = 0;
$tables = [];
while ($t = $result->next()) {
$tables[$numtab] = $t['TABLE_NAME'];
$numtab++;
}
for (; $offsettable<$numtab; $offsettable++) {
// Dump de la structure table
if ($offsetrow == -1) {
$todump = "\n".get_def($DB, $tables[$offsettable]);
gzwrite ($fileHandle, $todump);
$offsetrow++;
$cpt++;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
$fin = 0;
while (!$fin) {
$todump = get_content($DB, $tables[$offsettable], $offsetrow, $rowlimit);
$rowtodump = substr_count($todump, "INSERT INTO");
if ($rowtodump > 0) {
gzwrite ($fileHandle, $todump);
$cpt += $rowtodump;
$offsetrow += $rowlimit;
if ($rowtodump<$rowlimit) {
$fin = 1;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
} else {
$fin = 1;
$offsetrow = -1;
}
}
if ($fin) {
$offsetrow = -1;
}
current_time();
if (($duree > 0)
&& ($TPSCOUR >= $duree)) { //on atteint la fin du temps imparti
return true;
}
}
if ($DB->error()) {
echo "<hr>";
echo __("SQL error ");
echo "<br>".$DB->error()."<hr>";
}
$offsettable = -1;
gzclose($fileHandle);
return true;
}
// #################" DUMP sql#################################
if (isset($_GET["dump"]) && $_GET["dump"] != "") {
$time_file = date("Y-m-d-H-i");
$filename = GLPI_DUMP_DIR . "/glpi-backup-".GLPI_VERSION."-$time_file.sql.gz";
if (!isset($_GET["duree"]) && is_file($filename)) {
echo "<div class='center'>".__('The file already exists')."</div>";
} else {
init_time(); //initialise le temps
//debut de fichier
if (!isset($_GET["offsettable"])) {
$offsettable = 0;
} else {
$offsettable = $_GET["offsettable"];
}
//debut de fichier
if (!isset($_GET["offsetrow"])) {
$offsetrow = -1;
} else {
$offsetrow = $_GET["offsetrow"];
}
//timeout de 5 secondes par defaut, -1 pour utiliser sans timeout
if (!isset($_GET["duree"])) {
$duree = $defaulttimeout;
} else {
$duree = $_GET["duree"];
}
//Limite de lignes a dumper a chaque fois
if (!isset($_GET["rowlimit"])) {
$rowlimit = $defaultrowlimit;
} else {
$rowlimit = $_GET["rowlimit"];
}
//si le nom du fichier n'est pas en parametre le mettre ici
if (!isset($_GET["fichier"])) {
$fichier = $filename;
} else {
$fichier = $_GET["fichier"];
}
$tot = $DB->listTables()->count();
if (isset($offsettable)) {
if ($offsettable >= 0) {
$percent = min(100, round(100*$offsettable/$tot, 0));
} else {
$percent = 100;
}
} else {
$percent = 0;
}
if ($percent >= 0) {
Html::displayProgressBar(400, $percent);
echo '<br>';
}
if ($offsettable >= 0) {
if (backupMySql($DB, $fichier, $duree, $rowlimit)) {
echo "<div class='center spaced'>".
"<a href=\"backup.php?dump=1&duree=$duree&rowlimit=$rowlimit&offsetrow=".
"$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=$fichier\">".
__('Automatic redirection, else click')."</a>";
echo "<script type='text/javascript'>" .
"window.location=\"backup.php?dump=1&duree=$duree&rowlimit=".
"$rowlimit&offsetrow=$offsetrow&offsettable=$offsettable&cpt=$cpt&fichier=".
"$fichier\";</script></div>";
Html::glpi_flush();
exit;
}
}
}
}
// ############################## fin dump sql########################""""
// ################################## dump XML #############################
if (isset($_GET["xmlnow"]) && ($_GET["xmlnow"] != "")) {
xmlbackup();
}
// ################################## fin dump XML #############################
if (isset($_GET["file"]) && ($_GET["file"] != "") && is_file(GLPI_DUMP_DIR . "/" . $_GET["file"])) {
$filepath = realpath(GLPI_DUMP_DIR . "/" . $_GET['file']);
if (is_file($filepath) && Toolbox::startsWith($filepath, GLPI_DUMP_DIR)) {
init_time(); //initialise le temps
//debut de fichier
if (!isset($_GET["offset"])) {
$offset = 0;
} else {
$offset = $_GET["offset"];
}
//timeout de 5 secondes par defaut, -1 pour utiliser sans timeout
if (!isset($_GET["duree"])) {
$duree = $defaulttimeout;
} else {
$duree = $_GET["duree"];
}
$fsize = filesize($filepath);
if (isset($offset)) {
if ($offset == -1) {
$percent = 100;
} else {
$percent = min(100, round(100*$offset/$fsize, 0));
}
} else {
$percent = 0;
}
if ($percent >= 0) {
Html::displayProgressBar(400, $percent);
echo '<br>';
}
if ($offset != -1) {
if (restoreMySqlDump($DB, $filepath, $duree)) {
echo "<div class='center'>".
"<a href=\"backup.php?file=".$_GET["file"]."&duree=$duree&offset=".
"$offset&cpt=$cpt&donotcheckversion=1\">";
echo __('Automatic redirection, else click')."</a>";
echo "<script language='javascript' type='text/javascript'>".
"window.location=\"backup.php?file=".
$_GET["file"]."&duree=$duree&offset=$offset&cpt=$cpt&donotcheckversion=1\";".
"</script></div>";
Html::glpi_flush();
exit;
}
} else {
// Compatiblity for old version for utf8 complete conversion
$cnf = new Config();
$input = [
'id' => 1,
'utf8_conv' => 1,
];
$cnf->update($input);
}
}
}
if (isset($_POST["delfile"])) {
if (isset($_POST['file']) && ($_POST["file"] != "")) {
$filepath = realpath(GLPI_DUMP_DIR . "/" . $_POST['file']);
if (is_file($filepath) && Toolbox::startsWith($filepath, GLPI_DUMP_DIR)) {
$filename = $_POST["file"];
unlink($filepath);
// TRANS: %s is a file name
echo "<div class ='center spaced'>".sprintf(__('%s deleted'), $filename)."</div>";
}
}
}
if (Session::haveRight('backup', Backup::CHECKUPDATE)) {
echo "<div class='center spaced'><table class='tab_glpi'>";
echo "<tr class='tab_bg_1'><td colspan='4' class='center b'>";
Html::showSimpleForm($_SERVER['PHP_SELF'], 'check_version',
__('Check if a new version is available'));
echo "</td></tr></table></div>";
}
// Title backup
echo "<div class='center'>";
if (Session::haveRight('backup', CREATE)) {
echo "<table class='tab_glpi'><tr><td colspan='4'>";
echo "<div class='warning'><i class='fa fa-exclamation-triangle fa-5x'></i><ul><li>";
echo __('GLPI internal backup system is a helper for very small instances.');
echo "<br/>" . __('You should rather use a dedicated tool on your server.');
echo "</li></ul></div>";
echo "</td></tr><tr><td>";
echo "<i class='far fa-save fa-3x'></i>";
"</td>";
echo "<td><a class='vsubmit'
href=\"#\" ".HTML::addConfirmationOnAction(__('Backup the database?'),
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?dump=dump'").
">".__('SQL Dump')."</a> </td>";
echo "<td><a class='vsubmit'
href=\"#\" ".HTML::addConfirmationOnAction(__('Backup the database?'),
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?xmlnow=xmlnow'").
">".__('XML Dump')."</a> </td>";
echo "</tr></table>";
}
echo "<br><table class='tab_cadre' cellpadding='5'>".
"<tr class='center'>".
"<th><u><i>".__('File')."</i></u></th>".
"<th><u><i>".__('Size')."</i></u></th>".
"<th><u><i>".__('Date')."</i></u></th>".
"<th colspan='3'> </th>".
"</tr>";
$dir = opendir(GLPI_DUMP_DIR);
$files = [];
while ($file = readdir($dir)) {
if (($file != ".") && ($file != "..")
&& (preg_match("/\.sql.gz$/i", $file)
|| preg_match("/\.sql$/i", $file))) {
$files[$file] = filemtime(GLPI_DUMP_DIR . "/" . $file);
}
}
arsort($files);
if (count($files)) {
foreach ($files as $file => $date) {
$taille_fic = filesize(GLPI_DUMP_DIR . "/" . $file);
echo "<tr class='tab_bg_2'><td>$file </td>".
"<td class='right'>".Toolbox::getSize($taille_fic)."</td>".
"<td> " . Html::convDateTime(date("Y-m-d H:i", $date)) . "</td>";
if (Session::haveRight('backup', PURGE)) {
echo "<td> ";
//TRANS: %s is the filename
$string = sprintf(__('Delete the file %s?'), $file);
Html::showSimpleForm($_SERVER['PHP_SELF'], 'delfile',
_x('button', 'Delete permanently'),
['file' => $file], '', '', $string);
echo "</td>";
echo "<td> ";
// Multiple confirmation
$string = [];
//TRANS: %s is the filename
$string[] = [sprintf(__('Replace the current database with the backup file %s?'),
$file)];
$string[] = [__('Warning, your actual database will be totaly overwriten by the database you want to restore !!!')];
echo "<a class='vsubmit' href=\"#\" ".HTML::addConfirmationOnAction($string,
"window.location='".$CFG_GLPI["root_doc"].
"/front/backup.php?file=$file&donotcheckversion=1'").
">".__('Restore')."</a> </td>";
}
if (Session::haveRight('backup', CREATE)) {
echo "<td> ".
"<a class='vsubmit' href=\"document.send.php?file=_dumps/$file\">".__('Download').
"</a></td>";
}
echo "</tr>";
}
}
closedir($dir);
$dir = opendir(GLPI_DUMP_DIR);
unset($files);
$files = [];
while ($file = readdir($dir)) {
if (($file != ".") && ($file != "..")
&& preg_match("/\.xml$/i", $file)) {
$files[$file] = filemtime(GLPI_DUMP_DIR . "/" . $file);
}
}
arsort($files);
if (count($files)) {
foreach ($files as $file => $date) {
$taille_fic = filesize(GLPI_DUMP_DIR . "/" . $file);
echo "<tr class='tab_bg_1'><td colspan='6'><hr noshade></td></tr>".
"<tr class='tab_bg_2'><td>$file </td>".
"<td class='right'>".Toolbox::getSize($taille_fic)."</td>".
"<td> " . Html::convDateTime(date("Y-m-d H:i", $date)) . "</td>";
if (Session::haveRight('backup', PURGE)) {
echo "<td colspan=2>";
//TRANS: %s is the filename
$string = sprintf(__('Delete the file %s?'), $file);
Html::showSimpleForm($_SERVER['PHP_SELF'], 'delfile', _x('button', 'Delete permanently'),
['file' => $file], '', '', $string);
echo "</td>";
}
if (Session::haveRight('backup', CREATE)) {
echo "<td> <a class='vsubmit' href=\"document.send.php?file=_dumps/$file\">".
__('Download')."</a></td>";
}
echo "</tr>";
}
}
closedir($dir);
echo "</table>";
echo "</div>";
Html::footer();
| gpl-2.0 |
jiangchanghong/Mycat2 | src/main/java/io/mycat/server/parser/ServerParse.java | 22097 | /*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.server.parser;
import io.mycat.route.parser.util.ParseUtil;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author mycat
*/
public final class ServerParse {
public static final int OTHER = -1;
public static final int BEGIN = 1;
public static final int COMMIT = 2;
public static final int DELETE = 3;
public static final int INSERT = 4;
public static final int REPLACE = 5;
public static final int ROLLBACK = 6;
public static final int SELECT = 7;
public static final int SET = 8;
public static final int SHOW = 9;
public static final int START = 10;
public static final int UPDATE = 11;
public static final int KILL = 12;
public static final int SAVEPOINT = 13;
public static final int USE = 14;
public static final int EXPLAIN = 15;
public static final int EXPLAIN2 = 151;
public static final int KILL_QUERY = 16;
public static final int HELP = 17;
public static final int MYSQL_CMD_COMMENT = 18;
public static final int MYSQL_COMMENT = 19;
public static final int CALL = 20;
public static final int DESCRIBE = 21;
public static final int LOCK = 22;
public static final int UNLOCK = 23;
public static final int LOAD_DATA_INFILE_SQL = 99;
public static final int DDL = 100;
public static final int MIGRATE = 203;
private static final Pattern pattern = Pattern.compile("(load)+\\s+(data)+\\s+\\w*\\s*(infile)+",Pattern.CASE_INSENSITIVE);
private static final Pattern callPattern = Pattern.compile("\\w*\\;\\s*\\s*(call)+\\s+\\w*\\s*",Pattern.CASE_INSENSITIVE);
public static int parse(String stmt) {
int length = stmt.length();
//FIX BUG FOR SQL SUCH AS /XXXX/SQL
int rt = -1;
for (int i = 0; i < length; ++i) {
switch (stmt.charAt(i)) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
case '/':
// such as /*!40101 SET character_set_client = @saved_cs_client
// */;
if (i == 0 && stmt.charAt(1) == '*' && stmt.charAt(2) == '!' && stmt.charAt(length - 2) == '*'
&& stmt.charAt(length - 1) == '/') {
return MYSQL_CMD_COMMENT;
}
case '#':
i = ParseUtil.comment(stmt, i);
if (i + 1 == length) {
return MYSQL_COMMENT;
}
continue;
case 'A':
case 'a':
rt = aCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'B':
case 'b':
rt = beginCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'C':
case 'c':
rt = commitOrCallCheckOrCreate(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'D':
case 'd':
rt = deleteOrdCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'E':
case 'e':
rt = explainCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'I':
case 'i':
rt = insertCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'M':
case 'm':
rt = migrateCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'R':
case 'r':
rt = rCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'S':
case 's':
rt = sCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'T':
case 't':
rt = tCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'U':
case 'u':
rt = uCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'K':
case 'k':
rt = killCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'H':
case 'h':
rt = helpCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
case 'L':
case 'l':
rt = lCheck(stmt, i);
if (rt != OTHER) {
return rt;
}
continue;
default:
continue;
}
}
return OTHER;
}
static int lCheck(String stmt, int offset) {
if (stmt.length() > offset + 3) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
if ((c1 == 'O' || c1 == 'o') && (c2 == 'A' || c2 == 'a')
&& (c3 == 'D' || c3 == 'd')) {
Matcher matcher = pattern.matcher(stmt);
return matcher.find() ? LOAD_DATA_INFILE_SQL : OTHER;
} else if ((c1 == 'O' || c1 == 'o') && (c2 == 'C' || c2 == 'c')
&& (c3 == 'K' || c3 == 'k')){
return LOCK;
}
}
return OTHER;
}
private static int migrateCheck(String stmt, int offset) {
if (stmt.length() > offset + 7) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'i' || c1 == 'I')
&& (c2 == 'g' || c2 == 'G')
&& (c3 == 'r' || c3 == 'R')
&& (c4 == 'a' || c4 == 'A')
&& (c5 == 't' || c5 == 'T')
&& (c6 == 'e' || c6 == 'E'))
{
return MIGRATE;
}
}
return OTHER;
}
//truncate
private static int tCheck(String stmt, int offset) {
if (stmt.length() > offset + 7) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
char c7 = stmt.charAt(++offset);
char c8 = stmt.charAt(++offset);
if ((c1 == 'R' || c1 == 'r')
&& (c2 == 'U' || c2 == 'u')
&& (c3 == 'N' || c3 == 'n')
&& (c4 == 'C' || c4 == 'c')
&& (c5 == 'A' || c5 == 'a')
&& (c6 == 'T' || c6 == 't')
&& (c7 == 'E' || c7 == 'e')
&& (c8 == ' ' || c8 == '\t' || c8 == '\r' || c8 == '\n')) {
return DDL;
}
}
return OTHER;
}
//alter table/view/...
private static int aCheck(String stmt, int offset) {
if (stmt.length() > offset + 4) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
if ((c1 == 'L' || c1 == 'l')
&& (c2 == 'T' || c2 == 't')
&& (c3 == 'E' || c3 == 'e')
&& (c4 == 'R' || c4 == 'r')
&& (c5 == ' ' || c5 == '\t' || c5 == '\r' || c5 == '\n')) {
return DDL;
}
}
return OTHER;
}
//create table/view/...
private static int createCheck(String stmt, int offset) {
if (stmt.length() > offset + 5) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'R' || c1 == 'r')
&& (c2 == 'E' || c2 == 'e')
&& (c3 == 'A' || c3 == 'a')
&& (c4 == 'T' || c4 == 't')
&& (c5 == 'E' || c5 == 'e')
&& (c6 == ' ' || c6 == '\t' || c6 == '\r' || c6 == '\n')) {
return DDL;
}
}
return OTHER;
}
//drop
private static int dropCheck(String stmt, int offset) {
if (stmt.length() > offset + 3) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'R' || c1 == 'r')
&& (c2 == 'O' || c2 == 'o')
&& (c3 == 'P' || c3 == 'p')
&& (c4 == ' ' || c4 == '\t' || c4 == '\r' || c4 == '\n')) {
return DDL;
}
}
return OTHER;
}
// delete or drop
static int deleteOrdCheck(String stmt, int offset){
int sqlType = OTHER;
switch (stmt.charAt((offset + 1))) {
case 'E':
case 'e':
sqlType = dCheck(stmt, offset);
break;
case 'R':
case 'r':
sqlType = dropCheck(stmt, offset);
break;
default:
sqlType = OTHER;
}
return sqlType;
}
// HELP' '
static int helpCheck(String stmt, int offset) {
if (stmt.length() > offset + "ELP ".length()) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e') && (c2 == 'L' || c2 == 'l')
&& (c3 == 'P' || c3 == 'p')) {
return (offset << 8) | HELP;
}
}
return OTHER;
}
// EXPLAIN' '
static int explainCheck(String stmt, int offset) {
if (stmt.length() > offset + "XPLAIN ".length()) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
char c7 = stmt.charAt(++offset);
if ((c1 == 'X' || c1 == 'x') && (c2 == 'P' || c2 == 'p')
&& (c3 == 'L' || c3 == 'l') && (c4 == 'A' || c4 == 'a')
&& (c5 == 'I' || c5 == 'i') && (c6 == 'N' || c6 == 'n')
&& (c7 == ' ' || c7 == '\t' || c7 == '\r' || c7 == '\n')) {
return (offset << 8) | EXPLAIN;
}
}
if(stmt != null && stmt.toLowerCase().startsWith("explain2")){
return (offset << 8) | EXPLAIN2;
}
return OTHER;
}
// KILL' '
static int killCheck(String stmt, int offset) {
if (stmt.length() > offset + "ILL ".length()) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'I' || c1 == 'i') && (c2 == 'L' || c2 == 'l')
&& (c3 == 'L' || c3 == 'l')
&& (c4 == ' ' || c4 == '\t' || c4 == '\r' || c4 == '\n')) {
while (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
case 'Q':
case 'q':
return killQueryCheck(stmt, offset);
default:
return (offset << 8) | KILL;
}
}
return OTHER;
}
}
return OTHER;
}
// KILL QUERY' '
static int killQueryCheck(String stmt, int offset) {
if (stmt.length() > offset + "UERY ".length()) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
if ((c1 == 'U' || c1 == 'u') && (c2 == 'E' || c2 == 'e')
&& (c3 == 'R' || c3 == 'r') && (c4 == 'Y' || c4 == 'y')
&& (c5 == ' ' || c5 == '\t' || c5 == '\r' || c5 == '\n')) {
while (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
default:
return (offset << 8) | KILL_QUERY;
}
}
return OTHER;
}
}
return OTHER;
}
// BEGIN
static int beginCheck(String stmt, int offset) {
if (stmt.length() > offset + 4) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e')
&& (c2 == 'G' || c2 == 'g')
&& (c3 == 'I' || c3 == 'i')
&& (c4 == 'N' || c4 == 'n')
&& (stmt.length() == ++offset || ParseUtil.isEOF(stmt
.charAt(offset)))) {
return BEGIN;
}
}
return OTHER;
}
// COMMIT
static int commitCheck(String stmt, int offset) {
if (stmt.length() > offset + 5) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
if ((c1 == 'O' || c1 == 'o')
&& (c2 == 'M' || c2 == 'm')
&& (c3 == 'M' || c3 == 'm')
&& (c4 == 'I' || c4 == 'i')
&& (c5 == 'T' || c5 == 't')
&& (stmt.length() == ++offset || ParseUtil.isEOF(stmt
.charAt(offset)))) {
return COMMIT;
}
}
return OTHER;
}
// CALL
static int callCheck(String stmt, int offset) {
if (stmt.length() > offset + 3) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
if ((c1 == 'A' || c1 == 'a') && (c2 == 'L' || c2 == 'l')
&& (c3 == 'L' || c3 == 'l')) {
return CALL;
}
}
return OTHER;
}
static int commitOrCallCheckOrCreate(String stmt, int offset) {
int sqlType = OTHER;
switch (stmt.charAt((offset + 1))) {
case 'O':
case 'o':
sqlType = commitCheck(stmt, offset);
break;
case 'A':
case 'a':
sqlType = callCheck(stmt, offset);
break;
case 'R':
case 'r':
sqlType = createCheck(stmt, offset);
break;
default:
sqlType = OTHER;
}
return sqlType;
}
// DESCRIBE or desc or DELETE' '
static int dCheck(String stmt, int offset) {
if (stmt.length() > offset + 4) {
int res = describeCheck(stmt, offset);
if (res == DESCRIBE) {
return res;
}
}
// continue check
if (stmt.length() > offset + 6) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e') && (c2 == 'L' || c2 == 'l')
&& (c3 == 'E' || c3 == 'e') && (c4 == 'T' || c4 == 't')
&& (c5 == 'E' || c5 == 'e')
&& (c6 == ' ' || c6 == '\t' || c6 == '\r' || c6 == '\n')) {
return DELETE;
}
}
return OTHER;
}
// DESCRIBE' ' 或 desc' '
static int describeCheck(String stmt, int offset) {
//desc
if (stmt.length() > offset + 4) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e') && (c2 == 'S' || c2 == 's')
&& (c3 == 'C' || c3 == 'c')
&& (c4 == ' ' || c4 == '\t' || c4 == '\r' || c4 == '\n')) {
return DESCRIBE;
}
//describe
if (stmt.length() > offset + 4) {
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
char c7 = stmt.charAt(++offset);
char c8 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e') && (c2 == 'S' || c2 == 's')
&& (c3 == 'C' || c3 == 'c') && (c4 == 'R' || c4 == 'r')
&& (c5 == 'I' || c5 == 'i') && (c6 == 'B' || c6 == 'b')
&& (c7 == 'E' || c7 == 'e')
&& (c8 == ' ' || c8 == '\t' || c8 == '\r' || c8 == '\n')) {
return DESCRIBE;
}
}
}
return OTHER;
}
// INSERT' '
static int insertCheck(String stmt, int offset) {
if (stmt.length() > offset + 6) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'N' || c1 == 'n') && (c2 == 'S' || c2 == 's')
&& (c3 == 'E' || c3 == 'e') && (c4 == 'R' || c4 == 'r')
&& (c5 == 'T' || c5 == 't')
&& (c6 == ' ' || c6 == '\t' || c6 == '\r' || c6 == '\n')) {
return INSERT;
}
}
return OTHER;
}
static int rCheck(String stmt, int offset) {
if (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case 'E':
case 'e':
return replaceCheck(stmt, offset);
case 'O':
case 'o':
return rollabckCheck(stmt, offset);
default:
return OTHER;
}
}
return OTHER;
}
// REPLACE' '
static int replaceCheck(String stmt, int offset) {
if (stmt.length() > offset + 6) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'P' || c1 == 'p') && (c2 == 'L' || c2 == 'l')
&& (c3 == 'A' || c3 == 'a') && (c4 == 'C' || c4 == 'c')
&& (c5 == 'E' || c5 == 'e')
&& (c6 == ' ' || c6 == '\t' || c6 == '\r' || c6 == '\n')) {
return REPLACE;
}
}
return OTHER;
}
// ROLLBACK
static int rollabckCheck(String stmt, int offset) {
if (stmt.length() > offset + 6) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
if ((c1 == 'L' || c1 == 'l')
&& (c2 == 'L' || c2 == 'l')
&& (c3 == 'B' || c3 == 'b')
&& (c4 == 'A' || c4 == 'a')
&& (c5 == 'C' || c5 == 'c')
&& (c6 == 'K' || c6 == 'k')
&& (stmt.length() == ++offset || ParseUtil.isEOF(stmt
.charAt(offset)))) {
return ROLLBACK;
}
}
return OTHER;
}
static int sCheck(String stmt, int offset) {
if (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case 'A':
case 'a':
return savepointCheck(stmt, offset);
case 'E':
case 'e':
return seCheck(stmt, offset);
case 'H':
case 'h':
return showCheck(stmt, offset);
case 'T':
case 't':
return startCheck(stmt, offset);
default:
return OTHER;
}
}
return OTHER;
}
// SAVEPOINT
static int savepointCheck(String stmt, int offset) {
if (stmt.length() > offset + 8) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
char c6 = stmt.charAt(++offset);
char c7 = stmt.charAt(++offset);
char c8 = stmt.charAt(++offset);
if ((c1 == 'V' || c1 == 'v') && (c2 == 'E' || c2 == 'e')
&& (c3 == 'P' || c3 == 'p') && (c4 == 'O' || c4 == 'o')
&& (c5 == 'I' || c5 == 'i') && (c6 == 'N' || c6 == 'n')
&& (c7 == 'T' || c7 == 't')
&& (c8 == ' ' || c8 == '\t' || c8 == '\r' || c8 == '\n')) {
return SAVEPOINT;
}
}
return OTHER;
}
static int seCheck(String stmt, int offset) {
if (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case 'L':
case 'l':
return selectCheck(stmt, offset);
case 'T':
case 't':
if (stmt.length() > ++offset) {
//支持一下语句
// /*!mycat: sql=SELECT * FROM test where id=99 */set @pin=1;
// call p_test(@pin,@pout);
// select @pout;
if(stmt.startsWith("/*!mycat:")||stmt.startsWith("/*#mycat:")||stmt.startsWith("/*mycat:"))
{
Matcher matcher = callPattern.matcher(stmt);
if (matcher.find()) {
return CALL;
}
}
char c = stmt.charAt(offset);
if (c == ' ' || c == '\r' || c == '\n' || c == '\t'
|| c == '/' || c == '#') {
return (offset << 8) | SET;
}
}
return OTHER;
default:
return OTHER;
}
}
return OTHER;
}
// SELECT' '
static int selectCheck(String stmt, int offset) {
if (stmt.length() > offset + 4) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e')
&& (c2 == 'C' || c2 == 'c')
&& (c3 == 'T' || c3 == 't')
&& (c4 == ' ' || c4 == '\t' || c4 == '\r' || c4 == '\n'
|| c4 == '/' || c4 == '#')) {
return (offset << 8) | SELECT;
}
}
return OTHER;
}
// SHOW' '
static int showCheck(String stmt, int offset) {
if (stmt.length() > offset + 3) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
if ((c1 == 'O' || c1 == 'o') && (c2 == 'W' || c2 == 'w')
&& (c3 == ' ' || c3 == '\t' || c3 == '\r' || c3 == '\n')) {
return (offset << 8) | SHOW;
}
}
return OTHER;
}
// START' '
static int startCheck(String stmt, int offset) {
if (stmt.length() > offset + 4) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
if ((c1 == 'A' || c1 == 'a') && (c2 == 'R' || c2 == 'r')
&& (c3 == 'T' || c3 == 't')
&& (c4 == ' ' || c4 == '\t' || c4 == '\r' || c4 == '\n')) {
return (offset << 8) | START;
}
}
return OTHER;
}
// UPDATE' ' | USE' '
static int uCheck(String stmt, int offset) {
if (stmt.length() > ++offset) {
switch (stmt.charAt(offset)) {
case 'P':
case 'p':
if (stmt.length() > offset + 5) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
if ((c1 == 'D' || c1 == 'd')
&& (c2 == 'A' || c2 == 'a')
&& (c3 == 'T' || c3 == 't')
&& (c4 == 'E' || c4 == 'e')
&& (c5 == ' ' || c5 == '\t' || c5 == '\r' || c5 == '\n')) {
return UPDATE;
}
}
break;
case 'S':
case 's':
if (stmt.length() > offset + 2) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
if ((c1 == 'E' || c1 == 'e')
&& (c2 == ' ' || c2 == '\t' || c2 == '\r' || c2 == '\n')) {
return (offset << 8) | USE;
}
}
break;
case 'N':
case 'n':
if (stmt.length() > offset + 5) {
char c1 = stmt.charAt(++offset);
char c2 = stmt.charAt(++offset);
char c3 = stmt.charAt(++offset);
char c4 = stmt.charAt(++offset);
char c5 = stmt.charAt(++offset);
if ((c1 == 'L' || c1 == 'l')
&& (c2 == 'O' || c2 == 'o')
&& (c3 == 'C' || c3 == 'c')
&& (c4 == 'K' || c4 == 'k')
&& (c5 == ' ' || c5 == '\t' || c5 == '\r' || c5 == '\n')) {
return UNLOCK;
}
}
break;
default:
return OTHER;
}
}
return OTHER;
}
}
| gpl-2.0 |
olivierdalang/stdm | third_party/geraldo/cache.py | 4326 | """Caching functions file. You can use this stuff to store generated reports in a file
system cache, and save time and performance."""
import os
from utils import memoize, get_attr_value
try:
set
except:
from sets import Set as set
CACHE_DISABLED = 0
CACHE_BY_QUERYSET = 1
CACHE_BY_RENDER = 2
DEFAULT_CACHE_STATUS = CACHE_DISABLED
CACHE_BACKEND = 'geraldo.cache.FileCacheBackend'
CACHE_FILE_ROOT = '/tmp/'
class BaseCacheBackend(object):
"""This is the base class (and abstract too) to be inherited by any cache backend
to store and restore reports from a cache."""
def get(self, hash_key):
pass
def set(self, hash_key, content):
pass
def exists(self, hash_key):
pass
class FileCacheBackend(BaseCacheBackend):
"""This cache backend is able to store and restore using a path on the file system."""
cache_file_root = '/tmp/'
def __init__(self, cache_file_root=None):
self.cache_file_root = cache_file_root or self.cache_file_root
# Creates the directory if doesn't exists
if not os.path.exists(self.cache_file_root):
os.makedirs(self.cache_file_root)
def get(self, hash_key):
# Returns None if doesn't exists
if not self.exists(hash_key):
return None
# Returns the file content
fp = file(os.path.join(self.cache_file_root, hash_key), 'rb')
content = fp.read()
fp.close()
return content
def set(self, hash_key, content):
# Writes the content in the file
fp = file(os.path.join(self.cache_file_root, hash_key), 'wb')
fp.write(content)
fp.close()
def exists(self, hash_key):
return os.path.exists(os.path.join(self.cache_file_root, hash_key))
@memoize
def get_report_cache_attributes(report):
from widgets import ObjectValue
# Find widgets attributes
widgets = [widget.attribute_name for widget in report.find_by_type(ObjectValue)]
# Find grouppers attributes
groups = [group.attribute_name for group in report.groups]
return list(set(widgets + groups))
try:
# Python 2.5 or higher
from hashlib import sha512 as hash_constructor
except ImportError:
# Python 2.4
import sha
hash_constructor = sha.new
def make_hash_key(report, objects_list):
"""This function make a hash key from a list of objects.
Situation 1
-----------
If the objects have an method 'repr_for_cache_hash_key', it is called to get their
string repr value. This is the default way to get repr strings from rendered pages
and objects.
Situation 2
-----------
Otherwise, if exists, the method 'get_cache_relevant_attributes' from report will be
called to request what attributes have to be used from the object list to make the
string.
If the method above does't exists, then all attributes explicitly found in report
elements will be used.
The result list will be transformed to a long concatenated string and a hash key
will be generated from it."""
global get_report_cache_attributes
result = []
# Get attributes for cache from report
if hasattr(report, 'get_cache_relevant_attributes'):
report_attrs = report.get_cache_relevant_attributes
else:
report_attrs = lambda: get_report_cache_attributes(report)
for obj in objects_list:
# Situation 1 - mostly report pages and geraldo objects
if hasattr(obj, 'repr_for_cache_hash_key'):
result.append(obj.repr_for_cache_hash_key())
# Situation 2 - mostly queryset objects list
else:
result.append(u'/'.join([unicode(get_attr_value(obj, attr)) for attr in report_attrs()]))
# Makes the hash key
m = hash_constructor()
m.update(u'\n'.join(result))
return '%s-%s'%(report.cache_prefix, m.hexdigest())
def get_cache_backend(class_path, **kwargs):
"""This method initializes the cache backend from string path informed."""
parts = class_path.split('.')
module = __import__('.'.join(parts[:-1]), fromlist=[parts[-1]])
cls = getattr(module, parts[-1])
return cls(**kwargs)
| gpl-2.0 |
heros/LasCore | src/server/game/Chat/Channels/ChannelMgr.cpp | 2997 | /*
* Copyright (C) 2013 LasCore <http://lascore.makeforum.eu/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ChannelMgr.h"
#include "Player.h"
#include "World.h"
#include "WorldSession.h"
ChannelMgr::~ChannelMgr()
{
for (ChannelMap::iterator itr = channels.begin(); itr != channels.end(); ++itr)
delete itr->second;
channels.clear();
}
ChannelMgr* ChannelMgr::forTeam(uint32 team)
{
if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL))
return ACE_Singleton<AllianceChannelMgr, ACE_Null_Mutex>::instance(); // cross-faction
if (team == ALLIANCE)
return ACE_Singleton<AllianceChannelMgr, ACE_Null_Mutex>::instance();
if (team == HORDE)
return ACE_Singleton<HordeChannelMgr, ACE_Null_Mutex>::instance();
return NULL;
}
Channel* ChannelMgr::GetJoinChannel(std::string const& name, uint32 channelId)
{
std::wstring wname;
Utf8toWStr(name, wname);
wstrToLower(wname);
ChannelMap::const_iterator i = channels.find(wname);
if (i == channels.end())
{
Channel* nchan = new Channel(name, channelId, team);
channels[wname] = nchan;
return nchan;
}
return i->second;
}
Channel* ChannelMgr::GetChannel(std::string const& name, Player* player, bool pkt)
{
std::wstring wname;
Utf8toWStr(name, wname);
wstrToLower(wname);
ChannelMap::const_iterator i = channels.find(wname);
if (i == channels.end())
{
if (pkt)
{
WorldPacket data;
MakeNotOnPacket(&data, name);
player->GetSession()->SendPacket(&data);
}
return NULL;
}
return i->second;
}
void ChannelMgr::LeftChannel(std::string const& name)
{
std::wstring wname;
Utf8toWStr(name, wname);
wstrToLower(wname);
ChannelMap::const_iterator i = channels.find(wname);
if (i == channels.end())
return;
Channel* channel = i->second;
if (!channel->GetNumPlayers() && !channel->IsConstant())
{
channels.erase(wname);
delete channel;
}
}
void ChannelMgr::MakeNotOnPacket(WorldPacket* data, std::string const& name)
{
data->Initialize(SMSG_CHANNEL_NOTIFY, 1 + name.size());
(*data) << uint8(5) << name;
}
| gpl-2.0 |
videntity/tweatwell | config/sample_settings_local.py | 361 | #local settings -------------------------------------------------------------
STATIC_URL = 'http://tweatwellstatic.s3.amazonaws.com/static/'
ADMIN_MEDIA_PREFIX = 'http://djadminstatic.s3.amazonaws.com/'
HOSTNAME_URL = 'http://app.tweatwell.com'
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
#Cron key required to run scoreing and twitbot urls.
CRON_KEY='' | gpl-2.0 |
DialloAbdourahamane/siteDepotProjet | wp-content/plugins/simple-press/admin/panel-forums/forms/spa-forums-edit-group-form.php | 5924 | <?php
/*
Simple:Press
Admin Forums Edit Group Form
$LastChangedDate: 2012-11-18 11:04:10 -0700 (Sun, 18 Nov 2012) $
$Rev: 9312 $
*/
if (preg_match('#'.basename(__FILE__).'#', $_SERVER['PHP_SELF'])) die('Access denied - you cannot directly call this file');
# function to display the edit group information form. It is hidden until the edit group link is clicked
function spa_forums_edit_group_form($group_id) {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#sfgroupedit<?php echo $group_id; ?>').ajaxForm({
target: '#sfmsgspot',
success: function() {
jQuery('#sfreloadfb').click();
jQuery('#sfmsgspot').fadeIn();
jQuery('#sfmsgspot').fadeOut(6000);
}
});
});
</script>
<?php
global $SPPATHS;
$group = $group = spdb_table(SFGROUPS, "group_id=$group_id", "row");
spa_paint_options_init();
$ahahURL = SFHOMEURL.'index.php?sp_ahah=forums-loader&sfnonce='.wp_create_nonce('forum-ahah').'&saveform=editgroup';
?>
<form action="<?php echo $ahahURL; ?>" method="post" id="sfgroupedit<?php echo $group->group_id; ?>" name="sfgroupedit<?php echo $group->group_id; ?>">
<?php
echo sp_create_nonce('forum-adminform_groupedit');
spa_paint_open_tab(spa_text('Forums').' - '.spa_text('Manage Groups and Forums'));
spa_paint_open_panel();
spa_paint_open_fieldset(spa_text('Edit Group'), 'true', 'edit-forum-group', false);
?>
<input type="hidden" name="group_id" value="<?php echo $group->group_id; ?>" />
<input type="hidden" name="cgroup_name" value="<?php echo sp_filter_title_display($group->group_name); ?>" />
<input type="hidden" name="cgroup_desc" value="<?php echo sp_filter_text_edit($group->group_desc); ?>" />
<input type="hidden" name="cgroup_seq" value="<?php echo $group->group_seq; ?>" />
<input type="hidden" name="cgroup_icon" value="<?php echo esc_attr($group->group_icon); ?>" />
<input type="hidden" name="cgroup_rss" value="<?php echo $group->group_rss; ?>" />
<input type="hidden" name="cgroup_message" value="<?php echo sp_filter_text_edit($group->group_message); ?>" />
<table class="form-table">
<tr>
<td class="sflabel"><?php spa_etext('Group name') ?>:</td>
<td><input type="text" class=" sfpostcontrol" size="45" name="group_name" value="<?php echo sp_filter_title_display($group->group_name); ?>" /></td>
</tr><tr>
<td class="sflabel"><?php spa_etext('Description') ?>: </td>
<td><input type="text" class=" sfpostcontrol" size="85" name="group_desc" value="<?php echo sp_filter_text_edit($group->group_desc); ?>" /></td>
</tr><tr>
<?php
echo spa_group_sequence_options('edit', $group->group_seq);
?>
</tr><tr>
<td class="sflabel"><?php spa_etext('Custom icon') ?></td>
<td>
<?php spa_select_icon_dropdown('group_icon', spa_text('Select Icon'), SF_STORE_DIR.'/'.$SPPATHS['custom-icons'].'/', $group->group_icon); ?>
</td>
</tr><tr>
<td class="sflabel"><?php spa_etext('Replacement external RSS URL') ?>:<br /><?php spa_etext('Default'); ?>: <strong><?php echo sp_get_sfqurl(sp_build_url('', '', 0, 0, 0, 1)).'group='.$group->group_id; ?></strong></td>
<td><input class="sfpostcontrol" type="text" name="group_rss" size="45" value="<?php echo sp_filter_url_display($group->group_rss); ?>" /></td>
</tr><tr>
<td class="sflabel"><?php spa_etext('Special group message to be displayed above forums') ?>:</td>
<td><textarea class="sfpostcontrol" cols="65" rows="3" name="group_message"><?php echo sp_filter_text_edit($group->group_message); ?></textarea></td>
</tr>
<?php do_action('sph_forums_edit_group_panel'); ?>
</table>
<br /><br />
<?php spa_etext('Set default usergroup permission sets for this group') ?>
<br /><br />
<?php spa_etext('Note - This will not will add or modify any current permissions. It is only a default setting for future forums created in this group. Existing default usergroup settings will be shown in the drop down menus') ?>
<table class="form-table">
<?php
$usergroups = spa_get_usergroups_all();
foreach ($usergroups as $usergroup) {
?>
<tr>
<td class="sflabel"><?php echo sp_filter_title_display($usergroup->usergroup_name); ?>:
<input type="hidden" name="usergroup_id[]" value="<?php echo $usergroup->usergroup_id; ?>" /></td>
<?php $roles = sp_get_all_roles(); ?>
<td class="sflabel"><select style="width:165px" class='sfacontrol' name='role[]'>
<?php
$defrole = spa_get_defpermissions_role($group->group_id, $usergroup->usergroup_id);
$out = '';
if ($defrole == -1 || $defrole == '') {
$out = '<option value="-1">'.spa_text('Select permission set').'</option>';
}
foreach($roles as $role)
{
$selected = '';
if ($defrole == $role->role_id)
{
$selected = 'selected="selected" ';
}
$out.='<option '.$selected.'value="'.$role->role_id.'">'.sp_filter_title_display($role->role_name).'</option>'."\n";
}
echo $out;
?>
</select>
</td>
</tr>
<?php } ?>
</table>
<?php
spa_paint_close_fieldset(false);
spa_paint_close_panel();
spa_paint_close_tab();
?>
<div class="sfform-submit-bar">
<input type="submit" class="button-primary" id="groupedit<?php echo $group->group_id; ?>" name="groupedit<?php echo $group->group_id; ?>" value="<?php spa_etext('Update Group'); ?>" />
<input type="button" class="button-primary" onclick="javascript:jQuery('#group-<?php echo $group->group_id; ?>').html('');" id="sfgroupedit<?php echo $group->group_id; ?>" name="groupeditcancel<?php echo $group->group_id; ?>" value="<?php spa_etext('Cancel'); ?>" />
</div>
</form>
<div class="sfform-panel-spacer"></div>
<?php
}
?> | gpl-2.0 |
piratskul/MyAwesomeDrupal | sites/default/files/php/twig/590e4b87c5da1_form-element.html.twig_Jxz5wB641U2U4GZowYwrdmu9P/i5Lypgx8achkp39jh4KlRPbYEsc9N52gjha8CpnNxs4.php | 12470 | <?php
/* core/themes/classy/templates/form/form-element.html.twig */
class __TwigTemplate_cca7cb74aef7f11f68b7bf99dfcec953a9a958274ae851384358ebb696a83d5b extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("set" => 48, "if" => 67);
$filters = array("clean_class" => 51);
$functions = array();
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('set', 'if'),
array('clean_class'),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 48
$context["classes"] = array(0 => "js-form-item", 1 => "form-item", 2 => ("js-form-type-" . \Drupal\Component\Utility\Html::getClass( // line 51
(isset($context["type"]) ? $context["type"] : null))), 3 => ("form-type-" . \Drupal\Component\Utility\Html::getClass( // line 52
(isset($context["type"]) ? $context["type"] : null))), 4 => ("js-form-item-" . \Drupal\Component\Utility\Html::getClass( // line 53
(isset($context["name"]) ? $context["name"] : null))), 5 => ("form-item-" . \Drupal\Component\Utility\Html::getClass( // line 54
(isset($context["name"]) ? $context["name"] : null))), 6 => ((!twig_in_filter( // line 55
(isset($context["title_display"]) ? $context["title_display"] : null), array(0 => "after", 1 => "before"))) ? ("form-no-label") : ("")), 7 => ((( // line 56
(isset($context["disabled"]) ? $context["disabled"] : null) == "disabled")) ? ("form-disabled") : ("")), 8 => (( // line 57
(isset($context["errors"]) ? $context["errors"] : null)) ? ("form-item--error") : ("")));
// line 61
$context["description_classes"] = array(0 => "description", 1 => ((( // line 63
(isset($context["description_display"]) ? $context["description_display"] : null) == "invisible")) ? ("visually-hidden") : ("")));
// line 66
echo "<div";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 67
if (twig_in_filter((isset($context["label_display"]) ? $context["label_display"] : null), array(0 => "before", 1 => "invisible"))) {
// line 68
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true));
echo "
";
}
// line 70
echo " ";
if ( !twig_test_empty((isset($context["prefix"]) ? $context["prefix"] : null))) {
// line 71
echo " <span class=\"field-prefix\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["prefix"]) ? $context["prefix"] : null), "html", null, true));
echo "</span>
";
}
// line 73
echo " ";
if ((((isset($context["description_display"]) ? $context["description_display"] : null) == "before") && $this->getAttribute((isset($context["description"]) ? $context["description"] : null), "content", array()))) {
// line 74
echo " <div";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["description"]) ? $context["description"] : null), "attributes", array()), "html", null, true));
echo ">
";
// line 75
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["description"]) ? $context["description"] : null), "content", array()), "html", null, true));
echo "
</div>
";
}
// line 78
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true));
echo "
";
// line 79
if ( !twig_test_empty((isset($context["suffix"]) ? $context["suffix"] : null))) {
// line 80
echo " <span class=\"field-suffix\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["suffix"]) ? $context["suffix"] : null), "html", null, true));
echo "</span>
";
}
// line 82
echo " ";
if (((isset($context["label_display"]) ? $context["label_display"] : null) == "after")) {
// line 83
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true));
echo "
";
}
// line 85
echo " ";
if ((isset($context["errors"]) ? $context["errors"] : null)) {
// line 86
echo " <div class=\"form-item--error-message\">
<strong>";
// line 87
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["errors"]) ? $context["errors"] : null), "html", null, true));
echo "</strong>
</div>
";
}
// line 90
echo " ";
if ((twig_in_filter((isset($context["description_display"]) ? $context["description_display"] : null), array(0 => "after", 1 => "invisible")) && $this->getAttribute((isset($context["description"]) ? $context["description"] : null), "content", array()))) {
// line 91
echo " <div";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($this->getAttribute((isset($context["description"]) ? $context["description"] : null), "attributes", array()), "addClass", array(0 => (isset($context["description_classes"]) ? $context["description_classes"] : null)), "method"), "html", null, true));
echo ">
";
// line 92
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["description"]) ? $context["description"] : null), "content", array()), "html", null, true));
echo "
</div>
";
}
// line 95
echo "</div>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/form/form-element.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 139 => 95, 133 => 92, 128 => 91, 125 => 90, 119 => 87, 116 => 86, 113 => 85, 107 => 83, 104 => 82, 98 => 80, 96 => 79, 91 => 78, 85 => 75, 80 => 74, 77 => 73, 71 => 71, 68 => 70, 62 => 68, 60 => 67, 55 => 66, 53 => 63, 52 => 61, 50 => 57, 49 => 56, 48 => 55, 47 => 54, 46 => 53, 45 => 52, 44 => 51, 43 => 48,);
}
public function getSource()
{
return "{#
/**
* @file
* Theme override for a form element.
*
* Available variables:
* - attributes: HTML attributes for the containing element.
* - errors: (optional) Any errors for this form element, may not be set.
* - prefix: (optional) The form element prefix, may not be set.
* - suffix: (optional) The form element suffix, may not be set.
* - required: The required marker, or empty if the associated form element is
* not required.
* - type: The type of the element.
* - name: The name of the element.
* - label: A rendered label element.
* - label_display: Label display setting. It can have these values:
* - before: The label is output before the element. This is the default.
* The label includes the #title and the required marker, if #required.
* - after: The label is output after the element. For example, this is used
* for radio and checkbox #type elements. If the #title is empty but the
* field is #required, the label will contain only the required marker.
* - invisible: Labels are critical for screen readers to enable them to
* properly navigate through forms but can be visually distracting. This
* property hides the label for everyone except screen readers.
* - attribute: Set the title attribute on the element to create a tooltip but
* output no label element. This is supported only for checkboxes and radios
* in \\Drupal\\Core\\Render\\Element\\CompositeFormElementTrait::preRenderCompositeFormElement().
* It is used where a visual label is not needed, such as a table of
* checkboxes where the row and column provide the context. The tooltip will
* include the title and required marker.
* - description: (optional) A list of description properties containing:
* - content: A description of the form element, may not be set.
* - attributes: (optional) A list of HTML attributes to apply to the
* description content wrapper. Will only be set when description is set.
* - description_display: Description display setting. It can have these values:
* - before: The description is output before the element.
* - after: The description is output after the element. This is the default
* value.
* - invisible: The description is output after the element, hidden visually
* but available to screen readers.
* - disabled: True if the element is disabled.
* - title_display: Title display setting.
*
* @see template_preprocess_form_element()
*/
#}
{%
set classes = [
'js-form-item',
'form-item',
'js-form-type-' ~ type|clean_class,
'form-type-' ~ type|clean_class,
'js-form-item-' ~ name|clean_class,
'form-item-' ~ name|clean_class,
title_display not in ['after', 'before'] ? 'form-no-label',
disabled == 'disabled' ? 'form-disabled',
errors ? 'form-item--error',
]
%}
{%
set description_classes = [
'description',
description_display == 'invisible' ? 'visually-hidden',
]
%}
<div{{ attributes.addClass(classes) }}>
{% if label_display in ['before', 'invisible'] %}
{{ label }}
{% endif %}
{% if prefix is not empty %}
<span class=\"field-prefix\">{{ prefix }}</span>
{% endif %}
{% if description_display == 'before' and description.content %}
<div{{ description.attributes }}>
{{ description.content }}
</div>
{% endif %}
{{ children }}
{% if suffix is not empty %}
<span class=\"field-suffix\">{{ suffix }}</span>
{% endif %}
{% if label_display == 'after' %}
{{ label }}
{% endif %}
{% if errors %}
<div class=\"form-item--error-message\">
<strong>{{ errors }}</strong>
</div>
{% endif %}
{% if description_display in ['after', 'invisible'] and description.content %}
<div{{ description.attributes.addClass(description_classes) }}>
{{ description.content }}
</div>
{% endif %}
</div>
";
}
}
| gpl-2.0 |
akunft/fastr | com.oracle.truffle.r.nodes/src/com/oracle/truffle/r/nodes/access/vector/ReplaceS4ObjectNode.java | 2439 | /*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.nodes.access.vector;
import static com.oracle.truffle.r.runtime.RError.Message.NO_METHOD_ASSIGNING_SUBSET_S4;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.r.nodes.objects.GetS4DataSlot;
import com.oracle.truffle.r.nodes.objects.GetS4DataSlotNodeGen;
import com.oracle.truffle.r.runtime.RError;
import com.oracle.truffle.r.runtime.RType;
import com.oracle.truffle.r.runtime.data.RNull;
import com.oracle.truffle.r.runtime.data.RS4Object;
import com.oracle.truffle.r.runtime.data.RTypedValue;
public class ReplaceS4ObjectNode extends Node {
@Child private GetS4DataSlot getS4DataSlotNode = GetS4DataSlotNodeGen.create(RType.Environment);
@Child private ReplaceVectorNode replaceVectorNode;
public ReplaceS4ObjectNode(ElementAccessMode mode, boolean ignoreRecursive) {
replaceVectorNode = ReplaceVectorNode.create(mode, ignoreRecursive);
}
public Object execute(RS4Object obj, Object[] positions, Object values) {
RTypedValue dataSlot = getS4DataSlotNode.executeObject(obj);
if (dataSlot == RNull.instance) {
throw RError.error(RError.SHOW_CALLER, NO_METHOD_ASSIGNING_SUBSET_S4);
}
// No need to update the data slot, the value is env and they have reference semantics.
replaceVectorNode.execute(dataSlot, positions, values);
return obj;
}
}
| gpl-2.0 |
uniqname/ariellemartin15.com | wp-content/themes/fjords/functions.php | 3041 | <?php
/**
* @package WordPress
* @subpackage Fjords
*/
if ( function_exists( 'register_sidebars' ) )
register_sidebars( 3 );
function resize_youtube( $content ) {
return str_replace( "width='425' height='350'></embed>", "width='240' height='197'></embed>", $content );
}
add_filter( 'the_content', 'resize_youtube', 999 );
load_theme_textdomain( 'fjords', TEMPLATEPATH . '/languages' );
add_theme_support( 'automatic-feed-links' );
$themecolors = array(
'bg' => 'ffffff',
'text' => '888888',
'link' => '8ab459',
'border' => 'dee4da',
'url' => '63b4cd',
);
$content_width = 270;
define( 'HEADER_TEXTCOLOR', 'ffffff' );
define( 'HEADER_IMAGE', '%s/imagenes_qwilm/beach.jpg' ); // %s is theme dir uri
define( 'HEADER_IMAGE_WIDTH', 900 );
define( 'HEADER_IMAGE_HEIGHT', 200 );
function header_style() {
?>
<style type="text/css">
#content, #sidebar-1, #sidebar-2, #sidebar-3 {
background-image:url(<?php header_image(); ?>);
}
<?php if ( 'blank' == get_header_textcolor() ) { ?>
#hode h4, #hode span {
display: none;
}
<?php } else { ?>
#hode a, #hode {
color: #<?php header_textcolor(); ?>;
}
<?php } ?>
</style>
<?php
}
function admin_header_style() {
?>
<style type="text/css">
#headimg {
height: <?php echo HEADER_IMAGE_HEIGHT; ?>px;
width: <?php echo HEADER_IMAGE_WIDTH; ?>px;
}
#headimg h1 {
font-family: "Lucida Grande",Tahoma,Arial,sans-serif;
font-size: 17px;
font-weight: bold;
margin-left: 15px;
padding-top: 15px;
}
#headimg h1 a {
color:#<?php header_textcolor(); ?>;
border: none;
text-decoration: none;
}
#headimg a:hover
{
text-decoration:underline;
}
#headimg #desc
{
font-weight:normal;
color:#<?php header_textcolor(); ?>;
margin-left: 15px;
padding: 0;
margin-top: -10px;
font-family: "Lucida Grande",Tahoma,Arial,sans-serif;
font-size: 11px;
}
<?php if ( 'blank' == get_header_textcolor() ) { ?>
#headerimg h1, #headerimg #desc {
display: none;
}
#headimg h1 a, #headimg #desc {
color:#<?php echo HEADER_TEXTCOLOR ?>;
}
<?php } ?>
</style>
<?php }
add_custom_image_header( 'header_style', 'admin_header_style' );
add_custom_background();
function fjords_comment( $comment, $args, $depth ) {
$GLOBALS[ 'comment' ] = $comment;
extract( $args, EXTR_SKIP );
?>
<div <?php comment_class( empty( $args[ 'has_children' ] ) ? '' : 'parent' ); ?> id="comment-<?php comment_ID(); ?>">
<div id="div-comment-<?php comment_ID(); ?>">
<div class="comentarios">
<span class="comment-author vcard"><?php if ( $args[ 'avatar_size' ] != 0 ) echo get_avatar( $comment, $args[ 'avatar_size' ] ); ?>
<span class="fn"><a href="<?php comment_author_url(); ?>">
<?php printf ( __( '%1$s wrote @ %2$s at %3$s' ), comment_author() . '</a></span>' , '<span class="comment-meta commentmetadata">' . get_comment_date(), get_comment_time().'</span>' ) ?>
</span>
</div>
<?php comment_text(); ?>
<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args[ 'max_depth' ] ) ) ); ?>
</div>
</div>
<?php
} | gpl-2.0 |
seecr/cqlparser | cqlparser/cql2string.py | 2587 | ## begin license ##
#
# "CQLParser" is a parser that builds a parsetree for the given CQL and can convert this into other formats.
#
# Copyright (C) 2005-2010 Seek You Too (CQ2) http://www.cq2.nl
# Copyright (C) 2018, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
# Copyright (C) 2021 Data Archiving and Network Services https://dans.knaw.nl
# Copyright (C) 2021 SURF https://www.surf.nl
# Copyright (C) 2021 Stichting Kennisnet https://www.kennisnet.nl
# Copyright (C) 2021 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
#
# This file is part of "CQLParser"
#
# "CQLParser" 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.
#
# "CQLParser" 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 "CQLParser"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from .cqlvisitor import CqlVisitor
from re import compile
quottableTermChars = compile(r'[\"\(\)\>\=\<\/\s]')
class Cql2StringVisitor(CqlVisitor):
def visitSEARCH_CLAUSE(self, node):
children = node.visitChildren(self)
return ''.join(children)
def visitMODIFIER(self, node):
children = node.visitChildren(self)
return '/'+''.join(children)
def visitRELATION(self, node):
children = node.visitChildren(self)
result = ''.join(children)
if result == '=':
return result
return ' %s ' % result
def visitCQL_QUERY(self, node):
return '(%s)' % self._joinChildren(node)
def visitTERM(self, node):
term = CqlVisitor.visitTERM(self, node)
return quotTerm(term)
def _joinChildren(self, node):
children = node.visitChildren(self)
return ' '.join(children)
visitSEARCH_TERM = _joinChildren
visitSCOPED_CLAUSE = _joinChildren
visitINDEX = _joinChildren
visitMODIFIERLIST = _joinChildren
def cql2string(ast):
return Cql2StringVisitor(ast).visit()[1:-1]
def quotTerm(term):
if not term:
return term
if quottableTermChars.search(term):
return '"%s"' % term.replace(r'"', r'\"')
return term
| gpl-2.0 |
threedots/ThreedotsSSOServer | src/TestEngine/Bundle/SsoBundle/Service/SSOServer.php | 6927 | <?php
namespace TestEngine\Bundle\SsoBundle\Service;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SSOServer extends Base
{
protected $started = false;
protected $broker = null;
/**
* Information of the brokers.
* This should be data in a database.
*
* @var array
*/
protected static $brokers = array(
'ALEX' => array('secret'=>"abc123"),
'BINCK' => array('secret'=>"xyz789"),
'UZZA' => array('secret'=>"rino222"),
'AJAX' => array('secret'=>"amsterdam"),
'LYNX' => array('secret'=>"klm345"),
);
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
$this->links_path = sys_get_temp_dir();
}
/**
* Start session and protect against session hijacking
*/
protected function sessionStart()
{
if ($this->started) {
return;
}
$this->started = true;
$matches = null;
$sessionName = $this->get('session')->getName();
//$_REQUEST = array_merge($_REQUEST, $_COOKIE);
if (isset($_COOKIE[$sessionName]) && preg_match('/^SSO-(\w*+)-(\w*+)-([a-z0-9]*+)$/', $_COOKIE[$sessionName], $matches)) {
$sid = $_COOKIE[$sessionName];
$result = $this->get('users_repository')->getBySSOCode($sid);
if (isset($result['link'])) {
//$this->get('session')->setId($result['link']);
$this->get('session')->start();
$this->cookies->set($sessionName, '');
} else {
$this->get('session')->start();
}
$clientAddress = $this->get('session')->get('client_addr');
$clientAddress = '127.0.0.1';
if (!isset($clientAddress)) {
//$this->get('session')->invalidate();
$this->fail("Not attached");
}
if ($this->generateSessionId($matches[1], $matches[2], $clientAddress) != $sid) {
//$this->get('session')->invalidate();
$this->fail("Invalid session id");
}
$this->broker = $matches[1];
return;
}
$this->get('session')->start();
$clientAddress = $this->get('session')->get('client_addr');
$serverArr = Request::createFromGlobals()->server;
$remoteIP = $serverArr->get('REMOTE_ADDR');
if (isset($clientAddress) && $clientAddress != $remoteIP) {
$this->get('session')->migrate(true);
}
if (!isset($clientAddress)) {
$this->get('session')->set('client_addr', $remoteIP);
}
}
/**
* Generate session id from session token
*
* @param $broker
* @param $token
* @param null $client_address
* @return string
*/
protected function generateSessionId($broker, $token, $client_address = null)
{
$client_address = '127.0.0.1';
if (!isset(self::$brokers[$broker])) {
return null;
}
$serverArr = Request::createFromGlobals()->server;
if (!isset($client_address)) {
$client_address = $serverArr->get('REMOTE_ADDR');
}
return "SSO-{$broker}-{$token}-" . md5('session' . $token . $client_address . self::$brokers[$broker]['secret']);
}
/**
* Generate session id from session token
*
* @param $broker
* @param $token
* @return string
*/
protected function generateAttachChecksum($broker, $token)
{
if (!isset(self::$brokers[$broker])) {
return null;
}
$serverArr = Request::createFromGlobals()->server;
$ip = '127.0.0.1';
return md5('attach' . $token . $ip . self::$brokers[$broker]['secret']);
}
/**
* authenticate
*
*/
public function login()
{
$this->sessionStart();
if (empty($_POST['username'])) {
$this->failLogin("No user specified");
}
if (empty($_POST['password'])) {
$this->failLogin("No password specified");
}
$userInfo = $this->get('users_repository')->getUserInfoByEmailAndPassword($_POST['username'], $_POST['password']);
if( !$userInfo) {
$this->failLogin("Incorrect credentials");
}
$this->get('session')->set('user', $userInfo);
return $this->getUserInformation();
}
public function logout()
{
$this->sessionStart();
$this->get('session')->invalidate();
unset($_COOKIE);
$this->get('users_repository')->removeSSOLinks();
echo 1;
}
/**
* Attach a user session to a broker session
*/
public function attach()
{
$this->sessionStart();
if (empty($_REQUEST['broker'])) {
$this->fail("No broker specified");
}
if (empty($_REQUEST['token'])) {
$this->fail("No token specified");
}
if (empty($_REQUEST['checksum']) || $this->generateAttachChecksum($_REQUEST['broker'], $_REQUEST['token']) != $_REQUEST['checksum']) {
$this->fail("Invalid checksum");
}
$sid = $this->generateSessionId($_REQUEST['broker'], $_REQUEST['token']);
$result = $this->get('users_repository')->getBySSOCode($sid);
$userRepo = $this->get('users_repository');
if (!isset($result['link'])) {
$attached = $userRepo->insertSsoSessionId($sid, $this->get('session')->getId());
symlink('sess_' . $this->get('session')->getId(), realpath($sid));
if (!$attached) {
trigger_error("Failed to attach; Symlink wasn't created.", E_USER_ERROR);
}
} else {
$attached = $userRepo->updateSsoSessionId($sid, $this->get('session')->getId());
if (!$attached) {
trigger_error("Failed to attach; Link file wasn't created.", E_USER_ERROR);
}
}
if (isset($_REQUEST['redirect'])) {
header("Location: " . $_REQUEST['redirect'], true, 307);
exit;
}
// Output an image specially for AJAX apps
header("Content-Type: image/png");
readfile("empty.png");
}
public function getUserInformation()
{
$this->sessionStart();
$user = $this->get('session')->get('user');
if (!isset($user)) {
$this->failLogin("Not logged in");
}
return $user;
}
protected function fail($message)
{
header("HTTP/1.1 406 Not Acceptable");
echo $message;
exit;
}
protected function failLogin($message)
{
header("HTTP/1.1 401 Unauthorized");
//echo $message;
return false;
}
} | gpl-2.0 |
chrplace/fuzzy-octo-lana | contents/scripts/slider-value.js | 361 | $("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value.toFixed(1));
window.freq = data.value.toFixed(1);
});
| gpl-2.0 |
microresearch/diana | poetry.py | 4669 | from __future__ import division
import re
import urllib2
from curses.ascii import isdigit
from nltk.corpus import cmudict
d = cmudict.dict()
from nltk.corpus.util import LazyCorpusLoader
from nltk.corpus.reader import *
suffdict = LazyCorpusLoader(
'cmusuffdict', CMUDictCorpusReader, ['cmusuffdict'])
suffdict = suffdict.dict()
def try_syllable(syl):
''' helper function for phonemes()
Tests if syl is in suffdict. If not, removes the first letter
and then the first two letters, checking each time
'''
if syl in suffdict:
return suffdict[syl][0]
# else try without the first letter
elif syl[1:] in suffdict:
return suffdict[syl[1:]][0]
# else try without the first 2 letters
elif syl[2:] in suffdict:
return suffdict[syl[2:]][0]
# else return None, which the calling function should check for
else:
return None
def phonemes(word):
word = word.lower()
# If in cmudict, just use cmudict
if word in d:
return min(d[word], key=len)
# If not, try to use my cmu-based last syllable dictionary
# if we cannot detect the last syllable, give up
syl_re = re.compile("([bcdfghjklmnpqrstvwxz]{1,2}[aeiouy]+[bcdfghjklmnpqrstvwxz]*(e|ed)?('[a-z]{1,2})?)(?![a-zA-Z]+)")
if not syl_re.search(word):
return False
last_syl = syl_re.search(word).group()
# now try the last syllable against cmusuffdict
p = try_syllable(last_syl)
if p:
return p
# else try without the last 2 letters, if it ends in 's
elif last_syl[-2:] == "'s":
p = try_syllable(last_syl[:-2])
if p:
return p.append('Z')
else:
return False
# else try without the last letter, if it ends in s
elif last_syl[-1] == "s":
p = try_syllable(last_syl[:-1])
if p:
return p.append('Z')
else:
return False
else: # If not in cmudict or my cmusuffdict
return False
def approx_nsyl(word):
digraphs = {"ai", "au", "ay", "ea", "ee", "ei", "ey", "oa", "oe", "oi", "oo", "ou", "oy", "ua", "ue", "ui"}
# Ambiguous, currently split: ie, io
# Ambiguous, currently kept together: ui
count = 0
array = re.split("[^aeiouy]+", word.lower())
for i, v in enumerate(array):
if len(v) > 1 and v not in digraphs:
count += 1
if v == '':
del array[i]
count += len(array)
if re.search("(?<=\w)(ion|ious|(?<!t)ed|es|[^lr]e)(?![a-z']+)", word.lower()):
count -= 1
if re.search("'ve|n't", word.lower()):
count += 1
return count
def nsyl(word):
# return the min syllable count in the case of multiple pronunciations
if not word.lower() in d:
return approx_nsyl(word)
return min([len([y for y in x if isdigit(y[-1])]) for x in d[word.lower()]])
# For example: d["concatenate".lower()] == [['K', 'AH0', 'N', 'K', 'AE1', 'T', 'AH0', 'N', 'EY2', 'T']]
# Oh, and those numbers are actually stress/inflection (0: no stress, 1: primary stress, 2: secondary stress)
# This grabs each item where the last character is a digit (how cmudict represents vowel sounds), and counts them
# Ignores stress for now, while I'm not taking meter into account
def rhyme_from_phonemes(list1, list2):
i = -1
while i >= 0 - len(list1):
# print list1[i][-1]
if isdigit(str(list1[i][-1])):
if i >= 0 - len(list2) and list1[i][:-1] == list2[i][:-1] and (i == -1 or list1[i + 1:] == list2[i + 1:]):
return True
else:
return False
i -= 1
def rhyme(word1, word2):
try:
list1 = min(d[word1.lower()], key=len)
list2 = min(d[word2.lower()], key=len)
return rhyme_from_phonemes(list1, list2)
except:
return False
def tokenize_text(text):
text = re.sub("[^a-zA-Z\s'-]", '', text)
text = re.sub("'(?![a-z]{1,2})", '', text)
tokens = re.split("\s+|-", text)
# remove empty tokens
tokens = filter(None, tokens)
return tokens
def tokenize(file_path):
with open(file_path) as f:
data = f.read().strip()
return tokenize_text(data)
def tokenize_from_url(url):
data = urllib2.urlopen(url).read().strip()
return tokenize_text(data)
# Thinking about meter:
# In "there once" [was a man from Nantucket], I'd want to see that "there" is unstressed, and "once" is stressed
# But cmudict sees the single vowel in each of them as 1 (primary stress), because it looks at each word in isolation
# Maybe for now just assume than monosyllabic words are flexible, and use cmudict for stress on polysyllabic words?
| gpl-2.0 |
nikhilsharma869/bio-pharma-dev | publicprofile.php | 36073 | <?php
$current_page = "Profile details";
include "includes/header.php";
include("country.php");
$row_user = mysql_fetch_array(mysql_query("select * from " . $prev . "user, " . $prev . "user_profile where " . $prev . "user_profile.user_id=" . $prev . "user.user_id and " . $prev . "user.username = '" . $_GET[username] . "'"));
if (!empty($row_user[logo])) {
$temp_logo = $row_user[logo];
} else {
$temp_logo = "images/face_icon.gif";
}
?>
<div class="user-profile-area">
<div class="user-profile-banner">
<!-- <img src="<?= $vpath ?>/images/profile_banner.jpg"> -->
<?php if(empty($row_user['banner'])) { ?>
<img src="http://placehold.it/1260x320">
<?php } else { ?>
<img src="<?= $vpath ?>viewimage.php?img=<?php echo $row_user['banner']; ?>&width=1260&height=320">
<!-- <img src="<?= $vpath.$row_user['banner'] ?>"> -->
<?php } ?>
<?php if(!empty($_SESSION['user_id']) && $_SESSION['user_id'] == $row_user['user_id']) { ?>
<div class="up-banner-manage">
<a href="#" class="up-banner-edit" data-toggle="modal" data-target="#md-edit-banner"><i class="fa fa-pencil-square-o"></i> Edit</a>
</div>
<?php } ?>
</div>
<div class="user-profile-container">
<div class="user-profile-header">
<div class="up-avatar">
<img src="<?= $vpath ?>viewimage.php?img=<?php echo $temp_logo; ?>&width=200&height=200" alt="" />
</div>
<div class="up-infors">
<h1 class="up-name"><?= ucwords($row_user['fname']) . ' ' . ucwords($row_user['lname']); ?></h1>
<p class="up-slogan"><?= ucfirst($row_user[slogan]) ?></p>
</div>
</div>
<div class="clear-fix"></div>
<div class="user-profile-sidebar">
<?php if(!empty($_SESSION['user_id'])) { ?>
<?php if($_SESSION['user_type'] == 'E' && $_SESSION['user_id'] != $row_user['user_id']) { ?>
<div class="dropdown pb-drd">
<a id="dLabel" class="mt-action-profile" data-toggle="dropdown" data-target="#" href="/page.html">
Action
</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li><a href="javascript:;" onclick="getinvite()">Invite</a></li>
</ul>
</div>
<?php
$n = mysql_num_rows(mysql_query("select * from " . $prev . "wishlist where user_id='" . $_SESSION['user_id'] . "' and uid='" . $row_user['user_id'] . "'"));
?>
<a href="javascript:void(0);" onclick="addwistlist('<?= $row_user['user_id'] ?>');" style="cursor:pointer"><span id="addlist">
<?php if ($n == 0) { ?>
<img src='<?= $vpath ?>images/unfill.png' border=0 align=absmiddle alt='add to wishlist' title='add to wishlist'>
<?php } else { ?>
<img src='<?= $vpath ?>images/fill.png' border=0 align=absmiddle alt='added to wishlist' title='added to wishlist'>
<?php } ?>
</span>
</a>
<?php } else { ?>
<a class="up-contact" href="javascript:;">Contact</a>
<?php } ?>
<?php } ?>
<ul id="up-tabs" class="nav nav-tabs" role="tablist" style="margin-top: 30px;">
<li class="active"><a class="up-icon-overview" href="#up-overview">Overview</a></li>
<?php if(!empty($_SESSION['user_id'])) { ?>
<li><a class="up-icon-portfolio" href="#up-portfolio">Portfolio</a></li>
<li><a class="up-icon-feedback" href="#up-feedback">Feedback</a></li>
<?php } ?>
<li><a class="up-icon-skills" href="#up-overview">Skills</a></li>
</ul>
<?php if(!empty($_SESSION['user_id'])) { ?>
<div class="boxright" id="invidebox">
<h2><?= $lang['INVT_PROV'] ?></h2>
<div id="addinvite" align="center"></div>
<?php
$proj_sql_num = @mysql_num_rows(mysql_query("select id from " . $prev . "projects where user_id='" . $_SESSION[user_id] . "' and status='open'"));
if ($proj_sql_num > 0) {
?>
<div class="invitebox_section">
<span><?= $lang['SELECT_PROJECT'] ?>:</span>
</div>
<div class="invitebox_section">
<select name="proj" class="from_input_box" style="width:200px" id="project_id_val">
<?php
$proj_sql = @mysql_query("select * from " . $prev . "projects where user_id='" . $_SESSION[user_id] . "' and status='open'");
while ($proj_fetch = @mysql_fetch_array($proj_sql)) {
?>
<option value="<?= $proj_fetch['id'] ?>"><?= $proj_fetch['project'] ?></option>
<?php } ?>
</select>
</div>
<div class="invitebox_section">
<input type="hidden" id="f_name" name="f_name" size="52" value="<? print $row_user[fname]; ?>">
<input type="hidden" id="l_name" name="l_name" size="52" value="<? print $row_user[lname]; ?>">
<input type='button' border="0" class="submit_bott" value="<?= $lang['SEND'] ?>" name="send_submit" onclick="invideuser();">
</div>
<?php } else { ?>
<div style="margin: 10px auto;">
<div id="addinvite_post" align="center">
<a href="javascript:void(0)" onclick="postprojectinvite()">
<input type="button" name="Button" value="Post a New Project" class="submit_bott"/>
</a>
</div>
</div>
<?php } ?>
<input type="hidden" id="txtemail" name="txtemail" size="52" value="<? print $row_user[email]; ?>">
</div>
<?php } ?>
</div>
<div class="user-profile-data-area">
<div class="the-gru-of">
<h4>The Subject Matter Expert of</h4>
<?php
$skill_q = "select skills from " . $prev . "user_profile where user_id=" . $row_user[user_id];
$res_skill = mysql_query($skill_q);
$data_skills = @mysql_result($res_skill,0,"skills");
$data_skills = explode(',', $data_skills);
$count = 1;
foreach ($data_skills as $skill) {
if($count > 4 ) break;
$data_skill_name.= "<span><a href='javascript:;'>". $skill . '</a></span>';
$count++;
}
$skill_name = $data_skill_name;
echo $skill_name;
?>
</div>
<div id="up-content" class="tab-content">
<?php if(!empty($_SESSION['user_id'])) { ?>
<div class="up-content-section tab-pane" id="up-portfolio">
<div class="upps">
<h3>Portfolios</h3>
<?php if($_SESSION['user_id'] == $row_user['user_id']) { ?>
<div class="upload_bott"><a href="#" data-toggle="modal" data-target="#md-upload-folio">+ <?= $lang['UPLOAD_NEW'] ?></a></div>
<?php } ?>
</div>
<ul id="slider">
<?php
$rr = mysql_query("select * from " . $prev . "portfolio where user_id=" . $row_user['user_id'] . " and `status`='Y' order by id desc limit 20");
$pro = mysql_num_rows($rr);
if ($pro == "") {
echo '<div style="width:736px;padding:5px;float:left;" align="center">';
echo $lang['PORTF_NOT_UPD'];
echo '</div>';
} else {
$j = 0;
while ($f = mysql_fetch_array($rr)) {
$j++;
$date_up = explode('-', $f[add_date]);
$date = $date_up[2] . '-' . $date_up[1] . '-' . $date_up[0];
?>
<li>
<div class="prosl1"><img src="<?= $vpath ?>viewimage.php?img=<?= $f[image]; ?>&width=287&height=240" alt="" style="width: 295px;height: 242px;" /></div>
<div class="slidetxt">
<h2><?= substr($f[project_title], 0, 20); ?></h2>
<p style="font-size:12px;"><?= substr(nl2br($f[description]), 0, 200); ?></p>
<a href="http://<?= str_replace("http://", "", str_replace("https://", "", $f[link])) ?>" target="_blank"><?= $f[link] ?></a>
<?php if($f[attachment]):
$attachment_link = $vpath.$f[attachment];
?>
<a class="portfolio_attm" href="http://<?= str_replace("http://", "", str_replace("https://", "", $attachment_link)) ?>" target="_blank">Attachment</a>
<?php endif; ?>
<?php if($_SESSION['user_id'] == $row_user['user_id']) { ?>
<a class="portfolio_edit_btn" href="<?= $vpath ?>edit-portfolio/1/<?= $f['id'] ?>/"><span>Edit</span></a>
<?php } ?>
</div>
</li>
<?php
}
}
?>
</ul>
</div>
<div class="up-content-section tab-pane" id="up-feedback">
<h3>Feedback</h3>
<?php include("includes/puplic_review.php"); ?>
</div>
<?php } ?>
<div class="tab-pane active" id="up-overview">
<div class="up-content-section up-summary">
<h3>Summary</h3>
<p><?= $row_user['profile'] ?></p>
</div>
<div class="up-content-section up-experience">
<h3>Experience</h3>
<?php
$data_exps = $row_user['experience'];
$data_exps = json_decode($data_exps);
// echo "<pre>";
// var_dump($data_exps);
for($i=0;$i<count($data_exps->values);$i++) {
?>
<div class="up-content-view">
<h4><?php echo $data_exps->values[$i]->title; ?></h4>
<h5><?php echo $data_exps->values[$i]->company->name; ?></h5>
<span>
<?php
$begin = array ('year' => $data_exps->values[$i]->startDate->year, 'month' => $data_exps->values[$i]->startDate->month, 'day' => 1);
if($data_exps->values[$i]->isCurrent) {
$end = array ('year' => date('Y'), 'month' => date('m'), 'day' => 1);
} else {
$end = array ('year' => $data_exps->values[$i]->endDate->year, 'month' => $data_exps->values[$i]->endDate->month, 'day' => 1);
}
$date_diff = date_difference ($begin, $end);
echo date("F Y", mktime(0, 0, 0, $data_exps->values[$i]->startDate->month, 1 , $data_exps->values[$i]->startDate->year)); ?>
-
<?php if($data_exps->values[$i]->isCurrent) {
echo "Present";
} else {
echo date("F Y", mktime(0, 0, 0, $data_exps->values[$i]->endDate->month, 1 , $data_exps->values[$i]->endDate->year));
} ?>
<?php
// var_dump($date_diff);
if($date_diff['years'] == 1) {
echo '(' . $date_diff['years'] . ' year ';
} else if($date_diff['years'] > 1) {
echo '(' . $date_diff['years'] . ' years ';
} else if($date_diff['years'] == 0) {
echo '(';
}
if($date_diff['months'] == 0) {
echo '' . $date_diff['months']+1 . ' month)';
} else if($date_diff['months'] > 0) {
echo '' . $date_diff['months']+1 . ' months)';
}
?>
</span>
<?php if(isset($data_exps->values[$i]->summary)) { ?>
<p>
<?php echo $data_exps->values[$i]->summary; ?>
</p>
<?php } ?>
</div>
<?php
}
?>
</div>
<div class="up-content-section up-skills-endor">
<h3>Skills and Endorsements</h3>
<div id="profile-skills">
<h5>Top Skills</h5>
<ul class="skills-section">
<?php
$skills_linkedin = get_list_skill_linkedin();
foreach ($skills_linkedin['top_skill_skill'] as $sval) :
if (check_user_skill($sval['skill_name'], $row_user['user_id'])) :
?>
<li class="endorse-item">
<span class="skill-pill">
<a class="endorse-count" href="javascript:void(0)">
<span class="num-endorsements" data-count="1"><?php echo (int)$sval['skill_count'] - 1; ?></span>
</a>
<span class="endorse-item-name">
<a href="#" class="endorse-item-name-text"><?php echo $sval['skill_name']; ?></a>
</span>
</span>
<div class="endorsers-container">
<ul class="endorsers-pics">
<?php
$luser = get_list_user_by_skl($sval['skill_name'], $row_user['user_id']);
foreach ($luser as $user_data) :
?>
<li class="viewer-pic-container">
<span class="new-miniprofile-container">
<strong>
<img class="viewer-pic" src="<?= $vpath ?>viewimage.php?img=<?php echo $user_data['logo']; ?>&width=30&height=30" alt="" />
</strong>
</span>
</li>
<?php endforeach; ?>
<li class="endorsers-action">
<a class="see-all-endorsers" href="javascript:void(0)">
<span class="loader"></span>
</a>
</li>
</ul>
<span class="line-container"><span class="hr-line"></span></span>
</div>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<h5><?php echo $row_user['fname']; ?> also knows about...</h5>
<ul class="skills-section compact-view">
<?php foreach ($skills_linkedin['one_know_skill'] as $sval) :
if (check_user_skill($sval['skill_name'], $row_user['user_id'])) :
?>
<li class="endorse-item">
<div>
<span class="skill-pill">
<span class="endorse-item-name ">
<a href="#" class="endorse-item-name-text"><?php echo $sval['skill_name']; ?></a>
</span>
</span>
</div>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</div>
</div>
<div class="up-content-section up-education">
<h3>Education</h3>
<?php
$data_edus = $row_user['educations'];
$data_edus = json_decode($data_edus);
for($i=0;$i<count($data_edus->values);$i++) {
?>
<div class="up-content-view">
<h4><?php echo $data_edus->values[$i]->schoolName; ?></h4>
<h5><?php echo $data_edus->values[$i]->degree; ?></h5>
<span>
<?php
$begin = array ('year' => $data_edus->values[$i]->startDate->year, 'month' => $data_edus->values[$i]->startDate->month, 'day' => 1);
if($data_edus->values[$i]->isCurrent) {
$end = array ('year' => date('Y'), 'month' => date('m'), 'day' => 1);
} else {
$end = array ('year' => $data_edus->values[$i]->endDate->year, 'month' => $data_edus->values[$i]->endDate->month, 'day' => 1);
}
$date_diff = date_difference ($begin, $end);
echo date("F Y", mktime(0, 0, 0, $data_edus->values[$i]->startDate->month, 1 , $data_edus->values[$i]->startDate->year)); ?>
-
<?php if($data_edus->values[$i]->isCurrent) {
echo "Present";
} else {
echo date("F Y", mktime(0, 0, 0, $data_edus->values[$i]->endDate->month, 1 , $data_edus->values[$i]->endDate->year));
} ?>
<?php
// var_dump($date_diff);
if($date_diff['years'] == 1) {
echo '(' . $date_diff['years'] . ' year ';
} else if($date_diff['years'] > 1) {
echo '(' . $date_diff['years'] . ' years ';
} else if($date_diff['years'] == 0) {
echo '(';
}
if($date_diff['months'] == 0) {
echo '' . $date_diff['months']+1 . ' month)';
} else if($date_diff['months'] > 0) {
echo '' . $date_diff['months']+1 . ' months)';
}
?>
</span>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Upload Banner Modal -->
<div class="modal fade" id="md-edit-banner" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Banner Manager</h4>
</div>
<div class="modal-body">
<form role="form" name="upb-upload" id="upb-upload" method="post" enctype="multipart/form-data" action="<?=$vpath;?>bannerupload.php">
<div class="alert alert-success hide" role="alert"></div>
<div class="alert alert-warning hide" role="alert"></div>
<div class="form-group">
<label for="upb-upload-file">Upload Banner (1260x320)</label>
<input type="file" name="upb_upload_file" id="upb-upload-file">
</div>
<input type="hidden" name="upb_upload_userid" value="<?=$row_user['user_id']?>">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary upb-btn-submit">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Upload Portfolio -->
<div class="modal fade" id="md-upload-folio" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="">Upload Folio</h4>
</div>
<div class="modal-body">
<form action="<?= $vpath ?>upload-portfolio.html" method="post" enctype="multipart/form-data" name="exp_form" id="exp_form" onsubmit="return ValidateAndSubmit();">
<div class="alert alert-success hide" role="alert"></div>
<div class="alert alert-warning hide" role="alert"></div>
<table width="90%" align="center" border="0" cellspacing="0" cellpadding="0" >
<tr>
<td align="center" valign="top" class="bx-border">
<table width="100%" border="0" cellpadding="4" cellspacing="0" align="center" >
<tr class='link'>
<td ><?= $lang['PROJECT_TITLE'] ?> : *</td>
<td><input type="text" name="project_title" id="project_title" style='width:300px' value="" size="100" class="from_input_box" /></td>
</tr>
<tr class='link'>
<td ><?= $lang['DESCRIBING_SHORT'] ?> : *</td>
<td><textarea name="description" id="description" rows="5" cols="10" class="text_box"></textarea>
<br />
<div style="
float: left;
width: 200px;
"> <small><?= $lang['NOT_MORE_THAN'] ?></small></div></td>
</tr>
<tr class='link'>
<td >Tags: </td>
<td><input type="text" name="tags" style='width:300px' value="" size="100" class="from_input_box" /></td>
</tr>
<tr class='link'>
<td >Link: </td>
<td><input type="text" name="link" style='width:300px' value="" size="100" class="from_input_box" /></td>
</tr>
<tr class='link'>
<td ><?= $lang['PICTURES_EXAMPLES'] ?> : </td>
<td><input type="file" name="thumb" size="30" class="from_input_box" />
</td>
</tr>
<tr class='link'>
<td ><?= $lang['PORTFOLIO_ATTACHMENT'] ?> : </td>
<td><input type="file" id="portfolio_attachment" name="portfolio_attachment" size="30" class="from_input_box" />
</td>
</tr>
<tr class='link'>
<td ></td>
<input type="hidden" name='SBMT' value='Submit' /></td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-submit-folio">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#up-tabs a').click(function (e) {
e.preventDefault()
$(this).tab('show')
if($(this).hasClass('up-icon-skills')) {
$('body').animate({
scrollTop: $(".up-skills-endor").offset().top
},'slow');
}
})
$(function() {
$('#slider').anythingSlider({
hashTags: false
});
$('.upb-btn-submit').click(function(){
$('#upb-upload').ajaxSubmit({
success:function(data) {
if(data.trim() == 'success') {
$('#upb-upload .alert-success').html('Upload successfully.');
$('#upb-upload .alert-success').removeClass('hide');
location.reload();
}
if (data.trim() == 'empty_img') {
$('#upb-upload .alert-warning').html('Please select image to upload!');
$('#upb-upload .alert-warning').removeClass('hide');
}
if(data.trim() == 'error') {
$('#upb-upload .alert-warning').html('Could not upload!');
$('#upb-upload .alert-warning').removeClass('hide');
}
setTimeout(function(){
$('#upb-upload .alert').addClass('hide');
}, 4000);
}
});
})
$('#btn-submit-folio').click(function(){
if(document.getElementById("project_title").value=="") {
$('#exp_form .alert-warning').html("please enter project title");
$('#exp_form .alert-warning').removeClass('hide');
document.getElementById("project_title").focus();
setTimeout(function(){
$('#exp_form .alert').addClass('hide');
}, 3000);
return false;
}
if(document.getElementById("description").value=="") {
$('#exp_form .alert-warning').html("please enter description");
$('#exp_form .alert-warning').removeClass('hide');
document.getElementById("description").focus();
setTimeout(function(){
$('#exp_form .alert').addClass('hide');
}, 3000);
return false;
}
if(document.getElementById('portfolio_attachment').value!='') {
var filename = document.getElementById('portfolio_attachment').value;
var ext = filename.split('.');
var allow_exts = ["xls", "xlsx", "doc", "docx", "pdf"];
if(allow_exts.indexOf(ext[1]) == -1) {
$('#exp_form .alert-warning').html("Attachment allows only word, excel and pdf file!");
$('#exp_form .alert-warning').removeClass('hide');
setTimeout(function(){
$('#exp_form .alert').addClass('hide');
}, 3000);
return false;
}
}
$('#exp_form').ajaxSubmit({
success:function(data) {
var text = $(data).find('.mess-info > td > table > tbody > tr > td').text();
if(text == 'Portfolio details has been updated') {
$('#exp_form .alert-success').html(text);
$('#exp_form .alert-success').removeClass('hide');
location.reload();
} else {
$('#exp_form .alert-warning').html(text);
$('#exp_form .alert-warning').removeClass('hide');
}
setTimeout(function(){
$('#exp_form .alert').addClass('hide');
}, 4000);
}
})
});
});
function getinvite() {
$("#invidebox").slideDown('slow');
}
function invideuser() {
var txtemail = $("#txtemail").val();
var f_name = $("#f_name").val();
var l_name = $("#l_name").val();
var project_id_val = $("#project_id_val").val();
var info = "project_id_val=" + project_id_val + "&txtemail=" + txtemail + "&f_name=" + f_name + "&l_name" + l_name;
$.ajax({
type: "POST",
url: "<?= $vpath ?>addtoinvite.php",
data: info,
beforeSend: function() {
$('#addinvite').html('<img src="<?= $vpath ?>images/login_loader2.GIF" height=22 width=22 />');
},
success: function(dd) {
$("#addinvite").html(dd);
}
});
}
function postprojectinvite() {
var txtemail = $("#txtemail").val();
var info = "txtemail=" + txtemail + "&inviteuser=inviteuser";
$.ajax({
type: "POST",
url: "<?= $vpath ?>addtoinvite_post.php",
data: info,
beforeSend: function() {
$('#addinvite_post').html('<img src="<?= $vpath ?>images/login_loader2.GIF" height=22 width=22 />');
},
success: function(dd) {
$("#addinvite_post").html(dd);
}
});
}
function centerModal() {
$(this).css('display', 'block');
var $dialog = $(this).find(".modal-dialog");
var offset = ($(window).height() - $dialog.height()) / 2;
// Center modal vertically in window
$dialog.css("margin-top", offset);
}
$('.modal').on('show.bs.modal', centerModal);
$(window).on("resize", function () {
$('.modal:visible').each(centerModal);
});
function addwistlist(id) {
var info = "uid=" + id;
$.ajax({
type: "POST",
url: "<?= $vpath ?>addtowishlist.php",
data: info,
beforeSend: function() {
$('#addlist').html('<img src="<?= $vpath ?>images/login_loader2.GIF" height=22 width=22 />');
},
success: function(dd) {
$("#addlist").html(dd);
}
});
}
</script>
<?php include 'includes/footer.php'; ?>
| gpl-2.0 |
lvee/lvee-engine | config/initializers/secret_token.rb | 658 | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
Lvee::Application.config.secret_key_base = 'b42cc7d0a62b9abb410090b48c3a79e69e823994b66eea3445f26b939a641f9a4c9804b7d65c222f7d8a773c779a81fa291df144d46f280af8489bbf7ba3f924'
| gpl-2.0 |
Benestar/WikibaseConstraints | tests/unit/Constraint/OneOfCheckerTest.php | 2139 | <?php
namespace Wikibase\Test;
use DataValues\NumberValue;
use DataValues\StringValue;
use InvalidArgumentException;
use Wikibase\Constraints\Constraint\OneOfChecker;
/**
* @covers Wikibase\Constraints\Constraint\OneOfChecker
*
* @license GNU GPL v2+
* @author Bene* < [email protected] >
*/
class OneOfCheckerTest extends \PHPUnit_Framework_TestCase {
/**
* @expectedException InvalidArgumentException
*/
public function testConstructionFails() {
new OneOfChecker( array( new StringValue( 'foo bar' ), null ) );
}
public function testSupportsDataValue() {
$oneOfChecker = new OneOfChecker( array() );
$this->assertTrue( $oneOfChecker->supportsDataValue( new StringValue( 'foo bar' ) ) );
$this->assertTrue( $oneOfChecker->supportsDataValue( new NumberValue( 42 ) ) );
}
public function testCheckDataValue_returnsTrue() {
$oneOfChecker = new OneOfChecker( array( new StringValue( 'foo' ), new StringValue( 'bar' ) ) );
$this->assertTrue( $oneOfChecker->checkDataValue( new StringValue( 'foo' ) ) );
$this->assertTrue( $oneOfChecker->checkDataValue( new StringValue( 'bar' ) ) );
}
public function testCheckDataValue_returnsFalse() {
$oneOfChecker = new OneOfChecker( array( new StringValue( 'foo' ), new StringValue( 'bar' ) ) );
$this->assertFalse( $oneOfChecker->checkDataValue( new StringValue( 'baz' ) ) );
}
public function testGetName() {
$oneOfChecker = new OneOfChecker( array() );
$this->assertEquals( 'oneof', $oneOfChecker->getName() );
}
public function testEquals() {
$oneOfChecker1 = new OneOfChecker( array( new StringValue( 'foo' ) ) );
$oneOfChecker2 = new OneOfChecker( array( new StringValue( 'foo' ) ) );
$this->assertTrue( $oneOfChecker1->equals( $oneOfChecker2 ) );
$this->assertTrue( $oneOfChecker1->equals( $oneOfChecker1 ) );
}
public function testNotEquals() {
$oneOfChecker1 = new OneOfChecker( array( new StringValue( 'foo' ) ) );
$oneOfChecker2 = new OneOfChecker( array( new StringValue( 'bar' ) ) );
$this->assertFalse( $oneOfChecker1->equals( $oneOfChecker2 ) );
$this->assertFalse( $oneOfChecker1->equals( null ) );
}
}
| gpl-2.0 |
pins-ocs/OCP-tests | test-Rayleight/data/Rayleight_Data.lua | 4126 | --[[
/*-----------------------------------------------------------------------*\
| file: Rayleight_Data.lua |
| |
| version: 1.0 date 28/3/2020 |
| |
| Copyright (C) 2020 |
| |
| Enrico Bertolazzi, Francesco Biral and Paolo Bosetti |
| Dipartimento di Ingegneria Industriale |
| Universita` degli Studi di Trento |
| Via Sommarive 9, I-38123, Trento, Italy |
| email: [email protected] |
| [email protected] |
| [email protected] |
\*-----------------------------------------------------------------------*/
--]]
-- Auxiliary values
content = {
-- Level of message
InfoLevel = 4,
-- maximum number of threads used for linear algebra and various solvers
N_threads = 4,
U_threaded = true,
F_threaded = true,
JF_threaded = true,
LU_threaded = true,
-- Enable doctor
Doctor = false,
-- Enable check jacobian
JacobianCheck = false,
JacobianCheckFull = false,
JacobianCheck_epsilon = 1e-4,
FiniteDifferenceJacobian = false,
-- Redirect output to GenericContainer["stream_output"]
RedirectStreamToString = false,
-- Dump Function and Jacobian if uncommented
-- DumpFile = "Rayleight_dump",
-- spline output (all values as function of "s")
-- OutputSplines = [0],
-- Redirect output to GenericContainer["stream_output"]
RedirectStreamToString = false,
ControlSolver = {
-- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY", "MINIMIZATION"
factorization = "LU",
MaxIter = 50,
Tolerance = 1e-9,
Iterative = false,
InfoLevel = -1 -- suppress all messages
},
-- setup solver
Solver = {
-- Linear algebra factorization selection:
-- "LU", "QR", "QRP", "SUPERLU"
factorization = "LU",
-- Last Block selection:
-- "LU", "LUPQ", "QR", "QRP", "SVD", "LSS", "LSY"
last_factorization = "LU",
-- choose solves: Hyness, NewtonDumped
solver = "Hyness",
-- solver parameters
max_iter = 300,
max_step_iter = 40,
max_accumulated_iter = 800,
tolerance = 9.999999999999999e-10,
-- continuation parameters
ns_continuation_begin = 0,
ns_continuation_end = 0,
continuation = {
initial_step = 0.2, -- initial step for continuation
min_step = 0.001, -- minimum accepted step for continuation
reduce_factor = 0.5, -- if continuation step fails, reduce step by this factor
augment_factor = 1.5, -- if step successful in less than few_iteration augment step by this factor
few_iterations = 8
}
},
-- Boundary Conditions (SET/FREE)
BoundaryConditions = {
initial_x1 = SET,
initial_x2 = SET,
},
-- Guess
Guess = {
-- possible value: zero, default, none, warm
initialize = "zero",
-- possible value: default, none, warm, spline, table
guess_type = "default"
},
Parameters = {
-- Model Parameters
-- Guess Parameters
-- Boundary Conditions
-- Post Processing Parameters
-- User Function Parameters
-- Continuation Parameters
-- Constraints Parameters
},
-- functions mapped objects
MappedObjects = {
},
-- Controls: No penalties or barriers constraint defined
Constraints = {
-- Constraint1D: none defined
-- Constraint2D: none defined
},
-- User defined classes initialization
-- User defined classes: M E S H
Mesh =
{
s0 = 0,
segments = {
{
length = 2.5,
n = 1000,
},
},
},
}
-- EOF
| gpl-2.0 |
Inquisitor/mangos-old | src/game/Vehicle.cpp | 11965 | /*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "Log.h"
#include "ObjectMgr.h"
#include "Vehicle.h"
#include "Unit.h"
#include "Util.h"
#include "WorldPacket.h"
#include "CreatureAI.h"
VehicleKit::VehicleKit(Unit* base, VehicleEntry const* vehicleInfo) : m_vehicleInfo(vehicleInfo), m_pBase(base), m_uiNumFreeSeats(0)
{
for (uint32 i = 0; i < MAX_VEHICLE_SEAT; ++i)
{
uint32 seatId = m_vehicleInfo->m_seatID[i];
if (!seatId)
continue;
if(base)
{
if(m_vehicleInfo->m_flags & VEHICLE_FLAG_NO_STRAFE)
base->m_movementInfo.AddMovementFlag2(MOVEFLAG2_NO_STRAFE);
if(m_vehicleInfo->m_flags & VEHICLE_FLAG_NO_JUMPING)
base->m_movementInfo.AddMovementFlag2(MOVEFLAG2_NO_JUMPING);
}
if (VehicleSeatEntry const *seatInfo = sVehicleSeatStore.LookupEntry(seatId))
{
m_Seats.insert(std::make_pair(i, VehicleSeat(seatInfo)));
if (seatInfo->IsUsable())
++m_uiNumFreeSeats;
}
}
}
VehicleKit::~VehicleKit()
{
}
void VehicleKit::RemoveAllPassengers()
{
for (SeatMap::iterator itr = m_Seats.begin(); itr != m_Seats.end(); ++itr)
{
if (Unit *passenger = itr->second.passenger)
{
passenger->ExitVehicle();
// remove creatures of player mounts
if (passenger->GetTypeId() == TYPEID_UNIT)
passenger->AddObjectToRemoveList();
}
}
}
bool VehicleKit::HasEmptySeat(int8 seatId) const
{
SeatMap::const_iterator seat = m_Seats.find(seatId);
if (seat == m_Seats.end())
return false;
return !seat->second.passenger;
}
Unit *VehicleKit::GetPassenger(int8 seatId) const
{
SeatMap::const_iterator seat = m_Seats.find(seatId);
if (seat == m_Seats.end())
return NULL;
return seat->second.passenger;
}
int8 VehicleKit::GetNextEmptySeat(int8 seatId, bool next) const
{
SeatMap::const_iterator seat = m_Seats.find(seatId);
if (seat == m_Seats.end())
return -1;
while (seat->second.passenger || !seat->second.seatInfo->IsUsable())
{
if (next)
{
++seat;
if (seat == m_Seats.end())
seat = m_Seats.begin();
}
else
{
if (seat == m_Seats.begin())
seat = m_Seats.end();
--seat;
}
if (seat->first == seatId)
return -1; // no available seat
}
return seat->first;
}
bool VehicleKit::AddPassenger(Unit *passenger, int8 seatId)
{
SeatMap::iterator seat;
if (seatId < 0) // no specific seat requirement
{
for (seat = m_Seats.begin(); seat != m_Seats.end(); ++seat)
if (!seat->second.passenger && (seat->second.seatInfo->IsUsable() || (seat->second.seatInfo->m_flags & SEAT_FLAG_UNCONTROLLED)))
break;
if (seat == m_Seats.end()) // no available seat
return false;
}
else
{
seat = m_Seats.find(seatId);
if (seat == m_Seats.end())
return false;
if (seat->second.passenger)
return false;
}
seat->second.passenger = passenger;
passenger->addUnitState(UNIT_STAT_ON_VEHICLE);
VehicleSeatEntry const *seatInfo = seat->second.seatInfo;
passenger->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT);
passenger->m_movementInfo.SetTransportData(m_pBase->GetGUID(),
seatInfo->m_attachmentOffsetX, seatInfo->m_attachmentOffsetY, seatInfo->m_attachmentOffsetZ,
seatInfo->m_passengerYaw, WorldTimer::getMSTime(), seat->first, seatInfo);
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
((Player*)passenger)->UnsummonPetTemporaryIfAny();
((Player*)passenger)->GetCamera().SetView(m_pBase);
WorldPacket data(SMSG_FORCE_MOVE_ROOT, 8+4);
data << passenger->GetPackGUID();
data << uint32((passenger->m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0);
passenger->SendMessageToSet(&data, true);
}
if (seatInfo->m_flags & SEAT_FLAG_UNATTACKABLE)
{
passenger->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
}
if (seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL)
{
m_pBase->StopMoving();
m_pBase->GetMotionMaster()->Clear();
m_pBase->CombatStop(true);
m_pBase->DeleteThreatList();
m_pBase->getHostileRefManager().deleteReferences();
m_pBase->SetCharmerGuid(passenger->GetObjectGuid());
m_pBase->addUnitState(UNIT_STAT_CONTROLLED);
passenger->SetCharm(m_pBase);
if(m_pBase->HasAuraType(SPELL_AURA_FLY) || m_pBase->HasAuraType(SPELL_AURA_MOD_FLIGHT_SPEED) || ((Creature*)m_pBase)->CanFly())
{
WorldPacket data;
data.Initialize(SMSG_MOVE_SET_CAN_FLY, 12);
data << m_pBase->GetPackGUID();
data << (uint32)(0);
m_pBase->SendMessageToSet(&data,false);
}
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
m_pBase->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
if(m_pBase->GetMap() && !m_pBase->GetMap()->IsBattleGround())
m_pBase->setFaction(passenger->getFaction());
if (CharmInfo* charmInfo = m_pBase->InitCharmInfo(m_pBase))
{
charmInfo->InitVehicleCreateSpells();
charmInfo->SetReactState(REACT_PASSIVE);
}
Player* player = (Player*)passenger;
player->SetMover(m_pBase);
player->SetClientControl(m_pBase, 1);
player->VehicleSpellInitialize();
}
((Creature*)m_pBase)->AIM_Initialize();
if(m_pBase->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
{
WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 8+4);
data2 << m_pBase->GetPackGUID();
data2 << (uint32)(2);
m_pBase->SendMessageToSet(&data2,false);
}
}
passenger->SendMonsterMoveTransport(m_pBase, SPLINETYPE_FACINGANGLE, SPLINEFLAG_UNKNOWN5, 0, 0.0f);
RelocatePassengers(m_pBase->GetPositionX(), m_pBase->GetPositionY(), m_pBase->GetPositionZ()+0.5f, m_pBase->GetOrientation());
UpdateFreeSeatCount();
if (m_pBase->GetTypeId() == TYPEID_UNIT)
{
if (((Creature*)m_pBase)->AI())
((Creature*)m_pBase)->AI()->PassengerBoarded(passenger, seat->first, true);
}
return true;
}
void VehicleKit::RemovePassenger(Unit *passenger)
{
SeatMap::iterator seat;
for (seat = m_Seats.begin(); seat != m_Seats.end(); ++seat)
if (seat->second.passenger == passenger)
break;
if (seat == m_Seats.end())
return;
seat->second.passenger = NULL;
passenger->clearUnitState(UNIT_STAT_ON_VEHICLE);
float px, py, pz, po;
m_pBase->GetClosePoint(px, py, pz, m_pBase->GetObjectBoundingRadius(), 2.0f, M_PI_F);
po = m_pBase->GetOrientation();
passenger->m_movementInfo.ClearTransportData();
passenger->m_movementInfo.RemoveMovementFlag(MOVEFLAG_ONTRANSPORT);
if (seat->second.seatInfo->m_flags & SEAT_FLAG_UNATTACKABLE)
{
passenger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
}
if (seat->second.seatInfo->m_flags & SEAT_FLAG_CAN_CONTROL)
{
passenger->SetCharm(NULL);
passenger->RemoveSpellsCausingAura(SPELL_AURA_CONTROL_VEHICLE);
m_pBase->SetCharmerGuid(ObjectGuid());
m_pBase->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
m_pBase->clearUnitState(UNIT_STAT_CONTROLLED);
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
Player* player = (Player*)passenger;
player->SetMover(NULL);
player->SetClientControl(m_pBase, 0);
player->RemovePetActionBar();
}
((Creature*)m_pBase)->AIM_Initialize();
}
if (passenger->GetTypeId() == TYPEID_PLAYER)
{
((Player*)passenger)->GetCamera().ResetView();
WorldPacket data(SMSG_FORCE_MOVE_UNROOT, 8+4);
data << passenger->GetPackGUID();
data << uint32(2);
passenger->SendMessageToSet(&data, true);
((Player*)passenger)->ResummonPetTemporaryUnSummonedIfAny();
}
passenger->UpdateAllowedPositionZ(px, py, pz);
passenger->SetPosition(px, py, pz + 0.5f, po);
UpdateFreeSeatCount();
if (m_pBase->GetTypeId() == TYPEID_UNIT)
if (((Creature*)m_pBase)->AI())
((Creature*)m_pBase)->AI()->PassengerBoarded(passenger, seat->first, false);
}
void VehicleKit::Reset()
{
InstallAllAccessories(m_pBase->GetEntry());
UpdateFreeSeatCount();
}
void VehicleKit::InstallAllAccessories(uint32 entry)
{
VehicleAccessoryList const* mVehicleList = sObjectMgr.GetVehicleAccessoryList(entry);
if (!mVehicleList)
return;
for (VehicleAccessoryList::const_iterator itr = mVehicleList->begin(); itr != mVehicleList->end(); ++itr)
InstallAccessory(itr->uiAccessory, itr->uiSeat, itr->bMinion);
}
void VehicleKit::InstallAccessory( uint32 entry, int8 seatId, bool minion)
{
if (Unit *passenger = GetPassenger(seatId))
{
// already installed
if (passenger->GetEntry() == entry)
return;
passenger->ExitVehicle();
}
if (Creature *accessory = m_pBase->SummonCreature(entry, m_pBase->GetPositionX(), m_pBase->GetPositionY(), m_pBase->GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 30000))
{
accessory->SetCreatorGuid(ObjectGuid());
accessory->EnterVehicle(this, seatId);
accessory->SendHeartBeat(false);
}
}
void VehicleKit::UpdateFreeSeatCount()
{
m_uiNumFreeSeats = 0;
for (SeatMap::const_iterator itr = m_Seats.begin(); itr != m_Seats.end(); ++itr)
{
if (!itr->second.passenger && itr->second.seatInfo->IsUsable())
++m_uiNumFreeSeats;
}
uint32 flag = m_pBase->GetTypeId() == TYPEID_PLAYER ? UNIT_NPC_FLAG_PLAYER_VEHICLE : UNIT_NPC_FLAG_SPELLCLICK;
if (m_uiNumFreeSeats)
m_pBase->SetFlag(UNIT_NPC_FLAGS, flag);
else
m_pBase->RemoveFlag(UNIT_NPC_FLAGS, flag);
}
void VehicleKit::RelocatePassengers(float x, float y, float z, float ang)
{
for (SeatMap::const_iterator itr = m_Seats.begin(); itr != m_Seats.end(); ++itr)
{
if (Unit *passenger = itr->second.passenger)
{
float px = x + passenger->m_movementInfo.GetTransportPos()->x;
float py = y + passenger->m_movementInfo.GetTransportPos()->y;
float pz = z + passenger->m_movementInfo.GetTransportPos()->z;
float po = ang + passenger->m_movementInfo.GetTransportPos()->o;
passenger->UpdateAllowedPositionZ(px, py, pz);
passenger->SetPosition(px, py, pz, po);
}
}
}
VehicleSeatEntry const* VehicleKit::GetSeatInfo(Unit* passenger)
{
for (SeatMap::iterator itr = m_Seats.begin(); itr != m_Seats.end(); ++itr)
{
if (Unit *_passenger = itr->second.passenger)
if (_passenger = passenger)
return itr->second.seatInfo;
}
return NULL;
}
| gpl-2.0 |
XoopsModules25x/xoopstube | ratevideo.php | 5932 | <?php
/**
* Module: XoopsTube
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
*
* PHP version 5
*
* @category Module
* @package Xoopstube
* @author XOOPS Development Team
* @copyright 2001-2016 XOOPS Project (https://xoops.org)
* @license GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
* @link https://xoops.org/
* @since 1.0.6
*/
use Xmf\Request;
use XoopsModules\Xoopstube\{Utility
};
$GLOBALS['xoopsOption']['template_main'] = 'xoopstube_ratevideo.tpl';
require_once __DIR__ . '/header.php';
global $myts, $xoTheme;
// Check if videoload POSTER is voting (UNLESS Anonymous users allowed to post)
$lid = Request::getInt('lid', Request::getInt('lid', '', 'POST'), 'GET');
$ip = getenv('REMOTE_ADDR');
$ratinguser = (!is_object($GLOBALS['xoopsUser'])) ? 0 : $GLOBALS['xoopsUser']->getVar('uid');
if (0 == $GLOBALS['xoopsModuleConfig']['showrating'] || '' == $lid) {
$ratemessage = _MD_XOOPSTUBE_CANTVOTEOWN;
redirect_header('index.php', 4, $ratemessage);
}
if (0 !== $ratinguser) {
$sql = 'SELECT cid, submitter FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' WHERE lid=' . $lid;
$result = $GLOBALS['xoopsDB']->query($sql);
while (list($cid, $ratinguserDB) = $GLOBALS['xoopsDB']->fetchRow($result)) {
if ($ratinguserDB === $ratinguser) {
$ratemessage = _MD_XOOPSTUBE_CANTVOTEOWN;
redirect_header('singlevideo.php?cid=' . (int)$cid . '&lid=' . $lid, 4, $ratemessage);
}
}
// Check if REG user is trying to vote twice.
$sql = 'SELECT cid, ratinguser FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . ' WHERE lid=' . $lid;
$result = $GLOBALS['xoopsDB']->query($sql);
if ($result) {
while (list($cid, $ratinguserDB) = $GLOBALS['xoopsDB']->fetchRow($result)) {
if ($ratinguserDB === $ratinguser) {
$ratemessage = _MD_XOOPSTUBE_VOTEONCE;
redirect_header('singlevideo.php?cid=' . (int)$cid . '&lid=' . $lid, 4, $ratemessage);
}
}
}
} else {
// Check if ANONYMOUS user is trying to vote more than once per day.
$yesterday = (time() - (86400 * $anonwaitdays));
$sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . ' WHERE lid=' . $lid . ' AND ratinguser=0 AND ratinghostname=' . $ip . ' AND ratingtimestamp > ' . $yesterday;
$result = $GLOBALS['xoopsDB']->query($sql);
[$anonvotecount] = $GLOBALS['xoopsDB']->fetchRow($result);
if ($anonvotecount >= 1) {
$ratemessage = _MD_XOOPSTUBE_VOTEONCE;
redirect_header('singlevideo.php?cid=' . (int)$cid . '&lid=' . $lid, 4, $ratemessage);
}
}
if (!empty(Request::getString('submit', ''))) {
$ratinguser = (!is_object($GLOBALS['xoopsUser'])) ? 0 : $GLOBALS['xoopsUser']->getVar('uid');
// Make sure only 1 anonymous from an IP in a single day.
$anonwaitdays = 1;
$ip = getenv('REMOTE_ADDR');
$lid = Request::getInt('lid', 0, 'POST');
$cid = Request::getInt('cid', 0, 'POST');
$rating = Request::getInt('rating', 0, 'POST');
// $title = $myts->addslashes(trim(Request::getString('title', '', 'POST')));
$title = Request::getString('title', '', 'POST');
// Check if Rating is Null
if (0 == $rating) {
$ratemessage = _MD_XOOPSTUBE_NORATING;
redirect_header('ratevideo.php?cid=' . $cid . '&lid=' . $lid, 4, $ratemessage);
}
// All is well. Add to Line Item Rate to DB.
$newid = $GLOBALS['xoopsDB']->genId($GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . '_ratingid_seq');
$datetime = time();
$sql = sprintf(
'INSERT INTO `%s` (ratingid, lid, ratinguser, rating, ratinghostname, ratingtimestamp, title) VALUES (%u, %u, %u, %u, %s, %u, %s)',
$GLOBALS['xoopsDB']->prefix('xoopstube_votedata'),
$newid,
$lid,
$ratinguser,
$rating,
$GLOBALS['xoopsDB']->quoteString($ip),
$datetime,
$GLOBALS['xoopsDB']->quoteString($title)
);
if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
$ratemessage = _MD_XOOPSTUBE_ERROR;
} else {
// All is well. Calculate Score & Add to Summary (for quick retrieval & sorting) to DB.
Utility::updateRating($lid);
$ratemessage = _MD_XOOPSTUBE_VOTEAPPRE . '<br>' . sprintf(_MD_XOOPSTUBE_THANKYOU, $GLOBALS['xoopsConfig']['sitename']);
}
redirect_header('singlevideo.php?cid=' . $cid . '&lid=' . $lid, 4, $ratemessage);
} else {
//TODO add
require_once XOOPS_ROOT_PATH . '/header.php';
$catarray['imageheader'] = Utility::renderImageHeader();
$cid = Request::getInt('cid', Request::getInt('cid', '', 'POST'), 'GET');
$catarray['imageheader'] = Utility::renderImageHeader();
$xoopsTpl->assign('catarray', $catarray);
$xoopsTpl->assign('mod_url', XOOPS_URL . '/modules/' . $moduleDirName);
$result = $GLOBALS['xoopsDB']->query('SELECT title FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' WHERE lid=' . $lid);
[$title] = $GLOBALS['xoopsDB']->fetchRow($result);
$xoopsTpl->assign(
'video',
[
'id' => $lid,
'cid' => $cid,
'title' => htmlspecialchars($title, ENT_QUOTES | ENT_HTML5),
]
);
Utility::setNoIndexNoFollow();
$xoopsTpl->assign('module_dir', $xoopsModule->getVar('dirname'));
require_once XOOPS_ROOT_PATH . '/footer.php';
}
Utility::setNoIndexNoFollow();
$xoopsTpl->assign('module_dir', $xoopsModule->getVar('dirname'));
require_once XOOPS_ROOT_PATH . '/footer.php';
| gpl-2.0 |
bast1aan/commenter | src/bast1aan/commenter/action/BaseAction.java | 2059 | /*
* Commenter
* Copyright (C) 2017 Bastiaan Welmers, [email protected]
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package bast1aan.commenter.action;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
abstract public class BaseAction implements ServletRequestAware {
protected static final String COOKIE_NAME = "indent";
protected HttpServletRequest request;
protected String indent;
protected String readIndent() {
String indent = null;
// first try the GET parameter
indent = request.getParameter(COOKIE_NAME);
if (validateIndent(indent))
return indent;
// try the json parameter in case of POST/PUT
indent = this.indent;
if (validateIndent(indent))
return indent;
// try the cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (COOKIE_NAME.equals(cookie.getName())) {
indent = cookie.getValue();
}
}
}
if (validateIndent(indent))
return indent;
// in all other cases; not found
return null;
}
private boolean validateIndent(String indent) {
return indent != null && indent.length() > 10 && indent.length() <= 32;
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public void setIndent(String indent) {
this.indent = indent;
}
}
| gpl-2.0 |
CSIS-iLab/cpower-viz | _templates/hc-scatter-multiple/js/scatter.js | 3345 | $(function() {
var data = {}
var datasets
var seriesData = []
Highcharts.data({
googleSpreadsheetKey: '1xz7MTZmQeGeSueJv8wiUZp3HqiWdD92LyPJhuaBIhzE',
googleSpreadsheetWorksheet: 1,
switchRowsAndColumns: true,
parsed: function(columns) {
$.each(columns, function (i, code) {
if ( i == 0 ) {
return
}
data[code[0]] = data[code[0]] || {}
data[code[0]][code[1]] = data[code[0]][code[1]] || {
name: code[1],
data: []
}
data[code[0]][code[1]].data.push({
name: code[1],
x: code[3],
y: code[4],
label: code[2]
})
})
datasets = Object.keys(data)
// Convert object to array - we no longer need the keys
var dataArray = $.map(data, function(value, index) {
return [value];
});
// Convert each series into an array
dataArray.forEach(function(value) {
var series = $.map(value, function(value2, index2) {
return [value2];
});
seriesData.push(series)
})
populateSelect()
renderChart(seriesData[0], datasets[0])
}
})
function populateSelect() {
var options = '';
$.each(datasets, function(i, dataset) {
options += '<option value="'+ i + '">' + dataset + '</option>';
})
$('.datasets').append(options);
// Destroy & redraw chart so we get smooth animation when switching datasets.
$('.datasets').on('change', function() {
var chart = $('#hcContainer').highcharts()
chart.destroy()
renderChart(seriesData[this.value], datasets[this.value])
})
}
function renderChart(data, yAxisLabel) {
$('#hcContainer').highcharts({
// General Chart Options
chart: {
zoomType: 'x',
type: 'scatter'
},
// Chart Title and Subtitle
title: {
text: "Interactive Title"
},
subtitle: {
text: "Click and drag to zoom in"
},
// Credits
credits: {
enabled: true,
href: false,
text: "CSIS China Power Project | Source: NAME"
},
// Chart Legend
legend: {
title: {
text: 'Legend Title<br/><span style="font-size: 12px; color: #808080; font-weight: normal">(Click to hide)</span>'
},
align: 'center',
verticalAlign: 'bottom',
layout: 'horizontal'
},
// Y Axis
yAxis: {
title: {
text: yAxisLabel
},
},
series: data,
// Tooltip
/*
tooltip: {
formatter: function () {
return '<span style="color:' + this.series.color + '">● </span><b>' + this.point.series.name + '</b><br> x: ' + this.x + ' y: ' + this.y + '<br><i>x: ' + this.x + ' y: ' + this.y + '</i><br><b>x: ' + this.x + ' y: ' + this.y + '</b>';
}
}, */
// Additional Plot Options
plotOptions:
{
scatter: {
marker: {
enabled: true,
symbol: "circle",
},
stacking: null, // Normal bar graph
// stacking: "normal", // Stacked bar graph
dataLabels: {
enabled: false,
}
}
}
});
}
});
| gpl-2.0 |
avlhitech256/TimeTable | DataService/Entity/Specialty/ISpecialtyEntity.cs | 130 | namespace DataService.Entity.Specialty
{
public interface ISpecialtyEntity : IDomainEntity<Model.Specialty>
{
}
}
| gpl-2.0 |
o-schneider/firedav | www/css/gaia/shared/elements/gaia_grid/js/items/placeholder.js | 1594 | 'use strict';
/* global GaiaGrid */
(function(exports) {
/**
* The placeholder represents an empty place on the grid.
* This is generally used to detect distance from an empty spot on the grid.
*/
function Placeholder() {
this.detail = {
type: 'placeholder',
index: 0
};
}
Placeholder.prototype = {
__proto__: GaiaGrid.GridItem.prototype,
/**
* Returns the height in pixels of each icon.
*/
get pixelHeight() {
return this.grid.layout.gridItemHeight;
},
/**
* When the placeholder is rendered in the last row, for group creation
* purposes, there is special handling required for height.
*/
createsGroupOnDrop: false,
/**
* Width in grid units for each icon.
*/
gridWidth: 1,
/**
* Placeholders do not save. They are re-generated on render calls.
*/
persistToDB: false,
get name() {
return '';
},
/**
* Renders a transparent placeholder.
*/
render: function() {
// Generate an element if we need to
if (!this.element) {
var tile = document.createElement('div');
tile.className = 'icon placeholder';
tile.style.height = this.pixelHeight + 'px';
this.element = tile;
this.grid.element.appendChild(tile);
}
this.transform(this.x, this.y, this.grid.layout.percent);
},
remove: function() {
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
}
};
exports.GaiaGrid.Placeholder = Placeholder;
}(window));
| gpl-2.0 |
tonglin/pdPm | public_html/typo3_src-6.1.7/typo3/sysext/rtehtmlarea/extensions/EditElement/class.tx_rtehtmlarea_editelement.php | 375 | <?php
/*
* @deprecated since 6.0, the classname tx_rtehtmlarea_editelement and this file is obsolete
* and will be removed with 6.2. The class was renamed and is now located at:
* typo3/sysext/rtehtmlarea/Classes/Extension/EditElement.php
*/
require_once \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('rtehtmlarea') . 'Classes/Extension/EditElement.php';
?> | gpl-2.0 |
yogendra9891/legalconfirm | administrator/components/com_legalconfirm/controllers/lawfirm.php | 590 | <?php
/**
* @version 1.0.0
* @package com_legalconfirm
* @copyright Copyright (C) 2013. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Abhishek Gupta <[email protected]> - http://
*/
// No direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
/**
* Lawfirm controller class.
*/
class LegalconfirmControllerLawfirm extends JControllerForm
{
function __construct() {
$this->view_list = 'lawfirms';
parent::__construct();
}
} | gpl-2.0 |
mesocentrefc/Janua-SMS | janua-web/app/view/message/MessageStatsGraph.js | 1925 | /**
* Copyright (c) 2016 Cédric Clerget - HPC Center of Franche-Comté University
*
* This file is part of Janua-SMS
*
* http://github.com/mesocentrefc/Janua-SMS
*
* 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 v2.
*
* 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/>.
*/
Ext.define('JanuaWeb.view.message.MessageStatsGraph', {
extend: 'Ext.panel.Panel',
alias: 'widget.MessageStatsGraph',
layout: 'fit',
bodyPadding: 5,
items: [{
xtype: 'chart',
margin: '5 0 0 0',
animate: true,
shadow: false,
store: 'SmsStats',
axes: [{
type: 'numeric',
position: 'left',
grid: true,
fields: 'value',
minimum: 0
}, {
type: 'category',
position: 'bottom',
fields: 'month'
}],
series: [{
type: 'bar',
axis: 'left',
xField: 'month',
yField: 'value',
style: {
opacity: 0.70
},
highlight: {
fillStyle: 'yellow',
radius: 5,
linewidth: 1
},
tips: {
trackMouse: true,
renderer: function(tooltip, storeItem, item) {
tooltip.setHtml(storeItem.get('month') + ': ' + storeItem.get('value') + ' SMS sent');
}
}
}]
}]
});
| gpl-2.0 |
Iolaum/MrSmith | AdX/src/main/java/tau/tac/adx/users/DefaultAdxUserManagerBuilder.java | 3144 | /*
* DefaultUserManagerBuilder.java
*
* COPYRIGHT 2008
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* PERMISSION IS GRANTED TO USE, COPY, CREATE DERIVATIVE WORKS AND REDISTRIBUTE THIS
* SOFTWARE AND SUCH DERIVATIVE WORKS FOR NONCOMMERCIAL EDUCATION AND RESEARCH
* PURPOSES, SO LONG AS NO FEE IS CHARGED, AND SO LONG AS THE COPYRIGHT NOTICE
* ABOVE, THIS GRANT OF PERMISSION, AND THE DISCLAIMER BELOW APPEAR IN ALL COPIES
* MADE; AND SO LONG AS THE NAME OF THE UNIVERSITY OF MICHIGAN IS NOT USED IN ANY
* ADVERTISING OR PUBLICITY PERTAINING TO THE USE OR DISTRIBUTION OF THIS SOFTWARE
* WITHOUT SPECIFIC, WRITTEN PRIOR AUTHORIZATION.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION FROM THE UNIVERSITY OF
* MICHIGAN AS TO ITS FITNESS FOR ANY PURPOSE, AND WITHOUT WARRANTY BY THE
* UNIVERSITY OF MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE. THE REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE FOR ANY
* DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WITH
* RESPECT TO ANY CLAIM ARISING OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE,
* EVEN IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
package tau.tac.adx.users;
import java.util.Random;
import tau.tac.adx.agents.DefaultAdxUserManager;
import tau.tac.adx.sim.AdxAgentRepository;
import edu.umich.eecs.tac.util.config.ConfigProxy;
import edu.umich.eecs.tac.util.config.ConfigProxyUtils;
/**
* @author Patrick Jordan
* @author greenwald
*/
public class DefaultAdxUserManagerBuilder implements
AdxUserBehaviorBuilder<DefaultAdxUserManager> {
private static final String ADX_BASE = "adx_usermanager";
private static final String POPULATION_SIZE_KEY = "populationsize";
private static final int POPULATION_SIZE_DEFAULT = 10000;
private static final String VIEW_MANAGER_KEY = "viewmanager";
private static final String QUERY_MANAGER_KEY = "querymanager";
private static final String ADX_QUERY_MANAGER_DEFAULT = AdxUserQueryManagerBuilder.class
.getName();
@Override
public DefaultAdxUserManager build(ConfigProxy userConfigProxy,
AdxAgentRepository repository, Random random) {
try {
AdxUserBehaviorBuilder<DefaultAdxUserQueryManager> queryBuilder = ConfigProxyUtils
.createObjectFromProperty(userConfigProxy, ADX_BASE + '.'
+ QUERY_MANAGER_KEY, ADX_QUERY_MANAGER_DEFAULT);
DefaultAdxUserQueryManager queryManager = queryBuilder.build(
userConfigProxy, repository, random);
int populationSize = userConfigProxy.getPropertyAsInt(ADX_BASE
+ '.' + POPULATION_SIZE_KEY, POPULATION_SIZE_DEFAULT);
return new DefaultAdxUserManager(repository.getPublisherCatalog(),
repository.getUserPopulation(), queryManager,
populationSize, repository.getEventBus());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| gpl-2.0 |
benshez/DreamWeddingCeremomies | JsonApiApplication/client/app/interfaces/IPageContent/interface.js | 524 | define(["require", "exports", "../module"], function (require, exports) {
var app;
(function (app) {
var interfaces;
(function (interfaces) {
"use strict";
var IPageContent = (function () {
function IPageContent() {
}
return IPageContent;
})();
interfaces.IPageContent = IPageContent;
})(interfaces = app.interfaces || (app.interfaces = {}));
})(app = exports.app || (exports.app = {}));
});
| gpl-2.0 |
luniki/CliqrPlugin | migrations/02_migrate_from_studip_v34.php | 448 | <?php
class MigrateFromStudipV34 extends Migration
{
public function description()
{
return "create a configuration entry for the URL shortener service API key";
}
public function up()
{
// require composer autoloader
require_once __DIR__.'/../vendor/autoload.php';
$mig = new \Cliqr\StudIPv34Migrator();
$mig->migrate();
}
public function down()
{
# dummy
}
}
| gpl-2.0 |
dougwm/psi-probe | core/src/test/java/psiprobe/model/ApplicationResourceTest.java | 748 | /**
* Licensed under the GPL License. You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE.
*/
package psiprobe.model;
import com.codebox.bean.JavaBeanTester;
import org.junit.Test;
/**
* The Class ApplicationResourceTest.
*/
public class ApplicationResourceTest {
/**
* Javabean tester.
*/
@Test
public void javabeanTester() {
JavaBeanTester.builder(ApplicationResource.class).loadData().test();
}
}
| gpl-2.0 |
KDE/kimono | kde/KAssistantDialog.cs | 9226 | //Auto-generated by kalyptus. DO NOT EDIT.
namespace Kimono {
using System;
using Qyoto;
/// <remarks>
/// This class provides a framework for assistant dialogs.
/// The use of this class is the same as KWizard in KDE3.
/// You should use the word "assistant" instead of "wizard" both in the source
/// and translatable strings.
/// An assistant dialog consists of a sequence of pages.
/// Its purpose is to walk the user (assist) through a process step by step.
/// Assistant dialogs are useful for complex or infrequently occurring tasks
/// that people may find difficult to learn or do.
/// Sometimes a task requires too many input fields to fit them on a single dialog.
/// KAssistantDialog provides page titles and displays Next, Back, Finish, Cancel,
/// and Help push buttons, as appropriate to the current position in the page sequence.
/// The Finish Button has the code KDialog.User1, The Next button is KDialog.User2
/// and the Back button is KDialog.User3.
/// The help button may be hidden using showButton(KDialog.Help, false)
/// Create and populate dialog pages that inherit from QWidget and add them
/// to the assistant dialog using addPage().
/// The functions next() and back() are and may be reimplemented to
/// override the default actions of the next and back buttons.
/// </remarks> <author> Olivier Goffart <ogoffart at kde.org>
/// </author>
/// <short> This class provides a framework for assistant dialogs.</short>
[SmokeClass("KAssistantDialog")]
public class KAssistantDialog : KPageDialog, IDisposable {
protected KAssistantDialog(Type dummy) : base((Type) null) {}
protected new void CreateProxy() {
interceptor = new SmokeInvocation(typeof(KAssistantDialog), this);
}
/// <remarks>
/// Construct a new assistant dialog with <code>parent</code> as parent.
/// <param> name="parent" is the parent of the widget.
/// @flags the window flags to give to the assistant dialog. The
/// default of zero is usually what you want.
/// </param></remarks> <short> Construct a new assistant dialog with <code>parent</code> as parent.</short>
public KAssistantDialog(QWidget parent, uint flags) : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog#$", "KAssistantDialog(QWidget*, Qt::WindowFlags)", typeof(void), typeof(QWidget), parent, typeof(uint), flags);
}
public KAssistantDialog(QWidget parent) : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog#", "KAssistantDialog(QWidget*)", typeof(void), typeof(QWidget), parent);
}
public KAssistantDialog() : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog", "KAssistantDialog()", typeof(void));
}
/// <remarks>
/// Specify if the content of the page is valid, and if the next button may be enabled on this page.
/// By default all pages are valid.
/// This will disable or enable the next button on the specified page
/// <param> name="page" the page on which the next button will be enabled/disable
/// </param><param> name="enable" if true the next button will be enabled, if false it will be disabled
/// </param></remarks> <short> Specify if the content of the page is valid, and if the next button may be enabled on this page.</short>
public void SetValid(KPageWidgetItem page, bool enable) {
interceptor.Invoke("setValid#$", "setValid(KPageWidgetItem*, bool)", typeof(void), typeof(KPageWidgetItem), page, typeof(bool), enable);
}
/// <remarks>
/// return if a page is valid
/// <param> name="page" the page to check the validity of
/// </param></remarks> <short> return if a page is valid </short>
/// <see> setValid</see>
public bool IsValid(KPageWidgetItem page) {
return (bool) interceptor.Invoke("isValid#", "isValid(KPageWidgetItem*) const", typeof(bool), typeof(KPageWidgetItem), page);
}
/// <remarks>
/// Specify whether a page is appropriate.
/// A page is considered inappropriate if it should not be shown due to
/// the contents of other pages making it inappropriate.
/// A page which is inappropriate will not be shown.
/// The last page in an assistant dialog should always be appropriate
/// <param> name="page" the page to set as appropriate
/// </param><param> name="appropriate" flag indicating the appropriateness of the page.
/// If <code>appropriate</code> is true, then <code>page</code> is appropriate and will be
/// shown in the assistant dialog. If false, <code>page</code> will not be shown.
/// </param></remarks> <short> Specify whether a page is appropriate.</short>
public void SetAppropriate(KPageWidgetItem page, bool appropriate) {
interceptor.Invoke("setAppropriate#$", "setAppropriate(KPageWidgetItem*, bool)", typeof(void), typeof(KPageWidgetItem), page, typeof(bool), appropriate);
}
/// <remarks>
/// Check if a page is appropriate for use in the assistant dialog.
/// <param> name="page" is the page to check the appropriateness of.
/// </param></remarks> <return> true if <code>page</code> is appropriate, false if it is not
/// </return>
/// <short> Check if a page is appropriate for use in the assistant dialog.</short>
public bool IsAppropriate(KPageWidgetItem page) {
return (bool) interceptor.Invoke("isAppropriate#", "isAppropriate(KPageWidgetItem*) const", typeof(bool), typeof(KPageWidgetItem), page);
}
/// <remarks>
/// Called when the user clicks the Back button.
/// This function will show the preceding relevant page in the sequence.
/// Do nothing if the current page is the first page is the sequence.
/// </remarks> <short> Called when the user clicks the Back button.</short>
[Q_SLOT("void back()")]
[SmokeMethod("back()")]
public virtual void Back() {
interceptor.Invoke("back", "back()", typeof(void));
}
/// <remarks>
/// Called when the user clicks the Next/Finish button.
/// This function will show the next relevant page in the sequence.
/// If the current page is the last page, it will call accept()
/// </remarks> <short> Called when the user clicks the Next/Finish button.</short>
[Q_SLOT("void next()")]
[SmokeMethod("next()")]
public virtual void Next() {
interceptor.Invoke("next", "next()", typeof(void));
}
/// <remarks>
/// Construct an assistant dialog from a single widget.
/// <param> name="widget" the widget to construct the dialog with
/// </param><param> name="parent" the parent of the assistant dialog
/// @flags the window flags to use when creating the widget. The default
/// of zero is usually fine.
/// </param> Calls the KPageDialog(KPageWidget widget, QWidget parent, Qt.WFlags flags) constructor
/// </remarks> <short> Construct an assistant dialog from a single widget.</short>
public KAssistantDialog(KPageWidget widget, QWidget parent, uint flags) : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog##$", "KAssistantDialog(KPageWidget*, QWidget*, Qt::WindowFlags)", typeof(void), typeof(KPageWidget), widget, typeof(QWidget), parent, typeof(uint), flags);
}
public KAssistantDialog(KPageWidget widget, QWidget parent) : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog##", "KAssistantDialog(KPageWidget*, QWidget*)", typeof(void), typeof(KPageWidget), widget, typeof(QWidget), parent);
}
public KAssistantDialog(KPageWidget widget) : this((Type) null) {
CreateProxy();
interceptor.Invoke("KAssistantDialog#", "KAssistantDialog(KPageWidget*)", typeof(void), typeof(KPageWidget), widget);
}
[SmokeMethod("showEvent(QShowEvent*)")]
protected override void ShowEvent(QShowEvent arg1) {
interceptor.Invoke("showEvent#", "showEvent(QShowEvent*)", typeof(void), typeof(QShowEvent), arg1);
}
~KAssistantDialog() {
interceptor.Invoke("~KAssistantDialog", "~KAssistantDialog()", typeof(void));
}
public new void Dispose() {
interceptor.Invoke("~KAssistantDialog", "~KAssistantDialog()", typeof(void));
}
protected new IKAssistantDialogSignals Emit {
get { return (IKAssistantDialogSignals) Q_EMIT; }
}
}
public interface IKAssistantDialogSignals : IKPageDialogSignals {
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/demo/management/VerboseGC/PrintGCStat.java | 5791 | /*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
*/
import static java.lang.management.ManagementFactory.*;
import java.lang.management.*;
import javax.management.*;
import java.io.*;
import java.util.*;
/**
* Example of using the java.lang.management API to monitor
* the memory usage and garbage collection statistics.
*
* @author Mandy Chung
*/
public class PrintGCStat {
private RuntimeMXBean rmbean;
private MemoryMXBean mmbean;
private List<MemoryPoolMXBean> pools;
private List<GarbageCollectorMXBean> gcmbeans;
/**
* Constructs a PrintGCStat object to monitor a remote JVM.
*/
public PrintGCStat(MBeanServerConnection server) throws IOException {
// Create the platform mxbean proxies
this.rmbean = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME,
RuntimeMXBean.class);
this.mmbean = newPlatformMXBeanProxy(server,
MEMORY_MXBEAN_NAME,
MemoryMXBean.class);
ObjectName poolName = null;
ObjectName gcName = null;
try {
poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE+",*");
gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE+",*");
} catch (MalformedObjectNameException e) {
// should not reach here
assert(false);
}
Set mbeans = server.queryNames(poolName, null);
if (mbeans != null) {
pools = new ArrayList<MemoryPoolMXBean>();
Iterator iterator = mbeans.iterator();
while (iterator.hasNext()) {
ObjectName objName = (ObjectName) iterator.next();
MemoryPoolMXBean p =
newPlatformMXBeanProxy(server,
objName.getCanonicalName(),
MemoryPoolMXBean.class);
pools.add(p);
}
}
mbeans = server.queryNames(gcName, null);
if (mbeans != null) {
gcmbeans = new ArrayList<GarbageCollectorMXBean>();
Iterator iterator = mbeans.iterator();
while (iterator.hasNext()) {
ObjectName objName = (ObjectName) iterator.next();
GarbageCollectorMXBean gc =
newPlatformMXBeanProxy(server,
objName.getCanonicalName(),
GarbageCollectorMXBean.class);
gcmbeans.add(gc);
}
}
}
/**
* Constructs a PrintGCStat object to monitor the local JVM.
*/
public PrintGCStat() {
// Obtain the platform mxbean instances for the running JVM.
this.rmbean = getRuntimeMXBean();
this.mmbean = getMemoryMXBean();
this.pools = getMemoryPoolMXBeans();
this.gcmbeans = getGarbageCollectorMXBeans();
}
/**
* Prints the verbose GC log to System.out to list the memory usage
* of all memory pools as well as the GC statistics.
*/
public void printVerboseGc() {
System.out.print("Uptime: " + formatMillis(rmbean.getUptime()));
for (GarbageCollectorMXBean gc : gcmbeans) {
System.out.print(" [" + gc.getName() + ": ");
System.out.print("Count=" + gc.getCollectionCount());
System.out.print(" GCTime=" + formatMillis(gc.getCollectionTime()));
System.out.print("]");
}
System.out.println();
for (MemoryPoolMXBean p : pools) {
System.out.print(" [" + p.getName() + ":");
MemoryUsage u = p.getUsage();
System.out.print(" Used=" + formatBytes(u.getUsed()));
System.out.print(" Committed=" + formatBytes(u.getCommitted()));
System.out.println("]");
}
}
private String formatMillis(long ms) {
return String.format("%.4fsec", ms / (double) 1000);
}
private String formatBytes(long bytes) {
long kb = bytes;
if (bytes > 0) {
kb = bytes / 1024;
}
return kb + "K";
}
}
| gpl-2.0 |
elbruno/Blog | 20170711 UWP BLE Polar H7/Properties/AspMvcViewLocationFormatAttribute.cs | 393 | using System;
namespace ElBruno.PolarH7.Annotations
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute([NotNull] string format)
{
Format = format;
}
[NotNull] public string Format { get; private set; }
}
} | gpl-2.0 |
svn2github/autowikibrowser | tags/REL_5_3/UnitTests/RegexTests.cs | 110193 | using System.Text.RegularExpressions;
using WikiFunctions;
using NUnit.Framework;
namespace UnitTests
{
/// <summary>
/// This is the base class for every regex test. It contains helper functions that simplify checks.
/// </summary>
public class RegexTestsBase
{
/// <summary>
/// Checks if a regex matches a string
/// </summary>
/// <param name="r">Regex to test</param>
/// <param name="text">Text to match</param>
/// <param name="isMatch">If the regex should match the text</param>
protected static void TestMatch(Regex r, string text, bool isMatch)
{
Assert.AreEqual(isMatch, r.IsMatch(text));
}
/// <summary>
/// Checks if a regex matches a string
/// </summary>
/// <param name="r">Regex to test</param>
/// <param name="text">Text to match</param>
protected static void TestMatch(Regex r, string text)
{
TestMatch(r, text, true);
}
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="text"></param>
/// <param name="expectedMatches"></param>
protected static void TestMatches(Regex r, string text, int expectedMatches)
{
Assert.AreEqual(expectedMatches, r.Matches(text).Count);
}
protected static void TestMatch(Match m, params string[] groups)
{
Assert.GreaterOrEqual(m.Groups.Count, groups.Length, "Too few groups matched");
for (int i = 0; i < groups.Length; i++)
{
if (groups[i] == null) continue;
Assert.AreEqual(groups[i], m.Groups[i].Value);
}
}
protected static void TestMatch(Regex r, string text, params string[] groups)
{
TestMatch(r.Match(text), groups);
}
}
[TestFixture]
// Don't place tests that require switching to non-default locale here
public class RegexTests : RegexTestsBase
{
[Test]
public void GenerateNamespaceRegex()
{
Assert.AreEqual("", WikiRegexes.GenerateNamespaceRegex(0));
Assert.AreEqual("User", WikiRegexes.GenerateNamespaceRegex(Namespace.User));
Assert.AreEqual("User[ _]talk", WikiRegexes.GenerateNamespaceRegex(Namespace.UserTalk));
Assert.AreEqual("File|Image", WikiRegexes.GenerateNamespaceRegex(Namespace.File));
Assert.AreEqual("Wikipedia|Project", WikiRegexes.GenerateNamespaceRegex(Namespace.Project));
Assert.AreEqual("Media|File|Image",
WikiRegexes.GenerateNamespaceRegex(Namespace.Media, Namespace.File));
}
[Test]
public void SimpleWikiLink()
{
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo]]", "[[foo]]", "foo");
TestMatches(WikiRegexes.SimpleWikiLink, "[[foo[]]", 0);
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo bar]]", "[[foo bar]]", "foo bar");
TestMatches(WikiRegexes.SimpleWikiLink, "[[foo\r\nbar]]", 0);
TestMatches(WikiRegexes.SimpleWikiLink, "[foo]]", 0);
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo|bar]]", "[[foo|bar]]", "foo|bar");
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo]] [[bar]]", "[[foo]]", "foo");
TestMatches(WikiRegexes.SimpleWikiLink, "[[foo]] [[bar]]", 2);
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo]]]", "[[foo]]", "foo");
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo [[bar]] here]]", "[[foo [[bar]] here]]", "foo [[bar]] here");
TestMatch(WikiRegexes.SimpleWikiLink, "[[[foo]]", "[[foo]]", "foo");
TestMatch(WikiRegexes.SimpleWikiLink, "[[foo|bar]]");
TestMatch(WikiRegexes.SimpleWikiLink, "[[Image:Foo.jpg]]");
TestMatch(WikiRegexes.SimpleWikiLink, "[[Image:Bar.jpg|Bar]]");
TestMatch(WikiRegexes.SimpleWikiLink, "[[Image:Bar.jpg|Bar|20px]]");
TestMatch(WikiRegexes.SimpleWikiLink, "[[Category:Foo]]");
TestMatch(WikiRegexes.SimpleWikiLink, "[[Category:Foo|Bar]]");
}
[Test]
public void RedirectTest()
{
TestMatch(WikiRegexes.Redirect, "#redirect [[Foo]]", "#redirect [[Foo]]", @"Foo");
TestMatch(WikiRegexes.Redirect, "#redirect [[Foo|bar]]", "#redirect [[Foo|bar]]", @"Foo");
TestMatch(WikiRegexes.Redirect, "#Redirect : [[Foo#bar]]", "#Redirect : [[Foo#bar]]", @"Foo#bar");
TestMatch(WikiRegexes.Redirect, "#REDIRECT[[Foo]]", "#REDIRECT[[Foo]]", @"Foo");
TestMatch(WikiRegexes.Redirect, "#redirect[[:Foo bar ]]", "#redirect[[:Foo bar ]]", @"Foo bar");
TestMatches(WikiRegexes.Redirect, "[foo]]", 0);
}
[Test]
public void TalkpageHeader()
{
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talk header|foo}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{ talk header}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{Talk header|foo}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{Talkheader|foo}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{Talkpageheader|foo}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talkheader|foo}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talkheader
|foo|bar
|here}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{Talkheader}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talk header|search=yes}}", 1);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talk header|noarchive=yes}}", 1);
Assert.AreEqual(@"Talkpageheader", WikiRegexes.TalkHeaderTemplate.Match(@"{{ Talkpageheader |foo}}").Groups[1].Value);
// no match
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talkarchivenav|noredlinks=yes}}", 0);
TestMatches(WikiRegexes.TalkHeaderTemplate, @"{{talkheadernav}}", 0);
}
[Test]
public void SkipTOCTemplateRegex()
{
TestMatches(WikiRegexes.SkipTOCTemplateRegex, @"{{Skip to talk}}", 1);
TestMatches(WikiRegexes.SkipTOCTemplateRegex, @"{{ skiptotoctalk}}", 1);
TestMatches(WikiRegexes.SkipTOCTemplateRegex, @"{{skiptotoc}}", 1);
}
[Test]
public void WikiProjectBannerShellTemplate()
{
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WPBS|1=foo}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBannerShell}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBanners|foo}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBanners|1=foo|bar}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBanners|blp=yes|activepol=yes|1=foo}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBanners|blp=yes|1=
{{WPBiography|living=yes|class=}}
}}", 1);
TestMatches(WikiRegexes.WikiProjectBannerShellTemplate, @"{{WikiProjectBanners|blp=yes|1=
{{WPBiography|living=yes|class=}}
{{WikiProject Greece}}
|activepol=yes
}}", 1);
}
[Test]
public void BLPUnsourced()
{
TestMatches(WikiRegexes.BLPSources, @"{{BLP unsourced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{UnsourcedBLP|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{BLPunreferenced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Unreferencedblp|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Blpunsourced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{BLPunsourced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Unsourcedblp|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{BLPUnreferenced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Unsourced BLP|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{BLP unreferenced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Blpunref|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Unreferenced BLP|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Blpunreferenced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{UnreferencedBLP|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{BLPUnsourced|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{Unreferenced blp|foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{ BLP Unreferenced | foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{ BLP Unreferenced section| foo}}", 1);
TestMatches(WikiRegexes.BLPSources, @"{{bLP Unreferenced}}", 1);
}
[Test]
public void NamedReferences()
{
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"<ref name = ""foo"">text</ref>"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"<ref name = ""foo""></ref>"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"<ref name =foo>text</ref>"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"<ref name=foo>text< / ref >"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"<ref name = 'foo'>text</ref>"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"< REF NAME = ""foo"">text</ref>"));
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"< REF NAME = ""foo"">
{{ cite web|
title = text |
work = text
}}</ref>"), "matches multiple line ref");
Assert.IsTrue(WikiRegexes.NamedReferences.IsMatch(@"< REF NAME = ""foo"">text <br>more</ref>"), "case insensitive matching");
Assert.AreEqual(@"<ref name=""Shul726"">Shul, p. 726</ref>", WikiRegexes.NamedReferences.Match(@"<ref name=""vietnam.ttu.edu""/><ref name=""Shul726"">Shul, p. 726</ref>").Value, "match is not across consecutive references – first condensed");
Assert.AreEqual(@"<ref name=""Shul726"">Shul, p. 726</ref>", WikiRegexes.NamedReferences.Match(@"<ref name=""Shul726"">Shul, p. 726</ref><ref name=""Foo"">foo text</ref>").Value, "match is not across consecutive references – first full");
Assert.AreEqual(@"Shul726", WikiRegexes.NamedReferences.Match(@"<ref name=""vietnam.ttu.edu""/><ref name=""Shul726"">Shul, p. 726</ref>").Groups[2].Value, "ref name is group 2");
Assert.AreEqual(@"Shul, p. 726", WikiRegexes.NamedReferences.Match(@"<ref name=""vietnam.ttu.edu""/><ref name=""Shul726"">Shul, p. 726</ref>").Groups[3].Value, "ref value is group 3");
Assert.AreEqual(@"Shul726", WikiRegexes.NamedReferences.Match(@"<ref name=""vietnam.ttu.edu""/><ref name=""Shul726"">
Shul, p. 726 </ref>").Groups[2].Value, "ref value doesn't include leading/trailing whitespace");
}
[Test]
public void UnformattedTextTests()
{
Assert.IsTrue(WikiRegexes.UnformattedText.IsMatch(@"<pre>{{abc}}</pre>"));
Assert.IsTrue(WikiRegexes.UnformattedText.IsMatch(@"<math>{{abc}}</math>"));
Assert.IsTrue(WikiRegexes.UnformattedText.IsMatch(@"<nowiki>{{abc}}</nowiki>"));
Assert.IsTrue(WikiRegexes.UnformattedText.IsMatch(@"now hello {{bye}} <pre>{now}}</pre>"));
}
[Test]
public void MathPreSourceCodeTests()
{
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<pre>{{abc}}</pre>"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<!--{{abc}}-->"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<code>{{abc}}</code>"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<source lang=xml>{{abc}}</source>"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<source>{{abc}}</source>"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"now hello {{bye}} <pre>{now}}</pre>"));
Assert.IsTrue(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<math>{{abc}}</math>"));
Assert.IsFalse(WikiRegexes.MathPreSourceCodeComments.IsMatch(@"<nowiki>{{abc}}</nowiki>"));
}
[Test]
public void WikiLinksOnly()
{
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo]]", "[[foo]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[:foo]]", "[[:foo]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[a:foo]]", "[[a:foo]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[FOO:BAR]]", "[[FOO:BAR]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo bar:world series]]", "[[foo bar:world series]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo bar]]", "[[foo bar]]");
TestMatches(WikiRegexes.WikiLinksOnly, "[[foo\r\nbar]]", 0);
TestMatches(WikiRegexes.WikiLinksOnly, "[foo]]", 0);
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo|bar]]", "[[foo|bar]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo]] [[bar]]", "[[foo]]");
TestMatches(WikiRegexes.WikiLinksOnly, "[[foo]] [[bar]]", 2);
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo]]]", "[[foo]]");
TestMatch(WikiRegexes.WikiLinksOnly, "[[[foo]]", "[[foo]]");
TestMatches(WikiRegexes.WikiLinksOnly, "[[foo[]]", 0);
TestMatch(WikiRegexes.WikiLinksOnly, "[[foo [[bar]] here]", "[[bar]]");
// don't consider Categories, Images and IW to be "WikiLinks Only"
TestMatches(WikiRegexes.WikiLinksOnly, "[[Category:Test]]", 0);
TestMatches(WikiRegexes.WikiLinksOnly, "[[de:Test]]", 0);
TestMatches(WikiRegexes.WikiLinksOnly, "[[Image:Test,]]", 0);
//Assert.AreEqual("Test", WikiRegexes.WikiLinksOnly.Matches("[[Test]]")[0].Groups[1].Value);
}
[Test]
public void WikiLinksOnlyPossiblePipe()
{
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo]]", "[[foo]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[:foo]]", "[[:foo]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[a:foo]]", "[[a:foo]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[FOO:BAR]]", "[[FOO:BAR]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo bar:world series]]", "[[foo bar:world series]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo bar]]", "[[foo bar]]");
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo\r\nbar]]", 0);
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[foo]]", 0);
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo|bar]]", "[[foo|bar]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo]] [[bar]]", "[[foo]]");
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo]] [[bar]]", 2);
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo]]]", "[[foo]]");
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[[foo]]", "[[foo]]");
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo[]]", 0);
TestMatch(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[foo [[bar]] here]", "[[bar]]");
// don't consider Categories, Images and IW to be "WikiLinks Only"
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[Category:Test]]", 0);
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[de:Test]]", 0);
TestMatches(WikiRegexes.WikiLinksOnlyPossiblePipe, "[[Image:Test,]]", 0);
Assert.AreEqual("foo", WikiRegexes.WikiLinksOnlyPossiblePipe.Match("[[foo|bar]]").Groups[1].Value);
Assert.AreEqual("foo", WikiRegexes.WikiLinksOnlyPossiblePipe.Match("[[foo]]").Groups[1].Value);
Assert.AreEqual("foo smith:the great", WikiRegexes.WikiLinksOnlyPossiblePipe.Match("[[foo smith:the great|bar]]").Groups[1].Value);
Assert.AreEqual("bar here", WikiRegexes.WikiLinksOnlyPossiblePipe.Match("[[foo|bar here]]").Groups[2].Value);
}
[Test]
public void DeadLinkTests()
{
TestMatch(WikiRegexes.DeadLink, "{{dead link}}", "{{dead link}}");
TestMatch(WikiRegexes.DeadLink, "{{Dead link}}", "{{Dead link}}");
TestMatch(WikiRegexes.DeadLink, "{{Deadlink}}", "{{Deadlink}}");
TestMatch(WikiRegexes.DeadLink, "{{brokenlink}}", "{{brokenlink}}");
TestMatch(WikiRegexes.DeadLink, "{{Dl}}", "{{Dl}}");
TestMatch(WikiRegexes.DeadLink, "{{Dead link}}", "{{Dead link}}");
TestMatch(WikiRegexes.DeadLink, "{{dead link|date=May 2009}}", "{{dead link|date=May 2009}}");
}
[Test]
public void WikiLinkTests()
{
Assert.AreEqual(WikiRegexes.WikiLink.Match(@"[[foo]]").Groups[1].Value, @"foo");
Assert.AreEqual(WikiRegexes.WikiLink.Match(@"[[foo|bar]]").Groups[1].Value, @"foo");
Assert.AreEqual(WikiRegexes.WikiLink.Match(@"[[foo bar]]").Groups[1].Value, @"foo bar");
Assert.AreEqual(WikiRegexes.WikiLink.Match(@"[[Foo]]").Groups[1].Value, @"Foo");
Assert.AreEqual(WikiRegexes.WikiLink.Match(@"[[foo bar|word here]]").Groups[1].Value, @"foo bar");
}
[Test]
public void PipedWikiLink()
{
TestMatch(WikiRegexes.PipedWikiLink, "[[foo|bar]]");
TestMatch(WikiRegexes.PipedWikiLink, "a [[foo boo | bar bar ]] !one", "[[foo boo | bar bar ]]");
TestMatch(WikiRegexes.PipedWikiLink, "[[foo]]", false);
// shouldn't eat too much
TestMatch(WikiRegexes.PipedWikiLink, "[[foo]] [[foo|bar]]", "[[foo|bar]]");
TestMatch(WikiRegexes.PipedWikiLink, "[[foo|bar]] [[foo]]", "[[foo|bar]]");
TestMatch(WikiRegexes.PipedWikiLink, "[[foo|\r\nbar]]", false);
TestMatch(WikiRegexes.PipedWikiLink, "[[foo\r\n|bar]]", false);
TestMatch(WikiRegexes.PipedWikiLink, "[[foo]] | bar]]", false);
TestMatch(WikiRegexes.PipedWikiLink, "[[foo | [[bar]]", false);
Assert.AreEqual("foo", WikiRegexes.PipedWikiLink.Match("[[foo|bar]]").Groups[1].Value);
Assert.AreEqual("bar", WikiRegexes.PipedWikiLink.Match("[[foo|bar]]").Groups[2].Value);
}
[Test]
public void Blockquote()
{
// one line
TestMatch(WikiRegexes.Blockquote, "<blockquote>foo bar< /blockquote>", "<blockquote>foo bar< /blockquote>");
TestMatch(WikiRegexes.Blockquote, "<blockquote style=x>foo bar< /blockquote>", "<blockquote style=x>foo bar< /blockquote>");
// multiple lines
TestMatch(WikiRegexes.Blockquote, "< Blockquote >foo\r\nbar</ BLOCKQUOTE>", "< Blockquote >foo\r\nbar</ BLOCKQUOTE>");
}
[Test]
public void Persondata()
{
string pd1 = @"{{Persondata
|NAME= Skipworth, Alison
|ALTERNATIVE NAMES=
|SHORT DESCRIPTION=British actress
|DATE OF BIRTH= 25 July 1863
|PLACE OF BIRTH= [[London, England]], England
|DATE OF DEATH= 5 July 1952
|PLACE OF DEATH= {{city-state|Los Angeles|California}}, U.S.
}}", pd2 = @"{{Persondata
|NAME= Skipworth, Alison
|ALTERNATIVE NAMES=
|SHORT DESCRIPTION=British actress
|DATE OF BIRTH= 25 July 1863
|PLACE OF BIRTH= [[London, England]], England
|DATE OF DEATH= 5 July 1952
|PLACE OF DEATH= Los Angeles, California, U.S.
}}";
TestMatch(WikiRegexes.Persondata, pd1, pd1);
TestMatch(WikiRegexes.Persondata, pd2, pd2);
}
[Test]
public void UseDatesTemplateTests()
{
TestMatch(WikiRegexes.UseDatesTemplate, @"{{use mdy dates}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{mdy}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{Mdy}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{ Use dmy dates}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{dmy}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{DMY}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{use ymd dates}}", true);
TestMatch(WikiRegexes.UseDatesTemplate, @"{{ISO}}", true);
Assert.AreEqual(WikiRegexes.UseDatesTemplate.Match(@"{{use mdy dates}}").Groups[2].Value, "use mdy dates");
}
[Test]
public void ISODates()
{
TestMatch(WikiRegexes.ISODates, @"on 2009-12-11 a", true);
TestMatch(WikiRegexes.ISODates, @"on 2009-12-01 a", true);
TestMatch(WikiRegexes.ISODates, @"on 2009-12-21 a", true);
TestMatch(WikiRegexes.ISODates, @"on 2009-08-31 a", true);
TestMatch(WikiRegexes.ISODates, @"BC]] |date=2003-10-19 }}", true);
TestMatch(WikiRegexes.ISODates, @"on 1009-12-11 a", false);
TestMatch(WikiRegexes.ISODates, @"on 2209-12-11 a", false);
TestMatch(WikiRegexes.ISODates, @"on 2009-14-11 a", false);
TestMatch(WikiRegexes.ISODates, @"on 2009-2-11 a", false);
TestMatch(WikiRegexes.ISODates, @"on 2009-08-33 a", false);
TestMatch(WikiRegexes.ISODates, @"on 2009/08/31 a", false);
}
[Test]
public void ImageMapTests()
{
// one line
TestMatch(WikiRegexes.ImageMap, "<imagemap>foo bar< /imagemap>", "<imagemap>foo bar< /imagemap>");
TestMatch(WikiRegexes.ImageMap, "<Imagemap>foo bar< /Imagemap>", "<Imagemap>foo bar< /Imagemap>");
TestMatch(WikiRegexes.ImageMap, "<imagemap id=hello>foo bar< /imagemap>", "<imagemap id=hello>foo bar< /imagemap>");
// multiple lines
TestMatch(WikiRegexes.ImageMap, @"< imagemap >foo
bar</ IMAGEMAP>", @"< imagemap >foo
bar</ IMAGEMAP>");
}
[Test]
public void NoincludeTests()
{
// one line
TestMatch(WikiRegexes.Noinclude, "<noinclude>foo bar< /noinclude>", "<noinclude>foo bar< /noinclude>");
TestMatch(WikiRegexes.Noinclude, "<Noinclude>foo bar< /Noinclude>", "<Noinclude>foo bar< /Noinclude>");
// multiple lines
TestMatch(WikiRegexes.Noinclude, @"< noinclude >foo
bar</ NOINCLUDE>", @"< noinclude >foo
bar</ NOINCLUDE>");
}
[Test]
public void IncludeonlyTests()
{
// one line
TestMatch(WikiRegexes.Includeonly, "<includeonly>foo bar< /includeonly>", "<includeonly>foo bar< /includeonly>");
TestMatch(WikiRegexes.Includeonly, "<Includeonly>foo bar< /Includeonly>", "<Includeonly>foo bar< /Includeonly>");
TestMatch(WikiRegexes.Includeonly, "<onlyInclude>foo bar< /onlyInclude>", "<onlyInclude>foo bar< /onlyInclude>");
// multiple lines
TestMatch(WikiRegexes.Includeonly, @"< includeonly >foo
bar</ INCLUDEONLY>", @"< includeonly >foo
bar</ INCLUDEONLY>");
}
[Test]
public void Template()
{
RegexAssert.Matches("{{foo}}", WikiRegexes.TemplateMultiline, "{{foo}}");
RegexAssert.Matches("{{foo}}", WikiRegexes.TemplateMultiline, "123{{foo}}test");
RegexAssert.Matches("{{foo|bar}}", WikiRegexes.TemplateMultiline, "{{foo|bar}}");
RegexAssert.Matches("{{foo\r\n|bar=test}}", WikiRegexes.TemplateMultiline, "{{foo\r\n|bar=test}}");
RegexAssert.Matches("Should match distinct templates", WikiRegexes.TemplateMultiline, "{{foo}}{{bar}}", "{{foo}}", "{{bar}}");
// regex won't match if nested template or curly-bracketed stuff
RegexAssert.NoMatch(WikiRegexes.TemplateMultiline, "{{foo| {bar} }}");
}
[Test]
public void NestedTemplates()
{
RegexAssert.Matches("{{foo}}", WikiRegexes.NestedTemplates, "{{foo}}");
RegexAssert.Matches("{{foo}}", WikiRegexes.NestedTemplates, "123{{foo}}test");
RegexAssert.Matches("{{foo|bar}}", WikiRegexes.NestedTemplates, "{{foo|bar}}");
RegexAssert.Matches("{{foo\r\n|bar=test}}", WikiRegexes.NestedTemplates, "{{foo\r\n|bar=test}}");
RegexAssert.Matches("Should match distinct templates", WikiRegexes.NestedTemplates, "{{foo}}{{bar}}", "{{foo}}", "{{bar}}");
RegexAssert.Matches("{{foo| {bar} }}", WikiRegexes.NestedTemplates, "{{foo| {bar} }}");
RegexAssert.Matches("{{foo {{bar}} end}}", WikiRegexes.NestedTemplates, "{{foo {{bar}} end}}");
RegexAssert.Matches("{{foo {bar} end}}", WikiRegexes.NestedTemplates, "{{foo {bar} end}}");
RegexAssert.Matches("{{ foo |bar}}", WikiRegexes.NestedTemplates, "{{ foo |bar}}");
RegexAssert.Matches("{{foo<!--comm-->|bar}}", WikiRegexes.NestedTemplates, "{{foo<!--comm-->|bar}}");
RegexAssert.Matches("", WikiRegexes.NestedTemplates, "{{foo");
}
[Test]
public void TemplateName()
{
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{Start date and age|1833|7|11}}").Groups[1].Value == "Start date and age");
// whitespace handling
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{ Start date and age |1833|7|11}}").Groups[1].Value == "Start date and age");
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{
Start date and age
|1833|7|11}}").Groups[1].Value == "Start date and age");
// embedded comments
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{start date and age <!--comm--> |1833|7|11}}").Groups[1].Value == "start date and age");
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{start date and age <!--comm-->}}").Groups[1].Value == "start date and age");
// works on part templates
Assert.IsTrue(WikiRegexes.TemplateName.Match(@"{{Start date and age|1833|7|").Groups[1].Value == "Start date and age");
}
[Test]
public void BulletedText()
{
RegexAssert.NoMatch(WikiRegexes.BulletedText, "");
RegexAssert.Matches(WikiRegexes.BulletedText, ":foo", ":foo");
RegexAssert.Matches(WikiRegexes.BulletedText, ":foo\r\n", ":foo\r");
RegexAssert.Matches(WikiRegexes.BulletedText, "#foo\r\n*:bar", "#foo\r", "*:bar");
RegexAssert.Matches(WikiRegexes.BulletedText, "#foo\r\ntest\r\n*:bar", "#foo\r", "*:bar");
RegexAssert.Matches(WikiRegexes.BulletedText, " foo\r\nfoo bar", " foo\r");
}
[Test]
public void Headings()
{
RegexAssert.NoMatch(WikiRegexes.Headings, "");
RegexAssert.IsMatch(WikiRegexes.Headings, "=Foo=");
RegexAssert.IsMatch(WikiRegexes.Headings, "=Foo=<!--comm-->");
RegexAssert.IsMatch(WikiRegexes.Headings, "==Foo==");
RegexAssert.IsMatch(WikiRegexes.Headings, "======Foo======");
Assert.AreEqual(WikiRegexes.Headings.Match("======Foo======").Groups[1].Value, "Foo");
Assert.AreEqual(WikiRegexes.Headings.Match("== Foo == ").Groups[1].Value, "Foo");
RegexAssert.IsMatch(WikiRegexes.Headings, "==Foo=", "matches unbalanced headings");
}
[Test]
public void Refs()
{
RegexAssert.Matches(WikiRegexes.Refs, "<ref>foo</ref>", "<ref>foo</ref>");
RegexAssert.Matches(WikiRegexes.Refs, "<ref>foo<br></ref>", "<ref>foo<br></ref>");
RegexAssert.Matches(WikiRegexes.Refs, "<ref>foo<br>bar</ref>", "<ref>foo<br>bar</ref>");
RegexAssert.IsMatch(WikiRegexes.Refs, @"<ref>{{cite web
|url=http://www.h.com/.php?tmi=5177|title=Season-by-season record |accessdate = 2008-12-01}}</ref>");
RegexAssert.Matches(WikiRegexes.Refs, "<REF NAME=\"foo\" >bar</ref >", "<REF NAME=\"foo\" >bar</ref >");
RegexAssert.Matches(WikiRegexes.Refs, "<REF NAME=foo>bar< /ref>", "<REF NAME=foo>bar< /ref>");
RegexAssert.Matches(WikiRegexes.Refs, "<ReF Name=foo/>", "<ReF Name=foo/>");
RegexAssert.Matches(WikiRegexes.Refs, "<ReF Name = 'foo'/>", "<ReF Name = 'foo'/>");
RegexAssert.Matches(WikiRegexes.Refs, "<ReF Name = \"foo\"/>", "<ReF Name = \"foo\"/>");
RegexAssert.Matches(WikiRegexes.Refs, "< ref>foo</ ref>", "< ref>foo</ ref>");
RegexAssert.Matches(WikiRegexes.Refs, @"<ref name= ""foo/bar""/>", @"<ref name= ""foo/bar""/>");
RegexAssert.Matches(WikiRegexes.Refs, @"<ref name= ""foo/bar"">a</ref>", @"<ref name= ""foo/bar"">a</ref>");
RegexAssert.NoMatch(WikiRegexes.Refs, "<refname=foo>bar</ref>");
RegexAssert.NoMatch(WikiRegexes.Refs, "<refname=foo/>");
RegexAssert.Matches(WikiRegexes.Refs, "<ref group=a name=foo/>", "<ref group=a name=foo/>");
RegexAssert.Matches(WikiRegexes.Refs, "<ref name=foo group=a />", "<ref name=foo group=a />");
// http://en.wikipedia.org/wiki/Wikipedia_talk:AutoWikiBrowser/Bugs/Archive_10#.3Cp.3E_deletion_in_references_and_notes
RegexAssert.Matches(WikiRegexes.Refs, "<ref>foo<!-- bar --></ref>", "<ref>foo<!-- bar --></ref>");
// shouldn't eat too much
RegexAssert.Matches(WikiRegexes.Refs, "<ref>foo<!-- bar --></ref> <ref>foo</ref>", "<ref>foo<!-- bar --></ref>", "<ref>foo</ref>");
TestMatches(WikiRegexes.Refs, @"Article<ref>A</ref> <ref>B</ref> <ref>C</ref> <ref>B</ref> <ref>E</ref>", 5);
// this is why the <DEPTH> business is needed in WikiRegexes.Refs
RegexAssert.Matches(new Regex(WikiRegexes.Refs + @"\."), "Foo.<ref>bar</ref>. The next Foo.<ref>bar <br> other</ref> The next Foo.<ref>bar</ref> The next Foo.<ref>bar</ref> The nextFoo<ref>bar2</ref>. The next", "<ref>bar</ref>.", "<ref>bar2</ref>.");
}
[Test]
public void Small()
{
RegexAssert.Matches(WikiRegexes.Small, "<small>foo</small>", "<small>foo</small>");
RegexAssert.Matches(WikiRegexes.Small, "<small >foo</small >", "<small >foo</small >");
RegexAssert.Matches(WikiRegexes.Small, @"<small>
foo
</small>", @"<small>
foo
</small>");
RegexAssert.Matches(WikiRegexes.Small, "<SMALL>foo</SMALL>", "<SMALL>foo</SMALL>");
RegexAssert.Matches(WikiRegexes.Small, "<small>a<small>foo</small>b</small>", "<small>a<small>foo</small>b</small>");
RegexAssert.Matches(WikiRegexes.Small, @"<small>..<small>...</small>", @"<small>...</small>");
}
[Test]
public void Big()
{
RegexAssert.Matches(WikiRegexes.Big, "<big>foo</big>", "<big>foo</big>");
RegexAssert.Matches(WikiRegexes.Big, "<big >foo</big >", "<big >foo</big >");
RegexAssert.Matches(WikiRegexes.Big, @"<big>
foo
</big>", @"<big>
foo
</big>");
RegexAssert.Matches(WikiRegexes.Big, "<big>foo</big>", "<big>foo</big>");
RegexAssert.Matches(WikiRegexes.Big, "<big>a<big>foo</big>b</big>", "<big>a<big>foo</big>b</big>");
RegexAssert.Matches(WikiRegexes.Big, @"<big>..<big>...</big>", @"<big>...</big>");
}
[Test]
public void Nowiki()
{
RegexAssert.Matches(WikiRegexes.Nowiki, "<nowiki>foo</nowiki>", "<nowiki>foo</nowiki>");
RegexAssert.Matches(WikiRegexes.Nowiki, "<nowiki >foo</nowiki >", "<nowiki >foo</nowiki >");
}
[Test]
public void ExternalLink()
{
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://google.co.uk", "http://google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://google-here.co.uk", "http://google-here.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "https://google.co.uk", "https://google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://foo.com/asdfasdf/asdf.htm", "http://foo.com/asdfasdf/asdf.htm");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://www.google.co.uk", "http://www.google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "lol http://www.google.co.uk lol", "http://www.google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "[http://www.google.co.uk]", "[http://www.google.co.uk]");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "[http://www.google.co.uk google]", "[http://www.google.co.uk google]");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "lol [http://www.google.co.uk] lol", "[http://www.google.co.uk]");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "lol [http://www.google.co.uk google] lol", "[http://www.google.co.uk google]");
//http://en.wikipedia.org/wiki/Wikipedia_talk:AutoWikiBrowser/Bugs/Archive_14#Regex_problem
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://www.google.co.uk google}}", "http://www.google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, "http://www.google.co.uk}}", "http://www.google.co.uk");
RegexAssert.Matches(WikiRegexes.ExternalLinks, @"date=April 2010|url=http://w/010111a.html}}", "http://w/010111a.html");
RegexAssert.Matches(WikiRegexes.ExternalLinks, @"date=April 2010|url=http://w/010111a.html|location=London}}", "http://w/010111a.html");
// incorrect brackets
RegexAssert.Matches(WikiRegexes.ExternalLinks, "lol [http://www.google.co.uk lol", "http://www.google.co.uk");
RegexAssert.NoMatch(WikiRegexes.ExternalLinks, "Google");
// protocol is group 1
Assert.AreEqual("http", WikiRegexes.ExternalLinks.Match(@"http://google.co.uk").Groups[1].Value);
Assert.AreEqual("svn", WikiRegexes.ExternalLinks.Match(@"svn://google.co.uk Google}}").Groups[1].Value);
Assert.AreEqual("Http", WikiRegexes.ExternalLinks.Match(@"Http://google.co.uk").Groups[1].Value);
Assert.AreEqual("HTTP", WikiRegexes.ExternalLinks.Match(@"HTTP://google.co.uk").Groups[1].Value);
// not when in external link brackets
Assert.AreEqual("", WikiRegexes.ExternalLinks.Match(@"[http://google.co.uk Google]").Groups[1].Value);
}
[Test]
public void PossibleInterwikis()
{
RegexAssert.Matches(WikiRegexes.PossibleInterwikis, "foo[[en:bar]]", "[[en:bar]]");
RegexAssert.Matches(WikiRegexes.PossibleInterwikis, "[[en:bar]][[ru:", "[[en:bar]]");
RegexAssert.Matches(WikiRegexes.PossibleInterwikis, "foo[[en:bar:quux]][[ru:boz test]]", "[[en:bar:quux]]", "[[ru:boz test]]");
RegexAssert.NoMatch(WikiRegexes.PossibleInterwikis, "[[:en:foo]]");
RegexAssert.NoMatch(WikiRegexes.PossibleInterwikis, "[[:foo]]");
RegexAssert.NoMatch(WikiRegexes.PossibleInterwikis, "[[File:foo]]");
Assert.AreEqual("en", WikiRegexes.PossibleInterwikis.Match("[[ en :bar]]").Groups[1].Value);
Assert.AreEqual("bar", WikiRegexes.PossibleInterwikis.Match("[[en: bar ]]").Groups[2].Value);
Assert.AreEqual(" <!--comm-->", WikiRegexes.PossibleInterwikis.Match("[[en: bar ]] <!--comm-->").Groups[3].Value);
// length outside range
RegexAssert.NoMatch(WikiRegexes.PossibleInterwikis, "[[e:foo]]");
RegexAssert.NoMatch(WikiRegexes.PossibleInterwikis, "[[abcdefghijlkmnop:foo]]");
RegexAssert.Matches(WikiRegexes.PossibleInterwikis, "foo[[en:bar]] <!--comm-->", "[[en:bar]] <!--comm-->");
}
[Test]
public void UntemplatedQuotes()
{
// RegexAssert doesn't seem to work, so do tests this way
// be careful about condensing any of these unit tests, as some of the different quote characters *look* the same, but in fact are different Unicode characters
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ""very fast"" ", "1").Contains(@"""very fast"""));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" « very fast » ", "1").Contains(@"« very fast »"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ‘very fast‘ ", "1").Contains(@"‘very fast‘"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ’ very fast ’ ", "").Contains(@"’ very fast ’"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast “ ", "").Contains(@"“ very fast “"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ” very fast ” ", "").Contains(@"” very fast ”"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ‛ very fast ‛ ", "").Contains(@"‛ very fast ‛"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ‟ very fast‟ ", " ").Contains(@"‟ very fast‟"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ‹ very fast › ", "").Contains(@"‹ very fast ›"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast ” ", "").Contains(@"“ very fast ”"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" „ very fast „ ", "").Contains(@"„ very fast „"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" „ very fast „ ", "").Contains(@"„ very fast „"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ‘ very fast ‘ ", "").Contains(@"‘ very fast ‘"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ’ very fast ’ ", "").Contains(@"’ very fast ’"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast ” ", "").Contains(@"“ very fast ”"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ` very fast ` ", "").Contains(@"` very fast `"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" ’ very fast ‘ ", "").Contains(@"’ very fast ‘"));
Assert.IsFalse(WikiRegexes.UntemplatedQuotes.Replace(@" „very
fast„ ", "").Contains(@" „very
fast„ "));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast ” but not pretty ", "").Contains("but not pretty"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast ” but not pretty“ ", "").Contains("but not pretty“"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" “ very fast ” and “ very well ” ", "").Contains(" and "));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@"not pretty but “ very fast ” ", "").Contains("not pretty but "));
// don't match single quotes, no quotes
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" very fast ", "").Contains(@"very fast"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" 'very fast' ", "").Contains(@"'very fast'"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" ''very fast'' ", "").Contains(@"''very fast''"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" ''very fast'' ", "").Contains(@"''very fast''"));
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@" ,very fast, ", "").Contains(@",very fast,")); // commas
// don't match apostrophes when used within words
Assert.IsTrue(WikiRegexes.UntemplatedQuotes.Replace(@"Now it’s a shame as it’s a", "").Contains(@"Now it’s a shame as it’s a"));
}
[Test]
public void CurlyDoubleQuotes()
{
Assert.IsTrue(WikiRegexes.CurlyDoubleQuotes.IsMatch(@" “ very fast ”"));
Assert.IsTrue(WikiRegexes.CurlyDoubleQuotes.IsMatch(@"very fast «"));
Assert.IsTrue(WikiRegexes.CurlyDoubleQuotes.IsMatch(@"very fast»"));
}
[Test]
public void SicTagTests()
{
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now helo [sic] there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now helo[sic] there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now helo (sic) there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now helo {sic} there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now helo [Sic] there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now {{sic|helo}} there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now {{sic|hel|o}} there"));
Assert.IsTrue(WikiRegexes.SicTag.IsMatch("now {{typo|helo}} there"));
Assert.IsFalse(WikiRegexes.SicTag.IsMatch("now sickened by"));
Assert.IsFalse(WikiRegexes.SicTag.IsMatch("now helo sic there"));
}
[Test]
public void RFromModification()
{
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromModificationList).IsMatch(@"{{R from modification}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromModificationList).IsMatch(@"{{ r from modification}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromModificationList).IsMatch(@"{{R mod }}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromModificationList).IsMatch(@"{{R from alternate punctuation}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromModificationList).IsMatch(@"{{R from alternative punctuation}}"));
}
[Test]
public void RFromTitleWithoutDiacritics()
{
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R to accents}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{Redirects from title without diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{RDiacr}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{r to unicode name}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{ R to unicode}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R to unicode }}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R to title with diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R to diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R from name without diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R from title without diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R from original name without diacritics}}"));
Assert.IsTrue(Tools.NestedTemplateRegex(WikiRegexes.RFromTitleWithoutDiacriticsList).IsMatch(@"{{R without diacritics}}"));
}
[Test]
public void MoreNoFootnotesTests()
{
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{morefootnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{Morefootnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{More footnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{Nofootnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{No footnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{nofootnotes}}"));
Assert.IsTrue(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{nofootnotes|section}}"));
Assert.IsFalse(WikiRegexes.MoreNoFootnotes.IsMatch(@"{{NOFOOTNOTES}}"));
}
[Test]
public void ReferencesTemplateTests()
{
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{reflist}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{reflist|2}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{Reflist}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{ref-list}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{Reflink}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{reflink}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{References}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{references}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> <references/>"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> <references />"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{Listaref|2}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref> {{ listaref | 2}}"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"<references>
<ref name =Fred>Fred</ref> </references>"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"< references >
<ref name =Fred>Fred</ref> </ references >"));
Assert.IsFalse(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref>Fred</ref>"));
Assert.IsFalse(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello<ref name=""F"">Fred</ref>"));
Assert.IsFalse(WikiRegexes.ReferencesTemplate.IsMatch(@"Hello world"));
Assert.IsTrue(WikiRegexes.ReferencesTemplate.IsMatch(@"{{Reflist|refs=
<ref name=modern>{{cite news |first=William }}
}}"));
}
[Test]
public void CiteTemplate()
{
Assert.IsTrue(WikiRegexes.CiteTemplate.IsMatch(@"{{cite web|url=a|title=b}}"));
Assert.IsTrue(WikiRegexes.CiteTemplate.IsMatch(@"{{cite web}}"));
Assert.IsTrue(WikiRegexes.CiteTemplate.IsMatch(@"{{ cite web|url=a|title=b}}"));
Assert.IsTrue(WikiRegexes.CiteTemplate.IsMatch(@"{{Citeweb|url=a|title=b}}"));
Assert.IsTrue(WikiRegexes.CiteTemplate.IsMatch(@"{{Citeweb|url=a|title=b and {{foo}} there}}"));
// name derivation
Assert.AreEqual(WikiRegexes.CiteTemplate.Match(@"{{cite web|url=a|title=b}}").Groups[2].Value, "cite web");
Assert.AreEqual(WikiRegexes.CiteTemplate.Match(@"{{ cite web |url=a|title=b}}").Groups[2].Value, "cite web");
Assert.AreEqual(WikiRegexes.CiteTemplate.Match(@"{{Cite web
|url=a|title=b}}").Groups[2].Value, "Cite web");
Assert.AreEqual(WikiRegexes.CiteTemplate.Match(@"{{cite press release|url=a|title=b}}").Groups[2].Value, "cite press release");
}
[Test]
public void RefAfterReflist()
{
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== <references/> <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{Reflist}} <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflink}} <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{ref-list}} <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref>
==references== {{reflist}} <ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} blah
<ref>b</ref>"));
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} <ref name=""b"">b</ref>"));
// {{GR}} with argument as simple decimal provides embedded <ref></ref>
Assert.IsTrue(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} {{GR|4}}"));
Assert.IsFalse(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} {{GR|r4}}"));
Assert.IsFalse(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}} {{GR|India}}"));
// this is correct syntax
Assert.IsFalse(WikiRegexes.RefAfterReflist.IsMatch(@"blah <ref>a</ref> ==references== {{reflist}}"));
string bug1 = @"
==References==
<references />
{{Northampton County, Pennsylvania}}
[[Category:Boroughs in Pennsylvania]]
[[Category:Northampton County, Pennsylvania]]
[[Category:Settlements established in 1790]]
[[ht:Tatamy, Pennsilvani]]
[[nl:Tatamy]]
[[pt:Tatamy]]
[[vo:Tatamy]]";
Assert.IsFalse(WikiRegexes.RefAfterReflist.IsMatch(bug1));
}
[Test]
public void IbidOpCitation()
{
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"ibid"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"Ibid"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"IBID"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"op cit"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"Op.cit"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"Op. cit"));
Assert.IsTrue(WikiRegexes.IbidOpCitation.IsMatch(@"Op
cit"));
Assert.IsFalse(WikiRegexes.IbidOpCitation.IsMatch(@"Libid was"));
Assert.IsFalse(WikiRegexes.IbidOpCitation.IsMatch(@"The op was later cit"));
}
[Test]
public void Ibid()
{
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ibid}}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ Ibid }}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ibid|date=May 2009}}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ibid | date=May 2009}}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{Ibid|date={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ibid|date=May 2009|foo=bar}}"));
Assert.IsTrue(WikiRegexes.Ibid.IsMatch(@"{{ibid|}}"));
Assert.IsFalse(WikiRegexes.Ibid.IsMatch(@"Libid was"));
Assert.IsFalse(WikiRegexes.Ibid.IsMatch(@"{{IBID}}"));
Assert.IsFalse(WikiRegexes.Ibid.IsMatch(@"{{Ibidate}}"));
}
[Test]
public void DablinksTests()
{
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{For|Fred the dancer|Fred (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{for|Fred the dancer|Fred (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{otherpeople1|Fred the dancer|Fred Smith (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{For|Fred the dancer|Fred Smith (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{redirect2|Fred the dancer|Fred Smith (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{For
|Fred the dancer
|Fred (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{For|
Fred the dancer|
Fred (dancer)}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{Otheruse|something}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{Otheruses|something}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{Otheruses2|something}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{otheruse|something}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{otheruses}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{other persons}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{otheruse
|something}}"));
Assert.IsTrue(WikiRegexes.Dablinks.IsMatch(@"{{2otheruses|something}}"));
Assert.IsFalse(WikiRegexes.Dablinks.IsMatch(@"{{For fake template|Fred the dancer|Fred(dancer)}}"));
Assert.IsFalse(WikiRegexes.Dablinks.IsMatch(@"{{REDIRECT2|Fred the dancer|Fred Smith (dancer)}}"));
Assert.IsFalse(WikiRegexes.Dablinks.IsMatch(@"{{Otheruse2|something}}")); //non-existent
}
[Test]
public void Unreferenced()
{
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{unreferenced}}"));
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{ Unreferenced}}"));
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{unreferenced }}"));
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{unreferenced|date=May 2009}}"));
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{No refs}}"));
Assert.IsTrue(WikiRegexes.Unreferenced.IsMatch(@"{{Multiple issues|orphan = February 2009|wikify = April 2009|unreferenced = April 2007}}"));
Assert.IsFalse(WikiRegexes.Unreferenced.IsMatch(@"{{unreferenced-stub}}"));
}
[Test]
public void PortalTemplateTests()
{
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{portal}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{port|Foo}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{ portal}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{Portal}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{Portalpar}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{portal|Science}}"));
Assert.IsTrue(WikiRegexes.PortalTemplate.IsMatch(@"{{portal|Spaceflight|RocketSunIcon.svg|break=yes}}"));
Assert.IsFalse(WikiRegexes.PortalTemplate.IsMatch(@"{{PORTAL}}"));
Assert.IsFalse(WikiRegexes.PortalTemplate.IsMatch(@"{{portalos}}"));
Assert.IsFalse(WikiRegexes.PortalTemplate.IsMatch(@"{{portalparity}}"));
Assert.IsFalse(WikiRegexes.PortalTemplate.IsMatch(@"{{Spanish portal|game}}"));
}
[Test]
public void InfoboxTests()
{
TestMatch(WikiRegexes.InfoBox, @" {{Infobox hello| bye}} ", @"{{Infobox hello| bye}}", @"Infobox hello");
TestMatch(WikiRegexes.InfoBox, @" {{ Infobox hello | bye}} ", @"{{ Infobox hello | bye}}", @"Infobox hello");
TestMatch(WikiRegexes.InfoBox, @" {{infobox hello| bye}} ", @"{{infobox hello| bye}}", @"infobox hello");
TestMatch(WikiRegexes.InfoBox, @" {{Infobox hello| bye {{a}} was}} ", @"{{Infobox hello| bye {{a}} was}}", @"Infobox hello");
TestMatch(WikiRegexes.InfoBox, @" {{hello Infobox| bye {{a}} was}} ", @"{{hello Infobox| bye {{a}} was}}", @"hello Infobox");
TestMatch(WikiRegexes.InfoBox, @" {{hello_Infobox| bye {{a}} was}} ", @"{{hello_Infobox| bye {{a}} was}}", @"hello_Infobox");
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{infobox hello| bye}} "));
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{Template:infobox hello| bye}} "));
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{infobox hello
| bye}} "));
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{Infobox_play| bye}} "));
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{some infobox| hello| bye}} "));
Assert.IsTrue(WikiRegexes.InfoBox.IsMatch(@" {{Some Infobox| hello| bye}} "));
Assert.AreEqual(WikiRegexes.InfoBox.Match(@" {{Infobox
| hello| bye}} ").Groups[1].Value, "Infobox");
}
[Test]
public void ExpandTests()
{
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{expand}} here"),"with small first letter");
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{Expand}} here"),"with capital first letter");
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{Expand|date=May 2009}} here"),"with date");
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{expand-article}} here"));
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{Expand-article}} here"));
Assert.IsTrue(WikiRegexes.Expand.IsMatch(@"now {{Article issues
| orphan = December 2010
| expand = December 2010
}} here"));
Assert.IsFalse(WikiRegexes.Expand.IsMatch(@"now {{developers}} here"));
Assert.AreEqual(WikiRegexes.Expand.Replace(@"now {{expand}} here", ""), @"now here");
Assert.AreEqual(WikiRegexes.Expand.Replace(@"now {{expand-article}} here", ""), @"now here");
Assert.AreEqual(WikiRegexes.Expand.Replace(@"{{article issues|wikify=May 2009|COI=March 2009|expand=May 2008}}", ""), @"{{article issues|wikify=May 2009|COI=March 2009}}");
Assert.AreEqual(WikiRegexes.Expand.Replace(@"{{article issues|wikify=May 2009| expand = May 2008|COI=March 2009}}", ""), @"{{article issues|wikify=May 2009|COI=March 2009}}");
}
[Test]
public void TemplateEndTests()
{
Assert.AreEqual(WikiRegexes.TemplateEnd.Match(@"{{foo}}").Value, @"}}");
Assert.AreEqual(WikiRegexes.TemplateEnd.Match(@"{{foo }}").Value, @" }}");
Assert.AreEqual(WikiRegexes.TemplateEnd.Match(@"{{foo
}}").Value, @"
}}");
Assert.AreEqual(WikiRegexes.TemplateEnd.Match(@"{{foo
}}").Groups[1].Value, "\r\n");
Assert.AreEqual(WikiRegexes.TemplateEnd.Match(@"{{foo
}}").Value, "\r\n }}");
}
[Test]
public void PstylesTests()
{
Assert.IsTrue(WikiRegexes.Pstyles.IsMatch(@"<p style=""margin:0px;font-size:100%""><span style=""color:#00ff00"">▪</span> <small>Francophone minorities</small></p>"));
Assert.IsTrue(WikiRegexes.Pstyles.IsMatch(@"<p style=""font-family:monospace; line-height:130%"">hello</p>"));
Assert.IsTrue(WikiRegexes.Pstyles.IsMatch(@"<p style=""font-family:monospace; line-height:130%"">hello</P>"));
Assert.IsTrue(WikiRegexes.Pstyles.IsMatch(@"<p style=""font-family:monospace; line-height:130%"">hello</P>"));
Assert.IsTrue(WikiRegexes.Pstyles.IsMatch(@"<p style = ""font-family:monospace; line-height:130%"">
hello</P>"));
}
[Test]
public void FirstSection()
{
Assert.IsTrue(WikiRegexes.ZerothSection.IsMatch(@"article"));
Assert.IsTrue(WikiRegexes.ZerothSection.IsMatch(@"article ==heading=="));
Assert.IsTrue(WikiRegexes.ZerothSection.IsMatch(@"article ===heading==="));
Assert.AreEqual("==heading==", WikiRegexes.ZerothSection.Replace(@"article ==heading==", ""));
Assert.AreEqual(@"==heading== words ==another heading==", WikiRegexes.ZerothSection.Replace(@"{{wikify}}
{{Infobox hello | bye=yes}}
article words, '''bold''' blah.
==heading== words ==another heading==", ""));
Assert.IsFalse(WikiRegexes.ZerothSection.IsMatch(@""));
}
[Test]
public void HeadingLevelTwoTests()
{
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
==heading==
a"));
Assert.AreEqual("heading", WikiRegexes.HeadingLevelTwo.Match(@"article
==heading==
a").Groups[1].Value);
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
== heading ==
a"));
Assert.AreEqual(" heading ", WikiRegexes.HeadingLevelTwo.Match(@"article
== heading ==
a").Groups[1].Value);
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
== heading ==
words"));
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
==H==
a"));
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
==Hi==
a"));
Assert.IsTrue(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
==Here and=there==
a"));
// no matches
Assert.IsFalse(WikiRegexes.HeadingLevelTwo.IsMatch(@"article ==
heading=="));
Assert.IsFalse(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
==heading== words"));
Assert.IsFalse(WikiRegexes.HeadingLevelTwo.IsMatch(@"article ===heading=="));
Assert.IsFalse(WikiRegexes.HeadingLevelTwo.IsMatch(@"article
====heading===
words"));
}
[Test]
public void HeadingLevelThreeTests()
{
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
===heading===
a"));
Assert.AreEqual("heading", WikiRegexes.HeadingLevelThree.Match(@"article
===heading===
a").Groups[1].Value);
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
=== heading ===
a"));
Assert.AreEqual(" heading ", WikiRegexes.HeadingLevelThree.Match(@"article
=== heading ===
a").Groups[1].Value);
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
=== heading ===
words"));
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
===H===
a"));
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
===Hi===
a"));
Assert.IsTrue(WikiRegexes.HeadingLevelThree.IsMatch(@"article
===Here and=there===
a"));
// no matches
Assert.IsFalse(WikiRegexes.HeadingLevelThree.IsMatch(@"article ===
heading==="));
Assert.IsFalse(WikiRegexes.HeadingLevelThree.IsMatch(@"article
===heading=== words"));
Assert.IsFalse(WikiRegexes.HeadingLevelThree.IsMatch(@"article ====heading==="));
Assert.IsFalse(WikiRegexes.HeadingLevelThree.IsMatch(@"article
=====heading====
words"));
}
[Test]
public void SectionLevelTwoTests()
{
Assert.IsTrue(WikiRegexes.SectionLevelTwo.IsMatch(@"== heading a ==
words
=== subsection ===
words
words2
== heading b ==
"));
Assert.IsFalse(WikiRegexes.SectionLevelTwo.IsMatch(@"=== subsection ===
words
words2"));
Assert.IsFalse(WikiRegexes.SectionLevelTwo.IsMatch(@"=== heading a ==
words
=== subsection ===
words
words2"));
Assert.IsFalse(WikiRegexes.SectionLevelTwo.IsMatch(@"= heading a =
words
=== subsection ===
words
words2"));
}
[Test]
public void ArticleToFirstLevelTwoHeadingTests()
{
Assert.IsTrue(WikiRegexes.ArticleToFirstLevelTwoHeading.IsMatch(@"words
== heading a ==
"));
Assert.IsFalse(WikiRegexes.ArticleToFirstLevelTwoHeading.IsMatch(@"words
=== heading a ===
"));
}
[Test]
public void ArticleIssuesTests()
{
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Article issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Articleissues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{articleissues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{article issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{article issues | wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{article issues
| wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{article issues|}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Article issues|}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{articleissues}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Articleissues}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Articleissues }}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{Multiple issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{ multiple issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.MultipleIssues.IsMatch(@"{{ multiple issues|wikify={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|orphan={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|c=d}}"));
// no matches
Assert.IsFalse(WikiRegexes.MultipleIssues.IsMatch(@"{{ARTICLEISSUES }}"));
Assert.IsFalse(WikiRegexes.MultipleIssues.IsMatch(@"{{Bert|Articleissues }}"));
}
[Test]
public void ArticleIssuesTemplatesTests()
{
//dated
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{advert|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{advert|date = {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{autobiography|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{biased|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{blpdispute|date = April 2008}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citations missing|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citationstyle|date = May 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citation style|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citecheck|date=April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-laundry|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-reorganize|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-spam|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{COI|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{colloquial|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{confusing|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{context|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{contradict|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{copyedit|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{copy edit|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{criticism section|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{criticisms|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{crystal|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{deadend|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{dead end|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{disputed|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{do-attempt|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{essay|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{examplefarm|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{expand|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{expert| topic name}}")); // not dated
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{expert-subject|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{external links|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fancruft|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fanpov|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fansite|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fiction|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{game guide|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{gameguide|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{globalize|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{grammar|date= April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{histinfo|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{hoax|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{howto|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{inappropriate person|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{in-universe|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Inappropriate tone|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{inappropriate tone|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{incomplete|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro length|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intromissing|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{introrewrite|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro-toolong|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro-tooshort|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-jargon|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{laundrylists|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead missing|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead rewrite|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead too long|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead too short|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{likeresume|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{like resume|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{long|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{news release|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{newsrelease|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{notable|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{notability|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{onesource|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{one source|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Original research|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{orphan|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{peacock|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{plot|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{POV|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{pov-check|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{POV-check|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{primarysources|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{prose|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{proseline|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{quotefarm|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{recent|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{refimprove|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{restructure|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{review|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{rewrite|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Cleanup-rewrite|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{sections|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{self-published|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{spam|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{story|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{synthesis|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{tone|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{tooshort|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{travel guide|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{travelguide|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{trivia|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unbalanced|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unencyclopedic|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unreferenced|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{update|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{weasel|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{wikify|date = April 2009}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{copy edit|for=grammar|date = April 2009}}"));
//undated
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{advert}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{autobiography}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{biased}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{blpdispute}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{BLP sources}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{BLPsources}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{BLP IMDB refimprove}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citations missing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citationstyle}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citation style}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{citecheck}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-laundry}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-reorganize}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-spam}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{COI}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{colloquial}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{confusing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{context}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{contradict}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{copyedit}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{criticism section}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{criticisms}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{crystal}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{deadend}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{disputed}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{do-attempt}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{essay}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{examplefarm}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{example farm}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{expand}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{expert-subject}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{external links}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fancruft}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fanpov}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fansite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{fiction}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{game guide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{gameguide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{globalize}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{grammar}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{histinfo}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{hoax}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{howto}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{inappropriate person}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{in-universe}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{incomplete}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro length}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intromissing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{introrewrite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro-toolong}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{intro-tooshort}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{cleanup-jargon}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{laundrylists}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead too long}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{lead too short}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{likeresume}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{like resume}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{long}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{newsrelease}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{news release}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{notable}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{onesource}}"));
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{OR}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{orphan}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{peacock}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{plot}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{POV}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{primarysources}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{prose}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{proseline}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{quotefarm}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{recent}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{refimprove}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{restructure}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{review}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{rewrite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{sections}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{self-published}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{spam}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{story}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{synthesis}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{tone}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{tooshort}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{travelguide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{travel guide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{trivia}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unbalanced}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unencyclopedic}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{unreferenced}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{update}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{weasel}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{wikify}}"));
//undated, first letter capital
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Advert}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Autobiography}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Biased}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Blpdispute}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Citations missing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Citationstyle}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Citecheck}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Cleanup}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Colloquial}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Confusing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Context}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Contradict}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Copyedit}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Criticisms}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Crystal}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Deadend}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Disputed}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Do-attempt}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Essay}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Examplefarm}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Expand}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{External links}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Fancruft}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Fanpov}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Fansite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Fiction}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Gameguide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Globalize}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Grammar}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Histinfo}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Hoax}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Howto}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Inappropriate person}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{In-universe}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Incomplete}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Intro length}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Intromissing}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Introrewrite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Intro-toolong}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Intro-tooshort}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Cleanup-jargon}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Laundrylists}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Likeresume}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Likeresume}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Long}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Verylong}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{very long}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Newsrelease}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Notable}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Onesource}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Orphan}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Peacock}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Plot}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Primarysources}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Primary sources}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Prose}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Proseline}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Quotefarm}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Recent}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Refimprove}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Restructure}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Review}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Rewrite}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Sections}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Self-published}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Spam}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Story}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Synthesis}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Tone}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Tooshort}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Travelguide}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Trivia}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Unbalanced}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Unencyclopedic}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Unreferenced}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Update}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Weasel}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Wikify}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Coi}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{BLP unsourced}}"));
Assert.IsTrue(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{BLPunsourced}}"));
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Article issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{Multiple issues|wikify=May 2008|a=b|c=d}}"));
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{WIKIFY}}"));
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{roughtranslation|date = April 2009}}"));
// no support for handling templates with multiple parameters
Assert.IsFalse(WikiRegexes.MultipleIssuesTemplates.IsMatch(@"{{notability|Biographies|date=December 2008}}"));
}
[Test]
public void WordApostropheTests()
{
Assert.IsTrue(WikiRegexes.RegexWordApostrophes.IsMatch(@"Rachel"));
Assert.IsTrue(WikiRegexes.RegexWordApostrophes.IsMatch(@"Rachel's"));
Assert.IsTrue(WikiRegexes.RegexWordApostrophes.IsMatch(@"Rachel’s"), "curly apostrophe");
Assert.IsTrue(WikiRegexes.RegexWordApostrophes.IsMatch(@"Kwakwaka'wakw"));
Assert.AreEqual("", WikiRegexes.RegexWordApostrophes.Replace(@"Kwakwaka'wakw", ""));
}
[Test]
public void DeathsOrLivingCategoryTests()
{
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:653 deaths|Honorius]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:839 deaths]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:5th-century BC deaths]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:1209 deaths]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:Living people]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:221 BC deaths]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:Year of death missing]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:Year of death unknown]]"));
Assert.IsTrue(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:Date of death unknown]]"));
// no matches
Assert.IsFalse(WikiRegexes.DeathsOrLivingCategory.IsMatch(@""));
Assert.IsFalse(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"[[Category:strange deaths]]"));
Assert.IsFalse(WikiRegexes.DeathsOrLivingCategory.IsMatch(@"1990 deaths"));
}
[Test]
public void BirthsCategoryTests()
{
Assert.IsTrue(WikiRegexes.BirthsCategory.IsMatch(@"[[Category:12th-century births]]"));
Assert.IsTrue(WikiRegexes.BirthsCategory.IsMatch(@"[[Category:1299 births]]"));
Assert.IsTrue(WikiRegexes.BirthsCategory.IsMatch(@"[[Category:110 BC births]]"));
Assert.IsTrue(WikiRegexes.BirthsCategory.IsMatch(@"[[Category:1st-century births]]"));
//no matches
Assert.IsFalse(WikiRegexes.BirthsCategory.IsMatch(@"[[Category:strange births]]"));
Assert.IsFalse(WikiRegexes.BirthsCategory.IsMatch(@"1960 births"));
Assert.IsFalse(WikiRegexes.BirthsCategory.IsMatch(@""));
}
[Test]
public void DateBirthAndAgeTests()
{
Assert.IsTrue(WikiRegexes.DateBirthAndAge.IsMatch(@"{{Birth date|1972|02|18}}"));
Assert.IsTrue(WikiRegexes.DateBirthAndAge.IsMatch(@"{{Birth date and age|1972|02|18}}"));
Assert.IsTrue(WikiRegexes.DateBirthAndAge.IsMatch(@"{{Birth date| 1972 |02|18}}"));
Assert.IsTrue(WikiRegexes.DateBirthAndAge.IsMatch(@"{{birth date and age|mf=yes|1980|3|9}}"));
Assert.IsTrue(WikiRegexes.DateBirthAndAge.IsMatch(@"{{bda|mf=yes|1980|3|9}}"));
Assert.AreEqual("1975", WikiRegexes.DateBirthAndAge.Match(@"{{birth-date|1975}}").Groups[1].Value);
Assert.AreEqual("1975", WikiRegexes.DateBirthAndAge.Match(@"{{birth-date| 1975}}").Groups[1].Value);
Assert.AreEqual("1984", WikiRegexes.DateBirthAndAge.Match(@"{{birth date and age|year=1984|month=2|day=6}}").Groups[1].Value);
}
[Test]
public void DateDeathAndAgeTests()
{
Assert.IsTrue(WikiRegexes.DeathDate.IsMatch(@"{{Death date|1972|02|18}}"));
Assert.IsTrue(WikiRegexes.DeathDate.IsMatch(@"{{Death date and age|1972|02|18}}"));
Assert.IsTrue(WikiRegexes.DeathDate.IsMatch(@"{{Death date| 1972 |02|18}}"));
Assert.IsTrue(WikiRegexes.DeathDate.IsMatch(@"{{death date and age|mf=yes|1980|3|9}}"));
Assert.AreEqual("1975", WikiRegexes.DeathDate.Match(@"{{death-date|1975}}").Groups[1].Value);
Assert.AreEqual("1975", WikiRegexes.DeathDate.Match(@"{{death-date| 1975}}").Groups[1].Value);
Assert.AreEqual("1984", WikiRegexes.DeathDate.Match(@"{{death date and age|year=1984|month=2|day=6}}").Groups[1].Value);
Assert.AreEqual("1911", WikiRegexes.DeathDate.Match(@"{{death date and age|1911|12|12|1821|10|02}}").Groups[1].Value);
}
[Test]
public void DeathDateAndAge()
{
Assert.AreEqual("1911", WikiRegexes.DeathDateAndAge.Match(@"{{death date and age|1911|12|12|1821|10|02}}").Groups[1].Value);
Assert.AreEqual("1911", WikiRegexes.DeathDateAndAge.Match(@"{{death-date and age|1911|12|12|1821|10|02}}").Groups[1].Value);
Assert.AreEqual("1911", WikiRegexes.DeathDateAndAge.Match(@"{{dda|1911|12|12|1821|10|02}}").Groups[1].Value);
Assert.AreEqual("1821", WikiRegexes.DeathDateAndAge.Match(@"{{death date and age|1911|12|12|1821|10|02}}").Groups[2].Value);
}
[Test]
public void DeadEndTests()
{
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Deadend}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{deadend}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{dead end}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{deadend|date=May 2008}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Dead end}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{internal links}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{internallinks}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Internal links}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Internal links|date=May 2008}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{nuevointernallinks}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Nuevointernallinks}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{dep}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{dep|date=May 2008|Foobar}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Article issues|deadend=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{articleissues|deadend=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Article issues|dead end=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Multiple issues|deadend=May 2008|a=b|c=d}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{ Article issues|dead end=May 2008|a=b|c=d}}"));
Assert.IsFalse(WikiRegexes.DeadEnd.IsMatch(@"{{deadend|}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Dead end|date={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Multiple issues|dead end={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|a=b}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Multiple issues|orphan=May 2010 | dead end={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|a=b}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Multiple issues|wikify ={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|dead end ={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|orphan ={{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}"));
Assert.IsTrue(WikiRegexes.DeadEnd.IsMatch(@"{{Multiple issues|orphan =August 2010|cleanup =March 2009|COI =April 2009|BLP sources = April 2009|autobiography = {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|wikify = {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}|dead end = {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}}}}"));
Assert.AreEqual(@"{{multiple issues|peacock=September 2010|wikify=September 2010|BLP unsourced = July 2010}}", WikiRegexes.DeadEnd.Replace(@"{{multiple issues|deadend=September 2010|peacock=September 2010|wikify=September 2010|BLP unsourced = July 2010}}", "$1"));
}
[Test]
public void BareExternalLinkTests()
{
Assert.IsTrue(WikiRegexes.BareExternalLink.IsMatch(@"* http://www.site.com
"));
Assert.IsTrue(WikiRegexes.BareExternalLink.IsMatch(@"* http://www.site.com
"));
Assert.IsTrue(WikiRegexes.BareExternalLink.IsMatch(@"* http://www.site.com
"));
Assert.IsTrue(WikiRegexes.BareExternalLink.IsMatch(@"* http://www.site.com/great/a.htm
"));
Assert.IsFalse(WikiRegexes.BareExternalLink.IsMatch(@"* [http://www.site.com text]
"));
Assert.IsFalse(WikiRegexes.BareExternalLink.IsMatch(@"<ref>http://www.site.com</ref>
"));
}
[Test]
public void BareRefExternalLink()
{
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm]</ref>");
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm]]</ref>");
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref>http://news.bbc.co.uk/hi/England/story4384.htm</ref>");
TestMatch(WikiRegexes.BareRefExternalLink, @"< REF > [ http://news.bbc.co.uk/hi/England/story4384.htm]
< / ref >");
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref name=hello>[http://news.bbc.co.uk/hi/England/story4384.htm]</ref>");
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref>[ http://news.bbc.co.uk/hi/England/story4384.htm ] </ref>");
TestMatch(WikiRegexes.BareRefExternalLink, @"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm title here]</ref>", false);
TestMatches(WikiRegexes.BareRefExternalLink, @"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm</ref>", 0); // no matches for unbalanced braces
Assert.AreEqual(WikiRegexes.BareRefExternalLink.Match(@"<ref>[ http://news.bbc.co.uk/hi/England/story4384.htm ] </ref>").Groups[1].Value, @"http://news.bbc.co.uk/hi/England/story4384.htm");
Assert.AreEqual(WikiRegexes.BareRefExternalLink.Match(@"<ref>[ http://news.bbc.co.uk/hi/England/story4384.htm] </ref>").Groups[1].Value, @"http://news.bbc.co.uk/hi/England/story4384.htm");
Assert.AreEqual(WikiRegexes.BareRefExternalLink.Match(@"<ref>[ http://news.bbc.co.uk/hi/England/story4384.htm]. </ref>").Groups[1].Value, @"http://news.bbc.co.uk/hi/England/story4384.htm");
}
[Test]
public void BareRefExternalLinkBotGenTitle()
{
TestMatch(WikiRegexes.BareRefExternalLinkBotGenTitle, @"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm]</ref>");
TestMatch(WikiRegexes.BareRefExternalLinkBotGenTitle, @"<ref>http://news.bbc.co.uk/hi/England/story4384.htm</ref>");
TestMatch(WikiRegexes.BareRefExternalLinkBotGenTitle, @"<ref>[http://www.independent.co.uk/news/people/bo-johnson-30403.html Boris Johnson: People - The Independent<!-- Bot generated title -->]</ref>");
TestMatch(WikiRegexes.BareRefExternalLinkBotGenTitle, @"<ref>Smith, Fred [http://www.independent.co.uk/news/people/bo-johnson-30403.html Boris Johnson: People - The Independent<!-- Bot generated title -->]</ref>", false);
TestMatch(WikiRegexes.BareRefExternalLinkBotGenTitle, @"<ref>[http://www.independent.co.uk/news/people/bo-johnson-30403.html Boris Johnson: People - The Independent]</ref>", false);
Assert.IsTrue(WikiRegexes.BareRefExternalLinkBotGenTitle.IsMatch(@"attack<ref>http://www.news.com.au/heraldsun/story/0,21985,23169580-5006022,00.html</ref> was portrayed"));
Assert.AreEqual(@"http://news.bbc.co.uk/hi/England/story4384.htm", WikiRegexes.BareRefExternalLinkBotGenTitle.Match(@"<ref>[http://news.bbc.co.uk/hi/England/story4384.htm]</ref>").Groups[1].Value);
Assert.AreEqual(@"http://news.bbc.co.uk/hi/England/story4384.htm", WikiRegexes.BareRefExternalLinkBotGenTitle.Match(@"<ref> [ http://news.bbc.co.uk/hi/England/story4384.htm]. </ref>").Groups[1].Value);
Assert.AreEqual(@"Foo", WikiRegexes.BareRefExternalLinkBotGenTitle.Match(@"<ref> [ http://news.bbc.co.uk/hi/England/story4384.htm Foo<!--bot generated title-->]. </ref>").Groups[2].Value);
}
[Test]
public void BoldItalicTests()
{
Assert.AreEqual(WikiRegexes.Bold.Match(@"'''foo'''").Groups[1].Value, @"foo");
Assert.AreEqual(WikiRegexes.Bold.Match(@"'''foo bar'''").Groups[1].Value, @"foo bar");
Assert.AreEqual(WikiRegexes.Bold.Match(@"'''foo's bar'''").Groups[1].Value, @"foo's bar");
Assert.AreEqual(WikiRegexes.Bold.Match(@"'''''foo's bar'''''").Groups[1].Value, "", "no match on bold italics");
Assert.AreEqual(WikiRegexes.Italics.Match(@"''foo''").Groups[1].Value, @"foo");
Assert.AreEqual(WikiRegexes.Italics.Match(@"''foo bar''").Groups[1].Value, @"foo bar");
Assert.AreEqual(WikiRegexes.Italics.Match(@"''foo's bar''").Groups[1].Value, @"foo's bar");
Assert.AreEqual(WikiRegexes.Italics.Match(@"'''foo's bar'''").Groups[1].Value, "", "no match on bold");
Assert.AreEqual(WikiRegexes.Italics.Match(@"'''''foo's bar'''''").Groups[1].Value, "", "no match on bold italics");
Assert.AreEqual(WikiRegexes.Italics.Match(@"'''Tyrone Station''' is an by Amtrak's ''[[foo]]'', which").Groups[1].Value, "[[foo]]");
Assert.AreEqual(WikiRegexes.BoldItalics.Match(@"''''' foo'''''").Groups[1].Value, @" foo");
Assert.AreEqual(WikiRegexes.BoldItalics.Match(@"'''''foo bar'''''").Groups[1].Value, @"foo bar");
Assert.AreEqual(WikiRegexes.BoldItalics.Match(@"'''''foo's bar'''''").Groups[1].Value, @"foo's bar");
Assert.AreEqual(WikiRegexes.Italics.Match(@"''f''").Groups[1].Value, @"f");
Assert.AreEqual(WikiRegexes.Italics.Match(@"''f'' nar ''abc''").Groups[1].Value, @"f");
Assert.AreEqual(WikiRegexes.Bold.Match(@"'''f''' nar '''abc'''").Groups[1].Value, @"f");
Assert.IsFalse(WikiRegexes.Italics.IsMatch(@"'''foo'''"));
Assert.IsFalse(WikiRegexes.Italics.IsMatch(@"'''''foo'''''"));
Assert.IsFalse(WikiRegexes.Bold.IsMatch(@"''foo'''"));
Assert.IsFalse(WikiRegexes.Bold.IsMatch(@"''foo''"));
Assert.IsFalse(WikiRegexes.BoldItalics.IsMatch(@"''foo''"));
Assert.IsFalse(WikiRegexes.BoldItalics.IsMatch(@"'''foo'''"));
Assert.IsFalse(WikiRegexes.BoldItalics.IsMatch(@"'''''foo''"));
}
[Test]
public void StarRowsTests()
{
Assert.AreEqual(WikiRegexes.StarRows.Match(@"*foo bar
Bert").Groups[1].Value, @"*");
Assert.AreEqual(WikiRegexes.StarRows.Match(@"*foo bar
Bert").Groups[2].Value, "foo bar\r");
Assert.AreEqual(WikiRegexes.StarRows.Match(@" *foo bar").Groups[1].Value, @"*");
Assert.AreEqual(WikiRegexes.StarRows.Match(@" *foo bar").Groups[2].Value, @"foo bar");
}
[Test]
public void CircaTemplate()
{
Assert.IsTrue(WikiRegexes.CircaTemplate.IsMatch(@"{{circa}}"));
Assert.IsTrue(WikiRegexes.CircaTemplate.IsMatch(@"{{ circa}}"));
Assert.IsTrue(WikiRegexes.CircaTemplate.IsMatch(@"{{Circa}}"));
Assert.IsTrue(WikiRegexes.CircaTemplate.IsMatch(@"{{circa|foo=yes}}"));
}
[Test]
public void ReferenceList()
{
Assert.IsTrue(WikiRegexes.ReferenceList.IsMatch(@"{{reflist}}"));
Assert.IsTrue(WikiRegexes.ReferenceList.IsMatch(@"{{references-small}}"));
Assert.IsTrue(WikiRegexes.ReferenceList.IsMatch(@"{{references-2column}}"));
}
}
}
| gpl-2.0 |
xylusthemes/import-facebook-events | includes/class-import-facebook-events-admin.php | 16805 | <?php
/**
* The admin-specific functionality of the plugin.
*
* @package Import_Facebook_Events
* @subpackage Import_Facebook_Events/admin
* @copyright Copyright (c) 2016, Dharmesh Patel
* @since 1.0.0
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The admin-specific functionality of the plugin.
*
* @package Import_Facebook_Events
* @subpackage Import_Facebook_Events/admin
* @author Dharmesh Patel <[email protected]>
*/
class Import_Facebook_Events_Admin {
/**
* $adminpage_url
*
* @var string
*/
public $adminpage_url;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
*/
public function __construct() {
$this->adminpage_url = admin_url( 'admin.php?page=facebook_import' );
add_action( 'init', array( $this, 'register_scheduled_import_cpt' ) );
add_action( 'init', array( $this, 'register_history_cpt' ) );
add_action( 'admin_menu', array( $this, 'add_menu_pages' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
add_action( 'admin_notices', array( $this, 'display_notices' ) );
add_filter( 'admin_footer_text', array( $this, 'add_import_facebook_events_credit' ) );
add_action( 'admin_action_ife_view_import_history', array( $this, 'ife_view_import_history_handler' ) );
}
/**
* Create the Admin menu and submenu and assign their links to global varibles.
*
* @since 1.0
* @return void
*/
public function add_menu_pages() {
add_menu_page( __( 'Import Facebook Events', 'import-facebook-events' ), __( 'Facebook Import', 'import-facebook-events' ), 'manage_options', 'facebook_import', array( $this, 'admin_page' ), 'dashicons-calendar-alt', '30' );
}
/**
* Load Admin Scripts
*
* Enqueues the required admin scripts.
*
* @since 1.0
* @param string $hook Page hook.
* @return void
*/
public function enqueue_admin_scripts( $hook ) {
$js_dir = IFE_PLUGIN_URL . 'assets/js/';
wp_register_script( 'import-facebook-events', $js_dir . 'import-facebook-events-admin.js', array( 'jquery', 'jquery-ui-core', 'jquery-ui-datepicker', 'wp-color-picker' ), IFE_VERSION, true );
$params = array(
'ajax_nonce' => wp_create_nonce( 'ife_admin_js_nonce' ),
);
wp_localize_script( 'import-facebook-events', 'ife_ajax', $params );
wp_enqueue_script( 'import-facebook-events' );
}
/**
* Load Admin Styles.
*
* Enqueues the required admin styles.
*
* @since 1.0
* @param string $hook Page hook.
* @return void
*/
public function enqueue_admin_styles( $hook ) {
global $pagenow;
$current_screen = get_current_screen();
if ( 'toplevel_page_facebook_import' === $current_screen->id || 'widgets.php' === $pagenow || 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
$css_dir = IFE_PLUGIN_URL . 'assets/css/';
wp_enqueue_style( 'jquery-ui', $css_dir . 'jquery-ui.css', false, '1.12.0' );
wp_enqueue_style( 'import-facebook-events', $css_dir . 'import-facebook-events-admin.css', false, IFE_VERSION );
wp_enqueue_style( 'wp-color-picker' );
}
}
/**
* Load Admin page.
*
* @since 1.0
* @return void
*/
public function admin_page() {
?>
<div class="wrap">
<h2><?php esc_html_e( 'Import Facebook Events', 'import-facebook-events' ); ?></h2>
<?php
// Set Default Tab to Import.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'facebook'; // input var okay.
?>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="postbox-container-1" class="postbox-container">
<?php
if ( ! ife_is_pro() ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/admin-sidebar.php';
}
?>
</div>
<div id="postbox-container-2" class="postbox-container">
<h1 class="nav-tab-wrapper">
<a href="<?php echo esc_url( add_query_arg( 'tab', 'facebook', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'facebook' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Import', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'ics', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'ics' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Facebook .ics Import', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'scheduled', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'scheduled' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Scheduled Imports', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'history', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'history' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Import History', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'settings', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'settings' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Settings', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'shortcodes', $this->adminpage_url ) ); ?>" class="nav-tab <?php if ( 'shortcodes' == $tab) { echo 'nav-tab-active'; } ?>">
<?php esc_html_e( 'Shortcodes', 'import-facebook-events' ); ?>
</a>
<a href="<?php echo esc_url( add_query_arg( 'tab', 'support', $this->adminpage_url ) ); ?>" class="nav-tab <?php echo ( ( 'support' === $tab ) ? 'nav-tab-active' : '' ); ?>">
<?php esc_html_e( 'Support & Help', 'import-facebook-events' ); ?>
</a>
</h1>
<div class="import-facebook-events-page">
<?php
if ( 'facebook' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/facebook-import-events.php';
} elseif ( 'ics' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/ical-import-events.php';
} elseif ( 'settings' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/import-facebook-events-settings.php';
} elseif ( 'scheduled' === $tab ) {
if ( ife_is_pro() ) {
require_once IFEPRO_PLUGIN_DIR . '/templates/admin/scheduled-import-events.php';
} else {
do_action( 'ife_render_pro_notice' );
}
} elseif ( 'history' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/import-facebook-events-history.php';
} elseif ( 'support' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/import-facebook-events-support.php';
}elseif ( 'shortcodes' === $tab ) {
require_once IFE_PLUGIN_DIR . '/templates/admin/import-facebook-events-shortcode.php';
}
?>
<div style="clear: both"></div>
</div>
</div>
</div>
</div>
<?php
}
/**
* Display notices in admin.
*
* @since 1.0.0
*/
public function display_notices() {
global $ife_errors, $ife_success_msg, $ife_warnings, $ife_info_msg;
if ( ! empty( $ife_errors ) ) {
foreach ( $ife_errors as $error ) :
?>
<div class="notice notice-error is-dismissible">
<p><?php echo wp_kses_post( $error ); ?></p>
</div>
<?php
endforeach;
}
if ( ! empty( $ife_success_msg ) ) {
foreach ( $ife_success_msg as $success ) :
?>
<div class="notice notice-success is-dismissible">
<p><?php echo wp_kses_post( $success ); ?></p>
</div>
<?php
endforeach;
}
if ( ! empty( $ife_warnings ) ) {
foreach ( $ife_warnings as $warning ) :
?>
<div class="notice notice-warning is-dismissible">
<p><?php echo wp_kses_post( $warning ); ?></p>
</div>
<?php
endforeach;
}
if ( ! empty( $ife_info_msg ) ) {
foreach ( $ife_info_msg as $info ) :
?>
<div class="notice notice-info is-dismissible">
<p><?php echo wp_kses_post( $info ); ?></p>
</div>
<?php
endforeach;
}
}
/**
* Register custom post type for scheduled imports.
*
* @since 1.0.0
*/
public function register_scheduled_import_cpt() {
$labels = array(
'name' => _x( 'Scheduled Import', 'post type general name', 'import-facebook-events' ),
'singular_name' => _x( 'Scheduled Import', 'post type singular name', 'import-facebook-events' ),
'menu_name' => _x( 'Scheduled Imports', 'admin menu', 'import-facebook-events' ),
'name_admin_bar' => _x( 'Scheduled Import', 'add new on admin bar', 'import-facebook-events' ),
'add_new' => _x( 'Add New', 'book', 'import-facebook-events' ),
'add_new_item' => __( 'Add New Import', 'import-facebook-events' ),
'new_item' => __( 'New Import', 'import-facebook-events' ),
'edit_item' => __( 'Edit Import', 'import-facebook-events' ),
'view_item' => __( 'View Import', 'import-facebook-events' ),
'all_items' => __( 'All Scheduled Imports', 'import-facebook-events' ),
'search_items' => __( 'Search Scheduled Imports', 'import-facebook-events' ),
'parent_item_colon' => __( 'Parent Imports:', 'import-facebook-events' ),
'not_found' => __( 'No Imports found.', 'import-facebook-events' ),
'not_found_in_trash' => __( 'No Imports found in Trash.', 'import-facebook-events' ),
);
$args = array(
'labels' => $labels,
'description' => __( 'Scheduled Imports.', 'import-facebook-events' ),
'public' => false,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'show_in_admin_bar' => false,
'show_in_nav_menus' => false,
'can_export' => false,
'rewrite' => false,
'capability_type' => 'page',
'has_archive' => false,
'hierarchical' => false,
'supports' => array( 'title' ),
'menu_position' => 5,
);
register_post_type( 'fb_scheduled_imports', $args );
}
/**
* Register custom post type for Save import history.
*
* @since 1.0.0
*/
public function register_history_cpt() {
$labels = array(
'name' => _x( 'Import History', 'post type general name', 'import-facebook-events' ),
'singular_name' => _x( 'Import History', 'post type singular name', 'import-facebook-events' ),
'menu_name' => _x( 'Import History', 'admin menu', 'import-facebook-events' ),
'name_admin_bar' => _x( 'Import History', 'add new on admin bar', 'import-facebook-events' ),
'add_new' => _x( 'Add New', 'book', 'import-facebook-events' ),
'add_new_item' => __( 'Add New', 'import-facebook-events' ),
'new_item' => __( 'New History', 'import-facebook-events' ),
'edit_item' => __( 'Edit History', 'import-facebook-events' ),
'view_item' => __( 'View History', 'import-facebook-events' ),
'all_items' => __( 'All Import History', 'import-facebook-events' ),
'search_items' => __( 'Search History', 'import-facebook-events' ),
'parent_item_colon' => __( 'Parent History:', 'import-facebook-events' ),
'not_found' => __( 'No History found.', 'import-facebook-events' ),
'not_found_in_trash' => __( 'No History found in Trash.', 'import-facebook-events' ),
);
$args = array(
'labels' => $labels,
'description' => __( 'Import History', 'import-facebook-events' ),
'public' => false,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'show_in_admin_bar' => false,
'show_in_nav_menus' => false,
'can_export' => false,
'rewrite' => false,
'capability_type' => 'page',
'has_archive' => false,
'hierarchical' => false,
'supports' => array( 'title' ),
'menu_position' => 5,
);
register_post_type( 'ife_import_history', $args );
}
/**
* Add Import Facebook Events ratting text
*
* @since 1.0
* @param string $footer_text Current footer text.
* @return string
*/
public function add_import_facebook_events_credit( $footer_text ) {
$current_screen = get_current_screen();
if ( 'toplevel_page_facebook_import' === $current_screen->id ) {
$rate_url = 'https://wordpress.org/support/plugin/import-facebook-events/reviews/?rate=5#new-post';
$footer_text .= sprintf(
// translators: %1$s, %2$s and %3$s are html tags.
esc_html__( ' Rate %1$sImport Facebook Events%2$s %3$s', 'import-facebook-events' ),
'<strong>',
'</strong>',
'<a href="' . $rate_url . '" target="_blank">★★★★★</a>'
);
}
return $footer_text;
}
/**
* Get Plugin array
*
* @since 1.1.0
* @return array
*/
public function get_xyuls_themes_plugins() {
return array(
'wp-event-aggregator' => esc_html__( 'WP Event Aggregator', 'import-facebook-events' ),
'import-eventbrite-events' => esc_html__( 'Import Eventbrite Events', 'import-facebook-events' ),
'import-meetup-events' => esc_html__( 'Import Meetup Events', 'import-facebook-events' ),
'wp-bulk-delete' => esc_html__( 'WP Bulk Delete', 'import-facebook-events' ),
'event-schema' => esc_html__( 'Event Schema / Structured Data', 'import-facebook-events' ),
);
}
/**
* Get Plugin Details.
*
* @since 1.1.0
* @param string $slug Slug of plugin on wp.org.
* @return array
*/
public function get_wporg_plugin( $slug ) {
if ( empty( $slug ) ) {
return false;
}
$transient_name = 'support_plugin_box' . $slug;
$plugin_data = get_transient( $transient_name );
if ( false === $plugin_data ) {
if ( ! function_exists( 'plugins_api' ) ) {
include_once ABSPATH . '/wp-admin/includes/plugin-install.php';
}
$plugin_data = plugins_api(
'plugin_information',
array(
'slug' => $slug,
'is_ssl' => is_ssl(),
'fields' => array(
'banners' => true,
'active_installs' => true,
),
)
);
if ( ! is_wp_error( $plugin_data ) ) {
set_transient( $transient_name, $plugin_data, 24 * HOUR_IN_SECONDS );
} else {
// If there was a bug on the Current Request just leave.
return false;
}
}
return $plugin_data;
}
/**
* Render imported Events in history Page.
*
* @return void
*/
public function ife_view_import_history_handler() {
define( 'IFRAME_REQUEST', true );
iframe_header();
$history_id = isset( $_GET['history'] ) ? absint( $_GET['history'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( $history_id > 0 ) {
$imported_data = get_post_meta( $history_id, 'imported_data', true );
if ( ! empty( $imported_data ) ) {
?>
<table class="widefat fixed striped">
<thead>
<tr>
<th id="title" class="column-title column-primary"><?php esc_html_e( 'Event', 'import-facebook-events' ); ?></th>
<th id="action" class="column-operation"><?php esc_html_e( 'Created/Updated', 'import-facebook-events' ); ?></th>
<th id="action" class="column-date"><?php esc_html_e( 'Action', 'import-facebook-events' ); ?></th>
</tr>
</thead>
<tbody id="the-list">
<?php
foreach ( $imported_data as $event ) {
?>
<tr>
<td class="title column-title">
<?php
printf(
'<a href="%1$s" target="_blank">%2$s</a>',
esc_url( get_the_permalink( absint( $event['id'] ) ) ),
esc_attr( get_the_title( absint( $event['id'] ) ) )
);
?>
</td>
<td class="title column-title">
<?php echo esc_attr( ucfirst( $event['status'] ) ); ?>
</td>
<td class="title column-action">
<?php
printf(
'<a href="%1$s" target="_blank">%2$s</a>',
esc_url( get_edit_post_link( absint( $event['id'] ) ) ),
esc_attr__( 'Edit', 'import-facebook-events' )
);
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
} else {
?>
<div class="ife_no_import_events">
<?php esc_html_e( 'No data found', 'import-facebook-events' ); ?>
</div>
<?php
}
} else {
?>
<div class="ife_no_import_events">
<?php esc_html_e( 'No data found', 'import-facebook-events' ); ?>
</div>
<?php
}
?>
<style>
.ife_no_import_events{
text-align: center;
margin-top: 60px;
font-size: 1.4em;
}
</style>
<?php
iframe_footer();
exit;
}
}
| gpl-2.0 |
leoloso/PoP | layers/Legacy/Schema/packages/migrate-everythingelse/migrate/plugins/pop-automatedemails/library/automatedemails/automatedemails-operator.php | 2732 | <?php
use PoP\ComponentModel\State\ApplicationState;
use PoPCMSSchema\Users\Facades\UserTypeAPIFacade;
class PoP_AutomatedEmails_Operator
{
public function __construct()
{
\PoP\Root\App::addAction(
'shutdown', // This is a WP hook, must migrate to a PoP one
array($this, 'maybeSendAutomatedemail')
);
}
public function maybeSendAutomatedemail()
{
global $pop_automatedemails_manager;
$userTypeAPI = UserTypeAPIFacade::getInstance();
if (\PoP\Root\App::getState(['routing', 'is-generic'])) {
$route = \PoP\Root\App::getState('route');
if ($automatedemails = $pop_automatedemails_manager->getAutomatedEmails($route)) {
foreach ($automatedemails as $automatedemail) {
// Allow to change the header to 'newsletter' under PoPTheme Wassup
$header = \PoP\Root\App::applyFilters(
'PoP_AutomatedEmails_Operator:automatedemail:header',
null
);
foreach ($automatedemail->getEmails() as $email) {
$users = $email['users'] ?? array();
$recipients = $email['recipients'] ?? array();
if ($users || $recipients) {
$useremails = $names = array();
foreach ($users as $user_id) {
$useremails[] = $userTypeAPI->getUserEmail($user_id);
$names[] = $userTypeAPI->getUserDisplayName($user_id);
}
// Allow Gravity Forms to already send a list of useremails and names
foreach ($recipients as $recipient) {
$useremails[] = $recipient['email'];
$names[] = $recipient['name'];
}
// // Comment Leo: descomentar acá
// echo PHP_EOL.PHP_EOL;
// echo 'USERS: '.implode(',', $names).PHP_EOL;
// echo 'EMAILS: '.implode(',', $useremails).PHP_EOL;
// echo 'CONTENT: '.PHP_EOL;
// echo $email['content'];
// echo PHP_EOL;
PoP_EmailSender_Utils::sendemailToUsers($useremails, $names, $email['subject'], $email['content'], true, $header, $email['frame']);
}
}
}
}
}
}
}
/**
* Initialize
*/
new PoP_AutomatedEmails_Operator();
| gpl-2.0 |
Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Nikon/ColorHue.php | 733 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Nikon;
use PHPExiftool\Driver\AbstractTag;
class ColorHue extends AbstractTag
{
protected $Id = 141;
protected $Name = 'ColorHue';
protected $FullName = 'Nikon::Main';
protected $GroupName = 'Nikon';
protected $g0 = 'MakerNotes';
protected $g1 = 'Nikon';
protected $g2 = 'Camera';
protected $Type = 'string';
protected $Writable = true;
protected $Description = 'Color Hue';
protected $flag_Permanent = true;
}
| gpl-2.0 |
camposer/curso_spring-integration | TicketInt/src/main/java/es/indra/formacion/springint/tms/channel/TicketPrioridadAltaChannel.java | 822 | package es.indra.formacion.springint.tms.channel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.Message;
import org.springframework.integration.MessagingException;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageHandler;
import org.springframework.stereotype.Component;
@Component
public class TicketPrioridadAltaChannel implements MessageHandler {
private DirectChannel canal;
@Value("#{ticketPrioridadAlta}")
public void setCanal(DirectChannel canal) {
this.canal = canal;
}
public void suscribir() {
canal.subscribe(this);
}
@Override
public void handleMessage(Message<?> msg) throws MessagingException {
System.out.println("TicketPrioridadAltaChannel: " + msg.getPayload());
}
}
| gpl-2.0 |
cuong09m/krwe | emailmarketer/admin/com/upgrades/nx/list_subscribers_drop_lastresponderid.php | 1115 | <?php
/**
* This file is part of the upgrade process.
*
* @package SendStudio
*/
/**
* Do a sanity check to make sure the upgrade api has been included.
*/
if (!class_exists('Upgrade_API', false)) {
exit();
}
/**
* This class runs one change for the upgrade process.
* The Upgrade_API looks for a RunUpgrade method to call.
* That should return false for failure
* It should return true for success or if the change has already been made.
*
* @package SendStudio
*/
class list_subscribers_drop_lastresponderid extends Upgrade_API
{
/**
* RunUpgrade
* Runs the query for the upgrade process
* and returns the result from the query.
* The calling function looks for a true or false result
*
* @return Mixed Returns true if the condition is already met (eg the column already exists).
* Returns false if the database query can't be run.
* Returns the resource from the query (which is then checked to be true).
*/
function RunUpgrade()
{
$query = 'alter table ' . SENDSTUDIO_TABLEPREFIX . 'list_subscribers drop column LastResponderID';
$result = $this->Db->Query($query);
return $result;
}
}
| gpl-2.0 |
muravjov/bombono-dvd | libs/boost-lib/libs/filesystem/v3/src/operations.cpp | 58503 | // operations.cpp --------------------------------------------------------------------//
// Copyright 2002-2009 Beman Dawes
// Copyright 2001 Dietmar Kuehl
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See library home page at http://www.boost.org/libs/filesystem
//--------------------------------------------------------------------------------------//
#include <boost/config.hpp>
#if !defined( BOOST_NO_STD_WSTRING )
// Boost.Filesystem V3 and later requires std::wstring support.
// During the transition to V3, libraries are compiled with both V2 and V3 sources.
// On old compilers that don't support V3 anyhow, we just skip everything so the compile
// will succeed and the library can be built.
// define BOOST_FILESYSTEM_SOURCE so that <boost/filesystem/config.hpp> knows
// the library is being built (possibly exporting rather than importing code)
#define BOOST_FILESYSTEM_SOURCE
#ifndef BOOST_SYSTEM_NO_DEPRECATED
# define BOOST_SYSTEM_NO_DEPRECATED
#endif
#ifndef _POSIX_PTHREAD_SEMANTICS
# define _POSIX_PTHREAD_SEMANTICS // Sun readdir_r()needs this
#endif
#if !(defined(__HP_aCC) && defined(_ILP32) && \
!defined(_STATVFS_ACPP_PROBLEMS_FIXED))
#define _FILE_OFFSET_BITS 64 // at worst, these defines may have no effect,
#endif
#define __USE_FILE_OFFSET64 // but that is harmless on Windows and on POSIX
// 64-bit systems or on 32-bit systems which don't have files larger
// than can be represented by a traditional POSIX/UNIX off_t type.
// OTOH, defining them should kick in 64-bit off_t's (and thus
// st_size)on 32-bit systems that provide the Large File
// Support (LFS)interface, such as Linux, Solaris, and IRIX.
// The defines are given before any headers are included to
// ensure that they are available to all included headers.
// That is required at least on Solaris, and possibly on other
// systems as well.
#include <boost/filesystem/v3/operations.hpp>
#include <boost/scoped_array.hpp>
#include <boost/detail/workaround.hpp>
#include <cstdlib> // for malloc, free
#ifdef BOOST_FILEYSTEM_INCLUDE_IOSTREAM
# include <iostream>
#endif
namespace fs = boost::filesystem3;
using boost::filesystem3::path;
using boost::filesystem3::filesystem_error;
using boost::system::error_code;
using boost::system::error_category;
using boost::system::system_category;
using std::string;
using std::wstring;
# ifdef BOOST_POSIX_API
# include <sys/types.h>
# if !defined(__APPLE__) && !defined(__OpenBSD__)
# include <sys/statvfs.h>
# define BOOST_STATVFS statvfs
# define BOOST_STATVFS_F_FRSIZE vfs.f_frsize
# else
# ifdef __OpenBSD__
# include <sys/param.h>
# endif
# include <sys/mount.h>
# define BOOST_STATVFS statfs
# define BOOST_STATVFS_F_FRSIZE static_cast<boost::uintmax_t>(vfs.f_bsize)
# endif
# include <dirent.h>
# include <unistd.h>
# include <fcntl.h>
# include <utime.h>
# include "limits.h"
# else // BOOST_WINDOW_API
# if (defined(__MINGW32__) || defined(__CYGWIN__)) && !defined(WINVER)
// Versions of MinGW or Cygwin that support Filesystem V3 support at least WINVER 0x501.
// See MinGW's windef.h
# define WINVER 0x501
# endif
# include <windows.h>
# include <winnt.h>
# if !defined(_WIN32_WINNT)
# define _WIN32_WINNT 0x0500
# endif
# if defined(__BORLANDC__) || defined(__MWERKS__)
# if defined(__BORLANDC__)
using std::time_t;
# endif
# include <utime.h>
# else
# include <sys/utime.h>
# endif
// REPARSE_DATA_BUFFER related definitions are found in ntifs.h, which is part of the
// Windows Device Driver Kit. Since that's inconvenient, the definitions are provided
// here. See http://msdn.microsoft.com/en-us/library/ms791514.aspx
#if !defined(REPARSE_DATA_BUFFER_HEADER_SIZE) // mingw winnt.h does provide the defs
#define SYMLINK_FLAG_RELATIVE 1
typedef struct _REPARSE_DATA_BUFFER {
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union {
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags;
WCHAR PathBuffer[1];
/* Example of distinction between substitute and print names:
mklink /d ldrive c:\
SubstituteName: c:\\??\
PrintName: c:\
*/
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
#define REPARSE_DATA_BUFFER_HEADER_SIZE \
FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer)
#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )
#endif
# endif
// BOOST_FILESYSTEM_STATUS_CACHE enables file_status cache in
// dir_itr_increment. The config tests are placed here because some of the
// macros being tested come from dirent.h.
//
// TODO: find out what macros indicate dirent::d_type present in more libraries
# if defined(BOOST_WINDOWS_API)\
|| defined(_DIRENT_HAVE_D_TYPE)// defined by GNU C library if d_type present
# define BOOST_FILESYSTEM_STATUS_CACHE
# endif
#include <sys/stat.h> // even on Windows some functions use stat()
#include <string>
#include <cstring>
#include <cstdio> // for remove, rename
#include <cerrno>
#include <cassert>
// #include <iostream> // for debugging only; comment out when not in use
// POSIX/Windows macros ----------------------------------------------------//
// Portions of the POSIX and Windows API's are very similar, except for name,
// order of arguments, and meaning of zero/non-zero returns. The macros below
// abstract away those differences. They follow Windows naming and order of
// arguments, and return true to indicate no error occurred. [POSIX naming,
// order of arguments, and meaning of return were followed initially, but
// found to be less clear and cause more coding errors.]
# if defined(BOOST_POSIX_API)
// POSIX uses a 0 return to indicate success
# define BOOST_ERRNO errno
# define BOOST_SET_CURRENT_DIRECTORY(P)(::chdir(P)== 0)
# define BOOST_CREATE_DIRECTORY(P)(::mkdir(P, S_IRWXU|S_IRWXG|S_IRWXO)== 0)
# define BOOST_CREATE_HARD_LINK(F,T)(::link(T, F)== 0)
# define BOOST_CREATE_SYMBOLIC_LINK(F,T,Flag)(::symlink(T, F)== 0)
# define BOOST_REMOVE_DIRECTORY(P)(::rmdir(P)== 0)
# define BOOST_DELETE_FILE(P)(::unlink(P)== 0)
# define BOOST_COPY_DIRECTORY(F,T)(!(::stat(from.c_str(), &from_stat)!= 0\
|| ::mkdir(to.c_str(),from_stat.st_mode)!= 0))
# define BOOST_COPY_FILE(F,T,FailIfExistsBool)copy_file_api(F, T, FailIfExistsBool)
# define BOOST_MOVE_FILE(OLD,NEW)(::rename(OLD, NEW)== 0)
# define BOOST_RESIZE_FILE(P,SZ)(::truncate(P, SZ)== 0)
# define BOOST_ERROR_NOT_SUPPORTED ENOSYS
# define BOOST_ERROR_ALREADY_EXISTS EEXIST
# else // BOOST_WINDOWS_API
// Windows uses a non-0 return to indicate success
# define BOOST_ERRNO ::GetLastError()
# define BOOST_SET_CURRENT_DIRECTORY(P)(::SetCurrentDirectoryW(P)!= 0)
# define BOOST_CREATE_DIRECTORY(P)(::CreateDirectoryW(P, 0)!= 0)
# define BOOST_CREATE_HARD_LINK(F,T)(create_hard_link_api(F, T, 0)!= 0)
# define BOOST_CREATE_SYMBOLIC_LINK(F,T,Flag)(create_symbolic_link_api(F, T, Flag)!= 0)
# define BOOST_REMOVE_DIRECTORY(P)(::RemoveDirectoryW(P)!= 0)
# define BOOST_DELETE_FILE(P)(::DeleteFileW(P)!= 0)
# define BOOST_COPY_DIRECTORY(F,T)(::CreateDirectoryExW(F, T, 0)!= 0)
# define BOOST_COPY_FILE(F,T,FailIfExistsBool)(::CopyFileW(F, T, FailIfExistsBool)!= 0)
# define BOOST_MOVE_FILE(OLD,NEW)(::MoveFileExW(OLD, NEW, MOVEFILE_REPLACE_EXISTING)!= 0)
# define BOOST_RESIZE_FILE(P,SZ)(resize_file_api(P, SZ)!= 0)
# define BOOST_READ_SYMLINK(P,T)
# define BOOST_ERROR_ALREADY_EXISTS ERROR_ALREADY_EXISTS
# define BOOST_ERROR_NOT_SUPPORTED ERROR_NOT_SUPPORTED
# endif
//--------------------------------------------------------------------------------------//
// //
// helpers (all operating systems) //
// //
//--------------------------------------------------------------------------------------//
namespace
{
# ifdef BOOST_POSIX_API
const char dot = '.';
# else
const wchar_t dot = L'.';
# endif
boost::filesystem3::directory_iterator end_dir_itr;
const std::size_t buf_size(128);
const error_code ok;
bool error(bool was_error, error_code* ec, const string& message)
{
if (!was_error)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
error_code(BOOST_ERRNO, system_category())));
else
ec->assign(BOOST_ERRNO, system_category());
}
return was_error;
}
bool error(bool was_error, const path& p, error_code* ec, const string& message)
{
if (!was_error)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
p, error_code(BOOST_ERRNO, system_category())));
else
ec->assign(BOOST_ERRNO, system_category());
}
return was_error;
}
bool error(bool was_error, const path& p1, const path& p2, error_code* ec,
const string& message)
{
if (!was_error)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message,
p1, p2, error_code(BOOST_ERRNO, system_category())));
else
ec->assign(BOOST_ERRNO, system_category());
}
return was_error;
}
bool error(bool was_error, const error_code& result,
const path& p, error_code* ec, const string& message)
// Overwrites ec if there has already been an error
{
if (!was_error)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message, p, result));
else
*ec = result;
}
return was_error;
}
bool error(bool was_error, const error_code& result,
const path& p1, const path& p2, error_code* ec, const string& message)
// Overwrites ec if there has already been an error
{
if (!was_error)
{
if (ec != 0) ec->clear();
}
else
{ // error
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(message, p1, p2, result));
else
*ec = result;
}
return was_error;
}
bool is_empty_directory(const path& p)
{
return fs::directory_iterator(p)== end_dir_itr;
}
bool remove_directory(const path& p) // true if succeeds
{ return BOOST_REMOVE_DIRECTORY(p.c_str()); }
bool remove_file(const path& p) // true if succeeds
{ return BOOST_DELETE_FILE(p.c_str()); }
// called by remove and remove_all_aux
bool remove_file_or_directory(const path& p, fs::file_status sym_stat, error_code* ec)
// return true if file removed, false if not removed
{
if (sym_stat.type()== fs::file_not_found)
{
if (ec != 0) ec->clear();
return false;
}
if (fs::is_directory(sym_stat))
{
if (error(!remove_directory(p), p, ec, "boost::filesystem::remove"))
return false;
}
else
{
if (error(!remove_file(p), p, ec, "boost::filesystem::remove"))
return false;
}
return true;
}
boost::uintmax_t remove_all_aux(const path& p, fs::file_status sym_stat,
error_code* ec)
{
boost::uintmax_t count = 1;
if (!fs::is_symlink(sym_stat)// don't recurse symbolic links
&& fs::is_directory(sym_stat))
{
for (fs::directory_iterator itr(p);
itr != end_dir_itr; ++itr)
{
fs::file_status tmp_sym_stat = fs::symlink_status(itr->path(), *ec);
if (ec != 0 && ec)
return count;
count += remove_all_aux(itr->path(), tmp_sym_stat, ec);
}
}
remove_file_or_directory(p, sym_stat, ec);
return count;
}
#ifdef BOOST_POSIX_API
//--------------------------------------------------------------------------------------//
// //
// POSIX-specific helpers //
// //
//--------------------------------------------------------------------------------------//
bool not_found_error(int errval)
{
return errno == ENOENT || errno == ENOTDIR;
}
bool // true if ok
copy_file_api(const std::string& from_p,
const std::string& to_p, bool fail_if_exists)
{
const std::size_t buf_sz = 32768;
boost::scoped_array<char> buf(new char [buf_sz]);
int infile=-1, outfile=-1; // -1 means not open
// bug fixed: code previously did a stat()on the from_file first, but that
// introduced a gratuitous race condition; the stat()is now done after the open()
if ((infile = ::open(from_p.c_str(), O_RDONLY))< 0)
{ return false; }
struct stat from_stat;
if (::stat(from_p.c_str(), &from_stat)!= 0)
{ return false; }
int oflag = O_CREAT | O_WRONLY;
if (fail_if_exists)oflag |= O_EXCL;
if ((outfile = ::open(to_p.c_str(), oflag, from_stat.st_mode))< 0)
{
int open_errno = errno;
BOOST_ASSERT(infile >= 0);
::close(infile);
errno = open_errno;
return false;
}
ssize_t sz, sz_read=1, sz_write;
while (sz_read > 0
&& (sz_read = ::read(infile, buf.get(), buf_sz))> 0)
{
// Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
// Marc Rochkind, Addison-Wesley, 2004, page 94
sz_write = 0;
do
{
if ((sz = ::write(outfile, buf.get() + sz_write,
sz_read - sz_write))< 0)
{
sz_read = sz; // cause read loop termination
break; // and error to be thrown after closes
}
sz_write += sz;
} while (sz_write < sz_read);
}
if (::close(infile)< 0)sz_read = -1;
if (::close(outfile)< 0)sz_read = -1;
return sz_read >= 0;
}
# else
//--------------------------------------------------------------------------------------//
// //
// Windows-specific helpers //
// //
//--------------------------------------------------------------------------------------//
bool not_found_error(int errval)
{
return errval == ERROR_FILE_NOT_FOUND
|| errval == ERROR_PATH_NOT_FOUND
|| errval == ERROR_INVALID_NAME // "tools/jam/src/:sys:stat.h", "//foo"
|| errval == ERROR_INVALID_DRIVE // USB card reader with no card inserted
|| errval == ERROR_NOT_READY // CD/DVD drive with no disc inserted
|| errval == ERROR_INVALID_PARAMETER // ":sys:stat.h"
|| errval == ERROR_BAD_PATHNAME // "//nosuch" on Win64
|| errval == ERROR_BAD_NETPATH; // "//nosuch" on Win32
}
// these constants come from inspecting some Microsoft sample code
std::time_t to_time_t(const FILETIME & ft)
{
__int64 t = (static_cast<__int64>(ft.dwHighDateTime)<< 32)
+ ft.dwLowDateTime;
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 // > VC++ 7.0
t -= 116444736000000000LL;
# else
t -= 116444736000000000;
# endif
t /= 10000000;
return static_cast<std::time_t>(t);
}
void to_FILETIME(std::time_t t, FILETIME & ft)
{
__int64 temp = t;
temp *= 10000000;
# if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 // > VC++ 7.0
temp += 116444736000000000LL;
# else
temp += 116444736000000000;
# endif
ft.dwLowDateTime = static_cast<DWORD>(temp);
ft.dwHighDateTime = static_cast<DWORD>(temp >> 32);
}
// Thanks to Jeremy Maitin-Shepard for much help and for permission to
// base the equivalent()implementation on portions of his
// file-equivalence-win32.cpp experimental code.
struct handle_wrapper
{
HANDLE handle;
handle_wrapper(HANDLE h)
: handle(h){}
~handle_wrapper()
{
if (handle != INVALID_HANDLE_VALUE)
::CloseHandle(handle);
}
};
HANDLE create_file_handle(path p, DWORD dwDesiredAccess,
DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile)
{
return ::CreateFileW(p.c_str(), dwDesiredAccess, dwShareMode,
lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes,
hTemplateFile);
}
inline std::size_t get_full_path_name(
const path& src, std::size_t len, wchar_t* buf, wchar_t** p)
{
return static_cast<std::size_t>(
::GetFullPathNameW(src.c_str(), static_cast<DWORD>(len), buf, p));
}
BOOL resize_file_api(const wchar_t* p, boost::uintmax_t size)
{
HANDLE handle = CreateFileW(p, GENERIC_WRITE, 0, 0, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
LARGE_INTEGER sz;
sz.QuadPart = size;
return handle != INVALID_HANDLE_VALUE
&& ::SetFilePointerEx(handle, sz, 0, FILE_BEGIN)
&& ::SetEndOfFile(handle)
&& ::CloseHandle(handle);
}
// Windows kernel32.dll functions that may or may not be present
// must be accessed through pointers
typedef BOOL (WINAPI *PtrCreateHardLinkW)(
/*__in*/ LPCWSTR lpFileName,
/*__in*/ LPCWSTR lpExistingFileName,
/*__reserved*/ LPSECURITY_ATTRIBUTES lpSecurityAttributes
);
PtrCreateHardLinkW create_hard_link_api = PtrCreateHardLinkW(
::GetProcAddress(
::GetModuleHandle(TEXT("kernel32.dll")), "CreateHardLinkW"));
typedef BOOLEAN (WINAPI *PtrCreateSymbolicLinkW)(
/*__in*/ LPCWSTR lpSymlinkFileName,
/*__in*/ LPCWSTR lpTargetFileName,
/*__in*/ DWORD dwFlags
);
PtrCreateSymbolicLinkW create_symbolic_link_api = PtrCreateSymbolicLinkW(
::GetProcAddress(
::GetModuleHandle(TEXT("kernel32.dll")), "CreateSymbolicLinkW"));
#endif
//#ifdef BOOST_WINDOWS_API
//
//
// inline bool get_free_disk_space(const std::wstring& ph,
// PULARGE_INTEGER avail, PULARGE_INTEGER total, PULARGE_INTEGER free)
// { return ::GetDiskFreeSpaceExW(ph.c_str(), avail, total, free)!= 0; }
//
//#endif
} // unnamed namespace
//--------------------------------------------------------------------------------------//
// //
// operations functions declared in operations.hpp //
// in alphabetic order //
// //
//--------------------------------------------------------------------------------------//
namespace boost
{
namespace filesystem3
{
BOOST_FILESYSTEM_DECL
path absolute(const path& p, const path& base)
{
// if ( p.empty() || p.is_absolute() )
// return p;
// // recursively calling absolute is sub-optimal, but is simple
// path abs_base(base.is_absolute() ? base : absolute(base));
//# ifdef BOOST_WINDOWS_API
// if (p.has_root_directory())
// return abs_base.root_name() / p;
// // !p.has_root_directory
// if (p.has_root_name())
// return p.root_name()
// / abs_base.root_directory() / abs_base.relative_path() / p.relative_path();
// // !p.has_root_name()
//# endif
// return abs_base / p;
// recursively calling absolute is sub-optimal, but is sure and simple
path abs_base(base.is_absolute() ? base : absolute(base));
// store expensive to compute values that are needed multiple times
path p_root_name (p.root_name());
path base_root_name (abs_base.root_name());
path p_root_directory (p.root_directory());
if (p.empty())
return abs_base;
if (!p_root_name.empty()) // p.has_root_name()
{
if (p_root_directory.empty()) // !p.has_root_directory()
return p_root_name / abs_base.root_directory()
/ abs_base.relative_path() / p.relative_path();
// p is absolute, so fall through to return p at end of block
}
else if (!p_root_directory.empty()) // p.has_root_directory()
{
# ifdef BOOST_POSIX_API
// POSIX can have root name it it is a network path
if (base_root_name.empty()) // !abs_base.has_root_name()
return p;
# endif
return base_root_name / p;
}
else
{
return abs_base / p;
}
return p; // p.is_absolute() is true
}
namespace detail
{
BOOST_FILESYSTEM_DECL bool possible_large_file_size_support()
{
# ifdef BOOST_POSIX_API
struct stat lcl_stat;
return sizeof(lcl_stat.st_size)> 4;
# else
return true;
# endif
}
BOOST_FILESYSTEM_DECL
void copy(const path& from, const path& to, system::error_code* ec)
{
file_status s(symlink_status(from, *ec));
if (ec != 0 && ec)return;
if(is_symlink(s))
{
copy_symlink(from, to, *ec);
}
else if(is_directory(s))
{
copy_directory(from, to, *ec);
}
else if(is_regular_file(s))
{
copy_file(from, to, copy_option::fail_if_exists, *ec);
}
else
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::copy",
from, to, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category())));
ec->assign(BOOST_ERROR_NOT_SUPPORTED, system_category());
}
}
BOOST_FILESYSTEM_DECL
void copy_directory(const path& from, const path& to, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat from_stat;
# endif
error(!BOOST_COPY_DIRECTORY(from.c_str(), to.c_str()),
from, to, ec, "boost::filesystem::copy_directory");
}
BOOST_FILESYSTEM_DECL
void copy_file(const path& from, const path& to,
BOOST_SCOPED_ENUM(copy_option)option,
error_code* ec)
{
error(!BOOST_COPY_FILE(from.c_str(), to.c_str(),
option == copy_option::fail_if_exists),
from, to, ec, "boost::filesystem::copy_file");
}
BOOST_FILESYSTEM_DECL
void copy_symlink(const path& from, const path& to, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
path p(read_symlink(from, ec));
if (ec != 0 && ec) return;
create_symlink(p, to, ec);
# elif _WIN32_WINNT < 0x0600 // SDK earlier than Vista and Server 2008
error(true, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()), to, from, ec,
"boost::filesystem::copy_symlink");
# else // modern Windows
// see if actually supported by Windows runtime dll
if (error(!create_symbolic_link_api,
error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()),
to, from, ec,
"boost::filesystem3::copy_symlink"))
return;
// preconditions met, so attempt the copy
error(!::CopyFileExW(from.c_str(), to.c_str(), 0, 0, 0,
COPY_FILE_COPY_SYMLINK | COPY_FILE_FAIL_IF_EXISTS), to, from, ec,
"boost::filesystem3::copy_symlink");
# endif
}
BOOST_FILESYSTEM_DECL
bool create_directories(const path& p, system::error_code* ec)
{
if (p.empty() || exists(p))
{
if (!p.empty() && !is_directory(p))
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error(
"boost::filesystem::create_directories", p,
error_code(system::errc::file_exists, system::generic_category())));
else ec->assign(system::errc::file_exists, system::generic_category());
}
return false;
}
// First create branch, by calling ourself recursively
create_directories(p.parent_path(), ec);
// Now that parent's path exists, create the directory
create_directory(p, ec);
return true;
}
BOOST_FILESYSTEM_DECL
bool create_directory(const path& p, error_code* ec)
{
if (BOOST_CREATE_DIRECTORY(p.c_str()))
{
if (ec != 0) ec->clear();
return true;
}
// attempt to create directory failed
int errval(BOOST_ERRNO); // save reason for failure
error_code dummy;
if (errval == BOOST_ERROR_ALREADY_EXISTS && is_directory(p, dummy))
{
if (ec != 0) ec->clear();
return false;
}
// attempt to create directory failed && it doesn't already exist
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::create_directory",
p, error_code(errval, system_category())));
else
ec->assign(errval, system_category());
return false;
}
BOOST_FILESYSTEM_DECL
void create_directory_symlink(const path& to, const path& from,
system::error_code* ec)
{
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT < 0x0600 // SDK earlier than Vista and Server 2008
error(true, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()), to, from, ec,
"boost::filesystem::create_directory_symlink");
# else
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT >= 0x0600
// see if actually supported by Windows runtime dll
if (error(!create_symbolic_link_api,
error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()),
to, from, ec,
"boost::filesystem::create_directory_symlink"))
return;
# endif
error(!BOOST_CREATE_SYMBOLIC_LINK(from.c_str(), to.c_str(), SYMBOLIC_LINK_FLAG_DIRECTORY),
to, from, ec, "boost::filesystem::create_directory_symlink");
# endif
}
BOOST_FILESYSTEM_DECL
void create_hard_link(const path& to, const path& from, error_code* ec)
{
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT < 0x0500 // SDK earlier than Win 2K
error(true, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()), to, from, ec,
"boost::filesystem::create_hard_link");
# else
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT >= 0x0500
// see if actually supported by Windows runtime dll
if (error(!create_hard_link_api,
error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()),
to, from, ec,
"boost::filesystem::create_hard_link"))
return;
# endif
error(!BOOST_CREATE_HARD_LINK(from.c_str(), to.c_str()), to, from, ec,
"boost::filesystem::create_hard_link");
# endif
}
BOOST_FILESYSTEM_DECL
void create_symlink(const path& to, const path& from, error_code* ec)
{
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT < 0x0600 // SDK earlier than Vista and Server 2008
error(true, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()), to, from, ec,
"boost::filesystem::create_directory_symlink");
# else
# if defined(BOOST_WINDOWS_API) && _WIN32_WINNT >= 0x0600
// see if actually supported by Windows runtime dll
if (error(!create_symbolic_link_api,
error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()),
to, from, ec,
"boost::filesystem::create_directory_symlink"))
return;
# endif
error(!BOOST_CREATE_SYMBOLIC_LINK(from.c_str(), to.c_str(), 0),
to, from, ec, "boost::filesystem::create_directory_symlink");
# endif
}
BOOST_FILESYSTEM_DECL
path current_path(error_code* ec)
{
# ifdef BOOST_POSIX_API
path cur;
for (long path_max = 128;; path_max *=2)// loop 'til buffer large enough
{
boost::scoped_array<char>
buf(new char[static_cast<std::size_t>(path_max)]);
if (::getcwd(buf.get(), static_cast<std::size_t>(path_max))== 0)
{
if (error(errno != ERANGE
// bug in some versions of the Metrowerks C lib on the Mac: wrong errno set
# if defined(__MSL__) && (defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__))
&& errno != 0
# endif
, ec, "boost::filesystem::current_path"))
{
break;
}
}
else
{
cur = buf.get();
if (ec != 0) ec->clear();
break;
}
}
return cur;
# else
DWORD sz;
if ((sz = ::GetCurrentDirectoryW(0, NULL))== 0)sz = 1;
boost::scoped_array<path::value_type> buf(new path::value_type[sz]);
error(::GetCurrentDirectoryW(sz, buf.get())== 0, ec,
"boost::filesystem::current_path");
return path(buf.get());
# endif
}
BOOST_FILESYSTEM_DECL
void current_path(const path& p, system::error_code* ec)
{
error(!BOOST_SET_CURRENT_DIRECTORY(p.c_str()),
p, ec, "boost::filesystem::current_path");
}
BOOST_FILESYSTEM_DECL
bool equivalent(const path& p1, const path& p2, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat s2;
int e2(::stat(p2.c_str(), &s2));
struct stat s1;
int e1(::stat(p1.c_str(), &s1));
if (e1 != 0 || e2 != 0)
{
// if one is invalid and the other isn't then they aren't equivalent,
// but if both are invalid then it is an error
error (e1 != 0 && e2 != 0, p1, p2, ec, "boost::filesystem::equivalent");
return false;
}
// both stats now known to be valid
return s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino
// According to the POSIX stat specs, "The st_ino and st_dev fields
// taken together uniquely identify the file within the system."
// Just to be sure, size and mod time are also checked.
&& s1.st_size == s2.st_size && s1.st_mtime == s2.st_mtime;
# else // Windows
// Note well: Physical location on external media is part of the
// equivalence criteria. If there are no open handles, physical location
// can change due to defragmentation or other relocations. Thus handles
// must be held open until location information for both paths has
// been retrieved.
// p2 is done first, so any error reported is for p1
handle_wrapper h2(
create_file_handle(
p2.c_str(),
0,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0));
handle_wrapper h1(
create_file_handle(
p1.c_str(),
0,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0));
if (h1.handle == INVALID_HANDLE_VALUE
|| h2.handle == INVALID_HANDLE_VALUE)
{
// if one is invalid and the other isn't, then they aren't equivalent,
// but if both are invalid then it is an error
error(h1.handle == INVALID_HANDLE_VALUE
&& h2.handle == INVALID_HANDLE_VALUE, p1, p2, ec,
"boost::filesystem::equivalent");
return false;
}
// at this point, both handles are known to be valid
BY_HANDLE_FILE_INFORMATION info1, info2;
if (error(!::GetFileInformationByHandle(h1.handle, &info1),
p1, p2, ec, "boost::filesystem::equivalent"))
return false;
if (error(!::GetFileInformationByHandle(h2.handle, &info2),
p1, p2, ec, "boost::filesystem::equivalent"))
return false;
// In theory, volume serial numbers are sufficient to distinguish between
// devices, but in practice VSN's are sometimes duplicated, so last write
// time and file size are also checked.
return
info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
&& info1.nFileIndexHigh == info2.nFileIndexHigh
&& info1.nFileIndexLow == info2.nFileIndexLow
&& info1.nFileSizeHigh == info2.nFileSizeHigh
&& info1.nFileSizeLow == info2.nFileSizeLow
&& info1.ftLastWriteTime.dwLowDateTime
== info2.ftLastWriteTime.dwLowDateTime
&& info1.ftLastWriteTime.dwHighDateTime
== info2.ftLastWriteTime.dwHighDateTime;
# endif
}
BOOST_FILESYSTEM_DECL
boost::uintmax_t file_size(const path& p, error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (error(::stat(p.c_str(), &path_stat)!= 0,
p, ec, "boost::filesystem::file_size"))
return static_cast<boost::uintmax_t>(-1);
if (error(!S_ISREG(path_stat.st_mode),
error_code(EPERM, system_category()),
p, ec, "boost::filesystem::file_size"))
return static_cast<boost::uintmax_t>(-1);
return static_cast<boost::uintmax_t>(path_stat.st_size);
# else // Windows
// assume uintmax_t is 64-bits on all Windows compilers
WIN32_FILE_ATTRIBUTE_DATA fad;
if (error(::GetFileAttributesExW(p.c_str(), ::GetFileExInfoStandard, &fad)== 0,
p, ec, "boost::filesystem::file_size"))
return static_cast<boost::uintmax_t>(-1);
if (error((fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)!= 0,
error_code(ERROR_NOT_SUPPORTED, system_category()),
p, ec, "boost::filesystem::file_size"))
return static_cast<boost::uintmax_t>(-1);
return (static_cast<boost::uintmax_t>(fad.nFileSizeHigh)
<< (sizeof(fad.nFileSizeLow)*8)) + fad.nFileSizeLow;
# endif
}
BOOST_FILESYSTEM_DECL
boost::uintmax_t hard_link_count(const path& p, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
return error(::stat(p.c_str(), &path_stat)!= 0,
p, ec, "boost::filesystem::hard_link_count")
? 0
: static_cast<boost::uintmax_t>(path_stat.st_nlink);
# else // Windows
// Link count info is only available through GetFileInformationByHandle
BY_HANDLE_FILE_INFORMATION info;
handle_wrapper h(
create_file_handle(p.c_str(), 0,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
return
!error(h.handle == INVALID_HANDLE_VALUE,
p, ec, "boost::filesystem::hard_link_count")
&& !error(::GetFileInformationByHandle(h.handle, &info)== 0,
p, ec, "boost::filesystem::hard_link_count")
? info.nNumberOfLinks
: 0;
# endif
}
BOOST_FILESYSTEM_DECL
path initial_path(error_code* ec)
{
static path init_path;
if (init_path.empty())
init_path = current_path(ec);
else if (ec != 0) ec->clear();
return init_path;
}
BOOST_FILESYSTEM_DECL
bool is_empty(const path& p, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (error(::stat(p.c_str(), &path_stat)!= 0,
p, ec, "boost::filesystem::is_empty"))
return false;
return S_ISDIR(path_stat.st_mode)
? is_empty_directory(p)
: path_stat.st_size == 0;
# else
WIN32_FILE_ATTRIBUTE_DATA fad;
if (error(::GetFileAttributesExW(p.c_str(), ::GetFileExInfoStandard, &fad)== 0,
p, ec, "boost::filesystem::is_empty"))
return false;
if (ec != 0) ec->clear();
return
(fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
? is_empty_directory(p)
: (!fad.nFileSizeHigh && !fad.nFileSizeLow);
# endif
}
BOOST_FILESYSTEM_DECL
std::time_t last_write_time(const path& p, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (error(::stat(p.c_str(), &path_stat)!= 0,
p, ec, "boost::filesystem::last_write_time"))
return std::time_t(-1);
return path_stat.st_mtime;
# else
handle_wrapper hw(
create_file_handle(p.c_str(), 0,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
if (error(hw.handle == INVALID_HANDLE_VALUE,
p, ec, "boost::filesystem::last_write_time"))
return std::time_t(-1);
FILETIME lwt;
if (error(::GetFileTime(hw.handle, 0, 0, &lwt)== 0,
p, ec, "boost::filesystem::last_write_time"))
return std::time_t(-1);
return to_time_t(lwt);
# endif
}
BOOST_FILESYSTEM_DECL
void last_write_time(const path& p, const std::time_t new_time,
system::error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (error(::stat(p.c_str(), &path_stat)!= 0,
p, ec, "boost::filesystem::last_write_time"))
return;
::utimbuf buf;
buf.actime = path_stat.st_atime; // utime()updates access time too:-(
buf.modtime = new_time;
error(::utime(p.c_str(), &buf)!= 0,
p, ec, "boost::filesystem::last_write_time");
# else
handle_wrapper hw(
create_file_handle(p.c_str(), FILE_WRITE_ATTRIBUTES,
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
if (error(hw.handle == INVALID_HANDLE_VALUE,
p, ec, "boost::filesystem::last_write_time"))
return;
FILETIME lwt;
to_FILETIME(new_time, lwt);
error(::SetFileTime(hw.handle, 0, 0, &lwt)== 0,
p, ec, "boost::filesystem::last_write_time");
# endif
}
BOOST_FILESYSTEM_DECL
path read_symlink(const path& p, system::error_code* ec)
{
path symlink_path;
# ifdef BOOST_POSIX_API
for (std::size_t path_max = 64;; path_max *= 2)// loop 'til buffer large enough
{
boost::scoped_array<char> buf(new char[path_max]);
ssize_t result;
if ((result=::readlink(p.c_str(), buf.get(), path_max))== -1)
{
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::read_symlink",
p, error_code(errno, system_category())));
else ec->assign(errno, system_category());
break;
}
else
{
if(result != static_cast<ssize_t>(path_max))
{
symlink_path.assign(buf.get(), buf.get() + result);
if (ec != 0) ec->clear();
break;
}
}
}
# elif _WIN32_WINNT < 0x0600 // SDK earlier than Vista and Server 2008
error(true, error_code(BOOST_ERROR_NOT_SUPPORTED, system_category()), p, ec,
"boost::filesystem::read_symlink");
# else // Vista and Server 2008 SDK, or later
union info_t
{
char buf[REPARSE_DATA_BUFFER_HEADER_SIZE+MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
REPARSE_DATA_BUFFER rdb;
} info;
handle_wrapper h(
create_file_handle(p.c_str(),GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, 0));
if (error(h.handle == INVALID_HANDLE_VALUE, p, ec, "boost::filesystem::read_symlink"))
return symlink_path;
DWORD sz;
if (!error(::DeviceIoControl(h.handle, FSCTL_GET_REPARSE_POINT,
0, 0, info.buf, sizeof(info), &sz, 0) == 0, p, ec,
"boost::filesystem::read_symlink" ))
symlink_path.assign(
static_cast<wchar_t*>(info.rdb.SymbolicLinkReparseBuffer.PathBuffer)
+ info.rdb.SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(wchar_t),
static_cast<wchar_t*>(info.rdb.SymbolicLinkReparseBuffer.PathBuffer)
+ info.rdb.SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(wchar_t)
+ info.rdb.SymbolicLinkReparseBuffer.PrintNameLength/sizeof(wchar_t));
# endif
return symlink_path;
}
BOOST_FILESYSTEM_DECL
bool remove(const path& p, error_code* ec)
{
error_code tmp_ec;
file_status sym_status = symlink_status(p, tmp_ec);
if (error(sym_status.type() == status_error, tmp_ec, p, ec,
"boost::filesystem::remove"))
return false;
return remove_file_or_directory(p, sym_status, ec);
}
BOOST_FILESYSTEM_DECL
boost::uintmax_t remove_all(const path& p, error_code* ec)
{
error_code tmp_ec;
file_status sym_status = symlink_status(p, tmp_ec);
if (error(sym_status.type() == status_error, tmp_ec, p, ec,
"boost::filesystem::remove_all"))
return 0;
return exists(sym_status) // exists() throws nothing
? remove_all_aux(p, sym_status, ec)
: 0;
}
BOOST_FILESYSTEM_DECL
void rename(const path& old_p, const path& new_p, error_code* ec)
{
error(!BOOST_MOVE_FILE(old_p.c_str(), new_p.c_str()), old_p, new_p, ec,
"boost::filesystem::rename");
}
BOOST_FILESYSTEM_DECL
void resize_file(const path& p, uintmax_t size, system::error_code* ec)
{
error(!BOOST_RESIZE_FILE(p.c_str(), size), p, ec, "boost::filesystem::resize_file");
}
BOOST_FILESYSTEM_DECL
space_info space(const path& p, error_code* ec)
{
# ifdef BOOST_POSIX_API
struct BOOST_STATVFS vfs;
space_info info;
if (!error(::BOOST_STATVFS(p.c_str(), &vfs)!= 0,
p, ec, "boost::filesystem::space"))
{
info.capacity
= static_cast<boost::uintmax_t>(vfs.f_blocks)* BOOST_STATVFS_F_FRSIZE;
info.free
= static_cast<boost::uintmax_t>(vfs.f_bfree)* BOOST_STATVFS_F_FRSIZE;
info.available
= static_cast<boost::uintmax_t>(vfs.f_bavail)* BOOST_STATVFS_F_FRSIZE;
}
# else
ULARGE_INTEGER avail, total, free;
space_info info;
if (!error(::GetDiskFreeSpaceExW(p.c_str(), &avail, &total, &free)== 0,
p, ec, "boost::filesystem::space"))
{
info.capacity
= (static_cast<boost::uintmax_t>(total.HighPart)<< 32)
+ total.LowPart;
info.free
= (static_cast<boost::uintmax_t>(free.HighPart)<< 32)
+ free.LowPart;
info.available
= (static_cast<boost::uintmax_t>(avail.HighPart)<< 32)
+ avail.LowPart;
}
# endif
else
{
info.capacity = info.free = info.available = 0;
}
return info;
}
# ifndef BOOST_POSIX_API
file_status process_status_failure(const path& p, error_code* ec)
{
int errval(::GetLastError());
if (ec != 0) // always report errval, even though some
ec->assign(errval, system_category()); // errval values are not status_errors
if (not_found_error(errval))
{
return file_status(file_not_found);
}
else if ((errval == ERROR_SHARING_VIOLATION))
{
return file_status(type_unknown);
}
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::status",
p, error_code(errval, system_category())));
return file_status(status_error);
}
# endif
BOOST_FILESYSTEM_DECL
file_status status(const path& p, error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (::stat(p.c_str(), &path_stat)!= 0)
{
if (ec != 0) // always report errno, even though some
ec->assign(errno, system_category()); // errno values are not status_errors
if (not_found_error(errno))
{
return fs::file_status(fs::file_not_found);
}
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::status",
p, error_code(errno, system_category())));
return fs::file_status(fs::status_error);
}
if (ec != 0) ec->clear();;
if (S_ISDIR(path_stat.st_mode))
return fs::file_status(fs::directory_file);
if (S_ISREG(path_stat.st_mode))
return fs::file_status(fs::regular_file);
if (S_ISBLK(path_stat.st_mode))
return fs::file_status(fs::block_file);
if (S_ISCHR(path_stat.st_mode))
return fs::file_status(fs::character_file);
if (S_ISFIFO(path_stat.st_mode))
return fs::file_status(fs::fifo_file);
if (S_ISSOCK(path_stat.st_mode))
return fs::file_status(fs::socket_file);
return fs::file_status(fs::type_unknown);
# else // Windows
DWORD attr(::GetFileAttributesW(p.c_str()));
if (attr == 0xFFFFFFFF)
{
return detail::process_status_failure(p, ec);
}
// symlink handling
if (attr & FILE_ATTRIBUTE_REPARSE_POINT)// aka symlink
{
handle_wrapper h(
create_file_handle(
p.c_str(),
0, // dwDesiredAccess; attributes only
FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
0, // lpSecurityAttributes
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
0)); // hTemplateFile
if (h.handle == INVALID_HANDLE_VALUE)
{
return detail::process_status_failure(p, ec);
}
}
if (ec != 0) ec->clear();
return (attr & FILE_ATTRIBUTE_DIRECTORY)
? file_status(directory_file)
: file_status(regular_file);
# endif
}
BOOST_FILESYSTEM_DECL
file_status symlink_status(const path& p, error_code* ec)
{
# ifdef BOOST_POSIX_API
struct stat path_stat;
if (::lstat(p.c_str(), &path_stat)!= 0)
{
if (ec != 0) // always report errno, even though some
ec->assign(errno, system_category()); // errno values are not status_errors
if (errno == ENOENT || errno == ENOTDIR) // these are not errors
{
return fs::file_status(fs::file_not_found);
}
if (ec == 0)
BOOST_FILESYSTEM_THROW(filesystem_error("boost::filesystem::status",
p, error_code(errno, system_category())));
return fs::file_status(fs::status_error);
}
if (ec != 0) ec->clear();
if (S_ISREG(path_stat.st_mode))
return fs::file_status(fs::regular_file);
if (S_ISDIR(path_stat.st_mode))
return fs::file_status(fs::directory_file);
if (S_ISLNK(path_stat.st_mode))
return fs::file_status(fs::symlink_file);
if (S_ISBLK(path_stat.st_mode))
return fs::file_status(fs::block_file);
if (S_ISCHR(path_stat.st_mode))
return fs::file_status(fs::character_file);
if (S_ISFIFO(path_stat.st_mode))
return fs::file_status(fs::fifo_file);
if (S_ISSOCK(path_stat.st_mode))
return fs::file_status(fs::socket_file);
return fs::file_status(fs::type_unknown);
# else // Windows
DWORD attr(::GetFileAttributesW(p.c_str()));
if (attr == 0xFFFFFFFF)
{
return detail::process_status_failure(p, ec);
}
if (ec != 0) ec->clear();
if (attr & FILE_ATTRIBUTE_REPARSE_POINT)// aka symlink
return file_status(symlink_file);
return (attr & FILE_ATTRIBUTE_DIRECTORY)
? file_status(directory_file)
: file_status(regular_file);
# endif
}
BOOST_FILESYSTEM_DECL
path system_complete(const path& p, system::error_code* ec)
{
# ifdef BOOST_POSIX_API
return (p.empty() || p.is_absolute())
? p : current_path()/ p;
# else
if (p.empty())
{
if (ec != 0) ec->clear();
return p;
}
wchar_t buf[buf_size];
wchar_t* pfn;
std::size_t len = get_full_path_name(p, buf_size, buf, &pfn);
if (error(len == 0, p, ec, "boost::filesystem::system_complete"))
return path();
if (len < buf_size)// len does not include null termination character
return path(&buf[0]);
boost::scoped_array<wchar_t> big_buf(new wchar_t[len]);
return error(get_full_path_name(p, len , big_buf.get(), &pfn)== 0,
p, ec, "boost::filesystem::system_complete")
? path()
: path(big_buf.get());
# endif
}
} // namespace detail
//--------------------------------------------------------------------------------------//
// //
// directory_entry //
// //
//--------------------------------------------------------------------------------------//
file_status
directory_entry::m_get_status(system::error_code* ec) const
{
if (!status_known(m_status))
{
// optimization: if the symlink status is known, and it isn't a symlink,
// then status and symlink_status are identical so just copy the
// symlink status to the regular status.
if (status_known(m_symlink_status)
&& !is_symlink(m_symlink_status))
{
m_status = m_symlink_status;
if (ec != 0) ec->clear();
}
else m_status = detail::status(m_path, ec);
}
else if (ec != 0) ec->clear();
return m_status;
}
file_status
directory_entry::m_get_symlink_status(system::error_code* ec) const
{
if (!status_known(m_symlink_status))
m_symlink_status = detail::symlink_status(m_path, ec);
else if (ec != 0) ec->clear();
return m_symlink_status;
}
// dispatch directory_entry supplied here rather than in
// <boost/filesystem/path_traits.hpp>, thus avoiding header circularity.
// test cases are in operations_unit_test.cpp
namespace path_traits
{
void dispatch(const directory_entry & de,
# ifdef BOOST_WINDOWS_API
std::wstring& to,
# else
std::string& to,
# endif
const codecvt_type &)
{
to = de.path().native();
}
} // namespace path_traits
} // namespace filesystem3
} // namespace boost
//--------------------------------------------------------------------------------------//
// //
// directory_iterator //
// //
//--------------------------------------------------------------------------------------//
namespace
{
# ifdef BOOST_POSIX_API
error_code path_max(std::size_t & result)
// this code is based on Stevens and Rago, Advanced Programming in the
// UNIX envirnment, 2nd Ed., ISBN 0-201-43307-9, page 49
{
# ifdef PATH_MAX
static std::size_t max = PATH_MAX;
# else
static std::size_t max = 0;
# endif
if (max == 0)
{
errno = 0;
long tmp = ::pathconf("/", _PC_NAME_MAX);
if (tmp < 0)
{
if (errno == 0)// indeterminate
max = 4096; // guess
else return error_code(errno, system_category());
}
else max = static_cast<std::size_t>(tmp + 1); // relative root
}
result = max;
return ok;
}
error_code dir_itr_first(void *& handle, void *& buffer,
const char* dir, string& target,
fs::file_status &, fs::file_status &)
{
if ((handle = ::opendir(dir))== 0)
return error_code(errno, system_category());
target = string("."); // string was static but caused trouble
// when iteration called from dtor, after
// static had already been destroyed
std::size_t path_size (0); // initialization quiets gcc warning (ticket #3509)
error_code ec = path_max(path_size);
if (ec)return ec;
dirent de;
buffer = std::malloc((sizeof(dirent) - sizeof(de.d_name))
+ path_size + 1); // + 1 for "/0"
return ok;
}
// warning: the only dirent member updated is d_name
inline int readdir_r_simulator(DIR * dirp, struct dirent * entry,
struct dirent ** result)// *result set to 0 on end of directory
{
errno = 0;
# if !defined(__CYGWIN__)\
&& defined(_POSIX_THREAD_SAFE_FUNCTIONS)\
&& defined(_SC_THREAD_SAFE_FUNCTIONS)\
&& (_POSIX_THREAD_SAFE_FUNCTIONS+0 >= 0)\
&& (!defined(__hpux) || defined(_REENTRANT)) \
&& (!defined(_AIX) || defined(__THREAD_SAFE))
if (::sysconf(_SC_THREAD_SAFE_FUNCTIONS)>= 0)
{ return ::readdir_r(dirp, entry, result); }
# endif
struct dirent * p;
*result = 0;
if ((p = ::readdir(dirp))== 0)
return errno;
std::strcpy(entry->d_name, p->d_name);
*result = entry;
return 0;
}
error_code dir_itr_increment(void *& handle, void *& buffer,
string& target, fs::file_status & sf, fs::file_status & symlink_sf)
{
BOOST_ASSERT(buffer != 0);
dirent * entry(static_cast<dirent *>(buffer));
dirent * result;
int return_code;
if ((return_code = readdir_r_simulator(static_cast<DIR*>(handle),
entry, &result))!= 0)return error_code(errno, system_category());
if (result == 0)
return fs::detail::dir_itr_close(handle, buffer);
target = entry->d_name;
# ifdef BOOST_FILESYSTEM_STATUS_CACHE
if (entry->d_type == DT_UNKNOWN) // filesystem does not supply d_type value
{
sf = symlink_sf = fs::file_status(fs::status_error);
}
else // filesystem supplies d_type value
{
if (entry->d_type == DT_DIR)
sf = symlink_sf = fs::file_status(fs::directory_file);
else if (entry->d_type == DT_REG)
sf = symlink_sf = fs::file_status(fs::regular_file);
else if (entry->d_type == DT_LNK)
{
sf = fs::file_status(fs::status_error);
symlink_sf = fs::file_status(fs::symlink_file);
}
else sf = symlink_sf = fs::file_status(fs::status_error);
}
# else
sf = symlink_sf = fs::file_status(fs::status_error);
# endif
return ok;
}
# else // BOOST_WINDOWS_API
error_code dir_itr_first(void *& handle, const fs::path& dir,
wstring& target, fs::file_status & sf, fs::file_status & symlink_sf)
// Note: an empty root directory has no "." or ".." entries, so this
// causes a ERROR_FILE_NOT_FOUND error which we do not considered an
// error. It is treated as eof instead.
{
// use a form of search Sebastian Martel reports will work with Win98
wstring dirpath(dir.wstring());
dirpath += (dirpath.empty()
|| (dirpath[dirpath.size()-1] != L'\\'
&& dirpath[dirpath.size()-1] != L'/'
&& dirpath[dirpath.size()-1] != L':'))? L"\\*" : L"*";
WIN32_FIND_DATAW data;
if ((handle = ::FindFirstFileW(dirpath.c_str(), &data))
== INVALID_HANDLE_VALUE)
{
handle = 0;
return error_code( (::GetLastError() == ERROR_FILE_NOT_FOUND
// Windows Mobile returns ERROR_NO_MORE_FILES; see ticket #3551
|| ::GetLastError() == ERROR_NO_MORE_FILES)
? 0 : ::GetLastError(), system_category() );
}
target = data.cFileName;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{ sf.type(fs::directory_file); symlink_sf.type(fs::directory_file); }
else { sf.type(fs::regular_file); symlink_sf.type(fs::regular_file); }
return error_code();
}
error_code dir_itr_increment(void *& handle, wstring& target,
fs::file_status & sf, fs::file_status & symlink_sf)
{
WIN32_FIND_DATAW data;
if (::FindNextFileW(handle, &data)== 0)// fails
{
int error = ::GetLastError();
fs::detail::dir_itr_close(handle);
return error_code(error == ERROR_NO_MORE_FILES ? 0 : error, system_category());
}
target = data.cFileName;
if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{ sf.type(fs::directory_file); symlink_sf.type(fs::directory_file); }
else { sf.type(fs::regular_file); symlink_sf.type(fs::regular_file); }
return error_code();
}
#endif
const error_code not_found_error_code (
# ifdef BOOST_WINDOWS_API
ERROR_PATH_NOT_FOUND
# else
ENOENT
# endif
, system_category());
} // unnamed namespace
namespace boost
{
namespace filesystem3
{
namespace detail
{
// dir_itr_close is called both from the ~dir_itr_imp()destructor
// and dir_itr_increment()
BOOST_FILESYSTEM_DECL
system::error_code dir_itr_close( // never throws
void *& handle
# if defined(BOOST_POSIX_API)
, void *& buffer
# endif
)
{
# ifdef BOOST_POSIX_API
std::free(buffer);
buffer = 0;
if (handle == 0)return ok;
DIR * h(static_cast<DIR*>(handle));
handle = 0;
return error_code(::closedir(h)== 0 ? 0 : errno, system_category());
# else
if (handle != 0)
{
::FindClose(handle);
handle = 0;
}
return ok;
# endif
}
void directory_iterator_construct(directory_iterator& it,
const path& p, system::error_code* ec)
{
if (error(p.empty(), not_found_error_code, p, ec,
"boost::filesystem::directory_iterator::construct"))return;
path::string_type filename;
file_status file_stat, symlink_file_stat;
error_code result = dir_itr_first(it.m_imp->handle,
# if defined(BOOST_POSIX_API)
it.m_imp->buffer,
# endif
p.c_str(), filename, file_stat, symlink_file_stat);
if (result)
{
it.m_imp.reset();
error(true, result, p,
ec, "boost::filesystem::directory_iterator::construct");
return;
}
if (it.m_imp->handle == 0)it.m_imp.reset(); // eof, so make end iterator
else // not eof
{
it.m_imp->dir_entry.assign(p / filename,
file_stat, symlink_file_stat);
if (filename[0] == dot // dot or dot-dot
&& (filename.size()== 1
|| (filename[1] == dot
&& filename.size()== 2)))
{ it.increment(); }
}
}
void directory_iterator_increment(directory_iterator& it,
system::error_code* ec)
{
BOOST_ASSERT(it.m_imp.get() && "attempt to increment end iterator");
BOOST_ASSERT(it.m_imp->handle != 0 && "internal program error");
path::string_type filename;
file_status file_stat, symlink_file_stat;
system::error_code temp_ec;
for (;;)
{
temp_ec = dir_itr_increment(it.m_imp->handle,
# if defined(BOOST_POSIX_API)
it.m_imp->buffer,
# endif
filename, file_stat, symlink_file_stat);
if (temp_ec)
{
it.m_imp.reset();
if (ec == 0)
BOOST_FILESYSTEM_THROW(
filesystem_error("boost::filesystem::directory_iterator::operator++",
it.m_imp->dir_entry.path().parent_path(),
error_code(BOOST_ERRNO, system_category())));
ec->assign(BOOST_ERRNO, system_category());
return;
}
else if (ec != 0) ec->clear();
if (it.m_imp->handle == 0){ it.m_imp.reset(); return; } // eof, make end
if (!(filename[0] == dot // !(dot or dot-dot)
&& (filename.size()== 1
|| (filename[1] == dot
&& filename.size()== 2))))
{
it.m_imp->dir_entry.replace_filename(
filename, file_stat, symlink_file_stat);
return;
}
}
}
} // namespace detail
} // namespace filesystem3
} // namespace boost
#endif // no wide character support
| gpl-2.0 |
nachopavon/redprofesional | mod/event_manager/views/default/event_manager/js/site.php | 17063 | <?php ?>
//<script>
elgg.provide("elgg.event_manager");
var infowindow = null;
(function(){
var uid1 = 'D' + (+new Date()),
uid2 = 'D' + (+new Date() + 1);
jQuery.event.special.focus = {
setup: function() {
var _self = this,
handler = function(e) {
e = jQuery.event.fix(e);
e.type = 'focus';
if (_self === document) {
jQuery.event.handle.call(_self, e);
}
};
jQuery(this).data(uid1, handler);
if (_self === document) {
/* Must be live() */
if (_self.addEventListener) {
_self.addEventListener('focus', handler, true);
} else {
_self.attachEvent('onfocusin', handler);
}
} else {
return false;
}
},
teardown: function() {
var handler = jQuery(this).data(uid1);
if (this === document) {
if (this.removeEventListener) {
this.removeEventListener('focus', handler, true);
} else {
this.detachEvent('onfocusin', handler);
}
}
}
};
jQuery.event.special.blur = {
setup: function() {
var _self = this,
handler = function(e) {
e = jQuery.event.fix(e);
e.type = 'blur';
if (_self === document) {
jQuery.event.handle.call(_self, e);
}
};
jQuery(this).data(uid2, handler);
if (_self === document) {
/* Must be live() */
if (_self.addEventListener) {
_self.addEventListener('blur', handler, true);
} else {
_self.attachEvent('onfocusout', handler);
}
} else {
return false;
}
},
teardown: function() {
var handler = jQuery(this).data(uid2);
if (this === document) {
if (this.removeEventListener) {
this.removeEventListener('blur', handler, true);
} else {
this.detachEvent('onfocusout', handler);
}
}
}
};
// toggle drop down menu
$(".event_manager_event_actions").live("click", function(event){
if($(this).next().is(":hidden")){
// only needed if the current menu is already dropped down
$("body > .event_manager_event_actions_drop_down").remove();
$("body").append($(this).next().clone());
css_top = $(this).offset().top + $(this).height();
css_left = $(this).offset().left;
$("body > .event_manager_event_actions_drop_down").css({top: css_top, left: css_left}).show();;
}
event.stopPropagation();
});
// hide drop down menu items
$("body").live("click", function(){
$("body > .event_manager_event_actions_drop_down").remove();
});
}());
function event_manager_program_add_day(form){
$(form).find("input[type='submit']").hide();
$.post(elgg.get_site_url() + 'events/proc/day/edit', $(form).serialize(), function(response) {
if(response.valid) {
$.fancybox.close();
guid = response.guid;
if(response.edit){
$("#day_" + guid + " .event_manager_program_day_details").html(response.content_body);
$("#event_manager_event_view_program a[rel='day_" + guid + "']").html(response.content_title).click();
} else {
$("#event_manager_event_view_program").after(response.content_body);
$("#event_manager_event_view_program li:last").before(response.content_title);
$("#event_manager_event_view_program a[rel='day_" + guid + "']").click();
}
} else {
$(form).find("input[type='submit']").show();
}
}, 'json');
}
function event_manager_program_add_slot(form){
$(form).find("input[type='submit']").hide();
$.post(elgg.get_site_url() + 'events/proc/slot/edit', $(form).serialize(), function(response) {
if(response.valid) {
$.fancybox.close();
guid = response.guid;
parent_guid = response.parent_guid;
if(response.edit){
$("#" + guid).replaceWith(response.content);
} else {
$("#day_" + parent_guid).find("a.event_manager_program_slot_add").before(response.content);
}
} else {
$(form).find("input[type='submit']").show();
}
}, 'json');
}
function event_manager_registrationform_add_field(form) {
$(form).find("input[type='submit']").hide();
$.post(elgg.get_site_url() + 'events/proc/question/edit', $(form).serialize(), function(response){
if(response.valid) {
$.fancybox.close();
guid = response.guid;
if(response.edit) {
$('#question_' + guid).replaceWith(response.content);
} else {
$("#event_manager_registrationform_fields").append(response.content);
save_registrationform_question_order();
}
} else {
$(form).find("input[type='submit']").show();
}
}, 'json');
}
function event_manager_execute_search(){
$("#event_manager_result_refreshing").show();
map_data_only = false;
if($("#event_manager_result_navigation li.elgg-state-selected a").attr("rel") == "onthemap"){
map_data_only = true;
mapBounds = event_manager_gmap.getBounds();
latitude = mapBounds.getCenter().lat();
longitude = mapBounds.getCenter().lng();
distance_latitude = mapBounds.getNorthEast().lat() - latitude;
distance_longitude = mapBounds.getNorthEast().lng() - longitude;
if(distance_longitude < 0){
distance_longitude = 360 + distance_longitude;
}
$("#latitude").val(latitude);
$("#longitude").val(longitude);
$("#distance_latitude").val(distance_latitude);
$("#distance_longitude").val(distance_longitude);
}
var formData = $("#event_manager_search_form").serialize();
$.post(elgg.get_site_url() + 'events/proc/search/events', formData, function(response){
if(response.valid){
if(map_data_only) {
if(response.markers) {
infowindow = new google.maps.InfoWindow();
var shadowIcon = new google.maps.MarkerImage("//chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35));
var ownIcon = "//maps.google.com/mapfiles/ms/icons/yellow-dot.png";
var attendingIcon = "//maps.google.com/mapfiles/ms/icons/blue-dot.png";
$.each(response.markers, function(i, event) {
existing = false;
if (event_manager_gmarkers) {
if(event_manager_gmarkers[event.guid]){
existing = true;
}
}
if(!existing){
var myLatlng = new google.maps.LatLng(event.lat, event.lng);
markerOptions = {
map: event_manager_gmap,
position: myLatlng,
animation: google.maps.Animation.DROP,
title: event.title,
shadow: shadowIcon
};
if(event.iscreator){
markerOptions.icon = ownIcon;
} else {
if(event.has_relation){
markerOptions.icon = attendingIcon;
}
}
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(event.html);
infowindow.open(event_manager_gmap,marker);
});
event_manager_gmarkers[event.guid] = marker;
}
});
}
// make sidebar
//getMarkersJson();
} else {
$('#event_manager_event_list_search_more').remove();
$('#event_manager_event_listing').html(response.content);
$("#event_manager_result_refreshing").hide();
}
}
$("#event_manager_result_refreshing").hide();
}, 'json');
}
function save_registrationform_question_order() {
var $sortableRegistrationForm = $('#event_manager_registrationform_fields');
order = $sortableRegistrationForm.sortable('serialize');
$.getJSON(elgg.get_site_url() + 'events/proc/question/saveorder', order, function(response){
if(!response.valid) {
alert(elgg.echo('event_manager:registrationform:fieldorder:error'));
}
});
}
elgg.event_manager.init = function() {
$('.event_manager_program_slot_delete').live('click', function() {
if(confirm(elgg.echo('deleteconfirm'))) {
slotGuid = $(this).parent().attr("rel");
if(slotGuid) {
$slotElement = $("#" + slotGuid);
$slotElement.hide();
$.getJSON(elgg.get_site_url() + 'events/proc/slot/delete', {guid: slotGuid}, function(response) {
if(response.valid) {
$slotElement.remove();
} else {
$slotElement.show();
}
});
}
}
return false;
});
$('.event_manager_program_day_delete').live('click', function(e) {
if(confirm(elgg.echo('deleteconfirm'))) {
dayGuid = $(this).parent().attr("rel");
if(dayGuid) {
$dayElements = $("#day_" + dayGuid + ", #event_manager_event_view_program li.elgg-state-selected");
$dayElements.hide();
$.getJSON(elgg.get_site_url() + 'events/proc/day/delete', {guid: dayGuid}, function(response) {
if(response.valid) {
// remove from DOM
$dayElements.remove();
if($("#event_manager_event_view_program li").length > 1){
$("#event_manager_event_view_program li:first a").click();
}
} else {
// revert
$dayElements.show();
}
});
}
}
return false;
});
$('#event_manager_program_register').click(function() {
$.getJSON(elgg.get_site_url() + 'events/proc/program/register', {event: $('#eventguid').val(), guids: guids.toSource()}, function(response) {
if(response.valid) {
$('#register_status').html(elgg.echo('event_manager:registration:program:success'));
} else {
$('#register_status').html(elgg.echo('event_manager:registration:program:fail'));
}
});
});
$('.event_manager_questions_delete').live('click', function(e) {
if(confirm(elgg.echo('deleteconfirm'))) {
questionGuid = $(this).attr("rel");
if(questionGuid) {
$questionElement = $(this);
$questionElement.parent().hide();
$.getJSON(elgg.get_site_url() + 'events/proc/question/delete', {guid: questionGuid}, function(response) {
if(response.valid) {
// remove from DOM
$questionElement.parent().remove();
} else {
// revert
$questionElement.parent().show();
}
});
}
}
return false;
});
/* Event Manager Search Form */
$('#event_manager_registrationform_fields').sortable({
axis: 'y',
tolerance: 'pointer',
opacity: 0.8,
forcePlaceholderSize: true,
forceHelperSize: true,
update: function(event, ui) {
save_registrationform_question_order();
}
});
$('#event_manager_event_search_advanced_enable').click(function()
{
$('#event_manager_event_search_advanced_container, #past_events, #event_manager_event_search_advanced_enable span').toggle();
if($('#past_events').is(":hidden"))
{
console.log('advanced');
$('#advanced_search').val('1');
}
else
{
console.log('simple');
$('#advanced_search').val('0');
}
});
$('#event_manager_event_list_search_more').live('click', function() {
clickedElement = $(this);
clickedElement.html('');
clickedElement.addClass('event_manager_search_load');
offset = parseInt($(this).attr('rel'), 10);
$("#event_manager_result_refreshing").show();
if($('#past_events').is(":hidden") == true) {
var formData = $("#event_manager_search_form").serialize();
} else {
var formData = $($("#event_manager_search_form")[0].elements).not($("#event_manager_event_search_advanced_container")[0].children).serialize();
}
$.post(elgg.get_site_url() + 'events/proc/search/events?offset='+offset, formData, function(response) {
if(response.valid) {
$('#event_manager_event_list_search_more').remove();
//$(response.content).insertAfter('.search_listing:last');
$('#event_manager_event_listing').append(response.content);
}
$("#event_manager_result_refreshing").hide();
}, 'json');
});
$('#event_manager_search_form').submit(function(e) {
event_manager_execute_search();
e.preventDefault();
});
$("#event_manager_result_navigation li a").click(function() {
if(!($(this).parent().hasClass("elgg-state-selected"))){
selected = $(this).attr("rel");
$("#event_manager_result_navigation li").toggleClass("elgg-state-selected");
$("#event_manager_event_map, #event_manager_event_listing").toggle();
$('#search_type').val(selected);
if(selected == "onthemap"){
initMaps('event_manager_onthemap_canvas', true);
} else {
$("#event_manager_onthemap_sidebar").remove();
event_manager_execute_search();
}
}
});
$('.event_manager_registration_approve').click(function() {
regElmnt = $(this);
regId = regElmnt.attr('rel');
$.getJSON(elgg.get_site_url() + 'events/proc/registration/approve', {guid: regId}, function(response) {
if(response.valid) {
regElmnt.unbind('click');
regElmnt.replaceWith('<img border="0" src="/mod/event_manager/_graphics/icons/check_icon.png" />');
}
});
});
$('.event_manager_program_day_add').live('click', function() {
eventGuid = $(this).attr("rel");
$.fancybox({
'href': elgg.get_site_url() + 'events/program/day?event_guid=' + eventGuid,
'onComplete' : function() {
elgg.ui.initDatePicker();
}
});
return false;
});
$('.event_manager_program_day_edit').live('click', function() {
guid = $(this).attr("rel");
$.fancybox({
'href': elgg.get_site_url() + 'events/program/day?day_guid=' + guid,
'onComplete' : function() {
elgg.ui.initDatePicker();
}
});
return false;
});
$('.event_manager_program_slot_add').live('click', function() {
dayGuid = $(this).attr("rel");
$.fancybox({'href': elgg.get_site_url() + 'events/program/slot?day_guid=' + dayGuid});
return false;
});
$('.event_manager_program_slot_edit').live('click', function() {
guid = $(this).attr("rel");
$.fancybox({'href': elgg.get_site_url() + 'events/program/slot?slot_guid=' + guid});
return false;
});
$('#event_manager_questions_add').click(function() {
eventGuid = $(this).attr("rel");
$.fancybox({'href': elgg.get_site_url() + 'events/registrationform/question?event_guid=' + eventGuid});
return false;
});
$('.event_manager_questions_edit').live('click', function() {
guid = $(this).attr("rel");
$.fancybox({'href': elgg.get_site_url() + 'events/registrationform/question?question_guid=' + guid});
return false;
});
$('#event_manager_registrationform_question_fieldtype').live('change', function() {
if($('#event_manager_registrationform_question_fieldtype').val() == 'Radiobutton' || $('#event_manager_registrationform_question_fieldtype').val() == 'Dropdown') {
$('#event_manager_registrationform_select_options').show();
} else {
$('#event_manager_registrationform_select_options').hide();
}
});
$('#event_manager_event_register').submit(function() {
if(($("input[name='question_name']").val() == "") || ($("input[name='question_email']").val() == "")){
elgg.register_error(elgg.echo("event_manager:registration:required_fields"));
return false;
}
error_found = false;
$("#event_manager_registration_form_fields .required").each(function(index, elem){
if($(this).hasClass("elgg-input-radios")){
if($(this).find("input[type='radio']:checked").length == 0){
error_found = true;
return false;
}
} else if($(this).val() == ""){
error_found = true;
return false;
}
});
if(error_found){
elgg.register_error(elgg.echo("event_manager:registration:required_fields"));
return false;
}
guids = [];
$.each($('.event_manager_program_participatetoslot'), function(i, value) {
elementId = $(value).attr('id');
if($(value).is(':checked')) {
guids.push(elementId.substring(9, elementId.length));
}
});
$('#event_manager_program_guids').val(guids.join(','));
});
$('#with_program').change(function() {
if($(this).is(':checked')) {
$('#event_manager_start_time_pulldown').css('display', 'none');
} else {
$('#event_manager_start_time_pulldown').css('display', 'table-row');
}
});
};
elgg.register_hook_handler('init', 'system', elgg.event_manager.init); | gpl-2.0 |
evelynn/ArkCORE-NG | src/server/game/Maps/Map.cpp | 126501 | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Map.h"
#include "Battleground.h"
#include "MMapFactory.h"
#include "CellImpl.h"
#include "Config.h"
#include "DynamicTree.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "GridStates.h"
#include "Group.h"
#include "InstanceScript.h"
#include "MapInstanced.h"
#include "MapManager.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Pet.h"
#include "ScriptMgr.h"
#include "Transport.h"
#include "Vehicle.h"
#include "VMapFactory.h"
//npcbot
#include "botmgr.h"
//end npcbot
u_map_magic MapMagic = { {'M','A','P','S'} };
u_map_magic MapVersionMagic = { {'v','1','.','3'} };
u_map_magic MapAreaMagic = { {'A','R','E','A'} };
u_map_magic MapHeightMagic = { {'M','H','G','T'} };
u_map_magic MapLiquidMagic = { {'M','L','I','Q'} };
#define DEFAULT_GRID_EXPIRY 300
#define MAX_GRID_LOAD_TIME 50
#define MAX_CREATURE_ATTACK_RADIUS (45.0f * sWorld->getRate(RATE_CREATURE_AGGRO))
GridState* si_GridStates[MAX_GRID_STATE];
Map::~Map()
{
sScriptMgr->OnDestroyMap(this);
UnloadAll();
while (!i_worldObjects.empty())
{
WorldObject* obj = *i_worldObjects.begin();
ASSERT(obj->IsWorldObject());
//ASSERT(obj->GetTypeId() == TYPEID_CORPSE);
obj->RemoveFromWorld();
obj->ResetMap();
}
if (!m_scriptSchedule.empty())
sScriptMgr->DecreaseScheduledScriptCount(m_scriptSchedule.size());
MMAP::MMapFactory::createOrGetMMapManager()->unloadMapInstance(GetId(), i_InstanceId);
}
bool Map::ExistMap(uint32 mapid, int gx, int gy)
{
int len = sWorld->GetDataPath().length() + strlen("maps/%03u%02u%02u.map") + 1;
char* fileName = new char[len];
snprintf(fileName, len, (char *)(sWorld->GetDataPath() + "maps/%03u%02u%02u.map").c_str(), mapid, gx, gy);
bool ret = false;
FILE* pf = fopen(fileName, "rb");
if (!pf)
TC_LOG_ERROR("maps", "Map file '%s': does not exist!", fileName);
else
{
map_fileheader header;
if (fread(&header, sizeof(header), 1, pf) == 1)
{
if (header.mapMagic.asUInt != MapMagic.asUInt || header.versionMagic.asUInt != MapVersionMagic.asUInt)
TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please recreate using the mapextractor.",
fileName, 4, header.mapMagic.asChar, 4, header.versionMagic.asChar, 4, MapMagic.asChar, 4, MapVersionMagic.asChar);
else
ret = true;
}
fclose(pf);
}
delete[] fileName;
return ret;
}
bool Map::ExistVMap(uint32 mapid, int gx, int gy)
{
if (VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
{
if (vmgr->isMapLoadingEnabled())
{
bool exists = vmgr->existsMap((sWorld->GetDataPath()+ "vmaps").c_str(), mapid, gx, gy);
if (!exists)
{
std::string name = vmgr->getDirFileName(mapid, gx, gy);
TC_LOG_ERROR("maps", "VMap file '%s' is missing or points to wrong version of vmap file. Redo vmaps with latest version of vmap_assembler.exe.", (sWorld->GetDataPath()+"vmaps/"+name).c_str());
return false;
}
}
}
return true;
}
void Map::LoadMMap(int gx, int gy)
{
bool mmapLoadResult = MMAP::MMapFactory::createOrGetMMapManager()->loadMap((sWorld->GetDataPath() + "mmaps").c_str(), GetId(), gx, gy);
if (mmapLoadResult)
TC_LOG_INFO("maps", "MMAP loaded name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy);
else
TC_LOG_INFO("maps", "Could not load MMAP name:%s, id:%d, x:%d, y:%d (mmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy);
}
void Map::LoadVMap(int gx, int gy)
{
// x and y are swapped !!
int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld->GetDataPath()+ "vmaps").c_str(), GetId(), gx, gy);
switch (vmapLoadResult)
{
case VMAP::VMAP_LOAD_RESULT_OK:
TC_LOG_INFO("maps", "VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy);
break;
case VMAP::VMAP_LOAD_RESULT_ERROR:
TC_LOG_INFO("maps", "Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy);
break;
case VMAP::VMAP_LOAD_RESULT_IGNORED:
TC_LOG_DEBUG("maps", "Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", GetMapName(), GetId(), gx, gy, gx, gy);
break;
}
}
void Map::LoadMap(int gx, int gy, bool reload)
{
if (i_InstanceId != 0)
{
if (GridMaps[gx][gy])
return;
// load grid map for base map
if (!m_parentMap->GridMaps[gx][gy])
m_parentMap->EnsureGridCreated_i(GridCoord(63-gx, 63-gy));
((MapInstanced*)(m_parentMap))->AddGridMapReference(GridCoord(gx, gy));
GridMaps[gx][gy] = m_parentMap->GridMaps[gx][gy];
return;
}
if (GridMaps[gx][gy] && !reload)
return;
//map already load, delete it before reloading (Is it necessary? Do we really need the ability the reload maps during runtime?)
if (GridMaps[gx][gy])
{
TC_LOG_INFO("maps", "Unloading previously loaded map %u before reloading.", GetId());
sScriptMgr->OnUnloadGridMap(this, GridMaps[gx][gy], gx, gy);
delete (GridMaps[gx][gy]);
GridMaps[gx][gy]=NULL;
}
// map file name
char* tmp = NULL;
int len = sWorld->GetDataPath().length() + strlen("maps/%03u%02u%02u.map") + 1;
tmp = new char[len];
snprintf(tmp, len, (char *)(sWorld->GetDataPath() + "maps/%03u%02u%02u.map").c_str(), GetId(), gx, gy);
TC_LOG_INFO("maps", "Loading map %s", tmp);
// loading data
GridMaps[gx][gy] = new GridMap();
if (!GridMaps[gx][gy]->loadData(tmp))
TC_LOG_ERROR("maps", "Error loading map file: \n %s\n", tmp);
delete[] tmp;
sScriptMgr->OnLoadGridMap(this, GridMaps[gx][gy], gx, gy);
}
void Map::LoadMapAndVMap(int gx, int gy)
{
LoadMap(gx, gy);
// Only load the data for the base map
if (i_InstanceId == 0)
{
LoadVMap(gx, gy);
LoadMMap(gx, gy);
}
}
void Map::InitStateMachine()
{
si_GridStates[GRID_STATE_INVALID] = new InvalidState;
si_GridStates[GRID_STATE_ACTIVE] = new ActiveState;
si_GridStates[GRID_STATE_IDLE] = new IdleState;
si_GridStates[GRID_STATE_REMOVAL] = new RemovalState;
}
void Map::DeleteStateMachine()
{
delete si_GridStates[GRID_STATE_INVALID];
delete si_GridStates[GRID_STATE_ACTIVE];
delete si_GridStates[GRID_STATE_IDLE];
delete si_GridStates[GRID_STATE_REMOVAL];
}
Map::Map(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent):
_creatureToMoveLock(false), _gameObjectsToMoveLock(false), _dynamicObjectsToMoveLock(false),
i_mapEntry(sMapStore.LookupEntry(id)), i_spawnMode(SpawnMode), i_InstanceId(InstanceId),
m_unloadTimer(0), m_VisibleDistance(DEFAULT_VISIBILITY_DISTANCE),
m_VisibilityNotifyPeriod(DEFAULT_VISIBILITY_NOTIFY_PERIOD),
m_activeNonPlayersIter(m_activeNonPlayers.end()), _transportsUpdateIter(_transports.end()),
i_gridExpiry(expiry),
i_scriptLock(false), _defaultLight(GetDefaultMapLight(id))
{
m_parentMap = (_parent ? _parent : this);
for (unsigned int idx=0; idx < MAX_NUMBER_OF_GRIDS; ++idx)
{
for (unsigned int j=0; j < MAX_NUMBER_OF_GRIDS; ++j)
{
//z code
GridMaps[idx][j] =NULL;
setNGrid(NULL, idx, j);
}
}
//lets initialize visibility distance for map
Map::InitVisibilityDistance();
sScriptMgr->OnCreateMap(this);
}
void Map::InitVisibilityDistance()
{
//init visibility for continents
m_VisibleDistance = World::GetMaxVisibleDistanceOnContinents();
m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodOnContinents();
}
// Template specialization of utility methods
template<class T>
void Map::AddToGrid(T* obj, Cell const& cell)
{
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
if (obj->IsWorldObject())
grid->GetGridType(cell.CellX(), cell.CellY()).template AddWorldObject<T>(obj);
else
grid->GetGridType(cell.CellX(), cell.CellY()).template AddGridObject<T>(obj);
}
template<>
void Map::AddToGrid(Creature* obj, Cell const& cell)
{
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
if (obj->IsWorldObject())
grid->GetGridType(cell.CellX(), cell.CellY()).AddWorldObject(obj);
else
grid->GetGridType(cell.CellX(), cell.CellY()).AddGridObject(obj);
obj->SetCurrentCell(cell);
}
template<>
void Map::AddToGrid(GameObject* obj, Cell const& cell)
{
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
grid->GetGridType(cell.CellX(), cell.CellY()).AddGridObject(obj);
obj->SetCurrentCell(cell);
}
template<>
void Map::AddToGrid(DynamicObject* obj, Cell const& cell)
{
NGridType* grid = getNGrid(cell.GridX(), cell.GridY());
grid->GetGridType(cell.CellX(), cell.CellY()).AddGridObject(obj);
obj->SetCurrentCell(cell);
}
template<class T>
void Map::SwitchGridContainers(T* /*obj*/, bool /*on*/) { }
template<>
void Map::SwitchGridContainers(Creature* obj, bool on)
{
ASSERT(!obj->IsPermanentWorldObject());
CellCoord p = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY());
if (!p.IsCoordValid())
{
TC_LOG_ERROR("maps", "Map::SwitchGridContainers: Object " UI64FMTD " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
if (!IsGridLoaded(GridCoord(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
TC_LOG_DEBUG("maps", "Switch object " UI64FMTD " from grid[%u, %u] %u", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y, on);
NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY());
ASSERT(ngrid != NULL);
GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY());
obj->RemoveFromGrid(); //This step is not really necessary but we want to do ASSERT in remove/add
if (on)
{
grid.AddWorldObject(obj);
AddWorldObject(obj);
}
else
{
grid.AddGridObject(obj);
RemoveWorldObject(obj);
}
obj->m_isTempWorldObject = on;
}
template<>
void Map::SwitchGridContainers(GameObject* obj, bool on)
{
ASSERT(!obj->IsPermanentWorldObject());
CellCoord p = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY());
if (!p.IsCoordValid())
{
TC_LOG_ERROR("maps", "Map::SwitchGridContainers: Object " UI64FMTD " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), p.x_coord, p.y_coord);
return;
}
Cell cell(p);
if (!IsGridLoaded(GridCoord(cell.data.Part.grid_x, cell.data.Part.grid_y)))
return;
TC_LOG_DEBUG("maps", "Switch object " UI64FMTD " from grid[%u, %u] %u", obj->GetGUID(), cell.data.Part.grid_x, cell.data.Part.grid_y, on);
NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY());
ASSERT(ngrid != NULL);
GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY());
obj->RemoveFromGrid(); //This step is not really necessary but we want to do ASSERT in remove/add
if (on)
{
grid.AddWorldObject(obj);
AddWorldObject(obj);
}
else
{
grid.AddGridObject(obj);
RemoveWorldObject(obj);
}
}
template<class T>
void Map::DeleteFromWorld(T* obj)
{
// Note: In case resurrectable corpse and pet its removed from global lists in own destructor
delete obj;
}
template<>
void Map::DeleteFromWorld(Player* player)
{
sObjectAccessor->RemoveObject(player);
sObjectAccessor->RemoveUpdateObject(player); /// @todo I do not know why we need this, it should be removed in ~Object anyway
delete player;
}
void Map::EnsureGridCreated(const GridCoord &p)
{
TRINITY_GUARD(ACE_Thread_Mutex, GridLock);
EnsureGridCreated_i(p);
}
//Create NGrid so the object can be added to it
//But object data is not loaded here
void Map::EnsureGridCreated_i(const GridCoord &p)
{
if (!getNGrid(p.x_coord, p.y_coord))
{
TC_LOG_DEBUG("maps", "Creating grid[%u, %u] for map %u instance %u", p.x_coord, p.y_coord, GetId(), i_InstanceId);
setNGrid(new NGridType(p.x_coord*MAX_NUMBER_OF_GRIDS + p.y_coord, p.x_coord, p.y_coord, i_gridExpiry, sWorld->getBoolConfig(CONFIG_GRID_UNLOAD)),
p.x_coord, p.y_coord);
// build a linkage between this map and NGridType
buildNGridLinkage(getNGrid(p.x_coord, p.y_coord));
getNGrid(p.x_coord, p.y_coord)->SetGridState(GRID_STATE_IDLE);
//z coord
int gx = (MAX_NUMBER_OF_GRIDS - 1) - p.x_coord;
int gy = (MAX_NUMBER_OF_GRIDS - 1) - p.y_coord;
if (!GridMaps[gx][gy])
LoadMapAndVMap(gx, gy);
}
}
//Load NGrid and make it active
void Map::EnsureGridLoadedForActiveObject(const Cell &cell, WorldObject* object)
{
EnsureGridLoaded(cell);
NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
ASSERT(grid != NULL);
// refresh grid state & timer
if (grid->GetGridState() != GRID_STATE_ACTIVE)
{
TC_LOG_DEBUG("maps", "Active object " UI64FMTD " triggers loading of grid [%u, %u] on map %u", object->GetGUID(), cell.GridX(), cell.GridY(), GetId());
ResetGridExpiry(*grid, 0.1f);
grid->SetGridState(GRID_STATE_ACTIVE);
}
}
//Create NGrid and load the object data in it
bool Map::EnsureGridLoaded(const Cell &cell)
{
EnsureGridCreated(GridCoord(cell.GridX(), cell.GridY()));
NGridType *grid = getNGrid(cell.GridX(), cell.GridY());
ASSERT(grid != NULL);
if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY()))
{
TC_LOG_DEBUG("maps", "Loading grid[%u, %u] for map %u instance %u", cell.GridX(), cell.GridY(), GetId(), i_InstanceId);
setGridObjectDataLoaded(true, cell.GridX(), cell.GridY());
ObjectGridLoader loader(*grid, this, cell);
loader.LoadN();
// Add resurrectable corpses to world object list in grid
sObjectAccessor->AddCorpsesToGrid(GridCoord(cell.GridX(), cell.GridY()), grid->GetGridType(cell.CellX(), cell.CellY()), this);
Balance();
return true;
}
return false;
}
void Map::LoadGrid(float x, float y)
{
EnsureGridLoaded(Cell(x, y));
}
bool Map::AddPlayerToMap(Player* player)
{
CellCoord cellCoord = Trinity::ComputeCellCoord(player->GetPositionX(), player->GetPositionY());
if (!cellCoord.IsCoordValid())
{
TC_LOG_ERROR("maps", "Map::Add: Player (GUID: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", player->GetGUIDLow(), player->GetPositionX(), player->GetPositionY(), cellCoord.x_coord, cellCoord.y_coord);
return false;
}
Cell cell(cellCoord);
EnsureGridLoadedForActiveObject(cell, player);
AddToGrid(player, cell);
// Check if we are adding to correct map
ASSERT (player->GetMap() == this);
player->SetMap(this);
player->AddToWorld();
SendInitSelf(player);
SendInitTransports(player);
SendZoneDynamicInfo(player);
player->m_clientGUIDs.clear();
player->UpdateObjectVisibility(false);
sScriptMgr->OnPlayerEnterMap(this, player);
return true;
}
template<class T>
void Map::InitializeObject(T* /*obj*/) { }
template<>
void Map::InitializeObject(Creature* obj)
{
obj->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
}
template<>
void Map::InitializeObject(GameObject* obj)
{
obj->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
}
template<class T>
bool Map::AddToMap(T* obj)
{
/// @todo Needs clean up. An object should not be added to map twice.
if (obj->IsInWorld())
{
ASSERT(obj->IsInGrid());
obj->UpdateObjectVisibility(true);
return true;
}
CellCoord cellCoord = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY());
//It will create many problems (including crashes) if an object is not added to grid after creation
//The correct way to fix it is to make AddToMap return false and delete the object if it is not added to grid
//But now AddToMap is used in too many places, I will just see how many ASSERT failures it will cause
ASSERT(cellCoord.IsCoordValid());
if (!cellCoord.IsCoordValid())
{
TC_LOG_ERROR("maps", "Map::Add: Object " UI64FMTD " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), cellCoord.x_coord, cellCoord.y_coord);
return false; //Should delete object
}
Cell cell(cellCoord);
if (obj->isActiveObject())
EnsureGridLoadedForActiveObject(cell, obj);
else
EnsureGridCreated(GridCoord(cell.GridX(), cell.GridY()));
AddToGrid(obj, cell);
TC_LOG_DEBUG("maps", "Object %u enters grid[%u, %u]", GUID_LOPART(obj->GetGUID()), cell.GridX(), cell.GridY());
//Must already be set before AddToMap. Usually during obj->Create.
//obj->SetMap(this);
obj->AddToWorld();
InitializeObject(obj);
if (obj->isActiveObject())
AddToActive(obj);
//something, such as vehicle, needs to be update immediately
//also, trigger needs to cast spell, if not update, cannot see visual
obj->UpdateObjectVisibility(true);
return true;
}
template<>
bool Map::AddToMap(Transport* obj)
{
//TODO: Needs clean up. An object should not be added to map twice.
if (obj->IsInWorld())
return true;
CellCoord cellCoord = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY());
if (!cellCoord.IsCoordValid())
{
TC_LOG_ERROR("maps", "Map::Add: Object " UI64FMTD " has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUID(), obj->GetPositionX(), obj->GetPositionY(), cellCoord.x_coord, cellCoord.y_coord);
return false; //Should delete object
}
obj->AddToWorld();
_transports.insert(obj);
// Broadcast creation to players
if (!GetPlayers().isEmpty())
{
for (Map::PlayerList::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr)
{
if (itr->GetSource()->GetTransport() != obj)
{
UpdateData data(GetId());
obj->BuildCreateUpdateBlockForPlayer(&data, itr->GetSource());
WorldPacket packet;
data.BuildPacket(&packet);
itr->GetSource()->SendDirectMessage(&packet);
}
}
}
return true;
}
bool Map::IsGridLoaded(const GridCoord &p) const
{
return (getNGrid(p.x_coord, p.y_coord) && isGridObjectDataLoaded(p.x_coord, p.y_coord));
}
void Map::VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor<Trinity::ObjectUpdater, GridTypeMapContainer> &gridVisitor, TypeContainerVisitor<Trinity::ObjectUpdater, WorldTypeMapContainer> &worldVisitor)
{
// Check for valid position
if (!obj->IsPositionValid())
return;
// Update mobs/objects in ALL visible cells around object!
CellArea area = Cell::CalculateCellArea(obj->GetPositionX(), obj->GetPositionY(), obj->GetGridActivationRange());
for (uint32 x = area.low_bound.x_coord; x <= area.high_bound.x_coord; ++x)
{
for (uint32 y = area.low_bound.y_coord; y <= area.high_bound.y_coord; ++y)
{
// marked cells are those that have been visited
// don't visit the same cell twice
uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
if (isCellMarked(cell_id))
continue;
markCell(cell_id);
CellCoord pair(x, y);
Cell cell(pair);
cell.SetNoCreate();
Visit(cell, gridVisitor);
Visit(cell, worldVisitor);
}
}
}
void Map::Update(const uint32 t_diff)
{
_dynamicTree.update(t_diff);
/// update worldsessions for existing players
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* player = m_mapRefIter->GetSource();
if (player && player->IsInWorld())
{
//player->Update(t_diff);
WorldSession* session = player->GetSession();
MapSessionFilter updater(session);
session->Update(t_diff, updater);
}
}
/// update active cells around players and active objects
resetMarkedCells();
Trinity::ObjectUpdater updater(t_diff);
// for creature
TypeContainerVisitor<Trinity::ObjectUpdater, GridTypeMapContainer > grid_object_update(updater);
// for pets
TypeContainerVisitor<Trinity::ObjectUpdater, WorldTypeMapContainer > world_object_update(updater);
// the player iterator is stored in the map object
// to make sure calls to Map::Remove don't invalidate it
for (m_mapRefIter = m_mapRefManager.begin(); m_mapRefIter != m_mapRefManager.end(); ++m_mapRefIter)
{
Player* player = m_mapRefIter->GetSource();
if (!player || !player->IsInWorld())
continue;
// update players at tick
player->Update(t_diff);
VisitNearbyCellsOf(player, grid_object_update, world_object_update);
}
// non-player active objects, increasing iterator in the loop in case of object removal
for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end();)
{
WorldObject* obj = *m_activeNonPlayersIter;
++m_activeNonPlayersIter;
if (!obj || !obj->IsInWorld())
continue;
VisitNearbyCellsOf(obj, grid_object_update, world_object_update);
}
for (_transportsUpdateIter = _transports.begin(); _transportsUpdateIter != _transports.end();)
{
WorldObject* obj = *_transportsUpdateIter;
++_transportsUpdateIter;
if (!obj->IsInWorld())
continue;
obj->Update(t_diff);
}
///- Process necessary scripts
if (!m_scriptSchedule.empty())
{
i_scriptLock = true;
ScriptsProcess();
i_scriptLock = false;
}
MoveAllCreaturesInMoveList();
MoveAllGameObjectsInMoveList();
if (!m_mapRefManager.isEmpty() || !m_activeNonPlayers.empty())
ProcessRelocationNotifies(t_diff);
sScriptMgr->OnMapUpdate(this, t_diff);
}
struct ResetNotifier
{
template<class T>inline void resetNotify(GridRefManager<T> &m)
{
for (typename GridRefManager<T>::iterator iter=m.begin(); iter != m.end(); ++iter)
iter->GetSource()->ResetAllNotifies();
}
template<class T> void Visit(GridRefManager<T> &) { }
void Visit(CreatureMapType &m) { resetNotify<Creature>(m);}
void Visit(PlayerMapType &m) { resetNotify<Player>(m);}
};
void Map::ProcessRelocationNotifies(const uint32 diff)
{
for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); ++i)
{
NGridType *grid = i->GetSource();
if (grid->GetGridState() != GRID_STATE_ACTIVE)
continue;
grid->getGridInfoRef()->getRelocationTimer().TUpdate(diff);
if (!grid->getGridInfoRef()->getRelocationTimer().TPassed())
continue;
uint32 gx = grid->getX(), gy = grid->getY();
CellCoord cell_min(gx*MAX_NUMBER_OF_CELLS, gy*MAX_NUMBER_OF_CELLS);
CellCoord cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
for (uint32 x = cell_min.x_coord; x < cell_max.x_coord; ++x)
{
for (uint32 y = cell_min.y_coord; y < cell_max.y_coord; ++y)
{
uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
if (!isCellMarked(cell_id))
continue;
CellCoord pair(x, y);
Cell cell(pair);
cell.SetNoCreate();
Trinity::DelayedUnitRelocation cell_relocation(cell, pair, *this, MAX_VISIBILITY_DISTANCE);
TypeContainerVisitor<Trinity::DelayedUnitRelocation, GridTypeMapContainer > grid_object_relocation(cell_relocation);
TypeContainerVisitor<Trinity::DelayedUnitRelocation, WorldTypeMapContainer > world_object_relocation(cell_relocation);
Visit(cell, grid_object_relocation);
Visit(cell, world_object_relocation);
}
}
}
ResetNotifier reset;
TypeContainerVisitor<ResetNotifier, GridTypeMapContainer > grid_notifier(reset);
TypeContainerVisitor<ResetNotifier, WorldTypeMapContainer > world_notifier(reset);
for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end(); ++i)
{
NGridType *grid = i->GetSource();
if (grid->GetGridState() != GRID_STATE_ACTIVE)
continue;
if (!grid->getGridInfoRef()->getRelocationTimer().TPassed())
continue;
grid->getGridInfoRef()->getRelocationTimer().TReset(diff, m_VisibilityNotifyPeriod);
uint32 gx = grid->getX(), gy = grid->getY();
CellCoord cell_min(gx*MAX_NUMBER_OF_CELLS, gy*MAX_NUMBER_OF_CELLS);
CellCoord cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
for (uint32 x = cell_min.x_coord; x < cell_max.x_coord; ++x)
{
for (uint32 y = cell_min.y_coord; y < cell_max.y_coord; ++y)
{
uint32 cell_id = (y * TOTAL_NUMBER_OF_CELLS_PER_MAP) + x;
if (!isCellMarked(cell_id))
continue;
CellCoord pair(x, y);
Cell cell(pair);
cell.SetNoCreate();
Visit(cell, grid_notifier);
Visit(cell, world_notifier);
}
}
}
}
void Map::RemovePlayerFromMap(Player* player, bool remove)
{
sScriptMgr->OnPlayerLeaveMap(this, player);
player->RemoveFromWorld();
SendRemoveTransports(player);
player->UpdateObjectVisibility(true);
if (player->IsInGrid())
player->RemoveFromGrid();
else
ASSERT(remove); //maybe deleted in logoutplayer when player is not in a map
if (remove)
DeleteFromWorld(player);
}
template<class T>
void Map::RemoveFromMap(T *obj, bool remove)
{
obj->RemoveFromWorld();
if (obj->isActiveObject())
RemoveFromActive(obj);
obj->UpdateObjectVisibility(true);
obj->RemoveFromGrid();
obj->ResetMap();
if (remove)
{
// if option set then object already saved at this moment
if (!sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
obj->SaveRespawnTime();
DeleteFromWorld(obj);
}
}
template<>
void Map::RemoveFromMap(Transport* obj, bool remove)
{
obj->RemoveFromWorld();
Map::PlayerList const& players = GetPlayers();
if (!players.isEmpty())
{
UpdateData data(GetId());
obj->BuildOutOfRangeUpdateBlock(&data);
WorldPacket packet;
data.BuildPacket(&packet);
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (itr->GetSource()->GetTransport() != obj)
itr->GetSource()->SendDirectMessage(&packet);
}
if (_transportsUpdateIter != _transports.end())
{
TransportsContainer::iterator itr = _transports.find(obj);
if (itr == _transports.end())
return;
if (itr == _transportsUpdateIter)
++_transportsUpdateIter;
_transports.erase(itr);
}
else
_transports.erase(obj);
obj->ResetMap();
if (remove)
{
// if option set then object already saved at this moment
if (!sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY))
obj->SaveRespawnTime();
DeleteFromWorld(obj);
}
}
void Map::PlayerRelocation(Player* player, float x, float y, float z, float orientation)
{
ASSERT(player);
Cell old_cell(player->GetPositionX(), player->GetPositionY());
Cell new_cell(x, y);
//! If hovering, always increase our server-side Z position
//! Client automatically projects correct position based on Z coord sent in monster move
//! and UNIT_FIELD_HOVERHEIGHT sent in object updates
if (player->HasUnitMovementFlag(MOVEMENTFLAG_HOVER))
z += player->GetFloatValue(UNIT_FIELD_HOVERHEIGHT);
player->Relocate(x, y, z, orientation);
if (player->IsVehicle())
player->GetVehicleKit()->RelocatePassengers();
if (old_cell.DiffGrid(new_cell) || old_cell.DiffCell(new_cell))
{
TC_LOG_DEBUG("maps", "Player %s relocation grid[%u, %u]cell[%u, %u]->grid[%u, %u]cell[%u, %u]", player->GetName().c_str(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
player->RemoveFromGrid();
if (old_cell.DiffGrid(new_cell))
EnsureGridLoadedForActiveObject(new_cell, player);
AddToGrid(player, new_cell);
}
player->UpdateObjectVisibility(false);
}
void Map::CreatureRelocation(Creature* creature, float x, float y, float z, float ang, bool respawnRelocationOnFail)
{
ASSERT(CheckGridIntegrity(creature, false));
Cell old_cell = creature->GetCurrentCell();
Cell new_cell(x, y);
if (!respawnRelocationOnFail && !getNGrid(new_cell.GridX(), new_cell.GridY()))
return;
//! If hovering, always increase our server-side Z position
//! Client automatically projects correct position based on Z coord sent in monster move
//! and UNIT_FIELD_HOVERHEIGHT sent in object updates
if (creature->HasUnitMovementFlag(MOVEMENTFLAG_HOVER))
z += creature->GetFloatValue(UNIT_FIELD_HOVERHEIGHT);
// delay creature move for grid/cell to grid/cell moves
if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) added to moving list from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", creature->GetGUIDLow(), creature->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
AddCreatureToMoveList(creature, x, y, z, ang);
// in diffcell/diffgrid case notifiers called at finishing move creature in Map::MoveAllCreaturesInMoveList
}
else
{
creature->Relocate(x, y, z, ang);
if (creature->IsVehicle())
creature->GetVehicleKit()->RelocatePassengers();
creature->UpdateObjectVisibility(false);
RemoveCreatureFromMoveList(creature);
}
ASSERT(CheckGridIntegrity(creature, true));
}
void Map::GameObjectRelocation(GameObject* go, float x, float y, float z, float orientation, bool respawnRelocationOnFail)
{
Cell integrity_check(go->GetPositionX(), go->GetPositionY());
Cell old_cell = go->GetCurrentCell();
ASSERT(integrity_check == old_cell);
Cell new_cell(x, y);
if (!respawnRelocationOnFail && !getNGrid(new_cell.GridX(), new_cell.GridY()))
return;
// delay creature move for grid/cell to grid/cell moves
if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) added to moving list from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
AddGameObjectToMoveList(go, x, y, z, orientation);
// in diffcell/diffgrid case notifiers called at finishing move go in Map::MoveAllGameObjectsInMoveList
}
else
{
go->Relocate(x, y, z, orientation);
go->UpdateModelPosition();
go->UpdateObjectVisibility(false);
RemoveGameObjectFromMoveList(go);
}
old_cell = go->GetCurrentCell();
integrity_check = Cell(go->GetPositionX(), go->GetPositionY());
ASSERT(integrity_check == old_cell);
}
void Map::DynamicObjectRelocation(DynamicObject* dynObj, float x, float y, float z, float orientation)
{
Cell integrity_check(dynObj->GetPositionX(), dynObj->GetPositionY());
Cell old_cell = dynObj->GetCurrentCell();
ASSERT(integrity_check == old_cell);
Cell new_cell(x, y);
if (!getNGrid(new_cell.GridX(), new_cell.GridY()))
return;
// delay creature move for grid/cell to grid/cell moves
if (old_cell.DiffCell(new_cell) || old_cell.DiffGrid(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u) added to moving list from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", dynObj->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
AddDynamicObjectToMoveList(dynObj, x, y, z, orientation);
// in diffcell/diffgrid case notifiers called at finishing move dynObj in Map::MoveAllGameObjectsInMoveList
}
else
{
dynObj->Relocate(x, y, z, orientation);
dynObj->UpdateObjectVisibility(false);
RemoveDynamicObjectFromMoveList(dynObj);
}
old_cell = dynObj->GetCurrentCell();
integrity_check = Cell(dynObj->GetPositionX(), dynObj->GetPositionY());
ASSERT(integrity_check == old_cell);
}
void Map::AddCreatureToMoveList(Creature* c, float x, float y, float z, float ang)
{
if (_creatureToMoveLock) //can this happen?
return;
if (c->_moveState == MAP_OBJECT_CELL_MOVE_NONE)
_creaturesToMove.push_back(c);
c->SetNewCellPosition(x, y, z, ang);
}
void Map::RemoveCreatureFromMoveList(Creature* c)
{
if (_creatureToMoveLock) //can this happen?
return;
if (c->_moveState == MAP_OBJECT_CELL_MOVE_ACTIVE)
c->_moveState = MAP_OBJECT_CELL_MOVE_INACTIVE;
}
void Map::AddGameObjectToMoveList(GameObject* go, float x, float y, float z, float ang)
{
if (_gameObjectsToMoveLock) //can this happen?
return;
if (go->_moveState == MAP_OBJECT_CELL_MOVE_NONE)
_gameObjectsToMove.push_back(go);
go->SetNewCellPosition(x, y, z, ang);
}
void Map::RemoveGameObjectFromMoveList(GameObject* go)
{
if (_gameObjectsToMoveLock) //can this happen?
return;
if (go->_moveState == MAP_OBJECT_CELL_MOVE_ACTIVE)
go->_moveState = MAP_OBJECT_CELL_MOVE_INACTIVE;
}
void Map::AddDynamicObjectToMoveList(DynamicObject* dynObj, float x, float y, float z, float ang)
{
if (_dynamicObjectsToMoveLock) //can this happen?
return;
if (dynObj->_moveState == MAP_OBJECT_CELL_MOVE_NONE)
_dynamicObjectsToMove.push_back(dynObj);
dynObj->SetNewCellPosition(x, y, z, ang);
}
void Map::RemoveDynamicObjectFromMoveList(DynamicObject* dynObj)
{
if (_dynamicObjectsToMoveLock) //can this happen?
return;
if (dynObj->_moveState == MAP_OBJECT_CELL_MOVE_ACTIVE)
dynObj->_moveState = MAP_OBJECT_CELL_MOVE_INACTIVE;
}
void Map::MoveAllCreaturesInMoveList()
{
_creatureToMoveLock = true;
for (std::vector<Creature*>::iterator itr = _creaturesToMove.begin(); itr != _creaturesToMove.end(); ++itr)
{
Creature* c = *itr;
if (c->FindMap() != this) //pet is teleported to another map
continue;
if (c->_moveState != MAP_OBJECT_CELL_MOVE_ACTIVE)
{
c->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
continue;
}
c->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
if (!c->IsInWorld())
continue;
// do move or do move to respawn or remove creature if previous all fail
if (CreatureCellRelocation(c, Cell(c->_newPosition.m_positionX, c->_newPosition.m_positionY)))
{
// update pos
c->Relocate(c->_newPosition);
if (c->IsVehicle())
c->GetVehicleKit()->RelocatePassengers();
//CreatureRelocationNotify(c, new_cell, new_cell.cellCoord());
c->UpdateObjectVisibility(false);
}
else
{
// if creature can't be move in new cell/grid (not loaded) move it to repawn cell/grid
// creature coordinates will be updated and notifiers send
if (!CreatureRespawnRelocation(c, false))
{
// ... or unload (if respawn grid also not loaded)
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) cannot be move to unloaded respawn grid.", c->GetGUIDLow(), c->GetEntry());
#endif
//AddObjectToRemoveList(Pet*) should only be called in Pet::Remove
//This may happen when a player just logs in and a pet moves to a nearby unloaded cell
//To avoid this, we can load nearby cells when player log in
//But this check is always needed to ensure safety
/// @todo pets will disappear if this is outside CreatureRespawnRelocation
//need to check why pet is frequently relocated to an unloaded cell
if (c->IsPet())
((Pet*)c)->Remove(PET_SAVE_NOT_IN_SLOT, true);
else
AddObjectToRemoveList(c);
}
}
}
_creaturesToMove.clear();
_creatureToMoveLock = false;
}
void Map::MoveAllGameObjectsInMoveList()
{
_gameObjectsToMoveLock = true;
for (std::vector<GameObject*>::iterator itr = _gameObjectsToMove.begin(); itr != _gameObjectsToMove.end(); ++itr)
{
GameObject* go = *itr;
if (go->FindMap() != this) //transport is teleported to another map
continue;
if (go->_moveState != MAP_OBJECT_CELL_MOVE_ACTIVE)
{
go->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
continue;
}
go->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
if (!go->IsInWorld())
continue;
// do move or do move to respawn or remove creature if previous all fail
if (GameObjectCellRelocation(go, Cell(go->_newPosition.m_positionX, go->_newPosition.m_positionY)))
{
// update pos
go->Relocate(go->_newPosition);
go->UpdateModelPosition();
go->UpdateObjectVisibility(false);
}
else
{
// if GameObject can't be move in new cell/grid (not loaded) move it to repawn cell/grid
// GameObject coordinates will be updated and notifiers send
if (!GameObjectRespawnRelocation(go, false))
{
// ... or unload (if respawn grid also not loaded)
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) cannot be move to unloaded respawn grid.", go->GetGUIDLow(), go->GetEntry());
#endif
AddObjectToRemoveList(go);
}
}
}
_gameObjectsToMove.clear();
_gameObjectsToMoveLock = false;
}
void Map::MoveAllDynamicObjectsInMoveList()
{
_dynamicObjectsToMoveLock = true;
for (std::vector<DynamicObject*>::iterator itr = _dynamicObjectsToMove.begin(); itr != _dynamicObjectsToMove.end(); ++itr)
{
DynamicObject* dynObj = *itr;
if (dynObj->FindMap() != this) //transport is teleported to another map
continue;
if (dynObj->_moveState != MAP_OBJECT_CELL_MOVE_ACTIVE)
{
dynObj->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
continue;
}
dynObj->_moveState = MAP_OBJECT_CELL_MOVE_NONE;
if (!dynObj->IsInWorld())
continue;
// do move or do move to respawn or remove creature if previous all fail
if (DynamicObjectCellRelocation(dynObj, Cell(dynObj->_newPosition.m_positionX, dynObj->_newPosition.m_positionY)))
{
// update pos
dynObj->Relocate(dynObj->_newPosition);
dynObj->UpdateObjectVisibility(false);
}
else
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "DynamicObject (GUID: %u) cannot be moved to unloaded grid.", dynObj->GetGUIDLow());
#endif
}
}
_dynamicObjectsToMove.clear();
_dynamicObjectsToMoveLock = false;
}
bool Map::CreatureCellRelocation(Creature* c, Cell new_cell)
{
Cell const& old_cell = c->GetCurrentCell();
if (!old_cell.DiffGrid(new_cell)) // in same grid
{
// if in same cell then none do
if (old_cell.DiffCell(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) moved in grid[%u, %u] from cell[%u, %u] to cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
#endif
c->RemoveFromGrid();
AddToGrid(c, new_cell);
}
else
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) moved in same grid[%u, %u]cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
#endif
}
return true;
}
// in diff. grids but active creature
if (c->isActiveObject())
{
EnsureGridLoadedForActiveObject(new_cell, c);
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Active creature (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
c->RemoveFromGrid();
AddToGrid(c, new_cell);
return true;
}
// in diff. loaded grid normal creature
if (IsGridLoaded(GridCoord(new_cell.GridX(), new_cell.GridY())))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
c->RemoveFromGrid();
EnsureGridCreated(GridCoord(new_cell.GridX(), new_cell.GridY()));
AddToGrid(c, new_cell);
return true;
}
// fail to move: normal creature attempt move to unloaded grid
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) attempted to move from grid[%u, %u]cell[%u, %u] to unloaded grid[%u, %u]cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
return false;
}
bool Map::GameObjectCellRelocation(GameObject* go, Cell new_cell)
{
Cell const& old_cell = go->GetCurrentCell();
if (!old_cell.DiffGrid(new_cell)) // in same grid
{
// if in same cell then none do
if (old_cell.DiffCell(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) moved in grid[%u, %u] from cell[%u, %u] to cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
AddToGrid(go, new_cell);
}
else
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) moved in same grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
#endif
}
return true;
}
// in diff. grids but active GameObject
if (go->isActiveObject())
{
EnsureGridLoadedForActiveObject(new_cell, go);
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Active GameObject (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
AddToGrid(go, new_cell);
return true;
}
// in diff. loaded grid normal GameObject
if (IsGridLoaded(GridCoord(new_cell.GridX(), new_cell.GridY())))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
EnsureGridCreated(GridCoord(new_cell.GridX(), new_cell.GridY()));
AddToGrid(go, new_cell);
return true;
}
// fail to move: normal GameObject attempt move to unloaded grid
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) attempted to move from grid[%u, %u]cell[%u, %u] to unloaded grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
return false;
}
bool Map::DynamicObjectCellRelocation(DynamicObject* go, Cell new_cell)
{
Cell const& old_cell = go->GetCurrentCell();
if (!old_cell.DiffGrid(new_cell)) // in same grid
{
// if in same cell then none do
if (old_cell.DiffCell(new_cell))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "DynamicObject (GUID: %u) moved in grid[%u, %u] from cell[%u, %u] to cell[%u, %u].", go->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
AddToGrid(go, new_cell);
}
else
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "DynamicObject (GUID: %u) moved in same grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY());
#endif
}
return true;
}
// in diff. grids but active GameObject
if (go->isActiveObject())
{
EnsureGridLoadedForActiveObject(new_cell, go);
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Active DynamicObject (GUID: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
AddToGrid(go, new_cell);
return true;
}
// in diff. loaded grid normal GameObject
if (IsGridLoaded(GridCoord(new_cell.GridX(), new_cell.GridY())))
{
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "DynamicObject (GUID: %u) moved from grid[%u, %u]cell[%u, %u] to grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
go->RemoveFromGrid();
EnsureGridCreated(GridCoord(new_cell.GridX(), new_cell.GridY()));
AddToGrid(go, new_cell);
return true;
}
// fail to move: normal GameObject attempt move to unloaded grid
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "DynamicObject (GUID: %u) attempted to move from grid[%u, %u]cell[%u, %u] to unloaded grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), old_cell.GridX(), old_cell.GridY(), old_cell.CellX(), old_cell.CellY(), new_cell.GridX(), new_cell.GridY(), new_cell.CellX(), new_cell.CellY());
#endif
return false;
}
bool Map::CreatureRespawnRelocation(Creature* c, bool diffGridOnly)
{
float resp_x, resp_y, resp_z, resp_o;
c->GetRespawnPosition(resp_x, resp_y, resp_z, &resp_o);
Cell resp_cell(resp_x, resp_y);
//creature will be unloaded with grid
if (diffGridOnly && !c->GetCurrentCell().DiffGrid(resp_cell))
return true;
c->CombatStop();
c->GetMotionMaster()->Clear();
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "Creature (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to respawn grid[%u, %u]cell[%u, %u].", c->GetGUIDLow(), c->GetEntry(), c->GetCurrentCell().GridX(), c->GetCurrentCell().GridY(), c->GetCurrentCell().CellX(), c->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
#endif
// teleport it to respawn point (like normal respawn if player see)
if (CreatureCellRelocation(c, resp_cell))
{
c->Relocate(resp_x, resp_y, resp_z, resp_o);
c->GetMotionMaster()->Initialize(); // prevent possible problems with default move generators
//CreatureRelocationNotify(c, resp_cell, resp_cell.GetCellCoord());
c->UpdateObjectVisibility(false);
return true;
}
return false;
}
bool Map::GameObjectRespawnRelocation(GameObject* go, bool diffGridOnly)
{
float resp_x, resp_y, resp_z, resp_o;
go->GetRespawnPosition(resp_x, resp_y, resp_z, &resp_o);
Cell resp_cell(resp_x, resp_y);
//GameObject will be unloaded with grid
if (diffGridOnly && !go->GetCurrentCell().DiffGrid(resp_cell))
return true;
#ifdef TRINITY_DEBUG
TC_LOG_DEBUG("maps", "GameObject (GUID: %u Entry: %u) moved from grid[%u, %u]cell[%u, %u] to respawn grid[%u, %u]cell[%u, %u].", go->GetGUIDLow(), go->GetEntry(), go->GetCurrentCell().GridX(), go->GetCurrentCell().GridY(), go->GetCurrentCell().CellX(), go->GetCurrentCell().CellY(), resp_cell.GridX(), resp_cell.GridY(), resp_cell.CellX(), resp_cell.CellY());
#endif
// teleport it to respawn point (like normal respawn if player see)
if (GameObjectCellRelocation(go, resp_cell))
{
go->Relocate(resp_x, resp_y, resp_z, resp_o);
go->UpdateObjectVisibility(false);
return true;
}
return false;
}
bool Map::UnloadGrid(NGridType& ngrid, bool unloadAll)
{
const uint32 x = ngrid.getX();
const uint32 y = ngrid.getY();
{
if (!unloadAll)
{
//pets, possessed creatures (must be active), transport passengers
if (ngrid.GetWorldObjectCountInNGrid<Creature>())
return false;
if (ActiveObjectsNearGrid(ngrid))
return false;
}
TC_LOG_DEBUG("maps", "Unloading grid[%u, %u] for map %u", x, y, GetId());
if (!unloadAll)
{
// Finish creature moves, remove and delete all creatures with delayed remove before moving to respawn grids
// Must know real mob position before move
MoveAllCreaturesInMoveList();
MoveAllGameObjectsInMoveList();
// move creatures to respawn grids if this is diff.grid or to remove list
ObjectGridEvacuator worker;
TypeContainerVisitor<ObjectGridEvacuator, GridTypeMapContainer> visitor(worker);
ngrid.VisitAllGrids(visitor);
// Finish creature moves, remove and delete all creatures with delayed remove before unload
MoveAllCreaturesInMoveList();
MoveAllGameObjectsInMoveList();
}
{
ObjectGridCleaner worker;
TypeContainerVisitor<ObjectGridCleaner, GridTypeMapContainer> visitor(worker);
ngrid.VisitAllGrids(visitor);
}
RemoveAllObjectsInRemoveList();
{
ObjectGridUnloader worker;
TypeContainerVisitor<ObjectGridUnloader, GridTypeMapContainer> visitor(worker);
ngrid.VisitAllGrids(visitor);
}
ASSERT(i_objectsToRemove.empty());
delete &ngrid;
setNGrid(NULL, x, y);
}
int gx = (MAX_NUMBER_OF_GRIDS - 1) - x;
int gy = (MAX_NUMBER_OF_GRIDS - 1) - y;
// delete grid map, but don't delete if it is from parent map (and thus only reference)
//+++if (GridMaps[gx][gy]) don't check for GridMaps[gx][gy], we might have to unload vmaps
{
if (i_InstanceId == 0)
{
if (GridMaps[gx][gy])
{
GridMaps[gx][gy]->unloadData();
delete GridMaps[gx][gy];
}
VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(GetId(), gx, gy);
MMAP::MMapFactory::createOrGetMMapManager()->unloadMap(GetId(), gx, gy);
}
else
((MapInstanced*)m_parentMap)->RemoveGridMapReference(GridCoord(gx, gy));
GridMaps[gx][gy] = NULL;
}
TC_LOG_DEBUG("maps", "Unloading grid[%u, %u] for map %u finished", x, y, GetId());
return true;
}
void Map::RemoveAllPlayers()
{
if (HavePlayers())
{
for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
{
Player* player = itr->GetSource();
if (!player->IsBeingTeleportedFar())
{
// this is happening for bg
TC_LOG_ERROR("maps", "Map::UnloadAll: player %s is still in map %u during unload, this should not happen!", player->GetName().c_str(), GetId());
player->TeleportTo(player->m_homebindMapId, player->m_homebindX, player->m_homebindY, player->m_homebindZ, player->GetOrientation());
}
}
}
}
void Map::UnloadAll()
{
// clear all delayed moves, useless anyway do this moves before map unload.
_creaturesToMove.clear();
_gameObjectsToMove.clear();
for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
{
NGridType &grid(*i->GetSource());
++i;
UnloadGrid(grid, true); // deletes the grid and removes it from the GridRefManager
}
for (TransportsContainer::iterator itr = _transports.begin(); itr != _transports.end();)
{
Transport* transport = *itr;
++itr;
transport->RemoveFromWorld();
delete transport;
}
_transports.clear();
}
// *****************************
// Grid function
// *****************************
GridMap::GridMap()
{
_flags = 0;
// Area data
_gridArea = 0;
_areaMap = NULL;
// Height level data
_gridHeight = INVALID_HEIGHT;
_gridGetHeight = &GridMap::getHeightFromFlat;
_gridIntHeightMultiplier = 0;
m_V9 = NULL;
m_V8 = NULL;
// Liquid data
_liquidType = 0;
_liquidOffX = 0;
_liquidOffY = 0;
_liquidWidth = 0;
_liquidHeight = 0;
_liquidLevel = INVALID_HEIGHT;
_liquidEntry = NULL;
_liquidFlags = NULL;
_liquidMap = NULL;
}
GridMap::~GridMap()
{
unloadData();
}
bool GridMap::loadData(char* filename)
{
// Unload old data if exist
unloadData();
map_fileheader header;
// Not return error if file not found
FILE* in = fopen(filename, "rb");
if (!in)
return true;
if (fread(&header, sizeof(header), 1, in) != 1)
{
fclose(in);
return false;
}
if (header.mapMagic.asUInt == MapMagic.asUInt && header.versionMagic.asUInt == MapVersionMagic.asUInt)
{
// load up area data
if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
{
TC_LOG_ERROR("maps", "Error loading map area data\n");
fclose(in);
return false;
}
// load up height data
if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
{
TC_LOG_ERROR("maps", "Error loading map height data\n");
fclose(in);
return false;
}
// load up liquid data
if (header.liquidMapOffset && !loadLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
{
TC_LOG_ERROR("maps", "Error loading map liquids data\n");
fclose(in);
return false;
}
fclose(in);
return true;
}
TC_LOG_ERROR("maps", "Map file '%s' is from an incompatible map version (%.*s %.*s), %.*s %.*s is expected. Please recreate using the mapextractor.",
filename, 4, header.mapMagic.asChar, 4, header.versionMagic.asChar, 4, MapMagic.asChar, 4, MapVersionMagic.asChar);
fclose(in);
return false;
}
void GridMap::unloadData()
{
delete[] _areaMap;
delete[] m_V9;
delete[] m_V8;
delete[] _liquidEntry;
delete[] _liquidFlags;
delete[] _liquidMap;
_areaMap = NULL;
m_V9 = NULL;
m_V8 = NULL;
_liquidEntry = NULL;
_liquidFlags = NULL;
_liquidMap = NULL;
_gridGetHeight = &GridMap::getHeightFromFlat;
}
bool GridMap::loadAreaData(FILE* in, uint32 offset, uint32 /*size*/)
{
map_areaHeader header;
fseek(in, offset, SEEK_SET);
if (fread(&header, sizeof(header), 1, in) != 1 || header.fourcc != MapAreaMagic.asUInt)
return false;
_gridArea = header.gridArea;
if (!(header.flags & MAP_AREA_NO_AREA))
{
_areaMap = new uint16 [16*16];
if (fread(_areaMap, sizeof(uint16), 16*16, in) != 16*16)
return false;
}
return true;
}
bool GridMap::loadHeightData(FILE* in, uint32 offset, uint32 /*size*/)
{
map_heightHeader header;
fseek(in, offset, SEEK_SET);
if (fread(&header, sizeof(header), 1, in) != 1 || header.fourcc != MapHeightMagic.asUInt)
return false;
_gridHeight = header.gridHeight;
if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
{
if ((header.flags & MAP_HEIGHT_AS_INT16))
{
m_uint16_V9 = new uint16 [129*129];
m_uint16_V8 = new uint16 [128*128];
if (fread(m_uint16_V9, sizeof(uint16), 129*129, in) != 129*129 ||
fread(m_uint16_V8, sizeof(uint16), 128*128, in) != 128*128)
return false;
_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
_gridGetHeight = &GridMap::getHeightFromUint16;
}
else if ((header.flags & MAP_HEIGHT_AS_INT8))
{
m_uint8_V9 = new uint8 [129*129];
m_uint8_V8 = new uint8 [128*128];
if (fread(m_uint8_V9, sizeof(uint8), 129*129, in) != 129*129 ||
fread(m_uint8_V8, sizeof(uint8), 128*128, in) != 128*128)
return false;
_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
_gridGetHeight = &GridMap::getHeightFromUint8;
}
else
{
m_V9 = new float [129*129];
m_V8 = new float [128*128];
if (fread(m_V9, sizeof(float), 129*129, in) != 129*129 ||
fread(m_V8, sizeof(float), 128*128, in) != 128*128)
return false;
_gridGetHeight = &GridMap::getHeightFromFloat;
}
}
else
_gridGetHeight = &GridMap::getHeightFromFlat;
return true;
}
bool GridMap::loadLiquidData(FILE* in, uint32 offset, uint32 /*size*/)
{
map_liquidHeader header;
fseek(in, offset, SEEK_SET);
if (fread(&header, sizeof(header), 1, in) != 1 || header.fourcc != MapLiquidMagic.asUInt)
return false;
_liquidType = header.liquidType;
_liquidOffX = header.offsetX;
_liquidOffY = header.offsetY;
_liquidWidth = header.width;
_liquidHeight = header.height;
_liquidLevel = header.liquidLevel;
if (!(header.flags & MAP_LIQUID_NO_TYPE))
{
_liquidEntry = new uint16[16*16];
if (fread(_liquidEntry, sizeof(uint16), 16*16, in) != 16*16)
return false;
_liquidFlags = new uint8[16*16];
if (fread(_liquidFlags, sizeof(uint8), 16*16, in) != 16*16)
return false;
}
if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
{
_liquidMap = new float[uint32(_liquidWidth) * uint32(_liquidHeight)];
if (fread(_liquidMap, sizeof(float), _liquidWidth*_liquidHeight, in) != (uint32(_liquidWidth) * uint32(_liquidHeight)))
return false;
}
return true;
}
uint16 GridMap::getArea(float x, float y) const
{
if (!_areaMap)
return _gridArea;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return _areaMap[lx*16 + ly];
}
float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
{
return _gridHeight;
}
float GridMap::getHeightFromFloat(float x, float y) const
{
if (!m_V8 || !m_V9)
return _gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int&=(MAP_RESOLUTION - 1);
y_int&=(MAP_RESOLUTION - 1);
// Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
// +--------------> X
// | h1-------h2 Coordinates is:
// | | \ 1 / | h1 0, 0
// | | \ / | h2 0, 1
// | | 2 h5 3 | h3 1, 0
// | | / \ | h4 1, 1
// | | / 4 \ | h5 1/2, 1/2
// | h3-------h4
// V Y
// For find height need
// 1 - detect triangle
// 2 - solve linear equation from triangle points
// Calculate coefficients for solve h = a*x + b*y + c
float a, b, c;
// Select triangle:
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
float h1 = m_V9[(x_int)*129 + y_int];
float h2 = m_V9[(x_int+1)*129 + y_int];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
float h1 = m_V9[x_int*129 + y_int ];
float h3 = m_V9[x_int*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
float h2 = m_V9[(x_int+1)*129 + y_int ];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
float h3 = m_V9[(x_int)*129 + y_int+1];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return a * x + b * y + c;
}
float GridMap::getHeightFromUint8(float x, float y) const
{
if (!m_uint8_V8 || !m_uint8_V9)
return _gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int&=(MAP_RESOLUTION - 1);
y_int&=(MAP_RESOLUTION - 1);
int32 a, b, c;
uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*_gridIntHeightMultiplier + _gridHeight;
}
float GridMap::getHeightFromUint16(float x, float y) const
{
if (!m_uint16_V8 || !m_uint16_V9)
return _gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int&=(MAP_RESOLUTION - 1);
y_int&=(MAP_RESOLUTION - 1);
int32 a, b, c;
uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*_gridIntHeightMultiplier + _gridHeight;
}
float GridMap::getLiquidLevel(float x, float y) const
{
if (!_liquidMap)
return _liquidLevel;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int cx_int = ((int)x & (MAP_RESOLUTION-1)) - _liquidOffY;
int cy_int = ((int)y & (MAP_RESOLUTION-1)) - _liquidOffX;
if (cx_int < 0 || cx_int >=_liquidHeight)
return INVALID_HEIGHT;
if (cy_int < 0 || cy_int >=_liquidWidth)
return INVALID_HEIGHT;
return _liquidMap[cx_int*_liquidWidth + cy_int];
}
// Why does this return LIQUID data?
uint8 GridMap::getTerrainType(float x, float y) const
{
if (!_liquidFlags)
return 0;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return _liquidFlags[lx*16 + ly];
}
// Get water state on map
inline ZLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data)
{
// Check water type (if no water return)
if (!_liquidType && !_liquidFlags)
return LIQUID_MAP_NO_WATER;
// Get cell
float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)cx & (MAP_RESOLUTION-1);
int y_int = (int)cy & (MAP_RESOLUTION-1);
// Check water type in cell
int idx=(x_int>>3)*16 + (y_int>>3);
uint8 type = _liquidFlags ? _liquidFlags[idx] : _liquidType;
uint32 entry = 0;
if (_liquidEntry)
{
if (LiquidTypeEntry const* liquidEntry = sLiquidTypeStore.LookupEntry(_liquidEntry[idx]))
{
entry = liquidEntry->Id;
type &= MAP_LIQUID_TYPE_DARK_WATER;
uint32 liqTypeIdx = liquidEntry->Type;
if (entry < 21)
{
if (AreaTableEntry const* area = GetAreaEntryByAreaFlagAndMap(getArea(x, y), MAPID_INVALID))
{
uint32 overrideLiquid = area->LiquidTypeOverride[liquidEntry->Type];
if (!overrideLiquid && area->zone)
{
area = GetAreaEntryByAreaID(area->zone);
if (area)
overrideLiquid = area->LiquidTypeOverride[liquidEntry->Type];
}
if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(overrideLiquid))
{
entry = overrideLiquid;
liqTypeIdx = liq->Type;
}
}
}
type |= 1 << liqTypeIdx;
}
}
if (type == 0)
return LIQUID_MAP_NO_WATER;
// Check req liquid type mask
if (ReqLiquidType && !(ReqLiquidType&type))
return LIQUID_MAP_NO_WATER;
// Check water level:
// Check water height map
int lx_int = x_int - _liquidOffY;
int ly_int = y_int - _liquidOffX;
if (lx_int < 0 || lx_int >=_liquidHeight)
return LIQUID_MAP_NO_WATER;
if (ly_int < 0 || ly_int >=_liquidWidth)
return LIQUID_MAP_NO_WATER;
// Get water level
float liquid_level = _liquidMap ? _liquidMap[lx_int*_liquidWidth + ly_int] : _liquidLevel;
// Get ground level (sub 0.2 for fix some errors)
float ground_level = getHeight(x, y);
// Check water level and ground level
if (liquid_level < ground_level || z < ground_level - 2)
return LIQUID_MAP_NO_WATER;
// All ok in water -> store data
if (data)
{
data->entry = entry;
data->type_flags = type;
data->level = liquid_level;
data->depth_level = ground_level;
}
// For speed check as int values
float delta = liquid_level - z;
if (delta > 2.0f) // Under water
return LIQUID_MAP_UNDER_WATER;
if (delta > 0.0f) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -0.1f) // Walk on water
return LIQUID_MAP_WATER_WALK;
// Above water
return LIQUID_MAP_ABOVE_WATER;
}
inline GridMap* Map::GetGrid(float x, float y)
{
// half opt method
int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
// ensure GridMap is loaded
EnsureGridCreated(GridCoord(63-gx, 63-gy));
return GridMaps[gx][gy];
}
float Map::GetWaterOrGroundLevel(float x, float y, float z, float* ground /*= NULL*/, bool /*swim = false*/) const
{
if (const_cast<Map*>(this)->GetGrid(x, y))
{
// we need ground level (including grid height version) for proper return water level in point
float ground_z = GetHeight(PHASEMASK_NORMAL, x, y, z, true, 50.0f);
if (ground)
*ground = ground_z;
LiquidData liquid_status;
ZLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status);
return res ? liquid_status.level : ground_z;
}
return VMAP_INVALID_HEIGHT_VALUE;
}
float Map::GetHeight(float x, float y, float z, bool checkVMap /*= true*/, float maxSearchDist /*= DEFAULT_HEIGHT_SEARCH*/) const
{
// find raw .map surface under Z coordinates
float mapHeight = VMAP_INVALID_HEIGHT_VALUE;
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
{
float gridHeight = gmap->getHeight(x, y);
// look from a bit higher pos to find the floor, ignore under surface case
if (z + 2.0f > gridHeight)
mapHeight = gridHeight;
}
float vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
if (checkVMap)
{
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
if (vmgr->isHeightCalcEnabled())
vmapHeight = vmgr->getHeight(GetId(), x, y, z + 2.0f, maxSearchDist); // look from a bit higher pos to find the floor
}
// mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
// vmapheight set for any under Z value or <= INVALID_HEIGHT
if (vmapHeight > INVALID_HEIGHT)
{
if (mapHeight > INVALID_HEIGHT)
{
// we have mapheight and vmapheight and must select more appropriate
// we are already under the surface or vmap height above map heigt
// or if the distance of the vmap height is less the land height distance
if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z))
return vmapHeight;
else
return mapHeight; // better use .map surface height
}
else
return vmapHeight; // we have only vmapHeight (if have)
}
return mapHeight; // explicitly use map data
}
inline bool IsOutdoorWMO(uint32 mogpFlags, int32 /*adtId*/, int32 /*rootId*/, int32 /*groupId*/, WMOAreaTableEntry const* wmoEntry, AreaTableEntry const* atEntry)
{
bool outdoor = true;
if (wmoEntry && atEntry)
{
if (atEntry->flags & AREA_FLAG_OUTSIDE)
return true;
if (atEntry->flags & AREA_FLAG_INSIDE)
return false;
}
outdoor = mogpFlags&0x8;
if (wmoEntry)
{
if (wmoEntry->Flags & 4)
return true;
if ((wmoEntry->Flags & 2)!=0)
outdoor = false;
}
return outdoor;
}
bool Map::IsOutdoors(float x, float y, float z) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
// no wmo found? -> outside by default
if (!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
return true;
AreaTableEntry const* atEntry = 0;
WMOAreaTableEntry const* wmoEntry= GetWMOAreaTableEntryByTripple(rootId, adtId, groupId);
if (wmoEntry)
{
TC_LOG_DEBUG("maps", "Got WMOAreaTableEntry! flag %u, areaid %u", wmoEntry->Flags, wmoEntry->areaId);
atEntry = GetAreaEntryByAreaID(wmoEntry->areaId);
}
return IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
}
bool Map::IsIndoors(WorldObject* wo) const
{
return !IsOutdoors(wo->GetPositionX(), wo->GetPositionY(), wo->GetPositionZ());
}
bool Map::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
{
float vmap_z = z;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
if (vmgr->getAreaInfo(GetId(), x, y, vmap_z, flags, adtId, rootId, groupId))
{
// check if there's terrain between player height and object height
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
{
float _mapheight = gmap->getHeight(x, y);
// z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice...
if (z + 2.0f > _mapheight && _mapheight > vmap_z)
return false;
}
return true;
}
return false;
}
uint16 Map::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
WMOAreaTableEntry const* wmoEntry = 0;
AreaTableEntry const* atEntry = 0;
bool haveAreaInfo = false;
if (GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
{
haveAreaInfo = true;
wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId);
if (wmoEntry)
atEntry = GetAreaEntryByAreaID(wmoEntry->areaId);
}
uint16 areaflag;
if (atEntry)
areaflag = atEntry->exploreFlag;
else
{
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
areaflag = gmap->getArea(x, y);
// this used while not all *.map files generated (instances)
else
areaflag = GetAreaFlagByMapId(i_mapEntry->MapID);
}
if (isOutdoors)
{
if (haveAreaInfo)
*isOutdoors = IsOutdoorWMO(mogpFlags, adtId, rootId, groupId, wmoEntry, atEntry);
else
*isOutdoors = true;
}
return areaflag;
}
uint8 Map::GetTerrainType(float x, float y) const
{
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
return gmap->getTerrainType(x, y);
else
return 0;
}
ZLiquidStatus Map::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, LiquidData* data) const
{
ZLiquidStatus result = LIQUID_MAP_NO_WATER;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
float liquid_level = INVALID_HEIGHT;
float ground_level = INVALID_HEIGHT;
uint32 liquid_type = 0;
if (vmgr->GetLiquidLevel(GetId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type))
{
TC_LOG_DEBUG("maps", "getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type);
// Check water level and ground level
if (liquid_level > ground_level && z > ground_level - 2)
{
// All ok in water -> store data
if (data)
{
// hardcoded in client like this
if (GetId() == 530 && liquid_type == 2)
liquid_type = 15;
uint32 liquidFlagType = 0;
if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(liquid_type))
liquidFlagType = liq->Type;
if (liquid_type && liquid_type < 21)
{
if (AreaTableEntry const* area = GetAreaEntryByAreaFlagAndMap(GetAreaFlag(x, y, z), GetId()))
{
uint32 overrideLiquid = area->LiquidTypeOverride[liquidFlagType];
if (!overrideLiquid && area->zone)
{
area = GetAreaEntryByAreaID(area->zone);
if (area)
overrideLiquid = area->LiquidTypeOverride[liquidFlagType];
}
if (LiquidTypeEntry const* liq = sLiquidTypeStore.LookupEntry(overrideLiquid))
{
liquid_type = overrideLiquid;
liquidFlagType = liq->Type;
}
}
}
data->level = liquid_level;
data->depth_level = ground_level;
data->entry = liquid_type;
data->type_flags = 1 << liquidFlagType;
}
float delta = liquid_level - z;
// Get position delta
if (delta > 2.0f) // Under water
return LIQUID_MAP_UNDER_WATER;
if (delta > 0.0f) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -0.1f) // Walk on water
return LIQUID_MAP_WATER_WALK;
result = LIQUID_MAP_ABOVE_WATER;
}
}
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
{
LiquidData map_data;
ZLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data);
// Not override LIQUID_MAP_ABOVE_WATER with LIQUID_MAP_NO_WATER:
if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level))
{
if (data)
{
// hardcoded in client like this
if (GetId() == 530 && map_data.entry == 2)
map_data.entry = 15;
*data = map_data;
}
return map_result;
}
}
return result;
}
float Map::GetWaterLevel(float x, float y) const
{
if (GridMap* gmap = const_cast<Map*>(this)->GetGrid(x, y))
return gmap->getLiquidLevel(x, y);
else
return 0;
}
uint32 Map::GetAreaIdByAreaFlag(uint16 areaflag, uint32 map_id)
{
AreaTableEntry const* entry = GetAreaEntryByAreaFlagAndMap(areaflag, map_id);
if (entry)
return entry->ID;
else
return 0;
}
uint32 Map::GetZoneIdByAreaFlag(uint16 areaflag, uint32 map_id)
{
AreaTableEntry const* entry = GetAreaEntryByAreaFlagAndMap(areaflag, map_id);
if (entry)
return (entry->zone != 0) ? entry->zone : entry->ID;
else
return 0;
}
void Map::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag, uint32 map_id)
{
AreaTableEntry const* entry = GetAreaEntryByAreaFlagAndMap(areaflag, map_id);
areaid = entry ? entry->ID : 0;
zoneid = entry ? ((entry->zone != 0) ? entry->zone : entry->ID) : 0;
}
bool Map::isInLineOfSight(float x1, float y1, float z1, float x2, float y2, float z2, uint32 phasemask) const
{
return VMAP::VMapFactory::createOrGetVMapManager()->isInLineOfSight(GetId(), x1, y1, z1, x2, y2, z2)
&& _dynamicTree.isInLineOfSight(x1, y1, z1, x2, y2, z2, phasemask);
}
bool Map::getObjectHitPos(uint32 phasemask, float x1, float y1, float z1, float x2, float y2, float z2, float& rx, float& ry, float& rz, float modifyDist)
{
G3D::Vector3 startPos(x1, y1, z1);
G3D::Vector3 dstPos(x2, y2, z2);
G3D::Vector3 resultPos;
bool result = _dynamicTree.getObjectHitPos(phasemask, startPos, dstPos, resultPos, modifyDist);
rx = resultPos.x;
ry = resultPos.y;
rz = resultPos.z;
return result;
}
float Map::GetHeight(uint32 phasemask, float x, float y, float z, bool vmap/*=true*/, float maxSearchDist/*=DEFAULT_HEIGHT_SEARCH*/) const
{
return std::max<float>(GetHeight(x, y, z, vmap, maxSearchDist), _dynamicTree.getHeight(x, y, z, maxSearchDist, phasemask));
}
bool Map::IsInWater(float x, float y, float pZ, LiquidData* data) const
{
LiquidData liquid_status;
LiquidData* liquid_ptr = data ? data : &liquid_status;
return getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr) & (LIQUID_MAP_IN_WATER | LIQUID_MAP_UNDER_WATER);
}
bool Map::IsUnderWater(float x, float y, float z) const
{
return getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN) & LIQUID_MAP_UNDER_WATER;
}
bool Map::CheckGridIntegrity(Creature* c, bool moved) const
{
Cell const& cur_cell = c->GetCurrentCell();
Cell xy_cell(c->GetPositionX(), c->GetPositionY());
if (xy_cell != cur_cell)
{
TC_LOG_DEBUG("maps", "Creature (GUID: %u) X: %f Y: %f (%s) is in grid[%u, %u]cell[%u, %u] instead of grid[%u, %u]cell[%u, %u]",
c->GetGUIDLow(),
c->GetPositionX(), c->GetPositionY(), (moved ? "final" : "original"),
cur_cell.GridX(), cur_cell.GridY(), cur_cell.CellX(), cur_cell.CellY(),
xy_cell.GridX(), xy_cell.GridY(), xy_cell.CellX(), xy_cell.CellY());
return true; // not crash at error, just output error in debug mode
}
return true;
}
char const* Map::GetMapName() const
{
return i_mapEntry ? i_mapEntry->name : "UNNAMEDMAP\x0";
}
void Map::UpdateObjectVisibility(WorldObject* obj, Cell cell, CellCoord cellpair)
{
cell.SetNoCreate();
Trinity::VisibleChangesNotifier notifier(*obj);
TypeContainerVisitor<Trinity::VisibleChangesNotifier, WorldTypeMapContainer > player_notifier(notifier);
cell.Visit(cellpair, player_notifier, *this, *obj, obj->GetVisibilityRange());
}
void Map::UpdateObjectsVisibilityFor(Player* player, Cell cell, CellCoord cellpair)
{
Trinity::VisibleNotifier notifier(*player);
cell.SetNoCreate();
TypeContainerVisitor<Trinity::VisibleNotifier, WorldTypeMapContainer > world_notifier(notifier);
TypeContainerVisitor<Trinity::VisibleNotifier, GridTypeMapContainer > grid_notifier(notifier);
cell.Visit(cellpair, world_notifier, *this, *player, player->GetSightRange());
cell.Visit(cellpair, grid_notifier, *this, *player, player->GetSightRange());
// send data
notifier.SendToSelf();
}
void Map::SendInitSelf(Player* player)
{
TC_LOG_INFO("maps", "Creating player data for himself %u", player->GetGUIDLow());
UpdateData data(player->GetMapId());
// attach to player data current transport data
if (Transport* transport = player->GetTransport())
{
transport->BuildCreateUpdateBlockForPlayer(&data, player);
}
// build data for self presence in world at own client (one time for map)
player->BuildCreateUpdateBlockForPlayer(&data, player);
// build other passengers at transport also (they always visible and marked as visible and will not send at visibility update at add to map
if (Transport* transport = player->GetTransport())
{
for (std::set<WorldObject*>::const_iterator itr = transport->GetPassengers().begin(); itr != transport->GetPassengers().end(); ++itr)
{
if (player != (*itr) && player->HaveAtClient(*itr))
{
(*itr)->BuildCreateUpdateBlockForPlayer(&data, player);
}
}
}
WorldPacket packet;
data.BuildPacket(&packet);
player->GetSession()->SendPacket(&packet);
}
void Map::SendInitTransports(Player* player)
{
// Hack to send out transports
UpdateData transData(player->GetMapId());
for (TransportsContainer::const_iterator i = _transports.begin(); i != _transports.end(); ++i)
if (*i != player->GetTransport())
(*i)->BuildCreateUpdateBlockForPlayer(&transData, player);
WorldPacket packet;
transData.BuildPacket(&packet);
player->GetSession()->SendPacket(&packet);
}
void Map::SendRemoveTransports(Player* player)
{
// Hack to send out transports
UpdateData transData(player->GetMapId());
for (TransportsContainer::const_iterator i = _transports.begin(); i != _transports.end(); ++i)
if (*i != player->GetTransport())
(*i)->BuildOutOfRangeUpdateBlock(&transData);
WorldPacket packet;
transData.BuildPacket(&packet);
player->GetSession()->SendPacket(&packet);
}
inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y)
{
if (x >= MAX_NUMBER_OF_GRIDS || y >= MAX_NUMBER_OF_GRIDS)
{
TC_LOG_ERROR("maps", "map::setNGrid() Invalid grid coordinates found: %d, %d!", x, y);
ASSERT(false);
}
i_grids[x][y] = grid;
}
void Map::DelayedUpdate(const uint32 t_diff)
{
RemoveAllObjectsInRemoveList();
// Don't unload grids if it's battleground, since we may have manually added GOs, creatures, those doesn't load from DB at grid re-load !
// This isn't really bother us, since as soon as we have instanced BG-s, the whole map unloads as the BG gets ended
if (!IsBattlegroundOrArena())
{
for (GridRefManager<NGridType>::iterator i = GridRefManager<NGridType>::begin(); i != GridRefManager<NGridType>::end();)
{
NGridType *grid = i->GetSource();
GridInfo* info = i->GetSource()->getGridInfoRef();
++i; // The update might delete the map and we need the next map before the iterator gets invalid
ASSERT(grid->GetGridState() >= 0 && grid->GetGridState() < MAX_GRID_STATE);
si_GridStates[grid->GetGridState()]->Update(*this, *grid, *info, t_diff);
}
}
}
void Map::AddObjectToRemoveList(WorldObject* obj)
{
ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId());
obj->CleanupsBeforeDelete(false); // remove or simplify at least cross referenced links
i_objectsToRemove.insert(obj);
//TC_LOG_DEBUG("maps", "Object (GUID: %u TypeId: %u) added to removing list.", obj->GetGUIDLow(), obj->GetTypeId());
}
void Map::AddObjectToSwitchList(WorldObject* obj, bool on)
{
ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId());
// i_objectsToSwitch is iterated only in Map::RemoveAllObjectsInRemoveList() and it uses
// the contained objects only if GetTypeId() == TYPEID_UNIT , so we can return in all other cases
if (obj->GetTypeId() != TYPEID_UNIT && obj->GetTypeId() != TYPEID_GAMEOBJECT)
return;
std::map<WorldObject*, bool>::iterator itr = i_objectsToSwitch.find(obj);
if (itr == i_objectsToSwitch.end())
i_objectsToSwitch.insert(itr, std::make_pair(obj, on));
else if (itr->second != on)
i_objectsToSwitch.erase(itr);
else
ASSERT(false);
}
void Map::RemoveAllObjectsInRemoveList()
{
while (!i_objectsToSwitch.empty())
{
std::map<WorldObject*, bool>::iterator itr = i_objectsToSwitch.begin();
WorldObject* obj = itr->first;
bool on = itr->second;
i_objectsToSwitch.erase(itr);
if (!obj->IsPermanentWorldObject())
{
switch (obj->GetTypeId())
{
case TYPEID_UNIT:
SwitchGridContainers<Creature>(obj->ToCreature(), on);
break;
case TYPEID_GAMEOBJECT:
SwitchGridContainers<GameObject>(obj->ToGameObject(), on);
break;
default:
break;
}
}
}
//TC_LOG_DEBUG("maps", "Object remover 1 check.");
while (!i_objectsToRemove.empty())
{
std::set<WorldObject*>::iterator itr = i_objectsToRemove.begin();
WorldObject* obj = *itr;
switch (obj->GetTypeId())
{
case TYPEID_CORPSE:
{
Corpse* corpse = ObjectAccessor::GetCorpse(*obj, obj->GetGUID());
if (!corpse)
TC_LOG_ERROR("maps", "Tried to delete corpse/bones %u that is not in map.", obj->GetGUIDLow());
else
RemoveFromMap(corpse, true);
break;
}
case TYPEID_DYNAMICOBJECT:
RemoveFromMap((DynamicObject*)obj, true);
break;
case TYPEID_AREATRIGGER:
RemoveFromMap((AreaTrigger*)obj, true);
break;
case TYPEID_GAMEOBJECT:
if (Transport* transport = obj->ToGameObject()->ToTransport())
RemoveFromMap(transport, true);
else
RemoveFromMap(obj->ToGameObject(), true);
break;
case TYPEID_UNIT:
// in case triggered sequence some spell can continue casting after prev CleanupsBeforeDelete call
// make sure that like sources auras/etc removed before destructor start
obj->ToCreature()->CleanupsBeforeDelete();
RemoveFromMap(obj->ToCreature(), true);
break;
default:
TC_LOG_ERROR("maps", "Non-grid object (TypeId: %u) is in grid object remove list, ignored.", obj->GetTypeId());
break;
}
i_objectsToRemove.erase(itr);
}
//TC_LOG_DEBUG("maps", "Object remover 2 check.");
}
uint32 Map::GetPlayersCountExceptGMs() const
{
uint32 count = 0;
for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
if (!itr->GetSource()->IsGameMaster()) {
//npcbot - count npcbots as group members (event if not in group)
if (itr->GetSource()->HaveBot() && BotMgr::LimitBots(this))
{
++count;
BotMap const* botmap = itr->GetSource()->GetBotMgr()->GetBotMap();
for (BotMap::const_iterator itr = botmap->begin(); itr != botmap->end(); ++itr)
{
Creature* cre = itr->second;
if (!cre || !cre->IsInWorld() || cre->FindMap() != this)
continue;
++count;
}
}
else
//end npcbot
++count;
}
return count;
}
void Map::SendToPlayers(WorldPacket const* data) const
{
for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
itr->GetSource()->GetSession()->SendPacket(data);
}
bool Map::ActiveObjectsNearGrid(NGridType const& ngrid) const
{
CellCoord cell_min(ngrid.getX() * MAX_NUMBER_OF_CELLS, ngrid.getY() * MAX_NUMBER_OF_CELLS);
CellCoord cell_max(cell_min.x_coord + MAX_NUMBER_OF_CELLS, cell_min.y_coord+MAX_NUMBER_OF_CELLS);
//we must find visible range in cells so we unload only non-visible cells...
float viewDist = GetVisibilityRange();
int cell_range = (int)ceilf(viewDist / SIZE_OF_GRID_CELL) + 1;
cell_min.dec_x(cell_range);
cell_min.dec_y(cell_range);
cell_max.inc_x(cell_range);
cell_max.inc_y(cell_range);
for (MapRefManager::const_iterator iter = m_mapRefManager.begin(); iter != m_mapRefManager.end(); ++iter)
{
Player* player = iter->GetSource();
CellCoord p = Trinity::ComputeCellCoord(player->GetPositionX(), player->GetPositionY());
if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
(cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
return true;
}
for (ActiveNonPlayers::const_iterator iter = m_activeNonPlayers.begin(); iter != m_activeNonPlayers.end(); ++iter)
{
WorldObject* obj = *iter;
CellCoord p = Trinity::ComputeCellCoord(obj->GetPositionX(), obj->GetPositionY());
if ((cell_min.x_coord <= p.x_coord && p.x_coord <= cell_max.x_coord) &&
(cell_min.y_coord <= p.y_coord && p.y_coord <= cell_max.y_coord))
return true;
}
return false;
}
template<class T>
void Map::AddToActive(T* obj)
{
AddToActiveHelper(obj);
}
template <>
void Map::AddToActive(Creature* c)
{
AddToActiveHelper(c);
// also not allow unloading spawn grid to prevent creating creature clone at load
if (!c->IsPet() && c->GetDBTableGUIDLow())
{
float x, y, z;
c->GetRespawnPosition(x, y, z);
GridCoord p = Trinity::ComputeGridCoord(x, y);
if (getNGrid(p.x_coord, p.y_coord))
getNGrid(p.x_coord, p.y_coord)->incUnloadActiveLock();
//bot
else if (c->GetIAmABot())
EnsureGridLoadedForActiveObject(Cell(Trinity::ComputeCellCoord(c->GetPositionX(), c->GetPositionY())), c);
//end bot
else
{
GridCoord p2 = Trinity::ComputeGridCoord(c->GetPositionX(), c->GetPositionY());
TC_LOG_ERROR("maps", "Active creature (GUID: %u Entry: %u) added to grid[%u, %u] but spawn grid[%u, %u] was not loaded.",
c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
}
}
}
template<>
void Map::AddToActive(DynamicObject* d)
{
AddToActiveHelper(d);
}
template<class T>
void Map::RemoveFromActive(T* /*obj*/) { }
template <>
void Map::RemoveFromActive(Creature* c)
{
RemoveFromActiveHelper(c);
// also allow unloading spawn grid
if (!c->IsPet() && c->GetDBTableGUIDLow())
{
float x, y, z;
c->GetRespawnPosition(x, y, z);
GridCoord p = Trinity::ComputeGridCoord(x, y);
if (getNGrid(p.x_coord, p.y_coord))
getNGrid(p.x_coord, p.y_coord)->decUnloadActiveLock();
//bot
else if (c->GetIAmABot())
EnsureGridLoaded(Cell(Trinity::ComputeCellCoord(c->GetPositionX(), c->GetPositionY())));
//end bot
else
{
GridCoord p2 = Trinity::ComputeGridCoord(c->GetPositionX(), c->GetPositionY());
TC_LOG_ERROR("maps", "Active creature (GUID: %u Entry: %u) removed from grid[%u, %u] but spawn grid[%u, %u] was not loaded.",
c->GetGUIDLow(), c->GetEntry(), p.x_coord, p.y_coord, p2.x_coord, p2.y_coord);
}
}
}
template<>
void Map::RemoveFromActive(DynamicObject* obj)
{
RemoveFromActiveHelper(obj);
}
template bool Map::AddToMap(Corpse*);
template bool Map::AddToMap(Creature*);
template bool Map::AddToMap(GameObject*);
template bool Map::AddToMap(DynamicObject*);
template bool Map::AddToMap(AreaTrigger*);
template void Map::RemoveFromMap(Corpse*, bool);
template void Map::RemoveFromMap(Creature*, bool);
template void Map::RemoveFromMap(GameObject*, bool);
template void Map::RemoveFromMap(DynamicObject*, bool);
template void Map::RemoveFromMap(AreaTrigger*, bool);
/* ******* Dungeon Instance Maps ******* */
InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent)
: Map(id, expiry, InstanceId, SpawnMode, _parent),
m_resetAfterUnload(false), m_unloadWhenEmpty(false),
i_data(NULL), i_script_id(0)
{
//lets initialize visibility distance for dungeons
InstanceMap::InitVisibilityDistance();
// the timer is started by default, and stopped when the first player joins
// this make sure it gets unloaded if for some reason no player joins
m_unloadTimer = std::max(sWorld->getIntConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
}
InstanceMap::~InstanceMap()
{
delete i_data;
i_data = NULL;
}
void InstanceMap::InitVisibilityDistance()
{
//init visibility distance for instances
m_VisibleDistance = World::GetMaxVisibleDistanceInInstances();
m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodInInstances();
}
/*
Do map specific checks to see if the player can enter
*/
bool InstanceMap::CanEnter(Player* player)
{
if (player->GetMapRef().getTarget() == this)
{
TC_LOG_ERROR("maps", "ASSERT Check InstanceMap::CanEnter - player %s(%u) already in map %d, %d", player->GetName().c_str(), player->GetGUIDLow(), GetId(), GetInstanceId());
//ASSERT(false);
return false;
}
// allow GM's to enter
if (player->IsGameMaster())
return Map::CanEnter(player);
// cannot enter if the instance is full (player cap), GMs don't count
uint32 maxPlayers = GetMaxPlayers();
bool ignoreMaxPlayer = sConfigMgr->GetBoolDefault("Instance.IgnoreMaxPlayerCount", false);
if (ignoreMaxPlayer)
maxPlayers = 99;
if (GetPlayersCountExceptGMs() >= maxPlayers)
{
TC_LOG_INFO("maps", "MAP: Instance '%u' of map '%s' cannot have more than '%u' players. Player '%s' rejected", GetInstanceId(), GetMapName(), maxPlayers, player->GetName().c_str());
player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
return false;
}
// cannot enter while an encounter is in progress on raids
/*Group* group = player->GetGroup();
if (!player->IsGameMaster() && group && group->InCombatToInstance(GetInstanceId()) && player->GetMapId() != GetId())*/
if (IsRaid() && GetInstanceScript() && GetInstanceScript()->IsEncounterInProgress())
{
player->SendTransferAborted(GetId(), TRANSFER_ABORT_ZONE_IN_COMBAT);
return false;
}
// cannot enter if instance is in use by another party/soloer that have a
// permanent save in the same instance id
PlayerList const &playerList = GetPlayers();
if (!playerList.isEmpty())
for (PlayerList::const_iterator i = playerList.begin(); i != playerList.end(); ++i)
if (Player* iPlayer = i->GetSource())
{
if (iPlayer->IsGameMaster()) // bypass GMs
continue;
if (!player->GetGroup()) // player has not group and there is someone inside, deny entry
{
player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
return false;
}
// player inside instance has no group or his groups is different to entering player's one, deny entry
if (!iPlayer->GetGroup() || iPlayer->GetGroup() != player->GetGroup())
{
player->SendTransferAborted(GetId(), TRANSFER_ABORT_MAX_PLAYERS);
return false;
}
break;
}
return Map::CanEnter(player);
}
/*
Do map specific checks and add the player to the map if successful.
*/
bool InstanceMap::AddPlayerToMap(Player* player)
{
/// @todo Not sure about checking player level: already done in HandleAreaTriggerOpcode
// GMs still can teleport player in instance.
// Is it needed?
{
TRINITY_GUARD(ACE_Thread_Mutex, Lock);
// Check moved to void WorldSession::HandleMoveWorldportAckOpcode()
//if (!CanEnter(player))
//return false;
// Dungeon only code
if (IsDungeon())
{
Group* group = player->GetGroup();
// increase current instances (hourly limit)
if (!group || !group->isLFGGroup())
player->AddInstanceEnterTime(GetInstanceId(), time(NULL));
// get or create an instance save for the map
InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(GetInstanceId());
if (!mapSave)
{
TC_LOG_INFO("maps", "InstanceMap::Add: creating instance save for map %d spawnmode %d with instance id %d", GetId(), GetSpawnMode(), GetInstanceId());
mapSave = sInstanceSaveMgr->AddInstanceSave(GetId(), GetInstanceId(), Difficulty(GetSpawnMode()), 0, true);
}
ASSERT(mapSave);
// check for existing instance binds
InstancePlayerBind* playerBind = player->GetBoundInstance(GetId(), Difficulty(GetSpawnMode()));
if (playerBind && playerBind->perm)
{
// cannot enter other instances if bound permanently
if (playerBind->save != mapSave)
{
TC_LOG_ERROR("maps", "InstanceMap::Add: player %s(%d) is permanently bound to instance %s %d, %d, %d, %d, %d, %d but he is being put into instance %s %d, %d, %d, %d, %d, %d", player->GetName().c_str(), player->GetGUIDLow(), GetMapName(), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset(), GetMapName(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset());
return false;
}
}
else
{
if (group)
{
// solo saves should be reset when entering a group
InstanceGroupBind* groupBind = group->GetBoundInstance(this);
if (playerBind && playerBind->save != mapSave)
{
TC_LOG_ERROR("maps", "InstanceMap::Add: player %s(%d) is being put into instance %s %d, %d, %d, %d, %d, %d but he is in group %d and is bound to instance %d, %d, %d, %d, %d, %d!", player->GetName().c_str(), player->GetGUIDLow(), GetMapName(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), mapSave->GetPlayerCount(), mapSave->GetGroupCount(), mapSave->CanReset(), GUID_LOPART(group->GetLeaderGUID()), playerBind->save->GetMapId(), playerBind->save->GetInstanceId(), playerBind->save->GetDifficulty(), playerBind->save->GetPlayerCount(), playerBind->save->GetGroupCount(), playerBind->save->CanReset());
if (groupBind)
TC_LOG_ERROR("maps", "InstanceMap::Add: the group is bound to the instance %s %d, %d, %d, %d, %d, %d", GetMapName(), groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty(), groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount(), groupBind->save->CanReset());
//ASSERT(false);
return false;
}
// bind to the group or keep using the group save
if (!groupBind)
group->BindToInstance(mapSave, false);
else
{
// cannot jump to a different instance without resetting it
if (groupBind->save != mapSave)
{
TC_LOG_ERROR("maps", "InstanceMap::Add: player %s(%d) is being put into instance %d, %d, %d but he is in group %d which is bound to instance %d, %d, %d!", player->GetName().c_str(), player->GetGUIDLow(), mapSave->GetMapId(), mapSave->GetInstanceId(), mapSave->GetDifficulty(), GUID_LOPART(group->GetLeaderGUID()), groupBind->save->GetMapId(), groupBind->save->GetInstanceId(), groupBind->save->GetDifficulty());
TC_LOG_ERROR("maps", "MapSave players: %d, group count: %d", mapSave->GetPlayerCount(), mapSave->GetGroupCount());
if (groupBind->save)
TC_LOG_ERROR("maps", "GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount());
else
TC_LOG_ERROR("maps", "GroupBind save NULL");
return false;
}
// if the group/leader is permanently bound to the instance
// players also become permanently bound when they enter
if (groupBind->perm)
{
WorldPacket data(SMSG_INSTANCE_LOCK_WARNING_QUERY, 10);
data << uint32(60000);
data << uint32(i_data ? i_data->GetCompletedEncounterMask() : 0);
data << uint8(0);
data << uint8(0); // events it throws: 1 : INSTANCE_LOCK_WARNING 0 : INSTANCE_LOCK_STOP / INSTANCE_LOCK_START
player->GetSession()->SendPacket(&data);
player->SetPendingBind(mapSave->GetInstanceId(), 60000);
}
}
}
else
{
// set up a solo bind or continue using it
if (!playerBind)
player->BindToInstance(mapSave, false);
else
// cannot jump to a different instance without resetting it
ASSERT(playerBind->save == mapSave);
}
}
}
// for normal instances cancel the reset schedule when the
// first player enters (no players yet)
SetResetSchedule(false);
TC_LOG_INFO("maps", "MAP: Player '%s' entered instance '%u' of map '%s'", player->GetName().c_str(), GetInstanceId(), GetMapName());
// initialize unload state
m_unloadTimer = 0;
m_resetAfterUnload = false;
m_unloadWhenEmpty = false;
}
// this will acquire the same mutex so it cannot be in the previous block
Map::AddPlayerToMap(player);
if (i_data)
i_data->OnPlayerEnter(player);
return true;
}
void InstanceMap::Update(const uint32 t_diff)
{
Map::Update(t_diff);
if (i_data)
i_data->Update(t_diff);
}
void InstanceMap::RemovePlayerFromMap(Player* player, bool remove)
{
TC_LOG_INFO("maps", "MAP: Removing player '%s' from instance '%u' of map '%s' before relocating to another map", player->GetName().c_str(), GetInstanceId(), GetMapName());
//if last player set unload timer
if (!m_unloadTimer && m_mapRefManager.getSize() == 1)
m_unloadTimer = m_unloadWhenEmpty ? MIN_UNLOAD_DELAY : std::max(sWorld->getIntConfig(CONFIG_INSTANCE_UNLOAD_DELAY), (uint32)MIN_UNLOAD_DELAY);
Map::RemovePlayerFromMap(player, remove);
// for normal instances schedule the reset after all players have left
SetResetSchedule(true);
sInstanceSaveMgr->UnloadInstanceSave(GetInstanceId());
}
void InstanceMap::CreateInstanceData(bool load)
{
if (i_data != NULL)
return;
InstanceTemplate const* mInstance = sObjectMgr->GetInstanceTemplate(GetId());
if (mInstance)
{
i_script_id = mInstance->ScriptId;
i_data = sScriptMgr->CreateInstanceData(this);
}
if (!i_data)
return;
i_data->Initialize();
if (load)
{
/// @todo make a global storage for this
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_INSTANCE);
stmt->setUInt16(0, uint16(GetId()));
stmt->setUInt32(1, i_InstanceId);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (result)
{
Field* fields = result->Fetch();
std::string data = fields[0].GetString();
i_data->SetCompletedEncountersMask(fields[1].GetUInt32());
if (data != "")
{
TC_LOG_DEBUG("maps", "Loading instance data for `%s` with id %u", sObjectMgr->GetScriptName(i_script_id), i_InstanceId);
i_data->Load(data.c_str());
}
}
}
}
/*
Returns true if there are no players in the instance
*/
bool InstanceMap::Reset(uint8 method)
{
// note: since the map may not be loaded when the instance needs to be reset
// the instance must be deleted from the DB by InstanceSaveManager
if (HavePlayers())
{
if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
{
// notify the players to leave the instance so it can be reset
for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
itr->GetSource()->SendResetFailedNotify(GetId());
}
else
{
if (method == INSTANCE_RESET_GLOBAL)
// set the homebind timer for players inside (1 minute)
for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
itr->GetSource()->m_InstanceValid = false;
// the unload timer is not started
// instead the map will unload immediately after the players have left
m_unloadWhenEmpty = true;
m_resetAfterUnload = true;
}
}
else
{
// unloaded at next update
m_unloadTimer = MIN_UNLOAD_DELAY;
m_resetAfterUnload = true;
}
return m_mapRefManager.isEmpty();
}
void InstanceMap::PermBindAllPlayers(Player* source)
{
if (!IsDungeon())
return;
InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(GetInstanceId());
if (!save)
{
TC_LOG_ERROR("maps", "Cannot bind player (GUID: %u, Name: %s), because no instance save is available for instance map (Name: %s, Entry: %u, InstanceId: %u)!", source->GetGUIDLow(), source->GetName().c_str(), source->GetMap()->GetMapName(), source->GetMapId(), GetInstanceId());
return;
}
Group* group = source->GetGroup();
// group members outside the instance group don't get bound
for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
{
Player* player = itr->GetSource();
// players inside an instance cannot be bound to other instances
// some players may already be permanently bound, in this case nothing happens
InstancePlayerBind* bind = player->GetBoundInstance(save->GetMapId(), save->GetDifficulty());
if (!bind || !bind->perm)
{
player->BindToInstance(save, true);
WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
data << uint32(0);
player->GetSession()->SendPacket(&data);
player->GetSession()->SendCalendarRaidLockout(save, true);
}
// if the leader is not in the instance the group will not get a perm bind
if (group && group->GetLeaderGUID() == player->GetGUID())
group->BindToInstance(save, true);
}
}
void InstanceMap::UnloadAll()
{
ASSERT(!HavePlayers());
if (m_resetAfterUnload == true)
DeleteRespawnTimes();
Map::UnloadAll();
}
void InstanceMap::SendResetWarnings(uint32 timeLeft) const
{
for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
itr->GetSource()->SendInstanceResetWarning(GetId(), itr->GetSource()->GetDifficulty(IsRaid()), timeLeft);
}
void InstanceMap::SetResetSchedule(bool on)
{
// only for normal instances
// the reset time is only scheduled when there are no payers inside
// it is assumed that the reset time will rarely (if ever) change while the reset is scheduled
if (IsDungeon() && !HavePlayers() && !IsRaidOrHeroicDungeon())
{
if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(GetInstanceId()))
sInstanceSaveMgr->ScheduleReset(on, save->GetResetTime(), InstanceSaveManager::InstResetEvent(0, GetId(), Difficulty(GetSpawnMode()), GetInstanceId()));
else
TC_LOG_ERROR("maps", "InstanceMap::SetResetSchedule: cannot turn schedule %s, there is no save information for instance (map [id: %u, name: %s], instance id: %u, difficulty: %u)",
on ? "on" : "off", GetId(), GetMapName(), GetInstanceId(), Difficulty(GetSpawnMode()));
}
}
MapDifficulty const* Map::GetMapDifficulty() const
{
return GetMapDifficultyData(GetId(), GetDifficulty());
}
uint32 InstanceMap::GetMaxPlayers() const
{
MapDifficulty const* mapDiff = GetMapDifficulty();
if (mapDiff && mapDiff->maxPlayers)
return mapDiff->maxPlayers;
return GetEntry()->maxPlayers;
}
uint32 InstanceMap::GetMaxResetDelay() const
{
MapDifficulty const* mapDiff = GetMapDifficulty();
return mapDiff ? mapDiff->resetTime : 0;
}
/* ******* Battleground Instance Maps ******* */
BattlegroundMap::BattlegroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode)
: Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(NULL)
{
//lets initialize visibility distance for BG/Arenas
BattlegroundMap::InitVisibilityDistance();
}
BattlegroundMap::~BattlegroundMap()
{
if (m_bg)
{
//unlink to prevent crash, always unlink all pointer reference before destruction
m_bg->SetBgMap(NULL);
m_bg = NULL;
}
}
void BattlegroundMap::InitVisibilityDistance()
{
//init visibility distance for BG/Arenas
m_VisibleDistance = World::GetMaxVisibleDistanceInBGArenas();
m_VisibilityNotifyPeriod = World::GetVisibilityNotifyPeriodInBGArenas();
}
bool BattlegroundMap::CanEnter(Player* player)
{
if (player->GetMapRef().getTarget() == this)
{
TC_LOG_ERROR("maps", "BGMap::CanEnter - player %u is already in map!", player->GetGUIDLow());
ASSERT(false);
return false;
}
if (player->GetBattlegroundId() != GetInstanceId())
return false;
// player number limit is checked in bgmgr, no need to do it here
return Map::CanEnter(player);
}
bool BattlegroundMap::AddPlayerToMap(Player* player)
{
{
TRINITY_GUARD(ACE_Thread_Mutex, Lock);
//Check moved to void WorldSession::HandleMoveWorldportAckOpcode()
//if (!CanEnter(player))
//return false;
// reset instance validity, battleground maps do not homebind
player->m_InstanceValid = true;
}
return Map::AddPlayerToMap(player);
}
void BattlegroundMap::RemovePlayerFromMap(Player* player, bool remove)
{
TC_LOG_INFO("maps", "MAP: Removing player '%s' from bg '%u' of map '%s' before relocating to another map", player->GetName().c_str(), GetInstanceId(), GetMapName());
Map::RemovePlayerFromMap(player, remove);
}
void BattlegroundMap::SetUnload()
{
m_unloadTimer = MIN_UNLOAD_DELAY;
}
void BattlegroundMap::RemoveAllPlayers()
{
if (HavePlayers())
for (MapRefManager::iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr)
if (Player* player = itr->GetSource())
if (!player->IsBeingTeleportedFar())
player->TeleportTo(player->GetBattlegroundEntryPoint());
}
Creature* Map::GetCreature(uint64 guid)
{
return ObjectAccessor::GetObjectInMap(guid, this, (Creature*)NULL);
}
GameObject* Map::GetGameObject(uint64 guid)
{
return ObjectAccessor::GetObjectInMap(guid, this, (GameObject*)NULL);
}
Transport* Map::GetTransport(uint64 guid)
{
if (GUID_HIPART(guid) != HIGHGUID_MO_TRANSPORT)
return NULL;
GameObject* go = GetGameObject(guid);
return go ? go->ToTransport() : NULL;
}
DynamicObject* Map::GetDynamicObject(uint64 guid)
{
return ObjectAccessor::GetObjectInMap(guid, this, (DynamicObject*)NULL);
}
void Map::UpdateIteratorBack(Player* player)
{
if (m_mapRefIter == player->GetMapRef())
m_mapRefIter = m_mapRefIter->nocheck_prev();
}
void Map::SaveCreatureRespawnTime(uint32 dbGuid, time_t respawnTime)
{
if (!respawnTime)
{
// Delete only
RemoveCreatureRespawnTime(dbGuid);
return;
}
_creatureRespawnTimes[dbGuid] = respawnTime;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CREATURE_RESPAWN);
stmt->setUInt32(0, dbGuid);
stmt->setUInt32(1, uint32(respawnTime));
stmt->setUInt16(2, GetId());
stmt->setUInt32(3, GetInstanceId());
CharacterDatabase.Execute(stmt);
}
void Map::RemoveCreatureRespawnTime(uint32 dbGuid)
{
_creatureRespawnTimes.erase(dbGuid);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN);
stmt->setUInt32(0, dbGuid);
stmt->setUInt16(1, GetId());
stmt->setUInt32(2, GetInstanceId());
CharacterDatabase.Execute(stmt);
}
void Map::SaveGORespawnTime(uint32 dbGuid, time_t respawnTime)
{
if (!respawnTime)
{
// Delete only
RemoveGORespawnTime(dbGuid);
return;
}
_goRespawnTimes[dbGuid] = respawnTime;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GO_RESPAWN);
stmt->setUInt32(0, dbGuid);
stmt->setUInt32(1, uint32(respawnTime));
stmt->setUInt16(2, GetId());
stmt->setUInt32(3, GetInstanceId());
CharacterDatabase.Execute(stmt);
}
void Map::RemoveGORespawnTime(uint32 dbGuid)
{
_goRespawnTimes.erase(dbGuid);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GO_RESPAWN);
stmt->setUInt32(0, dbGuid);
stmt->setUInt16(1, GetId());
stmt->setUInt32(2, GetInstanceId());
CharacterDatabase.Execute(stmt);
}
void Map::LoadRespawnTimes()
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CREATURE_RESPAWNS);
stmt->setUInt16(0, GetId());
stmt->setUInt32(1, GetInstanceId());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
do
{
Field* fields = result->Fetch();
uint32 loguid = fields[0].GetUInt32();
uint32 respawnTime = fields[1].GetUInt32();
_creatureRespawnTimes[loguid] = time_t(respawnTime);
} while (result->NextRow());
}
stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GO_RESPAWNS);
stmt->setUInt16(0, GetId());
stmt->setUInt32(1, GetInstanceId());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
{
do
{
Field* fields = result->Fetch();
uint32 loguid = fields[0].GetUInt32();
uint32 respawnTime = fields[1].GetUInt32();
_goRespawnTimes[loguid] = time_t(respawnTime);
} while (result->NextRow());
}
}
void Map::DeleteRespawnTimes()
{
_creatureRespawnTimes.clear();
_goRespawnTimes.clear();
DeleteRespawnTimesInDB(GetId(), GetInstanceId());
}
void Map::DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId)
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE);
stmt->setUInt16(0, mapId);
stmt->setUInt32(1, instanceId);
CharacterDatabase.Execute(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GO_RESPAWN_BY_INSTANCE);
stmt->setUInt16(0, mapId);
stmt->setUInt32(1, instanceId);
CharacterDatabase.Execute(stmt);
}
time_t Map::GetLinkedRespawnTime(uint64 guid) const
{
uint64 linkedGuid = sObjectMgr->GetLinkedRespawnGuid(guid);
switch (GUID_HIPART(linkedGuid))
{
case HIGHGUID_UNIT:
return GetCreatureRespawnTime(GUID_LOPART(linkedGuid));
case HIGHGUID_GAMEOBJECT:
return GetGORespawnTime(GUID_LOPART(linkedGuid));
default:
break;
}
return time_t(0);
}
void Map::SendZoneDynamicInfo(Player* player)
{
uint32 zoneId = GetZoneId(player->GetPositionX(), player->GetPositionY(), player->GetPositionZ());
ZoneDynamicInfoMap::const_iterator itr = _zoneDynamicInfo.find(zoneId);
if (itr == _zoneDynamicInfo.end())
return;
if (uint32 music = itr->second.MusicId)
{
WorldPacket data(SMSG_PLAY_MUSIC, 4);
data << uint32(music);
data << uint64(player->GetGUID());
player->SendDirectMessage(&data);
}
if (uint32 weather = itr->second.WeatherId)
{
WorldPacket data(SMSG_WEATHER, 4 + 4 + 1);
data << uint32(weather);
data << float(itr->second.WeatherGrade);
data << uint8(0);
player->SendDirectMessage(&data);
}
if (uint32 OverrideLight = itr->second.OverrideLightId)
{
WorldPacket data(SMSG_OVERRIDE_LIGHT, 4 + 4 + 1);
data << uint32(_defaultLight);
data << uint32(OverrideLight);
data << uint32(itr->second.LightFadeInTime);
player->SendDirectMessage(&data);
}
}
void Map::SetZoneMusic(uint32 zoneId, uint32 musicId)
{
if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end())
_zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo()));
_zoneDynamicInfo[zoneId].MusicId = musicId;
Map::PlayerList const& players = GetPlayers();
if (!players.isEmpty())
{
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (Player* player = itr->GetSource())
if (player->GetZoneId() == zoneId)
{
WorldPacket data(SMSG_PLAY_MUSIC, 4);
data << uint32(musicId);
data << uint64(player->GetGUID());
player->SendDirectMessage(&data);
}
}
}
void Map::SetZoneWeather(uint32 zoneId, uint32 weatherId, float weatherGrade)
{
if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end())
_zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo()));
ZoneDynamicInfo& info = _zoneDynamicInfo[zoneId];
info.WeatherId = weatherId;
info.WeatherGrade = weatherGrade;
Map::PlayerList const& players = GetPlayers();
if (!players.isEmpty())
{
WorldPacket data(SMSG_WEATHER, 4 + 4 + 1);
data << uint32(weatherId);
data << float(weatherGrade);
data << uint8(0);
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (Player* player = itr->GetSource())
if (player->GetZoneId() == zoneId)
player->SendDirectMessage(&data);
}
}
void Map::SetZoneOverrideLight(uint32 zoneId, uint32 lightId, uint32 fadeInTime)
{
if (_zoneDynamicInfo.find(zoneId) == _zoneDynamicInfo.end())
_zoneDynamicInfo.insert(ZoneDynamicInfoMap::value_type(zoneId, ZoneDynamicInfo()));
ZoneDynamicInfo& info = _zoneDynamicInfo[zoneId];
info.OverrideLightId = lightId;
info.LightFadeInTime = fadeInTime;
Map::PlayerList const& players = GetPlayers();
if (!players.isEmpty())
{
WorldPacket data(SMSG_OVERRIDE_LIGHT, 4 + 4 + 1);
data << uint32(_defaultLight);
data << uint32(lightId);
data << uint32(fadeInTime);
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (Player* player = itr->GetSource())
if (player->GetZoneId() == zoneId)
player->SendDirectMessage(&data);
}
}
void Map::UpdateAreaDependentAuras()
{
Map::PlayerList const& players = GetPlayers();
for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
if (Player* player = itr->GetSource())
if (player->IsInWorld())
{
player->UpdateAreaDependentAuras(player->GetAreaId());
player->UpdateZoneDependentAuras(player->GetZoneId());
}
}
| gpl-2.0 |
3den/J-MediaGalleries | administrator/components/com_modules/views/module/tmpl/modal.php | 689 | <?php
/**
* @version $Id: modal.php 19205 2010-10-22 19:50:48Z 3dentech $
* @package Joomla.Administrator
* @subpackage Modules
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
?>
<div class="fltrt">
<button type="button" onclick="Joomla.submitbutton('module.save');">
<?php echo JText::_('JSAVE');?></button>
<button type="button" onclick="window.parent.SqueezeBox.close();">
<?php echo JText::_('JCANCEL');?></button>
</div>
<div class="clr"></div>
<?php
$this->setLayout('edit');
echo $this->loadTemplate(); | gpl-2.0 |
portalgas/site | plugins/system/nnframework/helpers/search.php | 5265 | <?php
/**
* @package NoNumber Framework
* @version 13.9.1
*
* @author Peter van Westen <[email protected]>
* @link http://www.nonumber.nl
* @copyright Copyright © 2013 NoNumber
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/**
* BASE ON JOOMLA CORE FILE:
* /components/com_search/models/search.php
*/
/**
* @package Joomla.Site
* @subpackage com_search
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Search Component Search Model
*
* @package Joomla.Site
* @subpackage com_search
* @since 1.5
*/
class SearchModelSearch extends JModelLegacy
{
/**
* Sezrch data array
*
* @var array
*/
var $_data = null;
/**
* Search total
*
* @var integer
*/
var $_total = null;
/**
* Search areas
*
* @var integer
*/
var $_areas = null;
/**
* Pagination object
*
* @var object
*/
var $_pagination = null;
/**
* Constructor
*
* @since 1.5
*/
function __construct()
{
parent::__construct();
//Get configuration
$app = JFactory::getApplication();
$config = JFactory::getConfig();
// Get the pagination request variables
$this->setState('limit', $app->getUserStateFromRequest('com_search.limit', 'limit', $config->get('list_limit'), 'uint'));
$this->setState('limitstart', $app->input->getInt('limitstart', 0));
// Set the search parameters
$keyword = urldecode($app->input->getString('searchword', ''));
$match = $app->input->getWord('searchphrase', 'all');
$ordering = $app->input->getWord('ordering', 'newest');
$this->setSearch($keyword, $match, $ordering);
//Set the search areas
$areas = $app->input->get('areas');
$this->setAreas($areas);
}
/**
* Method to set the search parameters
*
* @access public
* @param string search string
* @param string mathcing option, exact|any|all
* @param string ordering option, newest|oldest|popular|alpha|category
*/
function setSearch($keyword, $match = 'all', $ordering = 'newest')
{
if (isset($keyword)) {
$this->setState('origkeyword', $keyword);
if($match !== 'exact') {
$keyword = preg_replace('#\xE3\x80\x80#s', ' ', $keyword);
}
$this->setState('keyword', $keyword);
}
if (isset($match)) {
$this->setState('match', $match);
}
if (isset($ordering)) {
$this->setState('ordering', $ordering);
}
}
/**
* Method to set the search areas
*
* @access public
* @param array Active areas
* @param array Search areas
*/
function setAreas($active = array(), $search = array())
{
$this->_areas['active'] = $active;
$this->_areas['search'] = $search;
}
/**
* Method to get weblink item data for the category
*
* @access public
* @return array
*/
function getData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data))
{
$areas = $this->getAreas();
JPluginHelper::importPlugin('search');
$dispatcher = JDispatcher::getInstance();
$results = $dispatcher->trigger('onContentSearch', array(
$this->getState('keyword'),
$this->getState('match'),
$this->getState('ordering'),
$areas['active'])
);
$rows = array();
foreach ($results as $result) {
$rows = array_merge((array) $rows, (array) $result);
}
$this->_total = count($rows);
if ($this->getState('limit') > 0) {
$this->_data = array_splice($rows, $this->getState('limitstart'), $this->getState('limit'));
} else {
$this->_data = $rows;
}
/* >>> ADDED: Run content plugins over results */
$params = JFactory::getApplication()->getParams('com_content');
$params->set('nn_search', 1);
foreach ($this->_data as $item) {
if ($item->text != '') {
$results = $dispatcher->trigger('onContentPrepare', array('com_content.article', &$item, &$params, 0));
// strip html tags from title
$item->title = strip_tags($item->title);
}
}
/* <<< */
}
return $this->_data;
}
/**
* Method to get the total number of weblink items for the category
*
* @access public
* @return integer
*/
function getTotal()
{
return $this->_total;
}
/**
* Method to get a pagination object of the weblink items for the category
*
* @access public
* @return integer
*/
function getPagination()
{
// Lets load the content if it doesn't already exist
if (empty($this->_pagination))
{
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_pagination;
}
/**
* Method to get the search areas
*
* @since 1.5
*/
function getAreas()
{
// Load the Category data
if (empty($this->_areas['search']))
{
$areas = array();
JPluginHelper::importPlugin('search');
$dispatcher = JDispatcher::getInstance();
$searchareas = $dispatcher->trigger('onContentSearchAreas');
foreach ($searchareas as $area) {
if (is_array($area)) {
$areas = array_merge($areas, $area);
}
}
$this->_areas['search'] = $areas;
}
return $this->_areas;
}
}
| gpl-2.0 |
fratellodallaluna/hackunito | wp-content/plugins/WP-Geo-master/admin/dashboard.php | 2870 | <?php
/**
* WP Geo Dashboard
* Display the WP Geo Blog RSS feed in the dashboard.
*/
if ( ! class_exists( 'WPGeo_Dashboard' ) ) {
class WPGeo_Dashboard {
/**
* Constructor
*/
function WPGeo_Dashboard() {
add_action( 'wp_dashboard_setup', array( $this, 'register_widget' ) );
add_filter( 'wp_dashboard_widgets', array( $this, 'add_widget' ) );
}
/**
* Register the dashboard widget
*/
function register_widget() {
wp_add_dashboard_widget( 'wpgeo_dashboard', 'WP Geo',
array( $this, 'widget' ),
array(
'all_link' => 'http://www.wpgeo.com/',
'feed_link' => 'http://www.wpgeo.com/feed/'
)
);
}
/**
* Add the dashboard widget
*
* @param array $widgets Array of widgets.
* @return array Widgets.
*/
function add_widget( $widgets ) {
global $wp_registered_widgets;
if ( ! isset( $wp_registered_widgets['wpgeo_dashboard'] ) )
return $widgets;
array_splice( $widgets, sizeof( $widgets ) - 1, 0, 'wpgeo_dashboard' );
return $widgets;
}
/**
* Display the dashboard widget
*
* @param array $args Args.
*/
function widget( $args = null ) {
// Validate Args
$defaults = array(
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
'widget_name' => ''
);
extract( wp_parse_args( $args, $defaults ), EXTR_SKIP );
echo $before_widget . $before_title . $widget_name . $after_title;
echo '<div style="background-image:url(' . plugins_url( WPGEO_SUBDIR . 'img/logo/wp-geo.png' ) . '); background-repeat:no-repeat; background-position:right top; padding-right:80px;">';
$feed = fetch_feed( 'http://feeds2.feedburner.com/wpgeo' );
if ( is_wp_error( $feed ) || ! $feed->get_item_quantity() ) {
echo '<p>' . __( 'No recent updates.', 'wp-geo' ) . '</p>';
return;
}
$items = $feed->get_items( 0, 2 );
foreach ( $items as $item ) {
$url = esc_url( $item->get_link() );
$title = esc_html( $item->get_title() );
$date = esc_html( strip_tags( $item->get_date() ) );
$description = esc_html( strip_tags( @html_entity_decode( $item->get_description(), ENT_QUOTES, get_option( 'blog_charset' ) ) ) );
echo '<div style="margin-bottom:20px;">';
echo '<p style="margin-bottom:5px;"><a style="font-size: 1.2em; font-weight:bold;" href="' . $url . '" title="' . $title . '">' . $title . '</a></p>';
echo '<p style="color: #aaa; margin-top:5px;">' . date( 'l, jS F Y', strtotime( $date ) ) . '</p>';
echo '<p>' . $description .'</p>';
echo '</div>';
}
echo '<p><a href="http://www.wpgeo.com/">' . __( 'View all WP Geo news...', 'wp-geo' ) . '</a></p>';
echo '</div>';
echo $after_widget;
}
}
global $wpgeo_dashboard;
$wpgeo_dashboard = new WPGeo_Dashboard();
}
| gpl-2.0 |
emeraldstudio/intranet | components/com_propuestas/controllers/clientes.php | 784 | <?php
/**
* @version 1.0.0
* @package com_propuestas
* @copyright Copyright (C) 2015. Todos los derechos reservados.
* @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt
* @author Daniel Gustavo Álvarez Gaitán <[email protected]> - http://danielalvarez.com.co
*/
// No direct access.
defined('_JEXEC') or die;
require_once JPATH_COMPONENT.'/controller.php';
/**
* Clientes list controller class.
*/
class PropuestasControllerClientes extends PropuestasController
{
/**
* Proxy for getModel.
* @since 1.6
*/
public function &getModel($name = 'Clientes', $prefix = 'PropuestasModel', $config = array())
{
$model = parent::getModel($name, $prefix, array('ignore_request' => true));
return $model;
}
} | gpl-2.0 |
silenceper/CatPocket | temp/caches/0390/14afc3d05c33d8c249105ba8bd8bae8e.cache.php | 155 | <?php
/**
* @Created By CatPocket PhpCacheServer
* @Time:2012-05-08 22:33:15
*/
if(filemtime(__FILE__) + 3600 < time())return false;
return '0';
?> | gpl-2.0 |
silenceper/CatPocket | includes/libraries/image.func.php | 6894 | <?php
/**
* CatPocket: 图片处理函数库 水印 缩略图
* ============================================================================
* 版权所有 (C) 2005-2008 猫口袋,并保留所有权利。
* 网站地址: http://www.maokoudai.com
* -------------------------------------------------------
* 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用;
* 不允许对程序代码以任何形式任何目的的再发布。
* ============================================================================
* $Id: image.func.php 7715 2009-05-07 06:56:11Z yelin $
*/
/**
* 利用gd库生成缩略图
*
* @author weberliu
* @param string $src 原图片路径
* @param string $dst 缩略图保存路径
* @param int $thumb_width 缩略图高度
* @param int $thumb_height 缩略图高度 可选
* @param int $quality 缩略图品质 100之内的正整数
* @return boolean 成功返回 true 失败返回 false
*/
function make_thumb($src, $dst, $thumb_width, $thumb_height = 0, $quality = 85)
{
if (function_exists('imagejpeg'))
{
$func_imagecreate = function_exists('imagecreatetruecolor') ? 'imagecreatetruecolor' : 'imagecreate';
$func_imagecopy = function_exists('imagecopyresampled') ? 'imagecopyresampled' : 'imagecopyresized';
$dirpath = dirname($dst);
if (!ecm_mkdir($dirpath, 0777))
{
return false;
}
$data = getimagesize($src);
$src_width = $data[0];
$src_height = $data[1];
if ($thumb_height == 0)
{
if ($src_width > $src_height)
{
$thumb_height = $src_height * $thumb_width / $src_width;
}
else
{
$thumb_height = $thumb_width;
$thumb_width = $src_width * $thumb_height / $src_height;
}
$dst_x = 0;
$dst_y = 0;
$dst_w = $thumb_width;
$dst_h = $thumb_height;
}
else
{
if ($src_width / $src_height > $thumb_width / $thumb_height)
{
$dst_w = $thumb_width;
$dst_h = ($dst_w * $src_height) / $src_width;
$dst_x = 0;
$dst_y = ($thumb_height - $dst_h) / 2;
}
else
{
$dst_h = $thumb_height;
$dst_w = ($src_width * $dst_h) / $src_height;
$dst_y = 0;
$dst_x = ($thumb_width - $dst_w) / 2;
}
}
switch ($data[2])
{
case 1:
$im = imagecreatefromgif($src);
break;
case 2:
$im = imagecreatefromjpeg($src);
break;
case 3:
$im = imagecreatefrompng($src);
break;
default:
trigger_error("Cannot process this picture format: " .$data['mime']);
break;
}
$ni = $func_imagecreate($thumb_width, $thumb_height);
if ($func_imagecreate == 'imagecreatetruecolor')
{
imagefill($ni, 0, 0, imagecolorallocate($ni, 255, 255, 255));
}
else
{
imagecolorallocate($ni, 255, 255, 255);
}
$func_imagecopy($ni, $im, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height);
imagejpeg($ni, $dst, $quality);
return is_file($dst) ? $dst : false;
}
else
{
trigger_error("Unable to process picture.", E_USER_ERROR);
}
}
/**
* 给图片添加水印
* @param filepath $src 待处理图片
* @param filepath $mark_img 水印图片路径
* @param string $position 水印位置 lt左上 rt右上 rb右下 lb左下 其余取值为中间
* @param int $quality jpg图片质量,仅对jpg有效 默认85 取值 0-100之间整数
* @param int $pct 水印图片融合度(透明度)
*
* @return void
*/
function water_mark($src, $mark_img, $position = 'rb', $quality = 85, $pct = 80) {
if(function_exists('imagecopy') && function_exists('imagecopymerge')) {
$data = getimagesize($src);
if ($data[2] > 3)
{
return false;
}
$src_width = $data[0];
$src_height = $data[1];
$src_type = $data[2];
$data = getimagesize($mark_img);
$mark_width = $data[0];
$mark_height = $data[1];
$mark_type = $data[2];
if ($src_width < ($mark_width + 20) || $src_width < ($mark_height + 20))
{
return false;
}
switch ($src_type)
{
case 1:
$src_im = imagecreatefromgif($src);
$imagefunc = function_exists('imagejpeg') ? 'imagejpeg' : '';
break;
case 2:
$src_im = imagecreatefromjpeg($src);
$imagefunc = function_exists('imagegif') ? 'imagejpeg' : '';
break;
case 3:
$src_im = imagecreatefrompng($src);
$imagefunc = function_exists('imagepng') ? 'imagejpeg' : '';
break;
}
switch ($mark_type)
{
case 1:
$mark_im = imagecreatefromgif($mark_img);
break;
case 2:
$mark_im = imagecreatefromjpeg($mark_img);
break;
case 3:
$mark_im = imagecreatefrompng($mark_img);
break;
}
switch ($position)
{
case 'lt':
$x = 10;
$y = 10;
break;
case 'rt':
$x = $src_width - $mark_width - 10;
$y = 10;
break;
case 'rb':
$x = $src_width - $mark_width - 10;
$y = $src_height - $mark_height - 10;
break;
case 'lb':
$x = 10;
$y = $src_height - $mark_height - 10;
break;
default:
$x = ($src_width - $mark_width - 10) / 2;
$y = ($src_height - $mark_height - 10) / 2;
break;
}
if (function_exists('imagealphablending')) imageAlphaBlending($mark_im, true);
imageCopyMerge($src_im, $mark_im, $x, $y, 0, 0, $mark_width, $mark_height, $pct);
if ($src_type == 2)
{
$imagefunc($src_im, $src, $quality);
}
else
{
$imagefunc($dst_photo, $src);
}
}
}
?> | gpl-2.0 |
yimng/wlb | wlb/Halsign.Dwm.Communication/GetConfigurationResponse.cs | 372 | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Halsign.DWM.Communication
{
[DataContract(Namespace = "http://schemas.halsign.com/ARDS")]
public class GetConfigurationResponse : WorkloadBalanceResult
{
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public Dictionary<string, string> OptimizationParms;
}
}
| gpl-2.0 |
epicsdeb/rtems-gcc-newlib | libstdc++-v3/testsuite/19_diagnostics/headers/stdexcept/types_std.cc | 1184 | // { dg-do compile }
// Copyright (C) 2007 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#include <stdexcept>
namespace gnu
{
typedef std::logic_error t1;
typedef std::domain_error t2;
typedef std::invalid_argument t3;
typedef std::length_error t4;
typedef std::out_of_range t5;
typedef std::runtime_error t6;
typedef std::range_error t7;
typedef std::overflow_error t8;
typedef std::underflow_error t9;
}
| gpl-2.0 |
stampil/promo | wp-content/themes/MyTheme/header.php | 2068 | <?php
header('Content-Type: text/html; charset=utf-8');
global $wp_rewrite;
if(!$title){
$title = $post->post_title;
}
?><!DOCTYPE html>
<html style="margin-top: 0px !important;">
<head>
<title><?php echo $title; ?></title>
<meta charset="utf-8" />
<meta name="viewport" content="width=640">
<link rel="shortcut icon" type="image/x-icon" href="<?php echo TEMPLATEURL; ?>/img/favicon.ico" />
<link rel="stylesheet" href="<?php echo TEMPLATEURL; ?>/prod/css/main.css">
<script src="<?php echo find_javascript('jquery-1.11.2.min.js'); ?>"></script>
<script src="<?php echo find_javascript('jquery.cycle2.min.js'); ?>"></script>
<script src="<?php echo find_javascript('css_browser_selector.js'); ?>"></script>
<script src="<?php echo find_javascript('modernizr.js'); ?>"></script>
<script src="<?php echo find_javascript('placeholders.min.js'); ?>"></script>
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
</script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="<?php echo find_javascript('respond.min.js'); ?>"></script>
<![endif]-->
<?php wp_head(); ?>
<script>
$(document).ready(function(){
// if mobile addclass
var wWindow = $(window).width();
if (wWindow <=940 ) {
$('html').addClass('mobile');
}
else {
$('html').removeClass('mobile');
}
});
</script>
<script type="text/javascript" src="<?php echo find_javascript('Tag_google_analytics.js'); ?>"></script>
</head>
<body>
<!--[if lt IE 9]>
<div style="padding:5px;background:#656565;color:white;text-align:center;font-style:italic">
Pour une meilleure expérience utilisateur, nous vous invitons à <a style="color:whitesmoke;text-decoration:underline" target="_blank" href="https://www.google.fr/#q=mise+a+jour+navigateur">mettre à jour votre navigateur</a>.
</div>
<![endif]-->
<header>
<?php
wp_nav_menu( array( 'theme_location' => 'header-menu' ) );
?>
</header>
| gpl-2.0 |
muromec/qtopia-ezx | config.tests/alsa/main.cpp | 131 | #include <alsa/asoundlib.h>
main()
{
snd_seq_t *seq_handle;
snd_seq_open(&seq_handle, "default", SND_SEQ_OPEN_INPUT, 0);
}
| gpl-2.0 |
elitelinux/hack-space | php/plugins/databases/databases/setup.php | 5669 | <?php
/*
* @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $
-------------------------------------------------------------------------
Databases plugin for GLPI
Copyright (C) 2003-2011 by the databases Development Team.
https://forge.indepnet.net/projects/databases
-------------------------------------------------------------------------
LICENSE
This file is part of databases.
Databases 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.
Databases 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 Databases. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
// Init the hooks of the plugins -Needed
function plugin_init_databases() {
global $PLUGIN_HOOKS;
$PLUGIN_HOOKS['csrf_compliant']['databases'] = true;
$PLUGIN_HOOKS['change_profile']['databases'] = array('PluginDatabasesProfile','changeProfile');
$PLUGIN_HOOKS['assign_to_ticket']['databases'] = true;
if (Session::getLoginUserID()) {
Plugin::registerClass('PluginDatabasesDatabase', array(
'linkgroup_tech_types' => true,
'linkuser_tech_types' => true,
'document_types' => true,
'ticket_types' => true,
'helpdesk_visible_types' => true,
'addtabon' => 'Supplier'
));
Plugin::registerClass('PluginDatabasesProfile',
array('addtabon' => 'Profile'));
if (class_exists('PluginAccountsAccount')) {
PluginAccountsAccount::registerType('PluginDatabasesDatabase');
}
if (isset($_SESSION["glpi_plugin_environment_installed"]) && $_SESSION["glpi_plugin_environment_installed"]==1) {
$_SESSION["glpi_plugin_environment_databases"]=1;
// Display a menu entry ?
if (plugin_databases_haveRight("databases","r")) {
$PLUGIN_HOOKS['submenu_entry']['environment']['options']['databases']['title'] = PluginDatabasesDatabase::getTypeName(2);
$PLUGIN_HOOKS['submenu_entry']['environment']['options']['databases']['page'] = '/plugins/databases/front/database.php';
$PLUGIN_HOOKS['submenu_entry']['environment']['options']['databases']['links']['search'] = '/plugins/databases/front/database.php';
}
if (plugin_databases_haveRight("databases","w")) {
$PLUGIN_HOOKS['submenu_entry']['environment']['options']['databases']['links']['add'] = '/plugins/databases/front/database.form.php';
$PLUGIN_HOOKS['use_massive_action']['databases']=1;
}
} else {
// Display a menu entry ?
if (plugin_databases_haveRight("databases","r")) {
$PLUGIN_HOOKS['menu_entry']['databases'] = 'front/database.php';
$PLUGIN_HOOKS['submenu_entry']['databases']['search'] = 'front/database.php';
}
if (plugin_databases_haveRight("databases","w")) {
$PLUGIN_HOOKS['submenu_entry']['databases']['add'] = 'front/database.form.php?new=1';
$PLUGIN_HOOKS['use_massive_action']['databases']=1;
}
}
if (class_exists('PluginDatabasesDatabase_Item')) { // only if plugin activated
$PLUGIN_HOOKS['pre_item_purge']['databases']
= array('Profile'=>array('PluginDatabasesProfile', 'purgeProfiles'));
$PLUGIN_HOOKS['plugin_datainjection_populate']['databases'] = 'plugin_datainjection_populate_databases';
}
// End init, when all types are registered
$PLUGIN_HOOKS['post_init']['databases'] = 'plugin_databases_postinit';
// Import from Data_Injection plugin
$PLUGIN_HOOKS['migratetypes']['databases'] = 'plugin_datainjection_migratetypes_databases';
}
}
// Get the name and the version of the plugin - Needed
function plugin_version_databases() {
return array (
'name' => _n('Database', 'Databases', 2, 'databases'),
'version' => '1.6.0',
'author' => "<a href='http://infotel.com/services/expertise-technique/glpi/'>Infotel</a>",
'oldname' => 'sgbd',
'license' => 'GPLv2+',
'homepage'=>'https://forge.indepnet.net/projects/show/databases',
'minGlpiVersion' => '0.84',// For compatibility / no install in version < 0.80
);
}
// Optional : check prerequisites before install : may print errors or add to message after redirect
function plugin_databases_check_prerequisites() {
if (version_compare(GLPI_VERSION,'0.84','lt') || version_compare(GLPI_VERSION,'0.85','ge')) {
_e('This plugin requires GLPI >= 0.84', 'databases');
return false;
}
return true;
}
// Uninstall process for plugin : need to return true if succeeded : may display messages or add to message after redirect
function plugin_databases_check_config() {
return true;
}
function plugin_databases_haveRight($module,$right) {
$matches=array(
"" => array("","r","w"), // ne doit pas arriver normalement
"r" => array("r","w"),
"w" => array("w"),
"1" => array("1"),
"0" => array("0","1"), // ne doit pas arriver non plus
);
if (isset($_SESSION["glpi_plugin_databases_profile"][$module])
&& in_array($_SESSION["glpi_plugin_databases_profile"][$module],$matches[$right]))
return true;
else return false;
}
function plugin_datainjection_migratetypes_databases($types) {
$types[2400] = 'PluginDatabasesDatabase';
return $types;
}
?> | gpl-2.0 |
Toolbitorg/ToolbitSDK | bindings/python/samples/device_list.py | 605 | from toolbit import TbiDeviceManager, TbiCore
devm = TbiDeviceManager()
tdev = TbiCore()
dev_list = devm.getDeviceList()
dev_list = tuple(set(dev_list))
print("The number of connected devices:", devm.getDeviceNum())
print(" {:14} {:16} {:10}".format("Manufacturer", "Product", "Serial"))
for dev in dev_list:
serial_list = devm.getSerialList(dev)
for serial in serial_list:
tdev.openPath(devm.getPathByNameAndSerial(dev, serial))
print(" {:14} {:16} {:10}".format(tdev.getVendorName(), tdev.getProductName(), tdev.getProductSerial()))
tdev.close()
| gpl-2.0 |
nickavalos/gescore | tables/editorial.php | 1451 | <?php
/**
* This file is part of the project Gestor de Congresos y Revistas en Joomla (GesCORE).
*
* @package GesCORE backend
* @subpackage Tables
* @copyright Copyright (C) 2014 Open Source Matters, Inc. All rights reserved.
* @authors Nick Avalos, Enric Mayol, Mª José Casany
* @link https://github.com/nickavalos/gescore
* @license License GNU General Public License
*
* GesCORE 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.
*
* GesCORE 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 GesCORE. If not, see <http://www.gnu.org/licenses/>.
*/
// No direct access
defined('_JEXEC') or die('Restricted access');
// import Joomla table library
jimport('joomla.database.table');
/**
* Table class
*/
class GestorcoreTableEditorial extends JTable
{
/**
* Constructor de la clase
*
* @param object Database connector object
*/
function __construct(&$db)
{
parent::__construct('#__editorial', 'nombre', $db);
}
}
| gpl-2.0 |
segura2010/DSS-Practica-2 | src/modelo/Usuario.java | 1245 | package modelo;
import java.io.Serializable;
import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private long id;
private String nombre;
private String apellido;
private String email;
public Usuario() {
// TODO Auto-generated constructor stub
}
public Usuario(Usuario u) {
this.email = u.getEmail();
this.apellido = u.getApellido();
this.id = u.getId();
this.nombre = u.getNombre();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString () {
return nombre + " " + apellido + " − " + email;
}
}
| gpl-2.0 |
sieon/writing | woocommerce/myaccount/orders.php | 4982 | <?php
/**
* Orders
*
* Shows orders on the account page.
*
* This template can be overridden by copying it to yourtheme/woocommerce/myaccount/orders.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 3.2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
do_action( 'woocommerce_before_account_orders', $has_orders ); ?>
<?php if ( $has_orders ) : ?>
<table class="woocommerce-orders-table woocommerce-MyAccount-orders shop_table shop_table_responsive my_account_orders account-orders-table">
<thead>
<tr>
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<th class="woocommerce-orders-table__header woocommerce-orders-table__header-<?php echo esc_attr( $column_id ); ?>"><span class="nobr"><?php echo esc_html( $column_name ); ?></span></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ( $customer_orders->orders as $customer_order ) :
$order = wc_get_order( $customer_order );
$item_count = $order->get_item_count();
?>
<tr class="woocommerce-orders-table__row woocommerce-orders-table__row--status-<?php echo esc_attr( $order->get_status() ); ?> order">
<?php foreach ( wc_get_account_orders_columns() as $column_id => $column_name ) : ?>
<td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-<?php echo esc_attr( $column_id ); ?>" data-title="<?php echo esc_attr( $column_name ); ?>">
<?php if ( has_action( 'woocommerce_my_account_my_orders_column_' . $column_id ) ) : ?>
<?php do_action( 'woocommerce_my_account_my_orders_column_' . $column_id, $order ); ?>
<?php elseif ( 'order-number' === $column_id ) : ?>
<a href="<?php echo esc_url( $order->get_view_order_url() ); ?>">
<?php echo _x( '#', 'hash before order number', 'woocommerce' ) . $order->get_order_number(); ?>
</a>
<?php elseif ( 'order-date' === $column_id ) : ?>
<time datetime="<?php echo esc_attr( $order->get_date_created()->date( 'c' ) ); ?>"><?php echo esc_html( wc_format_datetime( $order->get_date_created() ) ); ?></time>
<?php elseif ( 'order-status' === $column_id ) : ?>
<?php echo esc_html( wc_get_order_status_name( $order->get_status() ) ); ?>
<?php elseif ( 'order-total' === $column_id ) : ?>
<?php
/* translators: 1: formatted order total 2: total order items */
printf( _n( '%1$s for %2$s item', '%1$s for %2$s items', $item_count, 'woocommerce' ), $order->get_formatted_order_total(), $item_count );
?>
<?php elseif ( 'order-actions' === $column_id ) : ?>
<?php
$actions = wc_get_account_orders_actions( $order );
if ( ! empty( $actions ) ) {
foreach ( $actions as $key => $action ) {
echo '<a href="' . esc_url( $action['url'] ) . '" class="woocommerce-button button ' . sanitize_html_class( $key ) . '">' . esc_html( $action['name'] ) . '</a>';
}
}
?>
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php do_action( 'woocommerce_before_account_orders_pagination' ); ?>
<?php if ( 1 < $customer_orders->max_num_pages ) : ?>
<div class="woocommerce-pagination woocommerce-pagination--without-numbers woocommerce-Pagination">
<?php if ( 1 !== $current_page ) : ?>
<a class="woocommerce-button woocommerce-button--previous woocommerce-Button woocommerce-Button--previous button" href="<?php echo esc_url( wc_get_endpoint_url( 'orders', $current_page - 1 ) ); ?>"><?php _e( 'Previous', 'woocommerce' ); ?></a>
<?php endif; ?>
<?php if ( intval( $customer_orders->max_num_pages ) !== $current_page ) : ?>
<a class="woocommerce-button woocommerce-button--next woocommerce-Button woocommerce-Button--next btn btn-outline-primary" href="<?php echo esc_url( wc_get_endpoint_url( 'orders', $current_page + 1 ) ); ?>"><?php _e( 'Next', 'woocommerce' ); ?></a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php else : ?>
<div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
<a class="btn btn-outline-primary" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>">
<?php _e( 'Go shop', 'woocommerce' ) ?>
</a>
<?php _e( 'No order has been made yet.', 'woocommerce' ); ?>
</div>
<?php endif; ?>
<?php do_action( 'woocommerce_after_account_orders', $has_orders ); ?>
| gpl-2.0 |
igorbotian/phdapp | log-log4j/src/main/java/ru/spbftu/igorbotian/phdapp/log/Log4j.java | 3220 | /**
* Copyright (c) 2014 Igor Botian
*
* 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
*
* @author Igor Botian <[email protected]>
*/
package ru.spbftu.igorbotian.phdapp.log;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
/**
* Вспомогательный класс, отвечающий за инициализацию и конфигурацию средств логирования.
* В данном случае это log4j.
*/
public final class Log4j {
/**
* Предопределенное название файла конфигурации log4j в формате <code>.properties</code>
*/
private static final String LOG4J_PROPERTIES = "log4j.properties";
/**
* Предопределенное название файла конфигурации log4j в формате <code>.xml</code>
*/
private static final String LOG4J_XML = "log4j.xml";
private Log4j() {
//
}
/**
* Инициализация log4j.
* Конфигурационный файл должен находиться либо в директории, определяемой системным свойством
* <code>phdapp.conf.folder</code>, либо в текущей папке.
*
* @param configFolder директория для хранения конфигурационных файлов
* @throws java.lang.NullPointerException если директория не задана
*/
public static void init(Path configFolder) {
Objects.requireNonNull(configFolder);
Path log4jXml = configFolder.resolve(LOG4J_XML);
if (Files.exists(log4jXml)) {
System.out.println("Loading LOG4J configuration from file: " + log4jXml.toAbsolutePath().toString());
DOMConfigurator.configure(log4jXml.toAbsolutePath().toString());
} else {
Path log4jProps = configFolder.resolve(LOG4J_PROPERTIES);
if (Files.exists(log4jProps)) {
System.out.println("Loading LOG4J configuration from file: " + log4jProps.toAbsolutePath().toString());
PropertyConfigurator.configure(log4jProps.toAbsolutePath().toString());
} else {
System.err.println("No LOG4J configuration files found in configuration folder: "
+ configFolder.toAbsolutePath().toString());
}
}
}
}
| gpl-2.0 |
BuddyForms/BuddyForms | includes/resources/pfbc/Validation/Email.php | 574 | <?php
/**
* Class Validation_Email
*/
class Validation_Email extends Validation {
/**
* @var string
*/
protected $message = "Error: %element% is not a valid email address.";
/**
* @param $value
* @param $element
*
* @return bool
*/
public function isValid( $value, $element ) {
$result = $this->isNotApplicable( $value ) || filter_var( $value, FILTER_VALIDATE_EMAIL );
if(!$result){
$this->message = str_replace( "%element%", $value, $this->message );
}
return apply_filters( 'buddyforms_element_email_validation', $result, $element );
}
}
| gpl-2.0 |
xjose93/chaoscore | src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp | 4586 | /*
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; 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/>.
*/
/* Script Data Start
SDName: Boss meathook
SDAuthor: Tartalo
SD%Complete: 100
SDComment: It may need timer adjustment
SDCategory:
Script Data End */
#include "ScriptPCH.h"
#include "culling_of_stratholme.h"
enum Spells
{
SPELL_CONSTRICTING_CHAINS = 52696, //Encases the targets in chains, dealing 1800 Physical damage every 1 sec. and stunning the target for 5 sec.
H_SPELL_CONSTRICTING_CHAINS = 58823,
SPELL_DISEASE_EXPULSION = 52666, //Meathook belches out a cloud of disease, dealing 1710 to 1890 Nature damage and interrupting the spell casting of nearby enemy targets for 4 sec.
H_SPELL_DISEASE_EXPULSION = 58824,
SPELL_FRENZY = 58841 //Increases the caster's Physical damage by 10% for 30 sec.
};
enum Yells
{
SAY_AGGRO = -1595026,
SAY_SLAY_1 = -1595027,
SAY_SLAY_2 = -1595028,
SAY_SLAY_3 = -1595029,
SAY_SPAWN = -1595030,
SAY_DEATH = -1595031
};
class boss_meathook : public CreatureScript
{
public:
boss_meathook() : CreatureScript("boss_meathook") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_meathookAI (pCreature);
}
struct boss_meathookAI : public ScriptedAI
{
boss_meathookAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
if (pInstance)
DoScriptText(SAY_SPAWN,me);
}
uint32 uiChainTimer;
uint32 uiDiseaseTimer;
uint32 uiFrenzyTimer;
InstanceScript* pInstance;
void Reset()
{
uiChainTimer = urand(10000, 15000);
uiDiseaseTimer = urand(3000, 5000);
uiFrenzyTimer = urand(15000, 20000);
if (pInstance)
pInstance->SetData(DATA_MEATHOOK_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/)
{
DoScriptText(SAY_AGGRO, me);
if (pInstance)
pInstance->SetData(DATA_MEATHOOK_EVENT, IN_PROGRESS);
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
if (uiDiseaseTimer <= diff)
{
DoCastAOE(DUNGEON_MODE(SPELL_DISEASE_EXPULSION, H_SPELL_DISEASE_EXPULSION));
uiDiseaseTimer = urand(3000, 5000);
} else uiDiseaseTimer -= diff;
if (uiFrenzyTimer <= diff)
{
DoCast(me, SPELL_FRENZY);
uiFrenzyTimer = urand(17000, 20000);
} else uiFrenzyTimer -= diff;
if (uiChainTimer <= diff)
{
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true))
DoCast(pTarget, DUNGEON_MODE(SPELL_CONSTRICTING_CHAINS, H_SPELL_CONSTRICTING_CHAINS)); //anyone but the tank
else
DoCast(me->getVictim(), DUNGEON_MODE(SPELL_CONSTRICTING_CHAINS, H_SPELL_CONSTRICTING_CHAINS));
uiChainTimer = urand(15000, 16000);
} else uiChainTimer -= diff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/)
{
DoScriptText(SAY_DEATH, me);
if (pInstance)
pInstance->SetData(DATA_MEATHOOK_EVENT, DONE);
}
void KilledUnit(Unit* victim)
{
if (victim == me)
return;
DoScriptText(RAND(SAY_SLAY_1,SAY_SLAY_2,SAY_SLAY_3), me);
}
};
};
void AddSC_boss_meathook()
{
new boss_meathook();
}
| gpl-2.0 |
ACP3/module-system | Resources/Assets/js/ajax-form.js | 12758 | /*
* Copyright (c) by the ACP3 Developers.
* See the LICENSE file at the top-level module directory for licencing details.
*/
(function ($, window, document) {
'use strict';
let pluginName = 'formSubmit',
defaults = {
targetElement: '#content',
loadingOverlay: true,
loadingText: '',
customFormData: null
};
function Plugin(element, options) {
this.element = element;
this.isFormValid = true;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function () {
const that = this;
this.mergeSettings();
this.findSubmitButton();
this.addLoadingLayer();
this.element.noValidate = true;
$(this.element).on('submit', function (e) {
e.preventDefault();
that.isFormValid = true;
$(document).trigger('acp3.ajaxFrom.submit.before', [that]);
if (that.isFormValid && that.preValidateForm(that.element)) {
that.processAjaxRequest();
}
}).on('click', function (e) {
if ($(this).prop('tagName') === 'A') {
e.preventDefault();
that.processAjaxRequest();
}
}).on('change', function () {
if (that.isFormValid === false) {
that.removeAllPreviousErrors();
that.checkFormElementsForErrors(that.element);
}
});
},
mergeSettings: function () {
const data = $(this.element).data();
for (let key in data) {
if (data.hasOwnProperty(key)) {
const keyStripped = this.lowerCaseFirstLetter(key.replace('ajaxForm', ''));
if (keyStripped.length > 0 && typeof this.settings[keyStripped] !== 'undefined') {
this.settings[keyStripped] = data[key];
}
}
}
},
lowerCaseFirstLetter: function (string) {
return string.charAt(0).toLowerCase() + string.slice(1);
},
findSubmitButton: function () {
$(this.element).find(':submit').click(function () {
$(':submit', $(this).closest('form')).removeAttr('data-clicked');
$(this).attr('data-clicked', 'true');
});
},
preValidateForm: function (form) {
this.removeAllPreviousErrors();
this.checkFormElementsForErrors(form);
this.focusTabWithFirstErrorMessage();
return this.isFormValid;
},
removeAllPreviousErrors: function () {
$('form .form-group.has-error')
.removeClass('has-error')
.find('.validation-failed').remove();
},
checkFormElementsForErrors: function (form) {
for (let i = 0; i < form.elements.length; i++) {
const field = form.elements[i];
if (field.nodeName !== 'INPUT' && field.nodeName !== 'TEXTAREA' && field.nodeName !== 'SELECT') {
continue;
}
if (!field.checkValidity()) {
this.addErrorDecorationToFormGroup($(field));
this.addErrorMessageToFormField($(field), field.validationMessage);
this.isFormValid = false;
}
}
},
addErrorDecorationToFormGroup: function ($elem) {
$elem.closest('.form-group').addClass('has-error');
},
removeErrorMessageFromFormField: function ($elem) {
$elem.closest('div').find('.validation-failed').remove();
},
addErrorMessageToFormField: function ($formField, errorMessage) {
this.removeErrorMessageFromFormField($formField);
$formField
.closest('div:not(.input-group):not(.btn-group)')
.append(
'<small class="help-block validation-failed"><i class="glyphicon glyphicon-remove"></i> ' + errorMessage + '</small>'
);
},
focusTabWithFirstErrorMessage: function () {
if ($('.tabbable').length > 0) {
let $elem = $('.tabbable .form-group.has-error:first'),
tabId = $elem.closest('.tab-pane').prop('id');
$('.tabbable .nav-tabs a[href="#' + tabId + '"]').tab('show');
$elem.find(':input').focus();
}
},
processAjaxRequest: function () {
const $form = $(this.element),
hasCustomData = !$.isEmptyObject(this.settings.customFormData);
let hash,
processData = true,
data = this.settings.customFormData || {},
$submitButton;
if ($form.attr('method')) {
$submitButton = $(':submit[data-clicked="true"]', $form);
hash = $submitButton.data('hashChange');
data = new FormData($form[0]);
if ($submitButton.length) {
data.append($submitButton.attr('name'), 1);
}
if (hasCustomData) {
for (let key in this.settings.customFormData) {
if (this.settings.customFormData.hasOwnProperty(key)) {
data.append(key, this.settings.customFormData[key]);
}
}
}
processData = false;
} else {
hash = $form.data('hashChange');
}
$.ajax({
url: $form.attr('action') || $form.attr('href'),
type: $form.attr('method') ? $form.attr('method').toUpperCase() : 'GET',
data: data,
processData: processData,
contentType: processData ? 'application/x-www-form-urlencoded; charset=UTF-8' : false,
beforeSend: () => {
this.showLoadingLayer($submitButton);
this.disableSubmitButton($submitButton);
}
}).done((responseData) => {
try {
let callback = $form.data('ajax-form-complete-callback');
if (typeof window[callback] === 'function') {
window[callback](responseData);
} else if (responseData.redirect_url) {
this.redirectToNewPage(hash, responseData);
} else {
this.scrollIntoView();
this.replaceContent(hash, responseData);
this.rebindHandlers(hash);
if (typeof hash !== 'undefined') {
window.location.hash = hash;
}
}
} catch (err) {
console.error(err.message);
}
}).fail((jqXHR) => {
if (jqXHR.status === 400) {
this.handleFormErrorMessages($form, jqXHR.responseText);
this.scrollIntoView();
$(document).trigger('acp3.ajaxFrom.submit.fail', [this]);
} else if (jqXHR.responseText.length > 0) {
document.open();
document.write(jqXHR.responseText);
document.close();
}
}).always(() => {
this.hideLoadingLayer();
this.enableSubmitButton($submitButton);
});
},
addLoadingLayer: function () {
if (this.settings.loadingOverlay === false) {
return;
}
let $loadingLayer = $('#loading-layer');
if ($loadingLayer.length === 0) {
let $body = $('body'),
loadingText = this.settings.loadingText || '',
html = '<div id="loading-layer" class="loading-layer"><h1><span class="glyphicon glyphicon-cog"></span>' + loadingText + '</h1></div>';
$(html).appendTo($body);
}
},
showLoadingLayer: function () {
$('#loading-layer').addClass('loading-layer__active');
},
disableSubmitButton: ($submitButton) => {
if (typeof $submitButton !== 'undefined') {
$submitButton.prop('disabled', true);
}
},
enableSubmitButton: ($submitButton) => {
if (typeof $submitButton !== 'undefined') {
$submitButton.prop('disabled', false);
}
},
redirectToNewPage: function (hash, responseData) {
if (typeof hash !== 'undefined') {
window.location.href = responseData.redirect_url + hash;
window.location.reload();
} else {
window.location.href = responseData.redirect_url;
}
},
/**
* Scroll to the beginning of the content area, if the current viewport is near the bottom
*/
scrollIntoView: function () {
const offsetTop = $(this.settings.targetElement).offset().top;
if ($(document).scrollTop() > offsetTop) {
$('html, body').animate(
{
scrollTop: offsetTop
},
'fast'
);
}
},
replaceContent: function (hash, responseData) {
if (hash && $(hash).length) {
$(hash).html($(responseData).find(hash).html());
} else {
$(this.settings.targetElement).html(responseData);
}
},
rebindHandlers: function (hash) {
const $bindingTarget = (hash && $(hash).length) ? $(hash) : $(this.settings.targetElement);
$bindingTarget.find('[data-ajax-form="true"]').formSubmit();
this.findSubmitButton();
},
hideLoadingLayer: function () {
$('#loading-layer').removeClass('loading-layer__active');
},
handleFormErrorMessages: function ($form, errorMessagesHtml) {
const $errorBox = $('#error-box'),
$modalBody = $form.find('.modal-body');
$errorBox.remove();
// Place the error messages inside the modal body for a better styling
$(errorMessagesHtml)
.hide()
.prependTo(($modalBody.length > 0 && $modalBody.is(':visible')) ? $modalBody : $form)
.fadeIn();
this.prettyPrintResponseErrorMessages($($errorBox.selector));
},
prettyPrintResponseErrorMessages: function ($errorBox) {
const that = this;
this.removeAllPreviousErrors();
// highlight all input fields where the validation has failed
$errorBox.find('li').each(function () {
let $this = $(this),
errorClass = $this.data('error');
if (errorClass.length > 0) {
let $elem = $('[id|="' + errorClass + '"]').filter(':not([id$="container"])');
if ($elem.length > 0) {
that.addErrorDecorationToFormGroup($elem);
// Move the error message to the responsible input field(s)
// and remove the list item from the error box container
if ($elem.length === 1) {
that.addErrorMessageToFormField($elem, $this.html());
$this.remove();
}
}
}
});
// if all list items have been removed, remove the error box container too
if ($errorBox.find('li').length === 0) {
$errorBox.remove();
}
this.focusTabWithFirstErrorMessage();
}
});
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
jQuery(document).ready(function ($) {
$('[data-ajax-form="true"]').formSubmit();
$(document).on('draw.dt', function (e) {
$(e.target).find('[data-ajax-form="true"]').formSubmit();
});
});
| gpl-2.0 |
guezaqiezs/WebsiteTest | modules/mod_gtalk_chatback/mod_gtalk_chatback.php | 875 | <?php
/**
* Gtalk chatback badge module
*
* @package Gtalk
* @copyright (C) 2006-2008 E. Capoccetti
* @url http://zarateprop.com.ar /
* @author Esteban Capoccetti <[email protected]>
**/
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
# Module Parameters loading
$url = trim ($params->get('url', ''));
$tk = trim ($params->get('tk', ''));
$width = trim ($params->get('width', ''));
$height = trim ($params->get('height', ''));
$allowTransparency = intval ($params->get('allowTransparency', 1));
$frameBorder = intval ($params->get('frameBorder', 1));
?>
<IFRAME src="<?php echo $url?>?tk=<?php echo $tk?>&w=<?php echo $width?>&h=<?php echo $height?>" frameBorder=<?php echo $frameBorder?> width=<?php echo $width?> height=<?php echo $height?><?php echo $allowTransparency ? " allowTransparency" : "";?>></IFRAME>
| gpl-2.0 |
Insurgencygame/LivingDead | TheLivingDeadv0.1.sdd/units/unused/corfav.lua | 3269 | return {
corfav = {
acceleration = 0.10999999940395,
brakerate = 0.14499999582767,
buildcostenergy = 256,
buildcostmetal = 24,
buildpic = "CORFAV.DDS",
buildtime = 1104,
canmove = true,
category = "ALL TANK MOBILE WEAPON NOTSUB NOTSHIP NOTAIR NOTHOVER SURFACE GROUNDSCOUT",
corpse = "DEAD",
description = "Light Scout Vehicle",
energymake = 0.30000001192093,
energyuse = 0.30000001192093,
explodeas = "SMALL_UNITEX",
footprintx = 2,
footprintz = 2,
idleautoheal = 5,
idletime = 1800,
leavetracks = true,
maxdamage = 95,
maxslope = 26,
maxvelocity = 4.8899998664856,
maxwaterdepth = 12,
movementclass = "TANK2",
name = "Weasel",
nochasecategory = "VTOL",
objectname = "CORFAV",
seismicsignature = 0,
selfdestructas = "SMALL_UNIT",
sightdistance = 535,
trackoffset = -3,
trackstrength = 3,
tracktype = "StdTank",
trackwidth = 27,
turnrate = 1097,
featuredefs = {
dead = {
blocking = false,
category = "corpses",
collisionvolumeoffsets = "0.0 -2.81028394531 1.25487518311",
collisionvolumescales = "27.7855834961 9.28491210938 30.4499664307",
collisionvolumetype = "Box",
damage = 132,
description = "Weasel Wreckage",
energy = 0,
featuredead = "HEAP",
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 20,
hitdensity = 100,
metal = 16,
object = "CORFAV_DEAD",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
heap = {
blocking = false,
category = "heaps",
damage = 66,
description = "Weasel Heap",
energy = 0,
featurereclamate = "SMUDGE01",
footprintx = 2,
footprintz = 2,
height = 4,
hitdensity = 100,
metal = 6,
object = "2X2B",
reclaimable = true,
seqnamereclamate = "TREE1RECLAMATE",
world = "All Worlds",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "vcormove",
},
select = {
[1] = "vcorsel",
},
},
weapondefs = {
core_laser = {
areaofeffect = 8,
beamtime = 0.18000000715256,
burstrate = 0.20000000298023,
corethickness = 0.10000000149012,
craterboost = 0,
cratermult = 0,
duration = 0.019999999552965,
energypershot = 5,
explosiongenerator = "custom:SMALL_YELLOW_BURN",
firestarter = 50,
hardstop = true,
impactonly = 1,
impulseboost = 0.12300000339746,
impulsefactor = 0.12300000339746,
laserflaresize = 5,
name = "Laser",
noselfdamage = true,
range = 180,
reloadtime = 1,
rgbcolor = "1 1 0",
soundstart = "lasrfir1",
soundtrigger = true,
targetmoveerror = 0.20000000298023,
thickness = 1,
tolerance = 10000,
turret = true,
weapontype = "BeamLaser",
weaponvelocity = 800,
damage = {
bombers = 2,
default = 35,
fighters = 2,
subs = 5,
vtol = 2,
},
},
},
weapons = {
[1] = {
badtargetcategory = "VTOL",
def = "CORE_LASER",
onlytargetcategory = "NOTSUB",
},
},
},
}
| gpl-2.0 |
zanderkyle/zandergraphics | components/com_ats/Controller/InstantReply.php | 1264 | <?php
/**
* @package AkeebaTicketSystem
* @copyright Copyright (c)2011-2015 Nicholas K. Dionysopoulos
* @license GNU General Public License version 3, or later
*/
namespace Akeeba\TicketSystem\Site\Controller;
use Akeeba\TicketSystem\Site\Model\Categories;
use FOF30\Container\Container;
use FOF30\Controller\DataController;
defined('_JEXEC') or die;
class InstantReply extends DataController
{
public function __construct(Container $container, array $config = array())
{
$config['cacheableTasks'] = array();
parent::__construct($container, $config);
}
protected function onBeforeBrowse()
{
// Get category information
$category_id = $this->input->getInt('catid',0);
/** @var Categories $catModel */
$catModel = $this->container->factory->model('Categories')->tmpInstance();
$category = $catModel->category($category_id)->get(true)->first();
if(!$category)
{
return false;
}
$params = new \JRegistry();
$params->loadString($category->params, 'JSON');
$docimportCategories = $params->get('dicats',array());
$this->getModel()->setState('dicats', $docimportCategories);
return true;
}
} | gpl-2.0 |
lizhekang/TCJDK | sources/openjdk8/jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java | 70131 | /*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.ja;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_ja extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"\u30a2\u30af\u30ec\u6642\u9593", "ACT",
"\u30a2\u30af\u30ec\u590f\u6642\u9593", "ACST",
"\u30a2\u30af\u30ec\u6642\u9593", "ACT"};
String ADELAIDE[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACT"};
String AGT[] = new String[] {"\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u6642\u9593", "ART",
"\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u590f\u6642\u9593", "ARST",
"\u30A2\u30EB\u30BC\u30F3\u30C1\u30F3\u6642\u9593", "ART"};
String AKST[] = new String[] {"\u30a2\u30e9\u30b9\u30ab\u6a19\u6e96\u6642", "AKST",
"\u30a2\u30e9\u30b9\u30ab\u590f\u6642\u9593", "AKDT",
"\u30A2\u30E9\u30B9\u30AB\u6642\u9593", "AKT"};
String AMT[] = new String[] {"\u30a2\u30de\u30be\u30f3\u6642\u9593", "AMT",
"\u30a2\u30de\u30be\u30f3\u590f\u6642\u9593", "AMST",
"\u30A2\u30DE\u30BE\u30F3\u6642\u9593", "AMT"};
String ARAST[] = new String[] {"\u30a2\u30e9\u30d3\u30a2\u6a19\u6e96\u6642", "AST",
"\u30a2\u30e9\u30d3\u30a2\u590f\u6642\u9593", "ADT",
"\u30A2\u30E9\u30D3\u30A2\u6642\u9593", "AT"};
String ARMT[] = new String[] {"\u30a2\u30eb\u30e1\u30cb\u30a2\u6642\u9593", "AMT",
"\u30a2\u30eb\u30e1\u30cb\u30a2\u590f\u6642\u9593", "AMST",
"\u30A2\u30EB\u30E1\u30CB\u30A2\u6642\u9593", "AMT"};
String AST[] = new String[] {"\u5927\u897f\u6d0b\u6a19\u6e96\u6642", "AST",
"\u5927\u897f\u6d0b\u590f\u6642\u9593", "ADT",
"\u5927\u897F\u6D0B\u6A19\u6E96\u6642", "AT"};
String BDT[] = new String[] {"\u30d0\u30f3\u30b0\u30e9\u30c7\u30b7\u30e5\u6642\u9593", "BDT",
"\u30d0\u30f3\u30b0\u30e9\u30c7\u30b7\u30e5\u590f\u6642\u9593", "BDST",
"\u30D0\u30F3\u30B0\u30E9\u30C7\u30B7\u30E5\u6642\u9593", "BDT"};
String BRISBANE[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AET"};
String BROKEN_HILL[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACT"};
String BRT[] = new String[] {"\u30d6\u30e9\u30b8\u30eb\u6642\u9593", "BRT",
"\u30d6\u30e9\u30b8\u30eb\u590f\u6642\u9593", "BRST",
"\u30D6\u30E9\u30B8\u30EA\u30A2\u6642\u9593", "BRT"};
String BTT[] = new String[] {"\u30d6\u30fc\u30bf\u30f3\u6642\u9593", "BTT",
"\u30d6\u30fc\u30bf\u30f3\u590f\u6642\u9593", "BTST",
"\u30D6\u30FC\u30BF\u30F3\u6642\u9593", "BTT"};
String CAT[] = new String[] {"\u4e2d\u90e8\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "CAT",
"\u4e2d\u90e8\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "CAST",
"\u4E2D\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "CAT"};
String CET[] = new String[] {"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "CET",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "CEST",
"\u4E2D\u90E8\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "CET"};
String CHAST[] = new String[] {"\u30c1\u30e3\u30bf\u30e0\u6a19\u6e96\u6642", "CHAST",
"\u30c1\u30e3\u30bf\u30e0\u590f\u6642\u9593", "CHADT",
"\u30C1\u30E3\u30BF\u30E0\u6642\u9593", "CHAT"};
String CHUT[] = new String[] {"\u30C1\u30E5\u30FC\u30AF\u6642\u9593", "CHUT",
"Chuuk Time", "CHUST",
"\u30C1\u30E5\u30FC\u30AF\u6642\u9593", "CHUT"};
String CIT[] = new String[] {"\u4e2d\u592e\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WITA",
"\u4e2d\u592e\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "CIST",
"\u4E2D\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WITA"};
String CLT[] = new String[] {"\u30c1\u30ea\u6642\u9593", "CLT",
"\u30c1\u30ea\u590f\u6642\u9593", "CLST",
"\u30C1\u30EA\u6642\u9593", "CLT"};
String CST[] = new String[] {"\u4e2d\u90e8\u6a19\u6e96\u6642", "CST",
"\u4e2d\u90e8\u590f\u6642\u9593", "CDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642", "CT"};
String CTT[] = new String[] {"\u4e2d\u56fd\u6a19\u6e96\u6642", "CST",
"\u4e2d\u56fd\u590f\u6642\u9593", "CDT",
"\u4E2D\u56FD\u6642\u9593", "CT"};
String CUBA[] = new String[] {"\u30ad\u30e5\u30fc\u30d0\u6a19\u6e96\u6642", "CST",
"\u30ad\u30e5\u30fc\u30d0\u590f\u6642\u9593", "CDT",
"\u30AD\u30E5\u30FC\u30D0\u6642\u9593", "CT"};
String DARWIN[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACT"};
String DUBLIN[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30a2\u30a4\u30eb\u30e9\u30f3\u30c9\u590f\u6642\u9593", "IST",
"\u30A2\u30A4\u30EB\u30E9\u30F3\u30C9\u6642\u9593", "IT"};
String EAT[] = new String[] {"\u6771\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "EAT",
"\u6771\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "EAST",
"\u6771\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "EAT"};
String EASTER[] = new String[] {"\u30a4\u30fc\u30b9\u30bf\u30fc\u5cf6\u6642\u9593", "EAST",
"\u30a4\u30fc\u30b9\u30bf\u30fc\u5cf6\u590f\u6642\u9593", "EASST",
"\u30A4\u30FC\u30B9\u30BF\u30FC\u5CF6\u6642\u9593", "EAST"};
String EET[] = new String[] {"\u6771\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "EET",
"\u6771\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "EEST",
"\u6771\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "EET"};
String EGT[] = new String[] {"\u6771\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u6642\u9593", "EGT",
"\u6771\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u590f\u6642\u9593", "EGST",
"\u6771\u90E8\u30B0\u30EA\u30FC\u30F3\u30E9\u30F3\u30C9\u6642\u9593", "EGT"};
String EST[] = new String[] {"\u6771\u90e8\u6a19\u6e96\u6642", "EST",
"\u6771\u90e8\u590f\u6642\u9593", "EDT",
"\u6771\u90E8\u6A19\u6E96\u6642", "ET"};
String EST_NSW[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AET"};
String FET[] = new String[] {"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "FET",
"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u590F\u6642\u9593", "FEST",
"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "FET"};
String GHMT[] = new String[] {"\u30ac\u30fc\u30ca\u6a19\u6e96\u6642", "GMT",
"\u30ac\u30fc\u30ca\u590f\u6642\u9593", "GHST",
"\u30AC\u30FC\u30CA\u6A19\u6E96\u6642", "GMT"};
String GAMBIER[] = new String[] {"\u30ac\u30f3\u30d3\u30a2\u6642\u9593", "GAMT",
"\u30ac\u30f3\u30d3\u30a2\u590f\u6642\u9593", "GAMST",
"\u30AC\u30F3\u30D3\u30A8\u6642\u9593", "GAMT"};
String GMT[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30B0\u30EA\u30CB\u30C3\u30B8\u6A19\u6E96\u6642", "GMT"};
String GMTBST[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u82f1\u56fd\u590f\u6642\u9593", "BST",
"\u30A4\u30AE\u30EA\u30B9\u6642\u9593", "BT"};
String GST[] = new String[] {"\u6e7e\u5cb8\u6a19\u6e96\u6642", "GST",
"\u6e7e\u5cb8\u590f\u6642\u9593", "GDT",
"\u6E7E\u5CB8\u6642\u9593", "GT"};
String HKT[] = new String[] {"\u9999\u6e2f\u6642\u9593", "HKT",
"\u9999\u6e2f\u590f\u6642\u9593", "HKST",
"\u9999\u6E2F\u6642\u9593", "HKT"};
String HST[] = new String[] {"\u30cf\u30ef\u30a4\u6a19\u6e96\u6642", "HST",
"\u30cf\u30ef\u30a4\u590f\u6642\u9593", "HDT",
"\u30CF\u30EF\u30A4\u6642\u9593", "HT"};
String ICT[] = new String[] {"\u30a4\u30f3\u30c9\u30b7\u30ca\u6642\u9593", "ICT",
"\u30a4\u30f3\u30c9\u30b7\u30ca\u590f\u6642\u9593", "ICST",
"\u30A4\u30F3\u30C9\u30B7\u30CA\u6642\u9593", "ICT"};
String IRKT[] = new String[] {"\u30a4\u30eb\u30af\u30fc\u30c4\u30af\u6642\u9593", "IRKT",
"\u30a4\u30eb\u30af\u30fc\u30c4\u30af\u590f\u6642\u9593", "IRKST",
"\u30A4\u30EB\u30AF\u30FC\u30C4\u30AF\u6642\u9593", "IRKT"};
String IRT[] = new String[] {"\u30a4\u30e9\u30f3\u6a19\u6e96\u6642", "IRST",
"\u30a4\u30e9\u30f3\u590f\u6642\u9593", "IRDT",
"\u30A4\u30E9\u30F3\u6642\u9593", "IRT"};
String ISRAEL[] = new String[] {"\u30a4\u30b9\u30e9\u30a8\u30eb\u6a19\u6e96\u6642", "IST",
"\u30a4\u30b9\u30e9\u30a8\u30eb\u590f\u6642\u9593", "IDT",
"\u30A4\u30B9\u30E9\u30A8\u30EB\u6642\u9593", "IT"};
String IST[] = new String[] {"\u30a4\u30f3\u30c9\u6a19\u6e96\u6642", "IST",
"\u30a4\u30f3\u30c9\u590f\u6642\u9593", "IDT",
"\u30A4\u30F3\u30C9\u6642\u9593", "IT"};
String JST[] = new String[] {"\u65e5\u672c\u6a19\u6e96\u6642", "JST",
"\u65e5\u672c\u590f\u6642\u9593", "JDT",
"\u65E5\u672C\u6642\u9593", "JT"};
String KRAT[] = new String[] {"\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u6642\u9593", "KRAT",
"\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u590f\u6642\u9593", "KRAST",
"\u30AF\u30E9\u30B9\u30CE\u30E4\u30EB\u30B9\u30AF\u6642\u9593", "KRAT"};
String KST[] = new String[] {"\u97d3\u56fd\u6a19\u6e96\u6642", "KST",
"\u97d3\u56fd\u590f\u6642\u9593", "KDT",
"\u97D3\u56FD\u6642\u9593", "KT"};
String LORD_HOWE[] = new String[] {"\u30ed\u30fc\u30c9\u30cf\u30a6\u5cf6\u6a19\u6e96\u6642", "LHST",
"\u30ed\u30fc\u30c9\u30cf\u30a6\u5cf6\u590f\u6642\u9593", "LHDT",
"\u30ED\u30FC\u30C9\u30CF\u30A6\u6642\u9593", "LHT"};
String MHT[] = new String[] {"\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u6642\u9593", "MHT",
"\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u590f\u6642\u9593", "MHST",
"\u30DE\u30FC\u30B7\u30E3\u30EB\u8AF8\u5CF6\u6642\u9593", "MHT"};
String MSK[] = new String[] {"\u30e2\u30b9\u30af\u30ef\u6a19\u6e96\u6642", "MSK",
"\u30e2\u30b9\u30af\u30ef\u590f\u6642\u9593", "MSD",
"\u30E2\u30B9\u30AF\u30EF\u6642\u9593", "MT"};
String MST[] = new String[] {"\u5c71\u5730\u6a19\u6e96\u6642", "MST",
"\u5c71\u5730\u590f\u6642\u9593", "MDT",
"\u5C71\u5730\u6A19\u6E96\u6642", "MT"};
String MYT[] = new String[] {"\u30de\u30ec\u30fc\u30b7\u30a2\u6642\u9593", "MYT",
"\u30de\u30ec\u30fc\u30b7\u30a2\u590f\u6642\u9593", "MYST",
"\u30DE\u30EC\u30FC\u30B7\u30A2\u6642\u9593", "MYT"};
String NORONHA[] = new String[] {"\u30d5\u30a7\u30eb\u30ca\u30f3\u30c9\u30fb\u30c7\u30fb\u30ce\u30ed\u30fc\u30cb\u30e3\u6642\u9593", "FNT",
"\u30d5\u30a7\u30eb\u30ca\u30f3\u30c9\u30fb\u30c7\u30fb\u30ce\u30ed\u30fc\u30cb\u30e3\u590f\u6642\u9593", "FNST",
"\u30D5\u30A7\u30EB\u30CA\u30F3\u30C9\u30FB\u30C7\u30FB\u30CE\u30ED\u30FC\u30CB\u30E3\u6642\u9593", "FNT"};
String NOVT[] = new String[] {"\u30ce\u30dc\u30b7\u30d3\u30eb\u30b9\u30af\u6642\u9593", "NOVT",
"\u30ce\u30dc\u30b7\u30d3\u30eb\u30b9\u30af\u590f\u6642\u9593", "NOVST",
"\u30CE\u30F4\u30A9\u30B7\u30D3\u30EB\u30B9\u30AF\u6642\u9593", "NOVT"};
String NPT[] = new String[] {"\u30cd\u30d1\u30fc\u30eb\u6642\u9593", "NPT",
"\u30cd\u30d1\u30fc\u30eb\u590f\u6642\u9593", "NPST",
"\u30CD\u30D1\u30FC\u30EB\u6642\u9593", "NPT"};
String NST[] = new String[] {"\u30cb\u30e5\u30fc\u30d5\u30a1\u30f3\u30c9\u30e9\u30f3\u30c9\u6a19\u6e96\u6642", "NST",
"\u30cb\u30e5\u30fc\u30d5\u30a1\u30f3\u30c9\u30e9\u30f3\u30c9\u590f\u6642\u9593", "NDT",
"\u30CB\u30E5\u30FC\u30D5\u30A1\u30F3\u30C9\u30E9\u30F3\u30C9\u6642\u9593", "NT"};
String NZST[] = new String[] {"\u30cb\u30e5\u30fc\u30b8\u30fc\u30e9\u30f3\u30c9\u6a19\u6e96\u6642", "NZST",
"\u30cb\u30e5\u30fc\u30b8\u30fc\u30e9\u30f3\u30c9\u590f\u6642\u9593", "NZDT",
"\u30CB\u30E5\u30FC\u30B8\u30FC\u30E9\u30F3\u30C9\u6642\u9593", "NZT"};
String PITCAIRN[] = new String[] {"\u30d4\u30c8\u30b1\u30eb\u30f3\u5cf6\u6a19\u6e96\u6642", "PST",
"\u30d4\u30c8\u30b1\u30eb\u30f3\u5cf6\u590f\u6642\u9593", "PDT",
"\u30D4\u30C8\u30B1\u30A2\u30F3\u6642\u9593", "PT"};
String PKT[] = new String[] {"\u30d1\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "PKT",
"\u30d1\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "PKST",
"\u30D1\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "PKT"};
String PONT[] = new String[] {"\u30DD\u30F3\u30DA\u30A4\u6642\u9593", "PONT",
"\u30DD\u30F3\u30DA\u30A4\u590F\u6642\u9593", "PONST",
"\u30DD\u30CA\u30DA\u6642\u9593", "PONT"};
String PST[] = new String[] {"\u592a\u5e73\u6d0b\u6a19\u6e96\u6642", "PST",
"\u592a\u5e73\u6d0b\u590f\u6642\u9593", "PDT",
"\u592A\u5E73\u6D0B\u6A19\u6E96\u6642", "PT"};
String SAST[] = new String[] {"\u5357\u30a2\u30d5\u30ea\u30ab\u6a19\u6e96\u6642", "SAST",
"\u5357\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "SAST",
"\u5357\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "SAT"};
String SBT[] = new String[] {"\u30bd\u30ed\u30e2\u30f3\u8af8\u5cf6\u6642\u9593", "SBT",
"\u30bd\u30ed\u30e2\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "SBST",
"\u30BD\u30ED\u30E2\u30F3\u8AF8\u5CF6\u6642\u9593", "SBT"};
String SGT[] = new String[] {"\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb\u6642\u9593", "SGT",
"\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb\u590f\u6642\u9593", "SGST",
"\u30B7\u30F3\u30AC\u30DD\u30FC\u30EB\u6642\u9593", "SGT"};
String TASMANIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AET"};
String TMT[] = new String[] {"\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3\u6642\u9593", "TMT",
"\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3\u590f\u6642\u9593", "TMST",
"\u30C8\u30EB\u30AF\u30E1\u30CB\u30B9\u30BF\u30F3\u6642\u9593", "TMT"};
String ULAT[]= new String[] {"\u30a6\u30e9\u30fc\u30f3\u30d0\u30fc\u30c8\u30eb\u6642\u9593", "ULAT",
"\u30a6\u30e9\u30fc\u30f3\u30d0\u30fc\u30c8\u30eb\u590f\u6642\u9593", "ULAST",
"\u30A6\u30E9\u30F3\u30D0\u30FC\u30C8\u30EB\u6642\u9593", "ULAT"};
String WAT[] = new String[] {"\u897f\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "WAT",
"\u897f\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "WAST",
"\u897F\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "WAT"};
String WET[] = new String[] {"\u897f\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "WET",
"\u897f\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "WEST",
"\u897F\u90E8\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "WET"};
String WIT[] = new String[] {"\u897f\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WIB",
"\u897f\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "WIST",
"\u897F\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WIB"};
String WST_AUS[] = new String[] {"\u897F\u90E8\u6A19\u6E96\u6642(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWST",
"\u897F\u90E8\u590F\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWDT",
"\u897F\u90E8\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWT"};
String SAMOA[] = new String[] {"\u30b5\u30e2\u30a2\u6a19\u6e96\u6642", "SST",
"\u30b5\u30e2\u30a2\u590f\u6642\u9593", "SDT",
"\u30B5\u30E2\u30A2\u6642\u9593", "ST"};
String WST_SAMOA[] = new String[] {"\u897f\u30b5\u30e2\u30a2\u6642\u9593", "WSST",
"\u897f\u30b5\u30e2\u30a2\u590f\u6642\u9593", "WSDT",
"\u897F\u30B5\u30E2\u30A2\u6642\u9593", "WST"};
String ChST[] = new String[] {"\u30b0\u30a2\u30e0\u6a19\u6e96\u6642", "ChST",
"\u30b0\u30a2\u30e0\u590f\u6642\u9593", "ChDT",
"\u30C1\u30E3\u30E2\u30ED\u6642\u9593", "ChT"};
String VICTORIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AET"};
String UTC[] = new String[] {"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u5354\u5B9A\u4E16\u754C\u6642", "UTC"};
String UZT[] = new String[] {"\u30a6\u30ba\u30d9\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "UZT",
"\u30a6\u30ba\u30d9\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "UZST",
"\u30A6\u30BA\u30D9\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "UZT"};
String XJT[] = new String[] {"\u4e2d\u56fd\u6a19\u6e96\u6642", "XJT",
"\u4e2d\u56fd\u590f\u6642\u9593", "XJDT",
"\u4E2D\u56FD\u6642\u9593", "XJT"};
String YAKT[] = new String[] {"\u30e4\u30af\u30fc\u30c4\u30af\u6642\u9593", "YAKT",
"\u30e4\u30af\u30fc\u30c4\u30af\u590f\u6642\u9593", "YAKST",
"\u30E4\u30AF\u30FC\u30C4\u30AF\u6642\u9593", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", EAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", EAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", WAT},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"\u30d1\u30e9\u30b0\u30a2\u30a4\u6642\u9593", "PYT",
"\u30d1\u30e9\u30b0\u30a2\u30a4\u590f\u6642\u9593", "PYST",
"\u30D1\u30E9\u30B0\u30A2\u30A4\u6642\u9593", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"\u30b3\u30ed\u30f3\u30d3\u30a2\u6642\u9593", "COT",
"\u30b3\u30ed\u30f3\u30d3\u30a2\u590f\u6642\u9593", "COST",
"\u30B3\u30ED\u30F3\u30D3\u30A2\u6642\u9593", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"\u30d9\u30cd\u30ba\u30a8\u30e9\u6642\u9593", "VET",
"\u30d9\u30cd\u30ba\u30a8\u30e9\u590f\u6642\u9593", "VEST",
"\u30D9\u30CD\u30BA\u30A8\u30E9\u6642\u9593", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"\u4ecf\u9818\u30ae\u30a2\u30ca\u6642\u9593", "GFT",
"\u4ecf\u9818\u30ae\u30a2\u30ca\u590f\u6642\u9593", "GFST",
"\u30D5\u30E9\u30F3\u30B9\u9818\u30AE\u30A2\u30CA\u6642\u9593", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", PST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", new String[] {"\u897f\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u6642\u9593", "WGT",
"\u897f\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u590f\u6642\u9593", "WGST",
"\u897F\u90E8\u30B0\u30EA\u30FC\u30F3\u30E9\u30F3\u30C9\u6642\u9593", "WGT"}},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", AST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"\u30a8\u30af\u30a2\u30c9\u30eb\u6642\u9593", "ECT",
"\u30a8\u30af\u30a2\u30c9\u30eb\u590f\u6642\u9593", "ECST",
"\u30A8\u30AF\u30A2\u30C9\u30EB\u6642\u9593", "ECT"}},
{"America/Guyana", new String[] {"\u30ac\u30a4\u30a2\u30ca\u6642\u9593", "GYT",
"\u30ac\u30a4\u30a2\u30ca\u590f\u6642\u9593", "GYST",
"\u30AC\u30A4\u30A2\u30CA\u6642\u9593", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"\u30dc\u30ea\u30d3\u30a2\u6642\u9593", "BOT",
"\u30dc\u30ea\u30d3\u30a2\u590f\u6642\u9593", "BOST",
"\u30DC\u30EA\u30D3\u30A2\u6642\u9593", "BOT"}},
{"America/Lima", new String[] {"\u30da\u30eb\u30fc\u6642\u9593", "PET",
"\u30da\u30eb\u30fc\u590f\u6642\u9593", "PEST",
"\u30DA\u30EB\u30FC\u6642\u9593", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"\u30b5\u30f3\u30d4\u30a8\u30fc\u30eb\u30fb\u30df\u30af\u30ed\u30f3\u8af8\u5cf6\u6a19\u6e96\u6642", "PMST",
"\u30b5\u30f3\u30d4\u30a8\u30fc\u30eb\u30fb\u30df\u30af\u30ed\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "PMDT",
"\u30D4\u30A8\u30FC\u30EB\u30FB\u30DF\u30AF\u30ED\u30F3\u6642\u9593", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"\u30a6\u30eb\u30b0\u30a2\u30a4\u6642\u9593", "UYT",
"\u30a6\u30eb\u30b0\u30a2\u30a4\u590f\u6642\u9593", "UYST",
"\u30A6\u30EB\u30B0\u30A2\u30A4\u6642\u9593", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Ojinaga", MST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"\u30b9\u30ea\u30ca\u30e0\u6642\u9593", "SRT",
"\u30b9\u30ea\u30ca\u30e0\u590f\u6642\u9593", "SRST",
"\u30B9\u30EA\u30CA\u30E0\u6642\u9593", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", PST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"\u30c7\u30a4\u30d3\u30b9\u6642\u9593", "DAVT",
"\u30c7\u30a4\u30d3\u30b9\u590f\u6642\u9593", "DAVST",
"\u30C7\u30FC\u30D3\u30B9\u6642\u9593", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"\u30c7\u30e5\u30e2\u30f3\u30c7\u30e5\u30eb\u30f4\u30a3\u30eb\u6642\u9593", "DDUT",
"\u30c7\u30e5\u30e2\u30f3\u30c7\u30e5\u30eb\u30f4\u30a3\u30eb\u590f\u6642\u9593", "DDUST",
"\u30C7\u30E5\u30E2\u30F3\u30FB\u30C7\u30E5\u30EB\u30D3\u30EB\u6642\u9593", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"\u30DE\u30C3\u30B3\u30FC\u30EA\u30FC\u5CF6\u6642\u9593", "MIST",
"\u30DE\u30C3\u30B3\u30FC\u30EA\u30FC\u5CF6\u590F\u6642\u9593", "MIST",
"\u30DE\u30C3\u30B3\u30FC\u30EA\u30FC\u5CF6\u6642\u9593", "MIST"}},
{"Antarctica/Mawson", new String[] {"\u30e2\u30fc\u30bd\u30f3\u6642\u9593", "MAWT",
"\u30e2\u30fc\u30bd\u30f3\u590f\u6642\u9593", "MAWST",
"\u30E2\u30FC\u30BD\u30F3\u6642\u9593", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"\u30ed\u30bc\u30e9\u6642\u9593", "ROTT",
"\u30ed\u30bc\u30e9\u590f\u6642\u9593", "ROTST",
"\u30ED\u30BC\u30E9\u6642\u9593", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"\u662d\u548c\u57fa\u5730\u6642\u9593", "SYOT",
"\u662d\u548c\u57fa\u5730\u590f\u6642\u9593", "SYOST",
"\u662D\u548C\u57FA\u5730\u6642\u9593", "SYOT"}},
{"Antarctica/Troll", new String[] {"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"\u30dc\u30b9\u30c8\u30fc\u30af\u57fa\u5730\u6642\u9593", "VOST",
"\u30dc\u30b9\u30c8\u30fc\u30af\u57fa\u5730\u590f\u6642\u9593", "VOSST",
"\u30DC\u30B9\u30C8\u30FC\u30AF\u6642\u9593", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"\u30a2\u30eb\u30de\u30a2\u30bf\u6642\u9593", "ALMT",
"\u30a2\u30eb\u30de\u30a2\u30bf\u590f\u6642\u9593", "ALMST",
"\u30A2\u30EB\u30DE\u30A2\u30BF\u6642\u9593", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"\u30a2\u30ca\u30c9\u30a5\u30a4\u30ea\u6642\u9593", "ANAT",
"\u30a2\u30ca\u30c9\u30a5\u30a4\u30ea\u590f\u6642\u9593", "ANAST",
"\u30A2\u30CA\u30C7\u30A3\u30EA\u6642\u9593", "ANAT"}},
{"Asia/Aqtau", new String[] {"\u30a2\u30af\u30bf\u30a6\u6642\u9593", "AQTT",
"\u30a2\u30af\u30bf\u30a6\u590f\u6642\u9593", "AQTST",
"\u30A2\u30AF\u30BF\u30A6\u6642\u9593", "AQTT"}},
{"Asia/Aqtobe", new String[] {"\u30a2\u30af\u30c8\u30d9\u6642\u9593", "AQTT",
"\u30a2\u30af\u30c8\u30d9\u590f\u6642\u9593", "AQTST",
"\u30A2\u30AF\u30C8\u30D9\u6642\u9593", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3\u6642\u9593", "AZT",
"\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3\u590f\u6642\u9593", "AZST",
"\u30A2\u30BC\u30EB\u30D0\u30A4\u30B8\u30E3\u30F3\u6642\u9593", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"\u30ad\u30eb\u30ae\u30b9\u30bf\u30f3\u6642\u9593", "KGT",
"\u30ad\u30eb\u30ae\u30b9\u30bf\u30f3\u590f\u6642\u9593", "KGST",
"\u30AD\u30EB\u30AE\u30B9\u6642\u9593", "KGT"}},
{"Asia/Brunei", new String[] {"\u30d6\u30eb\u30cd\u30a4\u6642\u9593", "BNT",
"\u30d6\u30eb\u30cd\u30a4\u590f\u6642\u9593", "BNST",
"\u30D6\u30EB\u30CD\u30A4\u6642\u9593", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"\u30c1\u30e7\u30a4\u30d0\u30eb\u30b5\u30f3\u6642\u9593", "CHOT",
"\u30c1\u30e7\u30a4\u30d0\u30eb\u30b5\u30f3\u590f\u6642\u9593", "CHOST",
"\u30C1\u30E7\u30A4\u30D0\u30EB\u30B5\u30F3\u6642\u9593", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"\u6771\u30c6\u30a3\u30e2\u30fc\u30eb\u6642\u9593", "TLT",
"\u6771\u30c6\u30a3\u30e2\u30fc\u30eb\u590f\u6642\u9593", "TLST",
"\u6771\u30C6\u30A3\u30E2\u30FC\u30EB\u6642\u9593", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "TJT",
"\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "TJST",
"\u30BF\u30B8\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"\u30db\u30d6\u30c9\u6642\u9593", "HOVT",
"\u30db\u30d6\u30c9\u590f\u6642\u9593", "HOVST",
"\u30DB\u30D6\u30C9\u6642\u9593", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"\u6771\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WIT",
"\u6771\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "EIST" ,
"\u6771\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WIT"}},
{"Asia/Kabul", new String[] {"\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3\u6642\u9593", "AFT",
"\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3\u590f\u6642\u9593", "AFST",
"\u30A2\u30D5\u30AC\u30CB\u30B9\u30BF\u30F3\u6642\u9593", "AFT"}},
{"Asia/Kamchatka", new String[] {"\u30da\u30c8\u30ed\u30d1\u30d6\u30ed\u30d5\u30b9\u30af\u30ab\u30e0\u30c1\u30e3\u30c4\u30ad\u30fc\u6642\u9593", "PETT",
"\u30da\u30c8\u30ed\u30d1\u30d6\u30ed\u30d5\u30b9\u30af\u30ab\u30e0\u30c1\u30e3\u30c4\u30ad\u30fc\u590f\u6642\u9593", "PETST",
"\u30DA\u30C8\u30ED\u30D1\u30D6\u30ED\u30D5\u30B9\u30AF\u30FB\u30AB\u30E0\u30C1\u30E3\u30C4\u30AD\u30FC\u6642\u9593", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"\u30de\u30ac\u30c0\u30f3\u6642\u9593", "MAGT",
"\u30de\u30ac\u30c0\u30f3\u590f\u6642\u9593", "MAGST",
"\u30DE\u30AC\u30C0\u30F3\u6642\u9593", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"\u30d5\u30a3\u30ea\u30d4\u30f3\u6642\u9593", "PHT",
"\u30d5\u30a3\u30ea\u30d4\u30f3\u590f\u6642\u9593", "PHST",
"\u30D5\u30A3\u30EA\u30D4\u30F3\u6642\u9593", "PHT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"\u30aa\u30e9\u30eb\u6642\u9593", "ORAT",
"\u30aa\u30e9\u30eb\u590f\u6642\u9593", "ORAST",
"\u30AA\u30E9\u30EB\u6642\u9593", "ORAT"}},
{"Asia/Omsk", new String[] {"\u30aa\u30e0\u30b9\u30af\u6642\u9593", "OMST",
"\u30aa\u30e0\u30b9\u30af\u590f\u6642\u9593", "OMSST",
"\u30AA\u30E0\u30B9\u30AF\u6642\u9593", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u6642\u9593", "QYZT",
"\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u590f\u6642\u9593", "QYZST",
"\u30AF\u30BA\u30ED\u30EB\u30C0\u6642\u9593", "QYZT"}},
{"Asia/Rangoon", new String[] {"\u30df\u30e3\u30f3\u30de\u30fc\u6642\u9593", "MMT",
"\u30df\u30e3\u30f3\u30de\u30fc\u590f\u6642\u9593", "MMST",
"\u30DF\u30E3\u30F3\u30DE\u30FC\u6642\u9593", "MMT"}},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"\u6a3a\u592a\u6642\u9593", "SAKT",
"\u6a3a\u592a\u590f\u6642\u9593", "SAKST",
"\u30B5\u30CF\u30EA\u30F3\u6642\u9593", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", CTT},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"\u30b0\u30eb\u30b8\u30a2\u6642\u9593", "GET",
"\u30b0\u30eb\u30b8\u30a2\u590f\u6642\u9593", "GEST",
"\u30B0\u30EB\u30B8\u30A2\u6642\u9593", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"\u30A6\u30B9\u30C1\u30CD\u30E9\u6642\u9593", "VLAT",
"\u30A6\u30B9\u30C1\u30CD\u30E9\u590F\u6642\u9593", "VLAST",
"\u30A6\u30B9\u30C1\u30CD\u30E9\u6642\u9593", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"\u30a6\u30e9\u30b8\u30aa\u30b9\u30c8\u30af\u6642\u9593", "VLAT",
"\u30a6\u30e9\u30b8\u30aa\u30b9\u30c8\u30af\u590f\u6642\u9593", "VLAST",
"\u30A6\u30E9\u30B8\u30AA\u30B9\u30C8\u30AF\u6642\u9593", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yekaterinburg", new String[] {"\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u6642\u9593", "YEKT",
"\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u590f\u6642\u9593", "YEKST",
"\u30A8\u30AB\u30C6\u30EA\u30F3\u30D6\u30EB\u30AF\u6642\u9593", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"\u30a2\u30be\u30ec\u30b9\u6642\u9593", "AZOT",
"\u30a2\u30be\u30ec\u30b9\u590f\u6642\u9593", "AZOST",
"\u30A2\u30BE\u30EC\u30B9\u6642\u9593", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"\u30ab\u30fc\u30dc\u30d9\u30eb\u30c7\u6642\u9593", "CVT",
"\u30ab\u30fc\u30dc\u30d9\u30eb\u30c7\u590f\u6642\u9593", "CVST",
"\u30AB\u30FC\u30DC\u30D9\u30EB\u30C7\u6642\u9593", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"\u5357\u30b8\u30e7\u30fc\u30b8\u30a2\u5cf6\u6a19\u6e96\u6642", "GST",
"\u5357\u30b8\u30e7\u30fc\u30b8\u30a2\u5cf6\u590f\u6642\u9593", "GDT",
"\u5357\u30B8\u30E7\u30FC\u30B8\u30A2\u6642\u9593", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"\u30d5\u30a9\u30fc\u30af\u30e9\u30f3\u30c9\u8af8\u5cf6\u6642\u9593", "FKT",
"\u30d5\u30a9\u30fc\u30af\u30e9\u30f3\u30c9\u8af8\u5cf6\u590f\u6642\u9593", "FKST",
"\u30D5\u30A9\u30FC\u30AF\u30E9\u30F3\u30C9\u8AF8\u5CF6\u6642\u9593", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"\u4E2D\u897F\u90E8\u6A19\u6E96\u6642(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWST",
"\u4E2D\u897F\u90E8\u590F\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWDT",
"\u4E2D\u897F\u90E8\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/East-Saskatchewan", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", PST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"\u30b5\u30de\u30e9\u6642\u9593", "SAMT",
"\u30b5\u30de\u30e9\u590f\u6642\u9593", "SAMST",
"\u30B5\u30DE\u30E9\u6642\u9593", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"\u30a4\u30f3\u30c9\u6d0b\u5730\u57df\u6642\u9593", "IOT",
"\u30a4\u30f3\u30c9\u6d0b\u5730\u57df\u590f\u6642\u9593", "IOST",
"\u30A4\u30F3\u30C9\u6D0B\u5730\u57DF\u6642\u9593", "IOT"}},
{"Indian/Christmas", new String[] {"\u30af\u30ea\u30b9\u30de\u30b9\u8af8\u5cf6\u6642\u9593", "CXT",
"\u30af\u30ea\u30b9\u30de\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "CXST",
"\u30AF\u30EA\u30B9\u30DE\u30B9\u5CF6\u6642\u9593", "CIT"}},
{"Indian/Cocos", new String[] {"\u30b3\u30b3\u30b9\u8af8\u5cf6\u6642\u9593", "CCT",
"\u30b3\u30b3\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "CCST",
"\u30B3\u30B3\u30B9\u8AF8\u5CF6\u6642\u9593", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"\u4ecf\u5357\u65b9\u9818\u304a\u3088\u3073\u5357\u6975\u6642\u9593", "TFT",
"\u4ecf\u5357\u65b9\u9818\u304a\u3088\u3073\u5357\u6975\u590f\u6642\u9593", "TFST",
"\u30D5\u30E9\u30F3\u30B9\u9818\u5357\u65B9\u304A\u3088\u3073\u5357\u6975\u5927\u9678\u6642\u9593", "TFT"}},
{"Indian/Mahe", new String[] {"\u30bb\u30a4\u30b7\u30a7\u30eb\u6642\u9593", "SCT",
"\u30bb\u30a4\u30b7\u30a7\u30eb\u590f\u6642\u9593", "SCST",
"\u30BB\u30FC\u30B7\u30A7\u30EB\u6642\u9593", "SCT"}},
{"Indian/Maldives", new String[] {"\u30e2\u30eb\u30b8\u30d6\u6642\u9593", "MVT",
"\u30e2\u30eb\u30b8\u30d6\u590f\u6642\u9593", "MVST",
"\u30E2\u30EB\u30B8\u30D6\u6642\u9593", "MVT"}},
{"Indian/Mauritius", new String[] {"\u30e2\u30fc\u30ea\u30b7\u30e3\u30b9\u6642\u9593", "MUT",
"\u30e2\u30fc\u30ea\u30b7\u30e3\u30b9\u590f\u6642\u9593", "MUST",
"\u30E2\u30FC\u30EA\u30B7\u30E3\u30B9\u6642\u9593", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"\u30ec\u30e6\u30cb\u30aa\u30f3\u6642\u9593", "RET",
"\u30ec\u30e6\u30cb\u30aa\u30f3\u590f\u6642\u9593", "REST",
"\u30EC\u30E6\u30CB\u30AA\u30F3\u6642\u9593", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "MET",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", CHUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"\u30d0\u30cc\u30a2\u30c4\u6642\u9593", "VUT",
"\u30d0\u30cc\u30a2\u30c4\u590f\u6642\u9593", "VUST",
"\u30D0\u30CC\u30A2\u30C4\u6642\u9593", "VUT"}},
{"Pacific/Enderbury", new String[] {"\u30d5\u30a7\u30cb\u30c3\u30af\u30b9\u8af8\u5cf6\u6642\u9593", "PHOT",
"\u30d5\u30a7\u30cb\u30c3\u30af\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "PHOST",
"\u30D5\u30A7\u30CB\u30C3\u30AF\u30B9\u8AF8\u5CF6\u6642\u9593", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"\u30c8\u30b1\u30e9\u30a6\u8af8\u5cf6\u6642\u9593", "TKT",
"\u30c8\u30b1\u30e9\u30a6\u8af8\u5cf6\u590f\u6642\u9593", "TKST",
"\u30C8\u30B1\u30E9\u30A6\u6642\u9593", "TKT"}},
{"Pacific/Fiji", new String[] {"\u30d5\u30a3\u30b8\u30fc\u6642\u9593", "FJT",
"\u30d5\u30a3\u30b8\u30fc\u590f\u6642\u9593", "FJST",
"\u30D5\u30A3\u30B8\u30FC\u6642\u9593", "FJT"}},
{"Pacific/Funafuti", new String[] {"\u30c4\u30d0\u30eb\u6642\u9593", "TVT",
"\u30c4\u30d0\u30eb\u590f\u6642\u9593", "TVST",
"\u30C4\u30D0\u30EB\u6642\u9593", "TVT"}},
{"Pacific/Galapagos", new String[] {"\u30ac\u30e9\u30d1\u30b4\u30b9\u6642\u9593", "GALT",
"\u30ac\u30e9\u30d1\u30b4\u30b9\u590f\u6642\u9593", "GALST",
"\u30AC\u30E9\u30D1\u30B4\u30B9\u6642\u9593", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"\u30e9\u30a4\u30f3\u8af8\u5cf6\u6642\u9593", "LINT",
"\u30e9\u30a4\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "LINST",
"\u30E9\u30A4\u30F3\u8AF8\u5CF6\u6642\u9593", "LINT"}},
{"Pacific/Kosrae", new String[] {"\u30b3\u30b9\u30e9\u30a8\u6642\u9593", "KOST",
"\u30b3\u30b9\u30e9\u30a8\u590f\u6642\u9593", "KOSST",
"\u30B3\u30B9\u30E9\u30A8\u6642\u9593", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"\u30de\u30eb\u30b1\u30b5\u30b9\u6642\u9593", "MART",
"\u30de\u30eb\u30b1\u30b5\u30b9\u590f\u6642\u9593", "MARST",
"\u30DE\u30EB\u30AD\u30FC\u30BA\u6642\u9593", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"\u30ca\u30a6\u30eb\u6642\u9593", "NRT",
"\u30ca\u30a6\u30eb\u590f\u6642\u9593", "NRST",
"\u30CA\u30A6\u30EB\u6642\u9593", "NRT"}},
{"Pacific/Niue", new String[] {"\u30cb\u30a6\u30a8\u5cf6\u6642\u9593", "NUT",
"\u30cb\u30a6\u30a8\u5cf6\u590f\u6642\u9593", "NUST",
"\u30CB\u30A6\u30A8\u6642\u9593", "NUT"}},
{"Pacific/Norfolk", new String[] {"\u30ce\u30fc\u30d5\u30a9\u30fc\u30af\u6642\u9593", "NFT",
"\u30ce\u30fc\u30d5\u30a9\u30fc\u30af\u590f\u6642\u9593", "NFST",
"\u30CE\u30FC\u30D5\u30A9\u30FC\u30AF\u6642\u9593", "NFT"}},
{"Pacific/Noumea", new String[] {"\u30cb\u30e5\u30fc\u30ab\u30ec\u30c9\u30cb\u30a2\u6642\u9593", "NCT",
"\u30cb\u30e5\u30fc\u30ab\u30ec\u30c9\u30cb\u30a2\u590f\u6642\u9593", "NCST",
"\u30CB\u30E5\u30FC\u30AB\u30EC\u30C9\u30CB\u30A2\u6642\u9593", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"\u30d1\u30e9\u30aa\u6642\u9593", "PWT",
"\u30d1\u30e9\u30aa\u590f\u6642\u9593", "PWST",
"\u30D1\u30E9\u30AA\u6642\u9593", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"\u30d1\u30d7\u30a2\u30cb\u30e5\u30fc\u30ae\u30cb\u30a2\u6642\u9593", "PGT",
"\u30d1\u30d7\u30a2\u30cb\u30e5\u30fc\u30ae\u30cb\u30a2\u590f\u6642\u9593", "PGST",
"\u30D1\u30D7\u30A2\u30CB\u30E5\u30FC\u30AE\u30CB\u30A2\u6642\u9593", "PGT"}},
{"Pacific/Rarotonga", new String[] {"\u30af\u30c3\u30af\u8af8\u5cf6\u6642\u9593", "CKT",
"\u30af\u30c3\u30af\u8af8\u5cf6\u590f\u6642\u9593", "CKHST",
"\u30AF\u30C3\u30AF\u8AF8\u5CF6\u6642\u9593", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"\u30bf\u30d2\u30c1\u6642\u9593", "TAHT",
"\u30bf\u30d2\u30c1\u590f\u6642\u9593", "TAHST",
"\u30BF\u30D2\u30C1\u6642\u9593", "TAHT"}},
{"Pacific/Tarawa", new String[] {"\u30ae\u30eb\u30d0\u30fc\u30c8\u8af8\u5cf6\u6642\u9593", "GILT",
"\u30ae\u30eb\u30d0\u30fc\u30c8\u8af8\u5cf6\u590f\u6642\u9593", "GILST",
"\u30AE\u30EB\u30D0\u30FC\u30C8\u8AF8\u5CF6\u6642\u9593", "GILT"}},
{"Pacific/Tongatapu", new String[] {"\u30c8\u30f3\u30ac\u6642\u9593", "TOT",
"\u30c8\u30f3\u30ac\u590f\u6642\u9593", "TOST",
"\u30C8\u30F3\u30AC\u6642\u9593", "TOT"}},
{"Pacific/Truk", CHUT},
{"Pacific/Wake", new String[] {"\u30a6\u30a7\u30fc\u30af\u6642\u9593", "WAKT",
"\u30a6\u30a7\u30fc\u30af\u590f\u6642\u9593", "WAKST",
"\u30A6\u30A7\u30FC\u30AF\u6642\u9593", "WAKT"}},
{"Pacific/Wallis", new String[] {"\u30ef\u30ea\u30b9\u53ca\u3073\u30d5\u30c4\u30ca\u6642\u9593", "WFT",
"\u30ef\u30ea\u30b9\u53ca\u3073\u30d5\u30c4\u30ca\u590f\u6642\u9593", "WFST",
"\u30A6\u30A9\u30EA\u30B9\u30FB\u30D5\u30C4\u30CA\u6642\u9593", "WFT"}},
{"Pacific/Yap", CHUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Pacific-New", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| gpl-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.