code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
// $Id$
/*!
* Dynamic display block module template: custom40-a - content template
* Copyright (c) 2008 - 2009 P. Blaauw All rights reserved.
* Version 1.1 (11-FEB-2009)
* Licenced under GPL license
* http://www.gnu.org/licenses/gpl.html
*/
/**
* @file
* Dynamic display block module template: custom40-a - content template
*
* Available variables:
* - $origin: From which module comes the block.
* - $delta: Block number of the block.
*
* - $custom_template: template name
* - $output_type: type of content
*
* - $slider_items: array with slidecontent
* - $slide_text_position of the text in the slider (top | right | bottom | left)
* - $slide_direction: direction of the text in the slider (horizontal | vertical )
* -
* - $pager_content: Themed pager content
* - $pager_position: position of the pager (top | bottom)
*
* notes: don't change the ID names, they are used by the jQuery script.
*/
// add Cascading style sheet
drupal_add_css($directory .'/custom/modules/ddblock/'.$custom_template. '/ddblock-cycle-'.$custom_template. '.css', 'template', 'all', FALSE);
?>
<!-- dynamic display block slideshow -->
<div id="ddblock-<?php print $delta ?>" class="ddblock-cycle-<?php print $custom_template ?> clear-block">
<div class="container clear-block border">
<div class="container-inner clear-block border">
<?php if ($pager_position == "top") : ?>
<!-- custom pager image -->
<?php print $pager_content ?>
<?php endif; ?>
<!-- slider content -->
<div class="slider clear-block border">
<div class="slider-inner clear-block border">
<?php if ($output_type == 'view_fields') : ?>
<?php foreach ($slider_items as $slider_item): ?>
<div class="slide clear-block border">
<div class="slide-inner clear-block border">
<?php print $slider_item['slide_image']; ?>
<div class="slide-text slide-text-<?php print $slide_direction ?> slide-text-<?php print $slide_text_position ?> clear-block border">
<div class="slide-text-inner clear-block border">
<div class="slide-title slide-title-<?php print $slide_direction ?> clear-block border">
<div class="slide-title-inner clear-block border">
<h2><?php print $slider_item['slide_title'] ?></h2>
</div> <!-- slide-title-inner-->
</div> <!-- slide-title-->
<div class="slide-body-<?php print $slide_direction ?> clear-block border">
<div class="slide-body-inner clear-block border">
<p><?php print $slider_item['slide_text'] ?></p>
</div> <!-- slide-body-inner-->
</div> <!-- slide-body-->
<div class="slide-read-more slide-read-more-<?php print $slide_direction ?> clear-block border">
<p><?php print $slider_item['slide_read_more'] ?></p>
</div><!-- slide-read-more-->
</div> <!-- slide-text-inner-->
</div> <!-- slide-text-->
</div> <!-- slide-inner-->
</div> <!-- slide-->
<?php endforeach; ?>
<?php endif; ?>
</div> <!-- slider-inner-->
</div> <!-- slider-->
<?php if ($pager_position == "bottom") : ?>
<!-- custom pager image -->
<?php print $pager_content ?>
<?php endif; ?>
</div> <!-- container-inner-->
</div> <!--container-->
</div> <!-- template -->
| pgrayove/mcpl-site-backup | sites/all/themes/mcpl/custom/modules/ddblock/ddblock-cycle-block-content-custom40-a.tpl.php | PHP | gpl-2.0 | 3,422 |
/*
* #%L
* OME Metadata Editor application for exploration and editing of OME-XML and
* OME-TIFF metadata.
* %%
* Copyright (C) 2006 - 2012 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.ome.editor;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
/**
* A class that handles editing of a cell that is defined in
* the template as having no Type attribute, e.g. it is neither
* of type "Ref" or type "Desc". Creates a JTextField to edit
* this cell instead of something fancy.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Christopher Peterson crpeterson2 at wisc.edu
*/
public class VariableTextFieldEditor extends VariableTextEditor
implements TableCellEditor
{
/** Construct a new VariableTextFieldEditor.*/
public VariableTextFieldEditor(MetadataPane.TablePanel tp) {
super(tp);
}
// -- TableCellEditor API methods --
/**
* The method a table calls to get the editing component for a
* particular cell.
*/
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column)
{
JTextField text = new JTextField(new RowDoc(row), (String) value, 1);
text.getDocument().addDocumentListener(this);
text.addFocusListener(this);
text.addMouseListener(this);
text.addActionListener(this);
return text;
}
}
| mtbc/bioformats | components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java | Java | gpl-2.0 | 2,545 |
<?php
/*
Plugin Name: Huge IT Portfolio Gallery
Plugin URI: http://huge-it.com/portfolio-gallery
Description: Portfolio Gallery is a great plugin for adding specialized portfolios or gallery to your site. There are various view options for the images to choose from.
Version: 1.3.6
Author: http://huge-it.com/
License: GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
add_action('media_buttons_context', 'add_portfolio_my_custom_button');
add_action('admin_footer', 'add_portfolio_inline_popup_content');
function add_portfolio_my_custom_button($context) {
$img = plugins_url( '/images/post.button.png' , __FILE__ );
$container_id = 'huge_it_portfolio';
$title = 'Select Huge IT Portfolio Gallery to insert into post.';
$context .= '<a class="button thickbox" title="Select portfolio gallery to insert into post" href="#TB_inline?width=400&inlineId='.$container_id.'">
<span class="wp-media-buttons-icon" style="background: url('.$img.'); background-repeat: no-repeat; background-position: left bottom;"></span>
Add Portfolio Gallery
</a>';
return $context;
}
function add_portfolio_inline_popup_content() {
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#hugeitportfolioinsert').on('click', function() {
var id = jQuery('#huge_it_portfolio-select option:selected').val();
window.send_to_editor('[huge_it_portfolio id="' + id + '"]');
tb_remove();
})
});
</script>
<div id="huge_it_portfolio" style="display:none;">
<h3>Select Huge IT Portfolio Gallery to insert into post</h3>
<?php
global $wpdb;
$query="SELECT * FROM ".$wpdb->prefix."huge_itportfolio_portfolios order by id ASC";
$shortcodeportfolios=$wpdb->get_results($query);
?>
<?php if (count($shortcodeportfolios)) {
echo "<select id='huge_it_portfolio-select'>";
foreach ($shortcodeportfolios as $shortcodeportfolio) {
echo "<option value='".$shortcodeportfolio->id."'>".$shortcodeportfolio->name."</option>";
}
echo "</select>";
echo "<button class='button primary' id='hugeitportfolioinsert'>Insert portfolio gallery</button>";
} else {
echo "No slideshows found", "huge_it_portfolio";
}
?>
</div>
<?php
}
///////////////////////////////////shortcode update/////////////////////////////////////////////
add_action('init', 'hugesl_portfolio_do_output_buffer');
function hugesl_portfolio_do_output_buffer() {
ob_start();
}
add_action('init', 'portfolio_lang_load');
function portfolio_lang_load()
{
load_plugin_textdomain('sp_portfolio', false, basename(dirname(__FILE__)) . '/Languages');
}
function huge_it_portfolio_images_list_shotrcode($atts)
{
extract(shortcode_atts(array(
'id' => 'no huge_it portfolio',
), $atts));
return huge_it_portfolio_images_list($atts['id']);
}
/////////////// Filter portfolio gallery
function portfolio_after_search_results($query)
{
global $wpdb;
if (isset($_REQUEST['s']) && $_REQUEST['s']) {
$serch_word = htmlspecialchars(($_REQUEST['s']));
$query = str_replace($wpdb->prefix . "posts.post_content", gen_string_portfolio_search($serch_word, $wpdb->prefix . 'posts.post_content') . " " . $wpdb->prefix . "posts.post_content", $query);
}
return $query;
}
add_filter('posts_request', 'portfolio_after_search_results');
function gen_string_portfolio_search($serch_word, $wordpress_query_post)
{
$string_search = '';
global $wpdb;
if ($serch_word) {
$rows_portfolio = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_portfolios WHERE (description LIKE %s) OR (name LIKE %s)", '%' . $serch_word . '%', "%" . $serch_word . "%"));
$count_cat_rows = count($rows_portfolio);
for ($i = 0; $i < $count_cat_rows; $i++) {
$string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="1" %\' OR ' . $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="1"%\' OR ';
}
$rows_portfolio = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_portfolios WHERE (name LIKE %s)","'%" . $serch_word . "%'"));
$count_cat_rows = count($rows_portfolio);
for ($i = 0; $i < $count_cat_rows; $i++) {
$string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="0"%\' OR ' . $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="0"%\' OR ';
}
$rows_single = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_images WHERE name LIKE %s","'%" . $serch_word . "%'"));
$count_sing_rows = count($rows_single);
if ($count_sing_rows) {
for ($i = 0; $i < $count_sing_rows; $i++) {
$string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio_Product id="' . $rows_single[$i]->id . '"]%\' OR ';
}
}
}
return $string_search;
}
///////////////////// end filter
add_shortcode('huge_it_portfolio', 'huge_it_portfolio_images_list_shotrcode');
function huge_it_portfolio_images_list($id)
{
require_once("Front_end/portfolio_front_end_view.php");
require_once("Front_end/portfolio_front_end_func.php");
if (isset($_GET['product_id'])) {
if (isset($_GET['view'])) {
if ($_GET['view'] == 'huge_itportfolio') {
return showPublishedportfolios_1($id);
} else {
return front_end_single_product($_GET['product_id']);
}
} else {
return front_end_single_product($_GET['product_id']);
}
} else {
return showPublishedportfolios_1($id);
}
}
add_filter('admin_head', 'huge_it_portfolio_ShowTinyMCE');
function huge_it_portfolio_ShowTinyMCE()
{
// conditions here
wp_enqueue_script('common');
wp_enqueue_script('jquery-color');
wp_print_scripts('editor');
if (function_exists('add_thickbox')) add_thickbox();
wp_print_scripts('media-upload');
if (version_compare(get_bloginfo('version'), 3.3) < 0) {
if (function_exists('wp_tiny_mce')) wp_tiny_mce();
}
wp_admin_css();
wp_enqueue_script('utils');
do_action("admin_print_styles-post-php");
do_action('admin_print_styles');
}
function portfolio_frontend_scripts_and_styles() {
wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('jquery'),'1.0.0',true );
wp_enqueue_script( 'jquery' );
wp_register_script( 'portfolio-all-js', plugins_url('/js/portfolio-all.js', __FILE__), array('jquery'),'1.0.0',true );
wp_enqueue_script( 'portfolio-all-js' );
wp_register_style( 'portfolio-all-css', plugins_url('/style/portfolio-all.css', __FILE__) );
wp_enqueue_style( 'portfolio-all-css' );
wp_register_script( 'jquery.colorbox-js', plugins_url('/js/jquery.colorbox.js', __FILE__), array('jquery'),'1.0.0',true );
wp_enqueue_script( 'jquery.colorbox-js' );
wp_register_script( 'hugeitmicro-min-js', plugins_url('/js/jquery.hugeitmicro.min.js', __FILE__), array('jquery'),'1.0.0',true );
wp_enqueue_script( 'hugeitmicro-min-js' );
wp_register_style( 'style2-os-css', plugins_url('/style/style2-os.css', __FILE__) );
wp_enqueue_style( 'style2-os-css' );
wp_register_style( 'lightbox-css', plugins_url('/style/lightbox.css', __FILE__) );
wp_enqueue_style( 'lightbox-css' );
}
add_action('wp_enqueue_scripts', 'portfolio_frontend_scripts_and_styles');
add_action('admin_menu', 'huge_it_portfolio_options_panel');
function huge_it_portfolio_options_panel()
{
$page_cat = add_menu_page('Theme page title', 'Huge IT Portfolio', 'manage_options', 'portfolios_huge_it_portfolio', 'portfolios_huge_it_portfolio', plugins_url('images/huge_it_portfolioLogoHover -for_menu.png', __FILE__));
add_submenu_page('portfolios_huge_it_portfolio', 'Portfolios', 'Portfolios', 'manage_options', 'portfolios_huge_it_portfolio', 'portfolios_huge_it_portfolio');
$page_option = add_submenu_page('portfolios_huge_it_portfolio', 'General Options', 'General Options', 'manage_options', 'Options_portfolio_styles', 'Options_portfolio_styles');
$lightbox_options = add_submenu_page('portfolios_huge_it_portfolio', 'Lightbox Options', 'Lightbox Options', 'manage_options', 'Options_portfolio_lightbox_styles', 'Options_portfolio_lightbox_styles');
add_submenu_page( 'portfolios_huge_it_portfolio', 'Licensing', 'Licensing', 'manage_options', 'huge_it_portfolio_Licensing', 'huge_it_portfolio_Licensing');
add_submenu_page('portfolios_huge_it_portfolio', 'Featured Plugins', 'Featured Plugins', 'manage_options', 'huge_it__portfolio_featured_plugins', 'huge_it__portfolio_featured_plugins');
add_action('admin_print_styles-' . $page_cat, 'huge_it_portfolio_admin_script');
add_action('admin_print_styles-' . $page_option, 'huge_it_portfolio_option_admin_script');
add_action('admin_print_styles-' . $lightbox_options, 'huge_it_portfolio_option_admin_script');
}
function huge_it__portfolio_featured_plugins()
{
include_once("admin/huge_it_featured_plugins.php");
}
function huge_it_portfolio_Licensing(){
?>
<div style="width:95%">
<p>
This plugin is the non-commercial version of the Huge IT Portfolio / Gallery. If you want to customize to the styles and colors of your website,than you need to buy a license.
Purchasing a license will add possibility to customize the general options and lightbox of the Huge IT Portfolio / Gallery.
</p>
<br /><br />
<a href="http://huge-it.com/portfolio-gallery/" class="button-primary" target="_blank">Purchase a License</a>
<br /><br /><br />
<p>After the purchasing the commercial version follow this steps:</p>
<ol>
<li>Deactivate Huge IT Portfolio / Gallery Plugin</li>
<li>Delete Huge IT Portfolio / Gallery Plugin</li>
<li>Install the downloaded commercial version of the plugin</li>
</ol>
</div>
<?php
}
function huge_it_portfolio_admin_script()
{
wp_enqueue_media();
wp_enqueue_style("jquery_ui", "http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css", FALSE);
wp_enqueue_style("admin_css", plugins_url("style/admin.style.css", __FILE__), FALSE);
wp_enqueue_script("admin_js", plugins_url("js/admin.js", __FILE__), FALSE);
}
function huge_it_portfolio_option_admin_script()
{
wp_enqueue_script("jquery_old", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js", FALSE);
wp_enqueue_script("simple_slider_js", plugins_url("js/simple-slider.js", __FILE__), FALSE);
wp_enqueue_style("simple_slider_css", plugins_url("style/simple-slider.css", __FILE__), FALSE);
wp_enqueue_style("admin_css", plugins_url("style/admin.style.css", __FILE__), FALSE);
wp_enqueue_script("admin_js", plugins_url("js/admin.js", __FILE__), FALSE);
wp_enqueue_script('param_block2', plugins_url("elements/jscolor/jscolor.js", __FILE__));
}
function portfolios_huge_it_portfolio()
{
require_once("admin/portfolios_func.php");
require_once("admin/portfolios_view.php");
if (!function_exists('print_html_nav'))
require_once("portfolio_function/html_portfolio_func.php");
if (isset($_GET["task"]))
$task = $_GET["task"];
else
$task = '';
if (isset($_GET["id"]))
$id = $_GET["id"];
else
$id = 0;
global $wpdb;
switch ($task) {
case 'add_cat':
add_portfolio();
break;
case 'edit_cat':
if ($id)
editportfolio($id);
else {
$id = $wpdb->get_var("SELECT MAX( id ) FROM " . $wpdb->prefix . "huge_itportfolio_portfolios");
editportfolio($id);
}
break;
case 'save':
if ($id)
apply_cat($id);
case 'apply':
if ($id) {
apply_cat($id);
editportfolio($id);
}
break;
case 'remove_cat':
removeportfolio($id);
showportfolio();
break;
default:
showportfolio();
break;
}
}
function Options_portfolio_styles()
{
require_once("admin/portfolio_Options_func.php");
require_once("admin/portfolio_Options_view.php");
if (isset($_GET['task']))
if ($_GET['task'] == 'save')
save_styles_options();
showStyles();
}
function Options_portfolio_lightbox_styles()
{
require_once("admin/portfolio_lightbox_func.php");
require_once("admin/portfolio_lightbox_view.php");
if (isset($_GET['task']))
if ($_GET['task'] == 'save')
save_styles_options();
showStyles();
}
class Huge_it_portfolio_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'Huge_it_portfolio_Widget',
'Huge IT Portfolio',
array( 'description' => __( 'Huge IT Portfolio', 'huge_it_portfolio' ), )
);
}
public function widget( $args, $instance ) {
extract($args);
if (isset($instance['portfolio_id'])) {
$portfolio_id = $instance['portfolio_id'];
$title = apply_filters( 'widget_title', $instance['title'] );
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
echo do_shortcode("[huge_it_portfolio id={$portfolio_id}]");
echo $after_widget;
}
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['portfolio_id'] = strip_tags( $new_instance['portfolio_id'] );
$instance['title'] = strip_tags( $new_instance['title'] );
return $instance;
}
public function form( $instance ) {
$selected_portfolio = 0;
$title = "";
$portfolios = false;
if (isset($instance['portfolio_id'])) {
$selected_portfolio = $instance['portfolio_id'];
}
if (isset($instance['title'])) {
$title = $instance['title'];
}
?>
<p>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<label for="<?php echo $this->get_field_id('portfolio_id'); ?>"><?php _e('Select portfolio:', 'huge_it_portfolio'); ?></label>
<select id="<?php echo $this->get_field_id('portfolio_id'); ?>" name="<?php echo $this->get_field_name('portfolio_id'); ?>">
<?php
global $wpdb;
$query="SELECT * FROM ".$wpdb->prefix."huge_itportfolio_portfolios ";
$rowwidget=$wpdb->get_results($query);
foreach($rowwidget as $rowwidgetecho){
?>
<option <?php if($rowwidgetecho->id == $instance['portfolio_id']){ echo 'selected'; } ?> value="<?php echo $rowwidgetecho->id; ?>"><?php echo $rowwidgetecho->name; ?></option>
<?php } ?>
</select>
</p>
<?php
}
}
add_action('widgets_init', 'register_Huge_it_portfolio_Widget');
function register_Huge_it_portfolio_Widget() {
register_widget('Huge_it_portfolio_Widget');
}
////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
////////////////////////////////////////////////////// Activate portfolio gallery ///////////////////////////////////////////////////////
////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
function huge_it_portfolio_activate()
{
global $wpdb;
/// creat database tables
$sql_huge_itportfolio_images = "
CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "huge_itportfolio_images` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`portfolio_id` varchar(200) DEFAULT NULL,
`description` text,
`image_url` text,
`sl_url` varchar(128) DEFAULT NULL,
`sl_type` text NOT NULL,
`link_target` text NOT NULL,
`ordering` int(11) NOT NULL,
`published` tinyint(4) unsigned DEFAULT NULL,
`published_in_sl_width` tinyint(4) unsigned DEFAULT NULL,
`category` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5";
$sql_huge_itportfolio_portfolios = "
CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "huge_itportfolio_portfolios` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`sl_height` int(11) unsigned DEFAULT NULL,
`sl_width` int(11) unsigned DEFAULT NULL,
`pause_on_hover` text,
`portfolio_list_effects_s` text,
`description` text,
`param` text,
`sl_position` text NOT NULL,
`ordering` int(11) NOT NULL,
`published` text,
`categories` text NOT NULL,
`ht_show_sorting` text NOT NULL,
`ht_show_filtering` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ";
$table_name = $wpdb->prefix . "huge_itportfolio_images";
$sql_2 = "
INSERT INTO
`" . $table_name . "` (`id`, `name`, `portfolio_id`, `description`, `image_url`, `sl_url`, `sl_type`, `link_target`, `ordering`, `published`, `published_in_sl_width`) VALUES
(1, 'Cutthroat & Cavalier', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/1.jpg", __FILE__).";".plugins_url("Front_images/projects/1.1.jpg", __FILE__).";".plugins_url("Front_images/projects/1.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 0, 1, NULL),
(2, 'Cone Music', '1', '<ul><li>lorem ipsumdolor sit amet</li><li>lorem ipsum dolor sit amet</li></ul><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/5.jpg", __FILE__).";".plugins_url("Front_images/projects/5.1.jpg", __FILE__).";".plugins_url("Front_images/projects/5.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 1, 1, NULL),
(3, 'Nexus', '1', '<h6>Lorem Ipsum </h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><ul><li>lorem ipsum</li><li>dolor sit amet</li><li>lorem ipsum</li><li>dolor sit amet</li></ul>', '".plugins_url("Front_images/projects/3.jpg", __FILE__).";".plugins_url("Front_images/projects/3.1.jpg", __FILE__).";".plugins_url("Front_images/projects/3.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 2, 1, NULL),
(4, 'De7igner', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><h7>Dolor sit amet</h7><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/4.jpg", __FILE__).";".plugins_url("Front_images/projects/4.1.jpg", __FILE__).";".plugins_url("Front_images/projects/4.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 3, 1, NULL),
(5, 'Autumn / Winter Collection', '1', '<h6>Lorem Ipsum</h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 4, 1, NULL),
(6, 'Retro Headphones', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/6.jpg", __FILE__).";".plugins_url("Front_images/projects/6.1.jpg", __FILE__).";".plugins_url("Front_images/projects/6.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 5, 1, NULL),
(7, 'Take Fight', '1', '<h6>Lorem Ipsum</h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/7.jpg", __FILE__).";".plugins_url("Front_images/projects/7.2.jpg", __FILE__).";".plugins_url("Front_images/projects/7.3.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 6, 1, NULL),
(8, 'The Optic', '1', '<h6>Lorem Ipsum </h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><ul><li>lorem ipsum</li><li>dolor sit amet</li><li>lorem ipsum</li><li>dolor sit amet</li></ul>', '".plugins_url("Front_images/projects/8.jpg", __FILE__).";".plugins_url("Front_images/projects/8.1.jpg", __FILE__).";".plugins_url("Front_images/projects/8.3.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 7, 1, NULL)";
$table_name = $wpdb->prefix . "huge_itportfolio_portfolios";
$sql_3 = "
INSERT INTO `$table_name` (`id`, `name`, `sl_height`, `sl_width`, `pause_on_hover`, `portfolio_list_effects_s`, `description`, `param`, `sl_position`, `ordering`, `published`) VALUES
(1, 'My First Portfolio', 375, 600, 'on', '2', '4000', '1000', 'center', 1, '300')";
$wpdb->query($sql_huge_itportfolio_params);
$wpdb->query($sql_huge_itportfolio_images);
$wpdb->query($sql_huge_itportfolio_portfolios);
if (!$wpdb->get_var("select count(*) from " . $wpdb->prefix . "huge_itportfolio_images")) {
$wpdb->query($sql_2);
}
if (!$wpdb->get_var("select count(*) from " . $wpdb->prefix . "huge_itportfolio_portfolios")) {
$wpdb->query($sql_3);
}
///////////////////////////update////////////////////////////////////
$imagesAllFieldsInArray = $wpdb->get_results("DESCRIBE " . $wpdb->prefix . "huge_itportfolio_images", ARRAY_A);
$forUpdate = 0;
foreach ($imagesAllFieldsInArray as $portfoliosField) {
if ($portfoliosField['Field'] == 'category') {
// "ka category field.<br>";
$forUpdate = 1;
$catValues = $wpdb->get_results( "SELECT category FROM ".$wpdb->prefix."huge_itportfolio_images" );
$needToUpdate=0;
foreach($catValues as $catValue){
if($catValue->category !== '') {
$needToUpdate=1;
//echo "category field - y datark chi.<br>";
}
}
if($needToUpdate == 0){
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Third Category,' WHERE id='1'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='2'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='3'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Second Category,' WHERE id='4'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,My Third Category,' WHERE id='5'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='6'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='7'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,' WHERE id='8'");
}
break;
}
}
if ($forUpdate == '0') {
$wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_images ADD category text");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Third Category,' WHERE id='1'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='2'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='3'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Second Category,' WHERE id='4'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,My Third Category,' WHERE id='5'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='6'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='7'");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,' WHERE id='8'");
}
$productPortfolio = $wpdb->get_results("DESCRIBE " . $wpdb->prefix . "huge_itportfolio_portfolios", ARRAY_A);
$isUpdate = 0;
foreach ($productPortfolio as $prodPortfolio) {
if ($prodPortfolio['Field'] == 'categories' && $prodPortfolio['Type'] == 'text') {
$isUpdate = 1;
$allCats = $wpdb->get_results( "SELECT categories FROM ".$wpdb->prefix."huge_itportfolio_portfolios" );
$needToUpdateAllCats=0;
foreach($allCats as $AllCatsVal){
if($AllCatsVal->categories !== '') {
$needToUpdateAllCats=1;
}
}
if($needToUpdateAllCats == 0){
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET categories = 'My First Category,My Second Category,My Third Category,' ");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_sorting = 'off' ");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_filtering = 'off' ");
}
break;
}
}
if ($isUpdate == '0') {
$wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD categories text");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET categories = 'My First Category,My Second Category,My Third Category,'");
$wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD ht_show_sorting text");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_sorting = 'off'");
$wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD ht_show_filtering text");
$wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_filtering = 'off'");
}
}
register_activation_hook(__FILE__, 'huge_it_portfolio_activate'); | YeongeunHeo/wordpress | wp-content/plugins/portfolio-gallery/portfolio-gallery.php | PHP | gpl-2.0 | 29,406 |
/*
* This file is part of the OpenJML project.
* Author: David R. Cok
*/
package org.jmlspecs.openjml.proverinterface;
import org.jmlspecs.openjml.proverinterface.IProverResult.ICounterexample;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCExpression;
/**
* A prover can be used to check if a formula is satisfiable,
* given a set of assumptions. The prover may need to be restarted
* before being reused.
* <P>
* The assume calls take a JCExpression encoding the logical expression
* that the prover is to assume. This is a OpenJDK AST but of restricted
* form. In particular, only the following AST nodes are allowed (there is
* no runtime check of this restriction):
* <UL>
* <LI>JCBinary - with any Java operator
* <LI>JmlBinary - with any JML operator
* <LI>JCUnary - with any Java operator
* <LI>JCIdent - the identifier for a logical variable, with the
* type field giving the Java type of the variable
* <LI>JCConditional - an if-then-else (i.e. ?:) construct
* <LI>JmlBBFieldAccess - encodes field access (replaces JCFieldAccess)
* <LI>JmlBBArrayAccess - array access, replacing JCArrayAccess
* <LI>JCParens - not needed but helps to keep pretty printed expressions less confusing
* <LI>JCLiteral - for boolean, integer, null literals
* <LI>JCMethodInvocation - FIXME - needs explanation
* </UL>
*
*
*
* TODO add properties, like timelimit
*
* @author David Cok, based on previous work by rgrig
*/
public interface IProver {
/** Returns an identifying name for the prover */
public String name();
/**
* Adds {@code tree} as an assumption; the concrete IProver is
* responsible to translate the AST into prover-dependent form.
* @param tree the assumption
* @return an integer id for the assumption (or 0 if ids are not supported)
* @throws ProverException if something goes wrong
*/
public int assume(/*@ non_null*/JCExpression tree) throws ProverException;
/**
* Adds {@code tree} as an assumption; the concrete IProver is
* responsible to translate the AST into prover-dependent form.
* @param tree the assumption
* @param weight a weight to be associated with the assertion (may be
* ignored if the prover does not support weights)
* @return an integer id for the assumption (or 0 if ids are not supported)
* @throws ProverException if something goes wrong
*/
public int assume(/*@ non_null*/JCExpression tree, int weight) throws ProverException;
/** Tells the prover to define a given variable as the stated type
* (not all provers need this)
* @param id the name of the variable
* @param type the type of the variable
* @throws ProverException if something goes wrong
*/
public void define(/*@ non_null*/String id, /*@ non_null*/Type type) throws ProverException;
/** Tells the prover to define a given variable as the stated type and with the given value
* (not all provers need this)
* @param id the name of the variable
* @param type the type of the variable
* @param value the value the variable is an abbreviation for
* @throws ProverException if something goes wrong
*/
public void define(/*@ non_null*/String id, /*@ non_null*/Type type, /*@ non_null*/ JCExpression value) throws ProverException;
/**
* Retract the last assumption.
* @throws ProverException if something goes wrong
*/
public void retract() throws ProverException;
/**
* Retracts a specific assumption.
* @param i the assertion to retract
* @throws ProverException if something goes wrong
*/
public void retract(int i) throws ProverException;
/**
* Make a new frame of assumptions.
* @throws ProverException if something goes wrong
*/
public void push() throws ProverException;
/**
* Removes the last frame of assumptions.
* @throws ProverException if something goes wrong
*/
public void pop() throws ProverException;
/** Checks whether the set of assertions known to the prover so far
* is satisfiable or not
* @return an object containing the details of the prover answer
* @throws ProverException if something goes wrong
*/
// /*@ non_null*/
// public IProverResult check() throws ProverException;
/*@ non_null*/
public IProverResult check(boolean details) throws ProverException;
/**
* Kills and restarts the prover process. Then it resends
* all the assumptions that are on the stack.
* @throws ProverException if something goes wrong
*/
public void restartProver() throws ProverException;
/** Kills the prover
* @throws ProverException if something goes wrong
*/
public void kill() throws ProverException;
public void reassertCounterexample(ICounterexample ce);
public Supports supports();
static public class Supports {
public Supports() {
retract = false;
unsatcore = false;
}
public boolean retract;
public boolean unsatcore;
}
}
| shunghsiyu/OpenJML_XOR | OpenJML/src/org/jmlspecs/openjml/proverinterface/IProver.java | Java | gpl-2.0 | 5,173 |
package com.sales.service;
import java.util.List;
import com.sales.model.TCurrency;
public interface K3EntryService {
public List getPayCondition();
public List getCurrency();
public TCurrency getCurrencyById(Integer fCurrencyID);
public List getEmp(String fName);
public List getDepartList();
public List getStaff();
public List getUser();
public List getEmpList();
/**
* @return 销售报价单开票方式
*/
public List getInvoiceTypeList();
/**
* @return 销售报价单运输方式
*/
public List getTransTypeList();
}
| goulin2k/salesManager | salesManagerServer/src/com/sales/service/K3EntryService.java | Java | gpl-2.0 | 604 |
/*
* org.openmicroscopy.shoola.agents.fsimporter.AnnotationDataLoader
*
*------------------------------------------------------------------------------
* Copyright (C) 2013 University of Dundee & Open Microscopy Environment.
* All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.agents.fsimporter;
//Java imports
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.openmicroscopy.shoola.agents.fsimporter.view.Importer;
import org.openmicroscopy.shoola.agents.treeviewer.DataBrowserLoader;
import omero.gateway.SecurityContext;
import org.openmicroscopy.shoola.env.data.views.CallHandle;
import pojos.FileAnnotationData;
import pojos.FilesetData;
/**
* Loads the annotations of a given type linked to the specified image.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @since 4.4
*/
public class AnnotationDataLoader
extends DataImporterLoader
{
/** Handle to the asynchronous call so that we can cancel it.*/
private CallHandle handle;
/** The index of the UI element.*/
private int index;
/** The identifier of the image.*/
private long fileSetID;
/**
* Creates a new instance.
*
* @param viewer The Importer this data loader is for.
* Mustn't be <code>null</code>.
* @param ctx The security context.
* @param imageID The identifier of the image.
* @param index The index of the UI element.
*/
public AnnotationDataLoader(Importer viewer, SecurityContext ctx,
long fileSetID, int index)
{
super(viewer, ctx);
this.fileSetID = fileSetID;
this.index = index;
}
/**
* Loads the annotations.
* @see DataImporterLoader#load()
*/
public void load()
{
List<String> nsInclude = new ArrayList<String>();
nsInclude.add(FileAnnotationData.LOG_FILE_NS);
handle = mhView.loadAnnotations(ctx, FilesetData.class,
Arrays.asList(fileSetID), FileAnnotationData.class, nsInclude,
null, this);
}
/**
* Cancels the data loading.
* @see DataImporterLoader#load()
*/
public void cancel() { handle.cancel(); }
/**
* Feeds the result back to the viewer.
* @see DataBrowserLoader#handleResult(Object)
*/
public void handleResult(Object result)
{
if (viewer.getState() == Importer.DISCARDED) return;
Map<Long, Collection<FileAnnotationData>> map =
(Map<Long, Collection<FileAnnotationData>>) result;
viewer.setImportLogFile(map.get(fileSetID), fileSetID, index);
}
}
| stelfrich/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/AnnotationDataLoader.java | Java | gpl-2.0 | 3,360 |
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutRight,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutLeft,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutStride,
Experimental::ROCm, int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int64_t********, LayoutRight, Experimental::ROCm,
int)
} // namespace Impl
} // namespace Kokkos
| pastewka/lammps | lib/kokkos/core/src/eti/ROCm/Kokkos_ROCm_ViewCopyETIInst_int_int64_t_LayoutRight_Rank8.cpp | C++ | gpl-2.0 | 2,682 |
#include <yafray_config.h>
#include <core_api/ray.h>
#include <core_api/color.h>
#include <core_api/volume.h>
#include <core_api/bound.h>
#include <core_api/surface.h>
#include <core_api/texture.h>
#include <core_api/environment.h>
#include <utilities/mcqmc.h>
#include <fstream>
#include <cstdlib>
__BEGIN_YAFRAY
struct renderState_t;
struct pSample_t;
class GridVolume : public DensityVolume {
public:
GridVolume(color_t sa, color_t ss, color_t le, float gg, point3d_t pmin, point3d_t pmax)
{
bBox = bound_t(pmin, pmax);
s_a = sa;
s_s = ss;
l_e = le;
g = gg;
haveS_a = (s_a.energy() > 1e-4f);
haveS_s = (s_s.energy() > 1e-4f);
haveL_e = (l_e.energy() > 1e-4f);
std::ifstream inputStream;
inputStream.open("/home/public/3dkram/cloud2_3.df3");
if(!inputStream) Y_ERROR << "GridVolume: Error opening input stream" << yendl;
inputStream.seekg(0, std::ios_base::beg);
std::ifstream::pos_type begin_pos = inputStream.tellg();
inputStream.seekg(0, std::ios_base::end);
int fileSize = static_cast<int>(inputStream.tellg() - begin_pos);
fileSize -= 6;
inputStream.seekg(0, std::ios_base::beg);
int dim[3];
for (int i = 0; i < 3; ++i) {
short i0 = 0, i1 = 0;
inputStream.read( (char*)&i0, 1 );
inputStream.read( (char*)&i1, 1 );
Y_VERBOSE << "GridVolume: " << i0 << " " << i1 << yendl;
dim[i] = (((unsigned short)i0 << 8) | (unsigned short)i1);
}
int sizePerVoxel = fileSize / (dim[0] * dim[1] * dim[2]);
Y_VERBOSE << "GridVolume: " << dim[0] << " " << dim[1] << " " << dim[2] << " " << fileSize << " " << sizePerVoxel << yendl;
sizeX = dim[0];
sizeY = dim[1];
sizeZ = dim[2];
/*
sizeX = 60;
sizeY = 60;
sizeZ = 60;
*/
grid = (float***)malloc(sizeX * sizeof(float));
for (int x = 0; x < sizeX; ++x) {
grid[x] = (float**)malloc(sizeY * sizeof(float));
for (int y = 0; y < sizeY; ++y) {
grid[x][y] = (float*)malloc(sizeZ * sizeof(float));
}
}
for (int z = 0; z < sizeZ; ++z) {
for (int y = 0; y < sizeY; ++y) {
for (int x = 0; x < sizeX; ++x) {
int voxel = 0;
inputStream.read( (char*)&voxel, 1 );
grid[x][y][z] = voxel / 255.f;
/*
float r = sizeX / 2.f;
float r2 = r*r;
float dist = sqrt((x-r)*(x-r) + (y-r)*(y-r) + (z-r)*(z-r));
grid[x][y][z] = (dist < r) ? 1.f-dist/r : 0.0f;
*/
}
}
}
Y_VERBOSE << "GridVolume: Vol.[" << s_a << ", " << s_s << ", " << l_e << "]" << yendl;
}
~GridVolume() {
Y_VERBOSE << "GridVolume: Freeing grid data" << yendl;
for (int x = 0; x < sizeX; ++x) {
for (int y = 0; y < sizeY; ++y) {
free(grid[x][y]);
}
free(grid[x]);
}
free(grid);
}
virtual float Density(point3d_t p);
static VolumeRegion* factory(paraMap_t ¶ms, renderEnvironment_t &render);
protected:
float*** grid;
int sizeX, sizeY, sizeZ;
};
inline float min(float a, float b) { return (a > b) ? b : a; }
inline float max(float a, float b) { return (a < b) ? b : a; }
float GridVolume::Density(const point3d_t p) {
float x = (p.x - bBox.a.x) / bBox.longX() * sizeX - .5f;
float y = (p.y - bBox.a.y) / bBox.longY() * sizeY - .5f;
float z = (p.z - bBox.a.z) / bBox.longZ() * sizeZ - .5f;
int x0 = max(0, floor(x));
int y0 = max(0, floor(y));
int z0 = max(0, floor(z));
int x1 = min(sizeX - 1, ceil(x));
int y1 = min(sizeY - 1, ceil(y));
int z1 = min(sizeZ - 1, ceil(z));
float xd = x - x0;
float yd = y - y0;
float zd = z - z0;
float i1 = grid[x0][y0][z0] * (1-zd) + grid[x0][y0][z1] * zd;
float i2 = grid[x0][y1][z0] * (1-zd) + grid[x0][y1][z1] * zd;
float j1 = grid[x1][y0][z0] * (1-zd) + grid[x1][y0][z1] * zd;
float j2 = grid[x1][y1][z0] * (1-zd) + grid[x1][y1][z1] * zd;
float w1 = i1 * (1 - yd) + i2 * yd;
float w2 = j1 * (1 - yd) + j2 * yd;
float dens = w1 * (1 - xd) + w2 * xd;
return dens;
}
VolumeRegion* GridVolume::factory(paraMap_t ¶ms,renderEnvironment_t &render) {
float ss = .1f;
float sa = .1f;
float le = .0f;
float g = .0f;
float min[] = {0, 0, 0};
float max[] = {0, 0, 0};
params.getParam("sigma_s", ss);
params.getParam("sigma_a", sa);
params.getParam("l_e", le);
params.getParam("g", g);
params.getParam("minX", min[0]);
params.getParam("minY", min[1]);
params.getParam("minZ", min[2]);
params.getParam("maxX", max[0]);
params.getParam("maxY", max[1]);
params.getParam("maxZ", max[2]);
GridVolume *vol = new GridVolume(color_t(sa), color_t(ss), color_t(le), g,
point3d_t(min[0], min[1], min[2]), point3d_t(max[0], max[1], max[2]));
return vol;
}
extern "C"
{
YAFRAYPLUGIN_EXPORT void registerPlugin(renderEnvironment_t &render)
{
render.registerFactory("GridVolume", GridVolume::factory);
}
}
__END_YAFRAY
| DavidBluecame/Core | src/volumes/GridVolume.cc | C++ | gpl-2.0 | 4,802 |
/*
* $RCSfile: JspFactory.java,v $
* $Revision: 1.1 $
* $Date: 2013-02-19 $
*
* Copyright (C) 2008 Skin, Inc. All rights reserved.
*
* This software is the proprietary information of Skin, Inc.
* Use is subject to license terms.
*/
package com.skin.ayada.runtime;
import java.io.Writer;
import java.util.Map;
import com.skin.ayada.ExpressionContext;
import com.skin.ayada.JspWriter;
import com.skin.ayada.PageContext;
/**
* <p>Title: JspFactory</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* @author xuesong.net
* @version 1.0
*/
public class JspFactory {
/**
* @param writer
* @return PageContext
*/
public static PageContext getPageContext(Writer writer) {
return getPageContext((Map<String, Object>)null, writer, 8192, false);
}
/**
* @param context
* @param writer
* @return PageContext
*/
public static PageContext getPageContext(Map<String, Object> context, Writer writer) {
return getPageContext(context, writer, 8192, false);
}
/**
* @param context
* @param writer
* @param buffserSize
* @param autoFlush
* @return PageContext
*/
public static PageContext getPageContext(Map<String, Object> context, Writer writer, int buffserSize, boolean autoFlush) {
JspWriter out = null;
if(writer instanceof JspWriter) {
out = (JspWriter)writer;
}
else {
out = new JspWriter(writer, buffserSize, autoFlush);
}
DefaultPageContext pageContext = new DefaultPageContext(out);
ExpressionContext expressionContext = DefaultExpressionFactory.getDefaultExpressionContext(pageContext);
pageContext.setTemplateContext(null);
pageContext.setExpressionContext(expressionContext);
pageContext.setContext(context);
return pageContext;
}
}
| xuesong123/jsp-jstl-engine | src/main/java/com/skin/ayada/runtime/JspFactory.java | Java | gpl-2.0 | 1,893 |
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates.
Copyright (c) 2012, 2020, MariaDB Corporation.
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */
/**
@file
This file is the net layer API for the MySQL client/server protocol.
Write and read of logical packets to/from socket.
Writes are cached into net_buffer_length big packets.
Read packets are reallocated dynamicly when reading big packets.
Each logical packet has the following pre-info:
3 byte length & 1 byte package-number.
This file needs to be written in C as it's used by the libmysql client as a
C file.
*/
/*
HFTODO this must be hidden if we don't want client capabilities in
embedded library
*/
#include "mariadb.h"
#include <mysql.h>
#include <mysql_com.h>
#include <mysqld_error.h>
#include <my_sys.h>
#include <m_string.h>
#include <my_net.h>
#include <violite.h>
#include <signal.h>
#include "probes_mysql.h"
#include <debug_sync.h>
#include "proxy_protocol.h"
PSI_memory_key key_memory_NET_buff;
PSI_memory_key key_memory_NET_compress_packet;
#ifdef EMBEDDED_LIBRARY
#undef MYSQL_SERVER
#undef MYSQL_CLIENT
#define MYSQL_CLIENT
#endif /*EMBEDDED_LIBRARY */
/*
to reduce the number of ifdef's in the code
*/
#ifdef EXTRA_DEBUG
#define EXTRA_DEBUG_fprintf fprintf
#define EXTRA_DEBUG_fflush fflush
#define EXTRA_DEBUG_ASSERT DBUG_ASSERT
#else
static void inline EXTRA_DEBUG_fprintf(...) {}
#ifndef MYSQL_SERVER
static int inline EXTRA_DEBUG_fflush(...) { return 0; }
#endif
#endif /* EXTRA_DEBUG */
#ifdef MYSQL_SERVER
#include <sql_class.h>
#include <sql_connect.h>
#define MYSQL_SERVER_my_error my_error
#else
static void inline MYSQL_SERVER_my_error(...) {}
#endif
#ifndef EXTRA_DEBUG_ASSERT
# define EXTRA_DEBUG_ASSERT(X) do {} while(0)
#endif
/*
The following handles the differences when this is linked between the
client and the server.
This gives an error if a too big packet is found.
The server can change this, but because the client can't normally do this
the client should have a bigger max_allowed_packet.
*/
#if defined(_WIN32) || !defined(MYSQL_SERVER)
/* The following is because alarms doesn't work on windows. */
#ifndef NO_ALARM
#define NO_ALARM
#endif
#endif
#ifndef NO_ALARM
#include "my_pthread.h"
void sql_print_error(const char *format,...);
#else
#define DONT_USE_THR_ALARM
#endif /* NO_ALARM */
#include "thr_alarm.h"
#ifdef MYSQL_SERVER
/*
The following variables/functions should really not be declared
extern, but as it's hard to include sql_priv.h here, we have to
live with this for a while.
*/
extern ulonglong test_flags;
extern ulong bytes_sent, bytes_received, net_big_packet_count;
#ifdef HAVE_QUERY_CACHE
#define USE_QUERY_CACHE
extern void query_cache_insert(void *thd, const char *packet, size_t length,
unsigned pkt_nr);
#endif // HAVE_QUERY_CACHE
#define update_statistics(A) A
extern my_bool thd_net_is_killed(THD *thd);
/* Additional instrumentation hooks for the server */
#include "mysql_com_server.h"
#else
#define update_statistics(A)
#define thd_net_is_killed(A) 0
#endif
static my_bool net_write_buff(NET *, const uchar *, size_t len);
my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags);
/** Init with packet info. */
my_bool my_net_init(NET *net, Vio *vio, void *thd, uint my_flags)
{
DBUG_ENTER("my_net_init");
DBUG_PRINT("enter", ("my_flags: %u", my_flags));
net->vio = vio;
net->read_timeout= 0;
net->write_timeout= 0;
my_net_local_init(net); /* Set some limits */
if (net_allocate_new_packet(net, thd, my_flags))
DBUG_RETURN(1);
net->error=0; net->return_status=0;
net->pkt_nr=net->compress_pkt_nr=0;
net->last_error[0]=0;
net->compress=0; net->reading_or_writing=0;
net->where_b = net->remain_in_buf=0;
net->net_skip_rest_factor= 0;
net->last_errno=0;
net->thread_specific_malloc= MY_TEST(my_flags & MY_THREAD_SPECIFIC);
net->thd= 0;
#ifdef MYSQL_SERVER
net->extension= NULL;
net->thd= thd;
#endif
if (vio)
{
/* For perl DBI/DBD. */
net->fd= vio_fd(vio);
#if defined(MYSQL_SERVER) && !defined(_WIN32)
if (!(test_flags & TEST_BLOCKING))
{
my_bool old_mode;
vio_blocking(vio, FALSE, &old_mode);
}
#endif
vio_fastsend(vio);
}
DBUG_RETURN(0);
}
/**
Allocate and assign new net buffer
@note In case of error the old buffer left
@retval TRUE error
@retval FALSE success
*/
my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags)
{
uchar *tmp;
DBUG_ENTER("net_allocate_new_packet");
if (!(tmp= (uchar*) my_malloc(key_memory_NET_buff,
(size_t) net->max_packet +
NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | my_flags))))
DBUG_RETURN(1);
net->buff= tmp;
net->buff_end=net->buff+net->max_packet;
net->write_pos=net->read_pos = net->buff;
DBUG_RETURN(0);
}
void net_end(NET *net)
{
DBUG_ENTER("net_end");
my_free(net->buff);
net->buff=0;
DBUG_VOID_RETURN;
}
/** Realloc the packet buffer. */
my_bool net_realloc(NET *net, size_t length)
{
uchar *buff;
size_t pkt_length;
DBUG_ENTER("net_realloc");
DBUG_PRINT("enter",("length: %lu", (ulong) length));
if (length >= net->max_packet_size)
{
DBUG_PRINT("error", ("Packet too large. Max size: %lu",
net->max_packet_size));
/* @todo: 1 and 2 codes are identical. */
net->error= 1;
net->last_errno= ER_NET_PACKET_TOO_LARGE;
MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
DBUG_RETURN(1);
}
pkt_length = (length+IO_SIZE-1) & ~(IO_SIZE-1);
/*
We must allocate some extra bytes for the end 0 and to be able to
read big compressed blocks + 1 safety byte since uint3korr() in
my_real_read() may actually read 4 bytes depending on build flags and
platform.
*/
if (!(buff= (uchar*) my_realloc(key_memory_NET_buff,
(char*) net->buff, pkt_length +
NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | (net->thread_specific_malloc
? MY_THREAD_SPECIFIC : 0)))))
{
/* @todo: 1 and 2 codes are identical. */
net->error= 1;
net->last_errno= ER_OUT_OF_RESOURCES;
/* In the server the error is reported by MY_WME flag. */
DBUG_RETURN(1);
}
net->buff=net->write_pos=buff;
net->buff_end=buff+(net->max_packet= (ulong) pkt_length);
DBUG_RETURN(0);
}
/**
Check if there is any data to be read from the socket.
@param sd socket descriptor
@retval
0 No data to read
@retval
1 Data or EOF to read
@retval
-1 Don't know if data is ready or not
*/
#if !defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF)
static int net_data_is_ready(my_socket sd)
{
#ifdef HAVE_POLL
struct pollfd ufds;
int res;
ufds.fd= sd;
ufds.events= POLLIN | POLLPRI;
if (!(res= poll(&ufds, 1, 0)))
return 0;
if (res < 0 || !(ufds.revents & (POLLIN | POLLPRI)))
return 0;
return 1;
#else
fd_set sfds;
struct timeval tv;
int res;
#ifndef _WIN32
/* Windows uses an _array_ of 64 fd's as default, so it's safe */
if (sd >= FD_SETSIZE)
return -1;
#define NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE
#endif
FD_ZERO(&sfds);
FD_SET(sd, &sfds);
tv.tv_sec= tv.tv_usec= 0;
if ((res= select((int) (sd + 1), &sfds, NULL, NULL, &tv)) < 0)
return 0;
else
return MY_TEST(res ? FD_ISSET(sd, &sfds) : 0);
#endif /* HAVE_POLL */
}
#endif /* EMBEDDED_LIBRARY */
/**
Clear (reinitialize) the NET structure for a new command.
@remark Performs debug checking of the socket buffer to
ensure that the protocol sequence is correct.
- Read from socket until there is nothing more to read. Discard
what is read.
- Initialize net for new net_read/net_write calls.
If there is anything when to read 'net_clear' is called this
normally indicates an error in the protocol. Normally one should not
need to do clear the communication buffer. If one compiles without
-DUSE_NET_CLEAR then one wins one read call / query.
When connection is properly closed (for TCP it means with
a FIN packet), then select() considers a socket "ready to read",
in the sense that there's EOF to read, but read() returns 0.
@param net NET handler
@param clear_buffer if <> 0, then clear all data from comm buff
*/
void net_clear(NET *net, my_bool clear_buffer __attribute__((unused)))
{
DBUG_ENTER("net_clear");
/*
We don't do a clear in case of not DBUG_OFF to catch bugs in the
protocol handling.
*/
#if (!defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF)) || defined(USE_NET_CLEAR)
if (clear_buffer)
{
size_t count;
int ready;
while ((ready= net_data_is_ready(vio_fd(net->vio))) > 0)
{
/* The socket is ready */
if ((long) (count= vio_read(net->vio, net->buff,
(size_t) net->max_packet)) > 0)
{
DBUG_PRINT("info",("skipped %ld bytes from file: %s",
(long) count, vio_description(net->vio)));
EXTRA_DEBUG_fprintf(stderr,"Note: net_clear() skipped %ld bytes from file: %s\n",
(long) count, vio_description(net->vio));
}
else
{
DBUG_PRINT("info",("socket ready but only EOF to read - disconnected"));
net->error= 2;
break;
}
}
#ifdef NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE
/* 'net_data_is_ready' returned "don't know" */
if (ready == -1)
{
/* Read unblocking to clear net */
my_bool old_mode;
if (!vio_blocking(net->vio, FALSE, &old_mode))
{
while ((long) (count= vio_read(net->vio, net->buff,
(size_t) net->max_packet)) > 0)
DBUG_PRINT("info",("skipped %ld bytes from file: %s",
(long) count, vio_description(net->vio)));
vio_blocking(net->vio, TRUE, &old_mode);
}
}
#endif /* NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE */
}
#endif /* EMBEDDED_LIBRARY */
net->pkt_nr=net->compress_pkt_nr=0; /* Ready for new command */
net->write_pos=net->buff;
DBUG_VOID_RETURN;
}
/** Flush write_buffer if not empty. */
my_bool net_flush(NET *net)
{
my_bool error= 0;
DBUG_ENTER("net_flush");
if (net->buff != net->write_pos)
{
error= MY_TEST(net_real_write(net, net->buff,
(size_t) (net->write_pos - net->buff)));
net->write_pos= net->buff;
}
/* Sync packet number if using compression */
if (net->compress)
net->pkt_nr=net->compress_pkt_nr;
DBUG_RETURN(error);
}
/*****************************************************************************
** Write something to server/client buffer
*****************************************************************************/
/**
Write a logical packet with packet header.
Format: Packet length (3 bytes), packet number (1 byte)
When compression is used, a 3 byte compression length is added.
@note If compression is used, the original packet is modified!
*/
my_bool my_net_write(NET *net, const uchar *packet, size_t len)
{
uchar buff[NET_HEADER_SIZE];
if (unlikely(!net->vio)) /* nowhere to write */
return 0;
MYSQL_NET_WRITE_START(len);
/*
Big packets are handled by splitting them in packets of MAX_PACKET_LENGTH
length. The last packet is always a packet that is < MAX_PACKET_LENGTH.
(The last packet may even have a length of 0)
*/
while (len >= MAX_PACKET_LENGTH)
{
const ulong z_size = MAX_PACKET_LENGTH;
int3store(buff, z_size);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE) ||
net_write_buff(net, packet, z_size))
{
MYSQL_NET_WRITE_DONE(1);
return 1;
}
packet += z_size;
len-= z_size;
}
/* Write last packet */
int3store(buff,len);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE))
{
MYSQL_NET_WRITE_DONE(1);
return 1;
}
#ifndef DEBUG_DATA_PACKETS
DBUG_DUMP("packet_header", buff, NET_HEADER_SIZE);
#endif
my_bool rc= MY_TEST(net_write_buff(net, packet, len));
MYSQL_NET_WRITE_DONE(rc);
return rc;
}
/**
Send a command to the server.
The reason for having both header and packet is so that libmysql
can easy add a header to a special command (like prepared statements)
without having to re-alloc the string.
As the command is part of the first data packet, we have to do some data
juggling to put the command in there, without having to create a new
packet.
This function will split big packets into sub-packets if needed.
(Each sub packet can only be 2^24 bytes)
@param net NET handler
@param command Command in MySQL server (enum enum_server_command)
@param header Header to write after command
@param head_len Length of header
@param packet Query or parameter to query
@param len Length of packet
@retval
0 ok
@retval
1 error
*/
my_bool
net_write_command(NET *net,uchar command,
const uchar *header, size_t head_len,
const uchar *packet, size_t len)
{
size_t length=len+1+head_len; /* 1 extra byte for command */
uchar buff[NET_HEADER_SIZE+1];
uint header_size=NET_HEADER_SIZE+1;
my_bool rc;
DBUG_ENTER("net_write_command");
DBUG_PRINT("enter",("length: %lu", (ulong) len));
DBUG_EXECUTE_IF("simulate_error_on_packet_write",
{
if (command == COM_BINLOG_DUMP)
{
net->last_errno = ER_NET_ERROR_ON_WRITE;
DBUG_ASSERT(!debug_sync_set_action(
(THD *)net->thd,
STRING_WITH_LEN("now SIGNAL parked WAIT_FOR continue")));
DBUG_RETURN(true);
}
};);
MYSQL_NET_WRITE_START(length);
buff[4]=command; /* For first packet */
if (length >= MAX_PACKET_LENGTH)
{
/* Take into account that we have the command in the first header */
len= MAX_PACKET_LENGTH - 1 - head_len;
do
{
int3store(buff, MAX_PACKET_LENGTH);
buff[3]= (uchar) net->pkt_nr++;
if (net_write_buff(net, buff, header_size) ||
net_write_buff(net, header, head_len) ||
net_write_buff(net, packet, len))
{
MYSQL_NET_WRITE_DONE(1);
DBUG_RETURN(1);
}
packet+= len;
length-= MAX_PACKET_LENGTH;
len= MAX_PACKET_LENGTH;
head_len= 0;
header_size= NET_HEADER_SIZE;
} while (length >= MAX_PACKET_LENGTH);
len=length; /* Data left to be written */
}
int3store(buff,length);
buff[3]= (uchar) net->pkt_nr++;
rc= MY_TEST(net_write_buff(net, buff, header_size) ||
(head_len && net_write_buff(net, header, head_len)) ||
net_write_buff(net, packet, len) || net_flush(net));
MYSQL_NET_WRITE_DONE(rc);
DBUG_RETURN(rc);
}
/**
Caching the data in a local buffer before sending it.
Fill up net->buffer and send it to the client when full.
If the rest of the to-be-sent-packet is bigger than buffer,
send it in one big block (to avoid copying to internal buffer).
If not, copy the rest of the data to the buffer and return without
sending data.
@param net Network handler
@param packet Packet to send
@param len Length of packet
@note
The cached buffer can be sent as it is with 'net_flush()'.
In this code we have to be careful to not send a packet longer than
MAX_PACKET_LENGTH to net_real_write() if we are using the compressed
protocol as we store the length of the compressed packet in 3 bytes.
@retval
0 ok
@retval
1
*/
static my_bool
net_write_buff(NET *net, const uchar *packet, size_t len)
{
size_t left_length;
if (net->compress && net->max_packet > MAX_PACKET_LENGTH)
left_length= (MAX_PACKET_LENGTH - (net->write_pos - net->buff));
else
left_length= (net->buff_end - net->write_pos);
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_written", packet, len);
#endif
if (len > left_length)
{
if (net->write_pos != net->buff)
{
/* Fill up already used packet and write it */
memcpy((char*) net->write_pos,packet,left_length);
if (net_real_write(net, net->buff,
(size_t) (net->write_pos - net->buff) + left_length))
return 1;
net->write_pos= net->buff;
packet+= left_length;
len-= left_length;
}
if (net->compress)
{
/*
We can't have bigger packets than 16M with compression
Because the uncompressed length is stored in 3 bytes
*/
left_length= MAX_PACKET_LENGTH;
while (len > left_length)
{
if (net_real_write(net, packet, left_length))
return 1;
packet+= left_length;
len-= left_length;
}
}
if (len > net->max_packet)
return net_real_write(net, packet, len) ? 1 : 0;
/* Send out rest of the blocks as full sized blocks */
}
if (len)
memcpy((char*) net->write_pos,packet,len);
net->write_pos+= len;
return 0;
}
/**
Read and write one packet using timeouts.
If needed, the packet is compressed before sending.
@todo
- TODO is it needed to set this variable if we have no socket
*/
int
net_real_write(NET *net,const uchar *packet, size_t len)
{
size_t length;
const uchar *pos,*end;
thr_alarm_t alarmed;
#ifndef NO_ALARM
ALARM alarm_buff;
#endif
uint retry_count=0;
my_bool net_blocking = vio_is_blocking(net->vio);
DBUG_ENTER("net_real_write");
#if defined(MYSQL_SERVER)
THD *thd= (THD *)net->thd;
#if defined(USE_QUERY_CACHE)
query_cache_insert(thd, (char*) packet, len, net->pkt_nr);
#endif
if (likely(thd))
{
/*
Wait until pending operations (currently it is engine
asynchronous group commit) are finished before replying
to the client, to keep durability promise.
*/
thd->async_state.wait_for_pending_ops();
}
#endif
if (unlikely(net->error == 2))
DBUG_RETURN(-1); /* socket can't be used */
net->reading_or_writing=2;
#ifdef HAVE_COMPRESS
if (net->compress)
{
size_t complen;
uchar *b;
uint header_length=NET_HEADER_SIZE+COMP_HEADER_SIZE;
if (!(b= (uchar*) my_malloc(key_memory_NET_compress_packet,
len + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1,
MYF(MY_WME | (net->thread_specific_malloc
? MY_THREAD_SPECIFIC : 0)))))
{
net->error= 2;
net->last_errno= ER_OUT_OF_RESOURCES;
/* In the server, the error is reported by MY_WME flag. */
net->reading_or_writing= 0;
DBUG_RETURN(1);
}
memcpy(b+header_length,packet,len);
/* Don't compress error packets (compress == 2) */
if (net->compress == 2 || my_compress(b+header_length, &len, &complen))
complen=0;
int3store(&b[NET_HEADER_SIZE],complen);
int3store(b,len);
b[3]=(uchar) (net->compress_pkt_nr++);
len+= header_length;
packet= b;
}
#endif /* HAVE_COMPRESS */
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_written", packet, len);
#endif
#ifndef NO_ALARM
thr_alarm_init(&alarmed);
if (net_blocking)
thr_alarm(&alarmed, net->write_timeout, &alarm_buff);
#else
alarmed=0;
/* Write timeout is set in my_net_set_write_timeout */
#endif /* NO_ALARM */
pos= packet;
end=pos+len;
while (pos != end)
{
if ((long) (length= vio_write(net->vio,pos,(size_t) (end-pos))) <= 0)
{
my_bool interrupted = vio_should_retry(net->vio);
#if !defined(_WIN32)
if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed))
{
if (!thr_alarm(&alarmed, net->write_timeout, &alarm_buff))
{ /* Always true for client */
my_bool old_mode;
while (vio_blocking(net->vio, TRUE, &old_mode) < 0)
{
if (vio_should_retry(net->vio) && retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr,
"%s: my_net_write: fcntl returned error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
net->error= 2; /* Close socket */
net->last_errno= ER_NET_PACKET_TOO_LARGE;
MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
goto end;
}
retry_count=0;
continue;
}
}
else
#endif /* !defined(_WIN32) */
if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) &&
interrupted)
{
if (retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr, "%s: write looped, aborting thread\n",
my_progname);
}
#ifndef MYSQL_SERVER
if (vio_errno(net->vio) == SOCKET_EINTR)
{
DBUG_PRINT("warning",("Interrupted write. Retrying..."));
continue;
}
#endif /* !defined(MYSQL_SERVER) */
net->error= 2; /* Close socket */
net->last_errno= (interrupted ? ER_NET_WRITE_INTERRUPTED :
ER_NET_ERROR_ON_WRITE);
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
break;
}
pos+=length;
update_statistics(thd_increment_bytes_sent(net->thd, length));
}
#ifndef _WIN32
end:
#endif
#ifdef HAVE_COMPRESS
if (net->compress)
my_free((void*) packet);
#endif
if (thr_alarm_in_use(&alarmed))
{
my_bool old_mode;
thr_end_alarm(&alarmed);
if (!net_blocking)
vio_blocking(net->vio, net_blocking, &old_mode);
}
net->reading_or_writing=0;
DBUG_RETURN(((int) (pos != end)));
}
/*****************************************************************************
** Read something from server/clinet
*****************************************************************************/
#ifndef NO_ALARM
static my_bool net_safe_read(NET *net, uchar *buff, size_t length,
thr_alarm_t *alarmed)
{
uint retry_count=0;
while (length > 0)
{
size_t tmp;
if ((long) (tmp= vio_read(net->vio, buff, length)) <= 0)
{
my_bool interrupted = vio_should_retry(net->vio);
if (!thr_got_alarm(alarmed) && interrupted)
{ /* Probably in MIT threads */
if (retry_count++ < net->retry_count)
continue;
}
return 1;
}
length-= tmp;
buff+= tmp;
}
return 0;
}
/**
Help function to clear the commuication buffer when we get a too big packet.
@param net Communication handle
@param remain Bytes to read
@param alarmed Parameter for thr_alarm()
@param alarm_buff Parameter for thr_alarm()
@retval
0 Was able to read the whole packet
@retval
1 Got mailformed packet from client
*/
static my_bool my_net_skip_rest(NET *net, uint32 remain, thr_alarm_t *alarmed,
ALARM *alarm_buff)
{
longlong limit= net->max_packet_size*net->net_skip_rest_factor;
uint32 old=remain;
DBUG_ENTER("my_net_skip_rest");
DBUG_PRINT("enter",("bytes_to_skip: %u", (uint) remain));
/* The following is good for debugging */
update_statistics(thd_increment_net_big_packet_count(net->thd, 1));
if (!thr_alarm_in_use(alarmed))
{
my_bool old_mode;
if (thr_alarm(alarmed,net->read_timeout, alarm_buff) ||
vio_blocking(net->vio, TRUE, &old_mode) < 0)
DBUG_RETURN(1); /* Can't setup, abort */
}
for (;;)
{
while (remain > 0)
{
size_t length= MY_MIN(remain, net->max_packet);
if (net_safe_read(net, net->buff, length, alarmed))
DBUG_RETURN(1);
update_statistics(thd_increment_bytes_received(net->thd, length));
remain -= (uint32) length;
limit-= length;
if (limit < 0)
DBUG_RETURN(1);
}
if (old != MAX_PACKET_LENGTH)
break;
if (net_safe_read(net, net->buff, NET_HEADER_SIZE, alarmed))
DBUG_RETURN(1);
limit-= NET_HEADER_SIZE;
old=remain= uint3korr(net->buff);
net->pkt_nr++;
}
DBUG_RETURN(0);
}
#endif /* NO_ALARM */
/**
Try to parse and process proxy protocol header.
This function is called in case MySQL packet header cannot be parsed.
It checks if proxy header was sent, and that it was send from allowed remote
host, as defined by proxy-protocol-networks parameter.
If proxy header is parsed, then THD and ACL structures and changed to indicate
the new peer address and port.
Note, that proxy header can only be sent either when the connection is established,
or as the client reply packet to
*/
#undef IGNORE /* for Windows */
typedef enum { RETRY, ABORT, IGNORE} handle_proxy_header_result;
static handle_proxy_header_result handle_proxy_header(NET *net)
{
#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
return IGNORE;
#else
THD *thd= (THD *)net->thd;
if (!has_proxy_protocol_header(net) || !thd ||
thd->get_command() != COM_CONNECT)
return IGNORE;
/*
Proxy information found in the first 4 bytes received so far.
Read and parse proxy header , change peer ip address and port in THD.
*/
proxy_peer_info peer_info;
if (!thd->net.vio)
{
DBUG_ASSERT(0);
return ABORT;
}
if (!is_proxy_protocol_allowed((sockaddr *)&(thd->net.vio->remote)))
{
/* proxy-protocol-networks variable needs to be set to allow this remote address */
my_printf_error(ER_HOST_NOT_PRIVILEGED, "Proxy header is not accepted from %s",
MYF(0), thd->main_security_ctx.ip);
return ABORT;
}
if (parse_proxy_protocol_header(net, &peer_info))
{
/* Failed to parse proxy header*/
my_printf_error(ER_UNKNOWN_ERROR, "Failed to parse proxy header", MYF(0));
return ABORT;
}
if (peer_info.is_local_command)
/* proxy header indicates LOCAL connection, no action necessary */
return RETRY;
/* Change peer address in THD and ACL structures.*/
uint host_errors;
return (handle_proxy_header_result)thd_set_peer_addr(thd,
&(peer_info.peer_addr), NULL, peer_info.port,
false, &host_errors);
#endif
}
/**
Reads one packet to net->buff + net->where_b.
Long packets are handled by my_net_read().
This function reallocates the net->buff buffer if necessary.
@return
Returns length of packet.
*/
static ulong
my_real_read(NET *net, size_t *complen,
my_bool header __attribute__((unused)))
{
uchar *pos;
size_t length;
uint i,retry_count=0;
ulong len=packet_error;
my_bool expect_error_packet __attribute__((unused))= 0;
thr_alarm_t alarmed;
#ifndef NO_ALARM
ALARM alarm_buff;
#endif
retry:
my_bool net_blocking=vio_is_blocking(net->vio);
uint32 remain= (net->compress ? NET_HEADER_SIZE+COMP_HEADER_SIZE :
NET_HEADER_SIZE);
#ifdef MYSQL_SERVER
size_t count= remain;
struct st_net_server *server_extension= 0;
if (header)
{
server_extension= static_cast<st_net_server*> (net->extension);
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_before_header(net, user_data, count);
}
}
#endif
*complen = 0;
net->reading_or_writing=1;
thr_alarm_init(&alarmed);
#ifndef NO_ALARM
if (net_blocking)
thr_alarm(&alarmed,net->read_timeout,&alarm_buff);
#else
/* Read timeout is set in my_net_set_read_timeout */
#endif /* NO_ALARM */
pos = net->buff + net->where_b; /* net->packet -4 */
for (i=0 ; i < 2 ; i++)
{
while (remain > 0)
{
/* First read is done with non blocking mode */
if ((long) (length= vio_read(net->vio, pos, remain)) <= 0L)
{
my_bool interrupted = vio_should_retry(net->vio);
DBUG_PRINT("info",("vio_read returned %ld errno: %d",
(long) length, vio_errno(net->vio)));
if (i== 0 && unlikely(thd_net_is_killed((THD*) net->thd)))
{
DBUG_PRINT("info", ("thd is killed"));
len= packet_error;
net->error= 0;
net->last_errno= ER_CONNECTION_KILLED;
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
goto end;
}
#if !defined(_WIN32) && defined(MYSQL_SERVER)
/*
We got an error that there was no data on the socket. We now set up
an alarm to not 'read forever', change the socket to the blocking
mode and try again
*/
if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed))
{
if (!thr_alarm(&alarmed,net->read_timeout,&alarm_buff)) /* Don't wait too long */
{
my_bool old_mode;
while (vio_blocking(net->vio, TRUE, &old_mode) < 0)
{
if (vio_should_retry(net->vio) &&
retry_count++ < net->retry_count)
continue;
DBUG_PRINT("error",
("fcntl returned error %d, aborting thread",
vio_errno(net->vio)));
EXTRA_DEBUG_fprintf(stderr,
"%s: read: fcntl returned error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
len= packet_error;
net->error= 2; /* Close socket */
net->last_errno= ER_NET_FCNTL_ERROR;
MYSQL_SERVER_my_error(ER_NET_FCNTL_ERROR, MYF(0));
goto end;
}
retry_count=0;
continue;
}
}
#endif /* (!defined(_WIN32) && defined(MYSQL_SERVER) */
if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) &&
interrupted)
{ /* Probably in MIT threads */
if (retry_count++ < net->retry_count)
continue;
EXTRA_DEBUG_fprintf(stderr, "%s: read looped with error %d, aborting thread\n",
my_progname,vio_errno(net->vio));
}
#ifndef MYSQL_SERVER
if (length != 0 && vio_errno(net->vio) == SOCKET_EINTR)
{
DBUG_PRINT("warning",("Interrupted read. Retrying..."));
continue;
}
#endif
DBUG_PRINT("error",("Couldn't read packet: remain: %u errno: %d length: %ld",
remain, vio_errno(net->vio), (long) length));
len= packet_error;
net->error= 2; /* Close socket */
net->last_errno= (vio_was_timeout(net->vio) ?
ER_NET_READ_INTERRUPTED :
ER_NET_READ_ERROR);
MYSQL_SERVER_my_error(net->last_errno, MYF(0));
goto end;
}
remain -= (uint32) length;
pos+= length;
update_statistics(thd_increment_bytes_received(net->thd, length));
}
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data_read", net->buff+net->where_b, length);
#endif
if (i == 0)
{ /* First parts is packet length */
size_t helping;
#ifndef DEBUG_DATA_PACKETS
DBUG_DUMP("packet_header", net->buff+net->where_b,
NET_HEADER_SIZE);
#endif
if (net->buff[net->where_b + 3] != (uchar) net->pkt_nr)
{
#ifndef MYSQL_SERVER
if (net->buff[net->where_b + 3] == (uchar) (net->pkt_nr -1))
{
/*
If the server was killed then the server may have missed the
last sent client packet and the packet numbering may be one off.
*/
DBUG_PRINT("warning", ("Found possible out of order packets"));
expect_error_packet= 1;
}
else
#endif
goto packets_out_of_order;
}
net->compress_pkt_nr= ++net->pkt_nr;
#ifdef HAVE_COMPRESS
if (net->compress)
{
/*
The following uint3korr() may read 4 bytes, so make sure we don't
read unallocated or uninitialized memory. The right-hand expression
must match the size of the buffer allocated in net_realloc().
*/
DBUG_ASSERT(net->where_b + NET_HEADER_SIZE + sizeof(uint32) <=
net->max_packet + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1);
/*
If the packet is compressed then complen > 0 and contains the
number of bytes in the uncompressed packet
*/
*complen=uint3korr(&(net->buff[net->where_b + NET_HEADER_SIZE]));
}
#endif
len=uint3korr(net->buff+net->where_b);
if (!len) /* End of big multi-packet */
goto end;
helping = MY_MAX(len,*complen) + net->where_b;
/* The necessary size of net->buff */
if (helping >= net->max_packet)
{
if (net_realloc(net,helping))
{
#if defined(MYSQL_SERVER) && !defined(NO_ALARM)
if (!net->compress &&
!my_net_skip_rest(net, (uint32) len, &alarmed, &alarm_buff))
net->error= 3; /* Successfully skiped packet */
#endif
len= packet_error; /* Return error and close connection */
goto end;
}
}
pos=net->buff + net->where_b;
remain = (uint32) len;
#ifdef MYSQL_SERVER
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_after_header(net, user_data, count, 0);
server_extension= NULL;
}
#endif
}
#ifndef MYSQL_SERVER
else if (expect_error_packet)
{
/*
This check is safe both for compressed and not compressed protocol
as for the compressed protocol errors are not compressed anymore.
*/
if (net->buff[net->where_b] != (uchar) 255)
{
/* Restore pkt_nr to original value */
net->pkt_nr--;
goto packets_out_of_order;
}
}
#endif
}
end:
if (thr_alarm_in_use(&alarmed))
{
my_bool old_mode;
thr_end_alarm(&alarmed);
if (!net_blocking)
vio_blocking(net->vio, net_blocking, &old_mode);
}
net->reading_or_writing=0;
#ifdef DEBUG_DATA_PACKETS
if (len != packet_error)
DBUG_DUMP("data_read", net->buff+net->where_b, len);
#endif
#ifdef MYSQL_SERVER
if (server_extension != NULL)
{
void *user_data= server_extension->m_user_data;
server_extension->m_after_header(net, user_data, count, 1);
DBUG_ASSERT(len == packet_error || len == 0);
}
#endif
return(len);
packets_out_of_order:
{
switch (handle_proxy_header(net)) {
case ABORT:
/* error happened, message is already written. */
len= packet_error;
goto end;
case RETRY:
goto retry;
case IGNORE:
break;
}
DBUG_PRINT("error",
("Packets out of order (Found: %d, expected %u)",
(int) net->buff[net->where_b + 3],
net->pkt_nr));
EXTRA_DEBUG_ASSERT(0);
/*
We don't make noise server side, since the client is expected
to break the protocol for e.g. --send LOAD DATA .. LOCAL where
the server expects the client to send a file, but the client
may reply with a new command instead.
*/
#ifndef MYSQL_SERVER
EXTRA_DEBUG_fflush(stdout);
EXTRA_DEBUG_fprintf(stderr,"Error: Packets out of order (Found: %d, expected %d)\n",
(int) net->buff[net->where_b + 3],
(uint) (uchar) net->pkt_nr);
EXTRA_DEBUG_fflush(stderr);
#endif
len= packet_error;
MYSQL_SERVER_my_error(ER_NET_PACKETS_OUT_OF_ORDER, MYF(0));
goto end;
}
}
/* Old interface. See my_net_read_packet() for function description */
#undef my_net_read
ulong my_net_read(NET *net)
{
return my_net_read_packet(net, 0);
}
/**
Read a packet from the client/server and return it without the internal
package header.
If the packet is the first packet of a multi-packet packet
(which is indicated by the length of the packet = 0xffffff) then
all sub packets are read and concatenated.
If the packet was compressed, its uncompressed and the length of the
uncompressed packet is returned.
read_from_server is set when the server is reading a new command
from the client.
@return
The function returns the length of the found packet or packet_error.
net->read_pos points to the read data.
*/
ulong
my_net_read_packet(NET *net, my_bool read_from_server)
{
ulong reallen = 0;
return my_net_read_packet_reallen(net, read_from_server, &reallen);
}
ulong
my_net_read_packet_reallen(NET *net, my_bool read_from_server, ulong* reallen)
{
size_t len, complen;
MYSQL_NET_READ_START();
*reallen = 0;
#ifdef HAVE_COMPRESS
if (!net->compress)
{
#endif
len = my_real_read(net,&complen, read_from_server);
if (len == MAX_PACKET_LENGTH)
{
/* First packet of a multi-packet. Concatenate the packets */
ulong save_pos = net->where_b;
size_t total_length= 0;
do
{
net->where_b += (ulong)len;
total_length += len;
len = my_real_read(net,&complen, 0);
} while (len == MAX_PACKET_LENGTH);
if (likely(len != packet_error))
len+= total_length;
net->where_b = save_pos;
}
net->read_pos = net->buff + net->where_b;
if (likely(len != packet_error))
{
net->read_pos[len]=0; /* Safeguard for mysql_use_result */
*reallen = (ulong)len;
}
MYSQL_NET_READ_DONE(0, len);
return (ulong)len;
#ifdef HAVE_COMPRESS
}
else
{
/* We are using the compressed protocol */
ulong buf_length;
ulong start_of_packet;
ulong first_packet_offset;
uint read_length, multi_byte_packet=0;
if (net->remain_in_buf)
{
buf_length= net->buf_length; /* Data left in old packet */
first_packet_offset= start_of_packet= (net->buf_length -
net->remain_in_buf);
/* Restore the character that was overwritten by the end 0 */
net->buff[start_of_packet]= net->save_char;
}
else
{
/* reuse buffer, as there is nothing in it that we need */
buf_length= start_of_packet= first_packet_offset= 0;
}
for (;;)
{
ulong packet_len;
if (buf_length - start_of_packet >= NET_HEADER_SIZE)
{
read_length = uint3korr(net->buff+start_of_packet);
if (!read_length)
{
/* End of multi-byte packet */
start_of_packet += NET_HEADER_SIZE;
break;
}
if (read_length + NET_HEADER_SIZE <= buf_length - start_of_packet)
{
if (multi_byte_packet)
{
/* Remove packet header for second packet */
memmove(net->buff + first_packet_offset + start_of_packet,
net->buff + first_packet_offset + start_of_packet +
NET_HEADER_SIZE,
buf_length - start_of_packet);
start_of_packet += read_length;
buf_length -= NET_HEADER_SIZE;
}
else
start_of_packet+= read_length + NET_HEADER_SIZE;
if (read_length != MAX_PACKET_LENGTH) /* last package */
{
multi_byte_packet= 0; /* No last zero len packet */
break;
}
multi_byte_packet= NET_HEADER_SIZE;
/* Move data down to read next data packet after current one */
if (first_packet_offset)
{
memmove(net->buff,net->buff+first_packet_offset,
buf_length-first_packet_offset);
buf_length-=first_packet_offset;
start_of_packet -= first_packet_offset;
first_packet_offset=0;
}
continue;
}
}
/* Move data down to read next data packet after current one */
if (first_packet_offset)
{
memmove(net->buff,net->buff+first_packet_offset,
buf_length-first_packet_offset);
buf_length-=first_packet_offset;
start_of_packet -= first_packet_offset;
first_packet_offset=0;
}
net->where_b=buf_length;
if ((packet_len = my_real_read(net,&complen, read_from_server))
== packet_error)
{
MYSQL_NET_READ_DONE(1, 0);
return packet_error;
}
read_from_server= 0;
if (my_uncompress(net->buff + net->where_b, packet_len,
&complen))
{
net->error= 2; /* caller will close socket */
net->last_errno= ER_NET_UNCOMPRESS_ERROR;
MYSQL_SERVER_my_error(ER_NET_UNCOMPRESS_ERROR, MYF(0));
MYSQL_NET_READ_DONE(1, 0);
return packet_error;
}
buf_length+= (ulong)complen;
*reallen += packet_len;
}
net->read_pos= net->buff+ first_packet_offset + NET_HEADER_SIZE;
net->buf_length= buf_length;
net->remain_in_buf= (ulong) (buf_length - start_of_packet);
len = ((ulong) (start_of_packet - first_packet_offset) - NET_HEADER_SIZE -
multi_byte_packet);
net->save_char= net->read_pos[len]; /* Must be saved */
net->read_pos[len]=0; /* Safeguard for mysql_use_result */
}
#endif /* HAVE_COMPRESS */
MYSQL_NET_READ_DONE(0, len);
return (ulong)len;
}
void my_net_set_read_timeout(NET *net, uint timeout)
{
DBUG_ENTER("my_net_set_read_timeout");
DBUG_PRINT("enter", ("timeout: %d", timeout));
if (net->read_timeout != timeout)
{
net->read_timeout= timeout;
if (net->vio)
vio_timeout(net->vio, 0, timeout);
}
DBUG_VOID_RETURN;
}
void my_net_set_write_timeout(NET *net, uint timeout)
{
DBUG_ENTER("my_net_set_write_timeout");
DBUG_PRINT("enter", ("timeout: %d", timeout));
if (net->write_timeout != timeout)
{
net->write_timeout= timeout;
if (net->vio)
vio_timeout(net->vio, 1, timeout);
}
DBUG_VOID_RETURN;
}
| MariaDB/server | sql/net_serv.cc | C++ | gpl-2.0 | 40,989 |
<?php
namespace UsingTraits;
/**
* A controller.
*/
class ProductController
{
use DeleteEntity;
/**
* @OA\Get(
* tags={"Products"},
* path="/products/{product_id}",
* @OA\Parameter(
* description="ID of product to return",
* in="path",
* name="product_id",
* required=true,
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Response(
* response="default",
* description="successful operation"
* )
* )
*/
public function getProduct($id)
{
}
}
| egbot/Symbiota | api/vendor/zircote/swagger-php/Examples/using-traits/ProductController.php | PHP | gpl-2.0 | 606 |
/*
* 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/>.
*/
/* ScriptData
SDName: Assembly of Iron
Author:
SD%Complete: 100%
SDComment:
EndScriptData */
#include "ScriptPCH.h"
#include "ulduar.h"
enum Spells
{
// Any boss
SPELL_SUPERCHARGE = 61920,
SPELL_BERSERK = 47008, // Hard enrage, don't know the correct ID.
// Steelbreaker
SPELL_HIGH_VOLTAGE = 61890,
SPELL_FUSION_PUNCH = 61903,
SPELL_STATIC_DISRUPTION = 44008, //63494
SPELL_OVERWHELMING_POWER = 64637,
SPELL_ELECTRICAL_CHARGE = 61902,
// Runemaster Molgeim
SPELL_SHIELD_OF_RUNES = 62274,
SPELL_RUNE_OF_POWER = 61973,
SPELL_RUNE_OF_POWER_VISUAL = 61974,
SPELL_RUNE_OF_DEATH = 62269,
SPELL_RUNE_OF_SUMMONING = 62273,
SPELL_RUNE_OF_SUMMONING_VISUAL = 62019,
SPELL_RUNE_OF_SUMMONING_SUMMON = 62020,
SPELL_LIGHTNING_BLAST = 62054,
// Stormcaller Brundir
SPELL_CHAIN_LIGHTNING = 61879,
SPELL_OVERLOAD = 61869,
SPELL_LIGHTNING_WHIRL = 61915,
SPELL_LIGHTNING_TENDRILS = 61887,
SPELL_LIGHTNING_TENDRILS_SELF_VISUAL = 61883,
SPELL_STORMSHIELD = 64187
};
enum eEnums
{
EVENT_ENRAGE,
// Steelbreaker
EVENT_FUSION_PUNCH,
EVENT_STATIC_DISRUPTION,
EVENT_OVERWHELMING_POWER,
// Molgeim
EVENT_RUNE_OF_POWER,
EVENT_SHIELD_OF_RUNES,
EVENT_RUNE_OF_DEATH,
EVENT_RUNE_OF_SUMMONING,
EVENT_LIGHTNING_BLAST,
// Brundir
EVENT_CHAIN_LIGHTNING,
EVENT_OVERLOAD,
EVENT_LIGHTNING_WHIRL,
EVENT_LIGHTNING_TENDRILS,
EVENT_FLIGHT,
EVENT_ENDFLIGHT,
EVENT_GROUND,
EVENT_LAND,
EVENT_MOVE_POS
};
enum Actions
{
ACTION_STEELBREAKER,
ACTION_MOLGEIM,
ACTION_BRUNDIR
};
// Achievements
#define ACHIEVEMENT_ON_YOUR_SIDE RAID_MODE(2945, 2946) // TODO
#define ACHIEVEMENT_CANT_WHILE_STUNNED RAID_MODE(2947, 2948) // TODO
#define ACHIEVEMENT_CHOOSE_STEELBREAKER RAID_MODE(2941, 2944)
#define ACHIEVEMENT_CHOOSE_MOLGEIM RAID_MODE(2939, 2942)
#define ACHIEVEMENT_CHOOSE_BRUNDIR RAID_MODE(2940, 2943)
#define EMOTE_OVERLOAD "Stormcaller Brundir begins to Overload!"
enum Yells
{
SAY_STEELBREAKER_AGGRO = -1603020,
SAY_STEELBREAKER_SLAY_1 = -1603021,
SAY_STEELBREAKER_SLAY_2 = -1603022,
SAY_STEELBREAKER_POWER = -1603023,
SAY_STEELBREAKER_DEATH_1 = -1603024,
SAY_STEELBREAKER_DEATH_2 = -1603025,
SAY_STEELBREAKER_BERSERK = -1603026,
SAY_MOLGEIM_AGGRO = -1603030,
SAY_MOLGEIM_SLAY_1 = -1603031,
SAY_MOLGEIM_SLAY_2 = -1603032,
SAY_MOLGEIM_RUNE_DEATH = -1603033,
SAY_MOLGEIM_SUMMON = -1603034,
SAY_MOLGEIM_DEATH_1 = -1603035,
SAY_MOLGEIM_DEATH_2 = -1603036,
SAY_MOLGEIM_BERSERK = -1603037,
SAY_BRUNDIR_AGGRO = -1603040,
SAY_BRUNDIR_SLAY_1 = -1603041,
SAY_BRUNDIR_SLAY_2 = -1603042,
SAY_BRUNDIR_SPECIAL = -1603043,
SAY_BRUNDIR_FLIGHT = -1603044,
SAY_BRUNDIR_DEATH_1 = -1603045,
SAY_BRUNDIR_DEATH_2 = -1603046,
SAY_BRUNDIR_BERSERK = -1603047,
};
bool IsEncounterComplete(InstanceScript* pInstance, Creature* me)
{
if (!pInstance || !me)
return false;
for (uint8 i = 0; i < 3; ++i)
{
uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i);
if (!guid)
return false;
if (Creature *boss = Unit::GetCreature(*me, guid))
{
if (boss->isAlive())
return false;
}
else
return false;
}
return true;
}
// Avoid killing bosses one to one
void CallBosses(InstanceScript* pInstance, uint32 caller, Unit *who)
{
// Respawn if dead
if (Creature* Steelbreaker = who->GetCreature(*who, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Brundir = who->GetCreature(*who, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Molgeim = who->GetCreature(*who, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
for (uint8 i = 0; i < 3; ++i)
{
if (caller == DATA_STEELBREAKER+i) continue;
uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i);
if (!guid) return;
if (Creature* m_boss = pInstance->instance->GetCreature(guid))
{
if (m_boss->isAlive())
{
m_boss->AddThreat(who, 100.0f);
m_boss->AI()->AttackStart(who);
}
}
}
}
class boss_steelbreaker : public CreatureScript
{
public:
boss_steelbreaker() : CreatureScript("boss_steelbreaker") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_steelbreakerAI (pCreature);
}
struct boss_steelbreakerAI : public ScriptedAI
{
boss_steelbreakerAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
EventMap events;
InstanceScript* pInstance;
uint32 phase;
void Reset()
{
events.Reset();
phase = 0;
me->RemoveAllAuras();
me->ResetLootMode();
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
// Respawn
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_STEELBREAKER_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_STEELBREAKER, who);
DoCast(me, SPELL_HIGH_VOLTAGE);
phase = 1;
events.SetPhase(phase);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_FUSION_PUNCH, 15000);
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_STEELBREAKER_DEATH_1, SAY_STEELBREAKER_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_STEELBREAKER);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
}
else me->SetLootRecipient(NULL);
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isAlive())
Brundir->AI()->DoAction(ACTION_BRUNDIR);
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isAlive())
Molgeim->AI()->DoAction(ACTION_MOLGEIM);
}
void KilledUnit(Unit * /*who*/)
{
DoScriptText(RAND(SAY_STEELBREAKER_SLAY_1,SAY_STEELBREAKER_SLAY_2), me);
if (phase == 3)
DoCast(me, SPELL_ELECTRICAL_CHARGE);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_ENRAGE:
DoScriptText(SAY_STEELBREAKER_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_FUSION_PUNCH:
if (me->IsWithinMeleeRange(me->getVictim()))
DoCastVictim(SPELL_FUSION_PUNCH);
events.ScheduleEvent(EVENT_FUSION_PUNCH, urand(15000, 20000));
break;
case EVENT_STATIC_DISRUPTION:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_STATIC_DISRUPTION);
events.ScheduleEvent(EVENT_STATIC_DISRUPTION, 20000 + (rand()%20)*1000);
break;
case EVENT_OVERWHELMING_POWER:
DoScriptText(SAY_STEELBREAKER_POWER, me);
DoCastVictim(SPELL_OVERWHELMING_POWER);
events.ScheduleEvent(EVENT_OVERWHELMING_POWER, RAID_MODE(60000, 35000));
break;
}
}
DoMeleeAttackIfReady();
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_STEELBREAKER:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
if (phase >= 2)
events.RescheduleEvent(EVENT_STATIC_DISRUPTION, 30000);
if (phase >= 3)
{
events.RescheduleEvent(EVENT_OVERWHELMING_POWER, urand(2000, 5000));
// Add HardMode Loot
me->AddLootMode(LOOT_MODE_HARD_MODE_2);
}
break;
}
}
};
};
class boss_runemaster_molgeim : public CreatureScript
{
public:
boss_runemaster_molgeim() : CreatureScript("boss_runemaster_molgeim") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_runemaster_molgeimAI (pCreature);
}
struct boss_runemaster_molgeimAI : public ScriptedAI
{
boss_runemaster_molgeimAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
InstanceScript* pInstance;
EventMap events;
uint32 phase;
void Reset()
{
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
events.Reset();
me->ResetLootMode();
me->RemoveAllAuras();
phase = 0;
// Respawn
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isDead())
{
Brundir->Respawn(true);
Brundir->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_MOLGEIM_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_MOLGEIM, who);
phase = 1;
pInstance->SetBossState(BOSS_ASSEMBLY, IN_PROGRESS);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, 30000);
events.ScheduleEvent(EVENT_RUNE_OF_POWER, 20000);
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_MOLGEIM_DEATH_1, SAY_MOLGEIM_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_MOLGEIM);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
}
else me->SetLootRecipient(NULL);
if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR)))
if (Brundir->isAlive())
Brundir->AI()->DoAction(ACTION_BRUNDIR);
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isAlive())
Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER);
}
void KilledUnit(Unit * /*who*/)
{
DoScriptText(RAND(SAY_MOLGEIM_SLAY_1,SAY_MOLGEIM_SLAY_2), me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_ENRAGE:
DoScriptText(SAY_MOLGEIM_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_RUNE_OF_POWER: // random alive friendly
{
Creature* bosschoosed;
uint32 choice = urand(0,2);
if (!pInstance) break;
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
if (!bosschoosed || !bosschoosed->isAlive())
{
choice = ((choice == 2) ? 0 : choice++);
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
if (!bosschoosed || !bosschoosed->isAlive())
{
choice = ((choice == 2) ? 0 : choice++);
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice));
}
}
if (!bosschoosed || !bosschoosed->isAlive())
bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM));
DoCast(bosschoosed, SPELL_RUNE_OF_POWER);
events.ScheduleEvent(EVENT_RUNE_OF_POWER, 35000);
break;
}
case EVENT_SHIELD_OF_RUNES:
DoCast(me, SPELL_SHIELD_OF_RUNES);
events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, urand(60000, 80000));
break;
case EVENT_RUNE_OF_DEATH:
DoScriptText(SAY_MOLGEIM_RUNE_DEATH, me);
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_RUNE_OF_DEATH);
events.ScheduleEvent(EVENT_RUNE_OF_DEATH, 30000);
break;
case EVENT_RUNE_OF_SUMMONING:
DoScriptText(SAY_MOLGEIM_SUMMON, me);
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_RUNE_OF_SUMMONING);
events.ScheduleEvent(EVENT_RUNE_OF_SUMMONING, urand(40000, 50000));
break;
}
}
DoMeleeAttackIfReady();
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_MOLGEIM:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
events.RescheduleEvent(EVENT_SHIELD_OF_RUNES, 30000);
events.RescheduleEvent(EVENT_RUNE_OF_POWER, 20000);
if (phase >= 2)
events.RescheduleEvent(EVENT_RUNE_OF_DEATH, 35000);
if (phase >= 3)
{
events.RescheduleEvent(EVENT_RUNE_OF_SUMMONING, 40000);
me->AddLootMode(LOOT_MODE_HARD_MODE_1);
}
break;
}
}
};
};
class npc_lightning_elemental : public CreatureScript
{
public:
npc_lightning_elemental() : CreatureScript("npc_lightning_elemental") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_lightning_elementalAI (pCreature);
}
struct npc_lightning_elementalAI : public ScriptedAI
{
npc_lightning_elementalAI(Creature *c) : ScriptedAI(c)
{
Charge();
Casted = false;
}
bool Casted;
void Charge()
{
Unit* pTarget = me->SelectNearestTarget();
me->AddThreat(pTarget, 5000000.0f);
AttackStart(pTarget);
}
void UpdateAI(const uint32 /*diff*/)
{
if (!UpdateVictim())
return;
if (me->IsWithinMeleeRange(me->getVictim()) && !Casted)
{
me->CastSpell(me, SPELL_LIGHTNING_BLAST, true);
me->ForcedDespawn(500);
Casted = true;
}
}
};
};
class npc_rune_of_summoning : public CreatureScript
{
public:
npc_rune_of_summoning() : CreatureScript("npc_rune_of_summoning") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_rune_of_summoningAI (pCreature);
}
struct npc_rune_of_summoningAI : public Scripted_NoMovementAI
{
npc_rune_of_summoningAI(Creature *c) : Scripted_NoMovementAI(c)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED);
}
uint32 SummonTimer;
void Reset()
{
SummonTimer = 1500;
me->ForcedDespawn(12500);
DoCast(me, SPELL_RUNE_OF_SUMMONING_VISUAL);
}
void UpdateAI(const uint32 uiDiff)
{
if (SummonTimer <= uiDiff)
{
DoCast(me, SPELL_RUNE_OF_SUMMONING_SUMMON);
SummonTimer = 1500;
}
else SummonTimer -= uiDiff;
}
};
};
class npc_rune_of_power : public CreatureScript
{
public:
npc_rune_of_power() : CreatureScript("npc_rune_of_power") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new npc_rune_of_powerAI (pCreature);
}
struct npc_rune_of_powerAI : public Scripted_NoMovementAI
{
npc_rune_of_powerAI(Creature *c) : Scripted_NoMovementAI(c)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED);
me->setFaction(16);
}
void Reset()
{
DoCast(me, SPELL_RUNE_OF_POWER_VISUAL, true);
me->ForcedDespawn(35000);
}
};
};
class boss_stormcaller_brundir : public CreatureScript
{
public:
boss_stormcaller_brundir() : CreatureScript("boss_stormcaller_brundir") { }
CreatureAI* GetAI(Creature* pCreature) const
{
return new boss_stormcaller_brundirAI (pCreature);
}
struct boss_stormcaller_brundirAI : public ScriptedAI
{
boss_stormcaller_brundirAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceScript();
me->SetReactState(REACT_PASSIVE);
me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true);
me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true);
}
EventMap events;
InstanceScript* pInstance;
uint32 phase;
uint32 Position;
void Reset()
{
if (pInstance)
pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED);
me->RemoveAllAuras();
me->ResetLootMode();
me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING | MOVEMENTFLAG_WALKING);
events.Reset();
phase = 0;
// Respawn
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isDead())
{
Molgeim->Respawn(true);
Molgeim->GetMotionMaster()->MoveTargetedHome();
}
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isDead())
{
Steelbreaker->Respawn(true);
Steelbreaker->GetMotionMaster()->MoveTargetedHome();
}
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_BRUNDIR_AGGRO, me);
DoZoneInCombat();
CallBosses(pInstance, DATA_BRUNDIR, who);
phase = 1;
events.ScheduleEvent(EVENT_MOVE_POS, 1000);
events.ScheduleEvent(EVENT_ENRAGE, 900000);
events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, 2000);
events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000));
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(RAND(SAY_BRUNDIR_DEATH_1, SAY_BRUNDIR_DEATH_2), me);
if (IsEncounterComplete(pInstance, me) && pInstance)
{
pInstance->SetBossState(BOSS_ASSEMBLY, DONE);
pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_BRUNDIR);
pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195);
if (me->GetPositionZ() > 428)
me->GetMotionMaster()->MoveFall(427.28f);
}
else me->SetLootRecipient(NULL);
if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)))
if (Molgeim->isAlive())
Molgeim->AI()->DoAction(ACTION_MOLGEIM);
if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER)))
if (Steelbreaker->isAlive())
Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER);
}
void KilledUnit(Unit* /*who*/)
{
DoScriptText(RAND(SAY_BRUNDIR_SLAY_1,SAY_BRUNDIR_SLAY_2), me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STAT_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch(eventId)
{
case EVENT_MOVE_POS:
MovePos();
events.RescheduleEvent(EVENT_MOVE_POS, 10000);
break;
case EVENT_ENRAGE:
DoScriptText(SAY_BRUNDIR_BERSERK, me);
DoCast(SPELL_BERSERK);
break;
case EVENT_CHAIN_LIGHTNING:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(pTarget, SPELL_CHAIN_LIGHTNING);
events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, urand(4000, 6000));
break;
case EVENT_OVERLOAD:
me->MonsterTextEmote(EMOTE_OVERLOAD, 0, true);
DoScriptText(SAY_BRUNDIR_SPECIAL, me);
me->GetMotionMaster()->Initialize();
DoCast(SPELL_OVERLOAD);
events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000));
break;
case EVENT_LIGHTNING_WHIRL:
me->GetMotionMaster()->Initialize();
DoCast(SPELL_LIGHTNING_WHIRL);
events.ScheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000));
break;
case EVENT_LIGHTNING_TENDRILS:
DoScriptText(SAY_BRUNDIR_FLIGHT, me);
DoCast(SPELL_LIGHTNING_TENDRILS);
DoCast(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL);
me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING);
me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 435);
events.DelayEvents(34000);
events.ScheduleEvent(EVENT_FLIGHT, 2500);
events.ScheduleEvent(EVENT_ENDFLIGHT, 28000);
events.ScheduleEvent(EVENT_LIGHTNING_TENDRILS, 90000);
break;
case EVENT_FLIGHT:
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0))
me->GetMotionMaster()->MovePoint(0, pTarget->GetPositionX(), pTarget->GetPositionY(), 435);
events.ScheduleEvent(EVENT_FLIGHT, 6000);
break;
case EVENT_ENDFLIGHT:
me->GetMotionMaster()->MovePoint(0, 1586.920f, 119.849f, 435);
events.CancelEvent(EVENT_FLIGHT);
events.ScheduleEvent(EVENT_LAND, 4000);
break;
case EVENT_LAND:
me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 427.28f);
events.ScheduleEvent(EVENT_GROUND, 1500);
break;
case EVENT_GROUND:
me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS);
me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL);
me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING);
me->SendMovementFlagUpdate();
break;
}
}
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_BRUNDIR:
me->SetFullHealth();
me->AddAura(SPELL_SUPERCHARGE, me);
++phase;
events.SetPhase(phase);
events.RescheduleEvent(EVENT_CHAIN_LIGHTNING, urand(6000, 12000));
events.RescheduleEvent(EVENT_OVERLOAD, 40000);
if (phase >= 2)
events.RescheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000));
if (phase >= 3)
{
me->AddAura(SPELL_STORMSHIELD, me);
events.RescheduleEvent(EVENT_LIGHTNING_TENDRILS, 60000);
me->AddLootMode(LOOT_MODE_HARD_MODE_1);
}
break;
}
}
void MovePos()
{
switch(Position)
{
case 0:
me->GetMotionMaster()->MovePoint(0, 1587.28f, 97.030f, 427.28f);
break;
case 1:
me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f);
break;
case 2:
me->GetMotionMaster()->MovePoint(0, 1587.34f, 142.58f, 427.28f);
break;
case 3:
me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f);
break;
}
Position++;
if (Position > 3)
{
Position = 0;
}
}
};
};
void AddSC_boss_assembly_of_iron()
{
new boss_steelbreaker();
new boss_runemaster_molgeim();
new boss_stormcaller_brundir();
new npc_lightning_elemental();
new npc_rune_of_summoning();
new npc_rune_of_power();
}
| proofrepo/MadboxpcWOW_3.0 | src/server/scripts/Northrend/Ulduar/ulduar/boss_assembly_of_iron.cpp | C++ | gpl-2.0 | 30,497 |
/**
* @file
* @author Witek902 (witek902@gmail.com)
*/
#include "PCH.hpp"
#include "Event_Input.hpp"
#include "Engine/Common/Reflection/ReflectionClassDefine.hpp"
NFE_DEFINE_POLYMORPHIC_CLASS(NFE::Scene::Event_Input)
NFE_CLASS_PARENT(NFE::Scene::Event)
NFE_END_DEFINE_CLASS()
namespace NFE {
namespace Scene {
Event_Input::Event_Input(const Input::EventData& data)
: mData(data)
{
}
} // namespace Scene
} // namespace NFE
| nfprojects/nfengine | Src/Engine/Core/Scene/Events/Event_Input.cpp | C++ | gpl-2.0 | 441 |
//
// GPActionDeclFloat.cs
//
// Author(s):
// Baptiste Dupy <baptiste.dupy@gmail.com>
//
// Copyright (c) 2014
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace ActionTool
{
[GPActionNoInput]
[GPActionAlias("Variable/Float/Declaration")]
public class GPActionDeclFloat : GPActionVariable
{
#region Public Members
public float _value;
#endregion
#region GPActionVariable Override
public override object GetValue ()
{
return _value;
}
public override void SetValue(System.Object value)
{
_value = (float) value;
}
#endregion
}
}
| trfd/Unity-ActionTool | Actions/Variables/Decl/GPActionDeclFloat.cs | C# | gpl-2.0 | 1,729 |
//$(document).ready(function() {
/* Range Slider Function */
(function($) {
$.fn.rkmd_rangeSlider = function() {
var self, slider_width, slider_offset, curnt, sliderContinuous, sliderDiscrete, range, slider;
self = $(this);
slider_width = self.outerWidth();
slider_offset = self.offset().left;
sliderContinuous = $('.slider-continuous');
sliderDiscrete = $('.slider-discrete');
if(self.hasClass('slider-continuous') === true) {
sliderContinuous.each(function(i, v) {
curnt = $(this);
curnt.append(sliderContinuous_tmplt());
range = curnt.find('input[type="range"]');
slider = curnt.find('.slider');
slider_fill = slider.find('.slider-fill');
slider_handle = slider.find('.slider-handle');
var range_val = range.val();
slider_fill.css('width', range_val +'%');
slider_handle.css('left', range_val +'%');
});
}
if(self.hasClass('slider-discrete') === true) {
sliderDiscrete.each(function(i, v) {
curnt = $(this);
curnt.append(sliderDiscrete_tmplt());
range = curnt.find('input[type="range"]');
slider = curnt.find('.slider');
slider_fill = slider.find('.slider-fill');
slider_handle = slider.find('.slider-handle');
slider_label = slider.find('.slider-label');
var range_val = parseInt(range.val());
slider_fill.css('width', range_val +'%');
slider_handle.css('left', range_val +'%');
slider_label.find('span').text(range_val);
});
}
self.on('mousedown', '.slider-handle', function(e) {
if(e.button === 2) {
return false;
}
var parents = $(this).parents('.rkmd-slider');
var slider_width = parents.outerWidth();
var slider_offset = parents.offset().left;
var check_range = parents.find('input[type="range"]').is(':disabled');
if(check_range === true) {
return false;
}
if(parents.hasClass('slider-discrete') === true) {
$(this).addClass('is-active');
}
var handlers = {
mousemove: function(e) {
var slider_new_width = e.pageX - slider_offset;
if(slider_new_width <= slider_width && !(slider_new_width < '0')) {
slider_move(parents, slider_new_width, slider_width);
}
},
mouseup: function(e) {
$(this).off(handlers);
if(parents.hasClass('slider-discrete') === true) {
parents.find('.is-active').removeClass('is-active');
}
}
};
$(document).on(handlers);
});
self.on('mousedown', '.slider', function(e) {
if(e.button === 2) {
return false;
}
var parents = $(this).parents('.rkmd-slider');
var slider_width = parents.outerWidth();
var slider_offset = parents.offset().left;
var check_range = parents.find('input[type="range"]').is(':disabled');
if(check_range === true) {
return false;
}
var slider_new_width = e.pageX - slider_offset;
if(slider_new_width <= slider_width && !(slider_new_width < '0')) {
slider_move(parents, slider_new_width, slider_width);
}
var handlers = {
mouseup: function(e) {
$(this).off(handlers);
}
};
$(document).on(handlers);
});
};
function sliderContinuous_tmplt() {
var tmplt = '<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"></div>' +
'</div>';
return tmplt;
}
function sliderDiscrete_tmplt() {
var tmplt = '<div class="slider">' +
'<div class="slider-fill"></div>' +
'<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>' +
'</div>';
return tmplt;
}
function slider_move(parents, newW, sliderW) {
var slider_new_val = parseInt(Math.round(newW / sliderW * 100));
var slider_fill = parents.find('.slider-fill');
var slider_handle = parents.find('.slider-handle');
var range = parents.find('input[type="range"]');
slider_fill.css('width', slider_new_val +'%');
slider_handle.css({
'left': slider_new_val +'%',
'transition': 'none',
'-webkit-transition': 'none',
'-moz-transition': 'none'
});
range.val(slider_new_val);
if(parents.hasClass('slider-discrete') === true) {
parents.find('.slider-handle span').text(slider_new_val);
}
}
}(jQuery));
/* Change Slider Color */
function change_slider_color() {
$('.color-box .show-box').on('click', function() {
$(".color-box").toggleClass("open");
});
$('.colors-list a').on('click', function() {
var curr_color = $('main').data('slider-color');
var color = $(this).data('slider-color');
var new_colot = 'slider-' + color;
$('.rkmd-slider').each(function(i, v) {
var findColor = $(this).hasClass(curr_color);
if(findColor) {
$(this).removeClass(curr_color);
$(this).addClass(new_colot);
}
$('main').data('slider-color', new_colot);
});
});
}
$('.rkmd-slider').rkmd_rangeSlider();
//window.setInterval(function(){
//$('.rkmd-slider').rkmd_rangeSlider();
//change_slider_color();
//console.log("range.js ran");
//}, 5000);
//});
| johnfrancisgit/Chromaticity | js/range.js | JavaScript | gpl-2.0 | 5,426 |
/*
* Copyright (C) 2002-2015 XimpleWare, info@ximpleware.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.
*/
/*VTD-XML is protected by US patent 7133857, 7260652, an 7761459*/
package com.ximpleware.extended;
/**
* This class iterates through all text nodes of an element.
* VTDNavHuge has getText() which is inadequate for mixed content style of XML.
* text nodes include character_data and CDATA.
* This version is adapted to support extended VTD (256GB max file size)
*/
public class TextIterHuge {
private int prevLocation; //previous location of text node
protected int depth;
protected int index; // this is index for the element
protected VTDNavHuge vn;
private int lcIndex;
private int lcLower;
private int lcUpper;
/**
* TextIter constructor comment.
*/
public TextIterHuge() {
super();
vn = null;
/*sel_char_data = true;
sel_comment = true;
sel_cdata = true;*/
}
/**
* Get the index vals for the text nodes in document order.
* Creation date: (12/5/03 6:11:50 PM)
* @return int (-1 if no more left)
*/
public int getNext() {
if (vn == null)
throw new IllegalArgumentException(" VTDNav instance can't be null");
int vtdSize = vn.vtdBuffer.size();
switch (depth) {
case -1: return -1;
case 0 :
// scan forward, if none found, jump to level 1 element and scan backward until one is found
// if there isn't a level-one element, jump to the end of vtd buffer and scan backward
int sp = (prevLocation != -1) ? increment(prevLocation): index + 1;
if (vn.l1Buffer.size() != 0) {
int temp1 = vn.l1Buffer.upper32At(0);
int temp2 = vn.l1Buffer.upper32At(vn.l1Buffer.size() - 1);
lcIndex = (lcIndex != -1) ? lcIndex : 0;
while (sp < vtdSize) {
if (sp >= temp1 && sp < temp2) {
int s = vn.l1Buffer.upper32At(lcIndex);
if (sp == s) { // get to the next l1 element then do a rewind
lcIndex++;
sp = vn.l1Buffer.upper32At(lcIndex)-1;
while (vn.getTokenDepth(sp) == 0
&& vn.getTokenType(sp) != VTDNavHuge.TOKEN_STARTING_TAG) { //probe depth in here
sp--;
}
sp++; // point to the first possible node
}
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
} else {
if (sp == temp2) { // get to the end of the document and do a rewind
sp = vn.vtdBuffer.size() - 1;
while (vn.getTokenDepth(sp) <= 0) {
sp--;
}
sp++;
//continue;
}
if (sp>=vtdSize)
return -1;
else if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
else if (vn.getTokenDepth(sp)>1) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
// found nothing
} else {
// no child element for root, just scan right forward
while (sp < vtdSize) {
if (isText(sp) == true && vn.getTokenDepth(sp)==0) {
prevLocation = sp;
return sp;
}
sp++;
}
return -1;
}
case 1 :
if (prevLocation != -1) {
sp = increment(prevLocation) ;
} else {
// fetch lclower and lcupper
lcLower = vn.l1Buffer.lower32At(vn.l1index);
if (lcLower != -1) {
lcUpper = vn.l2Buffer.size() - 1;
int size = vn.l1Buffer.size();
for (int i = vn.l1index + 1; i < size ; i++) {
int temp = vn.l1Buffer.lower32At(i);
if (temp != 0xffffffff) {
lcUpper = temp - 1;
break;
}
}
}
sp = index + 1;
} // check for l2lower and l2upper
if (lcLower != -1) { // have at least one child element
int temp1 = vn.l2Buffer.upper32At(lcLower);
int temp2 = vn.l2Buffer.upper32At(lcUpper);
lcIndex = (lcIndex != -1) ? lcIndex : lcLower;
while (sp < vtdSize) {
int s = vn.l2Buffer.upper32At(lcIndex);
if (sp >= temp1 && sp < temp2) {
if (sp == s) {
lcIndex++;
sp = vn.l2Buffer.upper32At(lcIndex) - 1;
while (vn.getTokenDepth(sp) == 1) {
sp--;
}
sp++;
//continue;
}
if (isText(sp) == true && vn.getTokenDepth(sp)==1 ) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true) {
prevLocation = sp;
return sp;
}
sp++;
} else {
//if (sp == temp2) { // last child element
//} else
if (isText(sp) == true && vn.getTokenDepth(sp) == 1){
//System.out.println("depth ->"+vn.getTokenDepth(sp));
prevLocation = sp;
return sp;
} else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG
&& vn.getTokenDepth(sp) < 2 ) || vn.getTokenDepth(sp)<1) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
} else { // no child element
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (sp < vtdSize
&& d >= 1
&& !(d == 1 && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
if (isText(sp) == true) {
prevLocation = sp;
return sp;
}
sp++;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
//prevLocation = vtdSize-1;
return -1;
}
case 2 :
if (prevLocation != -1) {
sp = increment(prevLocation);
} else {
// fetch lclower and lcupper
lcLower = vn.l2Buffer.lower32At(vn.l2index);
if (lcLower != -1) {
lcUpper = vn.l3Buffer.size() - 1;
int size = vn.l2Buffer.size();
for (int i = vn.l2index + 1; i < size ; i++) {
int temp = vn.l2Buffer.lower32At(i);
if (temp != 0xffffffff) {
lcUpper = temp - 1;
break;
}
}
}
sp = index + 1;
} // check for l3lower and l3upper
if (lcLower != -1) { // at least one child element
int temp1 = vn.l3Buffer.intAt(lcLower);
int temp2 = vn.l3Buffer.intAt(lcUpper);
lcIndex = (lcIndex != -1) ? lcIndex : lcLower;
while (sp < vtdSize) {
int s = vn.l3Buffer.intAt(lcIndex);
//int s = vn.l2Buffer.upper32At(lcIndex);
if (sp >= temp1 && sp < temp2) {
if (sp == s) {
lcIndex++;
sp = vn.l3Buffer.intAt(lcIndex) - 1;
while (vn.getTokenDepth(sp) == 2) {
sp--;
}
sp++;
//continue;
}
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
} else if (sp < temp1) {
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
} else {
//if (sp == temp2) { // last child element
//} else
if ( isText(sp) == true && vn.getTokenDepth(sp) == 2) {
prevLocation = sp;
return sp;
} else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG
&& vn.getTokenDepth(sp) < 3 ) || vn.getTokenDepth(sp)<2) {
break;
}
sp++;
}
}
//prevLocation = vtdSize-1;
return -1;
} else { // no child elements
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (sp < vtdSize
&& d >= 2
&& !(d == 2 && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
// the last condition indicates the start of the next sibling element
if (isText(sp) == true && vn.getTokenDepth(sp)==2) {
prevLocation = sp;
return sp;
}
sp++;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
//prevLocation = vtdSize-1;
return -1;
}
default :
//int curDepth = vn.context[0];
sp = (prevLocation != -1) ? increment(prevLocation): index + 1;
if (sp>=vtdSize) return -1;
int d = vn.getTokenDepth(sp);
int type = vn.getTokenType(sp);
while (d >= depth
&& !(d == depth && type == VTDNavHuge.TOKEN_STARTING_TAG)) {
if (isText(sp) == true && d == depth) {
prevLocation = sp;
return sp;
}
sp++;
if(sp >= vtdSize)
return -1;
d = vn.getTokenDepth(sp);
type = vn.getTokenType(sp);
}
}
//prevLocation = vtdSize-1;
return -1;
}
/**
* Test whether a give token type is a TEXT.
* Creation date: (12/11/03 3:46:10 PM)
* @return boolean
* @param type int
*/
final private boolean isText(int index) {
int type = vn.getTokenType(index);
return (type == VTDNavHuge.TOKEN_CHARACTER_DATA
//|| type == vn.TOKEN_COMMENT
|| type == VTDNavHuge.TOKEN_CDATA_VAL);
}
/**
* Obtain the current navigation position and element info from VTDNav.
* So one can instantiate it once and use it for many different elements
* Creation date: (12/5/03 6:20:44 PM)
* @param v com.ximpleware.VTDNav
*/
public void touch(VTDNavHuge v) {
if (v == null)
throw new IllegalArgumentException(" VTDNav instance can't be null");
depth = v.context[0];
if (depth == -1)
index = 0;
else
index = (depth != 0) ? v.context[depth] : v.rootIndex;
vn = v;
prevLocation = -1;
lcIndex = -1;
lcUpper = -1;
lcLower = -1;
}
private int increment(int sp){
int type = vn.getTokenType(sp);
int vtdSize = vn.vtdBuffer.size();
int i=sp+1;
while(i<vtdSize &&
depth == vn.getTokenDepth(i) &&
type == vn.getTokenType(i)&&
(vn.getTokenOffset(i-1)+ (int)((vn.vtdBuffer.longAt(i-1) & VTDNavHuge.MASK_TOKEN_FULL_LEN)>>32)
== vn.getTokenOffset(i))
){
i++;
}
return i;
}
}
| CoolBalance/vtd-xml | src/main/java/com/ximpleware/extended/TextIterHuge.java | Java | gpl-2.0 | 14,440 |
<?php
include_once('admin/class-emma-settings.php');
include_once('widget/class-widget.php');
include_once('shortcode/class-shortcode.php');
include_once('class-emma-api.php');
include_once('class-form.php');
/**
* Main Class for the Emma Emarketing Plugin
*
* long desc
* @package Emma_Emarketing
* @author ah so
* @version 1.0
* @abstract
* @copyright 2012
*/
class Emma_Emarketing {
/*
* the constructor
* Fired during plugins_loaded (very very early),
* only actions and filters,
*
*/
function __construct() {
$emma_settings = new Emma_Settings();
// Add shortcode support for widgets
add_filter('widget_text', 'do_shortcode');
}
} // end Class Emma_Emarketing
| samanthavandapuye/tease | wp-content/plugins/emma-emarketing-plugin/class-emma-emarketing.php | PHP | gpl-2.0 | 737 |
package com.numhero.client.mvp.document;
import com.google.gwt.resources.client.ResourcePrototype;
import com.google.gwt.core.client.GWT;
public class com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator implements com.numhero.client.mvp.document.InvoicePanel_InvoiceUiBinderImpl_GenBundle {
public ResourcePrototype[] getResources() {
return new ResourcePrototype[] {
};
}
public native ResourcePrototype getResource(String name) /*-{
switch (name) {
}
return null;
}-*/;
}
| midaboghetich/netnumero | gen/com/numhero/client/mvp/document/com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator.java | Java | gpl-2.0 | 561 |
<?php global $user; ?>
<article<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php if (!$page && $title): ?>
<header>
<h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2>
</header>
<?php endif; ?>
<?php print render($title_suffix); ?>
<div<?php print $content_attributes; ?>>
<div class="row">
<div class="col-sm-6">
<div class="panel panel-notitle">
<div class="panel-body">
<?php print render($content['stato_bene']); ?>
<div class="row">
<div class="col-sm-4">
<?php print render($content['field_fotografia']) ?>
</div>
<div class="col-sm-8">
<div class="profile-title">
<h1><?php print $title ; ?></h1>
</div>
<div class="row">
<div class="col-sm-12">
<?php
print render($content['field_tipologia']);
print render($content['field_progetto_collegato']);
print render($content['og_group_ref']);
?>
</div>
</div>
</div>
</div>
</div>
<?php if(count(array_intersect(array('redazione', 'administrator'), array_values($user->roles))) > 0): ?>
<div class="panel-footer">
<h3>Azioni redazione</h3>
<div class="action-links">
<?php print l('Aggiungi patto di collaborazione', 'node/add/patto-di-collaborazione', array('query' => array('field_contenuto_collegato' => $node->nid))); ?>
</div>
</div>
<?php endif; ?>
</div>
<?php if(isset($content['body'])): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Descrizione'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['body']); ?>
</div>
</div>
<?php endif; ?>
<?php if(isset($content['field_motivazione_bene'])): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Motivazione dell\'individuazione come Bene Comune'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['field_motivazione_bene']); ?>
</div>
</div>
<?php endif; ?>
</div>
<div class="col-sm-6">
<?php
print render($content['field_geo']);
?>
<?php
$view = views_get_view('patti_di_collaborazione');
$view->set_display('block');
$view->set_arguments(array($node->nid));
$view->pre_execute();
$view->execute();
if (!empty($view->result)) :
?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print $view->get_title() ?></h2>
</div>
<div class="panel-body">
<?php print $view->preview(); ?>
</div>
</div>
<?php endif; $view->destroy();?>
<?php if(!empty($field_link_a_risorse_online_di_i)): ?>
<div class="panel">
<div class="panel-heading">
<h2 class="panel-title"><?php print t('Link a risorse online di interesse specifico'); ?></h2>
</div>
<div class="panel-body">
<?php print render($content['field_link_a_risorse_online_di_i']); ?>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</article> | ComuneBologna/comunita | sites/comunita/themes/comunita_theme/templates/node--bene-comune.tpl.php | PHP | gpl-2.0 | 3,768 |
<?php
/*
Simple class to let themes add dependencies on plugins in ways they might find useful
Example usage:
$test = new Theme_Plugin_Dependency( 'simple-facebook-connect', 'http://ottopress.com/wordpress-plugins/simple-facebook-connect/' );
if ( $test->check_active() )
echo 'SFC is installed and activated!';
else if ( $test->check() )
echo 'SFC is installed, but not activated. <a href="'.$test->activate_link().'">Click here to activate the plugin.</a>';
else if ( $install_link = $test->install_link() )
echo 'SFC is not installed. <a href="'.$install_link.'">Click here to install the plugin.</a>';
else
echo 'SFC is not installed and could not be found in the Plugin Directory. Please install this plugin manually.';
*/
if (!class_exists('Theme_Plugin_Dependency')) {
class Theme_Plugin_Dependency {
// input information from the theme
var $slug;
var $uri;
// installed plugins and uris of them
private $plugins; // holds the list of plugins and their info
private $uris; // holds just the URIs for quick and easy searching
// both slug and PluginURI are required for checking things
function __construct( $slug, $uri ) {
$this->slug = $slug;
$this->uri = $uri;
if ( empty( $this->plugins ) )
$this->plugins = get_plugins();
if ( empty( $this->uris ) )
$this->uris = wp_list_pluck($this->plugins, 'PluginURI');
// echo '<pre>';
// print_r($this->uris);
// echo '</pre>';
}
// return true if installed, false if not
function check() {
return in_array($this->uri, $this->uris);
}
// return true if installed and activated, false if not
function check_active() {
$plugin_file = $this->get_plugin_file();
if ($plugin_file) return is_plugin_active($plugin_file);
return false;
}
// gives a link to activate the plugin
function activate_link() {
$plugin_file = $this->get_plugin_file();
if ($plugin_file) return wp_nonce_url(self_admin_url('plugins.php?action=activate&plugin='.$plugin_file), 'activate-plugin_'.$plugin_file);
return false;
}
// return a nonced installation link for the plugin. checks wordpress.org to make sure it's there first.
function install_link() {
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
$info = plugins_api('plugin_information', array('slug' => $this->slug ));
if ( is_wp_error( $info ) )
return false; // plugin not available from wordpress.org
return wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=' . $this->slug), 'install-plugin_' . $this->slug);
}
// return array key of plugin if installed, false if not, private because this isn't needed for themes, generally
private function get_plugin_file() {
return array_search($this->uri, $this->uris);
}
}
}
/**
+ * options "Add scripts to head" and "add scripts to footer"
+ *
+ * @package X2
+ * @since 1.5
+ */
// add to head function - hooks the stuff to bp_head
function x2_cap_add_to_head() {
global $cap;
echo $cap->add_to_head;
}
add_action('bp_head', 'x2_cap_add_to_head', 20);
// add to footer function - hooks the stuff to wp_footer
function x2_cap_add_to_footer() {
global $cap;
echo $cap->add_to_footer;
}
add_action('wp_footer', 'x2_cap_add_to_footer', 20);
function back_to_top(){
global $cap;
//if($cap->menu_waypoints == true) {
?>
<footer>
<nav>
<ul>
<li><a class="top" href="#" title="Back to top">Top</a></li>
</ul>
</nav>
</footer>
<?php }
//}
function waypoints_js(){
global $cap;
if($cap->menu_waypoints == true) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.top').addClass('hidden');
jQuery.waypoints.settings.scrollThrottle = 300;
jQuery('#outerrim').waypoint(function(event, direction) {
jQuery('.top').toggleClass('hidden', direction === "up");
}, {
offset: '-100%'
}).find('#access').waypoint(function(event, direction) {
jQuery('#access').toggleClass('sticky', direction === "down");
if(direction == 'up'){
jQuery('#nav-logo').animate({ opacity: 1},0, function() {
jQuery(this).hide('200');
});
jQuery(".wrapcheck").removeClass("inner");
}
if(direction == 'down'){
jQuery('#nav-logo').animate({ opacity: 1},0, function() {
jQuery(this).show('200');
});
jQuery(".wrapcheck").addClass("inner");
}
event.stopPropagation();
});
});
</script>
<?php
} else { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.top').addClass('hidden');
jQuery.waypoints.settings.scrollThrottle = 300;
jQuery('#outerrim').waypoint(function(event, direction) {
jQuery('.top').toggleClass('hidden', direction === "up");
}, {
offset: '-100%'
})
});
</script>
<?php
}
}
// this function adds the needed class "icon-white" if color scheme is dark or black..
function white_icon_class() {
if ( x2_get_color_scheme() == 'dark' || x2_get_color_scheme() == 'black' ) {
echo 'icon-white';
}
}
function add_home_to_nav(){ ?>
<div id="nav-logo">
<ul>
<li id="nav-home"<?php if ( is_home() ) : ?> class="page_item current-menu-item"<?php endif; ?>>
<a href="<?php echo site_url() ?>" title="<?php _e( 'Home', 'x2' ) ?>"><i class="icon-home <?php white_icon_class() ?>"></i></a>
</li>
</ul>
</div>
<?php }
// opens the inner wrap in the top menu - if needed
function open_inner_wrap_in_menu_top() {
global $cap;
if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true )
echo "<div class=\"inner\">";
}
// closes the inner wrap in the top menu - if needed
function close_inner_wrap_in_menu_top() {
global $cap;
if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true )
echo "</div>";
}
// the flying widget!
function out_of_site_widget(){
global $cap;
if($cap->out_of_content_widget == false) { ?>
<script>
var name = "#out_of_site_widget";
var menuYloc = null;
jQuery(document).ready(function(){
menuYloc = parseInt(jQuery(name).css("top").substring(0,jQuery(name).css("top").indexOf("px")))
jQuery(window).scroll(function () {
offset = menuYloc+jQuery(document).scrollTop()+"px";
jQuery(name).animate({top:offset},{duration:1000,queue:false});
});
});
</script>
<?php } ?>
<div id="out_of_site_widget" class=".visible-desktop">
<?php dynamic_sidebar( 'out_of_content' )?>
</div>
<?php }
// body badge function, if the option is set
function body_badge(){
global $cap;
if ( $cap->body_badge_show != "hide" ) {
// add a link around if a url is set
if ( $cap->body_badge_link != "" ) {
?><a class="body_badge_link" href="<?php echo $cap->body_badge_link; ?>"><?php
}
// only the badge body will be added anyway
?><div class="badge_body"><?php
// add the text only if something != "just my image" is set
if ( $cap->body_badge_show != "just my image" ) {
?><div class="badge_text"><?php echo $cap->body_badge_text; ?></div><?php
}
// close the badge body anyway
?></div><?php
// close the link around if a url was set
if ( $cap->body_badge_link != "" ) {
?></a><?php
}
}
}
function get_the_post_thumbnail_src($img)
{
return (preg_match('~\bsrc="([^"]++)"~', $img, $matches)) ? $matches[1] : '';
}
/**
* check if it's a child theme or parent theme and return the correct path
*
* @package x2
* @since 1.0
*/
function x2_require_path($path){
x2::require_path($path);
}
/**
* get the right img for the slideshow shadow
*
* @package x2
* @since 1.0
*/
function x2_slider_shadow() {
global $cap;
if ($cap->slideshow_shadow == "shadow") {
return "slider-shadow.png";
} else {
return "slider-shadow-sharp.png";
}
}
/**
* define new excerpt length
*
* @package x2
* @since 1.0
*/
function x2_excerpt_length() {
global $cap;
$excerpt_length = 30;
if($cap->excerpt_length){
$excerpt_length = $cap->excerpt_length;
}
return $excerpt_length;
}
/**
* change the profile tab order
*
* @package x2
* @since 1.0
*/
add_action( 'bp_init', 'x2_change_profile_tab_order' );
function x2_change_profile_tab_order() {
global $bp, $cap;
if($cap->bp_profiles_nav_order == ''){
$cap->bp_default_navigation = true;
return;
}
$order = $cap->bp_profiles_nav_order;
$order = str_replace(' ','',trim($order));
$order = explode(",", $order);
$i = 1;
$bp->bp_nav = x2_filter_custom_menu($bp->bp_nav, $order);
foreach($order as $item) {
// check this such component actually exists
if(!bp_is_active($item)){
continue;
}
$bp->bp_nav[$item]['position'] = $i;
$i ++;
}
}
/**
* change the groups tab order
*
* @package x2
* @since 1.0
*/
add_action('bp_init', 'x2_change_groups_tab_order');
function x2_change_groups_tab_order() {
global $bp, $cap;
// In BP 1.3, bp_options_nav for groups is keyed by group slug instead of by 'groups', to
// differentiate it from the top-level groups directories and the groups subtab of member
// profiles
$group_slug = isset( $bp->groups->current_group->slug ) ? $bp->groups->current_group->slug : false;
if($cap->bp_groups_nav_order == ''){
$cap->bp_default_navigation = true;
return;
}
$order = $cap->bp_groups_nav_order;
$order = str_replace(' ','',$order);
$order = explode(",", $order);
$i = 1;
$bp->bp_options_nav[$group_slug] = x2_filter_custom_menu($bp->bp_options_nav[$group_slug], $order);
if(!empty($bp->bp_options_nav[$group_slug])){
foreach($order as $item) {
if(!array_key_exists($item, $bp->bp_options_nav[$group_slug])){
continue;
}
$bp->bp_options_nav[$group_slug][$item]['position'] = $i;
$i ++;
}
}
}
/**
* Remove menu items wihich not included to custom list
* @param array $menu default menu
* @param array $custom_items list of items
* @return array new menu items
*/
function x2_filter_custom_menu($menu, $custom_items){
if(is_array($custom_items) && is_array($menu)){
return array_intersect_key($menu, array_flip($custom_items));
}
return $menu;
}
/**
* This function here defines the defaults for the main theme colors - if no other specific color is set ;)
* It's used only one time - in the beginning of style.php.
*
* @package x2
* @since 0.1
*/
function x2_switch_css(){
global $cap;
if(isset( $_GET['show_style']))
$cap->style_css = $_GET['show_style'];
switch ($cap->style_css){
case 'dark':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = '393939';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = '393939';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '232323';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = '282828';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '333333';
if( $cap->font_color == '' ) $cap->font_color = 'aaaaaa';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '777777';
if( $cap->link_color == '' ) $cap->link_color = 'b7c366';
break;
case 'white':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'ffffff';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'ffffff';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'e3e3e3';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'f1f1f1';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f9f9f9';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '6ba090';
break;
case 'black':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = '040404';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = '040404';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '222222';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = '121212';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '181818';
if( $cap->font_color == '' ) $cap->font_color = '696969';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '444444';
if( $cap->link_color == '' ) $cap->link_color = '2b9c83';
break;
case 'light':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '74a4a3';
break;
case 'natural':
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'e9e6d8';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'e9e6d8';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'cec7ab';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'dcd6bd';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'e3dec8';
if( $cap->font_color == '' ) $cap->font_color = '79735d';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = '999177';
if( $cap->link_color == '' ) $cap->link_color = 'c3874a';
break;
default:
if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9';
if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9';
if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede';
if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7';
if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1';
if( $cap->font_color == '' ) $cap->font_color = '777777';
if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa';
if( $cap->link_color == '' ) $cap->link_color = '74a4a3';
break;
}
return TRUE;
}
/**
* find out the right color scheme and create the array of css elements with the hex codes
*
* @package x2
* @since 1.0
*/
function x2_color_scheme(){
echo x2_get_color_scheme();
}
function x2_get_color_scheme(){
global $cap;
if(isset( $_GET['show_style']))
$cap->style_css = $_GET['show_style'];
switch ($cap->style_css){
case 'dark':
$color = 'dark';
break;
case 'light':
$color = 'light';
break;
case 'white':
$color = 'white';
break;
case 'black':
$color = 'black';
break;
case 'natural':
$color = 'natural';
break;
default:
$color = 'white';
break;
}
return $color;
}
function x2_the_loop( $template, $tk_query_id, $show_pagination){
switch ($template) {
case 'default':
get_template_part( 'loop-default' );
break;
case 'bubble':
get_template_part( 'loop-bubbles' );
break;
case 'image_caption':
get_template_part( 'loop-featured-image-caption' );
break;
default:
if(function_exists('tk_loop_designer_the_loop')){
tk_loop_designer_the_loop( $template, $tk_query_id, $show_pagination );
} else {
get_template_part( 'loop-default' );
}
break;
}
}
?> | jubjunior/Wordpress | wp-content/themes/x2/core/includes/helper-functions.php | PHP | gpl-2.0 | 16,806 |
<?php get_header(); ?>
<?php
$options = get_option('sf_dante_options');
$default_show_page_heading = $options['default_show_page_heading'];
$default_page_heading_bg_alt = $options['default_page_heading_bg_alt'];
$default_sidebar_config = $options['default_sidebar_config'];
$default_left_sidebar = $options['default_left_sidebar'];
$default_right_sidebar = $options['default_right_sidebar'];
$pb_active = get_post_meta($post->ID, '_spb_js_status', true);
$show_page_title = get_post_meta($post->ID, 'sf_page_title', true);
$page_title_style = get_post_meta($post->ID, 'sf_page_title_style', true);
$page_title = get_post_meta($post->ID, 'sf_page_title_one', true);
$page_subtitle = get_post_meta($post->ID, 'sf_page_subtitle', true);
$page_title_bg = get_post_meta($post->ID, 'sf_page_title_bg', true);
$fancy_title_image = rwmb_meta('sf_page_title_image', 'type=image&size=full');
$page_title_text_style = get_post_meta($post->ID, 'sf_page_title_text_style', true);
$fancy_title_image_url = "";
if ($show_page_title == "") {
$show_page_title = $default_show_page_heading;
}
if ($page_title_bg == "") {
$page_title_bg = $default_page_heading_bg_alt;
}
if ($page_title == "") {
$page_title = get_the_title();
}
foreach ($fancy_title_image as $detail_image) {
$fancy_title_image_url = $detail_image['url'];
break;
}
if (!$fancy_title_image) {
$fancy_title_image = get_post_thumbnail_id();
$fancy_title_image_url = wp_get_attachment_url( $fancy_title_image, 'full' );
}
$sidebar_config = get_post_meta($post->ID, 'sf_sidebar_config', true);
$left_sidebar = get_post_meta($post->ID, 'sf_left_sidebar', true);
$right_sidebar = get_post_meta($post->ID, 'sf_right_sidebar', true);
if ($sidebar_config == "") {
$sidebar_config = $default_sidebar_config;
}
if ($left_sidebar == "") {
$left_sidebar = $default_left_sidebar;
}
if ($right_sidebar == "") {
$right_sidebar = $default_right_sidebar;
}
sf_set_sidebar_global($sidebar_config);
$page_wrap_class = $post_class_extra = '';
if ($sidebar_config == "left-sidebar") {
$page_wrap_class = 'has-left-sidebar has-one-sidebar row';
$post_class_extra = 'col-sm-8';
} else if ($sidebar_config == "right-sidebar") {
$page_wrap_class = 'has-right-sidebar has-one-sidebar row';
$post_class_extra = 'col-sm-8';
} else if ($sidebar_config == "both-sidebars") {
$page_wrap_class = 'has-both-sidebars row';
$post_class_extra = 'col-sm-9';
} else {
$page_wrap_class = 'has-no-sidebar';
}
$remove_breadcrumbs = get_post_meta($post->ID, 'sf_no_breadcrumbs', true);
$remove_bottom_spacing = get_post_meta($post->ID, 'sf_no_bottom_spacing', true);
$remove_top_spacing = get_post_meta($post->ID, 'sf_no_top_spacing', true);
if ($remove_bottom_spacing) {
$page_wrap_class .= ' no-bottom-spacing';
}
if ($remove_top_spacing) {
$page_wrap_class .= ' no-top-spacing';
}
$options = get_option('sf_dante_options');
$disable_pagecomments = false;
if (isset($options['disable_pagecomments']) && $options['disable_pagecomments'] == 1) {
$disable_pagecomments = true;
}
?>
<?php if ($show_page_title) { ?>
<div class="container">
<div class="row">
<?php if ($page_title_style == "fancy") { ?>
<?php if ($fancy_title_image_url != "") { ?>
<div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_text_style; ?>-style fancy-image" style="background-image: url(<?php echo $fancy_title_image_url; ?>);">
<?php } else { ?>
<div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>">
<?php } ?>
<div class="heading-text">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
<?php if ($page_subtitle) { ?>
<h3><?php echo $page_subtitle; ?></h3>
<?php } ?>
</div>
</div>
<?php } else { ?>
<div class="page-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>">
<div class="heading-text">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
</div>
<?php
// BREADCRUMBS
if (!$remove_breadcrumbs) {
echo sf_breadcrumbs();
}
?>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?>
<div class="container">
<?php } ?>
<div class="inner-page-wrap <?php echo $page_wrap_class; ?> clearfix">
<?php if (have_posts()) : the_post(); ?>
<!-- OPEN page -->
<div <?php post_class('clearfix ' . $post_class_extra); ?> id="<?php the_ID(); ?>">
<?php if ($sidebar_config == "both-sidebars") { ?>
<div class="row">
<div class="page-content col-sm-8">
<?php the_content(); ?>
<div class="link-pages"><?php wp_link_pages(); ?></div>
<?php if ( comments_open() && !$disable_pagecomments ) { ?>
<div id="comment-area">
<?php comments_template('', true); ?>
</div>
<?php } ?>
</div>
<aside class="sidebar left-sidebar col-sm-4">
<?php dynamic_sidebar($left_sidebar); ?>
</aside>
</div>
<?php } else { ?>
<div class="page-content clearfix">
<?php the_content(); ?>
<div class="link-pages"><?php wp_link_pages(); ?></div>
<?php if ( comments_open() && !$disable_pagecomments ) { ?>
<?php if ($sidebar_config == "no-sidebars" && $pb_active == "true") { ?>
<div id="comment-area" class="container">
<?php } else { ?>
<div id="comment-area">
<?php } ?>
<?php comments_template('', true); ?>
</div>
<?php } ?>
</div>
<?php } ?>
<!-- CLOSE page -->
</div>
<?php endif; ?>
<?php if ($sidebar_config == "left-sidebar") { ?>
<aside class="sidebar left-sidebar col-sm-4">
<?php dynamic_sidebar($left_sidebar); ?>
</aside>
<?php } else if ($sidebar_config == "right-sidebar") { ?>
<aside class="sidebar right-sidebar col-sm-4">
<?php dynamic_sidebar($right_sidebar); ?>
</aside>
<?php } else if ($sidebar_config == "both-sidebars") { ?>
<aside class="sidebar right-sidebar col-sm-3">
<?php dynamic_sidebar($right_sidebar); ?>
</aside>
<?php } ?>
</div>
<?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?>
</div>
<?php } ?>
<!--// WordPress Hook //-->
<?php get_footer(); ?> | roycocup/enclothed | wp-content/themes/dante/page.php | PHP | gpl-2.0 | 6,214 |
<?php
/**
* TOP API: taobao.traderates.search request
*
* @author auto create
* @since 1.0, 2012-03-21 12:35:10
*/
class TraderatesSearchRequest
{
/**
* 商品的数字id
**/
private $numIid;
/**
* 当前页
**/
private $pageNo;
/**
* 每页显示的条数,允许值:5、10、20、40
**/
private $pageSize;
/**
* 商品所属的卖家nick
**/
private $sellerNick;
private $apiParas = array();
public function setNumIid($numIid)
{
$this->numIid = $numIid;
$this->apiParas["num_iid"] = $numIid;
}
public function getNumIid()
{
return $this->numIid;
}
public function setPageNo($pageNo)
{
$this->pageNo = $pageNo;
$this->apiParas["page_no"] = $pageNo;
}
public function getPageNo()
{
return $this->pageNo;
}
public function setPageSize($pageSize)
{
$this->pageSize = $pageSize;
$this->apiParas["page_size"] = $pageSize;
}
public function getPageSize()
{
return $this->pageSize;
}
public function setSellerNick($sellerNick)
{
$this->sellerNick = $sellerNick;
$this->apiParas["seller_nick"] = $sellerNick;
}
public function getSellerNick()
{
return $this->sellerNick;
}
public function getApiMethodName()
{
return "taobao.traderates.search";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->numIid,"numIid");
RequestCheckUtil::checkMinValue($this->pageNo,1,"pageNo");
RequestCheckUtil::checkMaxValue($this->pageSize,40,"pageSize");
RequestCheckUtil::checkMinValue($this->pageSize,1,"pageSize");
RequestCheckUtil::checkNotNull($this->sellerNick,"sellerNick");
RequestCheckUtil::checkMaxLength($this->sellerNick,32,"sellerNick");
}
}
| gxk9933/guoxk-blog | html/test_taobaoke/sdk/top/request/TraderatesSearchRequest.php | PHP | gpl-2.0 | 1,739 |
//
// FrameSpec.cpp
// Messaging
//
// Created by Dave Meehan on 21/04/2014.
// Copyright (c) 2014 Replicated Solutions Limited. All rights reserved.
//
#include <ZingBDD/ZingBDD.h>
#include "Frame.h"
#include <string.h>
namespace Messaging { namespace Specs {
describe(Frame, {
context("default constructor", {
Frame frame;
context("size", {
it("has size of zero", {
expect(frame.size()).should.equal(0);
});
});
});
context("size constructor", {
size_t expectedSize = 64;
Frame frame(expectedSize);
it("has expected size", {
expect(frame.size()).should.equal(expectedSize);
});
});
context("string constructor", {
char expectedData[] = "this is a test";
Frame frame(expectedData);
it("has expected size", {
expect(strlen(frame.data<char>())).should.equal(strlen(expectedData));
});
it("has expected data", {
expect(strcmp(frame.data<char>(), expectedData)).should.equal(0);
});
});
context("transmission", {
Context ctx;
Socket client(ctx, Socket::Type::request);
Socket server(ctx, Socket::Type::reply);
server.bind("inproc://test");
client.connect("inproc://test");
it("can send and receive", {
char expectedData[] = "this is a test";
Frame outbound(expectedData);
outbound.send(client, Frame::block::none, Frame::more::none);
Frame inbound;
inbound.receive(server, Frame::block::none);
expect(strcmp(inbound.data<char>(), expectedData)).should.equal(0);
});
});
});
} } | dmeehan1968/Playground | Messaging/Tests/FrameSpec.cpp | C++ | gpl-2.0 | 2,391 |
<hr>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Your Website 2014</p>
</div>
</div>
</div>
</footer> | manishkiozen/WebCms | resources/views/blog/includes/footer.blade.php | PHP | gpl-2.0 | 1,468 |
# These are some tools I am creating to help me build the map for the game. They are a work in progress.
# I am also learning python, so I apologize in advance if I do dumb things.
# Right now this consists of just two classes: locations and coordinate systems.
# As I have it implemented here, a coordinate system is simply a group of locations.
# I'm sure there is more I could do, for instance linking a coordinate system to a location so that
# you could, for example, enter a house (a location on a larger map) and get a coordinate system
# for more detailed movement inside the house. Right now this is very possible to do,
# but it has to be implemented outside of the class.
import array
import os
import sys
class location:
farDesc = "" # For Descriptions of locations from far away
nearDesc = "" # For descriptions of locations from close-up
name = ""
items = [] # I am investigating this, but apparently you can't use the "append" function with items and characters
# when there is an array of locations, i.e. a coordSystem locationArray. Don't know why this is.
characters = []
has_nEntrance = True
has_eEntrance = True
has_sEntrance = True
has_wEntrance = True
has_uEntrance = True
has_dEntrance = True
isCoordSys = False
def __init__(self):
self.farDesc = ""
self.nearDesc = ""
self.name = ""
self.items = []
self.characters = []
self.isCoordSys = False # save time so that we don't have to check for a matching coordSys for every
# single location
class coordSystem:
name = ""
xMax = 0
yMax = 0
zMax = 0
_locationArray = [] # I have it as a "private variable" (as far as they exist in Python) to avoid confusion:
# as the implementation stands, you have to access the array in the order of [z][y][x], but
# most people are used to the opposite ordering. Rather than screw around with naming and
# perhaps add confusion, I want people to only ever access the array by get and set methods.
def getLocation(self, x, y, z):
return self._locationArray[z][y][x]
def __init__(self, name, xMax, yMax, zMax):
self.name = name
self.xMax = xMax
self.yMax = yMax
self.zMax = zMax
self._locationArray = [[[location() for x in range(xMax)] for x in range(yMax)] for x in range(zMax)]
#The above line is weird, but I can't think of a better way to initialize an array of arrays
| nickdab/pygame | maptools.py | Python | gpl-2.0 | 2,622 |
'''
This file is part of the lenstractor project.
Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford).
Description
-----------
Wrapper class for tractor operation, to enable high level options (ie sampling or optimization).
To-do
-----
- debug, test
'''
import numpy as np
import os,subprocess
import tractor
import lenstractor
import emcee
emcee_defaults = {}
import pylab as plt
# ============================================================================
class LensTractor():
'''
PURPOSE
Optimize or sample a Lens or Nebula model using the Tractor.
COMMENTS
INPUTS
data A list of tractor.images
model A model (including a list of tractor.sources)
by A mode of operation ['optimizing','sampling']
using The required settings
survey The name of the survey being worked on
plot Make plots if desired
OUTPUTS
BUGS
HISTORY
2014-04-17 Started Marshall & Agnello (UCSB)
'''
# ----------------------------------------------------------------------------
def __init__(self,dataset,model,outstem,survey,counter=0,vb=0,noplots=True):
self.name = 'LensTractor'
self.survey = survey
self.settings = {}
# Optimization settings:
# self.settings['Nrounds'] = 5
# self.settings['Nsteps_optimizing_catalog'] = 100
# self.settings['Nsteps_optimizing_PSFs'] = 2
# Sampling settings:
self.settings['Nwalkers_per_dim'] = 8
self.settings['Nsnapshots'] = 3
self.settings['Nsteps_per_snapshot'] = 5000
self.settings['Restart'] = True
self.model = model
self.vb = vb
self.noplots = noplots
self.plot_all = True
self.outstem = outstem.split('.')[0]
self.bestpars = None
self.maxlnp = None
self.minchisq = None
self.psteps = None
self.counter = counter
# self.chug = tractor.Tractor(dataset)
self.chug = lenstractor.Trattore(dataset)
for src in self.model.srcs:
self.chug.addSource(src)
# Freeze the PSFs, wcs and photocal, leaving the sky and sources:
self.chug.thawParam('catalog')
for image in self.chug.getImages():
image.thawParams('sky')
image.freezeParams('photocal')
image.freezeParams('wcs')
image.freezeParams('psf')
# Plot initial state:
if not self.noplots:
self.plot_state('progress-%02d_initial_'%self.counter+self.model.name)
return None
# ----------------------------------------------------------------------------
# Drive the LensTractor. We have both steepest ascent and MCMC capability.
# Try a mixture!
def drive(self,by='cunning_and_guile'):
self.method = by
if self.method == 'sampling':
self.sample()
elif self.method == 'optimizing':
if self.model.flavor == 'Nebula':
# First optimize to get the Nebula model about right, at fixed PSF:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 100000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now optimize PSF at fixed model:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
# Refine Nebula model at best PSF:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
elif self.model.flavor == 'Lens':
# PSF is already optimized, during Nebula run.
# Just do the lens part:
self.settings['Nrounds'] = 2
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
else: # Apply cunning and guile! Both optimization and sampling.
# First optimize to get the fluxes about right:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 100000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now optimize PSF at fixed model:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
# Now draw a few samples to shuffle the positions:
self.settings['Nsnapshots'] = 1
self.settings['Nwalkers_per_dim'] = 4
self.settings['Nsteps_per_snapshot'] = 2500
self.settings['Restart'] = True
self.sample()
# Now optimize to refine model and PSF:
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 50000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 0
self.settings['Nsteps_optimizing_PSFs'] = 2
self.optimize()
self.settings['Nrounds'] = 1
self.settings['Nsteps_optimizing_catalog'] = 10000
self.settings['Nsteps_optimizing_PSFs'] = 0
self.optimize()
self.getBIC()
return None
# ----------------------------------------------------------------------------
# Fit the model to the image data by maximizing the posterior PDF
# ("optimizing") with respect to the parameters.
def optimize(self):
Nrounds = self.settings['Nrounds']
Nsteps_optimizing_catalog = self.settings['Nsteps_optimizing_catalog']
Nsteps_optimizing_PSFs = self.settings['Nsteps_optimizing_PSFs']
if self.vb:
print " "
print "Optimizing model:"
print " - no. of iterations per round to be spent on catalog: ",Nsteps_optimizing_catalog
print " - no. of iterations per round to be spent on PSFs: ",Nsteps_optimizing_PSFs
print " - no. of rounds: ",Nrounds
for round in range(Nrounds):
self.counter += 1
if self.vb: print "Fitting "+self.model.name+": seconds out, round",round
if self.vb:
print "Fitting "+self.model.name+": Catalog parameters to be optimized are:",self.chug.getParamNames()
print "Fitting "+self.model.name+": Initial values are:",self.chug.getParams()
print "Fitting "+self.model.name+": Step sizes:",self.chug.getStepSizes()
# Optimize sources:
for i in range(Nsteps_optimizing_catalog):
dlnp,X,a = self.chug.optimize(damp=3,shared_params=False)
# print "Fitting "+self.model.name+": at step",k,"parameter values are:",self.chug.getParams()
if self.vb:
print "Progress: counter,dlnp = ",self.counter,dlnp
print ""
print "Catalog parameters:",self.chug.getParamNames()
print "Catalog values:",self.chug.getParams()
if dlnp == 0:
print "Converged? Exiting..."
# Although this only leaves *this* loop...
break
if not self.noplots:
self.plot_state('progress-%02d_optimizing_'%self.counter+self.model.name)
if Nsteps_optimizing_PSFs > 0:
# Freeze the sources and calibration, and thaw the psfs:
if self.vb: print "Freezing catalog..."
self.chug.freezeParams('catalog')
for image in self.chug.getImages():
if self.vb: print "Thawing PSF..."
image.thawParams('psf')
if self.vb: print "Freezing photocal, WCS, sky (just to make sure...)"
image.freezeParams('photocal', 'wcs', 'sky')
if self.vb:
print "Fitting PSF: After thawing, zeroth PSF = ",self.chug.getImage(0).psf
print "Fitting PSF: PSF parameters to be optimized are:",self.chug.getParamNames()
print "Fitting PSF: Initial values are:",self.chug.getParams()
print "Fitting PSF: Step sizes:",self.chug.getStepSizes()
# Optimize everything that is not frozen:
for i in range(Nsteps_optimizing_PSFs):
dlnp,X,a = self.chug.optimize(shared_params=False)
if self.vb: print "Fitting PSF: at counter =",self.counter,"parameter values are:",self.chug.getParams()
self.counter += 1
if self.vb: print "Fitting PSF: After optimizing, zeroth PSF = ",self.chug.getImage(0).psf
if not self.noplots: self.plot_state(
'progress-%02d_optimizing_PSF_for_'%self.counter+self.model.name)
# Freeze the psf again, and thaw the sources:
if self.vb: print "Re-thawing catalog..."
self.chug.thawParams('catalog')
for image in self.chug.getImages():
if self.vb: print "Re-freezing PSF..."
image.freezeParams('psf')
if self.vb: print "Re-freezing photocal, WCS, sky (just to make sure...)"
image.freezeParams('photocal', 'wcs', 'sky')
# Save the best parameters!
self.maxlnp = self.chug.getLogProb()
self.bestpars = self.chug.getParams()
if self.vb: print "Optimizer: Best parameters: ",self.maxlnp,self.bestpars
self.minchisq = -2.0*self.chug.getLogLikelihood()
if self.vb: print "Optimizer: chisq at highest lnprob point: ",self.minchisq
return None
# ----------------------------------------------------------------------------
# Fit the model to the image data by drawing samples from the posterior PDF
# that have high probability density: note, this is not really sampling,
# its *sampling to optimize*...
def sample(self):
if self.vb:
print "Sampling model parameters with Emcee:"
# Magic numbers:
Nwalkers_per_dim = self.settings['Nwalkers_per_dim']
Nsnapshots = self.settings['Nsnapshots']
Nsteps_per_snapshot = self.settings['Nsteps_per_snapshot']
Restart = self.settings['Restart']
# Get the thawed parameters:
p0 = np.array(self.chug.getParams())
if self.vb: print 'Tractor parameters:'
for i,parname in enumerate(self.chug.getParamNames()):
print ' ', parname, '=', p0[i]
Ndim = len(p0)
if self.vb: print 'Number of parameter space dimensions: ',Ndim
# Make an emcee sampler that uses our tractor to compute its logprob:
Nw = Nwalkers_per_dim*Ndim # 8*ndim
sampler = emcee.EnsembleSampler(Nw, Ndim, self.chug, threads=4)
# Start the walkers off near the initialisation point -
# We need it to be ~1 pixel in position, and not too much
# flux restriction... But use any psteps we already have!
if self.psteps is None:
if self.model.name=='Lens':
# The following gets us 0.05" in dec:
self.psteps = np.zeros_like(p0) + 0.00001
# This could be optimized, to allow more initial freedom in eg flux.
else:
# Good first guess should be some fraction of the optimization step sizes:
self.psteps = 0.01*np.array(self.chug.getStepSizes())
if self.vb: print "Initial size (in each dimension) of sample ball = ",self.psteps
#pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw)
pp = emcee.utils.sample_ball(p0, self.psteps, Nw)
rstate = None
lnp = None
# Take a few steps - memory leaks fast! (~10Mb per sec)
for snapshot in range(1,Nsnapshots+1):
self.counter += 1
if self.vb: print 'Emcee: MCMC snapshot:', snapshot
t0 = tractor.Time()
pp,lnp,rstate = sampler.run_mcmc(pp, Nsteps_per_snapshot, lnprob0=lnp, rstate0=rstate)
if self.vb: print 'Emcee: Mean acceptance fraction after', sampler.iterations, 'iterations =',np.mean(sampler.acceptance_fraction)
t_mcmc = (tractor.Time() - t0)
if self.vb: print 'Emcee: Runtime:', t_mcmc
# Find the current best sample, and sample ball:
self.maxlnp = np.max(lnp)
best = np.where(lnp == self.maxlnp)
self.bestpars = np.ravel(pp[best,:])
if self.vb: print "Emcee: Best parameters: ",self.maxlnp,self.bestpars
self.minchisq = -2.0*self.chug.getLogLikelihood()
if self.vb: print "Emcee: chisq at highest lnprob point: ",self.minchisq
if not self.noplots:
self.chug.setParams(self.bestpars)
self.plot_state('progress-%02d_sampling_'%self.counter+self.model.name)
if Restart:
# Make a new sample ball centred on the current best point,
# and with width given by the standard deviations in each
# dimension:
self.chug.setParams(self.bestpars)
p0 = np.array(self.chug.getParams())
self.psteps = np.std(pp,axis=0)
# pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw)
pp = emcee.utils.sample_ball(p0, self.psteps, Nw)
rstate = None
lnp = None
if self.vb: print 'Emcee: total run time', t_mcmc, 'sec'
return None
# ----------------------------------------------------------------------------
def getBIC(self):
self.K = len(self.bestpars)
self.N = self.chug.getNdata()
self.BIC = self.minchisq + self.K*np.log(1.0*self.N)
return self.BIC
# ----------------------------------------------------------------------------
def write_catalog(self):
# Get parameter names and values:
parnames = self.chug.getParamNames()
values = np.array(np.outer(1,self.bestpars))
# Get image names:
imgnames = []
for image in self.chug.getImages():
imgnames.append(image.name)
# Set catalog file name:
outfile = self.outstem+'_'+self.model.name+'.cat'
# Open up a new file, over-writing any old one:
try: os.remove(outfile)
except OSError: pass
output = open(outfile,'w')
# Write header:
hdr = []
hdr.append('# LensTractor output parameter catalog')
# hdr.append('# ')
# hdr.append('# Date: %s' % datestring)
hdr.append('# ')
hdr.append('# Model: %s' % self.model.name)
hdr.append('# Notes:')
hdr.append('# * First source is always the galaxy, point sources follow')
for ii,imgname in enumerate(imgnames):
hdr.append('# * images.image%d = %s' % (ii,imgname))
hdr.append('# ')
# Last line contains the parameter names:
nameline = "# "
for name in parnames:
nameline += name+" "
hdr.append(nameline)
# Write to file:
for line in hdr:
output.write("%s\n" % line)
# Close file:
output.close()
np.savetxt('junk', values)
cat = subprocess.call("cat junk >> " + outfile, shell=True)
rm = subprocess.call("rm junk", shell=True)
if cat != 0 or rm != 0:
print "Error: write subprocesses failed in some way :-/"
sys.exit()
return outfile
# ----------------------------------------------------------------------------
def set_cookie(self,outstem,result):
outfile = self.outstem+'_result.cookie'
# Open up a new file, over-writing any old one:
try: os.remove(outfile)
except OSError: pass
output = open(outfile,'w')
# Write result to file:
output.write("%s\n" % result)
# Close file:
output.close()
return outfile
# ----------------------------------------------------------------------------
# Plot progress.
def plot_state(self,suffix):
'''
Make all the plots we need to assess the state of the LensTractor.
Mainly, a multi-panel figure of image, synthetic image and chi, for
each image being modelled.
self.chug is a Tractor object, containing a list of images.
'''
if self.plot_all:
# Make one giant plot with all progress panels on it, and
# save it to PNG:
# Plotting setup:
px,py = 4,len(self.chug.images)
figprops = dict(figsize=(5*px,5*py), dpi=128)
adjustprops = dict(\
left=0.05,\
bottom=0.05,\
right=0.95,\
top=0.95,\
wspace=0.1,\
hspace=0.1)
# Start the plot:
fig = plt.figure(**figprops)
fig.subplots_adjust(**adjustprops)
plt.clf()
plt.gray()
counter = 0
# Name the plot file:
pngfile = self.outstem+'_'+suffix+'.png'
else:
# Make one plot per image, and save each to PNG.
# Plotting setup:
px,py = 2,2
figprops = dict(figsize=(5*px,5*py), dpi=128)
adjustprops = dict(\
left=0.05,\
bottom=0.05,\
right=0.95,\
top=0.95,\
wspace=0.1,\
hspace=0.1)
# Loop over images, making plots:
for i,image in enumerate(self.chug.images):
if image.name is None:
imname = suffix+str(i)
else:
imname = image.name
chi = self.chug.getChiImage(i)
if self.survey == 'PS1':
ima, chia, psfa = lenstractor.PS1_imshow_settings(image,chi)
elif self.survey == 'KIDS':
ima, chia, psfa = lenstractor.KIDS_imshow_settings(image,chi)
else:
# Do the same as for PS1
scale = np.sqrt(np.median(1.0/image.invvar[image.invvar > 0.0]))
ima = dict(interpolation='nearest', origin='lower',
vmin=-100.*scale, vmax=3.*scale)
chia = dict(interpolation='nearest', origin='lower',
vmin=-5., vmax=5.)
psfa = dict(interpolation='nearest', origin='lower')
if not self.plot_all:
# Start a new plot:
fig = plt.figure(**figprops)
fig.subplots_adjust(**adjustprops)
plt.clf()
plt.gray()
counter = 0
# 1) Data Image
counter += 1
plt.subplot(py,px,counter)
plt.imshow(-image.data, **ima)
self.tidyup_plot()
plt.title('Observed image')
# Overlay image filter in lower left corner
plt.text(1,1,image.photocal.bandname+'-band')
# Figure out how to get this in bottom right hand corner instead
# 2) Predicted image
counter += 1
plt.subplot(py,px,counter)
model = self.chug.getModelImages()[i]
plt.imshow(-model, **ima)
self.tidyup_plot()
# Overlay cartoon of model:
self.model.plot(image.wcs,image.photocal.bandname)
plt.title('Predicted image')
# Overlay name of model in lower left corner
plt.text(1,1,self.model.name)
# Figure out how to get this in top left hand corner instead
# 3) Normalised residual
counter += 1
plt.subplot(py,px,counter)
plt.imshow(-chi, **chia)
self.tidyup_plot()
if self.survey == 'KIDS':
# It is not clear why the residual image is not in units of
# sigma. Perhaps this causes problems in the modelling.
# This code is not refactored into kids.py since it should
# not be necessary in the first place.
plt.title('Residuals (flexible scale)')
else:
plt.title('Residuals ($\pm 5\sigma$)')
# Overlay quantified goodness of fit, in sigma from acceptable...
# TBI!
# 4) PSF image
counter += 1
plt.subplot(py,px,counter)
psfimage = image.psf.getPointSourcePatch(*model.shape).patch
plt.imshow(-psfimage, **psfa)
self.tidyup_plot()
plt.title('PSF')
if not self.plot_all:
# Save this image's plot:
pngfile = imname+'_'+suffix+'.png'
plt.savefig(pngfile)
if self.vb:
print "Progress snapshot saved to "+pngfile
if self.plot_all:
# Save the giant plot:
plt.savefig(pngfile)
if self.vb:
print "Progress snapshot saved to "+pngfile
return
# ----------------------------------------------------------------------------
# Turn off the axis ticks and labels:
def tidyup_plot(self):
ax = plt.gca()
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
return
# ============================================================================
if __name__ == '__main__':
pass
| davidwhogg/LensTractor | lenstractor/driver.py | Python | gpl-2.0 | 21,961 |
<?php
/**
* 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; under version 2
* of the License (non-upgradable).
*
* 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.
*
* Copyright (c) 2015 (original work) Open Assessment Technologies SA;
*
*
*/
namespace oat\tao\model\requiredAction\implementation;
use oat\tao\model\requiredAction\RequiredActionAbstract;
use oat\tao\model\routing\FlowController;
/**
* Class RequiredAction
*
* RequiredAction is action which should be executed by user before performing any activities in the TAO
*
* @package oat\tao\model\requiredAction\implementation
*/
class RequiredActionRedirectUrlPart extends RequiredActionAbstract
{
/**
* Route to be ignored
*
* @var array
*/
protected $excludedRoutes = [
[
'extension' => 'tao',
'module' => 'ClientConfig',
'action' => 'config',
]
];
/**
* Array of url parts
*
* @var array
*/
protected $url;
/**
* RequiredActionRedirectUrlPart constructor.
* @param string $name
* @param array $rules
* @param array $url
*/
public function __construct($name, array $rules, array $url)
{
parent::__construct($name, $rules);
$this->url = $url;
}
/**
* Execute an action
*
* @param array $params
* @return string The callback url
*/
public function execute(array $params = [])
{
$context = \Context::getInstance();
$excludedRoutes = $this->getExcludedRoutes();
$currentRoute = [
'extension' => $context->getExtensionName(),
'module' => $context->getModuleName(),
'action' => $context->getActionName(),
];
if (! in_array($currentRoute, $excludedRoutes)) {
$currentUrl = \common_http_Request::currentRequest()->getUrl();
$transformedUrl = $this->getTransformedUrl($params);
$url = $transformedUrl . (parse_url($transformedUrl, PHP_URL_QUERY) ? '&' : '?') . 'return_url=' . urlencode($currentUrl);
$flowController = new FlowController();
$flowController->redirect($url);
}
}
/**
* @see \oat\oatbox\PhpSerializable::__toPhpCode()
*/
public function __toPhpCode()
{
$class = get_class($this);
$name = $this->name;
$rules = \common_Utils::toHumanReadablePhpString($this->getRules());
$url = \common_Utils::toHumanReadablePhpString($this->url);
return "new $class(
'$name',
$rules,
$url
)";
}
/**
* Get url string from $this->url
*
* @param array $params
* @return string
*/
protected function getTransformedUrl(array $params = [])
{
return call_user_func_array('_url', array_merge($this->url, [$params]));
}
/**
* Some actions should not be redirected (such as retrieving requireJs config)
*
* @return array
*/
protected function getExcludedRoutes()
{
$result = $this->excludedRoutes;
$resolver = new \Resolver($this->getTransformedUrl());
$result[] = [
'extension' => $resolver->getExtensionFromURL(),
'module' => $resolver->getModule(),
'action' => $resolver->getAction(),
];
return $result;
}
}
| oat-sa/tao-core | models/classes/requiredAction/implementation/RequiredActionRedirectUrlPart.php | PHP | gpl-2.0 | 3,945 |
/**
*/
package components.provider;
import components.Association;
import components.ComponentsPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link components.Association} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class AssociationItemProvider
extends ClassifierItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AssociationItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addTargetPropertyDescriptor(object);
addSourcePropertyDescriptor(object);
addLowerBoundPropertyDescriptor(object);
addUpperBoundPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Target feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addTargetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_target_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_target_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__TARGET,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Source feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addSourcePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_source_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_source_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__SOURCE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Lower Bound feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLowerBoundPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_lowerBound_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_lowerBound_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__LOWER_BOUND,
true,
false,
false,
ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Upper Bound feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addUpperBoundPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Association_upperBound_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Association_upperBound_feature", "_UI_Association_type"),
ComponentsPackage.Literals.ASSOCIATION__UPPER_BOUND,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns Association.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Association"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((Association)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Association_type") :
getString("_UI_Association_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(Association.class)) {
case ComponentsPackage.ASSOCIATION__LOWER_BOUND:
case ComponentsPackage.ASSOCIATION__UPPER_BOUND:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| peterbartha/j2eecm | edu.bme.vik.iit.j2eecm.edit/src/components/provider/AssociationItemProvider.java | Java | gpl-2.0 | 6,415 |
/**********************************************************************************************************************
* Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit. *
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. *
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. *
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. *
* Vestibulum commodo. Ut rhoncus gravida arcu. *
**********************************************************************************************************************/
package z.z.w.test.common.core.notify;
/**************************************************************************
* <pre>
* FileName: IDataManipulation
* Desc:
* author: Z_Z.W - myhongkongzhen@gmail.com
* version: 2015-12-28 23:54
* LastChange: 2015-12-28 23:54
* History:
* </pre>
**************************************************************************/
public interface IDataManipulation< T >
{
void operating( T t );
}
| myhongkongzhen/pro-study-jdk | src/main/java/z/z/w/test/common/core/notify/IDataManipulation.java | Java | gpl-2.0 | 1,312 |
# -*- coding: utf-8 -*-
import json
import datetime
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from misc.decorators import staff_required, common_ajax_response, verify_permission
from common import cache, debug, page
from message.interface import GlobalNoticeBase
#--------------------------------- 缓存管理
@verify_permission('')
def caches(request, template_name='admin/caches.html'):
indexes = [{'name': cache.CACHE_INDEX[k][0], 'value': k} for k in cache.CACHE_INDEX.keys()]
descs = [{'name': cache.CACHE_KEYS_DESC[k], 'value': k} for k in cache.CACHE_KEYS_DESC.keys()]
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
@verify_permission('modify_cache')
@common_ajax_response
def modify_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
value = request.REQUEST.get('key_value', '')
expire = request.REQUEST.get('key_expire', 3600)
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
c.set(key, value, expire)
return 0, u'修改成功!'
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
@verify_permission('remove_cache')
@common_ajax_response
def remove_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
c.delete(key)
return 0, u'删除成功!'
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
@verify_permission('get_cache')
@common_ajax_response
def get_cache(request):
index = request.REQUEST.get('index')
key = request.REQUEST.get('key_name')
try:
c = cache.Cache(cache.CACHE_INDEX[index][1])
return 0, [c.get(key) or '', c.ttl(key) or 0]
except Exception, e:
debug.get_debug_detail(e)
return 1, u'系统错误!'
#--------------------------------- 全站通告
@verify_permission('')
def notice(request, template_name='admin/notice.html'):
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
@verify_permission('query_notice')
def search_notice(request):
data = []
gnb = GlobalNoticeBase()
page_index = int(request.REQUEST.get('page_index'))
page_objs = page.Cpt(gnb.get_all_global_notice(), count=10, page=page_index).info
num = 10 * (page_index - 1)
for obj in page_objs[0]:
num += 1
data.append({
'num': num,
'notice_id': obj.id,
'content': obj.content,
'start_time': str(obj.start_time),
'end_time': str(obj.end_time),
'level': obj.level,
'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False
})
return HttpResponse(
json.dumps({'data': data, 'page_count': page_objs[4], 'total_count': page_objs[5]}),
mimetype='application/json'
)
@verify_permission('add_notice')
@common_ajax_response
def add_notice(request):
content = request.REQUEST.get('content')
start_time = request.REQUEST.get('start_time')
end_time = request.REQUEST.get('end_time')
level = request.REQUEST.get('level')
return GlobalNoticeBase().create_global_notice(
content, start_time, end_time, request.user.id, level)
@verify_permission('query_notice')
def get_notice_by_id(request):
notice_id = request.REQUEST.get('notice_id')
data = ''
obj = GlobalNoticeBase().get_notice_by_id(notice_id)
if obj:
data = {
'num': 1,
'notice_id': obj.id,
'content': obj.content,
'start_time': str(obj.start_time)[:10],
'end_time': str(obj.end_time)[:10],
'level': obj.level,
'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False
}
return HttpResponse(json.dumps(data), mimetype='application/json')
@verify_permission('modify_notice')
@common_ajax_response
def modify_notice(request):
notice_id = request.REQUEST.get('notice_id')
content = request.REQUEST.get('content')
start_time = request.REQUEST.get('start_time')
end_time = request.REQUEST.get('end_time')
level = request.REQUEST.get('level')
return GlobalNoticeBase().modify_global_notice(
notice_id, content=content, start_time=start_time, end_time=end_time, level=level)
@verify_permission('remove_notice')
@common_ajax_response
def remove_notice(request):
notice_id = request.REQUEST.get('notice_id')
return GlobalNoticeBase().remove_global_notice(notice_id)
| lantianlz/zx | www/admin/views_tools.py | Python | gpl-2.0 | 4,764 |
/*
* wowhead basic.js
* adapted to phpbb
*
*/
window.onload = resizeIfOdd;
window.onresize = forceBrowserEven;
function resizeIfOdd(){
if(navigator.userAgent.indexOf('Firefox/3') != -1 ||
navigator.userAgent.indexOf('WebKit') != -1)
if(document.documentElement.clientWidth % 2 == 1)
window.resizeBy(-1,0);
};
function forceBrowserEven(){
window.setTimeout('resizeIfOdd()',5);
};
if (typeof $WH == "undefined") {
var $WH = {}
}
if ((whPos = document.domain.indexOf(".wowhead.com")) != -1) {
document.domain = document.domain.substring(whPos + 1)
}
$WH.$E = function(a) {
if (!a) {
if (typeof event != "undefined") {
a = event
} else {
return null
}
}
if (a.which) {
a._button = a.which
} else {
a._button = a.button;
if ($WH.Browser.ie6789 && a._button) {
if (a._button & 4) {
a._button = 2
} else {
if (a._button & 2) {
a._button = 3
}
}
} else {
a._button = a.button + 1
}
}
a._target = a.target ? a.target : a.srcElement;
a._wheelDelta = a.wheelDelta ? a.wheelDelta : -a.detail;
return a
};
$WH.$A = function(c) {
var e = [];
for ( var d = 0, b = c.length; d < b; ++d) {
e.push(c[d])
}
return e
};
if (!Function.prototype.bind) {
Function.prototype.bind = function() {
var c = this, a = $WH.$A(arguments), b = a.shift();
return function() {
return c.apply(b, a.concat($WH.$A(arguments)))
}
}
}
$WH.bindfunc = function() {
args = $WH.$A(arguments);
var b = args.shift();
var a = args.shift();
return function() {
return b.apply(a, args.concat($WH.$A(arguments)))
}
};
if (!String.prototype.ltrim) {
String.prototype.ltrim = function() {
return this.replace(/^\s*/, "")
}
}
if (!String.prototype.rtrim) {
String.prototype.rtrim = function() {
return this.replace(/\s*$/, "")
}
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.ltrim().rtrim()
}
}
if (!String.prototype.removeAllWhitespace) {
String.prototype.removeAllWhitespace = function() {
return this.replace("/s+/g", "")
}
}
$WH.strcmp = function(d, c) {
if (d == c) {
return 0
}
if (d == null) {
return -1
}
if (c == null) {
return 1
}
var f = parseFloat(d);
var e = parseFloat(c);
if (!isNaN(f) && !isNaN(e) && f != e) {
return f < e ? -1 : 1
}
if (typeof d == "string" && typeof c == "string") {
return d.localeCompare(c)
}
return d < c ? -1 : 1
};
$WH.trim = function(a) {
return a.replace(/(^\s*|\s*$)/g, "")
};
$WH.rtrim = function(c, d) {
var b = c.length;
while (--b > 0 && c.charAt(b) == d) {
}
c = c.substring(0, b + 1);
if (c == d) {
c = "";
}
return c
};
$WH.sprintf = function(b) {
var a;
for (a = 1, len = arguments.length; a < len; ++a) {
b = b.replace("$" + a, arguments[a])
}
return b
};
$WH.sprintfa = function(b) {
var a;
for (a = 1, len = arguments.length; a < len; ++a) {
b = b.replace(new RegExp("\\$" + a, "g"), arguments[a])
}
return b
};
$WH.sprintfo = function(c) {
if (typeof c == "object" && c.length) {
var a = c;
c = a[0];
var b;
for (b = 1; b < a.length; ++b) {
c = c.replace("$" + b, a[b])
}
return c
}
};
$WH.str_replace = function(e, d, c) {
while (e.indexOf(d) != -1) {
e = e.replace(d, c)
}
return e
};
$WH.urlencode = function(a) {
a = encodeURIComponent(a);
a = $WH.str_replace(a, "+", "%2B");
return a
};
$WH.urlencode2 = function(a) {
a = encodeURIComponent(a);
a = $WH.str_replace(a, "%20", "+");
a = $WH.str_replace(a, "%3D", "=");
return a
};
$WH.number_format = function(a) {
x = ("" + parseFloat(a)).split(".");
a = x[0];
x = x.length > 1 ? "." + x[1] : "";
if (a.length <= 3) {
return a + x
}
return $WH.number_format(a.substr(0, a.length - 3)) + ","
+ a.substr(a.length - 3) + x
};
$WH.is_array = function(b) {
return !!(b && b.constructor == Array)
};
$WH.in_array = function(c, g, h, e) {
if (c == null) {
return -1
}
if (h) {
return $WH.in_arrayf(c, g, h, e)
}
for ( var d = e || 0, b = c.length; d < b; ++d) {
if (c[d] == g) {
return d
}
}
return -1
};
$WH.in_arrayf = function(c, g, h, e) {
for ( var d = e || 0, b = c.length; d < b; ++d) {
if (h(c[d]) == g) {
return d
}
}
return -1
};
$WH.rs = function() {
var e = $WH.rs.random;
var b = "";
for ( var a = 0; a < 16; a++) {
var d = Math.floor(Math.random() * e.length);
if (a == 0 && d < 11) {
d += 10
}
b += e.substring(d, d + 1)
}
return b
};
$WH.rs.random = "0123456789abcdefghiklmnopqrstuvwxyz";
$WH.isset = function(a) {
return typeof window[a] != "undefined"
};
if (!$WH.isset("console")) {
console = {
log : function() {
}
}
}
$WH.array_walk = function(d, h, c) {
var g;
for ( var e = 0, b = d.length; e < b; ++e) {
g = h(d[e], c, d, e);
if (g != null) {
d[e] = g
}
}
};
$WH.array_apply = function(d, h, c) {
var g;
for ( var e = 0, b = d.length; e < b; ++e) {
h(d[e], c, d, e)
}
};
$WH.array_filter = function(c, g) {
var e = [];
for ( var d = 0, b = c.length; d < b; ++d) {
if (g(c[d])) {
e.push(c[d])
}
}
return e
};
$WH.array_index = function(c, e, g, h) {
if (!$WH.is_array(c)) {
return false
}
if (!c.__R || h) {
c.__R = {};
if (!g) {
g = function(a) {
return a
}
}
for ( var d = 0, b = c.length; d < b; ++d) {
c.__R[g(c[d])] = d
}
}
return (e == null ? c.__R : !isNaN(c.__R[e]))
};
$WH.array_compare = function(d, c) {
if (d.length != c.length) {
return false
}
var g = {};
for ( var f = d.length; f >= 0; --f) {
g[d[f]] = true
}
var e = true;
for ( var f = c.length; f >= 0; --f) {
if (g[c[f]] === undefined) {
e = false
}
}
return e
};
$WH.array_unique = function(b) {
var c = [];
var e = {};
for ( var d = b.length - 1; d >= 0; --d) {
e[b[d]] = 1
}
for ( var d in e) {
c.push(d)
}
return c
};
$WH.ge = function(a) {
if (typeof a != "string") {
return a
}
return document.getElementById(a)
};
$WH.gE = function(a, b) {
return a.getElementsByTagName(b)
};
$WH.ce = function(d, b, e) {
var a = document.createElement(d);
if (b) {
$WH.cOr(a, b)
}
if (e) {
$WH.ae(a, e)
}
return a
};
$WH.de = function(a) {
if (!a || !a.parentNode) {
return
}
a.parentNode.removeChild(a)
};
$WH.ae = function(a, b) {
if ($WH.is_array(b)) {
$WH.array_apply(b, a.appendChild.bind(a));
return b
} else {
return a.appendChild(b)
}
};
$WH.aef = function(a, b) {
return a.insertBefore(b, a.firstChild)
};
$WH.ee = function(a, b) {
if (!b) {
b = 0
}
while (a.childNodes[b]) {
a.removeChild(a.childNodes[b])
}
};
$WH.ct = function(a) {
return document.createTextNode(a)
};
$WH.st = function(a, b) {
if (a.firstChild && a.firstChild.nodeType == 3) {
a.firstChild.nodeValue = b
} else {
$WH.aef(a, $WH.ct(b))
}
};
$WH.nw = function(a) {
a.style.whiteSpace = "nowrap"
};
$WH.rf = function() {
return false
};
$WH.rf2 = function(a) {
a = $WH.$E(a);
if (a.ctrlKey || a.shiftKey || a.altKey || a.metaKey) {
return
}
return false
};
$WH.tb = function() {
this.blur()
};
$WH.aE = function(b, c, a) {
if ($WH.Browser.ie6789) {
b.attachEvent("on" + c, a)
} else {
b.addEventListener(c, a, false)
}
};
$WH.dE = function(b, c, a) {
if ($WH.Browser.ie6789) {
b.detachEvent("on" + c, a)
} else {
b.removeEventListener(c, a, false)
}
};
$WH.sp = function(a) {
if (!a) {
a = event
}
if ($WH.Browser.ie6789) {
a.cancelBubble = true
} else {
a.stopPropagation()
}
};
$WH.sc = function(h, j, d, f, g) {
var e = new Date();
var c = h + "=" + escape(d) + "; ";
e.setDate(e.getDate() + j);
c += "expires=" + e.toUTCString() + "; ";
if (f) {
c += "path=" + f + "; "
}
if (g) {
c += "domain=" + g + "; "
}
document.cookie = c;
$WH.gc(h);
$WH.gc.C[h] = d
};
$WH.dc = function(a) {
$WH.sc(a, -1);
$WH.gc.C[a] = null
};
$WH.gc = function(f) {
if ($WH.gc.I == null) {
var e = unescape(document.cookie).split("; ");
$WH.gc.C = {};
for ( var c = 0, a = e.length; c < a; ++c) {
var g = e[c].indexOf("="), b, d;
if (g != -1) {
b = e[c].substr(0, g);
d = e[c].substr(g + 1)
} else {
b = e[c];
d = ""
}
$WH.gc.C[b] = d
}
$WH.gc.I = 1
}
if (!f) {
return $WH.gc.C
} else {
return $WH.gc.C[f]
}
};
$WH.ns = function(a) {
if ($WH.Browser.ie6789) {
a.onfocus = $WH.tb;
a.onmousedown = a.onselectstart = a.ondragstart = $WH.rf
}
};
$WH.eO = function(b) {
for ( var a in b) {
delete b[a]
}
};
$WH.dO = function(a) {
function b() {
}
b.prototype = a;
return new b
};
$WH.cO = function(c, a) {
for ( var b in a) {
if (a[b] !== null && typeof a[b] == "object" && a[b].length) {
c[b] = a[b].slice(0)
} else {
c[b] = a[b]
}
}
return c
};
$WH.cOr = function(c, a) {
for ( var b in a) {
if (typeof a[b] == "object") {
if (a[b].length) {
c[b] = a[b].slice(0)
} else {
if (!c[b]) {
c[b] = {}
}
$WH.cOr(c[b], a[b])
}
} else {
c[b] = a[b]
}
}
return c
};
$WH.Browser = {
ie : !!(window.attachEvent && !window.opera),
opera : !!window.opera,
safari : navigator.userAgent.indexOf("Safari") != -1,
firefox : navigator.userAgent.indexOf("Firefox") != -1,
chrome : navigator.userAgent.indexOf("Chrome") != -1
};
$WH.Browser.ie9 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 9.0") != -1;
$WH.Browser.ie8 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 8.0") != -1 && !$WH.Browser.ie9;
$WH.Browser.ie7 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 7.0") != -1 && !$WH.Browser.ie8;
$WH.Browser.ie6 = $WH.Browser.ie
&& navigator.userAgent.indexOf("MSIE 6.0") != -1 && !$WH.Browser.ie7;
$WH.Browser.ie67 = $WH.Browser.ie6 || $WH.Browser.ie7;
$WH.Browser.ie678 = $WH.Browser.ie67 || $WH.Browser.ie8;
$WH.Browser.ie6789 = $WH.Browser.ie678 || $WH.Browser.ie9;
$WH.OS = {
windows : navigator.appVersion.indexOf("Windows") != -1,
mac : navigator.appVersion.indexOf("Macintosh") != -1,
linux : navigator.appVersion.indexOf("Linux") != -1
};
$WH.g_getWindowSize = function() {
var a = 0, b = 0;
if (document.documentElement
&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
a = document.documentElement.clientWidth;
b = document.documentElement.clientHeight
} else {
if (document.body
&& (document.body.clientWidth || document.body.clientHeight)) {
a = document.body.clientWidth;
b = document.body.clientHeight
} else {
if (typeof window.innerWidth == "number") {
a = window.innerWidth;
b = window.innerHeight
}
}
}
return {
w : a,
h : b
}
};
$WH.g_getScroll = function() {
var a = 0, b = 0;
if (typeof (window.pageYOffset) == "number") {
a = window.pageXOffset;
b = window.pageYOffset
} else {
if (document.body
&& (document.body.scrollLeft || document.body.scrollTop)) {
a = document.body.scrollLeft;
b = document.body.scrollTop
} else {
if (document.documentElement
&& (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
a = document.documentElement.scrollLeft;
b = document.documentElement.scrollTop
}
}
}
return {
x : a,
y : b
}
};
$WH.g_getCursorPos = function(c) {
var a, d;
if (window.innerHeight) {
a = c.pageX;
d = c.pageY
} else {
var b = $WH.g_getScroll();
a = c.clientX + b.x;
d = c.clientY + b.y
}
return {
x : a,
y : d
}
};
$WH.ac = function(c, d) {
var a = 0, g = 0, b;
while (c) {
a += c.offsetLeft;
g += c.offsetTop;
b = c.parentNode;
while (b && b != c.offsetParent && b.offsetParent) {
if (b.scrollLeft || b.scrollTop) {
a -= (b.scrollLeft | 0);
g -= (b.scrollTop | 0);
break
}
b = b.parentNode
}
c = c.offsetParent
}
if ($WH.isset("Lightbox") && Lightbox.isVisible()) {
d = true
}
if (d) {
var f = $WH.g_getScroll();
a += f.x;
g += f.y
}
var e = [ a, g ];
e.x = a;
e.y = g;
return e
};
$WH.g_scrollTo = function(c, b) {
var m, l = $WH.g_getWindowSize(), o = $WH.g_getScroll(), j = l.w, e = l.h, g = o.x, d = o.y;
c = $WH.ge(c);
if (b == null) {
b = []
} else {
if (typeof b == "number") {
b = [ b ]
}
}
m = b.length;
if (m == 0) {
b[0] = b[1] = b[2] = b[3] = 0
} else {
if (m == 1) {
b[1] = b[2] = b[3] = b[0]
} else {
if (m == 2) {
b[2] = b[0];
b[3] = b[1]
} else {
if (m == 3) {
b[3] = b[1]
}
}
}
}
m = $WH.ac(c);
var a = m[0] - b[3], h = m[1] - b[0], k = m[0] + c.offsetWidth + b[1], f = m[1]
+ c.offsetHeight + b[2];
if (k - a > j || a < g) {
g = a
} else {
if (k - j > g) {
g = k - j
}
}
if (f - h > e || h < d) {
d = h
} else {
if (f - e > d) {
d = f - e
}
}
scrollTo(g, d)
};
$WH.g_createReverseLookupJson = function(b) {
var c = {};
for ( var a in b) {
c[b[a]] = a
}
return c
};
$WH.g_getLocaleFromDomain = function(a) {
var c = $WH.g_getLocaleFromDomain.L;
if (a) {
var b = a.indexOf(".");
if (b != -1) {
a = a.substring(0, b)
}
}
return (c[a] ? c[a] : 0)
};
$WH.g_getLocaleFromDomain.L = {
fr : 2,
de : 3,
es : 6,
ru : 7,
www : 0
};
$WH.g_getDomainFromLocale = function(a) {
var b;
if ($WH.g_getDomainFromLocale.L) {
b = $WH.g_getDomainFromLocale.L
} else {
b = $WH.g_getDomainFromLocale.L = $WH
.g_createReverseLookupJson($WH.g_getLocaleFromDomain.L)
}
return (b[a] ? b[a] : "www")
};
$WH.g_getIdFromTypeName = function(a) {
var b = $WH.g_getIdFromTypeName.L;
return (b[a] ? b[a] : -1)
};
$WH.g_getIdFromTypeName.L = {
npc : 1,
object : 2,
item : 3,
itemset : 4,
quest : 5,
spell : 6,
zone : 7,
faction : 8,
pet : 9,
achievement : 10,
title : 11,
statistic : 16,
profile : 100,
"transmog-set" : 101
};
$WH.g_ajaxIshRequest = function(b) {
var c = document.getElementsByTagName("head")[0], a = $WH.g_getGets();
if (a.refresh != null) {
if (a.refresh.length) {
b += ("&refresh=" + a.refresh)
} else {
b += "&refresh"
}
}
if (a.locale != null) {
b += "&locale=" + a.locale
}
if (a.ptr != null) {
b += "&ptr"
}
$WH.ae(c, $WH.ce("script", {
type : "text/javascript",
src : b,
charset : "utf8"
}))
};
$WH.g_getGets = function() {
if ($WH.g_getGets.C != null) {
return $WH.g_getGets.C
}
var b = $WH.g_getQueryString();
var a = $WH.g_parseQueryString(b);
$WH.g_getGets.C = a;
return a
};
$WH.g_getQueryString = function() {
var a = "";
if (location.pathname) {
a += location.pathname.substr(1)
}
if (location.search) {
if (location.pathname) {
a += "&"
}
a += location.search.substr(1)
}
return a
};
$WH.g_parseQueryString = function(e) {
e = decodeURIComponent(e);
var d = e.split("&");
var c = {};
for ( var b = 0, a = d.length; b < a; ++b) {
$WH.g_splitQueryParam(d[b], c)
}
return c
};
$WH.g_splitQueryParam = function(c, d) {
var e = c.indexOf("=");
var a;
var b;
if (e != -1) {
a = c.substr(0, e);
b = c.substr(e + 1)
} else {
a = c;
b = ""
}
d[a] = b
};
$WH.g_createRect = function(d, c, a, b) {
return {
l : d,
t : c,
r : d + a,
b : c + b
}
};
$WH.g_intersectRect = function(d, c) {
return !(d.l >= c.r || c.l >= d.r || d.t >= c.b || c.t >= d.b)
};
$WH.g_convertRatingToPercent = function(h, b, g, d) {
var f = $WH.g_convertRatingToPercent.RB, e = $WH.g_convertRatingToPercent.LH;
if (h < 0) {
h = 1
} else {
if (h > 85) {
h = 85
}
}
if ((b == 12 || b == 13 || b == 14 || b == 15) && h < 34) {
h = 34
}
if ((b == 28 || b == 36) && (d == 2 || d == 6 || d == 7 || d == 11)) {
f[b] /= 1.3
}
if (g < 0) {
g = 0
}
var a;
if (!f || f[b] == null) {
a = 0
} else {
var c;
if (h > 80) {
c = e[h]
} else {
if (h > 70) {
c = (82 / 52) * Math.pow((131 / 63), ((h - 70) / 10))
} else {
if (h > 60) {
c = (82 / (262 - 3 * h))
} else {
if (h > 10) {
c = ((h - 8) / 52)
} else {
c = 2 / 52
}
}
}
}
a = g / f[b] / c
}
return a
};
$WH.g_statToJson = {
0 : "mana",
1 : "health",
3 : "agi",
4 : "str",
5 : "int",
6 : "spi",
7 : "sta",
8 : "energy",
9 : "rage",
10 : "focus",
13 : "dodgertng",
14 : "parryrtng",
16 : "mlehitrtng",
17 : "rgdhitrtng",
18 : "splhitrtng",
19 : "mlecritstrkrtng",
20 : "rgdcritstrkrtng",
21 : "splcritstrkrtng",
22 : "_mlehitrtng",
23 : "_rgdhitrtng",
24 : "_splhitrtng",
25 : "_mlecritstrkrtng",
26 : "_rgdcritstrkrtng",
27 : "_splcritstrkrtng",
28 : "mlehastertng",
29 : "rgdhastertng",
30 : "splhastertng",
31 : "hitrtng",
32 : "critstrkrtng",
33 : "_hitrtng",
34 : "_critstrkrtng",
35 : "resirtng",
36 : "hastertng",
37 : "exprtng",
38 : "atkpwr",
39 : "rgdatkpwr",
41 : "splheal",
42 : "spldmg",
43 : "manargn",
44 : "armorpenrtng",
45 : "splpwr",
46 : "healthrgn",
47 : "splpen",
49 : "mastrtng",
50 : "armor",
51 : "firres",
52 : "frores",
53 : "holres",
54 : "shares",
55 : "natres",
56 : "arcres"
};
$WH.g_jsonToStat = {};
for ( var i in $WH.g_statToJson) {
$WH.g_jsonToStat[$WH.g_statToJson[i]] = i
}
$WH.g_individualToGlobalStat = {
16 : 31,
17 : 31,
18 : 31,
19 : 32,
20 : 32,
21 : 32,
22 : 33,
23 : 33,
24 : 33,
25 : 34,
26 : 34,
27 : 34,
28 : 36,
29 : 36,
30 : 36
};
$WH.g_convertScalingFactor = function(c, b, g, d, k) {
var f = $WH.g_convertScalingFactor.SV;
var e = $WH.g_convertScalingFactor.SD;
if (!f[c]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no item scaling values for level " + c)
}
return (k ? {} : 0)
}
var j = {}, h = f[c], a = e[g];
if (!a || !(d >= 0 && d <= 9)) {
j.v = h[b]
} else {
j.n = $WH.g_statToJson[a[d]];
j.s = a[d];
j.v = Math.floor(h[b] * a[d + 10] / 10000)
}
return (k ? j : j.v)
};
if (!$WH.wowheadRemote) {
$WH.g_ajaxIshRequest("/data=item-scaling")
}
$WH.g_convertScalingSpell = function(b, g) {
var j = {}, f = $WH.g_convertScalingSpell.SV, d = $WH.g_convertScalingSpell.SD, a, k;
if (!d[g]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no spell scaling distributions for dist " + g)
}
return j
}
if (!f[b]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("There are no spell scaling values for level " + b)
}
return j
}
a = d[g];
if (!a[3]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("This spell should not scale at all")
}
return j
} else {
if (a[3] == -1) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("This spell should use the generic scaling distribution 12")
}
a[3] = 12
}
}
if (!f[b][a[3] - 1]) {
if (g_user.roles & U_GROUP_ADMIN) {
alert("Unknown category for spell scaling " + a[3])
}
return j
}
k = f[b][a[3] - 1];
k *= (Math.min(b, a[14]) + (a[13] * Math.max(0, b - a[14]))) / b;
j.cast = Math.min(a[1], a[1] > 0 && b > 1 ? a[0]
+ (((b - 1) * (a[1] - a[0])) / (a[2] - 1)) : a[0]);
j.effects = {};
for ( var c = 0; c < 3; ++c) {
var l = a[4 + c], h = a[7 + c], e = a[10 + c], m = j.effects[c + 1] = {};
m.avg = l * k * (a[1] > 0 ? j.cast / a[1] : 1);
m.min = Math.round(m.avg) - Math.floor(m.avg * h / 2);
m.max = Math.round(m.avg) + Math.floor(m.avg * h / 2);
m.pts = Math.round(e * k);
m.avg = Math.max(Math.ceil(l), Math.round(m.avg))
}
j.cast = Math.round(j.cast / 10) / 100;
return j
};
if (!$WH.wowheadRemote) {
$WH.g_ajaxIshRequest("/data=spell-scaling")
}
$WH.g_getDataSource = function() {
if ($WH.isset("g_pageInfo")) {
switch (g_pageInfo.type) {
case 3:
if ($WH.isset("g_items")) {
return g_items
}
case 6:
if ($WH.isset("g_spells")) {
return g_spells
}
}
}
return []
};
$WH.g_setJsonItemLevel = function(o, b) {
if (!o.scadist || !o.scaflags) {
return
}
o.bonuses = o.bonuses || {};
var f = o.scaflags & 255, h = (o.scaflags >> 8) & 255, l = (o.scaflags & (1 << 16)) != 0, k = (o.scaflags & (1 << 17)) != 0, a = (o.scaflags & (1 << 18)) != 0, d;
switch (f) {
case 5:
case 1:
case 7:
case 17:
d = 7;
break;
case 3:
case 12:
d = 8;
break;
case 16:
case 11:
d = 9;
break;
case 15:
d = 10;
break;
case 23:
case 21:
case 22:
case 13:
d = 11;
break;
default:
d = -1
}
if (d >= 0) {
for ( var e = 0; e < 10; ++e) {
var m = $WH.g_convertScalingFactor(b, d, o.scadist, e, 1);
if (m.n) {
o[m.n] = m.v
}
o.bonuses[m.s] = m.v
}
}
if (a) {
o.splpwr = o.bonuses[45] = $WH.g_convertScalingFactor(b, 6)
}
if (l) {
switch (f) {
case 3:
o.armor = $WH.g_convertScalingFactor(b, 11 + h);
break;
case 5:
o.armor = $WH.g_convertScalingFactor(b, 15 + h);
break;
case 1:
o.armor = $WH.g_convertScalingFactor(b, 19 + h);
break;
case 7:
o.armor = $WH.g_convertScalingFactor(b, 23 + h);
break;
case 16:
o.armor = $WH.g_convertScalingFactor(b, 28);
break;
default:
o.armor = 0
}
}
if (k) {
var j = (o.mledps ? "mle" : "rgd"), g;
switch (f) {
case 23:
case 21:
case 22:
case 13:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 2 : 0);
g = 0.3;
break;
case 17:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 3 : 1);
g = 0.2;
break;
case 15:
o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, h == 19 ? 5
: 4);
g = 0.3;
break;
default:
o.dps = o[j + "dps"] = 0;
g = 0
}
o.dmgmin = o[j + "dmgmin"] = Math.floor(o.dps * o.speed * (1 - g));
o.dmgmax = o[j + "dmgmax"] = Math.floor(o.dps * o.speed * (1 + g))
}
if (o.gearscore != null) {
if (o._gearscore == null) {
o._gearscore = o.gearscore
}
var c = Math.min(85, b + 1);
if (c >= 70) {
n = ((c - 70) * 9.5) + 105
} else {
if (c >= 60) {
n = ((c - 60) * 4.5) + 60
} else {
n = c + 5
}
}
o.gearscore = (o._gearscore * n) / 1.8
}
};
$WH.g_setJsonSpellLevel = function(a, b) {
if (!a.scadist) {
return
}
$WH.cO(a, $WH.g_convertScalingSpell(b, a.scadist))
};
$WH.g_getJsonReforge = function(b, c) {
if (!c) {
if (!$WH.g_reforgeStats) {
return []
}
if (!b.__reforge) {
b.__reforge = {}
}
if (!b.__reforge.all) {
b.__reforge.all = [];
for ( var c in $WH.g_reforgeStats) {
var d = $WH.g_getJsonReforge(b, c);
if (d.amount) {
b.__reforge.all.push(d)
}
}
}
return b.__reforge.all
}
if (!$WH.g_reforgeStats || !$WH.g_reforgeStats[c]) {
return {}
}
if (!b.__statidx) {
b.__statidx = {};
for ( var a in b) {
if ($WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]) {
b.__statidx[$WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]] = b[a]
} else {
b.__statidx[$WH.g_jsonToStat[a]] = b[a]
}
}
}
if (!b.__reforge) {
b.__reforge = {}
}
if (!b.__reforge[c]) {
var d = b.__reforge[c] = $WH.dO($WH.g_reforgeStats[c]);
b.__reforge[c].amount = Math.floor(d.v
* (b.__statidx[d.i1] && !b.__statidx[d.i2] ? b.__statidx[d.i1]
: 0))
}
return b.__reforge[c]
};
$WH.g_setTooltipLevel = function(g, a, l) {
var h = typeof g;
if (h == "number") {
var e = $WH.g_getDataSource();
if (e[g] && e[g][(l ? "buff_" : "tooltip_") + Locale.getName()]) {
g = e[g][(l ? "buff_" : "tooltip_") + Locale.getName()]
} else {
return g
}
} else {
if (h != "string") {
return g
}
}
h = g.match(/<!--\?([0-9:]*)-->/);
if (!h) {
return g
}
h = h[1].split(":");
var a = Math.min(parseInt(h[2]), Math.max(parseInt(h[1]), a)), b = parseInt(h[4]) || 0;
if (b) {
if (!g.match(/<!--pts[0-9](:[0-9])?-->/g)) {
var k = parseInt(h[5]) || 0, c = g.match(/<!--spd-->(\d\.\d+)/);
if (c) {
c = parseFloat(c[1]) || 0
}
var j = {
scadist : b,
scaflags : k,
speed : c
};
$WH.g_setJsonItemLevel(j, a);
g = g.replace(/(<!--asc(\d+)-->)([^<]+)/, function(p, m, o) {
h = o;
if (a < 40 && (o == 3 || o == 4)) {
--h
}
return m + g_itemset_types[h]
});
g = g.replace(/(<!--dmg-->)\d+(\D+)\d+/, function(p, m, o) {
return m + j.dmgmin + o + j.dmgmax
});
g = g.replace(/(<!--dps-->\D*?)(\d+\.\d)/, function(o, m) {
return m + j.dps.toFixed(1)
});
g = g.replace(/(<!--amr-->)\d+/, function(o, m) {
return m + j.armor
});
g = g
.replace(
/<span><!--stat(\d+)-->[-+]\d+(\D*?)<\/span>(<!--e-->)?(<!--ps-->)?(<br ?\/?>)?/gi,
function(r, o, m, t, u, p) {
var q, s = j.bonuses[o];
if (s) {
s = (s > 0 ? "+" : "-") + s;
q = "";
p = (p ? "<br />" : "")
} else {
s = "+0";
q = ' style="display: none"';
p = (p ? "<!--br-->" : "")
}
return "<span" + q + "><!--stat" + o + "-->"
+ s + m + "</span>" + (t || "")
+ (u || "") + p
});
g = g
.replace(
/<span class="q2">(.*?)<!--rtg(\d+)-->\d+(.*?)<\/span>(<br \/>)?/gi,
function(m, q, s, u, r, o, v) {
var p, t = j.bonuses[$WH.g_individualToGlobalStat[s]
|| s];
if (t) {
p = "";
v = (v ? "<br />" : "")
} else {
p = ' style="display: none"';
v = (v ? "<!--br-->" : "")
}
return '<span class="q2"' + p + ">" + q
+ "<!--rtg" + s + "-->" + t + u
+ "</span>" + v
})
} else {
var j = {
scadist : b
};
$WH.g_setJsonSpellLevel(j, a);
g = g.replace(/<!--cast-->\d+\.\d+/, "<!--cast-->" + j.cast);
if (j.effects) {
for ( var d = 1; d < 4; ++d) {
var f = j.effects[d];
g = g.replace(new RegExp("<!--pts" + d + "(:0)?-->(.+?)<",
"g"), "<!--pts" + d + "$1-->"
+ (f.min == f.max ? f.avg : f.min + " to " + f.max)
+ "<");
g = g.replace(
new RegExp("<!--pts" + d + ":1-->(.+?)<", "g"),
"<!--pts" + d + ":1-->" + f.min + "<");
g = g.replace(
new RegExp("<!--pts" + d + ":2-->(.+?)<", "g"),
"<!--pts" + d + ":2-->" + f.max + "<");
g = g.replace(new RegExp("<!--pts" + d
+ ":3:(\\d+)-->(.+?)<", "g"), function(o, m) {
return "<!--pts" + d + ":3:" + m + "-->" + (f.avg * m)
+ "<"
});
g = g.replace(
new RegExp("<!--pts" + d + ":4-->(.+?)<", "g"),
"<!--pts" + d + ":4-->" + f.pts + "<")
}
}
}
}
g = g.replace(/<!--ppl(\d+):(\d+):(\d+):(\d+)-->\s*\d+/gi, function(p, m,
o, q, r) {
return "<!--ppl"
+ m
+ ":"
+ o
+ ":"
+ q
+ ":"
+ r
+ "-->"
+ Math.round(parseInt(q) + (Math.min(Math.max(a, m), o) - m)
* r / 100)
});
g = g.replace(/(<!--rtg%(\d+)-->)([\.0-9]+)/g, function(p, m, q, o) {
h = g.match(new RegExp("<!--rtg" + q + "-->(\\d+)"));
if (!h) {
return p
}
return m + Math.round($WH.g_convertRatingToPercent(a, q, h[1]) * 100)
/ 100
});
g = g.replace(/(<!--\?\d+:\d+:\d+:)\d+/, "$1" + a);
g = g.replace(/<!--lvl-->\d+/g, "<!--lvl-->" + a);
return g
};
$WH.g_setTooltipSpells = function(h, e, g, c) {
var k = {}, j = "<!--sp([0-9]+):[01]-->.+?<!--sp\\1-->", d;
if (e == null) {
e = []
}
if (c == null) {
c = {}
}
for ( var b = 0; b < e.length; ++b) {
k[e[b]] = 1
}
if (d = h.match(new RegExp(j, "g"))) {
for ( var b = 0; b < d.length; ++b) {
var a = d[b].match(j)[1];
k[a] = (k[a] | 0);
if (c[a] == null) {
c[a] = -1
}
c[a]++;
if (g[a] == null || g[a][c[a]] == null || g[a][c[a]][k[a]] == null) {
continue
}
var f = g[a][c[a]][k[a]];
f = $WH.g_setTooltipSpells(f, e, g, c);
h = h.replace(d[b], "<!--sp" + a + ":" + k[a] + "-->" + f
+ "<!--sp" + a + "-->")
}
}
return h
};
$WH.g_enhanceTooltip = function(h, l, j, d, o, m, e) {
var k = typeof h, c;
if (k == "number") {
var g = $WH.g_getDataSource(), a = h;
if (g[a] && g[a][(o ? "buff_" : "tooltip_") + Locale.getName()]) {
h = g[a][(o ? "buff_" : "tooltip_") + Locale.getName()];
c = g[a][(o ? "buff" : "") + "spells_" + Locale.getName()];
if (c) {
h = $WH.g_setTooltipSpells(h, m, c)
}
} else {
return h
}
} else {
if (k != "string") {
return h
}
}
if (j) {
var b = $WH.g_getGets();
if (b.lvl) {
h = $WH.g_setTooltipLevel(h, b.lvl, o)
}
}
if (l) {
h = h
.replace(
/<span class="q2"><!--addamr(\d+)--><span>.*?<\/span><\/span>/i,
function(p, q) {
return '<span class="q2 tip" onmouseover="$WH.Tooltip.showAtCursor(event, $WH.sprintf(LANG.tooltip_armorbonus, '
+ q
+ '), 0, 0, \'q\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">'
+ p + "</span>"
});
h = h
.replace(
/\(([^\)]*?<!--lvl-->[^\(]*?)\)/gi,
function(q, p) {
return '(<a href="javascript:;" onmousedown="return false" class="tip" style="color: white; cursor: pointer" onclick="$WH.g_staticTooltipLevelClick(this, null, 0)" onmouseover="$WH.Tooltip.showAtCursor(event, \'<span class=\\\'q2\\\'>\' + LANG.tooltip_changelevel + \'</span>\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">'
+ p + "</a>)"
})
}
if (d && Slider) {
if (o && o.slider) {
o.bufftip = this
} else {
var k = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/);
if (k && k[2] != k[3]) {
this.slider = Slider.init(d, {
minValue : parseInt(k[2]),
maxValue : parseInt(k[3]),
onMove : $WH.g_tooltipSliderMove.bind(this)
});
Slider.setValue(this.slider, parseInt(k[4]));
this.slider.onmouseover = function(p) {
$WH.Tooltip.showAtCursor(p, LANG.tooltip_changelevel2, 0,
0, "q2")
};
this.slider.onmousemove = $WH.Tooltip.cursorUpdate;
this.slider.onmouseout = $WH.Tooltip.hide
}
}
}
if (e) {
if (o && o.modified) {
o.bufftip = this
} else {
for ( var f in c) {
if (!g_spells[f] || $WH.in_array(m, f) != -1) {
continue
}
$(e).append('<input type="checkbox" id="known-' + f + '" />')
.append(
'<label for="known-'
+ f
+ '"><a rel="spell='
+ f
+ "&know="
+ f
+ '">'
+ g_spells[f]["name_"
+ Locale.getName()]
+ (g_spells[f]["rank_"
+ Locale.getName()] ? " ("
+ g_spells[f]["rank_"
+ Locale.getName()]
+ ")" : "") + "</a></label>")
.append("<br />");
$("#known-" + f).change($WH.g_tooltipSpellsChange.bind(this))
}
}
this.modified = [ e, c, m ];
$(e).toggle(!$(e).is(":empty"))
}
return h
};
$WH.g_staticTooltipLevelClick = function(b, a, g, j) {
while (b.className.indexOf("tooltip") == -1) {
b = b.parentNode
}
var h = b.innerHTML;
h = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/);
if (!h) {
return
}
var k = parseInt(h[1]), e = parseInt(h[2]), f = parseInt(h[3]), d = parseInt(h[4]);
if (e >= f) {
return
}
if (!a) {
a = prompt($WH.sprintf(LANG.prompt_ratinglevel, e, f), d)
}
a = parseInt(a);
if (isNaN(a)) {
return
}
if (a == d || a < e || a > f) {
return
}
var c = $WH.g_getDataSource();
h = $WH.g_setTooltipLevel(c[k][(j ? "buff_" : "tooltip_")
+ Locale.getName()], a, j);
h = $WH.g_enhanceTooltip(h, true);
b.innerHTML = "<table><tr><td>"
+ h
+ '</td><th style="background-position: top right"></th></tr><tr><th style="background-position: bottom left"></th><th style="background-position: bottom right"></th></tr></table>';
$WH.Tooltip.fixSafe(b, 1, 1);
if (b.slider && !g) {
Slider.setValue(b.slider, a)
}
if (!j) {
($WH.g_tooltipSpellsChange.bind(b))()
}
};
$WH.g_tooltipSliderMove = function(c, b, a) {
$WH.g_staticTooltipLevelClick(this, a.value, 1);
if (this.bufftip) {
$WH.g_staticTooltipLevelClick(this.bufftip, a.value, 1, 1)
}
$WH.Tooltip.hide()
};
$WH.g_tooltipSpellsChange = function() {
if (!this.modified) {
return
}
var c = this.modified[0], a = this.modified[1], b = [];
$.each($("input:checked", c), function(d, e) {
b.push(parseInt(e.id.replace("known-", "")))
});
this.modified[2] = b;
this.innerHTML = $WH.g_setTooltipSpells(this.innerHTML, b, a);
if (this.bufftip) {
($WH.g_tooltipSpellsChange.bind(this.bufftip))()
}
};
$WH.Tooltip = {
create : function(j, l) {
var g = $WH.ce("div"), o = $WH.ce("table"), b = $WH.ce("tbody"), f = $WH
.ce("tr"), c = $WH.ce("tr"), a = $WH.ce("td"), m = $WH.ce("th"), k = $WH
.ce("th"), h = $WH.ce("th");
g.className = "wowhead-tooltip";
m.style.backgroundPosition = "top right";
k.style.backgroundPosition = "bottom left";
h.style.backgroundPosition = "bottom right";
if (j) {
a.innerHTML = j
}
$WH.ae(f, a);
$WH.ae(f, m);
$WH.ae(b, f);
$WH.ae(c, k);
$WH.ae(c, h);
$WH.ae(b, c);
$WH.ae(o, b);
if (!l) {
$WH.Tooltip.icon = $WH.ce("p");
/*$WH.Tooltip.icon.style.visibility = "hidden";*/
$WH.ae($WH.Tooltip.icon, $WH.ce("div"));
$WH.ae(g, $WH.Tooltip.icon)
}
$WH.ae(g, o);
if (!l) {
var e = $WH.ce("div");
e.className = "wowhead-tooltip-powered";
$WH.ae(g, e);
$WH.Tooltip.logo = e
}
return g
},
getMultiPartHtml : function(b, a) {
return "<table><tr><td>" + b + "</td></tr></table><table><tr><td>" + a
+ "</td></tr></table>"
},
fix : function(d, b, f) {
var e = $WH.gE(d, "table")[0], h = $WH.gE(e, "td")[0], g = h.childNodes;
d.className = $WH.trim(d.className.replace("tooltip-slider", ""));
if (g.length >= 2 && g[0].nodeName == "TABLE"
&& g[1].nodeName == "TABLE") {
g[0].style.whiteSpace = "nowrap";
var a = parseInt(d.style.width);
if (!d.slider || !a) {
if (g[1].offsetWidth > 300) {
a = Math.max(300, g[0].offsetWidth) + 20
} else {
a = Math.max(g[0].offsetWidth, g[1].offsetWidth) + 20
}
}
a = Math.min(320, a);
if (a > 20) {
d.style.width = a + "px";
g[0].style.width = g[1].style.width = "100%";
if (d.slider) {
Slider.setSize(d.slider, a - 6);
d.className += " tooltip-slider"
}
if (!b && d.offsetHeight > document.body.clientHeight) {
e.className = "shrink"
}
}
}
if (f) {
d.style.visibility = "visible"
}
},
fixSafe : function(c, b, a) {
$WH.Tooltip.fix(c, b, a)
},
append : function(c, b) {
var c = $WH.ge(c);
var a = $WH.Tooltip.create(b);
$WH.ae(c, a);
$WH.Tooltip.fixSafe(a, 1, 1)
},
prepare : function() {
if ($WH.Tooltip.tooltip) {
return
}
var a = $WH.Tooltip.create();
a.style.position = "absolute";
a.style.left = a.style.top = "-2323px";
$WH.ae(document.body, a);
$WH.Tooltip.tooltip = a;
$WH.Tooltip.tooltipTable = $WH.gE(a, "table")[0];
$WH.Tooltip.tooltipTd = $WH.gE(a, "td")[0];
var a = $WH.Tooltip.create(null, true);
a.style.position = "absolute";
a.style.left = a.style.top = "-2323px";
$WH.ae(document.body, a);
$WH.Tooltip.tooltip2 = a;
$WH.Tooltip.tooltipTable2 = $WH.gE(a, "table")[0];
$WH.Tooltip.tooltipTd2 = $WH.gE(a, "td")[0]
},
set : function(c, b) {
var a = $WH.Tooltip.tooltip;
a.style.width = "550px";
a.style.left = "-2323px";
a.style.top = "-2323px";
if (c.nodeName) {
$WH.ee($WH.Tooltip.tooltipTd);
$WH.ae($WH.Tooltip.tooltipTd, c)
} else {
$WH.Tooltip.tooltipTd.innerHTML = c
}
a.style.display = "";
$WH.Tooltip.fix(a, 0, 0);
if (b) {
$WH.Tooltip.showSecondary = true;
var a = $WH.Tooltip.tooltip2;
a.style.width = "550px";
a.style.left = "-2323px";
a.style.top = "-2323px";
if (b.nodeName) {
$WH.ee($WH.Tooltip.tooltipTd2);
$WH.ae($WH.Tooltip.tooltipTd2, b)
} else {
$WH.Tooltip.tooltipTd2.innerHTML = b
}
a.style.display = "";
$WH.Tooltip.fix(a, 0, 0)
} else {
$WH.Tooltip.showSecondary = false
}
},
moveTests : [ [ null, null ], [ null, false ], [ false, null ],
[ false, false ] ],
move : function(q, p, e, r, d, b) {
if (!$WH.Tooltip.tooltipTable) {
return
}
var o = $WH.Tooltip.tooltip, j = $WH.Tooltip.tooltipTable.offsetWidth, c = $WH.Tooltip.tooltipTable.offsetHeight, l = $WH.Tooltip.tooltip2, g = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth
: 0, a = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight
: 0, s;
o.style.width = j + "px";
l.style.width = g + "px";
var m, f;
for ( var h = 0, k = $WH.Tooltip.moveTests.length; h < k; ++h) {
s = $WH.Tooltip.moveTests[h];
m = $WH.Tooltip.moveTest(q, p, e, r, d, b, s[0], s[1]);
if ($WH.isset("Ads") && !Ads.intersect(m)) {
f = true;
break
} else {
if (!$WH.isset("Ads")) {
break
}
}
}
if ($WH.isset("Ads") && !f) {
Ads.intersect(m, true)
}
o.style.left = m.l + "px";
o.style.top = m.t + "px";
o.style.visibility = "visible";
if ($WH.Tooltip.showSecondary) {
l.style.left = m.l + j + "px";
l.style.top = m.t + "px";
l.style.visibility = "visible"
}
},
moveTest : function(e, o, r, C, c, a, q, b) {
var m = e, A = o, g = $WH.Tooltip.tooltip, k = $WH.Tooltip.tooltipTable.offsetWidth, t = $WH.Tooltip.tooltipTable.offsetHeight, p = $WH.Tooltip.tooltip2, B = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth
: 0, f = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight
: 0, j = $WH.g_getWindowSize(), l = $WH.g_getScroll(), h = j.w, s = j.h, d = l.x, z = l.y, y = d, w = z, v = d
+ h, u = z + s;
if (q == null) {
q = (e + r + k + B <= v)
}
if (b == null) {
b = (o - Math.max(t, f) >= w)
}
if (q) {
e += r + c
} else {
e = Math.max(e - (k + B), y) - c
}
if (b) {
o -= Math.max(t, f) + a
} else {
o += C + a
}
if (e < y) {
e = y
} else {
if (e + k + B > v) {
e = v - (k + B)
}
}
if (o < w) {
o = w
} else {
if (o + Math.max(t, f) > u) {
o = Math.max(z, u - Math.max(t, f))
}
}
if ($WH.Tooltip.iconVisible) {
if (m >= e - 48 && m <= e && A >= o - 4 && A <= o + 48) {
o -= 48 - (A - o)
}
}
return $WH.g_createRect(e, o, k, t)
},
show : function(g, f, d, b, c, e) {
if ($WH.Tooltip.disabled) {
return
}
if (!d || d < 1) {
d = 1
}
if (!b || b < 1) {
b = 1
}
if (c) {
f = '<span class="' + c + '">' + f + "</span>"
}
var a = $WH.ac(g);
$WH.Tooltip.prepare();
$WH.Tooltip.set(f, e);
$WH.Tooltip.move(a.x, a.y, g.offsetWidth, g.offsetHeight, d, b)
},
showAtCursor : function(f, g, c, a, b, d) {
if ($WH.Tooltip.disabled) {
return
}
if (!c || c < 10) {
c = 10
}
if (!a || a < 10) {
a = 10
}
if (b) {
g = '<span class="' + b + '">' + g + "</span>";
if (d) {
d = '<span class="' + b + '">' + d + "</span>"
}
}
f = $WH.$E(f);
var h = $WH.g_getCursorPos(f);
$WH.Tooltip.prepare();
$WH.Tooltip.set(g, d);
$WH.Tooltip.move(h.x, h.y, 0, 0, c, a)
},
showAtXY : function(e, a, f, c, b, d) {
if ($WH.Tooltip.disabled) {
return
}
$WH.Tooltip.prepare();
$WH.Tooltip.set(e, d);
$WH.Tooltip.move(a, f, 0, 0, c, b)
},
cursorUpdate : function(b, a, d) {
if ($WH.Tooltip.disabled || !$WH.Tooltip.tooltip) {
return
}
b = $WH.$E(b);
if (!a || a < 10) {
a = 10
}
if (!d || d < 10) {
d = 10
}
var c = $WH.g_getCursorPos(b);
$WH.Tooltip.move(c.x, c.y, 0, 0, a, d)
},
hide : function() {
if ($WH.Tooltip.tooltip) {
$WH.Tooltip.tooltip.style.display = "none";
$WH.Tooltip.tooltip.visibility = "hidden";
$WH.Tooltip.tooltipTable.className = "";
$WH.Tooltip.setIcon(null);
if ($WH.isset("Ads")) {
Ads.restoreHidden()
}
}
if ($WH.Tooltip.tooltip2) {
$WH.Tooltip.tooltip2.style.display = "none";
$WH.Tooltip.tooltip2.visibility = "hidden";
$WH.Tooltip.tooltipTable2.className = ""
}
},
setIcon : function(a) {
$WH.Tooltip.prepare();
if (a) {
$WH.Tooltip.icon.style.backgroundImage = "url(https://wowimg.zamimg.com/images/wow/icons/medium/"
+ a.toLowerCase() + ".jpg)";
$WH.Tooltip.icon.style.visibility = "visible"
} else {
$WH.Tooltip.icon.style.backgroundImage = "none";
$WH.Tooltip.icon.style.visibility = "hidden"
}
$WH.Tooltip.iconVisible = a ? 1 : 0
}
};
if ($WH.isset("$WowheadPower")) {
$WowheadPower.init()
}
$WH.g_getProfileIcon = function(d, e, a, g, c, b) {
var f = {
10 : {
6 : 1,
3 : 1,
8 : 1,
2 : 1,
5 : 1,
4 : 1,
9 : 1
},
11 : {
6 : 1,
3 : 1,
8 : 1,
2 : 1,
5 : 1,
7 : 1,
1 : 1
},
3 : {
6 : 1,
3 : 1,
2 : 1,
5 : 1,
4 : 1,
1 : 1
},
7 : {
6 : 1,
8 : 1,
4 : 1,
9 : 1,
1 : 1
},
1 : {
6 : 1,
8 : 1,
2 : 1,
5 : 1,
4 : 1,
9 : 1,
1 : 1
},
4 : {
6 : 1,
11 : 1,
3 : 1,
5 : 1,
4 : 1,
1 : 1
},
2 : {
6 : 1,
3 : 1,
4 : 1,
7 : 1,
9 : 1,
1 : 1
},
6 : {
6 : 1,
11 : 1,
3 : 1,
7 : 1,
1 : 1
},
8 : {
6 : 1,
3 : 1,
8 : 1,
5 : 1,
4 : 1,
7 : 1,
1 : 1
},
5 : {
6 : 1,
8 : 1,
5 : 1,
4 : 1,
9 : 1,
1 : 1
}
};
if (c) {
return isNaN(c) ? c : "/profile=avatar" + (b ? "&size=" + b : "")
+ "&id=" + c + (b == "tiny" ? ".gif" : ".jpg")
}
if (!g_file_races[d] || !g_file_classes[e] || !g_file_genders[a] || !f[d]
|| !f[d][e] || (e == 6 && g < 55)) {
return "inv_misc_questionmark"
}
return "chr_" + g_file_races[d] + "_" + g_file_genders[a] + "_"
+ g_file_classes[e] + "0"
+ (g > 59 ? (Math.floor((g - 60) / 10) + 2) : 1)
};
| bbDKP/bbTips | root/adm/style/dkp/bbtips/basic.js | JavaScript | gpl-2.0 | 40,700 |
<?php $captcha_word = 'R75S'; ?> | CoordCulturaDigital-Minc/setoriais | wp-content/plugins/si-captcha-for-wordpress/captcha/temp/sQ5mnMOQmEJcMCR2.php | PHP | gpl-2.0 | 32 |
/* This file is part of the KDE project
Copyright (C) 2004 David Faure <faure@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kio_trash.h"
#include <kio/job.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <klargefile.h>
#include <kcmdlineargs.h>
#include <kmimetype.h>
#include <kprocess.h>
#include <dcopclient.h>
#include <qdatastream.h>
#include <qtextstream.h>
#include <qfile.h>
#include <qeventloop.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
static const KCmdLineOptions options[] =
{
{ "+protocol", I18N_NOOP( "Protocol name" ), 0 },
{ "+pool", I18N_NOOP( "Socket name" ), 0 },
{ "+app", I18N_NOOP( "Socket name" ), 0 },
KCmdLineLastOption
};
extern "C" {
int KDE_EXPORT kdemain( int argc, char **argv )
{
//KInstance instance( "kio_trash" );
// KApplication is necessary to use kio_file
putenv(strdup("SESSION_MANAGER="));
KApplication::disableAutoDcopRegistration();
KCmdLineArgs::init(argc, argv, "kio_trash", 0, 0, 0, 0);
KCmdLineArgs::addCmdLineOptions( options );
KApplication app( false, false );
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
TrashProtocol slave( args->arg(0), args->arg(1), args->arg(2) );
slave.dispatchLoop();
return 0;
}
}
#define INIT_IMPL \
if ( !impl.init() ) { \
error( impl.lastErrorCode(), impl.lastErrorMessage() ); \
return; \
}
TrashProtocol::TrashProtocol( const QCString& protocol, const QCString &pool, const QCString &app)
: SlaveBase(protocol, pool, app )
{
struct passwd *user = getpwuid( getuid() );
if ( user )
m_userName = QString::fromLatin1(user->pw_name);
struct group *grp = getgrgid( getgid() );
if ( grp )
m_groupName = QString::fromLatin1(grp->gr_name);
}
TrashProtocol::~TrashProtocol()
{
}
void TrashProtocol::restore( const KURL& trashURL )
{
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( trashURL, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( trashURL.prettyURL() ) );
return;
}
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
KURL dest;
dest.setPath( info.origPath );
if ( !relativePath.isEmpty() )
dest.addPath( relativePath );
// Check that the destination directory exists, to improve the error code in case it doesn't.
const QString destDir = dest.directory();
KDE_struct_stat buff;
if ( KDE_lstat( QFile::encodeName( destDir ), &buff ) == -1 ) {
error( KIO::ERR_SLAVE_DEFINED,
i18n( "The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. "
"You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it." ).arg( destDir ) );
return;
}
copyOrMove( trashURL, dest, false /*overwrite*/, Move );
}
void TrashProtocol::rename( const KURL &oldURL, const KURL &newURL, bool overwrite )
{
INIT_IMPL;
kdDebug()<<"TrashProtocol::rename(): old="<<oldURL<<" new="<<newURL<<" overwrite=" << overwrite<<endl;
if ( oldURL.protocol() == "trash" && newURL.protocol() == "trash" ) {
error( KIO::ERR_CANNOT_RENAME, oldURL.prettyURL() );
return;
}
copyOrMove( oldURL, newURL, overwrite, Move );
}
void TrashProtocol::copy( const KURL &src, const KURL &dest, int /*permissions*/, bool overwrite )
{
INIT_IMPL;
kdDebug()<<"TrashProtocol::copy(): " << src << " " << dest << endl;
if ( src.protocol() == "trash" && dest.protocol() == "trash" ) {
error( KIO::ERR_UNSUPPORTED_ACTION, i18n( "This file is already in the trash bin." ) );
return;
}
copyOrMove( src, dest, overwrite, Copy );
}
void TrashProtocol::copyOrMove( const KURL &src, const KURL &dest, bool overwrite, CopyOrMove action )
{
if ( src.protocol() == "trash" && dest.isLocalFile() ) {
// Extracting (e.g. via dnd). Ignore original location stored in info file.
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( src, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( src.prettyURL() ) );
return;
}
const QString destPath = dest.path();
if ( QFile::exists( destPath ) ) {
if ( overwrite ) {
ok = QFile::remove( destPath );
Q_ASSERT( ok ); // ### TODO
} else {
error( KIO::ERR_FILE_ALREADY_EXIST, destPath );
return;
}
}
if ( action == Move ) {
kdDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.moveFromTrash( destPath, trashId, fileId, relativePath );
} else { // Copy
kdDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.copyFromTrash( destPath, trashId, fileId, relativePath );
}
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
if ( action == Move && relativePath.isEmpty() )
(void)impl.deleteInfo( trashId, fileId );
finished();
}
return;
} else if ( src.isLocalFile() && dest.protocol() == "trash" ) {
QString dir = dest.directory();
//kdDebug() << "trashing a file to " << dir << endl;
// Trashing a file
// We detect the case where this isn't normal trashing, but
// e.g. if kwrite tries to save (moving tempfile over destination)
if ( dir.length() <= 1 && src.fileName() == dest.fileName() ) // new toplevel entry
{
const QString srcPath = src.path();
// In theory we should use TrashImpl::parseURL to give the right filename to createInfo,
// in case the trash URL didn't contain the same filename as srcPath.
// But this can only happen with copyAs/moveAs, not available in the GUI
// for the trash (New/... or Rename from iconview/listview).
int trashId;
QString fileId;
if ( !impl.createInfo( srcPath, trashId, fileId ) ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
bool ok;
if ( action == Move ) {
kdDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.moveToTrash( srcPath, trashId, fileId );
} else { // Copy
kdDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl;
ok = impl.copyToTrash( srcPath, trashId, fileId );
}
if ( !ok ) {
(void)impl.deleteInfo( trashId, fileId );
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
// Inform caller of the final URL. Used by konq_undo.
const KURL url = impl.makeURL( trashId, fileId, QString::null );
setMetaData( "trashURL-" + srcPath, url.url() );
finished();
}
}
return;
} else {
kdDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory" << endl;
// It's not allowed to add a file to an existing trash directory.
error( KIO::ERR_ACCESS_DENIED, dest.prettyURL() );
return;
}
} else
error( KIO::ERR_UNSUPPORTED_ACTION, "should never happen" );
}
static void addAtom(KIO::UDSEntry& entry, unsigned int ID, long long l, const QString& s = QString::null)
{
KIO::UDSAtom atom;
atom.m_uds = ID;
atom.m_long = l;
atom.m_str = s;
entry.append(atom);
}
void TrashProtocol::createTopLevelDirEntry(KIO::UDSEntry& entry)
{
entry.clear();
addAtom(entry, KIO::UDS_NAME, 0, ".");
addAtom(entry, KIO::UDS_FILE_TYPE, S_IFDIR);
addAtom(entry, KIO::UDS_ACCESS, 0700);
addAtom(entry, KIO::UDS_MIME_TYPE, 0, "inode/directory");
addAtom(entry, KIO::UDS_USER, 0, m_userName);
addAtom(entry, KIO::UDS_GROUP, 0, m_groupName);
}
void TrashProtocol::stat(const KURL& url)
{
INIT_IMPL;
const QString path = url.path();
if( path.isEmpty() || path == "/" ) {
// The root is "virtual" - it's not a single physical directory
KIO::UDSEntry entry;
createTopLevelDirEntry( entry );
statEntry( entry );
finished();
} else {
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
// ######## do we still need this?
kdDebug() << k_funcinfo << url << " looks fishy, returning does-not-exist" << endl;
// A URL like trash:/file simply means that CopyJob is trying to see if
// the destination exists already (it made up the URL by itself).
error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() );
//error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
const QString filePath = impl.physicalPath( trashId, fileId, relativePath );
if ( filePath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
QString fileName = filePath.section('/', -1, -1, QString::SectionSkipEmpty);
QString fileURL = QString::null;
if ( url.path().length() > 1 ) {
fileURL = url.url();
}
KIO::UDSEntry entry;
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( ok )
ok = createUDSEntry( filePath, fileName, fileURL, entry, info );
if ( !ok ) {
error( KIO::ERR_COULD_NOT_STAT, url.prettyURL() );
}
statEntry( entry );
finished();
}
}
void TrashProtocol::del( const KURL &url, bool /*isfile*/ )
{
int trashId;
QString fileId, relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
ok = relativePath.isEmpty();
if ( !ok ) {
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
return;
}
ok = impl.del(trashId, fileId);
if ( !ok ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
finished();
}
void TrashProtocol::listDir(const KURL& url)
{
INIT_IMPL;
kdDebug() << "listdir: " << url << endl;
if ( url.path().length() <= 1 ) {
listRoot();
return;
}
int trashId;
QString fileId;
QString relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
//was: const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath );
// Get info for deleted directory - the date of deletion and orig path will be used
// for all the items in it, and we need the physicalPath.
TrashedFileInfo info;
ok = impl.infoForFile( trashId, fileId, info );
if ( !ok || info.physicalPath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
if ( !relativePath.isEmpty() ) {
info.physicalPath += "/";
info.physicalPath += relativePath;
}
// List subdir. Can't use kio_file here since we provide our own info...
kdDebug() << k_funcinfo << "listing " << info.physicalPath << endl;
QStrList entryNames = impl.listDir( info.physicalPath );
totalSize( entryNames.count() );
KIO::UDSEntry entry;
QStrListIterator entryIt( entryNames );
for (; entryIt.current(); ++entryIt) {
QString fileName = QFile::decodeName( entryIt.current() );
if ( fileName == ".." )
continue;
const QString filePath = info.physicalPath + "/" + fileName;
// shouldn't be necessary
//const QString url = TrashImpl::makeURL( trashId, fileId, relativePath + "/" + fileName );
entry.clear();
TrashedFileInfo infoForItem( info );
infoForItem.origPath += '/';
infoForItem.origPath += fileName;
if ( ok && createUDSEntry( filePath, fileName, QString::null /*url*/, entry, infoForItem ) ) {
listEntry( entry, false );
}
}
entry.clear();
listEntry( entry, true );
finished();
}
bool TrashProtocol::createUDSEntry( const QString& physicalPath, const QString& fileName, const QString& url, KIO::UDSEntry& entry, const TrashedFileInfo& info )
{
QCString physicalPath_c = QFile::encodeName( physicalPath );
KDE_struct_stat buff;
if ( KDE_lstat( physicalPath_c, &buff ) == -1 ) {
kdWarning() << "couldn't stat " << physicalPath << endl;
return false;
}
if (S_ISLNK(buff.st_mode)) {
char buffer2[ 1000 ];
int n = readlink( physicalPath_c, buffer2, 1000 );
if ( n != -1 ) {
buffer2[ n ] = 0;
}
addAtom( entry, KIO::UDS_LINK_DEST, 0, QFile::decodeName( buffer2 ) );
// Follow symlink
// That makes sense in kio_file, but not in the trash, especially for the size
// #136876
#if 0
if ( KDE_stat( physicalPath_c, &buff ) == -1 ) {
// It is a link pointing to nowhere
buff.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
buff.st_mtime = 0;
buff.st_atime = 0;
buff.st_size = 0;
}
#endif
}
mode_t type = buff.st_mode & S_IFMT; // extract file type
mode_t access = buff.st_mode & 07777; // extract permissions
access &= 07555; // make it readonly, since it's in the trashcan
addAtom( entry, KIO::UDS_NAME, 0, fileName );
addAtom( entry, KIO::UDS_FILE_TYPE, type );
if ( !url.isEmpty() )
addAtom( entry, KIO::UDS_URL, 0, url );
KMimeType::Ptr mt = KMimeType::findByPath( physicalPath, buff.st_mode );
addAtom( entry, KIO::UDS_MIME_TYPE, 0, mt->name() );
addAtom( entry, KIO::UDS_ACCESS, access );
addAtom( entry, KIO::UDS_SIZE, buff.st_size );
addAtom( entry, KIO::UDS_USER, 0, m_userName ); // assumption
addAtom( entry, KIO::UDS_GROUP, 0, m_groupName ); // assumption
addAtom( entry, KIO::UDS_MODIFICATION_TIME, buff.st_mtime );
addAtom( entry, KIO::UDS_ACCESS_TIME, buff.st_atime ); // ## or use it for deletion time?
addAtom( entry, KIO::UDS_EXTRA, 0, info.origPath );
addAtom( entry, KIO::UDS_EXTRA, 0, info.deletionDate.toString( Qt::ISODate ) );
return true;
}
void TrashProtocol::listRoot()
{
INIT_IMPL;
const TrashedFileInfoList lst = impl.list();
totalSize( lst.count() );
KIO::UDSEntry entry;
createTopLevelDirEntry( entry );
listEntry( entry, false );
for ( TrashedFileInfoList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) {
const KURL url = TrashImpl::makeURL( (*it).trashId, (*it).fileId, QString::null );
KURL origURL;
origURL.setPath( (*it).origPath );
entry.clear();
if ( createUDSEntry( (*it).physicalPath, origURL.fileName(), url.url(), entry, *it ) )
listEntry( entry, false );
}
entry.clear();
listEntry( entry, true );
finished();
}
void TrashProtocol::special( const QByteArray & data )
{
INIT_IMPL;
QDataStream stream( data, IO_ReadOnly );
int cmd;
stream >> cmd;
switch (cmd) {
case 1:
if ( impl.emptyTrash() )
finished();
else
error( impl.lastErrorCode(), impl.lastErrorMessage() );
break;
case 2:
impl.migrateOldTrash();
finished();
break;
case 3:
{
KURL url;
stream >> url;
restore( url );
break;
}
default:
kdWarning(7116) << "Unknown command in special(): " << cmd << endl;
error( KIO::ERR_UNSUPPORTED_ACTION, QString::number(cmd) );
break;
}
}
void TrashProtocol::put( const KURL& url, int /*permissions*/, bool /*overwrite*/, bool /*resume*/ )
{
INIT_IMPL;
kdDebug() << "put: " << url << endl;
// create deleted file. We need to get the mtime and original location from metadata...
// Maybe we can find the info file for url.fileName(), in case ::rename() was called first, and failed...
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
}
void TrashProtocol::get( const KURL& url )
{
INIT_IMPL;
kdDebug() << "get() : " << url << endl;
if ( !url.isValid() ) {
kdDebug() << kdBacktrace() << endl;
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.url() ) );
return;
}
if ( url.path().length() <= 1 ) {
error( KIO::ERR_IS_DIRECTORY, url.prettyURL() );
return;
}
int trashId;
QString fileId;
QString relativePath;
bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath );
if ( !ok ) {
error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) );
return;
}
const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath );
if ( physicalPath.isEmpty() ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
return;
}
// Usually we run jobs in TrashImpl (for e.g. future kdedmodule)
// But for this one we wouldn't use DCOP for every bit of data...
KURL fileURL;
fileURL.setPath( physicalPath );
KIO::Job* job = KIO::get( fileURL );
connect( job, SIGNAL( data( KIO::Job*, const QByteArray& ) ),
this, SLOT( slotData( KIO::Job*, const QByteArray& ) ) );
connect( job, SIGNAL( mimetype( KIO::Job*, const QString& ) ),
this, SLOT( slotMimetype( KIO::Job*, const QString& ) ) );
connect( job, SIGNAL( result(KIO::Job *) ),
this, SLOT( jobFinished(KIO::Job *) ) );
qApp->eventLoop()->enterLoop();
}
void TrashProtocol::slotData( KIO::Job*, const QByteArray&arr )
{
data( arr );
}
void TrashProtocol::slotMimetype( KIO::Job*, const QString& mt )
{
mimeType( mt );
}
void TrashProtocol::jobFinished( KIO::Job* job )
{
if ( job->error() )
error( job->error(), job->errorText() );
else
finished();
qApp->eventLoop()->exitLoop();
}
#if 0
void TrashProtocol::mkdir( const KURL& url, int /*permissions*/ )
{
INIT_IMPL;
// create info about deleted dir
// ############ Problem: we don't know the original path.
// Let's try to avoid this case (we should get to copy() instead, for local files)
kdDebug() << "mkdir: " << url << endl;
QString dir = url.directory();
if ( dir.length() <= 1 ) // new toplevel entry
{
// ## we should use TrashImpl::parseURL to give the right filename to createInfo
int trashId;
QString fileId;
if ( !impl.createInfo( url.path(), trashId, fileId ) ) {
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else {
if ( !impl.mkdir( trashId, fileId, permissions ) ) {
(void)impl.deleteInfo( trashId, fileId );
error( impl.lastErrorCode(), impl.lastErrorMessage() );
} else
finished();
}
} else {
// Well it's not allowed to add a directory to an existing deleted directory.
error( KIO::ERR_ACCESS_DENIED, url.prettyURL() );
}
}
#endif
#include "kio_trash.moc"
| iegor/kdebase | kioslave/trash/kio_trash.cpp | C++ | gpl-2.0 | 20,976 |
import unittest
from mock import Mock
import os
from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase
from katello.tests.core.repo import repo_data
import katello.client.core.repo
from katello.client.core.repo import Status
from katello.client.api.utils import ApiDataError
class RequiredCLIOptionsTests(CLIOptionTestCase):
#repo is defined by either (org, product, repo_name, env name) or repo_id
action = Status()
disallowed_options = [
('--name=repo1', '--product=product1'),
('--org=ACME', '--name=repo1'),
('--org=ACME', '--product=product1'),
(),
]
allowed_options = [
('--org=ACME', '--name=repo1', '--product=product1'),
('--id=repo_id1', ),
]
class RepoStatusTest(CLIActionTestCase):
ORG_NAME = "org_1"
PROD_NAME = "product_1"
REPO = repo_data.REPOS[0]
ENV_NAME = "env_1"
OPTIONS_WITH_ID = {
'id': REPO['id'],
}
OPTIONS_WITH_NAME = {
'name': REPO['name'],
'product': PROD_NAME,
'org': ORG_NAME,
'environment': ENV_NAME,
}
repo = None
def setUp(self):
self.set_action(Status())
self.set_module(katello.client.core.repo)
self.mock_printer()
self.mock_options(self.OPTIONS_WITH_NAME)
self.mock(self.action.api, 'repo', self.REPO)
self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RESULT_WITHOUT_ERROR)
self.repo = self.mock(self.module, 'get_repo', self.REPO).return_value
def tearDown(self):
self.restore_mocks()
def test_finds_repo_by_id(self):
self.mock_options(self.OPTIONS_WITH_ID)
self.run_action()
self.action.api.repo.assert_called_once_with(self.REPO['id'])
def test_finds_repo_by_name(self):
self.mock_options(self.OPTIONS_WITH_NAME)
self.run_action()
self.module.get_repo.assert_called_once_with(self.ORG_NAME,
self.REPO['name'],
self.PROD_NAME, None,
None, self.ENV_NAME,
False, None, None, None)
def test_returns_with_error_when_no_repo_found(self):
self.mock_options(self.OPTIONS_WITH_NAME)
self.mock(self.module, 'get_repo').side_effect = ApiDataError()
self.run_action(os.EX_DATAERR)
def test_it_calls_last_sync_status_api(self):
self.run_action()
self.action.api.last_sync_status.assert_called_once_with(self.REPO['id'])
def test_it_does_not_set_progress_for_not_running_sync(self):
self.run_action()
self.assertRaises(KeyError, lambda: self.repo['progress'] )
def test_it_sets_progress_for_running_sync(self):
self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RUNNING_RESULT)
self.run_action()
self.assertTrue(isinstance(self.repo['progress'], str))
| Katello/katello-cli | test/katello/tests/core/repo/repo_status_test.py | Python | gpl-2.0 | 3,038 |
<?php
/**
* Created by PhpStorm.
* User: tiemanntan
* Date: 16/11/15
* Time: 16:51
*/
class Nextorder_Yandexmetrica_Block_Adminhtml_System_Config_Result
extends Mage_Adminhtml_Block_Abstract
implements Varien_Data_Form_Element_Renderer_Interface{
public function render(Varien_Data_Form_Element_Abstract $element){
$countID = Mage::helper('yandexmetrica/data')->getCountID();
$resultURL = "https://metrika.yandex.ru/dashboard?id=". $countID;
$html ="<button type='button' id='result'><a style='color:white' href='". $resultURL ."'>Analyse Result bei Yandex Dashboard</a></button>";
return $html;
}
} | fatalerrortan/Magento_Yandexmetrica | app/code/local/Nextorder/Yandexmetrica/Block/Adminhtml/System/Config/Result.php | PHP | gpl-2.0 | 657 |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2010
* Mayte Lázaro, Alejandro R. Mosteo
*
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SUB_OPT_H_
#define SUB_OPT_H_
#include "transf.hh"
void EIFnn(Matrix H, Matrix G, Matrix h, Matrix S, Matrix &F, Matrix &N);
void CalculateEstimationEIFnn(Matrix Fk, Matrix Nk, Matrix &x, Matrix &P);
#endif /* SUB_OPT_H_ */
| swem/player-git-svn | server/drivers/localization/ekfvloc/sub_opt.hh | C++ | gpl-2.0 | 1,106 |
//SpikeStream includes
#include "Globals.h"
#include "NetworkDisplay.h"
#include "ConnectionGroupModel.h"
#include "SpikeStreamException.h"
using namespace spikestream;
//Qt includes
#include <QDebug>
#include <QIcon>
/*! Constructor */
ConnectionGroupModel::ConnectionGroupModel() : QAbstractTableModel(){
connect(Globals::getEventRouter(), SIGNAL(networkChangedSignal()), this, SLOT(loadConnectionGroups()));
connect(Globals::getEventRouter(), SIGNAL(showAllOrNoneConnectionsSignal()), this, SLOT(showAllOrNone()));
}
/*! Destructor */
ConnectionGroupModel::~ConnectionGroupModel(){
}
/*--------------------------------------------------------*/
/*------- PUBLIC METHODS -------*/
/*--------------------------------------------------------*/
/*! Clears the list of selected neuron groups */
void ConnectionGroupModel::clearSelection(){
selectionMap.clear();
}
/*! Inherited from QAbstractTableModel. Returns the number of columns in the model */
int ConnectionGroupModel::columnCount(const QModelIndex&) const{
return NUM_COLS;
}
/*! Inherited from QAbstractTableModel. Returns the data at the specified model index
ready to be displayed in the way requested */
QVariant ConnectionGroupModel::data(const QModelIndex & index, int role) const{
//Return invalid index if index is invalid or no network loaded
if (!index.isValid())
return QVariant();
if(!Globals::networkLoaded())
return QVariant();
//Check rows and columns are in range
if (index.row() < 0 || index.row() >= rowCount() || index.column() < 0 || index.column() >= columnCount())
return QVariant();
//Return appropriate data
if (role == Qt::DisplayRole){
if(index.column() == ID_COL)
return conGrpInfoList[index.row()].getID();
if(index.column() == DESC_COL)
return conGrpInfoList[index.row()].getDescription();
if(index.column() == SIZE_COL)
return conGrpSizeList[index.row()];
if(index.column() == FROM_NEUR_ID_COL)
return conGrpInfoList[index.row()].getFromNeuronGroupID();
if(index.column() == T0_NEUR_ID_COL)
return conGrpInfoList[index.row()].getToNeuronGroupID();
if(index.column() == SYNAPSE_TYPE_COL)
return conGrpInfoList[index.row()].getSynapseTypeID();
}
//Icons
if (role == Qt::DecorationRole){
if(index.column() == VIS_COL ){
if(Globals::getNetworkDisplay()->connectionGroupVisible(conGrpInfoList[index.row()].getID()))
return QIcon(Globals::getSpikeStreamRoot() + "/images/visible.xpm");
return QIcon(Globals::getSpikeStreamRoot() + "/images/hidden.xpm");
}
if(index.column() == PARAM_COL){
return QIcon(Globals::getSpikeStreamRoot() + "/images/parameters.xpm");
}
}
if(role == Qt::SizeHintRole){
if(index.column() == PARAM_COL){
return QSize(50, 18);
}
}
//Check boxes
if(role == Qt::CheckStateRole){
if(index.column() == SELECT_COL){
if(selectionMap.contains(index.row())){
return true;
}
else {
return false;
}
}
}
//If we have reached this point ignore request
return QVariant();
}
/*! Returns the connection group info corresponding to a particular row or throws
an exception if this cannot be found. */
ConnectionGroupInfo ConnectionGroupModel::getInfo(const QModelIndex & index){
if(index.row() >= conGrpInfoList.size())
throw SpikeStreamException("Index out of range: " + QString::number(index.row()));
return conGrpInfoList[index.row()];
}
/*! Returns the parameters associated with a connection group */
QHash<QString, double> ConnectionGroupModel::getParameters(int row){
if(row >= rowCount())
throw SpikeStreamException("Failed to get parameters: row out of range: " + QString::number(row));
return conGrpInfoList[row].getParameterMap();
}
/*! Returns the IDs of the selected neuron groups */
QList<unsigned int> ConnectionGroupModel::getSelectedConnectionGroupIDs(){
//Double check lengths
if(conGrpInfoList.size() < selectionMap.size())
throw SpikeStreamException("There are more selected indexes than indexes");
QList<unsigned int> conGrpIDList;
foreach(unsigned int index, selectionMap.keys()){
conGrpIDList.append(conGrpInfoList.at(index).getID());
}
//Return list
return conGrpIDList;
}
/*! Reloads the list of connection groups */
void ConnectionGroupModel::reload(){
loadConnectionGroups();
}
/*! Selects all or none of the connection groups */
void ConnectionGroupModel::selectAllOrNone(){
//Deselect all groups
if(selectionMap.size() == conGrpInfoList.size()){
selectionMap.clear();
}
//Select all groups
else{
for(int i=0; i<conGrpInfoList.size(); ++i)
selectionMap[i] = true;
}
reset();
}
/*! Shows all or none of the connection groups */
void ConnectionGroupModel::showAllOrNone(){
//Make all groups visible if there are none showing
QList<unsigned> visConGrpIds = Globals::getNetworkDisplay()->getVisibleConnectionGroupIDs();
if(visConGrpIds.isEmpty()){
for(int i=0; i<conGrpInfoList.size(); ++i)
visConGrpIds.append(conGrpInfoList.at(i).getID());
}
//One or more is hidden: make all groups invisible
else{
visConGrpIds.clear();
}
Globals::getNetworkDisplay()->setVisibleConnectionGroupIDs(visConGrpIds);
reset();
}
/*! Inherited from QAbstractTableModel */
bool ConnectionGroupModel::setData(const QModelIndex& index, const QVariant&, int) {
if (!index.isValid() || !Globals::networkLoaded())
return false;
if (index.row() < 0 || index.row() >= rowCount())
return false;
//Change visibility of neuron group
if(index.column() == VIS_COL){
unsigned int tmpConGrpID = conGrpInfoList[index.row()].getID();
if(Globals::getNetworkDisplay()->connectionGroupVisible(tmpConGrpID))
Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, false);
else
Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, true);
//Emit signal that data has changed and return true to indicate data set succesfully.
emit dataChanged(index, index);
return true;
}
//Change selection status of connection group
if(index.column() == SELECT_COL){
if(selectionMap.contains(index.row()))
selectionMap.remove(index.row());
else
selectionMap[index.row()] = true;
reset();
return true;
}
//If we have reached this point no data has been set
return false;
}
/*! Inherited from QAbstractTableModel. Returns the header data */
QVariant ConnectionGroupModel::headerData(int section, Qt::Orientation orientation, int role) const{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal){
if(section == ID_COL)
return "ID";
if(section == DESC_COL)
return "Description";
if(section == SIZE_COL)
return "Size";
if(section == FROM_NEUR_ID_COL)
return "From";
if(section == T0_NEUR_ID_COL)
return "To";
if(section == SYNAPSE_TYPE_COL)
return "Synapse Type";
if(section == PARAM_COL)
return "Parameters";
}
return QVariant();//QString("Roow %1").arg(section);
}
/*! Inherited from QAbstractTableModel. Returns the number of rows in the model. */
int ConnectionGroupModel::rowCount(const QModelIndex&) const{
return conGrpInfoList.size();
}
/*! Reloads the current list of connection groups if a network is present */
void ConnectionGroupModel::loadConnectionGroups(){
//Clear current list of neuron group information
conGrpInfoList.clear();
conGrpSizeList.clear();
//Get list of current connection group info
if(Globals::networkLoaded())
conGrpInfoList = Globals::getNetwork()->getConnectionGroupsInfo();
//Load up sizes of connection groups
for(int i=0; i<conGrpInfoList.size(); ++i)
conGrpSizeList.append( Globals::getNetwork()->getConnectionCount( conGrpInfoList.at(i).getID() ) );
//Sanity check
if(conGrpInfoList.size() != conGrpSizeList.size())
qCritical()<<"Mismatch between list of connection group info and list of connection group size.";
//Instruct listening classes to reload data
this->reset();
}
| nico202/spikestream | applicationlibrary/src/models/ConnectionGroupModel.cpp | C++ | gpl-2.0 | 7,961 |
<?php
// Copyright 2013 Toby Zerner, Simon Zerner
// This file is part of esoTalk. Please see the included license file for usage information.
if (!defined("IN_ESOTALK")) {
exit;
}
ET::$pluginInfo["Debug"] = array(
"name" => "Debug",
"description" => "Shows useful debugging information, such as SQL queries, to administrators.",
"version" => ESOTALK_VERSION,
"author" => "esoTalk Team",
"authorEmail" => "support@esotalk.org",
"authorURL" => "http://esotalk.org",
"license" => "GPLv2"
);
/**
* Debug Plugin
*
* Shows useful debugging information, such as SQL queries, to administrators.
*/
class ETPlugin_Debug extends ETPlugin {
/**
* The time at which the current query started running.
* @var int
*/
private $queryStartTime;
/**
* An application backtrace taken before a query is executed, and used to work out which model/method the
* query came from.
* @var array
*/
private $backtrace;
/**
* An array of queries that have been executed.
* @var array
*/
private $queries = array();
/**
* Initialize the plugin: turn esoTalk's debug config variable on.
*
* @return void
*/
public function init()
{
parent::init();
// Turn debug mode on.
if (!ET::$session->isAdmin()) {
return;
}
ET::$config["esoTalk.debug"] = true;
}
/**
* On all controller initializations, add the debug CSS file to the page.
*
* @return void
*/
public function handler_init()
{
if (!ET::$session->isAdmin()) {
return;
}
ET::$controller->addCSSFile($this->resource("debug.css"), true);
ET::$controller->addJSFile($this->resource("debug.js"), true);
}
/**
* Store the current time (before a query is executed) so we can work out how long it took when it finishes.
*
* @return void
*/
public function handler_database_beforeQuery($sender, $query)
{
if (is_object(ET::$session) and !ET::$session->isAdmin()) {
return;
}
$this->queryStartTime = microtime(true);
$this->backtrace = debug_backtrace();
}
/**
* Work out how long the query took to run and add it to the log.
*
* @return void
*/
public function handler_database_afterQuery($sender, $result)
{
if (is_object(ET::$session) and !ET::$session->isAdmin()) {
return;
}
// The sixth item in the backtrace is typically the model. Screw being reliable.
$item = $this->backtrace[6];
$method = isset($item["class"]) ? $item["class"] . "::" : "";
$method .= $item["function"] . "()";
// Store the query in our queries array.
$this->queries[] = array($result->queryString, round(microtime(true) - $this->queryStartTime, 4), $method);
}
/**
* Render the debug area at the bottom of the page.
*
* @return void
*/
function handler_pageEnd($sender)
{
// Don't proceed if the user is not permitted to see the debug information!
if (!ET::$session->isAdmin()) {
return;
}
// Stop the page loading timer.
$end = microtime(true);
$time = round($end - PAGE_START_TIME, 4);
// Output the debug area.
echo "<div id='debug'>
<div id='debugHdr'><h2>".sprintf(T("Page loaded in %s seconds"), $time) . "</h2></div>";
// Include the geshi library so we can syntax-highlight MySQL queries.
include "geshi/geshi.php";
echo "<h3><a href='#' onclick='$(\"#debugQueries\").slideToggle(\"fast\");return false'>" . T("MySQL queries") . " (<span id='debugQueriesCount'>" . count($this->queries) . "</span>)</a></h3>
<div id='debugQueries' class='section'>";
foreach ($this->queries as $query) {
$geshi = new GeSHi(trim($query[0]), "mysql");
$geshi->set_header_type(GESHI_HEADER_PRE);
echo "<div><strong>" . $query[2] . "</strong> <span class='queryTime subText" . ($query[1] > 0.5 ? " warning" : "") . "'>" . $query[1] . "s</span>" . $geshi->parse_code() . "</div>";
}
$this->queries = array();
// Output POST + GET + FILES information.
echo "</div>
<h3><a href='#' onclick='$(\"#debugPostGetFiles\").slideToggle(\"fast\");return false'>".T("POST + GET + FILES information") . "</a></h3>
<div id='debugPostGetFiles' class='section'>
<p style='white-space:pre' class='fixed' id='debugPost'>\$_POST = ";
echo sanitizeHTML(print_r($_POST, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugGet'>\$_GET = ";
echo sanitizeHTML(print_r($_GET, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugFiles'>\$_FILES = ";
echo sanitizeHTML(print_r($_FILES, true));
echo "</p>
</div>";
// Output SESSION + COOKIE information.
echo "<h3><a href='#' onclick='$(\"#debugSessionCookie\").slideToggle(\"fast\");return false'>" . T("SESSION + COOKIE information") . "</a></h3>
<div id='debugSessionCookie' class='section'><p style='white-space:pre' class='fixed' id='debugSession'>\$_SESSION = ";
echo sanitizeHTML(print_r($_SESSION, true));
echo "</p><p style='white-space:pre' class='fixed' id='debugCookie'>\$_COOKIE = ";
echo sanitizeHTML(print_r($_COOKIE, true));
echo "</p></div>";
// Hide all panels by default.
echo "<script>
$(function() {
$('#debug .section').hide();
});
</script>";
}
// Construct and process the settings form.
public function settings($sender)
{
// Set up the settings form.
$form = ETFactory::make("form");
$form->action = URL("admin/plugins/settings/Debug");
// If the form was submitted...
if ($form->validPostBack("upgradeDB")) {
// Run the upgrade process.
ET::upgradeModel()->upgrade();
// Upgrade plugins as well.
foreach (ET::$plugins as $name => $plugin) {
$plugin->setup(C("$name.version"));
}
$sender->message(T("message.upgradeSuccessful"), "success");
$sender->redirect(URL("admin/plugins"));
}
$sender->data("debugSettingsForm", $form);
return $this->view("settings");
}
}
| Felli/fireside | addons/plugins/Debug/plugin.php | PHP | gpl-2.0 | 6,463 |
/**
* Copyright 2011 Kurtis L. Nusbaum
*
* This file is part of UDJ.
*
* UDJ 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.
*
* UDJ 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 UDJ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ActivePlaylistView.hpp"
#include "ActivePlaylistModel.hpp"
#include "Utils.hpp"
#include "Logger.hpp"
#include <QHeaderView>
#include <QSqlRecord>
#include <QAction>
#include <QMenu>
#include <QContextMenuEvent>
namespace UDJ{
ActivePlaylistView::ActivePlaylistView(DataStore* dataStore, QWidget* parent):
QTableView(parent),
dataStore(dataStore)
{
setContextMenuPolicy(Qt::CustomContextMenu);
setFocusPolicy(Qt::TabFocus);
setEditTriggers(QAbstractItemView::NoEditTriggers);
model = new ActivePlaylistModel(getDataQuery(), dataStore, this);
horizontalHeader()->setStretchLastSection(true);
createActions();
setModel(model);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ContiguousSelection);
configureHeaders();
connect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
connect(
this,
SIGNAL(activated(const QModelIndex&)),
this,
SLOT(setCurrentSong(const QModelIndex&)));
connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),
this, SLOT(handleContextMenuRequest(const QPoint&)));
connect(
selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this,
SLOT(handleSelectionChange(const QItemSelection&, const QItemSelection&)));
}
void ActivePlaylistView::configureHeaders(){
QSqlRecord record = model->record();
int idIndex = record.indexOf(DataStore::getActivePlaylistLibIdColName());
int downVoteIndex = record.indexOf(DataStore::getDownVoteColName());
int upVoteIndex = record.indexOf(DataStore::getUpVoteColName());
int adderNameIndex = record.indexOf(DataStore::getAdderUsernameColName());
int timeAddedIndex = record.indexOf(DataStore::getTimeAddedColName());
setColumnHidden(idIndex, true);
model->setHeaderData(
downVoteIndex, Qt::Horizontal, tr("Down Votes"), Qt::DisplayRole);
model->setHeaderData(
upVoteIndex, Qt::Horizontal, tr("Up Votes"), Qt::DisplayRole);
model->setHeaderData(
adderNameIndex, Qt::Horizontal, tr("Adder"), Qt::DisplayRole);
model->setHeaderData(
timeAddedIndex, Qt::Horizontal, tr("Time Added"), Qt::DisplayRole);
}
void ActivePlaylistView::setCurrentSong(const QModelIndex& index){
Logger::instance()->log("Manual setting of current song");
QSqlRecord songToPlayRecord = model->record(index.row());
QVariant data =
songToPlayRecord.value(DataStore::getActivePlaylistLibIdColName());
selectionModel()->clearSelection();
dataStore->setCurrentSong(data.value<library_song_id_t>());
}
void ActivePlaylistView::createActions(){
removeSongAction = new QAction(tr("Remove Song"), this);
connect(
removeSongAction,
SIGNAL(triggered()),
this,
SLOT(removeSongs()));
}
void ActivePlaylistView::handleContextMenuRequest(const QPoint& /*pos*/){
QMenu contextMenu(this);
contextMenu.addAction(removeSongAction);
QAction *selected = contextMenu.exec(QCursor::pos());
if(selected==NULL){
selectionModel()->clearSelection();
}
}
void ActivePlaylistView::removeSongs(){
QSet<library_song_id_t> toRemove =
Utils::getSelectedIds<library_song_id_t>(
this,
model,
DataStore::getActivePlaylistLibIdColName());
dataStore->removeSongsFromActivePlaylist(toRemove);
selectionModel()->clearSelection();
}
void ActivePlaylistView::handleSelectionChange(
const QItemSelection& selected,
const QItemSelection& /*deselected*/)
{
if(selected.indexes().size() == 0){
connect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
}
else{
disconnect(
dataStore,
SIGNAL(activePlaylistModified()),
model,
SLOT(refresh()));
}
}
void ActivePlaylistView::focusOutEvent(QFocusEvent *event){
if(event->reason() != Qt::PopupFocusReason){
selectionModel()->clearSelection();
}
}
} //end namespace
| klnusbaum/UDJ-Desktop-Client | src/ActivePlaylistView.cpp | C++ | gpl-2.0 | 4,615 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Board Class Library")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("QUT")]
[assembly: AssemblyProduct("Board Class Library")]
[assembly: AssemblyCopyright("Copyright © QUT 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db88e36f-8def-4e67-9836-e3aa9cb610ea")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Jaydak54/assignment4 | HareAndTortoise/Board Class Library/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,420 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import gtk # @UnusedImport
import gtk.glade
import gobject
from lib.pycsb19 import recibo
from lib.pycsb19 import ordenante
import sqlite3 as sqlite
import time
class Remesas:
def __init__(self):
self.Llamada=""
self.NifOrdenante=""
self.CodRemesa=""
self.fecha=""
glRemesas=gtk.glade.XML("./gld/remesas.glade")
self.ventana=glRemesas.get_widget("Remesas")
self.ventana.connect("destroy", self.Salir)
self.tvRecibos=glRemesas.get_widget("tvRecibos")
self.tvRecibos.connect("button_press_event",self.SacaCampos)
self.tNombre=glRemesas.get_widget("tNombre")
self.tOrdenante=glRemesas.get_widget("tOrdenante")
self.tImporte=glRemesas.get_widget("tImporte")
self.fecha=glRemesas.get_widget("tFecha")
self.btnOrdenante=glRemesas.get_widget("btnSeleccionar")
self.btnOrdenante.connect("clicked", self.SelOrdenante)
self.btnSalir=glRemesas.get_widget("btnSalir")
self.btnSalir.connect("clicked", self.Salir)
self.btnAnadir=glRemesas.get_widget("btnAnadir")
self.btnAnadir.connect("clicked", self.Anadir)
self.btnEliminar=glRemesas.get_widget("btnEliminar")
self.btnEliminar.connect("clicked", self.Eliminar)
self.btnModificar=glRemesas.get_widget("btnModificar")
self.btnModificar.connect("clicked", self.Modificar)
self.btnImprimir=glRemesas.get_widget("btnImprimir")
self.btnImprimir.connect("clicked", self.Imprimir)
self.btnGenerar=glRemesas.get_widget("btnGenerar")
self.btnGenerar.connect("clicked", self.Generar)
self.btnAyuda=glRemesas.get_widget("btnAyuda")
# self.btnAyuda.connect("clicked", self.Ayuda)
data=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
data.clear()
self.tvRecibos.set_model(data)
column = gtk.TreeViewColumn("Cod ", gtk.CellRendererText(), text=0)
self.tvRecibos.append_column(column)
column = gtk.TreeViewColumn("Cliente ", gtk.CellRendererText(), text=1)
self.tvRecibos.append_column(column)
render=gtk.CellRendererText()
render.set_property('xalign', 1.0)
column = gtk.TreeViewColumn("Importe", render, text=2)
self.tvRecibos.append_column(column)
def AbreDb(self):
self.conexion=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable
def CierraDb(self):
self.conexion.close()
def SacaCampos(self,widget,event):
if event.type==5:
self.Modificar(widget)
def MiraRemesa(self,Nombre):
con=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable
cursor = con.cursor()
#Mira a ver si ya existe la remesa
sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])<>0:
#no hay ninguno dado de alta
sql="Select titulo, ordenante, importe, codigo from remesas where titulo='"+Nombre+"'"
cursor.execute(sql)
for x in cursor.fetchall():
item=[]
for n in x:
item.append(n)
# En item[2] esta el importe
self.tImporte.set_text(str(item[2]))
self.NifOrdenante=item[1]
self.CodRemesa=str(item[3])
# miramos el nombre del ordenante
sql="Select nombre from ordenantes where nif='"+item[1].split(":")[0]+"' and sufijo='"+item[1].split(":")[1]+"'"
cursor.execute(sql)
self.tOrdenante.set_text(cursor.fetchall()[0][0])
#Mira el detalle
#Si no hay ningun detalle pasa de mirar mas porque si no da error
sql="SELECT count(codigo) FROM det_remesas"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])<>0:
sql="SELECT det_remesas.indice, clientes.nombre, det_remesas.importe FROM det_remesas,clientes WHERE clientes.codigo=det_remesas.cliente AND det_remesas.codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
for x in cursor.fetchall():
item=[]
numero=0
for n in x:
numero=numero+1
if numero==3:
#Todo este rollo es para completar el importe con dos decimales en el treeview
cadena=str(n)
if cadena.find(".")==-1:
cadena=cadena+".00"
elif (len(cadena)-1)-cadena.find(".")<2:
cadena=cadena+"0"
item.append(cadena)
else:
item.append(n)
self.VisualizaDatos(item)
con.close()
def Eliminar(self, widget):
if self.tvRecibos.get_selection().get_selected()[1]<>None:
store=self.tvRecibos.get_model()
self.AbreDb()
c = self.conexion.cursor()
#Borramos el recibo
sql="delete from det_remesas where codigo="+self.CodRemesa+" and indice="+store[self.tvRecibos.get_cursor()[0][0]][0]
c.execute(sql)
self.conexion.commit()
#Miramos a ver cuanto es el importe de la remesa ahora
sql="Select sum(importe) from det_remesas where codigo='"+self.CodRemesa+"'"
c.execute(sql)
Importe=0.0
Importe=float(c.fetchall()[0][0])
#Mete el importe en la casilla del importe
self.tImporte.set_text(str(Importe))
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa
c.execute(sql)
self.conexion.commit()
self.CierraDb()
store.remove(self.tvRecibos.get_selection().get_selected()[1])
self.tvRecibos.set_model(store)
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar una recibo para poder eliminarlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
def MiraOrdenante(self):
if self.Otro.CodOrdenante<>"x":
if self.Otro.CodOrdenante<>"":
self.tOrdenante.set_text(self.Otro.NomOrdenante)
self.NifOrdenante=self.Otro.CodOrdenante
self.AbreDb()
cursor = self.conexion.cursor()
#Hay que mirar a ver si es la primera remesa de la base de datos
sql="Select count(codigo) from remesas"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])==0:
#Es la primera remesa asin que el codigo es = 1 y solo hay que darla de alta
codigo="1"
self.CodRemesa=codigo
sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)"
cursor.execute(sql)
self.conexion.commit()
else:
#Mira a ver si ya existe la remesa por si es una modificacion del ordenante
sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
if int(cursor.fetchall()[0][0])==0:
#"no hay ninguno dado de alta"
# "Ahora miramos a ver cual es el ultimo codigo dado de alta y le sumamos 1"
sql="Select max(codigo) from remesas"
cursor.execute(sql)
codigo=str(int(cursor.fetchall()[0][0])+1)
self.CodRemesa=codigo
#Ahora la damos de alta
sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)"
cursor.execute(sql)
self.conexion.commit()
else:
# "ya esta dado de alta, Hay que hace un Update Tabla"
sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
codigo=str(cursor.fetchall()[0][0])
self.CodRemesa=codigo
sql="UPDATE remesas SET titulo='" +self.tNombre.get_text()+"', ordenante='"+self.NifOrdenante+"' WHERE codigo="+codigo
cursor.execute(sql)
self.conexion.commit()
self.CierraDb()
return 0
else:
return 1
def VisualizaDatos(self,Datos):
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable
store=self.tvRecibos.get_model()
itr=store.append()
store.set(itr,0,Datos[0],1,Datos[1],2,Datos[2])
self.tvRecibos.set_model(store)
def MiraRecibos(self):
#Aqui se graban los recibos que devuelve la pantalla de recibos
if self.VenRecibos.Llamada<>"remesas":
if self.VenRecibos.Llamada<>"Salir":
#Saca el codigo de la remesa en el improbable caso de que no exista
if self.CodRemesa=="":
self.AbreDb()
cursor = self.conexion.cursor()
sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'"
cursor.execute(sql)
self.CodRemesa=str(cursor.fetchall()[0][0])
self.CierraDb()
#lo primero es saber si es una modificacion de un recibo
if self.VenRecibos.Modificacion<>"":
#Es una modificacion
self.AbreDb()
cursor = self.conexion.cursor()
indice=self.VenRecibos.Modificacion
#Modificamos los datos del recibo
#sql="Update det_remesas SET cliente=?, importe=?, conceptos=? WHERE codigo='"+self.CodRemesa+"' AND indice='"+indice+"'"
#cursor.execute(sql, (self.VenRecibos.CodCliente,float(self.VenRecibos.Importe),self.VenRecibos.Conceptos))
sql="Update det_remesas SET cliente='"+self.VenRecibos.CodCliente+"', importe="+self.VenRecibos.Importe+", conceptos='"+self.VenRecibos.Conceptos+"' WHERE codigo="+self.CodRemesa+" AND indice="+indice
cursor.execute(sql)
self.conexion.commit()
cursor = self.conexion.cursor()
#Miramos a ver cuanto es el importe de la remesa ahora
sql="Select sum(importe) from det_remesas where codigo="+self.CodRemesa
cursor.execute(sql)
Importe=float(cursor.fetchall()[0][0])
#Mete el importe en la casilla del importe
self.tImporte.set_text(str(Importe))
cursor = self.conexion.cursor()
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa
cursor.execute(sql)
#sql="UPDATE remesas SET importe=? WHERE codigo=?"
#cursor.execute(sql,(Importe,self.CodRemesa))
self.conexion.commit()
#Carga los datos en el treeview
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
self.tvRecibos.set_model(store)
self.MiraRemesa(self.tNombre.get_text())
self.CierraDb()
else:
#Es un recibo nuevo
self.AbreDb()
cursor = self.conexion.cursor()
#miramos a ver si es el primer recibo de esta remesa (si el importe es 0)
sql="SELECT sum(importe) FROM remesas WHERE codigo="+self.CodRemesa
cursor.execute(sql)
if float(cursor.fetchall()[0][0])==0:
#Es el primero asin que le ponemos el numero 1
indice=1
else:
#No es el primero
#Miramos a ver el codigo que le corresponde a este recibo
sql="SELECT max(indice) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
indice=str(int(cursor.fetchall()[0][0])+1)
#A�adimos los datos del recibo
#sql="insert into det_remesas (codigo,indice, cliente, importe, conceptos) values (?,?,?,?,?)"
#cursor.execute(sql, (str(self.CodRemesa),indice , self.VenRecibos.CodCliente, str(self.VenRecibos.Importe), self.VenRecibos.Conceptos))
sql="insert into det_remesas (codigo, indice, cliente, importe, conceptos) values ("+str(self.CodRemesa)+","+str(indice)+",'"+self.VenRecibos.CodCliente+"',"+str(self.VenRecibos.Importe)+",'"+self.VenRecibos.Conceptos+"')"
cursor.execute(sql)
self.conexion.commit()
sql="SELECT sum(importe) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
Importe = float(cursor.fetchall()[0][0])
self.tImporte.set_text(str(Importe))
#Actualiza el importe en la base de datos de remesa
sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo='"+self.CodRemesa+"'"
cursor.execute(sql)
self.conexion.commit()
#Mete los datos del recibo en el TreeView
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
self.tvRecibos.set_model(store)
self.MiraRemesa(self.tNombre.get_text())
self.CierraDb()
else:
pass
# print "salio por aqui"
return 0
else:
#print "no Es distinto"
return 1
def SelOrdenante(self,widget):
#Se llama a la pantalla del ordenante
self.Otro=ordenante.Ordenante()
self.Otro.Llamada="remesas"
#self.Otro.ventana.set_modal(True)
self.Otro.CodOrdenante="x"
self.timeout= gtk.timeout_add(250, self.MiraOrdenante)
def Anadir(self,widget):
if self.tNombre.get_text()=="":
self.Dialogo("No se puede anadir un recibo si no se le ha dado un nombre a la remesa",2)
elif self.tOrdenante.get_text()=="":
self.Dialogo("No se puede anadir un recibo si no se ha selecionado el ordenante",2)
else:
self.VenRecibos=recibo.Recibo()
self.VenRecibos.Llamada="remesas"
self.VenRecibos.Modificacion=""
self.VenRecibos.Remesa=self.tNombre.get_text()
#self.VenRecibos.ventana.set_modal(True)
self.timeout= gtk.timeout_add(250, self.MiraRecibos)
def Modificar(self,widget):
store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable
store=self.tvRecibos.get_model()
if self.tvRecibos.get_cursor()[0]<>None:
self.VenRecibos=recibo.Recibo()
self.VenRecibos.Llamada="remesas"
#Mete el numero de recibo de la remesa
self.VenRecibos.Modificacion=store[self.tvRecibos.get_cursor()[0][0]][0]
self.AbreDb()
cClientes = self.conexion.cursor()
sql="SELECT codigo, nombre, banco, oficina, dc, cuenta FROM clientes WHERE nombre='"+store[self.tvRecibos.get_cursor()[0][0]][1]+"'"
cClientes.execute(sql)
pp=[]
pp=cClientes.fetchone()
CodCliente=pp[0]
self.VenRecibos.tCodCliente.set_text(CodCliente)
self.VenRecibos.tNomCliente.set_text(pp[1])
self.VenRecibos.tBanco.set_text(pp[2])
self.VenRecibos.tOficina.set_text(pp[3])
self.VenRecibos.tDc.set_text(pp[4])
self.VenRecibos.tCuenta.set_text(pp[5])
self.VenRecibos.tImporte.set_text(store[self.tvRecibos.get_cursor()[0][0]][2])
cDetalle = self.conexion.cursor()
sql="SELECT codigo, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa+" AND indice="+store[self.tvRecibos.get_cursor()[0][0]][0]
cDetalle.execute(sql)
n=cDetalle.fetchone()[3].split("�")
self.VenRecibos.tConcepto1.set_text(n[0])
self.VenRecibos.tConcepto2.set_text(n[1])
self.VenRecibos.tConcepto3.set_text(n[2])
self.VenRecibos.tConcepto4.set_text(n[3])
self.VenRecibos.tConcepto5.set_text(n[4])
self.VenRecibos.tConcepto6.set_text(n[5])
self.VenRecibos.tConcepto7.set_text(n[6])
self.VenRecibos.tConcepto8.set_text(n[7])
self.VenRecibos.tConcepto9.set_text(n[8])
self.VenRecibos.tConcepto10.set_text(n[9])
self.VenRecibos.tConcepto11.set_text(n[10])
self.VenRecibos.tConcepto12.set_text(n[11])
self.VenRecibos.tConcepto13.set_text(n[12])
self.VenRecibos.tConcepto14.set_text(n[13])
self.VenRecibos.tConcepto15.set_text(n[14])
self.VenRecibos.tConcepto16.set_text(n[15])
self.VenRecibos.Remesa=self.tNombre.get_text()
#self.VenRecibos.ventana.set_modal(True)
self.timeout= gtk.timeout_add(250, self.MiraRecibos)
self.CierraDb()
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar un recibo para poder abrirlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
def Imprimir(self,widget):
pass
def Espacios(self,Numero):
d=""
for n in range(0,Numero): # @UnusedVariable
d=d+" "
return d
def Ceros(self,Numero):
d=""
for n in range(0,Numero): # @UnusedVariable
d=d+"0"
return d
def Generar(self,widget):
self.Fiche = gtk.FileSelection("Seleccionar Fichero")
self.Fiche.connect("destroy", self.CerrarAbrirFichero)
self.Fiche.ok_button.connect("clicked", self.FicheroSeleccionado)
self.Fiche.cancel_button.connect("clicked", self.CerrarAbrirFichero)
self.Fiche.set_filename("")
self.Fiche.set_modal(True)
self.Fiche.show()
def CerrarAbrirFichero(self,widget):
self.Fiche.destroy()
def FicheroSeleccionado(self, widget):
#Cerramos la ventana de seleccionar fichero
if self.Fiche.get_filename()[len(self.Fiche.get_filename())-1:len(self.Fiche.get_filename())]<>'\\':
self.GrabaCSB(self.Fiche.get_filename())
else:
d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de introducir el nombre de un fichero para poder grabarlo")
d.connect('response', lambda dialog, response: dialog.destroy())
d.show()
self.Fiche.destroy()
def GrabaCSB(self,Fichero):
#Aqui se crea el fichero con el formato CSB19
self.AbreDb()
f=open(Fichero,"w")
#Cabecera de presentador
cur=self.conexion.cursor()
sql="SELECT ordenante FROM remesas WHERE codigo="+self.CodRemesa
cur.execute(sql)
ordenante=cur.fetchall()[0][0]
rem=self.conexion.cursor()
sql="SELECT nif, sufijo, nombre, banco, oficina, dc, cuenta FROM ordenantes WHERE nif='"+ordenante.split(":")[0]+"' and sufijo='"+ordenante.split(":")[1]+"'"
rem.execute(sql)
Linea=rem.fetchall()[0]
nif=Linea[0]
sufijo=Linea[1]
nombre=Linea[2]
banco=Linea[3]
oficina=Linea[4]
dc=Linea[5]
cuenta=Linea[6]
#a�o, mes, dia
dia=str(time.localtime()[2])
if len(dia)<2:
dia="0"+dia
mes=str(time.localtime()[1])
if len(mes)<2:
mes="0"+mes
ano=str(time.localtime()[0])[2:4]
FechaConfeccion=dia+mes+ano
#FechaCargo=FechaConfeccion
FechaCargo=self.fecha.get_text()
#Cambiar la FechaCargo por el valor del texto (casi nada...)
if len(nombre)<40:
nombre=nombre+self.Espacios(40-len(nombre))
Cadena="5180"+nif+sufijo+FechaConfeccion+self.Espacios(6)+nombre+self.Espacios(20)+banco+oficina+self.Espacios(12)+self.Espacios(40)+"***PyCsb19****"+"\r\n"
f.write(Cadena)
#Cabecera de Ordenante
Cadena="5380"+nif+sufijo+FechaConfeccion+FechaCargo+nombre+banco+oficina+dc+cuenta+self.Espacios(8)+"01"+self.Espacios(10)+self.Espacios(40)+"***PyCsb19****"+"\r\n"
f.write(Cadena)
#Registros de recibos
rec=self.conexion.cursor()
sql="SELECT indice, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa
rec.execute(sql)
nNumDomiciliaciones=0
nSuma=0.0
nNumRegistrosOrdenante=2 #Se pone con dos porque el fichero ya tiene las 2 cabeceras escritas
for remesa in rec.fetchall():
#El indice lo voy a utilizar para el codigo de devolucion
Indice=str(remesa[0])
nNumDomiciliaciones=nNumDomiciliaciones+1
if len(Indice)<6:
Indice=Indice+self.Espacios(6-len(Indice))
elif len(Indice)>6:
Indice=Indice[0:5]
Cliente=remesa[1]
nSuma=nSuma+remesa[2]
Importe=str(remesa[2])
if Importe.find(".")==-1:
Importe=Importe+self.Ceros(2)
else:
if len(Importe.split(".")[1])<2:
Importe=Importe.split(".")[0]+Importe.split(".")[1]+self.Ceros(2-len(Importe.split(".")[1]))
elif len(Importe.split(".")[1])>2:
Importe=Importe.split(".")[0]+Importe.split(".")[1][0:1]
else:
Importe=Importe.split(".")[0]+Importe.split(".")[1]
if len(Importe)<10:
Importe=self.Ceros(10-len(Importe))+Importe
Conceptos=[]
for n in remesa[3].split("�"):
if len(n)==0:
dato=""
elif len(n)<40:
dato=n+self.Espacios(40-len(n))
elif len(n)>40:
dato=n[0:40]
else:
dato=n
Conceptos.append(dato)
#Vamos a por los datos del cliente
cli=self.conexion.cursor()
sql="SELECT codigo, nif, nombre, direccion, ciudad, cp, banco, oficina, dc, cuenta FROM clientes WHERE codigo='"+Cliente+"'"
cli.execute(sql)
c=cli.fetchall()[0]
if len(c[0])<12:
CodCliente=c[0]+self.Espacios(12-len(c[0]))
else:
CodCliente=c[0]
#El nif lo voy a utilizar para el codigo de referencia interna
NifCliente=c[1]
if len(NifCliente)<10:
NifCliente=NifCliente+self.Espacios(10-len(NifCliente))
if len(c[2])<40:
NombreCliente=c[2]+self.Espacios(40-len(c[2]))
else:
NombreCliente=c[2]
DireCliente=c[3] # @UnusedVariable
CiudadCliente=c[4] # @UnusedVariable
CpCliente=c[5] # @UnusedVariable
BancoCliente=c[6]
OficinaCliente=c[7]
DcCliente=c[8]
CuentaCliente=c[9]
if len(Conceptos[0])<40:
Conceptos[0]=Conceptos[0]+self.Espacios(40-len(Conceptos[0]))
if len(Conceptos[0])>40:
Conceptos[0]=Conceptos[0][0:40]
Cadena="5680"+nif+sufijo+CodCliente+NombreCliente+BancoCliente+OficinaCliente+DcCliente+CuentaCliente+Importe+Indice+NifCliente+Conceptos[0]+self.Espacios(8)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
#Vamos a ver que pasa con los otros conceptos.
if len(Conceptos[1])<>0 or len(Conceptos[2])<>0 or len(Conceptos[3])<>0:
if len(Conceptos[1])<>40:
Conceptos[1]=Conceptos[1]+self.Espacios(40-len(Conceptos[1]))
if len(Conceptos[2])<>40:
Conceptos[2]=Conceptos[2]+self.Espacios(40-len(Conceptos[2]))
if len(Conceptos[3])<>40:
Conceptos[3]=Conceptos[3]+self.Espacios(40-len(Conceptos[3]))
Cadena="5681"+nif+sufijo+CodCliente+Conceptos[1]+Conceptos[2]+Conceptos[3]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[4])<>0 or len(Conceptos[5])<>0 or len(Conceptos[6])<>0:
if len(Conceptos[4])<>40:
Conceptos[4]=Conceptos[4]+self.Espacios(40-len(Conceptos[4]))
if len(Conceptos[5])<>40:
Conceptos[5]=Conceptos[5]+self.Espacios(40-len(Conceptos[5]))
if len(Conceptos[6])<>40:
Conceptos[6]=Conceptos[6]+self.Espacios(40-len(Conceptos[6]))
Cadena="5682"+nif+sufijo+CodCliente+Conceptos[4]+Conceptos[5]+Conceptos[6]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[7])<>0 or len(Conceptos[8])<>0 or len(Conceptos[9])<>0:
if len(Conceptos[7])<>40:
Conceptos[7]=Conceptos[7]+self.Espacios(40-len(Conceptos[7]))
if len(Conceptos[8])<>40:
Conceptos[8]=Conceptos[8]+self.Espacios(40-len(Conceptos[8]))
if len(Conceptos[9])<>40:
Conceptos[9]=Conceptos[9]+self.Espacios(40-len(Conceptos[9]))
Cadena="5683"+nif+sufijo+CodCliente+Conceptos[7]+Conceptos[8]+Conceptos[9]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[10])<>0 or len(Conceptos[11])<>0 or len(Conceptos[12])<>0:
if len(Conceptos[10])<>40:
Conceptos[10]=Conceptos[10]+self.Espacios(40-len(Conceptos[10]))
if len(Conceptos[11])<>40:
Conceptos[11]=Conceptos[11]+self.Espacios(40-len(Conceptos[11]))
if len(Conceptos[12])<>40:
Conceptos[12]=Conceptos[12]+self.Espacios(40-len(Conceptos[12]))
Cadena="5684"+nif+sufijo+CodCliente+Conceptos[10]+Conceptos[11]+Conceptos[12]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
if len(Conceptos[13])<>0 or len(Conceptos[14])<>0 or len(Conceptos[15])<>0:
if len(Conceptos[13])<>40:
Conceptos[13]=Conceptos[13]+self.Espacios(40-len(Conceptos[13]))
if len(Conceptos[14])<>40:
Conceptos[14]=Conceptos[14]+self.Espacios(40-len(Conceptos[14]))
if len(Conceptos[15])<>40:
Conceptos[15]=Conceptos[15]+self.Espacios(40-len(Conceptos[15]))
Cadena="5685"+nif+sufijo+CodCliente+Conceptos[13]+Conceptos[14]+Conceptos[15]+self.Espacios(14)+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
#La linea de datos del cliente no se implementa de monento
#Cadena="5686"+nif+sufijo+CodCliente
#Linea de totales de ordenante
Suma=str(nSuma)
if Suma.find(".")==-1:
Suma=Suma+self.Ceros(2)
else:
if len(Suma.split(".")[1])<2:
Suma=Suma.split(".")[0]+Suma.split(".")[1]+self.Ceros(2-len(Suma.split(".")[1]))
elif len(Suma.split(".")[1])>2:
Suma=Suma.split(".")[0]+Suma.split(".")[1][0:1]
else:
Suma=Suma.split(".")[0]+Suma.split(".")[1]
if len(Suma)<10:
Suma=self.Ceros(10-len(Suma))+Suma
NumDomiciliaciones=str(nNumDomiciliaciones)
if len(NumDomiciliaciones)<10:
NumDomiciliaciones=self.Ceros(10-len(NumDomiciliaciones))+NumDomiciliaciones
NumRegistrosOrdenante=str(nNumRegistrosOrdenante)
if len(NumRegistrosOrdenante)<10:
NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante
Cadena="5880"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+self.Espacios(20)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n"
f.write(Cadena)
nNumRegistrosOrdenante=nNumRegistrosOrdenante+1
NumRegistrosOrdenante=str(nNumRegistrosOrdenante+1)
if len(NumRegistrosOrdenante)<10:
NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante
#Linea de total general
Cadena="5980"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+"0001"+self.Espacios(16)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n"
f.write(Cadena)
f.close()
self.CierraDb()
self.Dialogo("El fichero se ha generado correctamente",1)
def Dialogo(self, msg, Tipo):
if Tipo==1:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,msg)
elif Tipo==2:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CLOSE,msg)
elif Tipo==3:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,msg)
elif Tipo==4:
dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL,msg)
dialog.connect('response', lambda dialog, response: dialog.destroy())
dialog.show()
return dialog
def Salir(self,*args):
#True
if self.Llamada<>"":
self.ventana.hide()
self.Cliente=""
self.Importe=""
self.Llamada=""
return True
else:
gtk.main_quit()
def Main(self):
self.Llamada=""
gtk.main()
if __name__ == "__main__":
gtk.rc_parse("gtkrc.txt")
ven = Remesas()
ven.Main()
| pacoqueen/ginn | ginn/lib/pycsb19/remesas.py | Python | gpl-2.0 | 32,357 |
<?php
/**
* @version $Id: rokpad.php 9100 2013-04-03 23:19:42Z djamil $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
defined('_JEXEC') or die;
/**
*
*/
class plgEditorRokPad extends JPlugin
{
/**
* @var bool
*/
protected static $_assets = false;
/**
* @var string
*/
protected $_version = '2.1.4';
/**
* @var string
*/
protected $_basepath = '/plugins/editors/rokpad/';
/**
* @var
*/
protected $_acepath;
/**
* @param $subject
* @param $config
*/
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
$this->loadLanguage();
}
/**
* @return string
*/
public function onInit()
{
JHtml::_('behavior.framework', true);
$document = JFactory::getDocument();
$this->_basepath = JURI::root(true) . $this->_basepath;
$this->_acepath = $this->_basepath . 'ace/';
if (!self::$_assets) {
/*
$document->addStyleSheet($this->_basepath . 'assets/css/rokpad.css'.$this->_appendCacheToken());
$document->addScript($this->_acepath . 'ace.js'.$this->_appendCacheToken());
$document->addScript($this->_basepath . 'assets/js/rokpad.js'.$this->_appendCacheToken());
*/
$document->addScriptDeclaration($this->getJSParams());
$this->compileLess();
$this->compileJS();
self::$_assets = true;
}
return '';
}
/**
* @param $id
*
* @return string
*/
public function onSave($id)
{
return "RokPadData.insertion.onSave('".$id."');\n";
}
/**
* @param $id
*
* @return string
*/
public function onGetContent($id)
{
return "RokPadData.insertion.onGetContent('".$id."');\n";
}
/**
* @param $id
* @param $content
*
* @return string
*/
public function onSetContent($id, $content)
{
return "RokPadData.insertion.onSetContent('".$id."', ".$content.");\n";
}
/**
* @return bool
*/
public function onGetInsertMethod()
{
static $done = false;
// Do this only once.
if (!$done) {
$done = true;
$doc = JFactory::getDocument();
$js = "\tfunction jInsertEditorText(text, editor) {\n
RokPadData.insertion.onGetInsertMethod(text, editor);\n
}\n";
$doc->addScriptDeclaration($js);
}
return true;
}
/**
* @param $name
* @param $content
* @param $width
* @param $height
* @param $col
* @param $row
* @param bool $buttons
* @param null $id
* @param null $asset
* @param null $author
* @param array $params
*
* @return string
*/
public function onDisplay($name, $content, $width, $height, $col, $row, $buttons = true, $id = null, $asset = null, $author = null, $params = array())
{
if (empty($id)) $id = $name;
$buttons = $this->_displayButtons($id, $buttons, $asset, $author);
$html = array();
$html[] = '<div class="rokpad-editor-wrapper" data-rokpad-editor="' . $id . '">';
$html[] = ' <div class="rokpad-toolbar">';
$html[] = ' <ul class="rok-left">';
$html[] = ' <li><div class="rok-button rok-button-primary rokpad-tip" data-original-title="Ajax Save" data-placement="below-left" data-rokpad-save><i class="rokpad-icon-save"></i> save</div></li>';
$html[] = ' <li class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Undo" data-placement="below" data-rokpad-undo><i class="rokpad-icon-undo"></i></div>';
$html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Redo" data-placement="below" data-rokpad-redo><i class="rokpad-icon-redo"></i></div>';
$html[] = ' </li>';
$html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Find..." data-placement="below" data-rokpad-find><i class="rokpad-icon-search"></i></div></li>';
$html[] = ' <li>';
$html[] = ' <div class="rok-dropdown-group">';
$html[] = ' <div class="rok-button" data-rokpad-toggle="extras"><i class="rokpad-icon-more"></i><span class="caret"></span></div>';
$html[] = ' <ul class="rok-dropdown" data-rokpad-dropdown="extras">';
$html[] = ' <li><a href="#" data-rokpad-goto>Goto Line...</a></li>';
$html[] = ' <li><a href="#" data-rokpad-find-replace>Find and Replace...</a></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li><a href="#" data-rokpad-beautify>Beautify HTML</a></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-right">';
$html[] = ' <li>';
$html[] = ' <div class="rok-popover-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Editor Settings" data-placement="below" data-rokpad-toggle="settings"><i class="rokpad-icon-settings"></i></div>';
$html[] = ' <div class="rok-popover" data-rokpad-popover="settings">';
$html[] = ' <ul class="options">';
$html[] = ' <li><span class="title">Theme</span><span class="input"><select data-rokpad-options="theme" class="chzn-done"></select></span></li>';
$html[] = ' <li><span class="title">Font Size</span><span class="input"><select data-rokpad-options="font-size" class="chzn-done"></select></span></li>';
$html[] = ' <li><span class="title">Code Folding</span><span class="input"><select data-rokpad-options="fold-style" class="chzn-done"><option value="manual">Manual</option><option value="markbegin">Mark Begin</option><option value="markbeginend">Mark Begin and End</option></select></span></li>';
$html[] = ' <li><span class="title">Soft Wrap</span><span class="input"><select data-rokpad-options="use-wrap-mode" class="chzn-done"><option value="off">Off</option><option value="40">40 Chars</option><option value="80">80 Chars</option><option value="free">Free</option></select></span></li>';
$html[] = ' <li><span class="title-checkbox">Full Line Selection</span><span class="input"><input type="checkbox" data-rokpad-options="selection-style" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Highlight Active Line</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-active-line" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Invisibles</span><span class="input"><input type="checkbox" data-rokpad-options="show-invisibles" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Gutter</span><span class="input"><input type="checkbox" data-rokpad-options="show-gutter" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Show Print Margin</span><span class="input"><input type="checkbox" data-rokpad-options="show-print-margin" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Highlight Selected Word</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-selected-word" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Autohide Fold Widgets</span><span class="input"><input type="checkbox" data-rokpad-options="fade-fold-widgets" /></span></li>';
$html[] = ' <li><span class="title-checkbox">Autosave</span><span class="input"><input type="checkbox" data-rokpad-options="autosave-enabled" /> <input type="text" data-rokpad-options="autosave-time" /> mins</span></li>';
$html[] = ' </ul>';
$html[] = ' <div class="rok-popover-arrow"></div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li>';
$html[] = ' <div class="rok-popover-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Keyboard Shortcuts" data-placement="below" data-rokpad-toggle="keyboard"><i class="rokpad-icon-keyboard"></i></div>';
$html[] = ' <div class="rok-popover rok-popover-keyboard" data-rokpad-popover="keyboard">';
$html[] = ' <ul class="keyboard">';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-win"></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Center selection</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Change to uppser case</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Change to lower case</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Copy lines down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Copy lines up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">S</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">S</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Save</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Use selection for find</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">G</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find next</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">G</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Find previous</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Fold all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Unfold all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">↓</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">N</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go line down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">↑</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">P</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go line up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">←</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">B</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">L</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">→</span> <br /><span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">→</span> <br /><span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">←</span> <br /><span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">←</span> <br /><span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEDOWN</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">V</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to page down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Goto to page up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">→</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Go to word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Indent</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Move lines down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Move lines up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Outdent</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">INS</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">INSERT</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Overwrite</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Pagedown</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Pageup</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Y</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">⌘</span> + <span class="rokpad-key">Y</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Redo</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">D</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">D</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">BACKSPACE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span> <br /> <span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">DELETE</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Remove word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">A</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select all</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select page down</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select page up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↓</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to line end</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to line start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select to start</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">↑</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select up</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">←</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select word left</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">→</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Select word right</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac">';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">O</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Split line</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">7</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">7</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Toggle comment</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Transpose letters</span>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">';
$html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Z</span></span>';
$html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">⌘</span> + <span class="rokpad-key">Z</span></span>';
$html[] = ' <span class="rokpad-kbd-desc">Undo</span>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' <div class="rok-popover-arrow"></div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Fullscreen / Windowed" data-placement="below-right" data-rokpad-fullscreen><i class="rokpad-icon-fullscreen"></i></div></li>';
//$html[] = ' <li><div class="rok-button rok-button-red"></div></li>';
//$html[] = ' <li><div class="rok-button rok-button-black"></div></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-shortcodes">';
$html[] = ' <ul>';
$html[] = ' <li data-rokpad-shortcode="<h1>{data}{cur}</h1>" class="rokpad-tip" data-original-title="Heading 1" data-placement="below-left"><i class="rokpad-icon-h1"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<h2>{data}{cur}</h2>" class="rokpad-tip" data-original-title="Heading 2" data-placement="below"><i class="rokpad-icon-h2"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<h3>{data}{cur}</h3>" class="rokpad-tip" data-original-title="Heading 3" data-placement="below"><i class="rokpad-icon-h3"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<strong>{data}{cur}</strong>" class="rokpad-tip" data-original-title="Bold/Strong Text" data-placement="below"><i class="rokpad-icon-bold"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<em>{data}{cur}</em>" class="rokpad-tip" data-original-title="Emphasized Text" data-placement="below"><i class="rokpad-icon-italic"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<u>{data}{cur}</u>" class="rokpad-tip" data-original-title="Underlined Text" data-placement="below"><i class="rokpad-icon-underline"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<ol>{n}{t}<li>{data}{cur}</li>{n}</ol>" class="rokpad-tip" data-original-title="Ordered List" data-placement="below"><i class="rokpad-icon-olist"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<ul>{n}{t}<li>{data}{cur}</li>{n}</ul>" class="rokpad-tip" data-original-title="Unordered List" data-placement="below"><i class="rokpad-icon-ulist"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<img src=\'{cur}\' alt=\'{data}\' />" class="rokpad-tip" data-original-title="Image" data-placement="below"><i class="rokpad-icon-image"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<p>{data}{cur}</p>" class="rokpad-tip" data-original-title="Paragraph" data-placement="below"><i class="rokpad-icon-paragraph"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<a href=\'{cur}\'>{data}</a>" class="rokpad-tip" data-original-title="Link" data-placement="below"><i class="rokpad-icon-link"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<hr />" class="rokpad-tip" data-original-title="Horizontal Rule (<hr />)" data-placement="below"><i class="rokpad-icon-hr"></i></li>';
$html[] = ' <li data-rokpad-shortcode="<{cur}>{data}</{cur}>" class="rokpad-tip" data-original-title="Universal Tag. Click and start typing the desired tag (ie, div). Hit ESC when done." data-placement="below"><i class="rokpad-icon-universal"></i></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-editor-container" data-rokpad-container>';
$html[] = ' <div id="' . $id . '-rokpad-editor" class="rokpad-editor"></div>';
$html[] = ' <textarea data-rokpad-original class="rokpad-editor-original" name="' . $name . '" id="' . $id . '" cols="' . $col . '" rows="' . $row . '">' . $content . '</textarea>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-actionbar" data-rokpad-actionbar>';
$html[] = ' <ul>';
$html[] = ' <li class="rokpad-column-1">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Regular Expression" data-placement="above-left" data-rokpad-action-setting="regExp"><i class="rokpad-icon-regexp"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Case Sensitive" data-placement="above" data-rokpad-action-setting="caseSensitive"><i class="rokpad-icon-casesensi"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Whole Word" data-placement="above" data-rokpad-action-setting="wholeWord"><i class="rokpad-icon-wholeword"></i></div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Reverse Direction" data-placement="above" data-rokpad-action-setting="backwards"><i class="rokpad-icon-reversedir"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Wrap" data-placement="above" data-rokpad-action-setting="wrap"><i class="rokpad-icon-wrap"></i></div>';
$html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="In Selection" data-placement="above" data-rokpad-action-setting="scope"><i class="rokpad-icon-inselection"></i></div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-column-2">';
$html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="find"><input type="text" placeholder="Find..." /></div>';
$html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="goto"><input type="text" placeholder="Goto Line..." /></div>';
$html[] = ' <div class="rok-input-wrapper rok-input-row-2" data-rokpad-action-method="replace"><input type="text" placeholder="Replace..." /></div>';
$html[] = ' </li>';
$html[] = ' <li class="rokpad-column-3">';
$html[] = ' <div class="rok-input-row-1">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="find">Find</div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="findAll">All</div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Previous" data-placement="above" data-rokpad-action="findPrevious"><i class="rokpad-icon-prev"></i></div>';
$html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Next" data-placement="above-right" data-rokpad-action="findNext"><i class="rokpad-icon-next"></i></div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="goto">Goto Line</div>';
$html[] = ' </div>';
$html[] = ' <div class="rok-input-row-2">';
$html[] = ' <div class="rok-buttons-group">';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replace">Replace</div>';
$html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replaceAll">All</div>';
$html[] = ' </div>';
$html[] = ' </div>';
$html[] = ' </li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = ' <div class="rokpad-statusbar">';
$html[] = ' <ul data-rokpad-dropdown="mode" class="rok-dropdown">';
$html[] = ' <li data-rokpad-mode="css"><a href="#">CSS</a></li>';
$html[] = ' <li data-rokpad-mode="html"><a href="#">HTML</a></li>';
$html[] = ' <li data-rokpad-mode="javascript"><a href="#">JavaScript</a></li>';
$html[] = ' <li data-rokpad-mode="json"><a href="#">JSON</a></li>';
$html[] = ' <li data-rokpad-mode="less"><a href="#">LESS</a></li>';
$html[] = ' <li data-rokpad-mode="markdown"><a href="#">Markdown</a></li>';
$html[] = ' <li data-rokpad-mode="php"><a href="#">PHP</a></li>';
$html[] = ' <li data-rokpad-mode="sql"><a href="#">SQL</a></li>';
$html[] = ' <li data-rokpad-mode="text"><a href="#">Plain Text</a></li>';
$html[] = ' <li data-rokpad-mode="textile"><a href="#">Textile</a></li>';
$html[] = ' <li data-rokpad-mode="xml"><a href="#">XML</a></li>';
$html[] = ' </ul>';
$html[] = ' <ul data-rokpad-dropdown="tabs" class="rok-dropdown">';
$html[] = ' <li data-rokpad-softtabs="0"><a href="#">Indent Using Spaces</a></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li data-rokpad-tabsize="1"><a href="#">Tab Width: 1</a></li>';
$html[] = ' <li data-rokpad-tabsize="2"><a href="#">Tab Width: 2</a></li>';
$html[] = ' <li data-rokpad-tabsize="3"><a href="#">Tab Width: 3</a></li>';
$html[] = ' <li data-rokpad-tabsize="4"><a href="#">Tab Width: 4</a></li>';
$html[] = ' <li data-rokpad-tabsize="5"><a href="#">Tab Width: 5</a></li>';
$html[] = ' <li data-rokpad-tabsize="6"><a href="#">Tab Width: 6</a></li>';
$html[] = ' <li data-rokpad-tabsize="7"><a href="#">Tab Width: 7</a></li>';
$html[] = ' <li data-rokpad-tabsize="8"><a href="#">Tab Width: 8</a></li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-left">';
$html[] = ' <li data-rokpad-lastsave>Last save: <span data-rokpad-savedate>never</span></li>';
$html[] = ' </ul>';
$html[] = ' <ul class="rok-right">';
$html[] = ' <li data-rokpad-tabsize data-rokpad-toggle="tabs">Tab Size: <span>4</span></li>';
$html[] = ' <li class="divider"></li>';
$html[] = ' <li data-rokpad-mode data-rokpad-toggle="mode">Mode: <span>HTML</span></li>';
$html[] = ' </ul>';
$html[] = ' </div>';
$html[] = '</div>';
$html[] = $buttons;
$output = "";
$output .= implode("\n", $html);
return $output;
}
/**
* @param $name
* @param $buttons
* @param $asset
* @param $author
*
* @return string
*/
protected function _displayButtons($name, $buttons, $asset, $author)
{
// Load modal popup behavior
JHtml::_('behavior.modal', 'a.modal-button');
$args['name'] = $name;
$args['event'] = 'onGetInsertMethod';
$return = '';
$results[] = $this->update($args);
foreach ($results as $result) {
if (is_string($result) && trim($result)) {
$return .= $result;
}
}
if (is_array($buttons) || (is_bool($buttons) && $buttons)) {
$results = $this->_subject->getButtons($name, $buttons, $asset, $author);
$version = new JVersion();
if (version_compare($version->getShortVersion(), '3.0', '>=')) {
/*
* This will allow plugins to attach buttons or change the behavior on the fly using AJAX
*/
$return .= "\n<div id=\"editor-xtd-buttons\" class=\"btn-toolbar pull-left\">\n";
$return .= "\n<div class=\"btn-toolbar\">\n";
foreach ($results as $button)
{
/*
* Results should be an object
*/
if ( $button->get('name') ) {
$modal = ($button->get('modal')) ? ' class="modal-button btn"' : null;
$href = ($button->get('link')) ? ' class="btn" href="'.JURI::base().$button->get('link').'"' : null;
$onclick = ($button->get('onclick')) ? ' onclick="'.$button->get('onclick').'"' : '';
$title = ($button->get('title')) ? $button->get('title') : $button->get('text');
$return .= '<a' . $modal . ' title="' . $title . '"' . $href . $onclick . ' rel="' . $button->get('options')
. '"><i class="icon-' . $button->get('name'). '"></i> ' . $button->get('text') . "</a>\n";
}
}
$return .= "</div>\n";
$return .= "</div>\n";
} else {
// This will allow plugins to attach buttons or change the behavior on the fly using AJAX
$return .= "\n".'<div id="editor-xtd-buttons"><div class="btn-toolbar pull-left rokpad-clearfix">'."\n";
foreach ($results as $button) {
// Results should be an object
if ($button->get('name')) {
$modal = ($button->get('modal')) ? 'class="modal-button"' : null;
$href = ($button->get('link')) ? 'href="' . JURI::base() . $button->get('link') . '"' : null;
$onclick = ($button->get('onclick')) ? 'onclick="' . $button->get('onclick') . '"' : null;
$title = ($button->get('title')) ? $button->get('title') : $button->get('text');
$return .= "\n".'<div class="button2-left"><div class="' . $button->get('name') . '">';
$return .= '<a ' . $modal . ' title="' . $title . '" ' . $href . ' ' . $onclick . ' rel="' . $button->get('options') . '">';
$return .= $button->get('text') . '</a>'."\n".'</div>'."\n".'</div>'."\n";
}
}
$return .= '</div></div>'."\n";
}
}
return $return;
}
/**
* @return string
*/
protected function _appendCacheToken()
{
return '?cache=' . $this->_version;
}
/**
*
*/
protected function compileLess()
{
$document = JFactory::getDocument();
$assets = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad' . DIRECTORY_SEPARATOR . 'assets';
@include_once($assets . '/less/mixins/lessc.inc.php');
if (defined('DEV') && DEV) {
try {
$css_file = $assets . '/styles/rokpad.css';
@unlink($css_file);
lessc::ccompile($assets . '/less/global.less', $css_file);
} catch (exception $e) {
JError::raiseError('LESS Compiler', $e->getMessage());
}
}
$document->addStyleSheet($this->_basepath . 'assets/styles/rokpad.css' . $this->_appendCacheToken());
}
/**
*
*/
protected function compileJS()
{
$document = JFactory::getDocument();
$rokpad = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad';
if (defined('DEV') && DEV) {
$buffer = "";
$assets = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR;
$app = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR;
$files = array(
$assets . 'moofx',
$app. 'respond', $app . 'jstorage', $app . 'beautify-html', $app . 'Twipsy',
$app . 'RokPad', $app . 'RokPad.ACE', $app. 'RokPad.Functs'
);
foreach ($files as $file) {
$file = $file . '.js';
$content = false;
if (file_exists($file)) $content = file_get_contents($file);
$buffer .= (!$content) ? "\n\n !!! File not Found: " . $file . " !!! \n\n" : $content;
}
file_put_contents($assets . 'rokpad.js', $buffer);
}
$document->addScript($this->_basepath . 'ace/ace.js' . $this->_appendCacheToken());
$document->addScript($this->_basepath . 'assets/js/rokpad.js' . $this->_appendCacheToken());
}
/**
* @return string
*/
protected function getJSParams()
{
$document = JFactory::getDocument();
$params = $this->params->toArray();
if (!array_key_exists('theme', $params)) {
$params = array(
'theme' => 'fluidvision',
'font-size' => '12px',
'fold-style' => 'markbeginend',
'use-wrap-mode' => 'free',
'selection-style' => '1',
'highlight-active-line' => '1',
'highlight-selected-word' => '1',
'show-invisibles' => '0',
'show-gutter' => '1',
'show-print-margin' => '1',
'fade-fold-widgets' => '0',
'autosave-enabled' => '0',
'autosave-time' => '5'
);
}
$data = "";
$data .= "var RokPadDefaultSettings = {";
foreach ($params as $param => $value) {
$data .= "'" . $param . "': '" . $value . "', ";
}
$data = substr($data, 0, strlen($data) - 2);
$data .= "}, RokPadAcePath = '".$this->_acepath."';";
return $data;
}
}
| cnpisit/myangkorpeopel | plugins/editors/rokpad/rokpad.php | PHP | gpl-2.0 | 50,100 |
package app.astrosoft.ui.cal;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.plaf.basic.BasicArrowButton;
import app.astrosoft.ui.util.UIUtil;
public class JCalendarCombo extends JPanel implements Observer {
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
private boolean condition;
private JWindow window;
private JCalendar calendar;
private JTextField textField;
private int startYear;
private int endYear;
public JCalendarCombo( ) {
condition = false;
startYear = 1801;
endYear = 2099;
calendar = new JCalendar( );
initializeJCalendarCombo( );
}
public JCalendarCombo( int firstDay, boolean showCurrentDate ) {
condition = false;
startYear = 1801;
endYear = 2099;
calendar = new JCalendar( firstDay, showCurrentDate );
initializeJCalendarCombo( );
}
public JCalendarCombo(
int firstDay, boolean showCurrentDate, int startYear, int endYear ) {
condition = false;
this.startYear = startYear;
this.endYear = endYear;
calendar =
new JCalendar( firstDay, showCurrentDate, startYear, endYear );
initializeJCalendarCombo( );
}
private final void initializeJCalendarCombo( ) {
textField = new JTextField( 10 );
textField.setEditable( false );
textField.setBackground( new Color( 255, 255, 255 ) );
javax.swing.JButton button =
new BasicArrowButton(
5, new Color( 255, 255, 255 ), new Color( 0, 0, 0 ),
new Color( 0, 0, 0 ), new Color( 0, 0, 0 ) );
setLayout( new BorderLayout( ) );
add( textField, "Center" );
add( button, "East" );
setSelectedDate( );
button.addActionListener(
new ActionListener( ) {
public void actionPerformed( ActionEvent e ) {
if ( !condition ) {
condition = true;
window =
new JWindow(
( Window ) textField.getTopLevelAncestor( ) );
window.getContentPane( ).setLayout(
new BorderLayout( ) );
//window.getContentPane().setBackground(new Color(0,0,0));
calendar.initializeCalendar( );
window.getContentPane( ).add( calendar, "Center" );
window.pack( );
UIUtil.setWindowLocation(window, textField);
// TODO: Remove later since this is replaced by UIUtil.setWindowLocation();
/*Point textFieldLocation =
textField.getLocationOnScreen( );
Dimension size = textField.getSize( );
Dimension windowSize = window.getSize( );
Dimension screenSize =
Toolkit.getDefaultToolkit( ).getScreenSize( );
if (
( ( textFieldLocation.x
- ( windowSize.width - size.width ) ) <= 0 )
&& ( ( textFieldLocation.y + size.height
+ windowSize.height ) >= screenSize.height ) ) {
window.setLocation(
0, textFieldLocation.y - windowSize.height );
} else if (
( textFieldLocation.x
- ( windowSize.width - size.width ) ) <= 0 ) {
window.setLocation(
0, textFieldLocation.y + size.height );
} else if (
( textFieldLocation.y + size.height
+ windowSize.height ) >= screenSize.height ) {
window.setLocation(
textFieldLocation.x
- ( windowSize.width - size.width ),
textFieldLocation.y - windowSize.height );
} else {
window.setLocation(
textFieldLocation.x
- ( windowSize.width - size.width ),
textFieldLocation.y + size.height );
}*/
window.setVisible( true );
} else {
window.dispose( );
setSelectedDate( );
condition = false;
}
}
} );
addAncestorListener(
new AncestorListener( ) {
public void ancestorAdded( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
public void ancestorMoved( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
public void ancestorRemoved( AncestorEvent e ) {
if ( condition ) {
condition = false;
setSelectedDate( );
window.dispose( );
}
}
} );
calendar.buttonItemListener.addObserver( this );
}
private final void setSelectedDate( ) {
textField.setText(
calendar.getDay( ) + "/" + calendar.getMonth( ) + "/"
+ calendar.getYear( ) );
condition = false;
}
public final void setSelectedDate( int year, int month, int day ) {
calendar.setDay( ( new Integer( day ) ).toString( ) );
calendar.setMonth( ( new Integer( month ) ).toString( ) );
calendar.setYear( ( new Integer( year ) ).toString( ) );
calendar.showCalendarForDate( year, month );
textField.setText(
calendar.getDay( ) + "/" + calendar.getMonth( ) + "/"
+ calendar.getYear( ) );
condition = false;
}
public final String getSelectedDate( ) {
return textField.getText( );
}
public final String getSelectedDay( ) {
return calendar.getDay( );
}
public final String getSelectedMonth( ) {
return calendar.getMonth( );
}
public final String getSelectedYear( ) {
return calendar.getYear( );
}
public void update( Observable observable, Object object ) {
window.dispose( );
setSelectedDate( );
}
}
| erajasekar/Astrosoft | src/app/astrosoft/ui/cal/JCalendarCombo.java | Java | gpl-2.0 | 7,350 |
/* $Id: ldrkStuff.cpp $ */
/** @file
* IPRT - Binary Image Loader, kLdr Interface.
*/
/*
* Copyright (C) 2006-2007 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP RTLOGGROUP_LDR
#include <iprt/ldr.h>
#include "internal/iprt.h"
#include <iprt/file.h>
#include <iprt/alloc.h>
#include <iprt/alloca.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/path.h>
#include <iprt/log.h>
#include <iprt/param.h>
#include <iprt/err.h>
#include "internal/ldr.h"
#define KLDR_ALREADY_INCLUDE_STD_TYPES
#define KLDR_NO_KLDR_H_INCLUDES
#include <k/kLdr.h>
#include <k/kRdrAll.h>
#include <k/kErr.h>
#include <k/kErrors.h>
#include <k/kMagics.h>
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* kLdr file provider.
*/
typedef struct RTKLDRRDR
{
/** The core. */
KRDR Core;
/** The IPRT bit reader. */
PRTLDRREADER pReader;
} RTKLDRRDR, *PRTKLDRRDR;
/**
* IPRT module.
*/
typedef struct RTLDRMODKLDR
{
/** The Core module structure. */
RTLDRMODINTERNAL Core;
/** The kLdr module. */
PKLDRMOD pMod;
} RTLDRMODKLDR, *PRTLDRMODKLDR;
/**
* Arguments for a RTLDRMODKLDR callback wrapper.
*/
typedef struct RTLDRMODKLDRARGS
{
union
{
PFNRT pfn;
PFNRTLDRENUMDBG pfnEnumDbgInfo;
PFNRTLDRENUMSYMS pfnEnumSyms;
PFNRTLDRIMPORT pfnGetImport;
} u;
void *pvUser;
const void *pvBits;
PRTLDRMODKLDR pMod;
int rc;
} RTLDRMODKLDRARGS, *PRTLDRMODKLDRARGS;
/**
* Converts a kLdr error code to an IPRT one.
*/
static int rtkldrConvertError(int krc)
{
if (!krc)
return VINF_SUCCESS;
switch (krc)
{
case KERR_INVALID_PARAMETER: return VERR_INVALID_PARAMETER;
case KERR_INVALID_HANDLE: return VERR_INVALID_HANDLE;
case KERR_NO_MEMORY: return VERR_NO_MEMORY;
case KLDR_ERR_UNKNOWN_FORMAT:
case KLDR_ERR_MZ_NOT_SUPPORTED: return VERR_MZ_EXE_NOT_SUPPORTED;
case KLDR_ERR_NE_NOT_SUPPORTED: return VERR_NE_EXE_NOT_SUPPORTED;
case KLDR_ERR_LX_NOT_SUPPORTED: return VERR_LX_EXE_NOT_SUPPORTED;
case KLDR_ERR_LE_NOT_SUPPORTED: return VERR_LE_EXE_NOT_SUPPORTED;
case KLDR_ERR_PE_NOT_SUPPORTED: return VERR_PE_EXE_NOT_SUPPORTED;
case KLDR_ERR_ELF_NOT_SUPPORTED: return VERR_ELF_EXE_NOT_SUPPORTED;
case KLDR_ERR_MACHO_NOT_SUPPORTED: return VERR_INVALID_EXE_SIGNATURE;
case KLDR_ERR_AOUT_NOT_SUPPORTED: return VERR_AOUT_EXE_NOT_SUPPORTED;
case KLDR_ERR_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND;
case KLDR_ERR_PREREQUISITE_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND;
case KLDR_ERR_MAIN_STACK_ALLOC_FAILED: return VERR_NO_MEMORY;
case KERR_BUFFER_OVERFLOW: return VERR_BUFFER_OVERFLOW;
case KLDR_ERR_SYMBOL_NOT_FOUND: return VERR_SYMBOL_NOT_FOUND;
case KLDR_ERR_FORWARDER_SYMBOL: return VERR_BAD_EXE_FORMAT;
case KLDR_ERR_BAD_FIXUP: AssertMsgFailedReturn(("KLDR_ERR_BAD_FIXUP\n"), VERR_BAD_EXE_FORMAT);
case KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS: return VERR_BAD_EXE_FORMAT;
case KLDR_ERR_NO_DEBUG_INFO: return VERR_FILE_NOT_FOUND;
case KLDR_ERR_ALREADY_MAPPED: return VERR_WRONG_ORDER;
case KLDR_ERR_NOT_MAPPED: return VERR_WRONG_ORDER;
case KLDR_ERR_ADDRESS_OVERFLOW: return VERR_NUMBER_TOO_BIG;
case KLDR_ERR_TODO: return VERR_NOT_IMPLEMENTED;
case KLDR_ERR_NOT_LOADED_DYNAMICALLY:
case KCPU_ERR_ARCH_CPU_NOT_COMPATIBLE:
case KLDR_ERR_TOO_LONG_FORWARDER_CHAIN:
case KLDR_ERR_MODULE_TERMINATING:
case KLDR_ERR_PREREQUISITE_MODULE_TERMINATING:
case KLDR_ERR_MODULE_INIT_FAILED:
case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED:
case KLDR_ERR_MODULE_INIT_FAILED_ALREADY:
case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED_ALREADY:
case KLDR_ERR_PREREQUISITE_RECURSED_TOO_DEEPLY:
case KLDR_ERR_THREAD_ATTACH_FAILED:
case KRDR_ERR_TOO_MANY_MAPPINGS:
case KLDR_ERR_NOT_DLL:
case KLDR_ERR_NOT_EXE:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_PE_UNSUPPORTED_MACHINE:
case KLDR_ERR_PE_BAD_FILE_HEADER:
case KLDR_ERR_PE_BAD_OPTIONAL_HEADER:
case KLDR_ERR_PE_BAD_SECTION_HEADER:
case KLDR_ERR_PE_BAD_FORWARDER:
case KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND:
case KLDR_ERR_PE_BAD_FIXUP:
case KLDR_ERR_PE_BAD_IMPORT:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_LX_BAD_HEADER:
case KLDR_ERR_LX_BAD_LOADER_SECTION:
case KLDR_ERR_LX_BAD_FIXUP_SECTION:
case KLDR_ERR_LX_BAD_OBJECT_TABLE:
case KLDR_ERR_LX_BAD_PAGE_MAP:
case KLDR_ERR_LX_BAD_ITERDATA:
case KLDR_ERR_LX_BAD_ITERDATA2:
case KLDR_ERR_LX_BAD_BUNDLE:
case KLDR_ERR_LX_NO_SONAME:
case KLDR_ERR_LX_BAD_SONAME:
case KLDR_ERR_LX_BAD_FORWARDER:
case KLDR_ERR_LX_NRICHAIN_NOT_SUPPORTED:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
case KLDR_ERR_MACHO_OTHER_ENDIAN_NOT_SUPPORTED:
case KLDR_ERR_MACHO_BAD_HEADER:
case KLDR_ERR_MACHO_UNSUPPORTED_FILE_TYPE:
case KLDR_ERR_MACHO_UNSUPPORTED_MACHINE:
case KLDR_ERR_MACHO_BAD_LOAD_COMMAND:
case KLDR_ERR_MACHO_UNKNOWN_LOAD_COMMAND:
case KLDR_ERR_MACHO_UNSUPPORTED_LOAD_COMMAND:
case KLDR_ERR_MACHO_BAD_SECTION:
case KLDR_ERR_MACHO_UNSUPPORTED_SECTION:
#ifdef KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION
case KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION:
case KLDR_ERR_MACHO_UNSUPPORTED_TERM_SECTION:
#endif
case KLDR_ERR_MACHO_UNKNOWN_SECTION:
case KLDR_ERR_MACHO_BAD_SECTION_ORDER:
case KLDR_ERR_MACHO_BIT_MIX:
case KLDR_ERR_MACHO_BAD_OBJECT_FILE:
case KLDR_ERR_MACHO_BAD_SYMBOL:
case KLDR_ERR_MACHO_UNSUPPORTED_FIXUP_TYPE:
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE);
default:
if (RT_FAILURE(krc))
return krc;
AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_NO_TRANSLATION);
}
}
/**
* Converts a IPRT error code to an kLdr one.
*/
static int rtkldrConvertErrorFromIPRT(int rc)
{
if (RT_SUCCESS(rc))
return 0;
switch (rc)
{
case VERR_NO_MEMORY: return KERR_NO_MEMORY;
case VERR_INVALID_PARAMETER: return KERR_INVALID_PARAMETER;
case VERR_INVALID_HANDLE: return KERR_INVALID_HANDLE;
case VERR_BUFFER_OVERFLOW: return KERR_BUFFER_OVERFLOW;
default:
return rc;
}
}
/** @copydoc KLDRRDROPS::pfnCreate
* @remark This is a dummy which isn't used. */
static int rtkldrRdr_Create( PPKRDR ppRdr, const char *pszFilename)
{
NOREF(ppRdr); NOREF(pszFilename);
AssertReleaseFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnDestroy */
static int rtkldrRdr_Destroy( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnDestroy(pReader);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnRead */
static int rtkldrRdr_Read( PKRDR pRdr, void *pvBuf, KSIZE cb, KFOFF off)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnRead(pReader, pvBuf, cb, off);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnAllMap */
static int rtkldrRdr_AllMap( PKRDR pRdr, const void **ppvBits)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnMap(pReader, ppvBits);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnAllUnmap */
static int rtkldrRdr_AllUnmap(PKRDR pRdr, const void *pvBits)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
int rc = pReader->pfnUnmap(pReader, pvBits);
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc KLDRRDROPS::pfnSize */
static KFOFF rtkldrRdr_Size( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return (KFOFF)pReader->pfnSize(pReader);
}
/** @copydoc KLDRRDROPS::pfnTell */
static KFOFF rtkldrRdr_Tell( PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return (KFOFF)pReader->pfnTell(pReader);
}
/** @copydoc KLDRRDROPS::pfnName */
static const char * rtkldrRdr_Name(PKRDR pRdr)
{
PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
return pReader->pfnLogName(pReader);
}
/** @copydoc KLDRRDROPS::pfnNativeFH */
static KIPTR rtkldrRdr_NativeFH(PKRDR pRdr)
{
NOREF(pRdr);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnPageSize */
static KSIZE rtkldrRdr_PageSize(PKRDR pRdr)
{
NOREF(pRdr);
return PAGE_SIZE;
}
/** @copydoc KLDRRDROPS::pfnMap */
static int rtkldrRdr_Map( PKRDR pRdr, void **ppvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fFixed)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(ppvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fFixed);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnRefresh */
static int rtkldrRdr_Refresh( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnProtect */
static int rtkldrRdr_Protect( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fUnprotectOrProtect)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fUnprotectOrProtect);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnUnmap */
static int rtkldrRdr_Unmap( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments)
{
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments);
AssertFailed();
return -1;
}
/** @copydoc KLDRRDROPS::pfnDone */
static void rtkldrRdr_Done( PKRDR pRdr)
{
NOREF(pRdr);
//PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader;
}
/**
* The file reader operations.
* We provide our own based on IPRT instead of using the kLdr ones.
*/
extern "C" const KRDROPS g_kLdrRdrFileOps;
extern "C" const KRDROPS g_kLdrRdrFileOps =
{
/* .pszName = */ "IPRT",
/* .pNext = */ NULL,
/* .pfnCreate = */ rtkldrRdr_Create,
/* .pfnDestroy = */ rtkldrRdr_Destroy,
/* .pfnRead = */ rtkldrRdr_Read,
/* .pfnAllMap = */ rtkldrRdr_AllMap,
/* .pfnAllUnmap = */ rtkldrRdr_AllUnmap,
/* .pfnSize = */ rtkldrRdr_Size,
/* .pfnTell = */ rtkldrRdr_Tell,
/* .pfnName = */ rtkldrRdr_Name,
/* .pfnNativeFH = */ rtkldrRdr_NativeFH,
/* .pfnPageSize = */ rtkldrRdr_PageSize,
/* .pfnMap = */ rtkldrRdr_Map,
/* .pfnRefresh = */ rtkldrRdr_Refresh,
/* .pfnProtect = */ rtkldrRdr_Protect,
/* .pfnUnmap = */ rtkldrRdr_Unmap,
/* .pfnDone = */ rtkldrRdr_Done,
/* .u32Dummy = */ 42
};
/** @copydoc RTLDROPS::pfnClose */
static DECLCALLBACK(int) rtkldr_Close(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
int rc = kLdrModClose(pModkLdr);
return rtkldrConvertError(rc);
}
/** @copydoc RTLDROPS::pfnDone */
static DECLCALLBACK(int) rtkldr_Done(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
int rc = kLdrModMostlyDone(pModkLdr);
return rtkldrConvertError(rc);
}
/** @copydoc FNKLDRMODENUMSYMS */
static int rtkldrEnumSymbolsWrapper(PKLDRMOD pMod, uint32_t iSymbol,
const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion,
KLDRADDR uValue, uint32_t fKind, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod); NOREF(pszVersion); NOREF(fKind);
/* If not zero terminated we'll have to use a temporary buffer. */
const char *pszSymbol = pchSymbol;
if (pchSymbol && pchSymbol[cchSymbol])
{
char *psz = (char *)alloca(cchSymbol + 1);
memcpy(psz, pchSymbol, cchSymbol);
psz[cchSymbol] = '\0';
pszSymbol = psz;
}
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/* skip the underscore prefix. */
if (*pszSymbol == '_')
pszSymbol++;
#endif
int rc = pArgs->u.pfnEnumSyms(&pArgs->pMod->Core, pszSymbol, iSymbol, uValue, pArgs->pvUser);
if (RT_FAILURE(rc))
return rc; /* don't bother converting. */
return 0;
}
/** @copydoc RTLDROPS::pfnEnumSymbols */
static DECLCALLBACK(int) rtkldr_EnumSymbols(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits, RTUINTPTR BaseAddress,
PFNRTLDRENUMSYMS pfnCallback, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnEnumSyms = pfnCallback;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModEnumSymbols(pModkLdr, pvBits, BaseAddress,
fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL ? KLDRMOD_ENUM_SYMS_FLAGS_ALL : 0,
rtkldrEnumSymbolsWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnGetImageSize */
static DECLCALLBACK(size_t) rtkldr_GetImageSize(PRTLDRMODINTERNAL pMod)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
return kLdrModSize(pModkLdr);
}
/** @copydoc FNKLDRMODGETIMPORT */
static int rtkldrGetImportWrapper(PKLDRMOD pMod, uint32_t iImport, uint32_t iSymbol, const char *pchSymbol, KSIZE cchSymbol,
const char *pszVersion, PKLDRADDR puValue, uint32_t *pfKind, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod); NOREF(pszVersion); NOREF(pfKind);
/* If not zero terminated we'll have to use a temporary buffer. */
const char *pszSymbol = pchSymbol;
if (pchSymbol && pchSymbol[cchSymbol])
{
char *psz = (char *)alloca(cchSymbol + 1);
memcpy(psz, pchSymbol, cchSymbol);
psz[cchSymbol] = '\0';
pszSymbol = psz;
}
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/* skip the underscore prefix. */
if (*pszSymbol == '_')
pszSymbol++;
#endif
/* get the import module name - TODO: cache this */
const char *pszModule = NULL;
if (iImport != NIL_KLDRMOD_IMPORT)
{
char *pszBuf = (char *)alloca(64);
int rc = kLdrModGetImport(pMod, pArgs->pvBits, iImport, pszBuf, 64);
if (rc)
return rc;
pszModule = pszBuf;
}
/* do the query */
RTUINTPTR Value;
int rc = pArgs->u.pfnGetImport(&pArgs->pMod->Core, pszModule, pszSymbol, pszSymbol ? ~0 : iSymbol, &Value, pArgs->pvUser);
if (RT_SUCCESS(rc))
{
*puValue = Value;
return 0;
}
return rtkldrConvertErrorFromIPRT(rc);
}
/** @copydoc RTLDROPS::pfnGetBits */
static DECLCALLBACK(int) rtkldr_GetBits(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress,
PFNRTLDRIMPORT pfnGetImport, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnGetImport = pfnGetImport;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModGetBits(pModkLdr, pvBits, BaseAddress, rtkldrGetImportWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnRelocate */
static DECLCALLBACK(int) rtkldr_Relocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress,
RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnGetImport = pfnGetImport;
Args.pMod = (PRTLDRMODKLDR)pMod;
Args.pvBits = pvBits;
Args.rc = VINF_SUCCESS;
int rc = kLdrModRelocateBits(pModkLdr, pvBits, NewBaseAddress, OldBaseAddress, rtkldrGetImportWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
else
rc = rtkldrConvertError(rc);
return rc;
}
/** @copydoc RTLDROPS::pfnGetSymbolEx */
static DECLCALLBACK(int) rtkldr_GetSymbolEx(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress,
const char *pszSymbol, RTUINTPTR *pValue)
{
PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod;
KLDRADDR uValue;
#if defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
/*
* Add underscore prefix.
*/
if (pszSymbol)
{
size_t cch = strlen(pszSymbol);
char *psz = (char *)alloca(cch + 2);
memcpy(psz + 1, pszSymbol, cch + 1);
*psz = '_';
pszSymbol = psz;
}
#endif
int rc = kLdrModQuerySymbol(pModkLdr, pvBits, BaseAddress,
NIL_KLDRMOD_SYM_ORDINAL, pszSymbol, strlen(pszSymbol), NULL,
NULL, NULL, &uValue, NULL);
if (!rc)
{
*pValue = uValue;
return VINF_SUCCESS;
}
return rtkldrConvertError(rc);
}
/** @copydoc FNKLDRENUMDBG */
static int rtkldrEnumDbgInfoWrapper(PKLDRMOD pMod, KU32 iDbgInfo, KLDRDBGINFOTYPE enmType, KI16 iMajorVer, KI16 iMinorVer,
const char *pszPartNm, KLDRFOFF offFile, KLDRADDR LinkAddress, KLDRSIZE cb,
const char *pszExtFile, void *pvUser)
{
PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser;
NOREF(pMod);
RTLDRDBGINFOTYPE enmMyType;
switch (enmType)
{
case KLDRDBGINFOTYPE_UNKNOWN: enmMyType = RTLDRDBGINFOTYPE_UNKNOWN; break;
case KLDRDBGINFOTYPE_STABS: enmMyType = RTLDRDBGINFOTYPE_STABS; break;
case KLDRDBGINFOTYPE_DWARF: enmMyType = RTLDRDBGINFOTYPE_DWARF; break;
case KLDRDBGINFOTYPE_CODEVIEW: enmMyType = RTLDRDBGINFOTYPE_CODEVIEW; break;
case KLDRDBGINFOTYPE_WATCOM: enmMyType = RTLDRDBGINFOTYPE_WATCOM; break;
case KLDRDBGINFOTYPE_HLL: enmMyType = RTLDRDBGINFOTYPE_HLL; break;
default:
AssertFailed();
enmMyType = RTLDRDBGINFOTYPE_UNKNOWN;
break;
}
int rc = pArgs->u.pfnEnumDbgInfo(&pArgs->pMod->Core, iDbgInfo, enmMyType, iMajorVer, iMinorVer, pszPartNm,
offFile, LinkAddress, cb, pszExtFile, pArgs->pvUser);
if (RT_FAILURE(rc))
return rc; /* don't bother converting. */
return 0;
}
/** @copydoc RTLDROPS::pfnEnumDbgInfo */
static DECLCALLBACK(int) rtkldr_EnumDbgInfo(PRTLDRMODINTERNAL pMod, const void *pvBits,
PFNRTLDRENUMDBG pfnCallback, void *pvUser)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
RTLDRMODKLDRARGS Args;
Args.pvUser = pvUser;
Args.u.pfnEnumDbgInfo = pfnCallback;
Args.pvBits = pvBits;
Args.pMod = pThis;
Args.rc = VINF_SUCCESS;
int rc = kLdrModEnumDbgInfo(pThis->pMod, pvBits, rtkldrEnumDbgInfoWrapper, &Args);
if (Args.rc != VINF_SUCCESS)
rc = Args.rc;
return rc;
}
/** @copydoc RTLDROPS::pfnEnumSegments. */
static DECLCALLBACK(int) rtkldr_EnumSegments(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
RTLDRSEG Seg;
Seg.pchName = paSegments[iSeg].pchName;
Seg.cchName = paSegments[iSeg].cchName;
Seg.SelFlat = paSegments[iSeg].SelFlat;
Seg.Sel16bit = paSegments[iSeg].Sel16bit;
Seg.fFlags = paSegments[iSeg].fFlags;
AssertCompile(KLDRSEG_FLAG_16BIT == RTLDRSEG_FLAG_16BIT );
AssertCompile(KLDRSEG_FLAG_OS2_ALIAS16 == RTLDRSEG_FLAG_OS2_ALIAS16);
AssertCompile(KLDRSEG_FLAG_OS2_CONFORM == RTLDRSEG_FLAG_OS2_CONFORM);
AssertCompile(KLDRSEG_FLAG_OS2_IOPL == RTLDRSEG_FLAG_OS2_IOPL );
switch (paSegments[iSeg].enmProt)
{
default:
AssertMsgFailed(("%d\n", paSegments[iSeg].enmProt));
case KPROT_NOACCESS:
Seg.fProt = 0;
break;
case KPROT_READONLY: Seg.fProt = RTMEM_PROT_READ; break;
case KPROT_READWRITE: Seg.fProt = RTMEM_PROT_READ | RTMEM_PROT_WRITE; break;
case KPROT_WRITECOPY: Seg.fProt = RTMEM_PROT_WRITE; break;
case KPROT_EXECUTE: Seg.fProt = RTMEM_PROT_EXEC; break;
case KPROT_EXECUTE_READ: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ; break;
case KPROT_EXECUTE_READWRITE: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ | RTMEM_PROT_WRITE; break;
case KPROT_EXECUTE_WRITECOPY: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_WRITE; break;
}
Seg.cb = paSegments[iSeg].cb;
Seg.Alignment = paSegments[iSeg].Alignment;
Seg.LinkAddress = paSegments[iSeg].LinkAddress;
Seg.offFile = paSegments[iSeg].offFile;
Seg.cbFile = paSegments[iSeg].cbFile;
Seg.RVA = paSegments[iSeg].RVA;
Seg.cbMapped = paSegments[iSeg].cbMapped;
int rc = pfnCallback(pMod, &Seg, pvUser);
if (rc != VINF_SUCCESS)
return rc;
}
return VINF_SUCCESS;
}
/** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */
static DECLCALLBACK(int) rtkldr_LinkAddressToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress,
uint32_t *piSeg, PRTLDRADDR poffSeg)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*piSeg = iSeg;
*poffSeg = offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_LINK_ADDRESS;
}
/** @copydoc RTLDROPS::pfnLinkAddressToRva. */
static DECLCALLBACK(int) rtkldr_LinkAddressToRva(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*pRva = paSegments[iSeg].RVA + offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_RVA;
}
/** @copydoc RTLDROPS::pfnSegOffsetToRva. */
static DECLCALLBACK(int) rtkldr_SegOffsetToRva(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg,
PRTLDRADDR pRva)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
if (iSeg >= pThis->pMod->cSegments)
return VERR_LDR_INVALID_SEG_OFFSET;
PCKLDRSEG const pSegment = &pThis->pMod->aSegments[iSeg];
if ( offSeg > pSegment->cbMapped
&& offSeg > pSegment->cb
&& ( pSegment->cbFile < 0
|| offSeg > (uint64_t)pSegment->cbFile))
return VERR_LDR_INVALID_SEG_OFFSET;
*pRva = pSegment->RVA + offSeg;
return VINF_SUCCESS;
}
/** @copydoc RTLDROPS::pfnRvaToSegOffset. */
static DECLCALLBACK(int) rtkldr_RvaToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva,
uint32_t *piSeg, PRTLDRADDR poffSeg)
{
PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
uint32_t const cSegments = pThis->pMod->cSegments;
PCKLDRSEG paSegments = &pThis->pMod->aSegments[0];
for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++)
{
KLDRADDR offSeg = Rva - paSegments[iSeg].RVA;
if ( offSeg < paSegments[iSeg].cbMapped
|| offSeg < paSegments[iSeg].cb)
{
*piSeg = iSeg;
*poffSeg = offSeg;
return VINF_SUCCESS;
}
}
return VERR_LDR_INVALID_RVA;
}
/**
* Operations for a kLdr module.
*/
static const RTLDROPS g_rtkldrOps =
{
"kLdr",
rtkldr_Close,
NULL,
rtkldr_Done,
rtkldr_EnumSymbols,
/* ext */
rtkldr_GetImageSize,
rtkldr_GetBits,
rtkldr_Relocate,
rtkldr_GetSymbolEx,
rtkldr_EnumDbgInfo,
rtkldr_EnumSegments,
rtkldr_LinkAddressToSegOffset,
rtkldr_LinkAddressToRva,
rtkldr_SegOffsetToRva,
rtkldr_RvaToSegOffset,
42
};
/**
* Open a image using kLdr.
*
* @returns iprt status code.
* @param pReader The loader reader instance which will provide the raw image bits.
* @param fFlags Reserved, MBZ.
* @param enmArch CPU architecture specifier for the image to be loaded.
* @param phLdrMod Where to store the handle.
*/
int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod)
{
/* Convert enmArch to k-speak. */
KCPUARCH enmCpuArch;
switch (enmArch)
{
case RTLDRARCH_WHATEVER:
enmCpuArch = KCPUARCH_UNKNOWN;
break;
case RTLDRARCH_X86_32:
enmCpuArch = KCPUARCH_X86_32;
break;
case RTLDRARCH_AMD64:
enmCpuArch = KCPUARCH_AMD64;
break;
default:
return VERR_INVALID_PARAMETER;
}
/* Create a rtkldrRdr_ instance. */
PRTKLDRRDR pRdr = (PRTKLDRRDR)RTMemAllocZ(sizeof(*pRdr));
if (!pRdr)
return VERR_NO_MEMORY;
pRdr->Core.u32Magic = KRDR_MAGIC;
pRdr->Core.pOps = &g_kLdrRdrFileOps;
pRdr->pReader = pReader;
/* Try open it. */
PKLDRMOD pMod;
int krc = kLdrModOpenFromRdr(&pRdr->Core, fFlags, enmCpuArch, &pMod);
if (!krc)
{
/* Create a module wrapper for it. */
PRTLDRMODKLDR pNewMod = (PRTLDRMODKLDR)RTMemAllocZ(sizeof(*pNewMod));
if (pNewMod)
{
pNewMod->Core.u32Magic = RTLDRMOD_MAGIC;
pNewMod->Core.eState = LDR_STATE_OPENED;
pNewMod->Core.pOps = &g_rtkldrOps;
pNewMod->pMod = pMod;
*phLdrMod = &pNewMod->Core;
#ifdef LOG_ENABLED
Log(("rtldrkLdrOpen: '%s' (%s) %u segments\n",
pMod->pszName, pMod->pszFilename, pMod->cSegments));
for (unsigned iSeg = 0; iSeg < pMod->cSegments; iSeg++)
{
Log(("Segment #%-2u: RVA=%08llx cb=%08llx '%.*s'\n", iSeg,
pMod->aSegments[iSeg].RVA,
pMod->aSegments[iSeg].cb,
pMod->aSegments[iSeg].cchName,
pMod->aSegments[iSeg].pchName));
}
#endif
return VINF_SUCCESS;
}
kLdrModClose(pMod);
krc = KERR_NO_MEMORY;
}
return rtkldrConvertError(krc);
}
| VirtualMonitor/VirtualMonitor | src/VBox/Runtime/common/ldr/ldrkStuff.cpp | C++ | gpl-2.0 | 30,065 |
<?php
/*
Twando.com Free PHP Twitter Application
http://www.twando.com/
*/
if (!$content_id) {
exit;
}
global $q1a, $pass_msg;
?>
<h2>Tweet Settings for <?=htmlentities($q1a['screen_name'])?></h2>
<?php
if ($q1a['id'] == "") {
echo mainFuncs::push_response(7);
} else {
//List all options here
?>
<div class="tab_row">
<div class="tab_main" id="tab1">
<a href="javascript:ajax_tweet_settings_tab('tab1');">Post Quick Tweet</a>
</div><div class="tab_main" id="tab2">
<a href="javascript:ajax_tweet_settings_tab('tab2');">Scheduled Tweets</a>
</div><div class="tab_main" id="tab3">
<a href="javascript:ajax_tweet_settings_tab('tab3');">Schedule a Tweet</a>
</div><div class="tab_main" id="tab3">
<a href="javascript:ajax_tweet_settings_tab('tab5');">Schedule a Tweet With Image</a>
</div><div class="tab_main" id="tab4">
<a href="javascript:ajax_tweet_settings_tab('tab4');">Bulk CSV Tweet Upload</a>
</div>
</div>
<br style="clear: both;" />
<div id="update_div">
</div>
<form>
<input type="hidden" name="twitter_id" id="twitter_id" value="<?=$q1a['id']?>" />
<input type="hidden" name="page_id" id="page_id" value="1" />
<input type="hidden" name="pass_msg" id="pass_msg" value="<?=$pass_msg?>" />
</form>
<form method="post" action="" name="deltweet" id="deltweet">
<input type="hidden" name="a" id="a" value="deletetweet" />
<input type="hidden" name="deltweet_id" id="deltweet_id" value="" />
</form>
<form method="post" action="" name="edittweet" id="edittweet">
<input type="hidden" name="a" id="a" value="edittweet" />
<input type="hidden" name="edittweet_id" id="edittweet_id" value="" />
<input type="hidden" name="everyday" id="everyday" value="" />
</form>
<?php
//End of valid id
}
?>
<br style="clear: both;" />
<a href="<?=BASE_LINK_URL?>">Return to main admin screen</a>
| txt3rob/twando | inc/content/english/tweet_settings.php | PHP | gpl-2.0 | 1,874 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Contains the DB_common base class
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Database
* @package DB
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id$
* @link http://pear.php.net/package/DB
*/
/**
* Obtain the PEAR class so it can be extended from
*/
require_once dirname(__FILE__).'/../PEAR.php';
/**
* DB_common is the base class from which each database driver class extends
*
* All common methods are declared here. If a given DBMS driver contains
* a particular method, that method will overload the one here.
*
* @category Database
* @package DB
* @author Stig Bakken <ssb@php.net>
* @author Tomas V.V. Cox <cox@idecnet.com>
* @author Daniel Convissor <danielc@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: @package_version@
* @link http://pear.php.net/package/DB
*/
class DB_common extends PEAR
{
// {{{ properties
/**
* The current default fetch mode
* @var integer
*/
var $fetchmode = DB_FETCHMODE_ORDERED;
/**
* The name of the class into which results should be fetched when
* DB_FETCHMODE_OBJECT is in effect
*
* @var string
*/
var $fetchmode_object_class = 'stdClass';
/**
* Was a connection present when the object was serialized()?
* @var bool
* @see DB_common::__sleep(), DB_common::__wake()
*/
var $was_connected = null;
/**
* The most recently executed query
* @var string
*/
var $last_query = '';
/**
* Run-time configuration options
*
* The 'optimize' option has been deprecated. Use the 'portability'
* option instead.
*
* @var array
* @see DB_common::setOption()
*/
var $options = array(
'result_buffering' => 500,
'persistent' => false,
'ssl' => false,
'debug' => 0,
'seqname_format' => '%s_seq',
'autofree' => false,
'portability' => DB_PORTABILITY_NONE,
'optimize' => 'performance', // Deprecated. Use 'portability'.
);
/**
* The parameters from the most recently executed query
* @var array
* @since Property available since Release 1.7.0
*/
var $last_parameters = array();
/**
* The elements from each prepared statement
* @var array
*/
var $prepare_tokens = array();
/**
* The data types of the various elements in each prepared statement
* @var array
*/
var $prepare_types = array();
/**
* The prepared queries
* @var array
*/
var $prepared_queries = array();
// }}}
// {{{ DB_common
/**
* This constructor calls <kbd>$this->PEAR('DB_Error')</kbd>
*
* @return void
*/
function DB_common()
{
$this->PEAR('DB_Error');
}
// }}}
// {{{ __sleep()
/**
* Automatically indicates which properties should be saved
* when PHP's serialize() function is called
*
* @return array the array of properties names that should be saved
*/
function __sleep()
{
if ($this->connection) {
// Don't disconnect(), people use serialize() for many reasons
$this->was_connected = true;
} else {
$this->was_connected = false;
}
if (isset($this->autocommit)) {
return array('autocommit',
'dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
} else {
return array('dbsyntax',
'dsn',
'features',
'fetchmode',
'fetchmode_object_class',
'options',
'was_connected',
);
}
}
// }}}
// {{{ __wakeup()
/**
* Automatically reconnects to the database when PHP's unserialize()
* function is called
*
* The reconnection attempt is only performed if the object was connected
* at the time PHP's serialize() function was run.
*
* @return void
*/
function __wakeup()
{
if ($this->was_connected) {
$this->connect($this->dsn, $this->options);
}
}
// }}}
// {{{ __toString()
/**
* Automatic string conversion for PHP 5
*
* @return string a string describing the current PEAR DB object
*
* @since Method available since Release 1.7.0
*/
function __toString()
{
$info = strtolower(get_class($this));
$info .= ': (phptype=' . $this->phptype .
', dbsyntax=' . $this->dbsyntax .
')';
if ($this->connection) {
$info .= ' [connected]';
}
return $info;
}
// }}}
// {{{ toString()
/**
* DEPRECATED: String conversion method
*
* @return string a string describing the current PEAR DB object
*
* @deprecated Method deprecated in Release 1.7.0
*/
function toString()
{
return $this->__toString();
}
// }}}
// {{{ quoteString()
/**
* DEPRECATED: Quotes a string so it can be safely used within string
* delimiters in a query
*
* @param string $string the string to be quoted
*
* @return string the quoted string
*
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Method deprecated some time before Release 1.2
*/
function quoteString($string)
{
$string = $this->quote($string);
if ($string{0} == "'") {
return substr($string, 1, -1);
}
return $string;
}
// }}}
// {{{ quote()
/**
* DEPRECATED: Quotes a string so it can be safely used in a query
*
* @param string $string the string to quote
*
* @return string the quoted string or the string <samp>NULL</samp>
* if the value submitted is <kbd>null</kbd>.
*
* @see DB_common::quoteSmart(), DB_common::escapeSimple()
* @deprecated Deprecated in release 1.6.0
*/
function quote($string = null)
{
return ($string === null) ? 'NULL'
: "'" . str_replace("'", "''", $string) . "'";
}
// }}}
// {{{ quoteIdentifier()
/**
* Quotes a string so it can be safely used as a table or column name
*
* Delimiting style depends on which database driver is being used.
*
* NOTE: just because you CAN use delimited identifiers doesn't mean
* you SHOULD use them. In general, they end up causing way more
* problems than they solve.
*
* Portability is broken by using the following characters inside
* delimited identifiers:
* + backtick (<kbd>`</kbd>) -- due to MySQL
* + double quote (<kbd>"</kbd>) -- due to Oracle
* + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
*
* Delimited identifiers are known to generally work correctly under
* the following drivers:
* + mssql
* + mysql
* + mysqli
* + oci8
* + odbc(access)
* + odbc(db2)
* + pgsql
* + sqlite
* + sybase (must execute <kbd>set quoted_identifier on</kbd> sometime
* prior to use)
*
* InterBase doesn't seem to be able to use delimited identifiers
* via PHP 4. They work fine under PHP 5.
*
* @param string $str the identifier name to be quoted
*
* @return string the quoted identifier
*
* @since Method available since Release 1.6.0
*/
function quoteIdentifier($str)
{
return '"' . str_replace('"', '""', $str) . '"';
}
// }}}
// {{{ quoteSmart()
/**
* Formats input so it can be safely used in a query
*
* The output depends on the PHP data type of input and the database
* type being used.
*
* @param mixed $in the data to be formatted
*
* @return mixed the formatted data. The format depends on the input's
* PHP type:
* <ul>
* <li>
* <kbd>input</kbd> -> <samp>returns</samp>
* </li>
* <li>
* <kbd>null</kbd> -> the string <samp>NULL</samp>
* </li>
* <li>
* <kbd>integer</kbd> or <kbd>double</kbd> -> the unquoted number
* </li>
* <li>
* <kbd>bool</kbd> -> output depends on the driver in use
* Most drivers return integers: <samp>1</samp> if
* <kbd>true</kbd> or <samp>0</samp> if
* <kbd>false</kbd>.
* Some return strings: <samp>TRUE</samp> if
* <kbd>true</kbd> or <samp>FALSE</samp> if
* <kbd>false</kbd>.
* Finally one returns strings: <samp>T</samp> if
* <kbd>true</kbd> or <samp>F</samp> if
* <kbd>false</kbd>. Here is a list of each DBMS,
* the values returned and the suggested column type:
* <ul>
* <li>
* <kbd>dbase</kbd> -> <samp>T/F</samp>
* (<kbd>Logical</kbd>)
* </li>
* <li>
* <kbd>fbase</kbd> -> <samp>TRUE/FALSE</samp>
* (<kbd>BOOLEAN</kbd>)
* </li>
* <li>
* <kbd>ibase</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>ifx</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>msql</kbd> -> <samp>1/0</samp>
* (<kbd>INTEGER</kbd>)
* </li>
* <li>
* <kbd>mssql</kbd> -> <samp>1/0</samp>
* (<kbd>BIT</kbd>)
* </li>
* <li>
* <kbd>mysql</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* <li>
* <kbd>mysqli</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* <li>
* <kbd>oci8</kbd> -> <samp>1/0</samp>
* (<kbd>NUMBER(1)</kbd>)
* </li>
* <li>
* <kbd>odbc</kbd> -> <samp>1/0</samp>
* (<kbd>SMALLINT</kbd>) [1]
* </li>
* <li>
* <kbd>pgsql</kbd> -> <samp>TRUE/FALSE</samp>
* (<kbd>BOOLEAN</kbd>)
* </li>
* <li>
* <kbd>sqlite</kbd> -> <samp>1/0</samp>
* (<kbd>INTEGER</kbd>)
* </li>
* <li>
* <kbd>sybase</kbd> -> <samp>1/0</samp>
* (<kbd>TINYINT(1)</kbd>)
* </li>
* </ul>
* [1] Accommodate the lowest common denominator because not all
* versions of have <kbd>BOOLEAN</kbd>.
* </li>
* <li>
* other (including strings and numeric strings) ->
* the data with single quotes escaped by preceeding
* single quotes, backslashes are escaped by preceeding
* backslashes, then the whole string is encapsulated
* between single quotes
* </li>
* </ul>
*
* @see DB_common::escapeSimple()
* @since Method available since Release 1.6.0
*/
function quoteSmart($in)
{
if (is_int($in) || is_double($in)) {
return $in;
} elseif (is_bool($in)) {
return $in ? 1 : 0;
} elseif (is_null($in)) {
return 'NULL';
} else {
return "'" . $this->escapeSimple($in) . "'";
}
}
// }}}
// {{{ escapeSimple()
/**
* Escapes a string according to the current DBMS's standards
*
* In SQLite, this makes things safe for inserts/updates, but may
* cause problems when performing text comparisons against columns
* containing binary data. See the
* {@link http://php.net/sqlite_escape_string PHP manual} for more info.
*
* @param string $str the string to be escaped
*
* @return string the escaped string
*
* @see DB_common::quoteSmart()
* @since Method available since Release 1.6.0
*/
function escapeSimple($str)
{
return str_replace("'", "''", $str);
}
// }}}
// {{{ provides()
/**
* Tells whether the present driver supports a given feature
*
* @param string $feature the feature you're curious about
*
* @return bool whether this driver supports $feature
*/
function provides($feature)
{
return $this->features[$feature];
}
// }}}
// {{{ setFetchMode()
/**
* Sets the fetch mode that should be used by default for query results
*
* @param integer $fetchmode DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC
* or DB_FETCHMODE_OBJECT
* @param string $object_class the class name of the object to be returned
* by the fetch methods when the
* DB_FETCHMODE_OBJECT mode is selected.
* If no class is specified by default a cast
* to object from the assoc array row will be
* done. There is also the posibility to use
* and extend the 'DB_row' class.
*
* @see DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC, DB_FETCHMODE_OBJECT
*/
function setFetchMode($fetchmode, $object_class = 'stdClass')
{
switch ($fetchmode) {
case DB_FETCHMODE_OBJECT:
$this->fetchmode_object_class = $object_class;
case DB_FETCHMODE_ORDERED:
case DB_FETCHMODE_ASSOC:
$this->fetchmode = $fetchmode;
break;
default:
return $this->raiseError('invalid fetchmode mode');
}
}
// }}}
// {{{ setOption()
/**
* Sets run-time configuration options for PEAR DB
*
* Options, their data types, default values and description:
* <ul>
* <li>
* <var>autofree</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />should results be freed automatically when there are no
* more rows?
* </li><li>
* <var>result_buffering</var> <kbd>integer</kbd> = <samp>500</samp>
* <br />how many rows of the result set should be buffered?
* <br />In mysql: mysql_unbuffered_query() is used instead of
* mysql_query() if this value is 0. (Release 1.7.0)
* <br />In oci8: this value is passed to ocisetprefetch().
* (Release 1.7.0)
* </li><li>
* <var>debug</var> <kbd>integer</kbd> = <samp>0</samp>
* <br />debug level
* </li><li>
* <var>persistent</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />should the connection be persistent?
* </li><li>
* <var>portability</var> <kbd>integer</kbd> = <samp>DB_PORTABILITY_NONE</samp>
* <br />portability mode constant (see below)
* </li><li>
* <var>seqname_format</var> <kbd>string</kbd> = <samp>%s_seq</samp>
* <br />the sprintf() format string used on sequence names. This
* format is applied to sequence names passed to
* createSequence(), nextID() and dropSequence().
* </li><li>
* <var>ssl</var> <kbd>boolean</kbd> = <samp>false</samp>
* <br />use ssl to connect?
* </li>
* </ul>
*
* -----------------------------------------
*
* PORTABILITY MODES
*
* These modes are bitwised, so they can be combined using <kbd>|</kbd>
* and removed using <kbd>^</kbd>. See the examples section below on how
* to do this.
*
* <samp>DB_PORTABILITY_NONE</samp>
* turn off all portability features
*
* This mode gets automatically turned on if the deprecated
* <var>optimize</var> option gets set to <samp>performance</samp>.
*
*
* <samp>DB_PORTABILITY_LOWERCASE</samp>
* convert names of tables and fields to lower case when using
* <kbd>get*()</kbd>, <kbd>fetch*()</kbd> and <kbd>tableInfo()</kbd>
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + oci8
*
*
* <samp>DB_PORTABILITY_RTRIM</samp>
* right trim the data output by <kbd>get*()</kbd> <kbd>fetch*()</kbd>
*
*
* <samp>DB_PORTABILITY_DELETE_COUNT</samp>
* force reporting the number of rows deleted
*
* Some DBMS's don't count the number of rows deleted when performing
* simple <kbd>DELETE FROM tablename</kbd> queries. This portability
* mode tricks such DBMS's into telling the count by adding
* <samp>WHERE 1=1</samp> to the end of <kbd>DELETE</kbd> queries.
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + fbsql
* + mysql
* + mysqli
* + sqlite
*
*
* <samp>DB_PORTABILITY_NUMROWS</samp>
* enable hack that makes <kbd>numRows()</kbd> work in Oracle
*
* This mode gets automatically turned on in the following databases
* if the deprecated option <var>optimize</var> gets set to
* <samp>portability</samp>:
* + oci8
*
*
* <samp>DB_PORTABILITY_ERRORS</samp>
* makes certain error messages in certain drivers compatible
* with those from other DBMS's
*
* + mysql, mysqli: change unique/primary key constraints
* DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
*
* + odbc(access): MS's ODBC driver reports 'no such field' as code
* 07001, which means 'too few parameters.' When this option is on
* that code gets mapped to DB_ERROR_NOSUCHFIELD.
* DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD
*
* <samp>DB_PORTABILITY_NULL_TO_EMPTY</samp>
* convert null values to empty strings in data output by get*() and
* fetch*(). Needed because Oracle considers empty strings to be null,
* while most other DBMS's know the difference between empty and null.
*
*
* <samp>DB_PORTABILITY_ALL</samp>
* turn on all portability features
*
* -----------------------------------------
*
* Example 1. Simple setOption() example
* <code>
* $db->setOption('autofree', true);
* </code>
*
* Example 2. Portability for lowercasing and trimming
* <code>
* $db->setOption('portability',
* DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
* </code>
*
* Example 3. All portability options except trimming
* <code>
* $db->setOption('portability',
* DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
* </code>
*
* @param string $option option name
* @param mixed $value value for the option
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::$options
*/
function setOption($option, $value)
{
if (isset($this->options[$option])) {
$this->options[$option] = $value;
/*
* Backwards compatibility check for the deprecated 'optimize'
* option. Done here in case settings change after connecting.
*/
if ($option == 'optimize') {
if ($value == 'portability') {
switch ($this->phptype) {
case 'oci8':
$this->options['portability'] =
DB_PORTABILITY_LOWERCASE |
DB_PORTABILITY_NUMROWS;
break;
case 'fbsql':
case 'mysql':
case 'mysqli':
case 'sqlite':
$this->options['portability'] =
DB_PORTABILITY_DELETE_COUNT;
break;
}
} else {
$this->options['portability'] = DB_PORTABILITY_NONE;
}
}
return DB_OK;
}
return $this->raiseError("unknown option $option");
}
// }}}
// {{{ getOption()
/**
* Returns the value of an option
*
* @param string $option the option name you're curious about
*
* @return mixed the option's value
*/
function getOption($option)
{
if (isset($this->options[$option])) {
return $this->options[$option];
}
return $this->raiseError("unknown option $option");
}
// }}}
// {{{ prepare()
/**
* Prepares a query for multiple execution with execute()
*
* Creates a query that can be run multiple times. Each time it is run,
* the placeholders, if any, will be replaced by the contents of
* execute()'s $data argument.
*
* Three types of placeholders can be used:
* + <kbd>?</kbd> scalar value (i.e. strings, integers). The system
* will automatically quote and escape the data.
* + <kbd>!</kbd> value is inserted 'as is'
* + <kbd>&</kbd> requires a file name. The file's contents get
* inserted into the query (i.e. saving binary
* data in a db)
*
* Example 1.
* <code>
* $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
* $data = array(
* "John's text",
* "'it''s good'",
* 'filename.txt'
* );
* $res = $db->execute($sth, $data);
* </code>
*
* Use backslashes to escape placeholder characters if you don't want
* them to be interpreted as placeholders:
* <pre>
* "UPDATE foo SET col=? WHERE col='over \& under'"
* </pre>
*
* With some database backends, this is emulated.
*
* {@internal ibase and oci8 have their own prepare() methods.}}
*
* @param string $query the query to be prepared
*
* @return mixed DB statement resource on success. A DB_Error object
* on failure.
*
* @see DB_common::execute()
*/
function prepare($query)
{
$tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
PREG_SPLIT_DELIM_CAPTURE);
$token = 0;
$types = array();
$newtokens = array();
foreach ($tokens as $val) {
switch ($val) {
case '?':
$types[$token++] = DB_PARAM_SCALAR;
break;
case '&':
$types[$token++] = DB_PARAM_OPAQUE;
break;
case '!':
$types[$token++] = DB_PARAM_MISC;
break;
default:
$newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val);
}
}
$this->prepare_tokens[] = &$newtokens;
end($this->prepare_tokens);
$k = key($this->prepare_tokens);
$this->prepare_types[$k] = $types;
$this->prepared_queries[$k] = implode(' ', $newtokens);
return $k;
}
// }}}
// {{{ autoPrepare()
/**
* Automaticaly generates an insert or update query and pass it to prepare()
*
* @param string $table the table name
* @param array $table_fields the array of field names
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return resource the query handle
*
* @uses DB_common::prepare(), DB_common::buildManipSQL()
*/
function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT,
$where = false)
{
$query = $this->buildManipSQL($table, $table_fields, $mode, $where);
if (DB::isError($query)) {
return $query;
}
return $this->prepare($query);
}
// }}}
// {{{ autoExecute()
/**
* Automaticaly generates an insert or update query and call prepare()
* and execute() with it
*
* @param string $table the table name
* @param array $fields_values the associative array where $key is a
* field name and $value its value
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* @uses DB_common::autoPrepare(), DB_common::execute()
*/
function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT,
$where = false)
{
$sth = $this->autoPrepare($table, array_keys($fields_values), $mode,
$where);
if (DB::isError($sth)) {
return $sth;
}
$ret =& $this->execute($sth, array_values($fields_values));
$this->freePrepared($sth);
return $ret;
}
// }}}
// {{{ buildManipSQL()
/**
* Produces an SQL query string for autoPrepare()
*
* Example:
* <pre>
* buildManipSQL('table_sql', array('field1', 'field2', 'field3'),
* DB_AUTOQUERY_INSERT);
* </pre>
*
* That returns
* <samp>
* INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
* </samp>
*
* NOTES:
* - This belongs more to a SQL Builder class, but this is a simple
* facility.
* - Be carefull! If you don't give a $where param with an UPDATE
* query, all the records of the table will be updated!
*
* @param string $table the table name
* @param array $table_fields the array of field names
* @param int $mode a type of query to make:
* DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
* @param string $where for update queries: the WHERE clause to
* append to the SQL statement. Don't
* include the "WHERE" keyword.
*
* @return string the sql query for autoPrepare()
*/
function buildManipSQL($table, $table_fields, $mode, $where = false)
{
if (count($table_fields) == 0) {
return $this->raiseError(DB_ERROR_NEED_MORE_DATA);
}
$first = true;
switch ($mode) {
case DB_AUTOQUERY_INSERT:
$values = '';
$names = '';
foreach ($table_fields as $value) {
if ($first) {
$first = false;
} else {
$names .= ',';
$values .= ',';
}
$names .= $value;
$values .= '?';
}
return "INSERT INTO $table ($names) VALUES ($values)";
case DB_AUTOQUERY_UPDATE:
$set = '';
foreach ($table_fields as $value) {
if ($first) {
$first = false;
} else {
$set .= ',';
}
$set .= "$value = ?";
}
$sql = "UPDATE $table SET $set";
if ($where) {
$sql .= " WHERE $where";
}
return $sql;
default:
return $this->raiseError(DB_ERROR_SYNTAX);
}
}
// }}}
// {{{ execute()
/**
* Executes a DB statement prepared with prepare()
*
* Example 1.
* <code>
* $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
* $data = array(
* "John's text",
* "'it''s good'",
* 'filename.txt'
* );
* $res =& $db->execute($sth, $data);
* </code>
*
* @param resource $stmt a DB statement resource returned from prepare()
* @param mixed $data array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* {@internal ibase and oci8 have their own execute() methods.}}
*
* @see DB_common::prepare()
*/
function &execute($stmt, $data = array())
{
$realquery = $this->executeEmulateQuery($stmt, $data);
if (DB::isError($realquery)) {
return $realquery;
}
$result = $this->simpleQuery($realquery);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp =& new DB_result($this, $result);
return $tmp;
}
}
// }}}
// {{{ executeEmulateQuery()
/**
* Emulates executing prepared statements if the DBMS not support them
*
* @param resource $stmt a DB statement resource returned from execute()
* @param mixed $data array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a string containing the real query run when emulating
* prepare/execute. A DB_Error object on failure.
*
* @access protected
* @see DB_common::execute()
*/
function executeEmulateQuery($stmt, $data = array())
{
$stmt = (int)$stmt;
$data = (array)$data;
$this->last_parameters = $data;
if (count($this->prepare_types[$stmt]) != count($data)) {
$this->last_query = $this->prepared_queries[$stmt];
return $this->raiseError(DB_ERROR_MISMATCH);
}
$realquery = $this->prepare_tokens[$stmt][0];
$i = 0;
foreach ($data as $value) {
if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) {
$realquery .= $this->quoteSmart($value);
} elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) {
$fp = @fopen($value, 'rb');
if (!$fp) {
return $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
}
$realquery .= $this->quoteSmart(fread($fp, filesize($value)));
fclose($fp);
} else {
$realquery .= $value;
}
$realquery .= $this->prepare_tokens[$stmt][++$i];
}
return $realquery;
}
// }}}
// {{{ executeMultiple()
/**
* Performs several execute() calls on the same statement handle
*
* $data must be an array indexed numerically
* from 0, one execute call is done for every "row" in the array.
*
* If an error occurs during execute(), executeMultiple() does not
* execute the unfinished rows, but rather returns that error.
*
* @param resource $stmt query handle from prepare()
* @param array $data numeric array containing the
* data to insert into the query
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::prepare(), DB_common::execute()
*/
function executeMultiple($stmt, $data)
{
foreach ($data as $value) {
$res =& $this->execute($stmt, $value);
if (DB::isError($res)) {
return $res;
}
}
return DB_OK;
}
// }}}
// {{{ freePrepared()
/**
* Frees the internal resources associated with a prepared query
*
* @param resource $stmt the prepared statement's PHP resource
* @param bool $free_resource should the PHP resource be freed too?
* Use false if you need to get data
* from the result set later.
*
* @return bool TRUE on success, FALSE if $result is invalid
*
* @see DB_common::prepare()
*/
function freePrepared($stmt, $free_resource = true)
{
$stmt = (int)$stmt;
if (isset($this->prepare_tokens[$stmt])) {
unset($this->prepare_tokens[$stmt]);
unset($this->prepare_types[$stmt]);
unset($this->prepared_queries[$stmt]);
return true;
}
return false;
}
// }}}
// {{{ modifyQuery()
/**
* Changes a query string for various DBMS specific reasons
*
* It is defined here to ensure all drivers have this method available.
*
* @param string $query the query string to modify
*
* @return string the modified query string
*
* @access protected
* @see DB_mysql::modifyQuery(), DB_oci8::modifyQuery(),
* DB_sqlite::modifyQuery()
*/
function modifyQuery($query)
{
return $query;
}
// }}}
// {{{ modifyLimitQuery()
/**
* Adds LIMIT clauses to a query string according to current DBMS standards
*
* It is defined here to assure that all implementations
* have this method defined.
*
* @param string $query the query to modify
* @param int $from the row to start to fetching (0 = the first row)
* @param int $count the numbers of rows to fetch
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return string the query string with LIMIT clauses added
*
* @access protected
*/
function modifyLimitQuery($query, $from, $count, $params = array())
{
return $query;
}
// }}}
// {{{ query()
/**
* Sends a query to the database server
*
* The query string can be either a normal statement to be sent directly
* to the server OR if <var>$params</var> are passed the query can have
* placeholders and it will be passed through prepare() and execute().
*
* @param string $query the SQL query or the statement to prepare
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*
* @see DB_result, DB_common::prepare(), DB_common::execute()
*/
function &query($query, $params = array())
{
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$ret =& $this->execute($sth, $params);
$this->freePrepared($sth, false);
return $ret;
} else {
$this->last_parameters = array();
$result = $this->simpleQuery($query);
if ($result === DB_OK || DB::isError($result)) {
return $result;
} else {
$tmp =& new DB_result($this, $result);
return $tmp;
}
}
}
// }}}
// {{{ limitQuery()
/**
* Generates and executes a LIMIT query
*
* @param string $query the query
* @param intr $from the row to start to fetching (0 = the first row)
* @param int $count the numbers of rows to fetch
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed a new DB_result object for successful SELECT queries
* or DB_OK for successul data manipulation queries.
* A DB_Error object on failure.
*/
function &limitQuery($query, $from, $count, $params = array())
{
$query = $this->modifyLimitQuery($query, $from, $count, $params);
if (DB::isError($query)){
return $query;
}
$result =& $this->query($query, $params);
if (is_a($result, 'DB_result')) {
$result->setOption('limit_from', $from);
$result->setOption('limit_count', $count);
}
return $result;
}
// }}}
// {{{ getOne()
/**
* Fetches the first column of the first row from a query result
*
* Takes care of doing the query and freeing the results when finished.
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return mixed the returned value of the query.
* A DB_Error object on failure.
*/
function &getOne($query, $params = array())
{
$params = (array)$params;
// modifyLimitQuery() would be nice here, but it causes BC issues
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, DB_FETCHMODE_ORDERED);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row[0];
}
// }}}
// {{{ getRow()
/**
* Fetches the first row of data returned from a query result
*
* Takes care of doing the query and freeing the results when finished.
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use
*
* @return array the first row of results as an array.
* A DB_Error object on failure.
*/
function &getRow($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
// modifyLimitQuery() would be nice here, but it causes BC issues
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$err = $res->fetchInto($row, $fetchmode);
$res->free();
if ($err !== DB_OK) {
return $err;
}
return $row;
}
// }}}
// {{{ getCol()
/**
* Fetches a single column from a query result and returns it as an
* indexed array
*
* @param string $query the SQL query
* @param mixed $col which column to return (integer [column number,
* starting at 0] or string [column name])
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of items
* passed must match quantity of placeholders in
* query: meaning 1 placeholder for non-array
* parameters or 1 placeholder per array element.
*
* @return array the results as an array. A DB_Error object on failure.
*
* @see DB_common::query()
*/
function &getCol($query, $col = 0, $params = array())
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
$fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC;
if (!is_array($row = $res->fetchRow($fetchmode))) {
$ret = array();
} else {
if (!array_key_exists($col, $row)) {
$ret =& $this->raiseError(DB_ERROR_NOSUCHFIELD);
} else {
$ret = array($row[$col]);
while (is_array($row = $res->fetchRow($fetchmode))) {
$ret[] = $row[$col];
}
}
}
$res->free();
if (DB::isError($row)) {
$ret = $row;
}
return $ret;
}
// }}}
// {{{ getAssoc()
/**
* Fetches an entire query result and returns it as an
* associative array using the first column as the key
*
* If the result set contains more than two columns, the value
* will be an array of the values from column 2-n. If the result
* set contains only two columns, the returned value will be a
* scalar with the value of the second column (unless forced to an
* array with the $force_array parameter). A DB error code is
* returned on errors. If the result set contains fewer than two
* columns, a DB_ERROR_TRUNCATED error is returned.
*
* For example, if the table "mytable" contains:
*
* <pre>
* ID TEXT DATE
* --------------------------------
* 1 'one' 944679408
* 2 'two' 944679408
* 3 'three' 944679408
* </pre>
*
* Then the call getAssoc('SELECT id,text FROM mytable') returns:
* <pre>
* array(
* '1' => 'one',
* '2' => 'two',
* '3' => 'three',
* )
* </pre>
*
* ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
* <pre>
* array(
* '1' => array('one', '944679408'),
* '2' => array('two', '944679408'),
* '3' => array('three', '944679408')
* )
* </pre>
*
* If the more than one row occurs with the same value in the
* first column, the last row overwrites all previous ones by
* default. Use the $group parameter if you don't want to
* overwrite like this. Example:
*
* <pre>
* getAssoc('SELECT category,id,name FROM mytable', false, null,
* DB_FETCHMODE_ASSOC, true) returns:
*
* array(
* '1' => array(array('id' => '4', 'name' => 'number four'),
* array('id' => '6', 'name' => 'number six')
* ),
* '9' => array(array('id' => '4', 'name' => 'number four'),
* array('id' => '6', 'name' => 'number six')
* )
* )
* </pre>
*
* Keep in mind that database functions in PHP usually return string
* values for results regardless of the database's internal type.
*
* @param string $query the SQL query
* @param bool $force_array used only when the query returns
* exactly two columns. If true, the values
* of the returned array will be one-element
* arrays instead of scalars.
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of
* items passed must match quantity of
* placeholders in query: meaning 1
* placeholder for non-array parameters or
* 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use
* @param bool $group if true, the values of the returned array
* is wrapped in another array. If the same
* key value (in the first column) repeats
* itself, the values will be appended to
* this array instead of overwriting the
* existing values.
*
* @return array the associative array containing the query results.
* A DB_Error object on failure.
*/
function &getAssoc($query, $force_array = false, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
{
$params = (array)$params;
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if (DB::isError($res)) {
return $res;
}
if ($fetchmode == DB_FETCHMODE_DEFAULT) {
$fetchmode = $this->fetchmode;
}
$cols = $res->numCols();
if ($cols < 2) {
$tmp =& $this->raiseError(DB_ERROR_TRUNCATED);
return $tmp;
}
$results = array();
if ($cols > 2 || $force_array) {
// return array values
// XXX this part can be optimized
if ($fetchmode == DB_FETCHMODE_ASSOC) {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) {
reset($row);
$key = current($row);
unset($row[key($row)]);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} elseif ($fetchmode == DB_FETCHMODE_OBJECT) {
while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
$arr = get_object_vars($row);
$key = current($arr);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
} else {
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
// we shift away the first element to get
// indices running from 0 again
$key = array_shift($row);
if ($group) {
$results[$key][] = $row;
} else {
$results[$key] = $row;
}
}
}
if (DB::isError($row)) {
$results = $row;
}
} else {
// return scalar values
while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
if ($group) {
$results[$row[0]][] = $row[1];
} else {
$results[$row[0]] = $row[1];
}
}
if (DB::isError($row)) {
$results = $row;
}
}
$res->free();
return $results;
}
// }}}
// {{{ getAll()
/**
* Fetches all of the rows from a query result
*
* @param string $query the SQL query
* @param mixed $params array, string or numeric data to be used in
* execution of the statement. Quantity of
* items passed must match quantity of
* placeholders in query: meaning 1
* placeholder for non-array parameters or
* 1 placeholder per array element.
* @param int $fetchmode the fetch mode to use:
* + DB_FETCHMODE_ORDERED
* + DB_FETCHMODE_ASSOC
* + DB_FETCHMODE_ORDERED | DB_FETCHMODE_FLIPPED
* + DB_FETCHMODE_ASSOC | DB_FETCHMODE_FLIPPED
*
* @return array the nested array. A DB_Error object on failure.
*/
function &getAll($query, $params = array(),
$fetchmode = DB_FETCHMODE_DEFAULT)
{
// compat check, the params and fetchmode parameters used to
// have the opposite order
if (!is_array($params)) {
if (is_array($fetchmode)) {
if ($params === null) {
$tmp = DB_FETCHMODE_DEFAULT;
} else {
$tmp = $params;
}
$params = $fetchmode;
$fetchmode = $tmp;
} elseif ($params !== null) {
$fetchmode = $params;
$params = array();
}
}
if (sizeof($params) > 0) {
$sth = $this->prepare($query);
if (DB::isError($sth)) {
return $sth;
}
$res =& $this->execute($sth, $params);
$this->freePrepared($sth);
} else {
$res =& $this->query($query);
}
if ($res === DB_OK || DB::isError($res)) {
return $res;
}
$results = array();
while (DB_OK === $res->fetchInto($row, $fetchmode)) {
if ($fetchmode & DB_FETCHMODE_FLIPPED) {
foreach ($row as $key => $val) {
$results[$key][] = $val;
}
} else {
$results[] = $row;
}
}
$res->free();
if (DB::isError($row)) {
$tmp =& $this->raiseError($row);
return $tmp;
}
return $results;
}
// }}}
// {{{ autoCommit()
/**
* Enables or disables automatic commits
*
* @param bool $onoff true turns it on, false turns it off
*
* @return int DB_OK on success. A DB_Error object if the driver
* doesn't support auto-committing transactions.
*/
function autoCommit($onoff = false)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ commit()
/**
* Commits the current transaction
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
function commit()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ rollback()
/**
* Reverts the current transaction
*
* @return int DB_OK on success. A DB_Error object on failure.
*/
function rollback()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ numRows()
/**
* Determines the number of rows in a query result
*
* @param resource $result the query result idenifier produced by PHP
*
* @return int the number of rows. A DB_Error object on failure.
*/
function numRows($result)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ affectedRows()
/**
* Determines the number of rows affected by a data maniuplation query
*
* 0 is returned for queries that don't manipulate data.
*
* @return int the number of rows. A DB_Error object on failure.
*/
function affectedRows()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ getSequenceName()
/**
* Generates the name used inside the database for a sequence
*
* The createSequence() docblock contains notes about storing sequence
* names.
*
* @param string $sqn the sequence's public name
*
* @return string the sequence's name in the backend
*
* @access protected
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::nextID(), DB_common::setOption()
*/
function getSequenceName($sqn)
{
return sprintf($this->getOption('seqname_format'),
preg_replace('/[^a-z0-9_.]/i', '_', $sqn));
}
// }}}
// {{{ nextId()
/**
* Returns the next free id in a sequence
*
* @param string $seq_name name of the sequence
* @param boolean $ondemand when true, the seqence is automatically
* created if it does not exist
*
* @return int the next id number in the sequence.
* A DB_Error object on failure.
*
* @see DB_common::createSequence(), DB_common::dropSequence(),
* DB_common::getSequenceName()
*/
function nextId($seq_name, $ondemand = true)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ createSequence()
/**
* Creates a new sequence
*
* The name of a given sequence is determined by passing the string
* provided in the <var>$seq_name</var> argument through PHP's sprintf()
* function using the value from the <var>seqname_format</var> option as
* the sprintf()'s format argument.
*
* <var>seqname_format</var> is set via setOption().
*
* @param string $seq_name name of the new sequence
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::dropSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
function createSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ dropSequence()
/**
* Deletes a sequence
*
* @param string $seq_name name of the sequence to be deleted
*
* @return int DB_OK on success. A DB_Error object on failure.
*
* @see DB_common::createSequence(), DB_common::getSequenceName(),
* DB_common::nextID()
*/
function dropSequence($seq_name)
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ raiseError()
/**
* Communicates an error and invoke error callbacks, etc
*
* Basically a wrapper for PEAR::raiseError without the message string.
*
* @param mixed integer error code, or a PEAR error object (all
* other parameters are ignored if this parameter is
* an object
* @param int error mode, see PEAR_Error docs
* @param mixed if error mode is PEAR_ERROR_TRIGGER, this is the
* error level (E_USER_NOTICE etc). If error mode is
* PEAR_ERROR_CALLBACK, this is the callback function,
* either as a function name, or as an array of an
* object and method name. For other error modes this
* parameter is ignored.
* @param string extra debug information. Defaults to the last
* query and native error code.
* @param mixed native error code, integer or string depending the
* backend
*
* @return object the PEAR_Error object
*
* @see PEAR_Error
*/
function &raiseError($code = DB_ERROR, $mode = null, $options = null,
$userinfo = null, $nativecode = null)
{
// The error is yet a DB error object
if (is_object($code)) {
// because we the static PEAR::raiseError, our global
// handler should be used if it is set
if ($mode === null && !empty($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
}
$tmp = PEAR::raiseError($code, null, $mode, $options,
null, null, true);
return $tmp;
}
if ($userinfo === null) {
$userinfo = $this->last_query;
}
if ($nativecode) {
$userinfo .= ' [nativecode=' . trim($nativecode) . ']';
} else {
$userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']';
}
$tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo,
'DB_Error', true);
return $tmp;
}
// }}}
// {{{ errorNative()
/**
* Gets the DBMS' native error code produced by the last query
*
* @return mixed the DBMS' error code. A DB_Error object on failure.
*/
function errorNative()
{
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ errorCode()
/**
* Maps native error codes to DB's portable ones
*
* Uses the <var>$errorcode_map</var> property defined in each driver.
*
* @param string|int $nativecode the error code returned by the DBMS
*
* @return int the portable DB error code. Return DB_ERROR if the
* current driver doesn't have a mapping for the
* $nativecode submitted.
*/
function errorCode($nativecode)
{
if (isset($this->errorcode_map[$nativecode])) {
return $this->errorcode_map[$nativecode];
}
// Fall back to DB_ERROR if there was no mapping.
return DB_ERROR;
}
// }}}
// {{{ errorMessage()
/**
* Maps a DB error code to a textual message
*
* @param integer $dbcode the DB error code
*
* @return string the error message corresponding to the error code
* submitted. FALSE if the error code is unknown.
*
* @see DB::errorMessage()
*/
function errorMessage($dbcode)
{
return DB::errorMessage($this->errorcode_map[$dbcode]);
}
// }}}
// {{{ tableInfo()
/**
* Returns information about a table or a result set
*
* The format of the resulting array depends on which <var>$mode</var>
* you select. The sample output below is based on this query:
* <pre>
* SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
* FROM tblFoo
* JOIN tblBar ON tblFoo.fldId = tblBar.fldId
* </pre>
*
* <ul>
* <li>
*
* <kbd>null</kbd> (default)
* <pre>
* [0] => Array (
* [table] => tblFoo
* [name] => fldId
* [type] => int
* [len] => 11
* [flags] => primary_key not_null
* )
* [1] => Array (
* [table] => tblFoo
* [name] => fldPhone
* [type] => string
* [len] => 20
* [flags] =>
* )
* [2] => Array (
* [table] => tblBar
* [name] => fldId
* [type] => int
* [len] => 11
* [flags] => primary_key not_null
* )
* </pre>
*
* </li><li>
*
* <kbd>DB_TABLEINFO_ORDER</kbd>
*
* <p>In addition to the information found in the default output,
* a notation of the number of columns is provided by the
* <samp>num_fields</samp> element while the <samp>order</samp>
* element provides an array with the column names as the keys and
* their location index number (corresponding to the keys in the
* the default output) as the values.</p>
*
* <p>If a result set has identical field names, the last one is
* used.</p>
*
* <pre>
* [num_fields] => 3
* [order] => Array (
* [fldId] => 2
* [fldTrans] => 1
* )
* </pre>
*
* </li><li>
*
* <kbd>DB_TABLEINFO_ORDERTABLE</kbd>
*
* <p>Similar to <kbd>DB_TABLEINFO_ORDER</kbd> but adds more
* dimensions to the array in which the table names are keys and
* the field names are sub-keys. This is helpful for queries that
* join tables which have identical field names.</p>
*
* <pre>
* [num_fields] => 3
* [ordertable] => Array (
* [tblFoo] => Array (
* [fldId] => 0
* [fldPhone] => 1
* )
* [tblBar] => Array (
* [fldId] => 2
* )
* )
* </pre>
*
* </li>
* </ul>
*
* The <samp>flags</samp> element contains a space separated list
* of extra information about the field. This data is inconsistent
* between DBMS's due to the way each DBMS works.
* + <samp>primary_key</samp>
* + <samp>unique_key</samp>
* + <samp>multiple_key</samp>
* + <samp>not_null</samp>
*
* Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
* elements if <var>$result</var> is a table name. The following DBMS's
* provide full information from queries:
* + fbsql
* + mysql
*
* If the 'portability' option has <samp>DB_PORTABILITY_LOWERCASE</samp>
* turned on, the names of tables and fields will be lowercased.
*
* @param object|string $result DB_result object from a query or a
* string containing the name of a table.
* While this also accepts a query result
* resource identifier, this behavior is
* deprecated.
* @param int $mode either unused or one of the tableInfo modes:
* <kbd>DB_TABLEINFO_ORDERTABLE</kbd>,
* <kbd>DB_TABLEINFO_ORDER</kbd> or
* <kbd>DB_TABLEINFO_FULL</kbd> (which does both).
* These are bitwise, so the first two can be
* combined using <kbd>|</kbd>.
*
* @return array an associative array with the information requested.
* A DB_Error object on failure.
*
* @see DB_common::setOption()
*/
function tableInfo($result, $mode = null)
{
/*
* If the DB_<driver> class has a tableInfo() method, that one
* overrides this one. But, if the driver doesn't have one,
* this method runs and tells users about that fact.
*/
return $this->raiseError(DB_ERROR_NOT_CAPABLE);
}
// }}}
// {{{ getTables()
/**
* Lists the tables in the current database
*
* @return array the list of tables. A DB_Error object on failure.
*
* @deprecated Method deprecated some time before Release 1.2
*/
function getTables()
{
return $this->getListOf('tables');
}
// }}}
// {{{ getListOf()
/**
* Lists internal database information
*
* @param string $type type of information being sought.
* Common items being sought are:
* tables, databases, users, views, functions
* Each DBMS's has its own capabilities.
*
* @return array an array listing the items sought.
* A DB DB_Error object on failure.
*/
function getListOf($type)
{
$sql = $this->getSpecialQuery($type);
if ($sql === null) {
$this->last_query = '';
return $this->raiseError(DB_ERROR_UNSUPPORTED);
} elseif (is_int($sql) || DB::isError($sql)) {
// Previous error
return $this->raiseError($sql);
} elseif (is_array($sql)) {
// Already the result
return $sql;
}
// Launch this query
return $this->getCol($sql);
}
// }}}
// {{{ getSpecialQuery()
/**
* Obtains the query string needed for listing a given type of objects
*
* @param string $type the kind of objects you want to retrieve
*
* @return string the SQL query string or null if the driver doesn't
* support the object type requested
*
* @access protected
* @see DB_common::getListOf()
*/
function getSpecialQuery($type)
{
return $this->raiseError(DB_ERROR_UNSUPPORTED);
}
// }}}
// {{{ _rtrimArrayValues()
/**
* Right-trims all strings in an array
*
* @param array $array the array to be trimmed (passed by reference)
*
* @return void
*
* @access protected
*/
function _rtrimArrayValues(&$array)
{
foreach ($array as $key => $value) {
if (is_string($value)) {
$array[$key] = rtrim($value);
}
}
}
// }}}
// {{{ _convertNullArrayValuesToEmpty()
/**
* Converts all null values in an array to empty strings
*
* @param array $array the array to be de-nullified (passed by reference)
*
* @return void
*
* @access protected
*/
function _convertNullArrayValuesToEmpty(&$array)
{
foreach ($array as $key => $value) {
if (is_null($value)) {
$array[$key] = '';
}
}
}
// }}}
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
*/
?>
| mikexstudios/xcomic | includes/DB/common.php | PHP | gpl-2.0 | 69,476 |
package conf;
/**
* Enthält die Konfigurationseinstellungen
* @author CreaByte
*
*/
public final class Conf {
/**
* Frames pro Sekunde
*/
public static final int fps = 22;
/**
* Standard-Zeitschritt für die Simulation
*/
public static final long defaultTimeStep = 1000/fps; // 22fps
/**
* Effektive Umrechnung Längeneinheiten in Pixel
* LINKS OBEN ist der Nullpunkt "der Welt"
*/
public static double pixelPerMeter=4;
public static final double MAX_ZOOM=10,MIN_ZOOM=0.01;
public static int convertToPixel(double meters) {
return (int)(meters * pixelPerMeter);
}
/**
* Typische Größen
*/
public static final double carWidth = 1.5; // Meter
public static final double carLength = 3; // Meter
public static final double laneWidth = 3; // Meter
/**
* Typische Größen für die Autobewegung
*/
public static final double L = 10; // [m] Typische Längeneinheit
public static final double V = 10; // [km/h] Typische Geschwindigkeit
public static final double T = L/V; // [h] Typische Zeiteinheit
public static final double d = 1; // [m] Standard-Sicherheitsabstand
public static final double c = 1; // [] Wie schnell wird beim auffahren gebremst?
public static final double v0 = 10; // [km/h] Standard - Wunschgeschwindigkeit
public static final double tau = 1; // [Sek] Standard - Relaxionszeit in (wie schnell p
public static final double a = 3.85; // [m/s²] Typische Längeneinheit in Metern
public static final double minCarDistance = 2; // Meter
public static final double eyeSight = 10; // Meter
/**
* Grenze der Stationen zum Rand des Stadtgebiets in Meter
*/
public static final double border = 4; // Meter
public static int random(int max) {
return (int)Math.round(Math.random() * max);
}
}
| rondiplomatico/traffic | src/conf/Conf.java | Java | gpl-2.0 | 1,922 |
/*
* (c) Copyright 2009-2013 by Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. 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.
*/
package org.databene.benerator.wrapper;
import org.databene.benerator.Generator;
/**
* Converts the {@link Number} products of another {@link Generator} to {@link Integer}.<br/>
* <br/>
* Created at 23.06.2009 22:58:26
* @since 0.6.0
* @author Volker Bergmann
*/
public class AsIntegerGeneratorWrapper<E extends Number> extends GeneratorWrapper<E, Integer> {
public AsIntegerGeneratorWrapper(Generator<E> source) {
super(source);
}
@Override
public Class<Integer> getGeneratedType() {
return Integer.class;
}
@Override
public ProductWrapper<Integer> generate(ProductWrapper<Integer> wrapper) {
assertInitialized();
ProductWrapper<E> tmp = generateFromSource();
if (tmp == null)
return null;
E unwrappedValue = tmp.unwrap();
return wrapper.wrap(unwrappedValue != null ? unwrappedValue.intValue() : null);
}
}
| raphaelfeng/benerator | src/org/databene/benerator/wrapper/AsIntegerGeneratorWrapper.java | Java | gpl-2.0 | 2,256 |
from bs4 import BeautifulSoup
import urllib.request
html = urllib.request.urlopen('http://www.nlotto.co.kr/common.do?method=main’')
soup = BeautifulSoup(html)
hoi = soup.find("span", id="lottoDrwNo")
numbers=[]
for n in range(1,7):
strV ="drwtNo" + str(n)
first = soup.find('img', id=strV)['alt']
numbers.append(first)
bonus = soup.find('img', id="bnusNo")['alt']
print('Lotto numbers')
print(hoi.string + "results")
print(" ".join(numbers))
print('Bonus_number: '+bonus)
| YongJang/PythonTelegram | examples/referenced/a.py | Python | gpl-2.0 | 497 |
<?php
$lang['plugin']['categories'] = array(
'subject' => 'Kategorie'
);
?> | evacchi/flatpress | fp-plugins/categories/lang/lang.cs-cz.php | PHP | gpl-2.0 | 89 |
<?php
/**
* @copyright Copyright(c) 2010 jooyea.net
* @file curd_action.php
* @brief 实现系统的自动增删改查
* @author webning
* @date 2010-12-23
* @version 0.6
*/
/**
* @brief 完成用户的自动增加删除修改功能DURD类
* @class ICURDAction
*/
class ICURDAction extends IAction
{
/**
* @brief 处理curd动作
* @return String
*/
public function curd()
{
$action = $this->id;
$controller = $this->controller;
$curdinfo = $this->initinfo();
if(is_array($curdinfo))
{
$modelName = $curdinfo['model'];
$key = $curdinfo['key'];
$actions = $curdinfo['actions'];
switch($action)
{
case 'add':
case 'upd':
{
if(method_exists($controller,'getValidate')) $validate = $controller->getValidate();
else $validate =null;
if($validate!=null)
{
$formValidate = new IFormValidation($validate);
$data = $formValidate->run();
}
$model = new IModel($modelName);
if(isset($data) && $data!==null)
{
$model->setData($data[$modelName]);
if($action = 'add') $flag = $model->add();
else $flag = $model->upd("$key = '".IReq::get($key)."'");
}
if(isset($flag) && $flag)
{
$_GET['action'] = $actions['success'];
}
else
{
$_GET['action'] = $actions['fail'];
}
$controller->run();
return true;
}
case 'del':
{
$model = new IModel($modelName);
$flag = $model->del("$key = '".IReq::get($key)."'");
if($flag)
{
$_GET['action']=$actions['success'];
}
else
{
$_GET['action'] = $actions['fail'];
}
$controller->run();
return true;
}
case 'get':
{
$model = new IModel($modelName);
$rs = $model->getObj("$key = '".IReq::get($key)."'");
echo JSON::encode($rs);
return false;
}
}
}
}
/**
* @brief 分析curd的配置信息
* @return mixed
*/
private function initinfo()
{
$action = $this->id;
$controller = $this->controller;
if(method_exists($controller,'curd'))
{
$curdinfo = $controller->curd();
$modelName = isset($curdinfo['model'])?$curdinfo['model']:null;
if($modelName !==null)
{
$key = isset($curdinfo['key'])?$curdinfo['key']:'id';
$actions = isset($curdinfo['actions'])?$curdinfo['actions']:null;
if(is_array($actions))
{
if(isset($actions[$action]))
{
$current = $actions[$action];
}
else
{
$current = isset($actions['*'])?$actions['*']:null;
}
if($current!==null)
{
$fail = isset($current['fail'])?$current['fail']:(isset($current[1])?$current[1]:'index');
$success = isset($current['success'])?$current['success']:(isset($current[0])?$current[0]:'index');
return array('model'=>$modelName,'key'=>$key, 'actions' =>array('success'=>$success,'fail'=>$fail) );
}
else
{
throw new IException('class '.get_class($controller).' have curd error');
}
}
}
}
return null;
}
/**
* @brief Action的运行方法
*/
public function run()
{
$this->curd();
}
}
?>
| zatol/iws | lib/web/action/curd_action.php | PHP | gpl-2.0 | 4,566 |
<?php
namespace CirrusSearch\Search;
use CirrusSearch\Search\Fetch\FetchPhaseConfigBuilder;
use Elastica\ResultSet as ElasticaResultSet;
/**
* Result type for a full text search.
*/
final class FullTextResultsType extends BaseResultsType {
/**
* @var bool
*/
private $searchContainedSyntax;
/**
* @var FetchPhaseConfigBuilder
*/
private $fetchPhaseBuilder;
/**
* @var TitleHelper
*/
private $titleHelper;
/**
* @var string[] list of extra fields to extract
*/
private $extraFieldsToExtract;
/**
* @param FetchPhaseConfigBuilder $fetchPhaseBuilder
* @param bool $searchContainedSyntax
* @param TitleHelper $titleHelper
* @param string[] $extraFieldsToExtract
*/
public function __construct(
FetchPhaseConfigBuilder $fetchPhaseBuilder,
$searchContainedSyntax,
TitleHelper $titleHelper,
array $extraFieldsToExtract = []
) {
$this->fetchPhaseBuilder = $fetchPhaseBuilder;
$this->searchContainedSyntax = $searchContainedSyntax;
$this->titleHelper = $titleHelper;
$this->extraFieldsToExtract = $extraFieldsToExtract;
}
/**
* @return false|string|array corresponding to Elasticsearch source filtering syntax
*/
public function getSourceFiltering() {
return array_merge(
parent::getSourceFiltering(),
[ 'redirect.*', 'timestamp', 'text_bytes' ],
$this->extraFieldsToExtract
);
}
/**
* @return array
*/
public function getStoredFields() {
return [ "text.word_count" ]; // word_count is only a stored field and isn't part of the source.
}
/**
* Setup highlighting.
* Don't fragment title because it is small.
* Get just one fragment from the text because that is all we will display.
* Get one fragment from redirect title and heading each or else they
* won't be sorted by score.
*
* @param array $extraHighlightFields (deprecated and ignored)
* @return array|null of highlighting configuration
*/
public function getHighlightingConfiguration( array $extraHighlightFields = [] ) {
$this->fetchPhaseBuilder->configureDefaultFullTextFields();
return $this->fetchPhaseBuilder->buildHLConfig();
}
/**
* @param ElasticaResultSet $result
* @return CirrusSearchResultSet
*/
public function transformElasticsearchResult( ElasticaResultSet $result ) {
// Should we make this a concrete class?
return new class( $this->titleHelper, $this->fetchPhaseBuilder, $result, $this->searchContainedSyntax, $this->extraFieldsToExtract )
extends BaseCirrusSearchResultSet {
/** @var TitleHelper */
private $titleHelper;
/** @var FullTextCirrusSearchResultBuilder */
private $resultBuilder;
/** @var ElasticaResultSet */
private $results;
/** @var bool */
private $searchContainedSyntax;
public function __construct(
TitleHelper $titleHelper,
FetchPhaseConfigBuilder $builder,
ElasticaResultSet $results,
$searchContainedSyntax,
array $extraFieldsToExtract
) {
$this->titleHelper = $titleHelper;
$this->resultBuilder = new FullTextCirrusSearchResultBuilder( $this->titleHelper,
$builder->getHLFieldsPerTargetAndPriority(), $extraFieldsToExtract );
$this->results = $results;
$this->searchContainedSyntax = $searchContainedSyntax;
}
/**
* @inheritDoc
*/
protected function transformOneResult( \Elastica\Result $result ) {
return $this->resultBuilder->build( $result );
}
/**
* @return \Elastica\ResultSet|null
*/
public function getElasticaResultSet() {
return $this->results;
}
/**
* @inheritDoc
*/
public function searchContainedSyntax() {
return $this->searchContainedSyntax;
}
protected function getTitleHelper(): TitleHelper {
return $this->titleHelper;
}
};
}
/**
* @param FetchPhaseConfigBuilder $builder
* @return FullTextResultsType
*/
public function withFetchPhaseBuilder( FetchPhaseConfigBuilder $builder ): FullTextResultsType {
return new self( $builder, $this->searchContainedSyntax, $this->titleHelper );
}
/**
* @return CirrusSearchResultSet
*/
public function createEmptyResult() {
return BaseCirrusSearchResultSet::emptyResultSet();
}
}
| wikimedia/mediawiki-extensions-CirrusSearch | includes/Search/FullTextResultsType.php | PHP | gpl-2.0 | 4,137 |
namespace L2dotNET.GameService.network.l2send
{
class AutoAttackStop : GameServerNetworkPacket
{
private int sId;
public AutoAttackStop(int sId)
{
this.sId = sId;
}
protected internal override void write()
{
writeC(0x2c);
writeD(sId);
}
}
}
| domis045/L2dotNET | src/L2dotNET.Game/network/serverpackets/AutoAttackStop.cs | C# | gpl-2.0 | 350 |
/**
* 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("/BenchmarkTest20813")
public class BenchmarkTest20813 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 {
org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request );
String param = scr.getTheValue("foo");
String bar = doSomething(param);
String a1 = "";
String a2 = "";
String osName = System.getProperty("os.name");
if (osName.indexOf("Windows") != -1) {
a1 = "cmd.exe";
a2 = "/c";
} else {
a1 = "sh";
a2 = "-c";
}
String[] args = {a1, a2, "echo", bar};
String[] argsEnv = { "foo=bar" };
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(args, argsEnv);
org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
} catch (IOException e) {
System.out.println("Problem executing cmdi - TestCase");
throw new ServletException(e);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
String bar = valuesList.get(0); // get the param value
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest20813.java | Java | gpl-2.0 | 2,749 |
/**
* Created by herve on 10/11/15.
*/
function ajax_exercises_by_muscles(muscle) {
$("#loader").show();
$("#loader-message").show();
$.ajax({
url : "/exercises/muscles/ajax-exercises-by-muscles/", // the endpoint
type : "POST", // http method
data : { muscle : muscle }, // data sent with the post request
// handle a successful response
success : function(json) {
json = JSON.stringify(json);
json = JSON.parse(json);
$("#loader").hide();
$("#loader-message").hide();
$("#exercises-count").text(json.count);
$("#exercises-count").attr('href', json.link);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
| 4383/street-workout-database | sport/web/static/js/ajax.js | JavaScript | gpl-2.0 | 926 |
require 'rails_helper'
RSpec.describe Category, type: :model do
let(:category) { create(:category) }
it 'is valid factory for :category' do
expect(category).to be_valid
end
it 'is check empty category name' do
category = build(:category, name: nil)
category.valid?
expect(category.errors[:name]).to include("can't be blank")
end
it 'is check category name limit with 255 chars' do
category = build(:category, name: 's' * 256)
category.valid?
expect(category.errors[:name]).to include('is too long (maximum is 255 characters)')
end
it 'is check empty category uri' do
category = build(:category, uri: nil)
category.valid?
expect(category.errors[:uri]).to include("can't be blank")
end
it 'is check category uri limit with 64 chars' do
category = build(:category, uri: 's' * 65)
category.valid?
expect(category.errors[:uri]).to include('is too long (maximum is 64 characters)')
end
it 'is check uniq values of category uri' do
create(:category, uri: 'cars')
category = build(:category, uri: 'cars')
category.valid?
expect(category.errors[:uri]).to include('has already been taken')
end
it 'is check subcategory should be destroyed when category deleted' do
parent_category = create(:category)
create(:subcategory, category: parent_category)
expect { parent_category.destroy }.to change(Subcategory, :count).by(-1)
end
end
| ufacode/wenternet | spec/models/category_spec.rb | Ruby | gpl-2.0 | 1,438 |
<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<div>
<input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
<label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
<input id="autocomplete" title="type "a"" type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" placeholder=" Help you find anything?" />
</div>
</form> | Kitzo/door-fellowship | wp-content/themes/chris-base-theme/searchform.php | PHP | gpl-2.0 | 506 |
require 'vx/container_connector'
require 'vx/instrumentation'
require 'active_support/notifications'
$stdout.puts ' --> initializing Vx::ContainerConnector'
Vx::ContainerConnector.instrumenter = ActiveSupport::Notifications
| pacoguzman/vx-worker | lib/vx/worker/initializers/containers.rb | Ruby | gpl-2.0 | 226 |
import React from "react";
import { connect } from "react-redux";
import { TimeMode, AppState, Dispatch } from "../../types";
import { getTimeObj } from "../../utils";
import * as Actions from "../../actionCreators";
import * as Selectors from "../../selectors";
import { TIME_MODE } from "../../constants";
interface StateProps {
timeElapsed: number;
duration: number;
timeMode: TimeMode;
}
interface DispatchProps {
toggleTimeMode(): void;
}
const Time = ({
timeElapsed,
duration,
timeMode,
toggleTimeMode,
}: StateProps & DispatchProps) => {
const seconds =
timeMode === TIME_MODE.ELAPSED ? timeElapsed : duration - timeElapsed;
const timeObj = getTimeObj(seconds);
return (
<div id="time" onClick={toggleTimeMode} className="countdown">
{timeMode === TIME_MODE.REMAINING && <div id="minus-sign" />}
<div
id="minute-first-digit"
className={`digit digit-${timeObj.minutesFirstDigit}`}
/>
<div
id="minute-second-digit"
className={`digit digit-${timeObj.minutesSecondDigit}`}
/>
<div
id="second-first-digit"
className={`digit digit-${timeObj.secondsFirstDigit}`}
/>
<div
id="second-second-digit"
className={`digit digit-${timeObj.secondsSecondDigit}`}
/>
</div>
);
};
const mapStateToProps = (state: AppState): StateProps => {
const timeElapsed = Selectors.getTimeElapsed(state);
const duration = Selectors.getDuration(state);
const { timeMode } = state.media;
return { timeElapsed, duration: duration || 0, timeMode };
};
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ({
toggleTimeMode: () => dispatch(Actions.toggleTimeMode()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Time);
| mazhar266/mazhar266.github.io | webamp/js/components/MainWindow/Time.tsx | TypeScript | gpl-2.0 | 1,798 |
<?php
/* This file is part of a copyrighted work; it is distributed with NO WARRANTY.
* See the file COPYRIGHT.html for more details.
*/
require_once("../shared/common.php");
$tab = "admin";
$nav = "materials";
$restrictInDemo = true;
require_once("../shared/logincheck.php");
require_once("../classes/DmQuery.php");
/*
require_once("../classes/CheckoutPrivsQuery.php"); //add jalg de la version openbiblio 7.1
require_once("../classes/MaterialFieldQuery.php"); //add jalg de la version openbiblio 7.1
*/
require_once("../functions/errorFuncs.php");
require_once("../classes/Localize.php");
$loc = new Localize(OBIB_LOCALE,$tab);
#****************************************************************************
#* Checking for query string. Go back to material type list if none found.
#****************************************************************************
if (!isset($_GET["code"])){
header("Location: ../admin/materials_list.php");
exit();
}
$code = $_GET["code"];
$description = $_GET["desc"];
#**************************************************************************
#* Delete row
#**************************************************************************
$dmQ = new DmQuery();
$dmQ->connect();
$dmQ->delete("material_type_dm",$code);
$dmQ->close();
/*
//add jalg de la version openbiblio 7.1
$checkoutPrivsQ = new CheckoutPrivsQuery();
$checkoutPrivsQ->connect();
$checkoutPrivsQ->delete_by_material_cd($code);
$checkoutPrivsQ->close();
$materialFieldQ = new MaterialFieldQuery();
$materialFieldQ->connect();
$materialFieldQ->deleteCustomField($code);
$materialFieldQ->close();
//add jalg de la version openbiblio 7.1
*/
#**************************************************************************
#* Show success page
#**************************************************************************
require_once("../shared/header.php");
?>
<?php echo $loc->getText("admin_materials_delMaterialType"); ?>
<?php echo H($description);?><?php echo $loc->getText("admin_materials_delMaterialdeleted"); ?>
<br><br>
<a href="../admin/materials_list.php"><?php echo $loc->getText("admin_materials_Return"); ?></a>
<?php require_once("../shared/footer.php");
| uniedpa/biblioteca | admin/materials_del.php | PHP | gpl-2.0 | 2,251 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Random mutator based on C. Miller 'algorithm' for Nightmare Fuzzing Project.
Created on Sun May 12 10:57:06 2013
@author: joxean
"""
import sys
import math
import random
#-----------------------------------------------------------------------
class CCMillerMutator(object):
def __init__(self, buf, skip=5):
self.buf = buf
self.skip = 5
def mutate(self):
buf = self.buf
fuzz_factor = len(buf)/500.
if fuzz_factor < 1:
fuzz_factor = 1
numwrites = random.randrange(math.ceil((float(len(buf)) / fuzz_factor)))+1
#print "Total of %d" % numwrites
diff = []
for j in range(numwrites):
rbyte = random.randrange(256)
rn = random.randrange(len(buf))
rtotal = random.randint(0, 16)
c = "%c" % rbyte
buf = buf[:rn-1] + c*rtotal + buf[rn+rtotal:]
diff.append("%d, %d" % (rn, rtotal))
return buf, diff
#-----------------------------------------------------------------------
def main(template, output):
mut = CCMillerMutator(open(template, "rb").read())
buf, diff = mut.mutate()
f = open(output, "wb")
f.write(buf)
f.close()
diff.sort()
f = open(output + ".diff", "wb")
f.write("# Original file created by 'CMiller Mutator Rep' was %s\n" % template)
f.write("\n".join(diff))
f.close()
#-----------------------------------------------------------------------
def usage():
print "Usage:", sys.argv[0], "<template> <output filename>"
if __name__ == "__main__":
if len(sys.argv) != 3:
usage()
else:
main(sys.argv[1], sys.argv[2])
| joxeankoret/nightmare | mutators/cmiller_mutator_rep.py | Python | gpl-2.0 | 1,588 |
/* class for generating random sample data*/
public class ValueGenerator {
private static String[] values = {
"elephant","giraffe","monkey","cheetah","dog","cat","tiger",
"mouse","tortoise","shark","whale","salmon","deer","wolf",
"grizzlybear","fox","snake","worm","fly","bee","hornet"
};
public static String[] getNewStringArray(){
int size = (int)(Math.random()*20 +1);
String[] arr = new String[size];
for(int i=0; i<size;++i){
arr[i] = getNewString();
}
return arr;
}
public static String getNewString(){
int index = (int)(Math.random()*values.length);
return values[index];
}
public static int getNewInt(){
return (int)(Math.random()*100);
}
public static Integer[] getNewIntArray(){
int size = (int)(Math.random()*20 +1);
Integer[] arr = new Integer[size];
for(int i=0; i<size;++i){
arr[i] = getNewInt();
}
return arr;
}
public static double getNewDouble(){
//round double to ##.###
return Math.floor(Math.random()*100000 ) / 1000;
}
public static Double[] getNewDoubleArray(){
int size = (int)(Math.random()*20 +1);
Double[] arr = new Double[size];
for(int i=0; i<size;++i){
arr[i] = getNewDouble();
}
return arr;
}
}
| DB-SE/isp2014.marcus.kamieth | Algorithms_DataStructures_RTVar/src/ValueGenerator.java | Java | gpl-2.0 | 1,197 |
//=============================================================================
// YHTTPD
// Helper
//=============================================================================
// c
#include <cstdio> // printf prototype.
#include <cstdlib> // calloc and free prototypes.
#include <cstring> // str* and memset prototypes.
#include <cstdarg>
#include <sstream>
#include <iomanip>
#include <unistd.h>
// yhttpd
#include <yconfig.h>
#include <tuxboxapi/controlapi.h>
#include "ytypes_globals.h"
#include "helper.h"
#include "ylogging.h"
//=============================================================================
// Integers
//=============================================================================
//-------------------------------------------------------------------------
// Check and set integer inside boundaries (min, max)
//-------------------------------------------------------------------------
int minmax(int value, int min, int max) {
if (value < min)
return min;
if (value > max)
return max;
return value;
}
//=============================================================================
// Date & Time
//=============================================================================
//-------------------------------------------------------------------------
// Check and set Date/Time (tm*) inside boundaries
//-------------------------------------------------------------------------
void correctTime(struct tm *zt) {
zt->tm_year = minmax(zt->tm_year, 0, 129);
zt->tm_mon = minmax(zt->tm_mon, 0, 11);
zt->tm_mday = minmax(zt->tm_mday, 1, 31); //-> eine etwas laxe pruefung, aber mktime biegt das wieder grade
zt->tm_hour = minmax(zt->tm_hour, 0, 23);
zt->tm_min = minmax(zt->tm_min, 0, 59);
zt->tm_sec = minmax(zt->tm_sec, 0, 59);
zt->tm_isdst = -1;
}
//=============================================================================
// Strings
//=============================================================================
//-------------------------------------------------------------------------
// Integer to Hexadecimal-String
//-------------------------------------------------------------------------
std::string itoh(unsigned int conv) {
return string_printf("0x%06x", conv);
}
//-------------------------------------------------------------------------
// Integer to String
//-------------------------------------------------------------------------
std::string itoa(unsigned int conv) {
return string_printf("%u", conv);
}
//-------------------------------------------------------------------------
// convert timer_t to "<hour>:<minutes>" String
//-------------------------------------------------------------------------
std::string timeString(time_t time) {
char tmp[7] = { '\0' };
struct tm *tm = localtime(&time);
if (strftime(tmp, 6, "%H:%M", tm))
return std::string(tmp);
else
return std::string("??:??");
}
//-------------------------------------------------------------------------
// Printf and return formatet String. Buffer-save!
// max length up to bufferlen -> then snip
//-------------------------------------------------------------------------
std::string string_printf(const char *fmt, ...) {
va_list arglist;
const int bufferlen = 4*1024;
char buffer[bufferlen] = {0};
va_start(arglist, fmt);
vsnprintf(buffer, bufferlen, fmt, arglist);
va_end(arglist);
return std::string(buffer);
}
//-------------------------------------------------------------------------
// ySplitString: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitString(std::string str, std::string delimiter, std::string& left,
std::string& right) {
std::string::size_type pos;
if ((pos = str.find_first_of(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + 1, str.length() - (pos + 1));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitString: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitStringExact(std::string str, std::string delimiter,
std::string& left, std::string& right) {
std::string::size_type pos;
if ((pos = str.find(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + delimiter.length(), str.length() - (pos
+ delimiter.length()));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitStringRight: spit string "str" in two strings "left" and "right" at
// one of the chars in "delimiter" returns true if delimiter found
//-------------------------------------------------------------------------
bool ySplitStringLast(std::string str, std::string delimiter,
std::string& left, std::string& right) {
std::string::size_type pos;
if ((pos = str.find_last_of(delimiter)) != std::string::npos) {
left = str.substr(0, pos);
right = str.substr(pos + 1, str.length() - (pos + 1));
} else {
left = str; //default if not found
right = "";
}
return (pos != std::string::npos);
}
//-------------------------------------------------------------------------
// ySplitStringVector: spit string "str" and build vector of strings
//-------------------------------------------------------------------------
CStringArray ySplitStringVector(std::string str, std::string delimiter) {
std::string left, right, rest;
bool found;
CStringArray split;
rest = str;
do {
found = ySplitString(rest, delimiter, left, right);
split.push_back(left);
rest = right;
} while (found);
return split;
}
//-------------------------------------------------------------------------
// trim whitespaces
//-------------------------------------------------------------------------
std::string trim(std::string const& source, char const* delims) {
std::string result(source);
std::string::size_type index = result.find_last_not_of(delims);
if (index != std::string::npos)
result.erase(++index);
index = result.find_first_not_of(delims);
if (index != std::string::npos)
result.erase(0, index);
else
result.erase();
return result;
}
//-------------------------------------------------------------------------
// replace all occurrences find_what
//-------------------------------------------------------------------------
void replace(std::string &str, const std::string &find_what,
const std::string &replace_with) {
std::string::size_type pos = 0;
while ((pos = str.find(find_what, pos)) != std::string::npos) {
str.erase(pos, find_what.length());
str.insert(pos, replace_with);
pos += replace_with.length();
}
}
//-------------------------------------------------------------------------
// equal-function for case insensitive compare
//-------------------------------------------------------------------------
bool nocase_compare(char c1, char c2) {
return toupper(c1) == toupper(c2);
}
//-----------------------------------------------------------------------------
// Decode URLEncoded std::string
//-----------------------------------------------------------------------------
std::string decodeString(std::string encodedString) {
const char *string = encodedString.c_str();
unsigned int count = 0;
char hex[3] = { '\0' };
unsigned long iStr;
std::string result = "";
count = 0;
while (count < encodedString.length()) /* use the null character as a loop terminator */
{
if (string[count] == '%' && count + 2 < encodedString.length()) {
hex[0] = string[count + 1];
hex[1] = string[count + 2];
hex[2] = '\0';
iStr = strtoul(hex, NULL, 16); /* convert to Hex char */
result += (char) iStr;
count += 3;
} else if (string[count] == '+') {
result += ' ';
count++;
} else {
result += string[count];
count++;
}
} /* end of while loop */
return result;
}
//-----------------------------------------------------------------------------
// HTMLEncode std::string
//-----------------------------------------------------------------------------
std::string encodeString(const std::string &decodedString)
{
std::string result="";
char buf[10]= {0};
for (unsigned int i=0; i<decodedString.length(); i++)
{
const char one_char = decodedString[i];
if (isalnum(one_char)) {
result += one_char;
} else {
snprintf(buf,sizeof(buf), "&#%d;",(unsigned char) one_char);
result +=buf;
}
}
result+='\0';
result.reserve();
return result;
}
//-----------------------------------------------------------------------------
// returns string in lower case
//-----------------------------------------------------------------------------
std::string string_tolower(std::string str) {
for (unsigned int i = 0; i < str.length(); i++)
str[i] = tolower(str[i]);
return str;
}
//-----------------------------------------------------------------------------
// write string to a file
//-----------------------------------------------------------------------------
bool write_to_file(std::string filename, std::string content, bool append) {
FILE *fd = NULL;
if ((fd = fopen(filename.c_str(), append ? "a" : "w")) != NULL) // open file
{
fwrite(content.c_str(), content.length(), 1, fd);
fflush(fd); // flush and close file
fclose(fd);
return true;
} else
return false;
}
//-----------------------------------------------------------------------------
// JSON: create pair string "<_key>". "<_value>"
// Handle wrong quotes
//-----------------------------------------------------------------------------
std::string json_out_quote_convert(std::string _str) {
replace(_str, "\"", "\'");
return _str;
}
//-----------------------------------------------------------------------------
// JSON: create pair string "<_key>". "<_value>"
// Handle wrong quotes
//-----------------------------------------------------------------------------
std::string json_out_pair(std::string _key, std::string _value) {
replace(_key, "\"", "");
replace(_value, "\"", "\'");
return "\"" + _key + "\": " + "\"" + _value + "\"";
}
//-----------------------------------------------------------------------------
// JSON: create success return string
//-----------------------------------------------------------------------------
std::string json_out_success(std::string _result) {
return "{\"success\": \"true\", \"data\":{" + _result + "}}";
}
//-----------------------------------------------------------------------------
// JSON: create success return string
//-----------------------------------------------------------------------------
std::string json_out_error(std::string _error) {
return "{\"success\": \"false\", \"error\":{\"text\": \"" + _error + "\"}}";
}
//-----------------------------------------------------------------------------
// JSON: convert string to JSON-String
//-----------------------------------------------------------------------------
std::string json_convert_string(std::string value)
{
std::string result;
for (size_t i = 0; i < value.length(); i++)
{
unsigned char c = unsigned(value[i]);
switch(c)
{
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
if ( isControlCharacter( c ) )
{
std::ostringstream oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast<int>(c);
result += oss.str();
}
else
{
result += c;
}
break;
}
}
return result;
}
#if 0
std::string json_convert_string(std::string s) {
std::stringstream ss;
for (size_t i = 0; i < s.length(); ) {
unsigned char ch = unsigned(s[i]);
if(ch == 0x0d){
ss << "\\u000d";
i++;
continue;
}
if(ch == 0x0a){
ss << "\\u000a";
i++;
continue;
}
if(ch < '\x20' || ch == '\\' || ch == '"' || ch >= '\x80') {
unsigned long unicode = 0;
size_t todo = 0;
if (ch <= 0xBF) {
}
else if (ch <= 0xDF) {
unicode = ch & 0x1F;
todo = 1;
}
else if (ch <= 0xEF) {
unicode = ch & 0x0F;
todo = 2;
}
else if (ch <= 0xF7) {
unicode = ch & 0x07;
todo = 3;
}
for (size_t j = 0; j < todo; ++j){
++i;
unicode <<= 6;
unicode += unsigned(s[i]) & 0x3F;
}
if (unicode <= 0xFFFF)
{
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << unicode;
}else
{
unicode -= 0x10000;
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << ((unicode >> 10) + 0xD800);
ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << ((unicode & 0x3FF) + 0xDC00);
}
}
else {
ss << s[i];
}
++i;
}
return ss.str();
}
#endif // 0
std::string yExecuteScript(std::string cmd) {
#if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE
const char *fbshot = "Y_Tools fbshot fb /";
int len = strlen(fbshot);
if (!strncmp(cmd.c_str(), fbshot, len))
return CFrameBuffer::getInstance()->OSDShot(cmd.substr(len - 1)) ? "" : "error";
#endif
std::string script, para, result;
bool found = false;
//aprintf("%s: %s\n", __func__, cmd.c_str());
// split script and parameters
int pos;
if ((pos = cmd.find_first_of(" ")) > 0) {
script = cmd.substr(0, pos);
para = cmd.substr(pos + 1, cmd.length() - (pos + 1)); // snip
} else
script = cmd;
// get file
std::string fullfilename;
script += ".sh"; //add script extention
char cwd[255];
getcwd(cwd, 254);
for (unsigned int i = 0; i < CControlAPI::PLUGIN_DIR_COUNT && !found; i++) {
fullfilename = CControlAPI::PLUGIN_DIRS[i] + "/" + script;
FILE *test = fopen(fullfilename.c_str(), "r"); // use fopen: popen does not work
if (test != NULL) {
fclose(test);
chdir(CControlAPI::PLUGIN_DIRS[i].c_str());
FILE *f = popen((fullfilename + " " + para).c_str(), "r"); //execute
if (f != NULL) {
found = true;
char output[1024];
while (fgets(output, 1024, f)) // get script output
result += output;
pclose(f);
}
}
}
chdir(cwd);
if (!found) {
printf("%s: script %s not found in:\n", __func__, script.c_str());
for (unsigned int i = 0; i < CControlAPI::PLUGIN_DIR_COUNT; i++) {
printf("\t%s\n", CControlAPI::PLUGIN_DIRS[i].c_str());
}
result = "error";
}
return result;
}
| j00zek/j00zeks-neutrino-mp-cst-next | src/nhttpd/yhttpd_core/helper.cpp | C++ | gpl-2.0 | 14,657 |
<?php
/**
* @version SEBLOD 3.x Core ~ $Id: _debug.php sebastienheraud $
* @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder)
* @url http://www.seblod.com
* @editor Octopoos - www.octopoos.com
* @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved.
* @license GNU General Public License version 2 or later; see _LICENSE.php
**/
defined( '_JEXEC' ) or die;
// Init
jimport( 'joomla.error.profiler' );
$db = JFactory::getDbo();
$config = JCckDev::init();
$cck = JCckDev::preload( array( '' ) );
$doc = JFactory::getDocument();
$profiler = new JProfiler();
// -- DEBUG:START -- //
$js = '';
$js2 = '';
$js_script = '';
$js_script = JURI::root( true ).$js_script;
echo '<br /><div style="color: #999999; font-size: 10px; font-weight: bold;">-------- Debug --------<br />';
// -------- -------- -------- -------- -------- -------- -------- -------- //
$n = 10000;
$profiler = new JProfiler();
for ( $i = 0; $i < $n; $i++ ) {
//
}
$profiler_res = $profiler->mark( 'afterDebug' );
// -------- -------- -------- -------- -------- -------- -------- -------- //
if ( $js_script ) {
$doc->addScript( $js_script );
}
if ( $js || $js2 ) {
echo '<input text id="toto" name="toto" value="" />'.'<input text id="toto2" name="toto2" value="" />';
$doc->addScriptDeclaration( 'jQuery(document).ready(function($) {' . $js . '});' . $js2 );
}
echo '<br />'. $profiler_res . '<br />-------- Debug --------<br /></div>';
// -- DEBUG:END -- //
/*
$log = JLog::addLogger( array( 'format'=>'{DATE}\t{TIME}\t{LEVEL}\t{CODE}\t{MESSAGE}', 'text_file'=>'com_cck.php' ) );
*/ | klas/SEBLOD | administrator/components/com_cck/helpers/scripts/_debug.php | PHP | gpl-2.0 | 1,658 |
<?php
/**
* @package Blue Hat CDN
* @version 2.9.4
* @copyright (C) Copyright 2006-2014 Blue Hat Network, BlueHatNetwork.com. All rights reserved.
* @license GNU/GPL http://www.gnu.org/licenses/gpl-3.0.txt
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/>.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
class BlueHatNetworkCommon
{
private static $_getWebsiteOwnerEmailAddress;
public static function isValidEmailAddress($emailAddress)
{
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
return is_email($emailAddress);
}
elseif(BlueHatNetworkFactory::isJoomla())
{
jimport('joomla.mail.helper');
return JMailHelper::isEmailAddress($emailAddress);
}
}
public static function getWebsiteOwnerEmailAddress()
{
if(!empty(self::$_getWebsiteOwnerEmailAddress)) return self::$_getWebsiteOwnerEmailAddress;
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
self::$_getWebsiteOwnerEmailAddress = get_bloginfo('admin_email');
}
elseif(BlueHatNetworkFactory::isJoomla())
{
$config =& JFactory::getConfig();
if(method_exists($config, 'getValue'))
{
self::$_getWebsiteOwnerEmailAddress = $config->getValue('config.mailfrom');
}
else
{
self::$_getWebsiteOwnerEmailAddress = $config->get('mailfrom');
}
}
return self::$_getWebsiteOwnerEmailAddress;
}
public static function mkdir($dirPath)
{
if(!class_exists('BlueHatNetworkFactory')) require BHN_PLUGIN_ADMIN_ROOT.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'factory.php';
if(BlueHatNetworkFactory::isWordPress())
{
return wp_mkdir_p($dirPath);
}
elseif(BlueHatNetworkFactory::isJoomla())
{
jimport('joomla.filesystem.folder');
return JFolder::create($dirPath);
}
}
public static function humanReadableFilesize($size)
{
$mod = 1024;
$units = explode(' ', 'Bytes KB MB GB TB PB');
for($i = 0; $size > $mod; $i++)
{
$size /= $mod;
}
return round($size, 2).' '.$units[$i];
}
public static function getFileExt($file)
{
return substr($file, strrpos($file, '.')+1);
}
public static function isWindows()
{
if(strncasecmp(PHP_OS, 'WIN', 3) == 0)
{
return true;
}
else
{
return false;
}
}
public static function extractGzipFile($gzipFilePath)
{
if(!is_file($gzipFilePath)) return false;
// Raising this value may increase performance
$buffer_size = 4096; // read 4kb at a time
$out_file_name = preg_replace('@\.gz$@i', '', $gzipFilePath, 1);
// Open our files (in binary mode)
$file = gzopen($gzipFilePath, 'rb');
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while(!gzeof($file))
{
// Read buffer-size bytes
// Both fwrite and gzread and binary-safe
fwrite($out_file, gzread($file, $buffer_size));
}
// Files are done, close files
fclose($out_file);
gzclose($file);
}
} | dialoquad/dialoquad | wp-content/plugins/blue-hat-cdn/lib/common.php | PHP | gpl-2.0 | 3,884 |
<?php
// Checking if visitor is connected
$connected = false;
$is_admin = false;
if ( !empty($_SESSION['member'])) {
$connected = true;
$stmt = $PDO->prepare('SELECT members_id FROM admins WHERE id=1');
$stmt->execute();
$rslt = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$members_id = explode(',', $rslt['members_id']);
if ( in_array($_SESSION['member']['id'], $members_id) )
$is_admin = true; // Visitor is an admin
}
// Global settings
error_reporting(0);
// Define path
define( 'PATH', '/TSBlog/' ); // Default : "/"
// Gettings configs
$stmt = $PDO->prepare('SELECT * FROM config WHERE id=1');
$stmt->execute();
$rslt = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->closeCursor();
define( 'MAX_SIZE_PICTURE', $rslt['maxsize'] ); // Limit of file's size 4 Mo
define( 'SITE_NAME', $rslt['sitename'] ); // Site name
define( 'PHONE_NUMBER', $rslt['phonenumber'] ); // Your phone number
define ('EMAIL_ADRESS', $rslt['email'] ); // Email adress
define('ABOUT', $rslt['aboutme'] ); // About me
// List of months
$mois = array('01'=>$lang15,
'02'=>$lang16,
'03'=>$lang17,
'04'=>$lang18,
'05'=>$lang19,
'06'=>$lang20,
'07'=>$lang21,
'08'=>$lang22,
'09'=>$lang23,
'10'=>$lang24,
'11'=>$lang25,
'12'=>$lang26);
?> | Tunisia-Sat/TSBlog | config/config.php | PHP | gpl-2.0 | 1,343 |
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using HTTPServer.Resources;
namespace HTTPServer
{
public partial class App : Application
{
/// <summary>
///提供对电话应用程序的根框架的轻松访问。
/// </summary>
/// <returns>电话应用程序的根框架。</returns>
public static PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Application 对象的构造函数。
/// </summary>
public App()
{
// 未捕获的异常的全局处理程序。
UnhandledException += Application_UnhandledException;
// 标准 XAML 初始化
InitializeComponent();
// 特定于电话的初始化
InitializePhoneApplication();
// 语言显示初始化
InitializeLanguage();
// 调试时显示图形分析信息。
if (Debugger.IsAttached)
{
// 显示当前帧速率计数器。
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// 显示在每个帧中重绘的应用程序区域。
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// 启用非生产分析可视化模式,
// 该模式显示递交给 GPU 的包含彩色重叠区的页面区域。
//Application.Current.Host.Settings.EnableCacheVisualization = true;
// 通过禁用以下对象阻止在调试过程中关闭屏幕
// 应用程序的空闲检测。
// 注意: 仅在调试模式下使用此设置。禁用用户空闲检测的应用程序在用户不使用电话时将继续运行
// 并且消耗电池电量。
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// 应用程序启动(例如,从“开始”菜单启动)时执行的代码
// 此代码在重新激活应用程序时不执行
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
// 激活应用程序(置于前台)时执行的代码
// 此代码在首次启动应用程序时不执行
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// 停用应用程序(发送到后台)时执行的代码
// 此代码在应用程序关闭时不执行
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// 应用程序关闭(例如,用户点击“后退”)时执行的代码
// 此代码在停用应用程序时不执行
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// 导航失败时执行的代码
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// 导航已失败;强行进入调试器
Debugger.Break();
}
}
// 出现未处理的异常时执行的代码
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// 出现未处理的异常;强行进入调试器
Debugger.Break();
}
}
#region 电话应用程序初始化
// 避免双重初始化
private bool phoneApplicationInitialized = false;
// 请勿向此方法中添加任何其他代码
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// 创建框架但先不将它设置为 RootVisual;这允许初始
// 屏幕保持活动状态,直到准备呈现应用程序时。
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// 处理导航故障
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// 在下一次导航中处理清除 BackStack 的重置请求,
RootFrame.Navigated += CheckForResetNavigation;
// 确保我们未再次初始化
phoneApplicationInitialized = true;
}
// 请勿向此方法中添加任何其他代码
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// 设置根视觉效果以允许应用程序呈现
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// 删除此处理程序,因为不再需要它
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
private void CheckForResetNavigation(object sender, NavigationEventArgs e)
{
// 如果应用程序收到“重置”导航,则需要进行检查
// 以确定是否应重置页面堆栈
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += ClearBackStackAfterReset;
}
private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
{
// 取消注册事件,以便不再调用该事件
RootFrame.Navigated -= ClearBackStackAfterReset;
// 只为“新建”(向前)和“刷新”导航清除堆栈
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// 为了获得 UI 一致性,请清除整个页面堆栈
while (RootFrame.RemoveBackEntry() != null)
{
; // 不执行任何操作
}
}
#endregion
// 初始化应用程序在其本地化资源字符串中定义的字体和排列方向。
//
// 若要确保应用程序的字体与受支持的语言相符,并确保
// 这些语言的 FlowDirection 都采用其传统方向,ResourceLanguage
// 应该初始化每个 resx 文件中的 ResourceFlowDirection,以便将这些值与以下对象匹配
// 文件的区域性。例如:
//
// AppResources.es-ES.resx
// ResourceLanguage 的值应为“es-ES”
// ResourceFlowDirection 的值应为“LeftToRight”
//
// AppResources.ar-SA.resx
// ResourceLanguage 的值应为“ar-SA”
// ResourceFlowDirection 的值应为“RightToLeft”
//
// 有关本地化 Windows Phone 应用程序的详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=262072。
//
private void InitializeLanguage()
{
try
{
// 将字体设置为与由以下对象定义的显示语言匹配
// 每种受支持的语言的 ResourceLanguage 资源字符串。
//
// 如果显示出现以下情况,则回退到非特定语言的字体
// 手机的语言不受支持。
//
// 如果命中编译器错误,则表示以下对象中缺少 ResourceLanguage
// 资源文件。
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// 根据以下条件设置根框架下的所有元素的 FlowDirection
// 每个以下对象的 ResourceFlowDirection 资源字符串上的
// 受支持的语言。
//
// 如果命中编译器错误,则表示以下对象中缺少 ResourceFlowDirection
// 资源文件。
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// 如果此处导致了异常,则最可能的原因是
// ResourceLangauge 未正确设置为受支持的语言
// 代码或 ResourceFlowDirection 设置为 LeftToRight 以外的值
// 或 RightToLeft。
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
}
} | sintrb/WindowsPhoneHTTPServer | App.xaml.cs | C# | gpl-2.0 | 8,746 |
package com.arantius.tivocommander.rpc.request;
import com.arantius.tivocommander.rpc.MindRpc;
public class Unsubscribe extends MindRpcRequest {
public Unsubscribe(String subscriptionId) {
super("unsubscribe");
mDataMap.put("bodyId", MindRpc.mTivoDevice.tsn);
mDataMap.put("subscriptionId", subscriptionId);
}
}
| arantius/TiVo-Commander | src/com/arantius/tivocommander/rpc/request/Unsubscribe.java | Java | gpl-2.0 | 330 |
/* -----------------------------------------------------------------------------------------------------------
Software License for The Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android
© Copyright 1995 - 2012 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
Copyright (C) 2012 Sony Mobile Communications AB.
1. INTRODUCTION
The Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
of the MPEG specifications.
Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
individually for the purpose of encoding or decoding bit streams in products that are compliant with
the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
software may already be covered under those patent licenses when it is used for those licensed purposes only.
Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
applications information and documentation.
2. COPYRIGHT LICENSE
Redistribution and use in source and binary forms, with or without modification, are permitted without
payment of copyright license fees provided that you satisfy the following conditions:
You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
your modifications thereto in source code form.
You must retain the complete text of this software license in the documentation and/or other materials
provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
modifications thereto to recipients of copies in binary form.
The name of Fraunhofer may not be used to endorse or promote products derived from this library without
prior written permission.
You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
software or your modifications thereto.
Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
and the date of any change. For modified versions of the FDK AAC Codec, the term
"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
3. NO PATENT LICENSE
NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
respect to this software.
You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
by appropriate patent licenses.
4. DISCLAIMER
This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
or business interruption, however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence), arising in any way out of the use of this software, even if
advised of the possibility of such damage.
5. CONTACT INFORMATION
Fraunhofer Institute for Integrated Circuits IIS
Attention: Audio and Multimedia Departments - FDK AAC LL
Am Wolfsmantel 33
91058 Erlangen, Germany
www.iis.fraunhofer.de/amm
amm-info@iis.fraunhofer.de
----------------------------------------------------------------------------------------------------------- */
/******************************** Fraunhofer IIS ***************************
Author(s): Arthur Tritthart
Description: (ARM optimised) LPP transposer subroutines
******************************************************************************/
#if defined(__arm__)
#define FUNCTION_LPPTRANSPOSER_func1
#ifdef FUNCTION_LPPTRANSPOSER_func1
/* Note: This code requires only 43 cycles per iteration instead of 61 on ARM926EJ-S */
__attribute__ ((noinline)) static void lppTransposer_func1(
FIXP_DBL *lowBandReal,
FIXP_DBL *lowBandImag,
FIXP_DBL **qmfBufferReal,
FIXP_DBL **qmfBufferImag,
int loops,
int hiBand,
int dynamicScale,
int descale,
FIXP_SGL a0r,
FIXP_SGL a0i,
FIXP_SGL a1r,
FIXP_SGL a1i)
{
FIXP_DBL real1, real2, imag1, imag2, accu1, accu2;
real2 = lowBandReal[-2];
real1 = lowBandReal[-1];
imag2 = lowBandImag[-2];
imag1 = lowBandImag[-1];
for(int i=0; i < loops; i++)
{
accu1 = fMultDiv2( a0r,real1);
accu2 = fMultDiv2( a0i,imag1);
accu1 = fMultAddDiv2(accu1,a1r,real2);
accu2 = fMultAddDiv2(accu2,a1i,imag2);
real2 = fMultDiv2( a1i,real2);
accu1 = accu1 - accu2;
accu1 = accu1 >> dynamicScale;
accu2 = fMultAddDiv2(real2,a1r,imag2);
real2 = real1;
imag2 = imag1;
accu2 = fMultAddDiv2(accu2,a0i,real1);
real1 = lowBandReal[i];
accu2 = fMultAddDiv2(accu2,a0r,imag1);
imag1 = lowBandImag[i];
accu2 = accu2 >> dynamicScale;
accu1 <<= 1;
accu2 <<= 1;
qmfBufferReal[i][hiBand] = accu1 + (real1>>descale);
qmfBufferImag[i][hiBand] = accu2 + (imag1>>descale);
}
}
#endif /* #ifdef FUNCTION_LPPTRANSPOSER_func1 */
#endif /* __arm__ */
| percy-g2/Novathor_xperia_u8500 | 6.2.A.1.100/external/aac/libSBRdec/src/arm/lpp_tran_arm.cpp | C++ | gpl-2.0 | 6,494 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2008-2020 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2020 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.web.rest.v1;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.EnumUtils;
import org.opennms.core.criteria.CriteriaBuilder;
import org.opennms.netmgt.dao.api.AcknowledgmentDao;
import org.opennms.netmgt.dao.api.AlarmDao;
import org.opennms.netmgt.model.AckAction;
import org.opennms.netmgt.model.OnmsAcknowledgment;
import org.opennms.netmgt.model.OnmsAlarm;
import org.opennms.netmgt.model.OnmsAlarmCollection;
import org.opennms.netmgt.model.TroubleTicketState;
import org.opennms.netmgt.model.alarm.AlarmSummary;
import org.opennms.netmgt.model.alarm.AlarmSummaryCollection;
import org.opennms.web.rest.support.MultivaluedMapImpl;
import org.opennms.web.rest.support.SecurityHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("alarmRestService")
@Path("alarms")
public class AlarmRestService extends AlarmRestServiceBase {
@Autowired
private AlarmDao m_alarmDao;
@Autowired
private AcknowledgmentDao m_ackDao;
/**
* <p>
* getAlarm
* </p>
*
* @param alarmId
* a {@link java.lang.String} object.
* @return a {@link org.opennms.netmgt.model.OnmsAlarm} object.
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML})
@Path("{alarmId}")
@Transactional
public Response getAlarm(@Context SecurityContext securityContext, @PathParam("alarmId") final String alarmId) {
SecurityHelper.assertUserReadCredentials(securityContext);
if ("summaries".equals(alarmId)) {
final List<AlarmSummary> collection = m_alarmDao.getNodeAlarmSummaries();
return collection == null ? Response.status(Status.NOT_FOUND).build() : Response.ok(new AlarmSummaryCollection(collection)).build();
} else {
final OnmsAlarm alarm = m_alarmDao.get(Integer.valueOf(alarmId));
return alarm == null ? Response.status(Status.NOT_FOUND).build() : Response.ok(alarm).build();
}
}
/**
* <p>
* getCount
* </p>
*
* @return a {@link java.lang.String} object.
*/
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("count")
@Transactional
public String getCount(@Context SecurityContext securityContext) {
SecurityHelper.assertUserReadCredentials(securityContext);
return Integer.toString(m_alarmDao.countAll());
}
/**
* <p>
* getAlarms
* </p>
*
* @return a {@link org.opennms.netmgt.model.OnmsAlarmCollection} object.
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML})
@Transactional
public OnmsAlarmCollection getAlarms(@Context final SecurityContext securityContext, @Context final UriInfo uriInfo) {
SecurityHelper.assertUserReadCredentials(securityContext);
final CriteriaBuilder builder = getCriteriaBuilder(uriInfo.getQueryParameters(), false);
builder.distinct();
final OnmsAlarmCollection coll = new OnmsAlarmCollection(m_alarmDao.findMatching(builder.toCriteria()));
// For getting totalCount
coll.setTotalCount(m_alarmDao.countMatching(builder.count().toCriteria()));
return coll;
}
/**
* <p>
* updateAlarm
* </p>
*
* @param alarmId
* a {@link java.lang.String} object.
* @param ack
* a {@link java.lang.Boolean} object.
*/
@PUT
@Path("{alarmId}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Transactional
public Response updateAlarm(@Context final SecurityContext securityContext, @PathParam("alarmId") final Integer alarmId, final MultivaluedMapImpl formProperties) {
writeLock();
try {
if (alarmId == null) {
return getBadRequestResponse("Unable to determine alarm ID to update based on query path.");
}
final String ackValue = formProperties.getFirst("ack");
formProperties.remove("ack");
final String escalateValue = formProperties.getFirst("escalate");
formProperties.remove("escalate");
final String clearValue = formProperties.getFirst("clear");
formProperties.remove("clear");
final String ackUserValue = formProperties.getFirst("ackUser");
formProperties.remove("ackUser");
final String ticketIdValue = formProperties.getFirst("ticketId");
formProperties.remove("ticketId");
final String ticketStateValue = formProperties.getFirst("ticketState");
formProperties.remove("ticketState");
final OnmsAlarm alarm = m_alarmDao.get(alarmId);
if (alarm == null) {
return getBadRequestResponse("Unable to locate alarm with ID '" + alarmId + "'");
}
boolean alarmUpdated = false;
if (StringUtils.isNotBlank(ticketIdValue)) {
alarmUpdated = true;
alarm.setTTicketId(ticketIdValue);
}
if (EnumUtils.isValidEnum(TroubleTicketState.class, ticketStateValue)) {
alarmUpdated = true;
alarm.setTTicketState(TroubleTicketState.valueOf(ticketStateValue));
}
if (alarmUpdated) {
m_alarmDao.saveOrUpdate(alarm);
}
final String ackUser = ackUserValue == null ? securityContext.getUserPrincipal().getName() : ackUserValue;
if (ackUser != null && StringUtils.isNotBlank(ackUser)) {
SecurityHelper.assertUserEditCredentials(securityContext, ackUser);
}
final OnmsAcknowledgment acknowledgement = new OnmsAcknowledgment(alarm, ackUser);
acknowledgement.setAckAction(AckAction.UNSPECIFIED);
boolean isProcessAck = false;
if (ackValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(ackValue)) {
acknowledgement.setAckAction(AckAction.ACKNOWLEDGE);
} else {
acknowledgement.setAckAction(AckAction.UNACKNOWLEDGE);
}
} else if (escalateValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(escalateValue)) {
acknowledgement.setAckAction(AckAction.ESCALATE);
}
} else if (clearValue != null) {
isProcessAck = true;
if (Boolean.parseBoolean(clearValue)) {
acknowledgement.setAckAction(AckAction.CLEAR);
}
}
if (isProcessAck) {
m_ackDao.processAck(acknowledgement);
m_ackDao.flush();
}
return Response.noContent().build();
} finally {
writeUnlock();
}
}
/**
* <p>
* updateAlarms
* </p>
*
* @param formProperties
* a {@link org.opennms.web.rest.support.MultivaluedMapImpl} object.
*/
@PUT
@Transactional
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updateAlarms(@Context final SecurityContext securityContext, final MultivaluedMapImpl formProperties) {
writeLock();
try {
final String ackValue = formProperties.getFirst("ack");
formProperties.remove("ack");
final String escalateValue = formProperties.getFirst("escalate");
formProperties.remove("escalate");
final String clearValue = formProperties.getFirst("clear");
formProperties.remove("clear");
final CriteriaBuilder builder = getCriteriaBuilder(formProperties, false);
builder.distinct();
builder.limit(0);
builder.offset(0);
final String ackUser = formProperties.containsKey("ackUser") ? formProperties.getFirst("ackUser") : securityContext.getUserPrincipal().getName();
formProperties.remove("ackUser");
SecurityHelper.assertUserEditCredentials(securityContext, ackUser);
final List<OnmsAlarm> alarms = m_alarmDao.findMatching(builder.toCriteria());
for (final OnmsAlarm alarm : alarms) {
final OnmsAcknowledgment acknowledgement = new OnmsAcknowledgment(alarm, ackUser);
acknowledgement.setAckAction(AckAction.UNSPECIFIED);
if (ackValue != null) {
if (Boolean.parseBoolean(ackValue)) {
acknowledgement.setAckAction(AckAction.ACKNOWLEDGE);
} else {
acknowledgement.setAckAction(AckAction.UNACKNOWLEDGE);
}
} else if (escalateValue != null) {
if (Boolean.parseBoolean(escalateValue)) {
acknowledgement.setAckAction(AckAction.ESCALATE);
}
} else if (clearValue != null) {
if (Boolean.parseBoolean(clearValue)) {
acknowledgement.setAckAction(AckAction.CLEAR);
}
} else {
throw getException(Status.BAD_REQUEST, "Must supply one of the 'ack', 'escalate', or 'clear' parameters, set to either 'true' or 'false'.");
}
m_ackDao.processAck(acknowledgement);
}
return alarms == null || alarms.isEmpty() ? Response.notModified().build() : Response.noContent().build();
} finally {
writeUnlock();
}
}
}
| jeffgdotorg/opennms | opennms-webapp-rest/src/main/java/org/opennms/web/rest/v1/AlarmRestService.java | Java | gpl-2.0 | 11,406 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VDS.RDF.Query.Expressions.Functions.Leviathan.Numeric.Trigonometry
{
/// <summary>
/// Represents the Leviathan lfn:cot() or lfn:cot-1 function
/// </summary>
public class CotangentFunction
: BaseTrigonometricFunction
{
private bool _inverse = false;
private static Func<double, double> _cotangent = (d => (Math.Cos(d) / Math.Sin(d)));
private static Func<double, double> _arccotangent = (d => Math.Atan(1 / d));
/// <summary>
/// Creates a new Leviathan Cotangent Function
/// </summary>
/// <param name="expr">Expression</param>
public CotangentFunction(ISparqlExpression expr)
: base(expr, _cotangent) { }
/// <summary>
/// Creates a new Leviathan Cotangent Function
/// </summary>
/// <param name="expr">Expression</param>
/// <param name="inverse">Whether this should be the inverse function</param>
public CotangentFunction(ISparqlExpression expr, bool inverse)
: base(expr)
{
this._inverse = inverse;
if (this._inverse)
{
this._func = _arccotangent;
}
else
{
this._func = _cotangent;
}
}
/// <summary>
/// Gets the String representation of the function
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this._inverse)
{
return "<" + LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotanInv + ">(" + this._expr.ToString() + ")";
}
else
{
return "<" + LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotan + ">(" + this._expr.ToString() + ")";
}
}
/// <summary>
/// Gets the Functor of the Expression
/// </summary>
public override string Functor
{
get
{
if (this._inverse)
{
return LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotanInv;
}
else
{
return LeviathanFunctionFactory.LeviathanFunctionsNamespace + LeviathanFunctionFactory.TrigCotan;
}
}
}
/// <summary>
/// Transforms the Expression using the given Transformer
/// </summary>
/// <param name="transformer">Expression Transformer</param>
/// <returns></returns>
public override ISparqlExpression Transform(IExpressionTransformer transformer)
{
return new CotangentFunction(transformer.Transform(this._expr), this._inverse);
}
}
}
| jmahmud/RDFer | RDFerSolution/dotNetRdf/Query/Expressions/Functions/Leviathan/Numeric/Trigonometry/CotangentFunction.cs | C# | gpl-2.0 | 2,997 |
// $ANTLR 2.7.0a11: "antlr.g" -> "ANTLRLexer.java"$
package antlr;
public interface ANTLRTokenTypes {
int EOF = 1;
int NULL_TREE_LOOKAHEAD = 3;
int LITERAL_tokens = 4;
int LITERAL_header = 5;
int STRING_LITERAL = 6;
int ACTION = 7;
int DOC_COMMENT = 8;
int LITERAL_lexclass = 9;
int LITERAL_class = 10;
int LITERAL_extends = 11;
int LITERAL_Lexer = 12;
int LITERAL_TreeParser = 13;
int OPTIONS = 14;
int ASSIGN = 15;
int SEMI = 16;
int RCURLY = 17;
int LITERAL_charVocabulary = 18;
int CHAR_LITERAL = 19;
int INT = 20;
int OR = 21;
int RANGE = 22;
int TOKENS = 23;
int TOKEN_REF = 24;
int OPEN_ELEMENT_OPTION = 25;
int CLOSE_ELEMENT_OPTION = 26;
int LPAREN = 27;
int RULE_REF = 28;
int RPAREN = 29;
int LITERAL_Parser = 30;
int LITERAL_protected = 31;
int LITERAL_public = 32;
int LITERAL_private = 33;
int BANG = 34;
int ARG_ACTION = 35;
int LITERAL_returns = 36;
int COLON = 37;
int LITERAL_exception = 38;
int LITERAL_catch = 39;
int NOT_OP = 40;
int SEMPRED = 41;
int TREE_BEGIN = 42;
int QUESTION = 43;
int STAR = 44;
int PLUS = 45;
int IMPLIES = 46;
int CARET = 47;
int WILDCARD = 48;
int LITERAL_options = 49;
int WS = 50;
int COMMENT = 51;
int SL_COMMENT = 52;
int ML_COMMENT = 53;
int COMMA = 54;
int ESC = 55;
int DIGIT = 56;
int XDIGIT = 57;
int VOCAB = 58;
int NESTED_ARG_ACTION = 59;
int NESTED_ACTION = 60;
int WS_LOOP = 61;
int INTERNAL_RULE_REF = 62;
int WS_OPT = 63;
int NOT_USEFUL = 64;
}
| dbenn/cgp | lib/antlr-2.7.0/antlr/ANTLRTokenTypes.java | Java | gpl-2.0 | 1,472 |
package Common.Loggers;
import Common.FuncInterfaces.*;
import Common.Interfaces.ILogger;
import java.io.*;
import static Common.Utils.StringUtils.LineBreak;
import static Common.Utils.TimeUtils.nowTime;
import static java.lang.String.format;
/**
* Created by roman.i on 25.09.2014.
*/
public class DefaultLogger implements ILogger {
public FuncT<String> LogFileFormat;
private static String LogRecordTemplate = LineBreak + "[%s] %s: %s" + LineBreak;
private FuncTTT<String, String, String> LogRecord = (String s1, String s2) -> format(LogRecordTemplate, s1, nowTime("yyyy-MM-dd HH:mm:ss.S"), s2);
public FuncT<String> LogDirectoryRoot = () -> ".Logs/";
public boolean CreateFoldersForLogTypes = true;
public static String getValidUrl(String logPath)
{
if (logPath == null || logPath.equals(""))
return "";
String result = logPath.replace("/", "\\");
if (result.charAt(1) != ':')
if (result.substring(0, 3).equals("..\\"))
result = result.substring(2);
if (result.charAt(0) != '\\')
result = "\\" + result;
return (result.charAt(result.length() - 1) == '\\')
? result
: result + "\\";
}
public File getFile(String fileName) throws Exception {
File file = new File(".");
String current = file.getCanonicalPath();
String logDirectory = current + getValidUrl(LogDirectoryRoot.invoke()) + (CreateFoldersForLogTypes ? fileName + "s\\" : "");
return new File(logDirectory + format(LogFileFormat.invoke(), fileName));
}
public void createDirFile(File file) throws IOException {
file.getParentFile().mkdirs();
if (!file.exists())
file.createNewFile();
}
private void InLog(String fileName, String typeName, String msg) throws Exception {
File file = getFile(fileName);
createDirFile(file);
writeInFile(file, LogRecord.invoke(typeName, msg));
}
private void writeInFile(File file, String msg) throws Exception {
FileWriter fw = new FileWriter(file, true);
fw.write(msg);
fw.close();
}
public void Event(String msg) throws Exception {
InLog("Event", "Event", msg);
}
public void Error(String msg) throws Exception {
InLog("Error", "Error", msg);
InLog("Event", "Error", msg);
}
}
| elv1s42/VIQAUITestingTool | Java/src/main/java/Common/Loggers/DefaultLogger.java | Java | gpl-2.0 | 2,428 |
<?php
//-
$ranges=Array(
"3573547008" => array("3573612543","ES"),
"3573612544" => array("3573743615","GB"),
"3573743616" => array("3573809151","CH"),
"3573809152" => array("3573874687","ES"),
"3573874688" => array("3573878783","PL"),
"3573878784" => array("3573882879","RU"),
"3573882880" => array("3573884927","DK"),
"3573884928" => array("3573886975","PL"),
"3573886976" => array("3573889023","RU"),
"3573889024" => array("3573891071","HR"),
"3573891072" => array("3573893119","NL"),
"3573893120" => array("3573897215","RU"),
"3573897216" => array("3573899263","GB"),
"3573899264" => array("3573903359","RU"),
"3573903360" => array("3573905407","SI"),
"3573905408" => array("3573909503","RU"),
"3573909504" => array("3573913599","PL"),
"3573913600" => array("3573915647","CH"),
"3573915648" => array("3573917695","RU"),
"3573917696" => array("3573919743","SA"),
"3573919744" => array("3573921791","GB"),
"3573921792" => array("3573923839","RU"),
"3573923840" => array("3573925887","UA"),
"3573925888" => array("3573929983","PL"),
"3573929984" => array("3573938175","RU"),
"3573938176" => array("3573940223","PL"),
"3573940224" => array("3574005759","PS"),
"3574005760" => array("3574071295","CY"),
"3574071296" => array("3574136831","IL"),
"3574136832" => array("3574169599","DE"),
"3574169600" => array("3574202367","ES"),
"3574202368" => array("3574267903","NL"),
"3574267904" => array("3574333439","FR"),
"3574333440" => array("3574398975","EU"),
"3574398976" => array("3574464511","PT"),
"3574464512" => array("3574530047","TR"),
"3574530048" => array("3574595583","SE"),
"3574595584" => array("3574603775","FR"),
"3574603776" => array("3574611967","BG"),
"3574611968" => array("3574628351","HU"),
"3574628352" => array("3574661119","GR"),
"3574661120" => array("3574693887","NL"),
"3574693888" => array("3574726655","PL"),
"3574726656" => array("3574792191","GB"),
"3574792192" => array("3574824959","CZ"),
"3574824960" => array("3574857727","GB"),
"3574857728" => array("3574923263","DE"),
"3574923264" => array("3574939647","RU"),
"3574939648" => array("3574956031","SE"),
"3574956032" => array("3574972415","IT"),
"3574972416" => array("3574988799","LV"),
"3574988800" => array("3575054335","PT"),
"3575054336" => array("3575119871","DE"),
"3575119872" => array("3575185407","RU"),
"3575185408" => array("3575250943","PL"),
"3575250944" => array("3575316479","IT"),
"3575316480" => array("3575349247","RU"),
"3575349248" => array("3575382015","ES"),
"3575382016" => array("3575447551","FI"),
"3575447552" => array("3575513087","CZ"),
"3575513088" => array("3575545855","PT"),
"3575545856" => array("3575562239","FR"),
"3575562240" => array("3575578623","DE"),
"3575578624" => array("3575644159","BE"),
"3575644160" => array("3575709695","DK"),
"3575709696" => array("3575742463","AT"),
"3575742464" => array("3575775231","RU"),
"3575775232" => array("3575824383","NL"),
"3575824384" => array("3575832575","KW"),
"3575832576" => array("3575840767","NL"),
"3575840768" => array("3575873535","GB"),
"3575873536" => array("3575906303","EE"),
"3575906304" => array("3575971839","FR"),
"3575971840" => array("3576037375","ES"),
"3576037376" => array("3576102911","EU"),
"3576102912" => array("3576135679","GB"),
"3576135680" => array("3576168447","DE"),
"3576168448" => array("3576266751","GB"),
"3576266752" => array("3576299519","FR"),
"3576299520" => array("3576365055","AE"),
"3576365056" => array("3576430591","TR"),
"3576430592" => array("3576496127","FR"),
"3576496128" => array("3576561663","IT"),
"3576561664" => array("3576627199","NL"),
"3576627200" => array("3576692735","AT"),
"3576692736" => array("3576758271","GB"),
"3576758272" => array("3576823807","BE"),
"3576823808" => array("3576889343","SE"),
"3576889344" => array("3576954879","NL"),
"3576954880" => array("3576987647","NO"),
"3576987648" => array("3577020415","GB"),
"3577020416" => array("3577085951","NL"),
"3577085952" => array("3577151487","DE"),
"3577151488" => array("3577167871","FR"),
"3577167872" => array("3577184255","ET"),
"3577184256" => array("3577217023","CH"),
"3577217024" => array("3577282559","FR"),
"3577282560" => array("3577348095","IL"),
"3577348096" => array("3577413631","PT"),
"3577413632" => array("3577479167","RU"),
"3577479168" => array("3577544703","ES"),
"3577544704" => array("3577610239","DE"),
"3577610240" => array("3577675775","EU"),
"3577675776" => array("3577741311","PT"),
"3577741312" => array("3578003455","SE"),
"3578003456" => array("3578265599","DE"),
"3578265600" => array("3578331135","GB"),
"3578331136" => array("3578339327","PL"),
"3578339328" => array("3578347519","ES"),
"3578347520" => array("3578363903","DE"),
"3578363904" => array("3578396671","NL"),
"3578396672" => array("3578462207","TR"),
"3578462208" => array("3578527743","NL"),
"3578527744" => array("3578658815","PL"),
"3578658816" => array("3578724351","GB"),
"3578724352" => array("3578732543","RU"),
"3578732544" => array("3578740735","IE"),
"3578740736" => array("3578757119","RU"),
"3578757120" => array("3578822655","SE"),
"3578822656" => array("3578855423","RU"),
"3578855424" => array("3578888191","GB"),
"3578888192" => array("3578920959","SK"),
"3578920960" => array("3578986495","IT"),
"3578986496" => array("3579002879","DE"),
"3579002880" => array("3579019263","GB"),
"3579019264" => array("3579052031","DK"),
"3579052032" => array("3579117567","NL"),
"3579117568" => array("3579183103","RU"),
"3579183104" => array("3579248639","GB"),
"3579248640" => array("3579346943","RU"),
"3579346944" => array("3579445247","SE"),
"3579445248" => array("3579478015","AT"),
"3579478016" => array("3579527167","FR"),
"3579527168" => array("3579543551","BA"),
"3579543552" => array("3579576319","BG"),
"3579576320" => array("3579609087","IT"),
"3579609088" => array("3579641855","PL"),
"3579641856" => array("3579707391","NL"),
"3579707392" => array("3579723775","ES"),
"3579723776" => array("3579740159","AT"),
"3579740160" => array("3579772927","IE"),
"3579772928" => array("3579838463","DE"),
"3579838464" => array("3580100607","ES"),
"3580100608" => array("3580362751","SE"),
"3580362752" => array("3580624895","GB"),
"3580624896" => array("3580626943","RU"),
"3580626944" => array("3580628991","PL"),
"3580628992" => array("3580631039","RU"),
"3580631040" => array("3580633087","NL"),
"3580633088" => array("3580635135","RU"),
"3580635136" => array("3580637183","UA"),
"3580637184" => array("3580639231","KZ"),
"3580639232" => array("3580641279","PL"),
"3580641280" => array("3580643327","FR"),
"3580643328" => array("3580645375","UA"),
"3580645376" => array("3580647423","PL"),
"3580647424" => array("3580649471","DE"),
"3580649472" => array("3580651519","SE"),
"3580651520" => array("3580653567","NL"),
"3580653568" => array("3580655615","PL"),
"3580655616" => array("3580657663","SK"),
"3580657664" => array("3580663807","RU"),
"3580663808" => array("3580665855","PL"),
"3580665856" => array("3580667903","CZ"),
"3580667904" => array("3580669951","RU"),
"3580669952" => array("3580671999","UA"),
"3580672000" => array("3580682239","RU"),
"3580682240" => array("3580684287","PL"),
"3580684288" => array("3580686335","FR"),
"3580686336" => array("3580688383","BG"),
"3580688384" => array("3580698623","RU"),
"3580698624" => array("3580702719","PL"),
"3580702720" => array("3580710911","RU"),
"3580710912" => array("3580715007","UA"),
"3580715008" => array("3580719103","RU"),
"3580719104" => array("3580723199","NL"),
"3580723200" => array("3580727295","UA"),
"3580727296" => array("3580731391","RU"),
"3580731392" => array("3580739583","RO"),
"3580739584" => array("3580743679","RU"),
"3580743680" => array("3580751871","UA"),
"3580751872" => array("3580755967","IR"),
"3580755968" => array("3580772351","RU"),
"3580772352" => array("3580780543","LV"),
"3580780544" => array("3580805119","UA"),
"3580805120" => array("3580821503","RU"),
"3580821504" => array("3580837887","FR"),
"3580837888" => array("3580887039","UA"),
"3580887040" => array("3581149183","SE"),
"3581149184" => array("3581280255","EU"),
"3581280256" => array("3581411327","BE"),
"3581411328" => array("3581673471","GB"),
"3581673472" => array("3581935615","NL"),
"3581935616" => array("3581943807","RU"),
"3581943808" => array("3581951999","FR"),
"3581952000" => array("3581960191","TR"),
"3581960192" => array("3581976575","DE"),
"3581976576" => array("3581984767","NO"),
"3581984768" => array("3581992959","RU"),
"3581992960" => array("3582001151","GB"),
"3582001152" => array("3582009343","DK"),
"3582009344" => array("3582017535","RU"),
"3582017536" => array("3582025727","GB"),
"3582025728" => array("3582033919","RU"),
"3582033920" => array("3582042111","CZ"),
"3582042112" => array("3582050303","ES"),
"3582050304" => array("3582058495","NL"),
"3582058496" => array("3582066687","AT"),
"3582066688" => array("3582074879","UA"),
"3582074880" => array("3582083071","GB"),
"3582083072" => array("3582091263","BG"),
"3582091264" => array("3582099455","QA"),
"3582099456" => array("3582107647","GB"),
"3582107648" => array("3582115839","NL"),
"3582115840" => array("3582124031","SE"),
"3582124032" => array("3582132223","FI"),
"3582132224" => array("3582140415","RU"),
"3582140416" => array("3582148607","GE"),
"3582148608" => array("3582156799","EG"),
"3582156800" => array("3582164991","GB"),
"3582164992" => array("3582173183","SE"),
"3582173184" => array("3582181375","GB"),
"3582181376" => array("3582197759","DE"),
"3582197760" => array("3582205951","DK"),
"3582205952" => array("3582214143","AE"),
"3582214144" => array("3582222335","RU"),
"3582222336" => array("3582230527","SE"),
"3582230528" => array("3582238719","BE"),
"3582238720" => array("3582255103","NL"),
"3582255104" => array("3582263295","KW"),
"3582263296" => array("3582271487","ME"),
"3582271488" => array("3582279679","NL"),
"3582279680" => array("3582287871","GB"),
"3582287872" => array("3582296063","DE"),
"3582296064" => array("3582304255","GB"),
"3582304256" => array("3582312447","UA"),
"3582312448" => array("3582320639","JE"),
"3582320640" => array("3582328831","CH"),
"3582328832" => array("3582337023","HU"),
"3582337024" => array("3582345215","ES"),
"3582345216" => array("3582353407","IT"),
"3582353408" => array("3582361599","SE"),
"3582361600" => array("3582377983","PL"),
"3582377984" => array("3582386175","RU"),
"3582386176" => array("3582394367","NL"),
"3582394368" => array("3582402559","DE"),
"3582402560" => array("3582410751","PL"),
"3582410752" => array("3582435327","RU"),
"3582435328" => array("3582443519","MK"),
"3582443520" => array("3582451711","DE"),
"3582451712" => array("3582459903","LU"),
"3582459904" => array("3582468095","NL"),
"3582468096" => array("3582476287","SE"),
"3582476288" => array("3582484479","DE"),
"3582484480" => array("3582492671","CI"),
"3582492672" => array("3582509055","IT"),
"3582509056" => array("3582517247","SA"),
"3582517248" => array("3582525439","PL"),
"3582525440" => array("3582533631","GB"),
"3582533632" => array("3582541823","BG"),
"3582541824" => array("3582550015","US"),
"3582550016" => array("3582558207","RS"),
"3582558208" => array("3582566399","MC"),
"3582566400" => array("3582574591","EU"),
"3582574592" => array("3582582783","DE"),
"3582582784" => array("3582590975","RU"),
"3582590976" => array("3582599167","FR"),
"3582599168" => array("3582607359","DE"),
"3582607360" => array("3582615551","RU"),
"3582615552" => array("3582623743","GB"),
"3582623744" => array("3582631935","FI"),
"3582631936" => array("3582640127","NO"),
"3582640128" => array("3582648319","RU"),
"3582648320" => array("3582656511","PT"),
"3582656512" => array("3582664703","ES"),
"3582664704" => array("3582672895","JO"),
"3582672896" => array("3582681087","DE"),
"3582681088" => array("3582689279","FR"),
"3582689280" => array("3582697471","DE"),
"3582697472" => array("3582705663","FI"),
"3582705664" => array("3582722047","TR"),
"3582722048" => array("3582730239","IT"),
"3582730240" => array("3582738431","ES"),
"3582738432" => array("3582746623","DK"),
"3582746624" => array("3582754815","RU"),
"3582754816" => array("3582763007","GR"),
"3582763008" => array("3582771199","FI"),
"3582771200" => array("3582779391","CY"),
"3582779392" => array("3582787583","RU"),
"3582787584" => array("3582795775","PT"),
"3582795776" => array("3582803967","ES"),
"3582803968" => array("3582812159","SE"),
"3582812160" => array("3582820351","FI"),
"3582820352" => array("3582828543","RU"),
"3582828544" => array("3582836735","KZ"),
"3582836736" => array("3582853119","RU"),
"3582853120" => array("3582861311","SE"),
"3582861312" => array("3582869503","RU"),
"3582869504" => array("3582877695","NO"),
"3582877696" => array("3582885887","AT"),
"3582885888" => array("3582894079","TR"),
"3582894080" => array("3582902271","CH"),
"3582902272" => array("3582910463","RU"),
"3582910464" => array("3582918655","SI"),
"3582918656" => array("3582926847","GB"),
"3582926848" => array("3582935039","ES"),
"3582935040" => array("3582943231","SI"),
"3582943232" => array("3582951423","AT"),
"3582951424" => array("3582959615","GB"),
"3582959616" => array("3582967807","FI"),
"3582967808" => array("3582975999","DE"),
"3582976000" => array("3582984191","TR"),
"3582984192" => array("3582992383","DE"),
"3582992384" => array("3583000575","ES"),
"3583000576" => array("3583008767","IT"),
"3583008768" => array("3583016959","TR"),
"3583016960" => array("3583025151","CH"),
"3583025152" => array("3583033343","IT"),
"3583033344" => array("3583041535","FR"),
"3583041536" => array("3583049727","NL"),
"3583049728" => array("3583066111","RU"),
"3583066112" => array("3583074303","DE"),
"3583074304" => array("3583082495","BG"),
"3583082496" => array("3583090687","KG"),
"3583090688" => array("3583098879","NO"),
"3583098880" => array("3583107071","FI"),
"3583107072" => array("3583115263","AT"),
"3583115264" => array("3583123455","CH"),
"3583123456" => array("3583131647","PL"),
"3583131648" => array("3583139839","SE"),
"3583139840" => array("3583148031","DE"),
"3583148032" => array("3583164415","GB"),
"3583164416" => array("3583172607","PT"),
"3583172608" => array("3583188991","DE"),
"3583188992" => array("3583197183","RU"),
"3583197184" => array("3583205375","KE"),
"3583205376" => array("3583213567","HR"),
"3583213568" => array("3583221759","IR"),
"3583221760" => array("3583229951","AT"),
"3583229952" => array("3583238143","RU"),
"3583238144" => array("3583246335","GB"),
"3583246336" => array("3583254527","RU"),
"3583254528" => array("3583262719","GB"),
"3583262720" => array("3583270911","TR"),
"3583270912" => array("3583287295","DE"),
"3583287296" => array("3583295487","RU"),
"3583295488" => array("3583303679","ES"),
"3583303680" => array("3583311871","NL"),
"3583311872" => array("3583320063","RU"),
"3583320064" => array("3583328255","HR"),
"3583328256" => array("3583336447","DE"),
"3583336448" => array("3583344639","ME"),
"3583344640" => array("3583352831","BG"),
"3583352832" => array("3583361023","CY"),
"3583361024" => array("3583369215","IT"),
"3583369216" => array("3583377407","ES"),
"3583377408" => array("3583385599","AT"),
"3583385600" => array("3583393791","DK"),
"3583393792" => array("3583401983","RU"),
"3583401984" => array("3583410175","KE"),
"3583410176" => array("3583418367","SE"),
"3583418368" => array("3583426559","TN"),
"3583426560" => array("3583434751","CI"),
"3583434752" => array("3583442943","AT"),
"3583442944" => array("3583451135","UA"),
"3583451136" => array("3583459327","IL"),
"3583459328" => array("3583467519","CZ"),
"3583467520" => array("3583475711","ES"),
"3583475712" => array("3583483903","NO"),
"3583483904" => array("3583492095","FR"),
"3583492096" => array("3583508479","SK"),
"3583508480" => array("3583516671","FR"),
"3583516672" => array("3583524863","GB"),
"3583524864" => array("3583533055","EG"),
"3583533056" => array("3583541247","DE"),
"3583541248" => array("3583549439","RU"),
"3583549440" => array("3583557631","NL"),
"3583557632" => array("3583565823","IT"),
"3583565824" => array("3583574015","GB"),
"3583574016" => array("3583582207","NO"),
"3583582208" => array("3583590399","AT"),
"3583590400" => array("3583598591","DE"),
"3583598592" => array("3583606783","SE"),
"3583606784" => array("3583639551","TR"),
"3583639552" => array("3583647743","AZ"),
"3583647744" => array("3583655935","EG"),
"3583655936" => array("3583664127","SN"),
"3583664128" => array("3583680511","RO"),
"3583680512" => array("3583688703","RU"),
"3583688704" => array("3583696895","UA"),
"3583696896" => array("3583705087","NL"),
"3583705088" => array("3583713279","UA"),
"3583713280" => array("3583721471","CZ"),
"3583721472" => array("3583729663","DE"),
"3583729664" => array("3583737855","TR"),
"3583737856" => array("3583746047","EU"),
"3583746048" => array("3583754239","PL"),
"3583754240" => array("3583762431","RU"),
"3583762432" => array("3583770623","CZ"),
"3583770624" => array("3583778815","NL"),
"3583778816" => array("3583787007","IT"),
"3583787008" => array("3583795199","UA"),
"3583795200" => array("3583803391","PL"),
"3583803392" => array("3583811583","RU"),
"3583811584" => array("3583819775","DE"),
"3583819776" => array("3583827967","RU"),
"3583827968" => array("3583836159","CH"),
"3583836160" => array("3583844351","DE"),
"3583844352" => array("3583852543","KZ"),
"3583852544" => array("3583860735","FI"),
"3583860736" => array("3583868927","HU"),
"3583868928" => array("3583877119","AT"),
"3583877120" => array("3583885311","RO"),
"3583885312" => array("3583893503","GE"),
"3583893504" => array("3583901695","SI"),
"3583901696" => array("3583909887","RU"),
"3583909888" => array("3583918079","SE"),
"3583918080" => array("3583926271","IT"),
"3583926272" => array("3583934463","DE"),
"3583934464" => array("3583942655","CH"),
"3583942656" => array("3583950847","EG"),
"3583950848" => array("3583959039","PL"),
"3583959040" => array("3583967231","NO"),
"3583967232" => array("3583975423","NL"),
"3583975424" => array("3583983615","LT"),
"3583983616" => array("3583999999","RU"),
"3584000000" => array("3584008191","IE"),
"3584008192" => array("3584016383","DK"),
"3584016384" => array("3584024575","RU"),
"3584024576" => array("3584032767","UA"),
"3584032768" => array("3584040959","DE"),
"3584040960" => array("3584049151","CH"),
"3584049152" => array("3584057343","DE"),
"3584057344" => array("3584065535","GB"),
"3584065536" => array("3584073727","UA"),
"3584073728" => array("3584081919","SK"),
"3584081920" => array("3584098303","NL"),
"3584098304" => array("3584106495","SI"),
"3584106496" => array("3584114687","FI"),
"3584114688" => array("3584122879","GB"),
"3584122880" => array("3584131071","PL"),
"3584131072" => array("3584139263","TR"),
"3584139264" => array("3584147455","NO"),
"3584147456" => array("3584155647","FR"),
"3584155648" => array("3584163839","NO"),
"3584163840" => array("3584172031","CH"),
"3584172032" => array("3584180223","FR"),
"3584180224" => array("3584188415","AT"),
"3584188416" => array("3584196607","GB"),
"3584196608" => array("3584204799","DE"),
"3584204800" => array("3584212991","NL"),
"3584212992" => array("3584221183","ES"),
"3584221184" => array("3584229375","NO"),
"3584229376" => array("3584245759","HU"),
"3584245760" => array("3584253951","NL"),
"3584253952" => array("3584262143","ME"),
"3584262144" => array("3584270335","SE"),
"3584270336" => array("3584278527","FR"),
"3584278528" => array("3584286719","GB"),
"3584286720" => array("3584303103","AT"),
"3584303104" => array("3584311295","ES"),
"3584311296" => array("3584319487","DE"),
"3584319488" => array("3584327679","LT"),
"3584327680" => array("3584335871","DE"),
"3584335872" => array("3584344063","ES"),
"3584344064" => array("3584352255","SE"),
"3584352256" => array("3584360447","RO"),
"3584360448" => array("3584368639","GB"),
"3584368640" => array("3584376831","LB"),
"3584376832" => array("3584393215","DE"),
"3584393216" => array("3584401407","GB"),
"3584401408" => array("3584409599","MT"),
"3584409600" => array("3584417791","RU"),
"3584417792" => array("3584434175","GB"),
"3584434176" => array("3584442367","LU"),
"3584442368" => array("3584450559","GB"),
"3584450560" => array("3584458751","EU"),
"3584458752" => array("3584466943","SA"),
"3584466944" => array("3584475135","NO"),
"3584475136" => array("3584483327","FR"),
"3584483328" => array("3584491519","DE"),
"3584491520" => array("3584499711","BG"),
"3584499712" => array("3584507903","RU"),
"3584507904" => array("3584516095","GB"),
"3584516096" => array("3584524287","NO"),
"3584524288" => array("3584532479","IS"),
"3584532480" => array("3584540671","DE"),
"3584540672" => array("3584548863","RU"),
"3584548864" => array("3584557055","ES"),
"3584557056" => array("3584565247","EE"),
"3584565248" => array("3584573439","RU"),
"3584573440" => array("3584589823","DE"),
"3584589824" => array("3584598015","RU"),
"3584598016" => array("3584606207","CZ"),
"3584606208" => array("3584614399","DE"),
"3584614400" => array("3584622591","IE"),
"3584622592" => array("3584630783","FI"),
"3584630784" => array("3584638975","BG"),
"3584638976" => array("3584647167","UA"),
"3584647168" => array("3584655359","LU"),
"3584655360" => array("3584663551","CY"),
"3584663552" => array("3584671743","FR"),
"3584671744" => array("3584688127","NL"),
"3584688128" => array("3584696319","GB"),
"3584696320" => array("3584704511","ES"),
"3584704512" => array("3584720895","RU"),
"3584720896" => array("3584729087","GB"),
"3584729088" => array("3584737279","DE"),
"3584737280" => array("3584745471","GR"),
"3584745472" => array("3584753663","DK"),
"3584753664" => array("3584770047","RU"),
"3584770048" => array("3584778239","NL"),
"3584778240" => array("3584786431","IT"),
"3584786432" => array("3584794623","NL"),
"3584794624" => array("3584802815","IT"),
"3584802816" => array("3584811007","GB"),
"3584811008" => array("3584819199","ES"),
"3584819200" => array("3584827391","RU"),
"3584827392" => array("3584835583","ES"),
"3584835584" => array("3584843775","AZ"),
"3584843776" => array("3584851967","DE"),
"3584860160" => array("3584868351","PL"),
"3584868352" => array("3584876543","NO"),
"3584876544" => array("3584884735","SI"),
"3584884736" => array("3584892927","DE"),
"3584892928" => array("3584901119","IL"),
"3584901120" => array("3584909311","AT"),
"3584909312" => array("3584917503","IT"),
"3584917504" => array("3584925695","FI"),
"3584925696" => array("3584933887","CH"),
"3584933888" => array("3584942079","SE"),
"3584942080" => array("3584950271","DK"),
"3584950272" => array("3584958463","UA"),
"3584958464" => array("3584966655","DE"),
"3584966656" => array("3584974847","DK"),
"3584974848" => array("3584983039","FR"),
"3584983040" => array("3584991231","NL"),
"3584991232" => array("3584999423","IT"),
"3584999424" => array("3585007615","GB"),
"3585007616" => array("3585015807","AT"),
"3585015808" => array("3585023999","IT"),
"3585024000" => array("3585032191","CZ"),
"3585032192" => array("3585048575","LV"),
"3585048576" => array("3585056767","GB"),
"3585056768" => array("3585064959","LB"),
"3585064960" => array("3585081343","GB"),
"3585081344" => array("3585114111","IR"),
"3585114112" => array("3585122303","IS"),
"3585122304" => array("3585130495","ES"),
"3585130496" => array("3585138687","FR"),
"3585138688" => array("3585146879","RU"),
"3585146880" => array("3585155071","RO"),
"3585155072" => array("3585163263","GB"),
"3585163264" => array("3585171455","BE"),
"3585171456" => array("3585179647","RU"),
"3585179648" => array("3585196031","BE"),
"3585196032" => array("3585204223","ES"),
"3585204224" => array("3585212415","GB"),
"3585212416" => array("3585220607","DE"),
"3585220608" => array("3585228799","RU"),
"3585228800" => array("3585236991","DE"),
"3585236992" => array("3585245183","HU"),
"3585245184" => array("3585253375","GB"),
"3585253376" => array("3585261567","DE"),
"3585261568" => array("3585269759","IT"),
"3585269760" => array("3585277951","SY"),
"3585277952" => array("3585286143","SE"),
"3585286144" => array("3585294335","NO"),
"3585294336" => array("3585302527","DE"),
"3585302528" => array("3585310719","ES"),
"3585310720" => array("3585318911","DE"),
"3585318912" => array("3585327103","DZ"),
"3585327104" => array("3585335295","NL"),
"3585335296" => array("3585343487","UA"),
"3585343488" => array("3585351679","EE"),
"3585351680" => array("3585359871","CZ"),
"3585359872" => array("3585368063","SE"),
"3585368064" => array("3585376255","LV"),
"3585376256" => array("3585384447","PL"),
"3585384448" => array("3585392639","CH"),
"3585392640" => array("3585400831","RU"),
"3585400832" => array("3585409023","FR"),
"3585409024" => array("3585417215","RU"),
"3585417216" => array("3585425407","BE"),
"3585425408" => array("3585433599","ES"),
"3585433600" => array("3585441791","IS"),
"3585441792" => array("3585449983","SK"),
"3585449984" => array("3585458175","SA"),
"3585458176" => array("3585466367","HU"),
"3585466368" => array("3585474559","EG"),
"3585474560" => array("3585482751","DE"),
"3585482752" => array("3585490943","FR"),
"3585490944" => array("3585499135","IT"),
"3585499136" => array("3585515519","DE"),
"3585515520" => array("3585523711","RU"),
"3585523712" => array("3585531903","LV"),
"3585531904" => array("3585540095","AT"),
"3585540096" => array("3585548287","DE"),
"3585548288" => array("3585556479","RU"),
"3585556480" => array("3585564671","DE"),
"3585564672" => array("3585572863","RU"),
"3585572864" => array("3585581055","IT"),
"3585581056" => array("3585597439","DE"),
"3585597440" => array("3585605631","RU"),
"3585605632" => array("3585613823","PL"),
"3585613824" => array("3585622015","EE"),
"3585622016" => array("3585630207","RU"),
"3585630208" => array("3585638399","RS"),
"3585638400" => array("3585646591","RU"),
"3585646592" => array("3585654783","SA"),
"3585654784" => array("3585662975","NO"),
"3585662976" => array("3585671167","BY"),
"3585671168" => array("3585679359","SE"),
"3585679360" => array("3585687551","FI"),
"3585687552" => array("3585695743","DE"),
"3585695744" => array("3585703935","GB"),
"3585703936" => array("3585712127","DE"),
"3585712128" => array("3585720319","AT"),
"3585720320" => array("3585728511","GB"),
"3585728512" => array("3585736703","SE"),
"3585736704" => array("3585744895","HR"),
"3585744896" => array("3585753087","FR"),
"3585753088" => array("3585761279","PL"),
"3585761280" => array("3585769471","UA"),
"3585769472" => array("3585777663","TR"),
"3585777664" => array("3585785855","JO"),
"3585785856" => array("3585794047","UA"),
"3585794048" => array("3585802239","FI"),
"3585802240" => array("3585810431","IT"),
"3585810432" => array("3585818623","GB"),
"3585818624" => array("3585826815","DE"),
"3585826816" => array("3585835007","RU"),
"3585835008" => array("3585843199","US"),
"3585843200" => array("3585851391","NO"),
"3585851392" => array("3585859583","SE"),
"3585859584" => array("3585867775","DE"),
"3585867776" => array("3585875967","NO"),
"3585875968" => array("3585884159","CH"),
"3585884160" => array("3585892351","IQ"),
"3585892352" => array("3585900543","DE"),
"3585900544" => array("3585908735","NO"),
"3585908736" => array("3585916927","FR"),
"3585916928" => array("3585925119","IT"),
"3585925120" => array("3585933311","CH"),
"3585933312" => array("3585941503","NL"),
"3585941504" => array("3585949695","PL"),
"3585949696" => array("3585957887","KW"),
"3585957888" => array("3585966079","SE"),
"3585966080" => array("3585974271","CH"),
"3585974272" => array("3585982463","BE"),
"3585982464" => array("3585998847","RU"),
"3585998848" => array("3586007039","ES"),
"3586007040" => array("3586015231","LT"),
"3586015232" => array("3586023423","FR"),
"3586023424" => array("3586031615","IS"),
"3586031616" => array("3586039807","IE"),
"3586039808" => array("3586047999","GB"),
"3586048000" => array("3586056191","PT"),
"3586056192" => array("3586072575","RU"),
"3586072576" => array("3586088959","DE"),
"3586088960" => array("3586097151","CZ"),
"3586097152" => array("3586105343","HR"),
"3586113536" => array("3586121727","BG"),
"3586121728" => array("3586129919","IE"),
"3586129920" => array("3586146303","CZ"),
"3586146304" => array("3586162687","PL"),
"3586162688" => array("3586179071","FI"),
"3586179072" => array("3586195455","ES"),
"3586195456" => array("3586203647","RU"),
"3586203648" => array("3586211839","ZA"),
"3586211840" => array("3586228223","CH"),
"3586228224" => array("3586244607","BE"),
"3586244608" => array("3586260991","NL"),
"3586260992" => array("3586277375","ES"),
"3586277376" => array("3586293759","TR"),
"3586293760" => array("3586310143","ES"),
"3586310144" => array("3586326527","CZ"),
"3586326528" => array("3586342911","IR"),
"3586342912" => array("3586359295","ES"),
"3586359296" => array("3586375679","PL"),
"3586375680" => array("3586392063","CZ"),
"3586392064" => array("3586408447","NL"),
"3586408448" => array("3586424831","BA"),
"3586424832" => array("3586441215","CH"),
"3586441216" => array("3586457599","DE"),
"3586457600" => array("3586473983","NL"),
"3586473984" => array("3586490367","HU"),
"3586490368" => array("3586506751","LT"),
"3586506752" => array("3586523135","NL"),
"3586523136" => array("3586555903","DE"),
"3586555904" => array("3586572287","IT"),
"3586572288" => array("3586588671","RS"),
"3586588672" => array("3586596863","IT"),
"3586596864" => array("3586605055","GB"),
"3586605056" => array("3586621439","SE"),
"3586621440" => array("3586637823","GB"),
"3586637824" => array("3586654207","PL"),
"3586654208" => array("3586662399","GE"),
"3586662400" => array("3586670591","UA"),
"3586670592" => array("3586686975","IE"),
"3586686976" => array("3586703359","SE"),
"3586703360" => array("3586719743","CH"),
"3586719744" => array("3586752511","ES"),
"3586752512" => array("3586785279","NL"),
"3586785280" => array("3586793471","OM"),
"3586793472" => array("3586801663","CH"),
"3586801664" => array("3586818047","HR"),
"3586818048" => array("3586834431","IE"),
"3586834432" => array("3586850815","DE"),
"3586850816" => array("3586867199","NO"),
"3586867200" => array("3586883583","FR"),
"3586883584" => array("3586899967","IT"),
"3586899968" => array("3586916351","DE"),
"3586916352" => array("3586924543","IT"),
"3586924544" => array("3586932735","AX"),
"3586932736" => array("3586949119","LB"),
"3586949120" => array("3586965503","SE"),
"3586965504" => array("3586981887","NL"),
"3586981888" => array("3586998271","IT"),
"3586998272" => array("3587006463","PT"),
"3587006464" => array("3587014655","FR"),
"3587014656" => array("3587055615","GB"),
"3587055616" => array("3587063807","UZ"),
"3587063808" => array("3587080191","NL"),
"3587080192" => array("3587088383","GB"),
"3587088384" => array("3587096575","DE"),
"3587096576" => array("3587121151","NL"),
"3587121152" => array("3587129343","AL"),
"3587129344" => array("3587145727","NL"),
"3587145728" => array("3587162111","CY"),
"3587162112" => array("3587178495","IR"),
"3587178496" => array("3587186687","AT"),
"3587186688" => array("3587194879","DE"),
"3587194880" => array("3587211263","GB"),
"3587211264" => array("3587219455","AT"),
"3587219456" => array("3587227647","RU"),
"3587227648" => array("3587244031","GB"),
"3587244032" => array("3587260415","IT"),
"3587260416" => array("3587284991","DE"),
"3587284992" => array("3587309567","IT"),
"3587309568" => array("3587325951","GB"),
"3587325952" => array("3587342335","RU"),
"3587342336" => array("3587358719","CZ"),
"3587358720" => array("3587375103","SA"),
"3587375104" => array("3587383295","TR"),
"3587383296" => array("3587391487","CZ"),
"3587391488" => array("3587407871","KZ"),
"3587407872" => array("3587424255","BE"),
"3587424256" => array("3587440639","DE"),
"3587440640" => array("3587457023","SE"),
"3587457024" => array("3587473407","GB"),
"3587473408" => array("3587489791","IT"),
"3587489792" => array("3587506175","EG"),
"3587506176" => array("3587538943","IT"),
"3587538944" => array("3587547135","IS"),
"3587547136" => array("3587555327","CH"),
"3587555328" => array("3587571711","BE"),
"3587571712" => array("3587579903","DE"),
"3587579904" => array("3587588095","BE"),
"3587588096" => array("3587596287","BG"),
"3587596288" => array("3587604479","NL"),
"3587604480" => array("3587620863","FI"),
"3587620864" => array("3587637247","SE"),
"3587637248" => array("3587653631","FR"),
"3587653632" => array("3587670015","SK"),
"3587670016" => array("3587702783","IT"),
"3587702784" => array("3587710975","DE"),
"3587710976" => array("3587719167","CZ"),
"3587719168" => array("3587735551","PL"),
"3587735552" => array("3587751935","GB"),
"3587751936" => array("3587768319","FI"),
"3587768320" => array("3587776511","DE"),
"3587776512" => array("3587784703","IR"),
"3587784704" => array("3587801087","DE"),
"3587801088" => array("3587817471","IT"),
"3587817472" => array("3587833855","MT"),
"3587833856" => array("3587842047","DE"),
"3587842048" => array("3587850239","IT"),
"3587850240" => array("3587866623","PL"),
"3587866624" => array("3587874815","FR"),
"3587874816" => array("3587883007","DE"),
"3587883008" => array("3587915775","GB"),
"3587915776" => array("3587932159","EE"),
"3587932160" => array("3587948543","BE"),
"3587948544" => array("3587964927","RU"),
"3587964928" => array("3587981311","ES"),
"3587981312" => array("3587997695","IS"),
"3587997696" => array("3588014079","DE"),
"3588014080" => array("3588030463","CZ"),
"3588030464" => array("3588046847","RU"),
"3588046848" => array("3588063231","DE"),
"3588063232" => array("3588071423","CH"),
"3588071424" => array("3588079615","GB"),
"3588079616" => array("3588095999","CH"),
"3588096000" => array("3588104191","NL"),
"3588104192" => array("3588112383","BG"),
"3588112384" => array("3588128767","FR"),
"3588128768" => array("3588145151","HU"),
"3588145152" => array("3588153343","PL"),
"3588153344" => array("3588161535","RU"),
"3588161536" => array("3588227071","FR"),
"3588227072" => array("3588292607","BE"),
"3588292608" => array("3588308991","AT"),
"3588308992" => array("3588325375","NO"),
"3588325376" => array("3588333567","GB"),
"3588333568" => array("3588341759","FR"),
"3588341760" => array("3588358143","IT"),
"3588358144" => array("3588374527","BG"),
"3588374528" => array("3588390911","SE"),
"3588390912" => array("3588407295","LT"),
"3588407296" => array("3588423679","CZ"),
"3588423680" => array("3588440063","ES"),
"3588440064" => array("3588456447","PL"),
"3588456448" => array("3588464639","NL"),
"3588464640" => array("3588472831","AT"),
"3588472832" => array("3588489215","UA"),
"3588489216" => array("3588505599","FR"),
"3588505600" => array("3588521983","RU"),
"3588521984" => array("3588538367","PT"),
"3588538368" => array("3588554751","GB"),
"3588554752" => array("3588571135","AT"),
"3588571136" => array("3588587519","GB"),
"3588587520" => array("3588603903","ES"),
"3588603904" => array("3588620287","SI"),
"3588620288" => array("3588628479","SA"),
"3588628480" => array("3588636671","CH"),
"3588636672" => array("3588653055","UZ"),
"3588653056" => array("3588661247","IT"),
"3588661248" => array("3588669439","NO"),
"3588669440" => array("3588685823","GB"),
"3588685824" => array("3588702207","UA"),
"3588702208" => array("3588718591","ES"),
"3588718592" => array("3588734975","BG"),
"3588734976" => array("3588751359","PL"),
"3588751360" => array("3588767743","TR"),
"3588767744" => array("3588784127","GB"),
"3588784128" => array("3588800511","CH"),
"3588800512" => array("3588816895","RU"),
"3588816896" => array("3588833279","IT"),
"3588833280" => array("3588849663","RO"),
"3588849664" => array("3588857855","IE"),
"3588857856" => array("3588866047","IR"),
"3588866048" => array("3588882431","NL"),
"3588882432" => array("3588890623","RU"),
"3588890624" => array("3588898815","GB"),
"3588898816" => array("3588915199","NO"),
"3588915200" => array("3588931583","IT"),
"3588931584" => array("3588947967","RU"),
"3588947968" => array("3588964351","GB"),
"3588964352" => array("3588997119","CZ"),
"3588997120" => array("3589013503","AT"),
"3589013504" => array("3589021695","ES"),
"3589021696" => array("3589029887","SA"),
"3589029888" => array("3589046271","NL"),
"3589046272" => array("3589079039","NO"),
"3589079040" => array("3589128191","DK"),
"3589128192" => array("3589144575","GB"),
"3589144576" => array("3589152767","UA"),
"3589152768" => array("3589160959","DE"),
"3589160960" => array("3589177343","PL"),
"3589177344" => array("3589193727","TR"),
"3589193728" => array("3589210111","SE"),
"3589210112" => array("3589226495","NL"),
"3589226496" => array("3589242879","NO"),
"3589242880" => array("3589259263","NL"),
"3589259264" => array("3589275647","DE"),
"3589275648" => array("3589292031","RS"),
"3589292032" => array("3589308415","AT"),
"3589308416" => array("3589324799","DE"),
"3589324800" => array("3589341183","BG"),
"3589341184" => array("3589373951","PL"),
"3589373952" => array("3589390335","DE"),
"3589390336" => array("3589423103","RU"),
"3589423104" => array("3589439487","GB"),
"3589439488" => array("3589455871","SE"),
"3589455872" => array("3589472255","RU"),
"3589472256" => array("3589488639","TR"),
"3589488640" => array("3589505023","RU"),
"3589505024" => array("3589521407","FI"),
"3589521408" => array("3589537791","IT"),
"3589537792" => array("3589545983","FR"),
"3589545984" => array("3589554175","DE"),
"3589554176" => array("3589570559","PS"),
"3589570560" => array("3589586943","GB"),
"3589586944" => array("3589603327","RS"),
"3589603328" => array("3589668863","FR"),
"3589668864" => array("3589677055","RU"),
"3589677056" => array("3589685247","FR"),
"3589685248" => array("3589718015","GB"),
"3589718016" => array("3589734399","BE"),
"3589734400" => array("3589742591","EG"),
"3589742592" => array("3589767167","NL"),
"3589767168" => array("3589816319","RU"),
"3589816320" => array("3589832703","EU"),
"3589832704" => array("3589849087","TR"),
"3589849088" => array("3589865471","GB"),
"3589865472" => array("3589881855","GR"),
"3589881856" => array("3589890047","NL"),
"3589890048" => array("3589931007","GB"),
"3589931008" => array("3589947391","SI"),
"3589947392" => array("3589963775","FI"),
"3589963776" => array("3589980159","ES"),
"3589980160" => array("3589996543","CZ"),
"3589996544" => array("3590012927","GB"),
"3590012928" => array("3590029311","BE"),
"3590029312" => array("3590045695","FR"),
"3590045696" => array("3590062079","RU"),
"3590062080" => array("3590078463","DE"),
"3590078464" => array("3590094847","RU"),
"3590094848" => array("3590111231","DE"),
"3590111232" => array("3590127615","LT"),
"3590127616" => array("3590143999","GB"),
"3590144000" => array("3590160383","SI"),
"3590160384" => array("3590176767","GB"),
"3590176768" => array("3590193151","HU"),
"3590193152" => array("3590201343","IT"),
"3590201344" => array("3590209535","DE"),
"3590209536" => array("3590225919","ES"),
"3590225920" => array("3590234111","TR"),
"3590234112" => array("3590242303","GB"),
"3590242304" => array("3590258687","IE"),
"3590258688" => array("3590291455","IT"),
"3590291456" => array("3590299647","EG"),
"3590299648" => array("3590307839","FI"),
"3590307840" => array("3590324223","GB"),
);
?> | hodorogandrei/contesteasyplatform | admiasi/include/ip2country_files/213.php | PHP | gpl-2.0 | 38,880 |
def float_example():
a = -10
print a.__float__()
print float(a)
if __name__ == '__main__':
float_example() | ramesharpu/python | basic-coding/built-in-functions/float.py | Python | gpl-2.0 | 124 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2001 David R. Hampton
# Copyright (C) 2001-2006 Donald N. Allingham
# Copyright (C) 2007 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# 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.
#
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.utils.grampslocale import GrampsLocale
from gramps.gen.display.name import NameDisplay
from gramps.gen.config import config
#-------------------------------------------------------------------------
#
# Report
#
#-------------------------------------------------------------------------
class Report:
"""
The Report base class. This is a base class for generating
customized reports. It cannot be used as is, but it can be easily
sub-classed to create a functional report generator.
"""
def __init__(self, database, options_class, user):
self.database = database
self.options_class = options_class
self._user = user
self.doc = options_class.get_document()
creator = database.get_researcher().get_name()
self.doc.set_creator(creator)
output = options_class.get_output()
if output:
self.standalone = True
self.doc.open(options_class.get_output())
else:
self.standalone = False
def begin_report(self):
pass
def set_locale(self, language):
"""
Set the translator to one selected with
stdoptions.add_localization_option().
"""
if language == GrampsLocale.DEFAULT_TRANSLATION_STR:
language = None
locale = GrampsLocale(lang=language)
self._ = locale.translation.sgettext
self._get_date = locale.get_date
self._get_type = locale.get_type
self._ldd = locale.date_displayer
self._name_display = NameDisplay(locale) # a legacy/historical name
self._name_display.set_name_format(self.database.name_formats)
fmt_default = config.get('preferences.name-format')
self._name_display.set_default_format(fmt_default)
return locale
def write_report(self):
pass
def end_report(self):
if self.standalone:
self.doc.close()
| beernarrd/gramps | gramps/gen/plug/report/_reportbase.py | Python | gpl-2.0 | 3,048 |
<?php
// Search
// Wp Estate Pack
global $row_number_col;
get_header();
$options = wpestate_page_details('');
$unit_class = "col-md-6";
$row_number_col=6;
if($options['content_class'] == "col-md-12"){
$unit_class="col-md-4";
$row_number_col=4;
}
$row_number_col=4;
?>
<div class="row content-fixed">
<?php get_template_part('templates/breadcrumbs'); ?>
<div class=" col-md-12 ">
<div class="blog_list_wrapper row">
<?php
if (have_posts()){
print ' <h1 class="entry-title-search">'. esc_html__( 'Search Results for: ','wpestate');print '"' . get_search_query() . '"'.'</h1>';
while (have_posts()) : the_post();
get_template_part('templates/blog_unit');
endwhile;
}else{
?>
<h1 class="entry-title-search"><?php esc_html_e( 'We didn\'t find any results. Please try again with different search parameters. ', 'wpestate' ); ?></h1>
<form method="get" class="searchform" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="text" class="form-control search_res_form" name="s" id="s" value="<?php esc_attr (esc_html_e( 'Type Keyword', 'wpestate' )); ?>" />
<input type="submit" id="submit-form" class="wpb_btn-info wpb_regularsize wpestate_vc_button vc_button" value="<?php esc_attr ( esc_html_e( 'Search', 'wpestate') ); ?>">
</form>
<?php
}
wp_reset_query();
?>
</div>
<?php kriesi_pagination('', $range = 2); ?>
</div><!-- end 8col container-->
<?php // include(locate_template('sidebar.php')); ?>
</div>
<?php get_footer(); ?> | riddya85/rentail_upwrk | wp-content/themes/wprentals/search.php | PHP | gpl-2.0 | 1,879 |
from distutils.core import setup
setup(
name='tinyfsm',
version='0.1',
packages=[''],
url='https://github.com/tonyfunc/tinyfsm',
license='GNU Library',
author='tony',
author_email='me@tonyfunc.com',
description='A tiny implementation of Finite State Machine in Python.'
)
| tonyfunc/tinyfsm | setup.py | Python | gpl-2.0 | 305 |
package cn.guoyukun.demo.cts.dao;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.stereotype.Repository;
@Repository
public class DealerDao extends BaseDao{
private static final String _TABLE_NAME = "dealer";
private static final String _PK_NAME = "JXSDM";
@Override
protected String getTableName() {
return _TABLE_NAME;
}
@Override
protected String getPKName() {
return _PK_NAME;
}
public void add(Map <String,Object> info){
super.getJdbcTemplate().update("insert into dealer (" +
"JXSDM," +
"JXSMC," +
"SYB," +
"SHENG," +
"SHI," +
"QY," +
"SFTY" +
") values(?,?,?,?,?,?,?)",
info.get("JXSDM"),
info.get("JXSMC"),
info.get("SYB"),
info.get("SHENG"),
info.get("SHI"),
info.get("QY"),
info.get("SFTY")
);
}
public void edit(Map <String,Object> info){
super.getJdbcTemplate().update("update dealer set "+
"JXSMC=?,"+
"SYB=?,"+
"SHENG=?,"+
"SHI=?,"+
"QY=?,"+
"SFTY=?"+
" where JXSMC=?",
info.get("JXSMC"),
info.get("SYB"),
info.get("SHENG"),
info.get("SHI"),
info.get("QY"),
info.get("SFTY"),
info.get("JXSDM")
);
}
}
| gyk001/demo-cts | src/main/java/cn/guoyukun/demo/cts/dao/DealerDao.java | Java | gpl-2.0 | 1,189 |
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Falla extends Model{
protected $fillable = ['name', 'address', 'status'];
public function objections(){
return $this->hasMany('App\Models\Objection', 'id_falla');
}
public function fools(){
return $this->belongsToMany('App\Models\User', 'objections', 'id_falla', 'id_user');
}
} | victorarcasrios/fallas | app/Models/Falla.php | PHP | gpl-2.0 | 367 |
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""Water dynamics analysis --- :mod:`MDAnalysis.analysis.waterdynamics`
=======================================================================
:Author: Alejandro Bernardin
:Year: 2014-2015
:Copyright: GNU Public License v3
.. versionadded:: 0.11.0
This module provides functions to analize water dynamics trajectories and water
interactions with other molecules. The functions in this module are: water
orientational relaxation (WOR) [Yeh1999]_, hydrogen bond lifetimes (HBL)
[Rapaport1983]_, angular distribution (AD) [Grigera1995]_, mean square
displacement (MSD) [Brodka1994]_ and survival probability (SP) [Liu2004]_.
For more information about this type of analysis please refer to
[Araya-Secchi2014]_ (water in a protein cavity) and [Milischuk2011]_ (water in
a nanopore).
.. rubric:: References
.. [Rapaport1983] D.C. Rapaport (1983): Hydrogen bonds in water, Molecular
Physics: An International Journal at the Interface Between
Chemistry and Physics, 50:5, 1151-1162.
.. [Yeh1999] Yu-ling Yeh and Chung-Yuan Mou (1999). Orientational Relaxation
Dynamics of Liquid Water Studied by Molecular Dynamics Simulation,
J. Phys. Chem. B 1999, 103, 3699-3705.
.. [Grigera1995] Raul Grigera, Susana G. Kalko and Jorge Fischbarg
(1995). Wall-Water Interface. A Molecular Dynamics Study,
Langmuir 1996,12,154-158
.. [Liu2004] Pu Liu, Edward Harder, and B. J. Berne (2004).On the Calculation
of Diffusion Coefficients in Confined Fluids and Interfaces with
an Application to the Liquid-Vapor Interface of Water,
J. Phys. Chem. B 2004, 108, 6595-6602.
.. [Brodka1994] Aleksander Brodka (1994). Diffusion in restricted volume,
Molecular Physics, 1994, Vol. 82, No. 5, 1075-1078.
.. [Araya-Secchi2014] Araya-Secchi, R., Tomas Perez-Acle, Seung-gu Kang, Tien
Huynh, Alejandro Bernardin, Yerko Escalona, Jose-Antonio
Garate, Agustin D. Martinez, Isaac E. Garcia, Juan
C. Saez, Ruhong Zhou (2014). Characterization of a novel
water pocket inside the human Cx26 hemichannel
structure. Biophysical journal, 107(3), 599-612.
.. [Milischuk2011] Anatoli A. Milischuk and Branka M. Ladanyi. Structure and
dynamics of water confined in silica
nanopores. J. Chem. Phys. 135, 174709 (2011); doi:
10.1063/1.3657408
Example use of the analysis classes
-----------------------------------
HydrogenBondLifetimes
~~~~~~~~~~~~~~~~~~~~~
To analyse hydrogen bond lifetime, use
:meth:`MDAnalysis.analysis.hydrogenbonds.hbond_analysis.HydrogenBondAnalysis.liftetime`.
See Also
--------
:mod:`MDAnalysis.analysis.hydrogenbonds.hbond_analysis`
WaterOrientationalRelaxation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Analyzing water orientational relaxation (WOR)
:class:`WaterOrientationalRelaxation`. In this case we are analyzing "how fast"
water molecules are rotating/changing direction. If WOR is very stable we can
assume that water molecules are rotating/changing direction very slow, on the
other hand, if WOR decay very fast, we can assume that water molecules are
rotating/changing direction very fast::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import WaterOrientationalRelaxation as WOR
u = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and sphzone 6.0 protein and resid 42"
WOR_analysis = WOR(universe, select, 0, 1000, 20)
WOR_analysis.run()
time = 0
#now we print the data ready to plot. The first two columns are WOR_OH vs t plot,
#the second two columns are WOR_HH vs t graph and the third two columns are WOR_dip vs t graph
for WOR_OH, WOR_HH, WOR_dip in WOR_analysis.timeseries:
print("{time} {WOR_OH} {time} {WOR_HH} {time} {WOR_dip}".format(time=time, WOR_OH=WOR_OH, WOR_HH=WOR_HH,WOR_dip=WOR_dip))
time += 1
#now, if we want, we can plot our data
plt.figure(1,figsize=(18, 6))
#WOR OH
plt.subplot(131)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR OH')
plt.plot(range(0,time),[column[0] for column in WOR_analysis.timeseries])
#WOR HH
plt.subplot(132)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR HH')
plt.plot(range(0,time),[column[1] for column in WOR_analysis.timeseries])
#WOR dip
plt.subplot(133)
plt.xlabel('time')
plt.ylabel('WOR')
plt.title('WOR dip')
plt.plot(range(0,time),[column[2] for column in WOR_analysis.timeseries])
plt.show()
where t0 = 0, tf = 1000 and dtmax = 20. In this way we create 20 windows
timesteps (20 values in the x axis), the first window is created with 1000
timestep average (1000/1), the second window is created with 500 timestep
average(1000/2), the third window is created with 333 timestep average (1000/3)
and so on.
AngularDistribution
~~~~~~~~~~~~~~~~~~~
Analyzing angular distribution (AD) :class:`AngularDistribution` for OH vector,
HH vector and dipole vector. It returns a line histogram with vector
orientation preference. A straight line in the output plot means no
preferential orientation in water molecules. In this case we are analyzing if
water molecules have some orientational preference, in this way we can see if
water molecules are under an electric field or if they are interacting with
something (residue, protein, etc)::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import AngularDistribution as AD
u = MDAnalysis.Universe(pdb, trajectory)
selection = "byres name OH2 and sphzone 6.0 (protein and (resid 42 or resid 26) )"
bins = 30
AD_analysis = AD(universe,selection,bins)
AD_analysis.run()
#now we print data ready to graph. The first two columns are P(cos(theta)) vs cos(theta) for OH vector ,
#the seconds two columns are P(cos(theta)) vs cos(theta) for HH vector and thirds two columns
#are P(cos(theta)) vs cos(theta) for dipole vector
for bin in range(bins):
print("{AD_analysisOH} {AD_analysisHH} {AD_analysisDip}".format(AD_analysis.graph0=AD_analysis.graph[0][bin], AD_analysis.graph1=AD_analysis.graph[1][bin],AD_analysis.graph2=AD_analysis.graph[2][bin]))
#and if we want to graph our results
plt.figure(1,figsize=(18, 6))
#AD OH
plt.subplot(131)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for OH')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[0][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[0][:-1]])
#AD HH
plt.subplot(132)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for HH')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[1][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[1][:-1]])
#AD dip
plt.subplot(133)
plt.xlabel('cos theta')
plt.ylabel('P(cos theta)')
plt.title('PDF cos theta for dipole')
plt.plot([float(column.split()[0]) for column in AD_analysis.graph[2][:-1]],[float(column.split()[1]) for column in AD_analysis.graph[2][:-1]])
plt.show()
where `P(cos(theta))` is the angular distribution or angular probabilities.
MeanSquareDisplacement
~~~~~~~~~~~~~~~~~~~~~~
Analyzing mean square displacement (MSD) :class:`MeanSquareDisplacement` for
water molecules. In this case we are analyzing the average distance that water
molecules travels inside protein in XYZ direction (cylindric zone of radius
11[nm], Zmax 4.0[nm] and Zmin -8.0[nm]). A strong rise mean a fast movement of
water molecules, a weak rise mean slow movement of particles::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import MeanSquareDisplacement as MSD
u = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and cyzone 11.0 4.0 -8.0 protein"
MSD_analysis = MSD(universe, select, 0, 1000, 20)
MSD_analysis.run()
#now we print data ready to graph. The graph
#represents MSD vs t
time = 0
for msd in MSD_analysis.timeseries:
print("{time} {msd}".format(time=time, msd=msd))
time += 1
#Plot
plt.xlabel('time')
plt.ylabel('MSD')
plt.title('MSD')
plt.plot(range(0,time),MSD_analysis.timeseries)
plt.show()
.. _SP-examples:
SurvivalProbability
~~~~~~~~~~~~~~~~~~~
Analyzing survival probability (SP) :class:`SurvivalProbability` of molecules.
In this case we are analyzing how long water molecules remain in a
sphere of radius 12.3 centered in the geometrical center of resid 42 and 26.
A slow decay of SP means a long permanence time of water molecules in
the zone, on the other hand, a fast decay means a short permanence time::
import MDAnalysis
from MDAnalysis.analysis.waterdynamics import SurvivalProbability as SP
import matplotlib.pyplot as plt
universe = MDAnalysis.Universe(pdb, trajectory)
select = "byres name OH2 and sphzone 12.3 (resid 42 or resid 26) "
sp = SP(universe, select, verbose=True)
sp.run(start=0, stop=101, tau_max=20)
tau_timeseries = sp.tau_timeseries
sp_timeseries = sp.sp_timeseries
# print in console
for tau, sp in zip(tau_timeseries, sp_timeseries):
print("{time} {sp}".format(time=tau, sp=sp))
# plot
plt.xlabel('Time')
plt.ylabel('SP')
plt.title('Survival Probability')
plt.plot(tau_timeseries, sp_timeseries)
plt.show()
One should note that the `stop` keyword as used in the above example has an
`exclusive` behaviour, i.e. here the final frame used will be 100 not 101.
This behaviour is aligned with :class:`AnalysisBase` but currently differs from
other :mod:`MDAnalysis.analysis.waterdynamics` classes, which all exhibit
`inclusive` behaviour for their final frame selections.
Another example applies to the situation where you work with many different "residues".
Here we calculate the SP of a potassium ion around each lipid in a membrane and
average the results. In this example, if the SP analysis were run without treating each lipid
separately, potassium ions may hop from one lipid to another and still be counted as remaining
in the specified region. That is, the survival probability of the potassium ion around the
entire membrane will be calculated.
Note, for this example, it is advisable to use `Universe(in_memory=True)` to ensure that the
simulation is not being reloaded into memory for each lipid::
import MDAnalysis as mda
from MDAnalysis.analysis.waterdynamics import SurvivalProbability as SP
import numpy as np
u = mda.Universe("md.gro", "md100ns.xtc", in_memory=True)
lipids = u.select_atoms('resname LIPIDS')
joined_sp_timeseries = [[] for _ in range(20)]
for lipid in lipids.residues:
print("Lipid ID: %d" % lipid.resid)
select = "resname POTASSIUM and around 3.5 (resid %d and name O13 O14) " % lipid.resid
sp = SP(u, select, verbose=True)
sp.run(tau_max=20)
# Raw SP points for each tau:
for sps, new_sps in zip(joined_sp_timeseries, sp.sp_timeseries_data):
sps.extend(new_sps)
# average all SP datapoints
sp_data = [np.mean(sp) for sp in joined_sp_timeseries]
for tau, sp in zip(range(1, tau_max + 1), sp_data):
print("{time} {sp}".format(time=tau, sp=sp))
.. _Output:
Output
------
WaterOrientationalRelaxation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Water orientational relaxation (WOR) data is returned per window timestep,
which is stored in :attr:`WaterOrientationalRelaxation.timeseries`::
results = [
[ # time t0
<WOR_OH>, <WOR_HH>, <WOR_dip>
],
[ # time t1
<WOR_OH>, <WOR_HH>, <WOR_dip>
],
...
]
AngularDistribution
~~~~~~~~~~~~~~~~~~~
Angular distribution (AD) data is returned per vector, which is stored in
:attr:`AngularDistribution.graph`. In fact, AngularDistribution returns a
histogram::
results = [
[ # OH vector values
# the values are order in this way: <x_axis y_axis>
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
[ # HH vector values
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
[ # dip vector values
<cos_theta0 ang_distr0>, <cos_theta1 ang_distr1>, ...
],
]
MeanSquareDisplacement
~~~~~~~~~~~~~~~~~~~~~~
Mean Square Displacement (MSD) data is returned in a list, which each element
represents a MSD value in its respective window timestep. Data is stored in
:attr:`MeanSquareDisplacement.timeseries`::
results = [
#MSD values orders by window timestep
<MSD_t0>, <MSD_t1>, ...
]
SurvivalProbability
~~~~~~~~~~~~~~~~~~~
Survival Probability (SP) computes two lists: a list of taus (:attr:`SurvivalProbability.tau_timeseries`) and a list of
the corresponding survival probabilities (:attr:`SurvivalProbability.sp_timeseries`).
results = [ tau1, tau2, ..., tau_n ], [ sp_tau1, sp_tau2, ..., sp_tau_n]
Additionally, a list :attr:`SurvivalProbability.sp_timeseries_data`, is provided which contains
a list of all SPs calculated for each tau. This can be used to compute the distribution or time dependence of SP, etc.
Classes
--------
.. autoclass:: WaterOrientationalRelaxation
:members:
:inherited-members:
.. autoclass:: AngularDistribution
:members:
:inherited-members:
.. autoclass:: MeanSquareDisplacement
:members:
:inherited-members:
.. autoclass:: SurvivalProbability
:members:
:inherited-members:
"""
from MDAnalysis.lib.correlations import autocorrelation, correct_intermittency
import MDAnalysis.analysis.hbonds
from itertools import zip_longest
import logging
import warnings
import numpy as np
logger = logging.getLogger('MDAnalysis.analysis.waterdynamics')
from MDAnalysis.lib.log import ProgressBar
class WaterOrientationalRelaxation(object):
r"""Water orientation relaxation analysis
Function to evaluate the Water Orientational Relaxation proposed by Yu-ling
Yeh and Chung-Yuan Mou [Yeh1999_]. WaterOrientationalRelaxation indicates
"how fast" water molecules are rotating or changing direction. This is a
time correlation function given by:
.. math::
C_{\hat u}(\tau)=\langle \mathit{P}_2[\mathbf{\hat{u}}(t_0)\cdot\mathbf{\hat{u}}(t_0+\tau)]\rangle
where :math:`P_2=(3x^2-1)/2` is the second-order Legendre polynomial and :math:`\hat{u}` is
a unit vector along HH, OH or dipole vector.
Parameters
----------
universe : Universe
Universe object
selection : str
Selection string for water [‘byres name OH2’].
t0 : int
frame where analysis begins
tf : int
frame where analysis ends
dtmax : int
Maximum dt size, `dtmax` < `tf` or it will crash.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, t0, tf, dtmax, nproc=1):
self.universe = universe
self.selection = select
self.t0 = t0
self.tf = tf
self.dtmax = dtmax
self.nproc = nproc
self.timeseries = None
def _repeatedIndex(self, selection, dt, totalFrames):
"""
Indicates the comparation between all the t+dt.
The results is a list of list with all the repeated index per frame
(or time).
Ex: dt=1, so compare frames (1,2),(2,3),(3,4)...
Ex: dt=2, so compare frames (1,3),(3,5),(5,7)...
Ex: dt=3, so compare frames (1,4),(4,7),(7,10)...
"""
rep = []
for i in range(int(round((totalFrames - 1) / float(dt)))):
if (dt * i + dt < totalFrames):
rep.append(self._sameMolecTandDT(
selection, dt * i, (dt * i) + dt))
return rep
def _getOneDeltaPoint(self, universe, repInd, i, t0, dt):
"""
Gives one point to calculate the mean and gets one point of the plot
C_vect vs t.
Ex: t0=1 and tau=1 so calculate the t0-tau=1-2 intervale.
Ex: t0=5 and tau=3 so calcultate the t0-tau=5-8 intervale.
i = come from getMeanOnePoint (named j) (int)
"""
valOH = 0
valHH = 0
valdip = 0
n = 0
for j in range(len(repInd[i]) // 3):
begj = 3 * j
universe.trajectory[t0]
Ot0 = repInd[i][begj]
H1t0 = repInd[i][begj + 1]
H2t0 = repInd[i][begj + 2]
OHVector0 = H1t0.position - Ot0.position
HHVector0 = H1t0.position - H2t0.position
dipVector0 = ((H1t0.position + H2t0.position) * 0.5) - Ot0.position
universe.trajectory[t0 + dt]
Otp = repInd[i][begj]
H1tp = repInd[i][begj + 1]
H2tp = repInd[i][begj + 2]
OHVectorp = H1tp.position - Otp.position
HHVectorp = H1tp.position - H2tp.position
dipVectorp = ((H1tp.position + H2tp.position) * 0.5) - Otp.position
normOHVector0 = np.linalg.norm(OHVector0)
normOHVectorp = np.linalg.norm(OHVectorp)
normHHVector0 = np.linalg.norm(HHVector0)
normHHVectorp = np.linalg.norm(HHVectorp)
normdipVector0 = np.linalg.norm(dipVector0)
normdipVectorp = np.linalg.norm(dipVectorp)
unitOHVector0 = [OHVector0[0] / normOHVector0,
OHVector0[1] / normOHVector0,
OHVector0[2] / normOHVector0]
unitOHVectorp = [OHVectorp[0] / normOHVectorp,
OHVectorp[1] / normOHVectorp,
OHVectorp[2] / normOHVectorp]
unitHHVector0 = [HHVector0[0] / normHHVector0,
HHVector0[1] / normHHVector0,
HHVector0[2] / normHHVector0]
unitHHVectorp = [HHVectorp[0] / normHHVectorp,
HHVectorp[1] / normHHVectorp,
HHVectorp[2] / normHHVectorp]
unitdipVector0 = [dipVector0[0] / normdipVector0,
dipVector0[1] / normdipVector0,
dipVector0[2] / normdipVector0]
unitdipVectorp = [dipVectorp[0] / normdipVectorp,
dipVectorp[1] / normdipVectorp,
dipVectorp[2] / normdipVectorp]
valOH += self.lg2(np.dot(unitOHVector0, unitOHVectorp))
valHH += self.lg2(np.dot(unitHHVector0, unitHHVectorp))
valdip += self.lg2(np.dot(unitdipVector0, unitdipVectorp))
n += 1
return (valOH/n, valHH/n, valdip/n) if n > 0 else (0, 0, 0)
def _getMeanOnePoint(self, universe, selection1, selection_str, dt,
totalFrames):
"""
This function gets one point of the plot C_vec vs t. It uses the
_getOneDeltaPoint() function to calculate the average.
"""
repInd = self._repeatedIndex(selection1, dt, totalFrames)
sumsdt = 0
n = 0.0
sumDeltaOH = 0.0
sumDeltaHH = 0.0
sumDeltadip = 0.0
for j in range(totalFrames // dt - 1):
a = self._getOneDeltaPoint(universe, repInd, j, sumsdt, dt)
sumDeltaOH += a[0]
sumDeltaHH += a[1]
sumDeltadip += a[2]
sumsdt += dt
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return (sumDeltaOH / n, sumDeltaHH / n, sumDeltadip / n) if n > 0 else (0, 0, 0)
def _sameMolecTandDT(self, selection, t0d, tf):
"""
Compare the molecules in the t0d selection and the t0d+dt selection and
select only the particles that are repeated in both frame. This is to
consider only the molecules that remains in the selection after the dt
time has elapsed.
The result is a list with the indexs of the atoms.
"""
a = set(selection[t0d])
b = set(selection[tf])
sort = sorted(list(a.intersection(b)))
return sort
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
@staticmethod
def lg2(x):
"""Second Legendre polynomial"""
return (3*x*x - 1)/2
def run(self, **kwargs):
"""Analyze trajectory and produce timeseries"""
# All the selection to an array, this way is faster than selecting
# later.
if self.nproc == 1:
selection_out = self._selection_serial(
self.universe, self.selection)
else:
# selection_out = self._selection_parallel(self.universe,
# self.selection, self.nproc)
# parallel selection to be implemented
selection_out = self._selection_serial(
self.universe, self.selection)
self.timeseries = []
for dt in list(range(1, self.dtmax + 1)):
output = self._getMeanOnePoint(
self.universe, selection_out, self.selection, dt, self.tf)
self.timeseries.append(output)
class AngularDistribution(object):
r"""Angular distribution function analysis
The angular distribution function (AD) is defined as the distribution
probability of the cosine of the :math:`\theta` angle formed by the OH
vector, HH vector or dipolar vector of water molecules and a vector
:math:`\hat n` parallel to chosen axis (z is the default value). The cosine
is define as :math:`\cos \theta = \hat u \cdot \hat n`, where :math:`\hat
u` is OH, HH or dipole vector. It creates a histogram and returns a list
of lists, see Output_. The AD is also know as Angular Probability (AP).
Parameters
----------
universe : Universe
Universe object
select : str
Selection string to evaluate its angular distribution ['byres name OH2']
bins : int (optional)
Number of bins to create the histogram by means of :func:`numpy.histogram`
axis : {'x', 'y', 'z'} (optional)
Axis to create angle with the vector (HH, OH or dipole) and calculate
cosine theta ['z'].
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, bins=40, nproc=1, axis="z"):
self.universe = universe
self.selection_str = select
self.bins = bins
self.nproc = nproc
self.axis = axis
self.graph = None
def _getCosTheta(self, universe, selection, axis):
valOH = []
valHH = []
valdip = []
i = 0
while i <= (len(selection) - 1):
universe.trajectory[i]
line = selection[i].positions
Ot0 = line[::3]
H1t0 = line[1::3]
H2t0 = line[2::3]
OHVector0 = H1t0 - Ot0
HHVector0 = H1t0 - H2t0
dipVector0 = (H1t0 + H2t0) * 0.5 - Ot0
unitOHVector0 = OHVector0 / \
np.linalg.norm(OHVector0, axis=1)[:, None]
unitHHVector0 = HHVector0 / \
np.linalg.norm(HHVector0, axis=1)[:, None]
unitdipVector0 = dipVector0 / \
np.linalg.norm(dipVector0, axis=1)[:, None]
j = 0
while j < len(line) / 3:
if axis == "z":
valOH.append(unitOHVector0[j][2])
valHH.append(unitHHVector0[j][2])
valdip.append(unitdipVector0[j][2])
elif axis == "x":
valOH.append(unitOHVector0[j][0])
valHH.append(unitHHVector0[j][0])
valdip.append(unitdipVector0[j][0])
elif axis == "y":
valOH.append(unitOHVector0[j][1])
valHH.append(unitHHVector0[j][1])
valdip.append(unitdipVector0[j][1])
j += 1
i += 1
return (valOH, valHH, valdip)
def _getHistogram(self, universe, selection, bins, axis):
"""
This function gets a normalized histogram of the cos(theta) values. It
return a list of list.
"""
a = self._getCosTheta(universe, selection, axis)
cosThetaOH = a[0]
cosThetaHH = a[1]
cosThetadip = a[2]
lencosThetaOH = len(cosThetaOH)
lencosThetaHH = len(cosThetaHH)
lencosThetadip = len(cosThetadip)
histInterval = bins
histcosThetaOH = np.histogram(cosThetaOH, histInterval, density=True)
histcosThetaHH = np.histogram(cosThetaHH, histInterval, density=True)
histcosThetadip = np.histogram(cosThetadip, histInterval, density=True)
return (histcosThetaOH, histcosThetaHH, histcosThetadip)
def _hist2column(self, aList):
"""
This function transform from the histogram format
to a column format.
"""
a = []
for x in zip_longest(*aList, fillvalue="."):
a.append(" ".join(str(i) for i in x))
return a
def run(self, **kwargs):
"""Function to evaluate the angular distribution of cos(theta)"""
if self.nproc == 1:
selection = self._selection_serial(
self.universe, self.selection_str)
else:
# not implemented yet
# selection = self._selection_parallel(self.universe,
# self.selection_str,self.nproc)
selection = self._selection_serial(
self.universe, self.selection_str)
self.graph = []
output = self._getHistogram(
self.universe, selection, self.bins, self.axis)
# this is to format the exit of the file
# maybe this output could be improved
listOH = [list(output[0][1]), list(output[0][0])]
listHH = [list(output[1][1]), list(output[1][0])]
listdip = [list(output[2][1]), list(output[2][0])]
self.graph.append(self._hist2column(listOH))
self.graph.append(self._hist2column(listHH))
self.graph.append(self._hist2column(listdip))
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
class MeanSquareDisplacement(object):
r"""Mean square displacement analysis
Function to evaluate the Mean Square Displacement (MSD_). The MSD gives the
average distance that particles travels. The MSD is given by:
.. math::
\langle\Delta r(t)^2\rangle = 2nDt
where :math:`r(t)` is the position of particle in time :math:`t`,
:math:`\Delta r(t)` is the displacement after time lag :math:`t`,
:math:`n` is the dimensionality, in this case :math:`n=3`,
:math:`D` is the diffusion coefficient and :math:`t` is the time.
.. _MSD: http://en.wikipedia.org/wiki/Mean_squared_displacement
Parameters
----------
universe : Universe
Universe object
select : str
Selection string for water [‘byres name OH2’].
t0 : int
frame where analysis begins
tf : int
frame where analysis ends
dtmax : int
Maximum dt size, `dtmax` < `tf` or it will crash.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Changed `selection` keyword to `select`
"""
def __init__(self, universe, select, t0, tf, dtmax, nproc=1):
self.universe = universe
self.selection = select
self.t0 = t0
self.tf = tf
self.dtmax = dtmax
self.nproc = nproc
self.timeseries = None
def _repeatedIndex(self, selection, dt, totalFrames):
"""
Indicate the comparation between all the t+dt.
The results is a list of list with all the repeated index per frame
(or time).
- Ex: dt=1, so compare frames (1,2),(2,3),(3,4)...
- Ex: dt=2, so compare frames (1,3),(3,5),(5,7)...
- Ex: dt=3, so compare frames (1,4),(4,7),(7,10)...
"""
rep = []
for i in range(int(round((totalFrames - 1) / float(dt)))):
if (dt * i + dt < totalFrames):
rep.append(self._sameMolecTandDT(
selection, dt * i, (dt * i) + dt))
return rep
def _getOneDeltaPoint(self, universe, repInd, i, t0, dt):
"""
Gives one point to calculate the mean and gets one point of the plot
C_vect vs t.
- Ex: t0=1 and dt=1 so calculate the t0-dt=1-2 interval.
- Ex: t0=5 and dt=3 so calcultate the t0-dt=5-8 interva
i = come from getMeanOnePoint (named j) (int)
"""
valO = 0
n = 0
for j in range(len(repInd[i]) // 3):
begj = 3 * j
universe.trajectory[t0]
# Plus zero is to avoid 0to be equal to 0tp
Ot0 = repInd[i][begj].position + 0
universe.trajectory[t0 + dt]
# Plus zero is to avoid 0to be equal to 0tp
Otp = repInd[i][begj].position + 0
# position oxygen
OVector = Ot0 - Otp
# here it is the difference with
# waterdynamics.WaterOrientationalRelaxation
valO += np.dot(OVector, OVector)
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return valO/n if n > 0 else 0
def _getMeanOnePoint(self, universe, selection1, selection_str, dt,
totalFrames):
"""
This function gets one point of the plot C_vec vs t. It's uses the
_getOneDeltaPoint() function to calculate the average.
"""
repInd = self._repeatedIndex(selection1, dt, totalFrames)
sumsdt = 0
n = 0.0
sumDeltaO = 0.0
valOList = []
for j in range(totalFrames // dt - 1):
a = self._getOneDeltaPoint(universe, repInd, j, sumsdt, dt)
sumDeltaO += a
valOList.append(a)
sumsdt += dt
n += 1
# if no water molecules remain in selection, there is nothing to get
# the mean, so n = 0.
return sumDeltaO/n if n > 0 else 0
def _sameMolecTandDT(self, selection, t0d, tf):
"""
Compare the molecules in the t0d selection and the t0d+dt selection and
select only the particles that are repeated in both frame. This is to
consider only the molecules that remains in the selection after the dt
time has elapsed. The result is a list with the indexs of the atoms.
"""
a = set(selection[t0d])
b = set(selection[tf])
sort = sorted(list(a.intersection(b)))
return sort
def _selection_serial(self, universe, selection_str):
selection = []
for ts in ProgressBar(universe.trajectory, verbose=True,
total=universe.trajectory.n_frames):
selection.append(universe.select_atoms(selection_str))
return selection
def run(self, **kwargs):
"""Analyze trajectory and produce timeseries"""
# All the selection to an array, this way is faster than selecting
# later.
if self.nproc == 1:
selection_out = self._selection_serial(
self.universe, self.selection)
else:
# parallel not yet implemented
# selection = selection_parallel(universe, selection_str, nproc)
selection_out = self._selection_serial(
self.universe, self.selection)
self.timeseries = []
for dt in list(range(1, self.dtmax + 1)):
output = self._getMeanOnePoint(
self.universe, selection_out, self.selection, dt, self.tf)
self.timeseries.append(output)
class SurvivalProbability(object):
r"""
Survival Probability (SP) gives the probability for a group of particles to remain in a certain region.
The SP is given by:
.. math::
P(\tau) = \frac1T \sum_{t=1}^T \frac{N(t,t+\tau)}{N(t)}
where :math:`T` is the maximum time of simulation, :math:`\tau` is the
timestep, :math:`N(t)` the number of particles at time :math:`t`, and
:math:`N(t, t+\tau)` is the number of particles at every frame from :math:`t` to `\tau`.
Parameters
----------
universe : Universe
Universe object
select : str
Selection string; any selection is allowed. With this selection you
define the region/zone where to analyze, e.g.: "resname SOL and around 5 (resid 10)". See `SP-examples`_.
verbose : Boolean, optional
When True, prints progress and comments to the console.
Notes
-----
Currently :class:`SurvivalProbability` is the only on in
:mod:`MDAnalysis.analysis.waterdynamics` to support an `exclusive`
behaviour (i.e. similar to the current behaviour of :class:`AnalysisBase`
to the `stop` keyword passed to :meth:`SurvivalProbability.run`. Unlike
other :mod:`MDAnalysis.analysis.waterdynamics` final frame definitions
which are `inclusive`.
.. versionadded:: 0.11.0
.. versionchanged:: 1.0.0
Using the MDAnalysis.lib.correlations.py to carry out the intermittency
and autocorrelation calculations.
Changed `selection` keyword to `select`.
Removed support for the deprecated `t0`, `tf`, and `dtmax` keywords.
These should instead be passed to :meth:`SurvivalProbability.run` as
the `start`, `stop`, and `tau_max` keywords respectively.
The `stop` keyword as passed to :meth:`SurvivalProbability.run` has now
changed behaviour and will act in an `exclusive` manner (instead of it's
previous `inclusive` behaviour),
"""
def __init__(self, universe, select, verbose=False):
self.universe = universe
self.selection = select
self.verbose = verbose
def run(self, tau_max=20, start=None, stop=None, step=None, residues=False,
intermittency=0, verbose=False):
"""
Computes and returns the Survival Probability (SP) timeseries
Parameters
----------
start : int, optional
Zero-based index of the first frame to be analysed, Default: None
(first frame).
stop : int, optional
Zero-based index of the last frame to be analysed (exclusive),
Default: None (last frame).
step : int, optional
Jump every `step`-th frame. This is compatible but independant of
the taus used, and it is good to consider using the `step` equal
to `tau_max` to remove the overlap. Note that `step` and `tau_max`
work consistently with intermittency. Default: None
(use every frame).
tau_max : int, optional
Survival probability is calculated for the range
1 <= `tau` <= `tau_max`.
residues : Boolean, optional
If true, the analysis will be carried out on the residues
(.resids) rather than on atom (.ids). A single atom is sufficient
to classify the residue as within the distance.
intermittency : int, optional
The maximum number of consecutive frames for which an atom can
leave but be counted as present if it returns at the next frame.
An intermittency of `0` is equivalent to a continuous survival
probability, which does not allow for the leaving and returning of
atoms. For example, for `intermittency=2`, any given atom may leave
a region of interest for up to two consecutive frames yet be
treated as being present at all frames. The default is continuous
(0).
verbose : Boolean, optional
Print the progress to the console.
Returns
-------
tau_timeseries : list
tau from 1 to `tau_max`. Saved in the field tau_timeseries.
sp_timeseries : list
survival probability for each value of `tau`. Saved in the field
sp_timeseries.
sp_timeseries_data: list
raw datapoints from which the average is taken (sp_timeseries).
Time dependancy and distribution can be extracted.
.. versionchanged:: 1.0.0
To math other analysis methods, the `stop` keyword is now exclusive
rather than inclusive.
"""
start, stop, step = self.universe.trajectory.check_slice_indices(
start,
stop,
step
)
if tau_max > (stop - start):
raise ValueError("Too few frames selected for given tau_max.")
# preload the frames (atom IDs) to a list of sets
self._selected_ids = []
# fixme - to parallise: the section should be rewritten so that this loop only creates a list of indices,
# on which the parallel _single_frame can be applied.
# skip frames that will not be used in order to improve performance
# because AtomGroup.select_atoms is the most expensive part of this calculation
# Example: step 5 and tau 2: LLLSS LLLSS, ... where L = Load, and S = Skip
# Intermittency means that we have to load the extra frames to know if the atom is actually missing.
# Say step=5 and tau=1, intermittency=0: LLSSS LLSSS
# Say step=5 and tau=1, intermittency=1: LLLSL LLLSL
frame_loaded_counter = 0
# only for the first window (frames before t are not used)
frames_per_window = tau_max + 1 + intermittency
# This number will apply after the first windows was loaded
frames_per_window_subsequent = (tau_max + 1) + (2 * intermittency)
num_frames_to_skip = max(step - frames_per_window_subsequent, 0)
frame_no = start
while frame_no < stop: # we have already added 1 to stop, therefore <
if num_frames_to_skip != 0 and frame_loaded_counter == frames_per_window:
logger.info("Skipping the next %d frames:", num_frames_to_skip)
frame_no += num_frames_to_skip
frame_loaded_counter = 0
# Correct the number of frames to be loaded after the first window (which starts at t=0, and
# intermittency does not apply to the frames before)
frames_per_window = frames_per_window_subsequent
continue
# update the frame number
self.universe.trajectory[frame_no]
logger.info("Loading frame: %d", self.universe.trajectory.frame)
atoms = self.universe.select_atoms(self.selection)
# SP of residues or of atoms
ids = atoms.residues.resids if residues else atoms.ids
self._selected_ids.append(set(ids))
frame_no += 1
frame_loaded_counter += 1
# adjust for the frames that were not loaded (step>tau_max + 1),
# and for extra frames that were loaded (intermittency)
window_jump = step - num_frames_to_skip
self._intermittent_selected_ids = correct_intermittency(self._selected_ids, intermittency=intermittency)
tau_timeseries, sp_timeseries, sp_timeseries_data = autocorrelation(self._intermittent_selected_ids,
tau_max, window_jump)
# warn the user if the NaN are found
if all(np.isnan(sp_timeseries[1:])):
logger.warning('NaN Error: Most likely data was not found. Check your atom selections. ')
# user can investigate the distribution and sample size
self.sp_timeseries_data = sp_timeseries_data
self.tau_timeseries = tau_timeseries
self.sp_timeseries = sp_timeseries
return self
| MDAnalysis/mdanalysis | package/MDAnalysis/analysis/waterdynamics.py | Python | gpl-2.0 | 41,156 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var beerSchema = new Schema({
name: String,
categoryId: ObjectId,
description: String,
stars: Number,
categoryIdString: String
});
var Beer = mongoose.model('Beer', beerSchema);
module.exports = Beer;
| HomeTap/HomeTap | models/beer.js | JavaScript | gpl-2.0 | 318 |
// $Id: DeploymentDiagramRenderer.java 7783 2005-02-20 21:55:19Z linus $
// Copyright (c) 2003-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.diagram.deployment.ui;
import java.util.Collection;
import java.util.Map;
import org.apache.log4j.Logger;
import org.argouml.model.Model;
import org.argouml.uml.diagram.UmlDiagramRenderer;
import org.argouml.uml.diagram.static_structure.ui.CommentEdge;
import org.argouml.uml.diagram.static_structure.ui.FigClass;
import org.argouml.uml.diagram.static_structure.ui.FigComment;
import org.argouml.uml.diagram.static_structure.ui.FigEdgeNote;
import org.argouml.uml.diagram.static_structure.ui.FigInterface;
import org.argouml.uml.diagram.static_structure.ui.FigLink;
import org.argouml.uml.diagram.ui.FigAssociation;
import org.argouml.uml.diagram.ui.FigAssociationClass;
import org.argouml.uml.diagram.ui.FigAssociationEnd;
import org.argouml.uml.diagram.ui.FigDependency;
import org.argouml.uml.diagram.ui.FigGeneralization;
import org.argouml.uml.diagram.ui.FigNodeAssociation;
import org.tigris.gef.base.Layer;
import org.tigris.gef.graph.GraphModel;
import org.tigris.gef.presentation.FigEdge;
import org.tigris.gef.presentation.FigNode;
/**
* This class defines a renderer object for UML Deployment Diagrams.
*
*/
public class DeploymentDiagramRenderer extends UmlDiagramRenderer {
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(DeploymentDiagramRenderer.class);
/**
* Return a Fig that can be used to represent the given node.
*
* @see org.tigris.gef.graph.GraphNodeRenderer#getFigNodeFor(
* org.tigris.gef.graph.GraphModel, org.tigris.gef.base.Layer,
* java.lang.Object, java.util.Map)
*/
public FigNode getFigNodeFor(
GraphModel gm,
Layer lay,
Object node,
Map styleAttributes) {
if (Model.getFacade().isANode(node)) {
return new FigMNode(gm, node);
} else if (Model.getFacade().isAAssociation(node)) {
return new FigNodeAssociation(gm, node);
} else if (Model.getFacade().isANodeInstance(node)) {
return new FigMNodeInstance(gm, node);
} else if (Model.getFacade().isAComponent(node)) {
return new FigComponent(gm, node);
} else if (Model.getFacade().isAComponentInstance(node)) {
return new FigComponentInstance(gm, node);
} else if (Model.getFacade().isAClass(node)) {
return new FigClass(gm, node);
} else if (Model.getFacade().isAInterface(node)) {
return new FigInterface(gm, node);
} else if (Model.getFacade().isAObject(node)) {
return new FigObject(gm, node);
} else if (Model.getFacade().isAComment(node)) {
return new FigComment(gm, node);
}
LOG.debug("TODO: DeploymentDiagramRenderer getFigNodeFor");
return null;
}
/**
* Return a Fig that can be used to represent the given edge.
*
* @see org.tigris.gef.graph.GraphEdgeRenderer#getFigEdgeFor(
* org.tigris.gef.graph.GraphModel, org.tigris.gef.base.Layer,
* java.lang.Object, java.util.Map)
*/
public FigEdge getFigEdgeFor(
GraphModel gm,
Layer lay,
Object edge,
Map styleAttributes) {
if (Model.getFacade().isAAssociationClass(edge)) {
FigAssociationClass ascCFig = new FigAssociationClass(edge, lay);
return ascCFig;
} else if (Model.getFacade().isAAssociation(edge)) {
Object asc = /*(MAssociation)*/ edge;
FigAssociation ascFig = new FigAssociation(asc, lay);
return ascFig;
} else if (Model.getFacade().isAAssociationEnd(edge)) {
FigAssociationEnd asend = new FigAssociationEnd(edge, lay);
Model.getFacade().getAssociation(edge);
FigNode associationFN =
(FigNode) lay.presentationFor(Model
.getFacade().getAssociation(edge));
FigNode classifierFN =
(FigNode) lay.presentationFor(Model
.getFacade().getType(edge));
asend.setSourcePortFig(associationFN);
asend.setSourceFigNode(associationFN);
asend.setDestPortFig(classifierFN);
asend.setDestFigNode(classifierFN);
return asend;
}
if (Model.getFacade().isALink(edge)) {
Object lnk = /*(MLink)*/ edge;
FigLink lnkFig = new FigLink(lnk);
Collection linkEnds = Model.getFacade().getConnections(lnk);
if (linkEnds == null) {
LOG.debug("null linkRoles....");
}
Object[] leArray = linkEnds.toArray();
Object fromEnd = leArray[0];
Object fromInst = Model.getFacade().getInstance(fromEnd);
Object toEnd = leArray[1];
Object toInst = Model.getFacade().getInstance(toEnd);
FigNode fromFN = (FigNode) lay.presentationFor(fromInst);
FigNode toFN = (FigNode) lay.presentationFor(toInst);
lnkFig.setSourcePortFig(fromFN);
lnkFig.setSourceFigNode(fromFN);
lnkFig.setDestPortFig(toFN);
lnkFig.setDestFigNode(toFN);
return lnkFig;
}
if (Model.getFacade().isADependency(edge)) {
Object dep = /*(MDependency)*/ edge;
FigDependency depFig = new FigDependency(dep);
Object supplier =
((Model.getFacade().getSuppliers(dep).toArray())[0]);
Object client =
((Model.getFacade().getClients(dep).toArray())[0]);
FigNode supFN = (FigNode) lay.presentationFor(supplier);
FigNode cliFN = (FigNode) lay.presentationFor(client);
depFig.setSourcePortFig(cliFN);
depFig.setSourceFigNode(cliFN);
depFig.setDestPortFig(supFN);
depFig.setDestFigNode(supFN);
depFig.getFig().setDashed(true);
return depFig;
}
if (Model.getFacade().isAGeneralization(edge)) {
Object gen = /*(MGeneralization)*/ edge;
FigGeneralization genFig = new FigGeneralization(gen, lay);
return genFig;
}
if (edge instanceof CommentEdge) {
return new FigEdgeNote(edge, lay);
}
return null;
}
static final long serialVersionUID = 8002278834226522224L;
}
| carvalhomb/tsmells | sample/argouml/argouml/org/argouml/uml/diagram/deployment/ui/DeploymentDiagramRenderer.java | Java | gpl-2.0 | 7,999 |
#!/usr/bin/env python
# encoding: utf-8
import sys
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--m_number", dest = "m", help = "pleaer enter the m...", type = int)
parser.add_argument("-n", "--n_number", dest = "n", help = "pleaer enter the n...", type = int)
args = parser.parse_args()
print "%d ^ %d = %d" % (args.m, args.n, args.m ** args.n) | gatieme/AderXCoding | language/python/argparse/m-n3.py | Python | gpl-2.0 | 435 |
<?php
/**
* File containing the eZDiffEngine class.
*
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2012.5
* @package lib
*/
/*!
\class eZDiffEngine ezdiffengine.php
\abstract
\ingroup eZDiff
\brief eZDiff provides an access point the diff system
The eZDiffEngine class is an abstract class, providing interface and shared code
for the different available DiffEngine.
*/
class eZDiffEngine
{
/*!
This method must be overridden for each implementation of eZDiffEngine. This is the function
which created the object containing the detected changes in the data set.
*/
function createDifferenceObject( $fromData, $toData )
{
}
/// \privatesection
public $DiffMode;
}
?>
| pauletienney/siliconnexion | lib/ezdiff/classes/ezdiffengine.php | PHP | gpl-2.0 | 850 |
/*
* Kexi Report Plugin
* Copyright (C) 2007-2009 by Adam Pigg (adam@piggz.co.uk)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "kexisourceselector.h"
#include <kpushbutton.h>
#include <klineedit.h>
#include <QLabel>
#include <klocale.h>
#include <kdebug.h>
#include <QDomElement>
#include "KexiDataSourceComboBox.h"
#include <kexiproject.h>
//#define NO_EXTERNAL_SOURCES
#ifdef NO_EXTERNAL_SOURCES
#ifdef __GNUC__
#warning enable external data sources for 2.3
#else
#pragma WARNING( enable external data sources for 2.3 )
#endif
#endif
class KexiSourceSelector::Private
{
public:
Private()
: kexiDBData(0)
{
}
~Private()
{
delete kexiDBData;
#ifndef KEXI_MOBILE
delete kexiMigrateData;
#endif
}
KexiDB::Connection *conn;
QVBoxLayout *layout;
QComboBox *sourceType;
KexiDataSourceComboBox *internalSource;
KLineEdit *externalSource;
KPushButton *setData;
KexiDBReportData *kexiDBData;
#ifndef KEXI_MOBILE
KexiMigrateReportData *kexiMigrateData;
#endif
};
KexiSourceSelector::KexiSourceSelector(KexiProject* project, QWidget* parent)
: QWidget(parent)
, d(new Private)
{
d->conn = project->dbConnection();
d->kexiDBData = 0;
#ifndef KEXI_MOBILE
d->kexiMigrateData = 0;
#endif
d->layout = new QVBoxLayout(this);
d->sourceType = new QComboBox(this);
d->internalSource = new KexiDataSourceComboBox(this);
d->internalSource->setProject(project);
d->externalSource = new KLineEdit(this);
d->setData = new KPushButton(i18n("Set Data"));
connect(d->setData, SIGNAL(clicked()), this, SLOT(setDataClicked()));
d->sourceType->addItem(i18n("Internal"), QVariant("internal"));
d->sourceType->addItem(i18n("External"), QVariant("external"));
#ifndef NO_EXTERNAL_SOURCES
//!@TODO enable when adding external data
d->layout->addWidget(new QLabel(i18n("Source Type:"), this));
d->layout->addWidget(d->sourceType);
d->layout->addSpacing(10);
#else
d->sourceType->setVisible(false);
d->externalSource->setVisible(false);
#endif
d->layout->addWidget(new QLabel(i18n("Internal Source:"), this));
d->layout->addWidget(d->internalSource);
d->layout->addSpacing(10);
#ifndef NO_EXTERNAL_SOURCES
d->layout->addWidget(new QLabel(i18n("External Source:"), this));
d->layout->addWidget(d->externalSource);
#endif
d->layout->addSpacing(20);
d->layout->addWidget(d->setData);
d->layout->addStretch();
setLayout(d->layout);
}
KexiSourceSelector::~KexiSourceSelector()
{
delete d;
}
void KexiSourceSelector::setConnectionData(QDomElement c)
{
if (c.attribute("type") == "internal") {
d->sourceType->setCurrentIndex(d->sourceType->findData("internal"));
d->internalSource->setCurrentIndex(d->internalSource->findText(c.attribute("source")));
}
if (c.attribute("type") == "external") {
d->sourceType->setCurrentIndex(d->sourceType->findText("external"));
d->externalSource->setText(c.attribute("source"));
}
emit(setData(sourceData()));
}
QDomElement KexiSourceSelector::connectionData()
{
kDebug();
QDomDocument dd;
QDomElement conndata = dd.createElement("connection");
#ifndef NO_EXTERNAL_SOURCES
//!@TODO Make a better gui for selecting external data source
conndata.setAttribute("type", d->sourceType->itemData(d->sourceType->currentIndex()).toString());
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "internal") {
conndata.setAttribute("source", d->internalSource->currentText());
} else {
conndata.setAttribute("source", d->externalSource->text());
}
#else
conndata.setAttribute("type", "internal");
conndata.setAttribute("source", d->internalSource->currentText());
#endif
return conndata;
}
KoReportData* KexiSourceSelector::sourceData()
{
if (d->kexiDBData) {
delete d->kexiDBData;
d->kexiDBData = 0;
}
#ifndef KEXI_MOBILE
if (d->kexiMigrateData) {
delete d->kexiMigrateData;
d->kexiMigrateData = 0;
}
#endif
//!@TODO Fix when enable external data
#ifndef NO_EXTERNAL_SOURCES
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "internal" && d->internalSource->isSelectionValid()) {
d->kexiDBData = new KexiDBReportData(d->internalSource->selectedName(), d->internalSource->selectedPartClass(), d->conn);
return d->kexiDBData;
}
#ifndef KEXI_MOBILE
if (d->sourceType->itemData(d->sourceType->currentIndex()).toString() == "external") {
d->kexiMigrateData = new KexiMigrateReportData(d->externalSource->text());
return d->kexiMigrateData;
}
#endif
#else
if (d->internalSource->isSelectionValid()) {
d->kexiDBData = new KexiDBReportData(d->internalSource->selectedName(), d->conn);
return d->kexiDBData;
}
#endif
return 0;
}
void KexiSourceSelector::setDataClicked()
{
emit(setData(sourceData()));
}
| donniexyz/calligra | kexi/plugins/reports/kexisourceselector.cpp | C++ | gpl-2.0 | 5,620 |
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source 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 for more details.
You should have received a copy of the GNU General Public License
along with Quake III Arena source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "vm_local.h"
#include <stdint.h>
#define PAD(base, alignment) (((base)+(alignment)-1) & ~((alignment)-1))
#define PADLEN(base, alignment) (PAD((base), (alignment)) - (base))
#define PADP(base, alignment) ((void *) PAD((intptr_t) (base), (alignment)))
#define ARRAY_LEN(x) (sizeof(x) / sizeof(*(x)))
//#define DEBUG_VM
#ifdef DEBUG_VM
static char *opnames[256] = {
"OP_UNDEF",
"OP_IGNORE",
"OP_BREAK",
"OP_ENTER",
"OP_LEAVE",
"OP_CALL",
"OP_PUSH",
"OP_POP",
"OP_CONST",
"OP_LOCAL",
"OP_JUMP",
//-------------------
"OP_EQ",
"OP_NE",
"OP_LTI",
"OP_LEI",
"OP_GTI",
"OP_GEI",
"OP_LTU",
"OP_LEU",
"OP_GTU",
"OP_GEU",
"OP_EQF",
"OP_NEF",
"OP_LTF",
"OP_LEF",
"OP_GTF",
"OP_GEF",
//-------------------
"OP_LOAD1",
"OP_LOAD2",
"OP_LOAD4",
"OP_STORE1",
"OP_STORE2",
"OP_STORE4",
"OP_ARG",
"OP_BLOCK_COPY",
//-------------------
"OP_SEX8",
"OP_SEX16",
"OP_NEGI",
"OP_ADD",
"OP_SUB",
"OP_DIVI",
"OP_DIVU",
"OP_MODI",
"OP_MODU",
"OP_MULI",
"OP_MULU",
"OP_BAND",
"OP_BOR",
"OP_BXOR",
"OP_BCOM",
"OP_LSH",
"OP_RSHI",
"OP_RSHU",
"OP_NEGF",
"OP_ADDF",
"OP_SUBF",
"OP_DIVF",
"OP_MULF",
"OP_CVIF",
"OP_CVFI"
};
#endif
#if idppc
//FIXME: these, um... look the same to me
#if defined(__GNUC__)
static ID_INLINE unsigned int loadWord(void *addr) {
unsigned int word;
asm("lwbrx %0,0,%1" : "=r" (word) : "r" (addr));
return word;
}
#else
static ID_INLINE unsigned int __lwbrx(register void *addr,
register int offset) {
register unsigned int word;
asm("lwbrx %0,%2,%1" : "=r" (word) : "r" (addr), "b" (offset));
return word;
}
#define loadWord(addr) __lwbrx(addr,0)
#endif
#else
static ID_INLINE int loadWord(void *addr) {
int word;
memcpy(&word, addr, 4);
return LittleLong(word);
}
#endif
char *VM_Indent( vm_t *vm ) {
static char *string = " ";
if ( vm->callLevel > 20 ) {
return string;
}
return string + 2 * ( 20 - vm->callLevel );
}
void VM_StackTrace( vm_t *vm, int programCounter, int programStack ) {
int count;
count = 0;
do {
Com_Printf( "%s\n", VM_ValueToSymbol( vm, programCounter ) );
programStack = *(int *)&vm->dataBase[programStack+4];
programCounter = *(int *)&vm->dataBase[programStack];
} while ( programCounter != -1 && ++count < 32 );
}
/*
====================
VM_PrepareInterpreter
====================
*/
void VM_PrepareInterpreter( vm_t *vm, vmHeader_t *header ) {
int op;
int byte_pc;
int int_pc;
byte *code;
int instruction;
int *codeBase;
vm->codeBase = (byte *)Hunk_Alloc( vm->codeLength*4, h_high ); // we're now int aligned
// memcpy( vm->codeBase, (byte *)header + header->codeOffset, vm->codeLength );
// we don't need to translate the instructions, but we still need
// to find each instructions starting point for jumps
int_pc = byte_pc = 0;
instruction = 0;
code = (byte *)header + header->codeOffset;
codeBase = (int *)vm->codeBase;
// Copy and expand instructions to words while building instruction table
while ( instruction < header->instructionCount ) {
vm->instructionPointers[ instruction ] = int_pc;
instruction++;
op = (int)code[ byte_pc ];
codeBase[int_pc] = op;
if(byte_pc > header->codeLength)
Com_Error(ERR_DROP, "VM_PrepareInterpreter: pc > header->codeLength");
byte_pc++;
int_pc++;
// these are the only opcodes that aren't a single byte
switch ( op ) {
case OP_ENTER:
case OP_CONST:
case OP_LOCAL:
case OP_LEAVE:
case OP_EQ:
case OP_NE:
case OP_LTI:
case OP_LEI:
case OP_GTI:
case OP_GEI:
case OP_LTU:
case OP_LEU:
case OP_GTU:
case OP_GEU:
case OP_EQF:
case OP_NEF:
case OP_LTF:
case OP_LEF:
case OP_GTF:
case OP_GEF:
case OP_BLOCK_COPY:
codeBase[int_pc] = loadWord(&code[byte_pc]);
byte_pc += 4;
int_pc++;
break;
case OP_ARG:
codeBase[int_pc] = (int)code[byte_pc];
byte_pc++;
int_pc++;
break;
default:
break;
}
}
int_pc = 0;
instruction = 0;
// Now that the code has been expanded to int-sized opcodes, we'll translate instruction index
//into an index into codeBase[], which contains opcodes and operands.
while ( instruction < header->instructionCount ) {
op = codeBase[ int_pc ];
instruction++;
int_pc++;
switch ( op ) {
// These ops need to translate addresses in jumps from instruction index to int index
case OP_EQ:
case OP_NE:
case OP_LTI:
case OP_LEI:
case OP_GTI:
case OP_GEI:
case OP_LTU:
case OP_LEU:
case OP_GTU:
case OP_GEU:
case OP_EQF:
case OP_NEF:
case OP_LTF:
case OP_LEF:
case OP_GTF:
case OP_GEF:
if(codeBase[int_pc] < 0 || codeBase[int_pc] > vm->instructionCount)
Com_Error(ERR_DROP, "VM_PrepareInterpreter: Jump to invalid instruction number");
// codeBase[pc] is the instruction index. Convert that into an offset into
//the int-aligned codeBase[] by the lookup table.
codeBase[int_pc] = vm->instructionPointers[codeBase[int_pc]];
int_pc++;
break;
// These opcodes have an operand that isn't an instruction index
case OP_ENTER:
case OP_CONST:
case OP_LOCAL:
case OP_LEAVE:
case OP_BLOCK_COPY:
case OP_ARG:
int_pc++;
break;
default:
break;
}
}
}
/*
==============
VM_Call
Upon a system call, the stack will look like:
sp+32 parm1
sp+28 parm0
sp+24 return stack
sp+20 return address
sp+16 local1
sp+14 local0
sp+12 arg1
sp+8 arg0
sp+4 return stack
sp return address
An interpreted function will immediately execute
an OP_ENTER instruction, which will subtract space for
locals from sp
==============
*/
#define DEBUGSTR va("%s%i", VM_Indent(vm), opStackOfs)
int VM_CallInterpreted( vm_t *vm, int *args ) {
byte stack[OPSTACK_SIZE + 15];
int *opStack;
uint8_t opStackOfs;
int programCounter;
int programStack;
int stackOnEntry;
byte *image;
int *codeImage;
int v1;
int dataMask;
int arg;
#ifdef DEBUG_VM
vmSymbol_t *profileSymbol;
#endif
// interpret the code
vm->currentlyInterpreting = qtrue;
// we might be called recursively, so this might not be the very top
programStack = stackOnEntry = vm->programStack;
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, 0 );
// uncomment this for debugging breakpoints
vm->breakFunction = 0;
#endif
// set up the stack frame
image = vm->dataBase;
codeImage = (int *)vm->codeBase;
dataMask = vm->dataMask;
programCounter = 0;
programStack -= ( 8 + 4 * MAX_VMMAIN_ARGS );
for ( arg = 0; arg < MAX_VMMAIN_ARGS; arg++ )
*(int *)&image[ programStack + 8 + arg * 4 ] = args[ arg ];
*(int *)&image[ programStack + 4 ] = 0; // return stack
*(int *)&image[ programStack ] = -1; // will terminate the loop on return
VM_Debug(0);
// leave a free spot at start of stack so
// that as long as opStack is valid, opStack-1 will
// not corrupt anything
opStack = (int *)PADP(stack, 16);
*opStack = 0xDEADBEEF;
opStackOfs = 0;
// vm_debugLevel=2;
// main interpreter loop, will exit when a LEAVE instruction
// grabs the -1 program counter
#define r2 codeImage[programCounter]
while ( 1 ) {
int opcode, r0, r1;
// unsigned int r2;
nextInstruction:
r0 = opStack[opStackOfs];
r1 = opStack[(uint8_t) (opStackOfs - 1)];
nextInstruction2:
#ifdef DEBUG_VM
if ( (unsigned)programCounter >= vm->codeLength ) {
Com_Error( ERR_DROP, "VM pc out of range" );
return 0;
}
if ( programStack <= vm->stackBottom ) {
Com_Error( ERR_DROP, "VM stack overflow" );
return 0;
}
if ( programStack & 3 ) {
Com_Error( ERR_DROP, "VM program stack misaligned" );
return 0;
}
if ( vm_debugLevel > 1 ) {
Com_Printf( "%s %s\n", DEBUGSTR, opnames[opcode] );
}
profileSymbol->profileCount++;
#endif
opcode = codeImage[ programCounter++ ];
switch ( opcode ) {
#ifdef DEBUG_VM
default:
Com_Error( ERR_DROP, "Bad VM instruction" ); // this should be scanned on load!
return 0;
#endif
case OP_BREAK:
vm->breakCount++;
goto nextInstruction2;
case OP_CONST:
opStackOfs++;
r1 = r0;
r0 = opStack[opStackOfs] = r2;
programCounter += 1;
goto nextInstruction2;
case OP_LOCAL:
opStackOfs++;
r1 = r0;
r0 = opStack[opStackOfs] = r2+programStack;
programCounter += 1;
goto nextInstruction2;
case OP_LOAD4:
#ifdef DEBUG_VM
if(opStack[opStackOfs] & 3)
{
Com_Error( ERR_DROP, "OP_LOAD4 misaligned" );
return 0;
}
#endif
r0 = opStack[opStackOfs] = *(int *) &image[r0 & dataMask & ~3 ];
goto nextInstruction2;
case OP_LOAD2:
r0 = opStack[opStackOfs] = *(unsigned short *)&image[ r0&dataMask&~1 ];
goto nextInstruction2;
case OP_LOAD1:
r0 = opStack[opStackOfs] = image[ r0&dataMask ];
goto nextInstruction2;
case OP_STORE4:
*(int *)&image[ r1&(dataMask & ~3) ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_STORE2:
*(short *)&image[ r1&(dataMask & ~1) ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_STORE1:
image[ r1&dataMask ] = r0;
opStackOfs -= 2;
goto nextInstruction;
case OP_ARG:
// single byte offset from programStack
*(int *)&image[ (codeImage[programCounter] + programStack)&dataMask&~3 ] = r0;
opStackOfs--;
programCounter += 1;
goto nextInstruction;
case OP_BLOCK_COPY:
VM_BlockCopy(r1, r0, r2);
programCounter += 1;
opStackOfs -= 2;
goto nextInstruction;
case OP_CALL:
// save current program counter
*(int *)&image[ programStack ] = programCounter;
// jump to the location on the stack
programCounter = r0;
opStackOfs--;
if ( programCounter < 0 ) {
// system call
int r;
// int temp;
#ifdef DEBUG_VM
int stomped;
if ( vm_debugLevel ) {
Com_Printf( "%s---> systemcall(%i)\n", DEBUGSTR, -1 - programCounter );
}
#endif
// save the stack to allow recursive VM entry
// temp = vm->callLevel;
vm->programStack = programStack - 4;
#ifdef DEBUG_VM
stomped = *(int *)&image[ programStack + 4 ];
#endif
*(int *)&image[ programStack + 4 ] = -1 - programCounter;
//VM_LogSyscalls( (int *)&image[ programStack + 4 ] );
{
// the vm has ints on the stack, we expect
// pointers so we might have to convert it
if (sizeof(intptr_t) != sizeof(int)) {
intptr_t argarr[ MAX_VMSYSCALL_ARGS ];
int *imagePtr = (int *)&image[ programStack ];
int i;
for (i = 0; i < ARRAY_LEN(argarr); ++i) {
argarr[i] = *(++imagePtr);
}
r = vm->systemCall( argarr );
} else {
intptr_t* argptr = (intptr_t *)&image[ programStack + 4 ];
r = vm->systemCall( argptr );
}
}
#ifdef DEBUG_VM
// this is just our stack frame pointer, only needed
// for debugging
*(int *)&image[ programStack + 4 ] = stomped;
#endif
// save return value
opStackOfs++;
opStack[opStackOfs] = r;
programCounter = *(int *)&image[ programStack ];
// vm->callLevel = temp;
#ifdef DEBUG_VM
if ( vm_debugLevel ) {
Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
}
#endif
} else if ( (unsigned)programCounter >= vm->instructionCount ) {
Com_Error( ERR_DROP, "VM program counter out of range in OP_CALL" );
return 0;
} else {
programCounter = vm->instructionPointers[ programCounter ];
}
goto nextInstruction;
// push and pop are only needed for discarded or bad function return values
case OP_PUSH:
opStackOfs++;
goto nextInstruction;
case OP_POP:
opStackOfs--;
goto nextInstruction;
case OP_ENTER:
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
#endif
// get size of stack frame
v1 = r2;
programCounter += 1;
programStack -= v1;
#ifdef DEBUG_VM
// save old stack frame for debugging traces
*(int *)&image[programStack+4] = programStack + v1;
if ( vm_debugLevel ) {
Com_Printf( "%s---> %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter - 5 ) );
if ( vm->breakFunction && programCounter - 5 == vm->breakFunction ) {
// this is to allow setting breakpoints here in the debugger
vm->breakCount++;
// vm_debugLevel = 2;
// VM_StackTrace( vm, programCounter, programStack );
}
// vm->callLevel++;
}
#endif
goto nextInstruction;
case OP_LEAVE:
// remove our stack frame
v1 = r2;
programStack += v1;
// grab the saved program counter
programCounter = *(int *)&image[ programStack ];
#ifdef DEBUG_VM
profileSymbol = VM_ValueToFunctionSymbol( vm, programCounter );
if ( vm_debugLevel ) {
// vm->callLevel--;
Com_Printf( "%s<--- %s\n", DEBUGSTR, VM_ValueToSymbol( vm, programCounter ) );
}
#endif
// check for leaving the VM
if ( programCounter == -1 ) {
goto done;
} else if ( (unsigned)programCounter >= vm->codeLength ) {
Com_Error( ERR_DROP, "VM program counter out of range in OP_LEAVE" );
return 0;
}
goto nextInstruction;
/*
===================================================================
BRANCHES
===================================================================
*/
case OP_JUMP:
if ( (unsigned)r0 >= vm->instructionCount )
{
Com_Error( ERR_DROP, "VM program counter out of range in OP_JUMP" );
return 0;
}
programCounter = vm->instructionPointers[ r0 ];
opStackOfs--;
goto nextInstruction;
case OP_EQ:
opStackOfs -= 2;
if ( r1 == r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_NE:
opStackOfs -= 2;
if ( r1 != r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTI:
opStackOfs -= 2;
if ( r1 < r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEI:
opStackOfs -= 2;
if ( r1 <= r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTI:
opStackOfs -= 2;
if ( r1 > r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEI:
opStackOfs -= 2;
if ( r1 >= r0 ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTU:
opStackOfs -= 2;
if ( ((unsigned)r1) < ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEU:
opStackOfs -= 2;
if ( ((unsigned)r1) <= ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTU:
opStackOfs -= 2;
if ( ((unsigned)r1) > ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEU:
opStackOfs -= 2;
if ( ((unsigned)r1) >= ((unsigned)r0) ) {
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_EQF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] == ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_NEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] != ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LTF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] < ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_LEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 1))] <= ((float *) opStack)[(uint8_t) ((uint8_t) (opStackOfs + 2))])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GTF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] > ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
case OP_GEF:
opStackOfs -= 2;
if(((float *) opStack)[(uint8_t) (opStackOfs + 1)] >= ((float *) opStack)[(uint8_t) (opStackOfs + 2)])
{
programCounter = r2; //vm->instructionPointers[r2];
goto nextInstruction;
} else {
programCounter += 1;
goto nextInstruction;
}
//===================================================================
case OP_NEGI:
opStack[opStackOfs] = -r0;
goto nextInstruction;
case OP_ADD:
opStackOfs--;
opStack[opStackOfs] = r1 + r0;
goto nextInstruction;
case OP_SUB:
opStackOfs--;
opStack[opStackOfs] = r1 - r0;
goto nextInstruction;
case OP_DIVI:
opStackOfs--;
opStack[opStackOfs] = r1 / r0;
goto nextInstruction;
case OP_DIVU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) / ((unsigned) r0);
goto nextInstruction;
case OP_MODI:
opStackOfs--;
opStack[opStackOfs] = r1 % r0;
goto nextInstruction;
case OP_MODU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) % ((unsigned) r0);
goto nextInstruction;
case OP_MULI:
opStackOfs--;
opStack[opStackOfs] = r1 * r0;
goto nextInstruction;
case OP_MULU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) * ((unsigned) r0);
goto nextInstruction;
case OP_BAND:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) & ((unsigned) r0);
goto nextInstruction;
case OP_BOR:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) | ((unsigned) r0);
goto nextInstruction;
case OP_BXOR:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) ^ ((unsigned) r0);
goto nextInstruction;
case OP_BCOM:
opStack[opStackOfs] = ~((unsigned) r0);
goto nextInstruction;
case OP_LSH:
opStackOfs--;
opStack[opStackOfs] = r1 << r0;
goto nextInstruction;
case OP_RSHI:
opStackOfs--;
opStack[opStackOfs] = r1 >> r0;
goto nextInstruction;
case OP_RSHU:
opStackOfs--;
opStack[opStackOfs] = ((unsigned) r1) >> r0;
goto nextInstruction;
case OP_NEGF:
((float *) opStack)[opStackOfs] = -((float *) opStack)[opStackOfs];
goto nextInstruction;
case OP_ADDF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] + ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_SUBF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] - ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_DIVF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] / ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_MULF:
opStackOfs--;
((float *) opStack)[opStackOfs] = ((float *) opStack)[opStackOfs] * ((float *) opStack)[(uint8_t) (opStackOfs + 1)];
goto nextInstruction;
case OP_CVIF:
((float *) opStack)[opStackOfs] = (float) opStack[opStackOfs];
goto nextInstruction;
case OP_CVFI:
opStack[opStackOfs] = Q_ftol(((float *) opStack)[opStackOfs]);
goto nextInstruction;
case OP_SEX8:
opStack[opStackOfs] = (signed char) opStack[opStackOfs];
goto nextInstruction;
case OP_SEX16:
opStack[opStackOfs] = (short) opStack[opStackOfs];
goto nextInstruction;
}
}
done:
vm->currentlyInterpreting = qfalse;
if (opStackOfs != 1 || *opStack != 0xDEADBEEF)
Com_Error(ERR_DROP, "Interpreter error: opStack[0] = %X, opStackOfs = %d", opStack[0], opStackOfs);
vm->programStack = stackOnEntry;
// return the result
return opStack[opStackOfs];
}
| ensiform/jk2mv | src/qcommon/vm_interpreted.cpp | C++ | gpl-2.0 | 21,435 |
<?php
if ( ! class_exists( 'Redux_Validation_not_empty' ) ) {
class Redux_Validation_not_empty {
/**
* Field Constructor.
* Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
*
* @since ReduxFramework 1.0.0
*/
function __construct( $parent, $field, $value, $current ) {
$this->parent = $parent;
$this->field = $field;
$this->field['msg'] = ( isset( $this->field['msg'] ) ) ? $this->field['msg'] : __( 'This field cannot be empty. Please provide a value.', 'helpme' );
$this->value = $value;
$this->current = $current;
$this->validate();
} //function
/**
* Field Render Function.
* Takes the vars and outputs the HTML for the field in the settings
*
* @since ReduxFramework 1.0.0
*/
function validate() {
if ( ! isset( $this->value ) || empty( $this->value ) ) {
$this->value = ( isset( $this->current ) ) ? $this->current : '';
$this->error = $this->field;
}
} //function
} //class
} | wanmendoza/fundecan | wp-content/themes/helpme/includes/framework/ReduxCore/inc/validation/not_empty/validation_not_empty.php | PHP | gpl-2.0 | 1,384 |
package iptat.util;
public interface Observer {
public void update(int state);
}
| AlexandruGhergut/IPTAT | src/iptat/util/Observer.java | Java | gpl-2.0 | 83 |
/*
* Copyright (C) 2008-2018 TrinityCore <https://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/>.
*/
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "Battleground.h"
#include "BattlegroundPackets.h"
#include "CellImpl.h"
#include "CreatureTextMgr.h"
#include "DB2Stores.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "Group.h"
#include "GroupMgr.h"
#include "Log.h"
#include "Map.h"
#include "MapManager.h"
#include "MiscPackets.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "WorldSession.h"
#include "WorldStatePackets.h"
#include <G3D/g3dmath.h>
Battlefield::Battlefield()
{
_scriptType = ZONE_SCRIPT_TYPE_BATTLEFIELD;
m_Timer = 0;
m_IsEnabled = true;
m_isActive = false;
m_DefenderTeam = TEAM_NEUTRAL;
m_TypeId = 0;
m_BattleId = 0;
m_ZoneId = 0;
m_Map = nullptr;
m_MapId = 0;
m_MaxPlayer = 0;
m_MinPlayer = 0;
m_MinLevel = 0;
m_BattleTime = 0;
m_NoWarBattleTime = 0;
m_RestartAfterCrash = 0;
m_TimeForAcceptInvite = 20;
m_uiKickDontAcceptTimer = 1000;
m_uiKickAfkPlayersTimer = 1000;
m_LastResurrectTimer = 30 * IN_MILLISECONDS;
m_StartGroupingTimer = 0;
m_StartGrouping = false;
}
Battlefield::~Battlefield()
{
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
delete itr->second;
for (GraveyardVect::const_iterator itr = m_GraveyardList.begin(); itr != m_GraveyardList.end(); ++itr)
delete *itr;
}
// Called when a player enters the zone
void Battlefield::HandlePlayerEnterZone(Player* player, Area* /*zone*/)
{
// If battle is started,
// If not full of players > invite player to join the war
// If full of players > announce to player that BF is full and kick him after a few second if he desn't leave
if (IsWarTime())
{
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer) // Vacant spaces
InvitePlayerToWar(player);
else // No more vacant places
{
/// @todo Send a packet to announce it to player
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
InvitePlayerToQueue(player);
}
}
else
{
// If time left is < 15 minutes invite player to join queue
if (m_Timer <= m_StartGroupingTimer)
InvitePlayerToQueue(player);
}
// Add player in the list of player in zone
m_players[player->GetTeamId()].insert(player->GetGUID());
OnPlayerEnterZone(player);
}
// Called when a player leave the zone
void Battlefield::HandlePlayerLeaveZone(Player* player, Area* /*zone*/)
{
if (IsWarTime())
{
// If the player is participating to the battle
if (m_PlayersInWar[player->GetTeamId()].find(player->GetGUID()) != m_PlayersInWar[player->GetTeamId()].end())
{
m_PlayersInWar[player->GetTeamId()].erase(player->GetGUID());
player->GetSession()->SendBfLeaveMessage(GetQueueId(), GetState(), player->GetZoneId() == GetZoneId());
if (Group* group = player->GetGroup()) // Remove the player from the raid group
group->RemoveMember(player->GetGUID());
OnPlayerLeaveWar(player);
}
}
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
itr->second->HandlePlayerLeave(player);
m_InvitedPlayers[player->GetTeamId()].erase(player->GetGUID());
m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID());
m_players[player->GetTeamId()].erase(player->GetGUID());
SendRemoveWorldStates(player);
RemovePlayerFromResurrectQueue(player->GetGUID());
OnPlayerLeaveZone(player);
}
bool Battlefield::Update(uint32 diff)
{
if (m_Timer <= diff)
{
// Battlefield ends on time
if (IsWarTime())
EndBattle(true);
else // Time to start a new battle!
StartBattle();
}
else
m_Timer -= diff;
// Invite players a few minutes before the battle's beginning
if (!IsWarTime() && !m_StartGrouping && m_Timer <= m_StartGroupingTimer)
{
m_StartGrouping = true;
InvitePlayersInZoneToQueue();
OnStartGrouping();
}
bool objective_changed = false;
if (IsWarTime())
{
if (m_uiKickAfkPlayersTimer <= diff)
{
m_uiKickAfkPlayersTimer = 1000;
KickAfkPlayers();
}
else
m_uiKickAfkPlayersTimer -= diff;
// Kick players who chose not to accept invitation to the battle
if (m_uiKickDontAcceptTimer <= diff)
{
time_t now = time(nullptr);
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (PlayerTimerMap::iterator itr = m_InvitedPlayers[team].begin(); itr != m_InvitedPlayers[team].end(); ++itr)
if (itr->second <= now)
KickPlayerFromBattlefield(itr->first);
InvitePlayersInZoneToWar();
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (PlayerTimerMap::iterator itr = m_PlayersWillBeKick[team].begin(); itr != m_PlayersWillBeKick[team].end(); ++itr)
if (itr->second <= now)
KickPlayerFromBattlefield(itr->first);
m_uiKickDontAcceptTimer = 1000;
}
else
m_uiKickDontAcceptTimer -= diff;
for (BfCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr)
if (itr->second->Update(diff))
objective_changed = true;
}
if (m_LastResurrectTimer <= diff)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
if (GetGraveyardById(i))
m_GraveyardList[i]->Resurrect();
m_LastResurrectTimer = RESURRECTION_INTERVAL;
}
else
m_LastResurrectTimer -= diff;
return objective_changed;
}
void Battlefield::InvitePlayersInZoneToQueue()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
InvitePlayerToQueue(player);
}
void Battlefield::InvitePlayerToQueue(Player* player)
{
if (m_PlayersInQueue[player->GetTeamId()].count(player->GetGUID()))
return;
if (m_PlayersInQueue[player->GetTeamId()].size() <= m_MinPlayer || m_PlayersInQueue[GetOtherTeam(player->GetTeamId())].size() >= m_MinPlayer)
player->GetSession()->SendBfInvitePlayerToQueue(GetQueueId(), GetState());
}
void Battlefield::InvitePlayersInQueueToWar()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (auto itr = m_PlayersInQueue[team].begin(); itr != m_PlayersInQueue[team].end(); ++itr)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer)
InvitePlayerToWar(player);
else
{
//Full
}
}
}
m_PlayersInQueue[team].clear();
}
}
void Battlefield::InvitePlayersInZoneToWar()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (m_PlayersInWar[player->GetTeamId()].count(player->GetGUID()) || m_InvitedPlayers[player->GetTeamId()].count(player->GetGUID()))
continue;
if (m_PlayersInWar[player->GetTeamId()].size() + m_InvitedPlayers[player->GetTeamId()].size() < m_MaxPlayer)
InvitePlayerToWar(player);
else // Battlefield is full of players
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
}
}
}
}
uint64 Battlefield::GetQueueId() const
{
return MAKE_PAIR64(m_BattleId | 0x20000, 0x1F100000);
}
void Battlefield::InvitePlayerToWar(Player* player)
{
if (!player)
return;
/// @todo needed ?
if (player->IsInFlight())
return;
if (player->InArena() || player->GetBattleground())
{
m_PlayersInQueue[player->GetTeamId()].erase(player->GetGUID());
return;
}
// If the player does not match minimal level requirements for the battlefield, kick him
if (player->getLevel() < m_MinLevel)
{
if (m_PlayersWillBeKick[player->GetTeamId()].count(player->GetGUID()) == 0)
m_PlayersWillBeKick[player->GetTeamId()][player->GetGUID()] = time(nullptr) + 10;
return;
}
// Check if player is not already in war
if (m_PlayersInWar[player->GetTeamId()].count(player->GetGUID()) || m_InvitedPlayers[player->GetTeamId()].count(player->GetGUID()))
return;
m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID());
m_InvitedPlayers[player->GetTeamId()][player->GetGUID()] = time(nullptr) + m_TimeForAcceptInvite;
player->GetSession()->SendBfInvitePlayerToWar(GetQueueId(), m_ZoneId, m_TimeForAcceptInvite);
}
void Battlefield::InitStalker(uint32 entry, Position const& pos)
{
if (Creature* creature = SpawnCreature(entry, pos))
StalkerGuid = creature->GetGUID();
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::InitStalker: Could not spawn Stalker (Creature entry %u), zone messages will be unavailable!", entry);
}
void Battlefield::KickAfkPlayers()
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
if (player->isAFK())
KickPlayerFromBattlefield(*itr);
}
void Battlefield::KickPlayerFromBattlefield(ObjectGuid guid)
{
if (Player* player = ObjectAccessor::FindPlayer(guid))
if (player->GetZoneId() == GetZoneId())
player->TeleportTo(KickPosition);
}
void Battlefield::StartBattle()
{
if (m_isActive)
return;
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
m_PlayersInWar[team].clear();
m_Groups[team].clear();
}
m_Timer = m_BattleTime;
m_isActive = true;
InvitePlayersInZoneToWar();
InvitePlayersInQueueToWar();
OnBattleStart();
}
void Battlefield::EndBattle(bool endByTimer)
{
if (!m_isActive)
return;
m_isActive = false;
m_StartGrouping = false;
if (!endByTimer)
SetDefenderTeam(GetAttackerTeam());
OnBattleEnd(endByTimer);
// Reset battlefield timer
m_Timer = m_NoWarBattleTime;
SendInitWorldStatesToAll();
}
void Battlefield::DoPlaySoundToAll(uint32 soundID)
{
BroadcastPacketToWar(WorldPackets::Misc::PlaySound(ObjectGuid::Empty, soundID).Write());
}
bool Battlefield::HasPlayer(Player* player) const
{
return m_players[player->GetTeamId()].find(player->GetGUID()) != m_players[player->GetTeamId()].end();
}
// Called in WorldSession::HandleBfQueueInviteResponse
void Battlefield::PlayerAcceptInviteToQueue(Player* player)
{
// Add player in queue
m_PlayersInQueue[player->GetTeamId()].insert(player->GetGUID());
// Send notification
player->GetSession()->SendBfQueueInviteResponse(GetQueueId(), m_ZoneId, GetState());
}
// Called in WorldSession::HandleBfExitRequest
void Battlefield::AskToLeaveQueue(Player* player)
{
// Remove player from queue
m_PlayersInQueue[player->GetTeamId()].erase(player->GetGUID());
}
// Called in WorldSession::HandleHearthAndResurrect
void Battlefield::PlayerAskToLeave(Player* player)
{
// Player leaving Wintergrasp, teleport to Dalaran.
// ToDo: confirm teleport destination.
player->TeleportTo(571, 5804.1499f, 624.7710f, 647.7670f, 1.6400f);
}
// Called in WorldSession::HandleBfEntryInviteResponse
void Battlefield::PlayerAcceptInviteToWar(Player* player)
{
if (!IsWarTime())
return;
if (AddOrSetPlayerToCorrectBfGroup(player))
{
player->GetSession()->SendBfEntered(GetQueueId(), player->GetZoneId() != GetZoneId(), player->GetTeamId() == GetAttackerTeam());
m_PlayersInWar[player->GetTeamId()].insert(player->GetGUID());
m_InvitedPlayers[player->GetTeamId()].erase(player->GetGUID());
if (player->isAFK())
player->ToggleAFK();
OnPlayerJoinWar(player); //for scripting
}
}
void Battlefield::TeamCastSpell(TeamId team, int32 spellId)
{
if (spellId > 0)
{
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->CastSpell(player, uint32(spellId), true);
}
else
{
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->RemoveAuraFromStack(uint32(-spellId));
}
}
void Battlefield::BroadcastPacketToZone(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_players[team].begin(); itr != m_players[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::BroadcastPacketToQueue(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInQueue[team].begin(); itr != m_PlayersInQueue[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindConnectedPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::BroadcastPacketToWar(WorldPacket const* data) const
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (auto itr = m_PlayersInWar[team].begin(); itr != m_PlayersInWar[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendDirectMessage(data);
}
void Battlefield::SendWarning(uint8 id, WorldObject const* target /*= nullptr*/)
{
if (Creature* stalker = GetCreature(StalkerGuid))
sCreatureTextMgr->SendChat(stalker, id, target);
}
void Battlefield::SendUpdateWorldState(uint32 variable, uint32 value, bool hidden /*= false*/)
{
WorldPackets::WorldState::UpdateWorldState worldstate;
worldstate.VariableID = variable;
worldstate.Value = value;
worldstate.Hidden = hidden;
BroadcastPacketToZone(worldstate.Write());
}
void Battlefield::AddCapturePoint(BfCapturePoint* cp)
{
Battlefield::BfCapturePointMap::iterator i = m_capturePoints.find(cp->GetCapturePointEntry());
if (i != m_capturePoints.end())
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::AddCapturePoint: CapturePoint %u already exists!", cp->GetCapturePointEntry());
delete i->second;
}
m_capturePoints[cp->GetCapturePointEntry()] = cp;
}
BfCapturePoint* Battlefield::GetCapturePoint(uint32 entry) const
{
Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(entry);
if (itr != m_capturePoints.end())
return itr->second;
return nullptr;
}
void Battlefield::RegisterZone(uint32 zoneId)
{
sBattlefieldMgr->AddZone(zoneId, this);
}
void Battlefield::HideNpc(Creature* creature)
{
creature->CombatStop();
creature->SetReactState(REACT_PASSIVE);
creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
creature->DisappearAndDie();
creature->SetVisible(false);
}
void Battlefield::ShowNpc(Creature* creature, bool aggressive)
{
creature->SetVisible(true);
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
if (!creature->IsAlive())
creature->Respawn(true);
if (aggressive)
creature->SetReactState(REACT_AGGRESSIVE);
else
{
creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
creature->SetReactState(REACT_PASSIVE);
}
}
// ****************************************************
// ******************* Group System *******************
// ****************************************************
Group* Battlefield::GetFreeBfRaid(TeamId TeamId)
{
for (auto itr = m_Groups[TeamId].begin(); itr != m_Groups[TeamId].end(); ++itr)
if (Group* group = sGroupMgr->GetGroupByGUID(*itr))
if (!group->IsFull())
return group;
return nullptr;
}
Group* Battlefield::GetGroupPlayer(ObjectGuid guid, TeamId TeamId)
{
for (auto itr = m_Groups[TeamId].begin(); itr != m_Groups[TeamId].end(); ++itr)
if (Group* group = sGroupMgr->GetGroupByGUID(*itr))
if (group->IsMember(guid))
return group;
return nullptr;
}
bool Battlefield::AddOrSetPlayerToCorrectBfGroup(Player* player)
{
if (!player->IsInWorld())
return false;
if (Group* group = player->GetGroup())
group->RemoveMember(player->GetGUID());
Group* group = GetFreeBfRaid(player->GetTeamId());
if (!group)
{
group = new Group;
group->SetBattlefieldGroup(this);
group->Create(player);
sGroupMgr->AddGroup(group);
m_Groups[player->GetTeamId()].insert(group->GetGUID());
}
else if (group->IsMember(player->GetGUID()))
{
uint8 subgroup = group->GetMemberGroup(player->GetGUID());
player->SetBattlegroundOrBattlefieldRaid(group, subgroup);
}
else
group->AddMember(player);
return true;
}
//***************End of Group System*******************
//*****************************************************
//***************Spirit Guide System*******************
//*****************************************************
//--------------------
//-Battlefield Method-
//--------------------
BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const
{
if (id < m_GraveyardList.size())
{
if (BfGraveyard* graveyard = m_GraveyardList.at(id))
return graveyard;
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u does not exist.", id);
}
else
TC_LOG_ERROR("bg.battlefield", "Battlefield::GetGraveyardById Id:%u could not be found.", id);
return nullptr;
}
WorldSafeLocsEntry const* Battlefield::GetClosestGraveYard(Player* player)
{
BfGraveyard* closestGY = nullptr;
float maxdist = -1;
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (m_GraveyardList[i])
{
if (m_GraveyardList[i]->GetControlTeamId() != player->GetTeamId())
continue;
float dist = m_GraveyardList[i]->GetDistance(player);
if (dist < maxdist || maxdist < 0)
{
closestGY = m_GraveyardList[i];
maxdist = dist;
}
}
}
if (closestGY)
return sWorldSafeLocsStore.LookupEntry(closestGY->GetGraveyardId());
return nullptr;
}
void Battlefield::AddPlayerToResurrectQueue(ObjectGuid npcGuid, ObjectGuid playerGuid)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (!m_GraveyardList[i])
continue;
if (m_GraveyardList[i]->HasNpc(npcGuid))
{
m_GraveyardList[i]->AddPlayer(playerGuid);
break;
}
}
}
void Battlefield::RemovePlayerFromResurrectQueue(ObjectGuid playerGuid)
{
for (uint8 i = 0; i < m_GraveyardList.size(); i++)
{
if (!m_GraveyardList[i])
continue;
if (m_GraveyardList[i]->HasPlayer(playerGuid))
{
m_GraveyardList[i]->RemovePlayer(playerGuid);
break;
}
}
}
void Battlefield::SendAreaSpiritHealerQueryOpcode(Player* player, ObjectGuid const& guid)
{
WorldPackets::Battleground::AreaSpiritHealerTime areaSpiritHealerTime;
areaSpiritHealerTime.HealerGuid = guid;
areaSpiritHealerTime.TimeLeft = m_LastResurrectTimer;
player->SendDirectMessage(areaSpiritHealerTime.Write());
}
// ----------------------
// - BfGraveyard Method -
// ----------------------
BfGraveyard::BfGraveyard(Battlefield* battlefield)
{
m_Bf = battlefield;
m_GraveyardId = 0;
m_ControlTeam = TEAM_NEUTRAL;
}
void BfGraveyard::Initialize(TeamId startControl, uint32 graveyardId)
{
m_ControlTeam = startControl;
m_GraveyardId = graveyardId;
}
void BfGraveyard::SetSpirit(Creature* spirit, TeamId team)
{
if (!spirit)
{
TC_LOG_ERROR("bg.battlefield", "BfGraveyard::SetSpirit: Invalid Spirit.");
return;
}
m_SpiritGuide[team] = spirit->GetGUID();
spirit->SetReactState(REACT_PASSIVE);
}
float BfGraveyard::GetDistance(Player* player)
{
WorldSafeLocsEntry const* safeLoc = sWorldSafeLocsStore.LookupEntry(m_GraveyardId);
return player->GetDistance2d(safeLoc->Loc.X, safeLoc->Loc.Y);
}
void BfGraveyard::AddPlayer(ObjectGuid playerGuid)
{
if (!m_ResurrectQueue.count(playerGuid))
{
m_ResurrectQueue.insert(playerGuid);
if (Player* player = ObjectAccessor::FindPlayer(playerGuid))
player->CastSpell(player, SPELL_WAITING_FOR_RESURRECT, true);
}
}
void BfGraveyard::RemovePlayer(ObjectGuid playerGuid)
{
m_ResurrectQueue.erase(m_ResurrectQueue.find(playerGuid));
if (Player* player = ObjectAccessor::FindPlayer(playerGuid))
player->RemoveAurasDueToSpell(SPELL_WAITING_FOR_RESURRECT);
}
void BfGraveyard::Resurrect()
{
if (m_ResurrectQueue.empty())
return;
for (GuidSet::const_iterator itr = m_ResurrectQueue.begin(); itr != m_ResurrectQueue.end(); ++itr)
{
// Get player object from his guid
Player* player = ObjectAccessor::FindPlayer(*itr);
if (!player)
continue;
// Check if the player is in world and on the good graveyard
if (player->IsInWorld())
if (Creature* spirit = m_Bf->GetCreature(m_SpiritGuide[m_ControlTeam]))
spirit->CastSpell(spirit, SPELL_SPIRIT_HEAL, true);
// Resurrect player
player->CastSpell(player, SPELL_RESURRECTION_VISUAL, true);
player->ResurrectPlayer(1.0f);
player->CastSpell(player, 6962, true);
player->CastSpell(player, SPELL_SPIRIT_HEAL_MANA, true);
player->SpawnCorpseBones(false);
}
m_ResurrectQueue.clear();
}
// For changing graveyard control
void BfGraveyard::GiveControlTo(TeamId team)
{
// Guide switching
// Note: Visiblity changes are made by phasing
/*if (m_SpiritGuide[1 - team])
m_SpiritGuide[1 - team]->SetVisible(false);
if (m_SpiritGuide[team])
m_SpiritGuide[team]->SetVisible(true);*/
m_ControlTeam = team;
// Teleport to other graveyard, player witch were on this graveyard
RelocateDeadPlayers();
}
void BfGraveyard::RelocateDeadPlayers()
{
WorldSafeLocsEntry const* closestGrave = nullptr;
for (GuidSet::const_iterator itr = m_ResurrectQueue.begin(); itr != m_ResurrectQueue.end(); ++itr)
{
Player* player = ObjectAccessor::FindPlayer(*itr);
if (!player)
continue;
if (closestGrave)
player->TeleportTo(player->GetMapId(), closestGrave->Loc.X, closestGrave->Loc.Y, closestGrave->Loc.Z, player->GetOrientation());
else
{
closestGrave = m_Bf->GetClosestGraveYard(player);
if (closestGrave)
player->TeleportTo(player->GetMapId(), closestGrave->Loc.X, closestGrave->Loc.Y, closestGrave->Loc.Z, player->GetOrientation());
}
}
}
bool BfGraveyard::HasNpc(ObjectGuid guid)
{
if (!m_SpiritGuide[TEAM_ALLIANCE] || !m_SpiritGuide[TEAM_HORDE])
return false;
if (!m_Bf->GetCreature(m_SpiritGuide[TEAM_ALLIANCE]) ||
!m_Bf->GetCreature(m_SpiritGuide[TEAM_HORDE]))
return false;
return (m_SpiritGuide[TEAM_ALLIANCE] == guid || m_SpiritGuide[TEAM_HORDE] == guid);
}
// *******************************************************
// *************** End Spirit Guide system ***************
// *******************************************************
// ********************** Misc ***************************
// *******************************************************
Creature* Battlefield::SpawnCreature(uint32 entry, Position const& pos)
{
//Get map object
Map* map = sMapMgr->CreateBaseMap(m_MapId);
if (!map)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u, map not found.", entry);
return nullptr;
}
if (!sObjectMgr->GetCreatureTemplate(entry))
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: entry %u does not exist.", entry);
return nullptr;
}
Creature* creature = Creature::CreateCreature(entry, map, pos);
if (!creature)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnCreature: Can't create creature entry: %u", entry);
return nullptr;
}
creature->SetHomePosition(pos);
// Set creature in world
map->AddToMap(creature);
creature->setActive(true);
return creature;
}
// Method for spawning gameobject on map
GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot)
{
// Get map object
Map* map = sMapMgr->CreateBaseMap(m_MapId);
if (!map)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Can't create GameObject (Entry: %u). Map not found.", entry);
return nullptr;
}
if (!sObjectMgr->GetGameObjectTemplate(entry))
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: GameObject template %u not found in database! Battlefield not created!", entry);
return nullptr;
}
// Create gameobject
GameObject* go = GameObject::CreateGameObject(entry, map, pos, rot, 255, GO_STATE_READY);
if (!go)
{
TC_LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Could not create gameobject template %u! Battlefield has not been created!", entry);
return nullptr;
}
// Add to world
map->AddToMap(go);
go->setActive(true);
return go;
}
Creature* Battlefield::GetCreature(ObjectGuid guid)
{
if (!m_Map)
return nullptr;
return m_Map->GetCreature(guid);
}
GameObject* Battlefield::GetGameObject(ObjectGuid guid)
{
if (!m_Map)
return nullptr;
return m_Map->GetGameObject(guid);
}
// *******************************************************
// ******************* CapturePoint **********************
// *******************************************************
BfCapturePoint::BfCapturePoint(Battlefield* battlefield) : m_Bf(battlefield), m_capturePointGUID()
{
m_team = TEAM_NEUTRAL;
m_value = 0;
m_minValue = 0.0f;
m_maxValue = 0.0f;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL;
m_OldState = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL;
m_capturePointEntry = 0;
m_neutralValuePct = 0;
m_maxSpeed = 0;
}
bool BfCapturePoint::HandlePlayerEnter(Player* player)
{
if (!m_capturePointGUID.IsEmpty())
{
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 1);
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate2, uint32(ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f)));
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate3, m_neutralValuePct);
}
}
return m_activePlayers[player->GetTeamId()].insert(player->GetGUID()).second;
}
GuidSet::iterator BfCapturePoint::HandlePlayerLeave(Player* player)
{
if (!m_capturePointGUID.IsEmpty())
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
player->SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 0);
GuidSet::iterator current = m_activePlayers[player->GetTeamId()].find(player->GetGUID());
if (current == m_activePlayers[player->GetTeamId()].end())
return current; // return end()
m_activePlayers[player->GetTeamId()].erase(current++);
return current;
}
void BfCapturePoint::SendChangePhase()
{
if (!m_capturePointGUID)
return;
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
// send this too, sometimes the slider disappears, dunno why :(
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldState1, 1);
// send these updates to only the ones in this objective
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate2, (uint32)std::ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f));
// send this too, sometimes it resets :S
SendUpdateWorldState(capturePoint->GetGOInfo()->controlZone.worldstate3, m_neutralValuePct);
}
}
bool BfCapturePoint::SetCapturePointData(GameObject* capturePoint)
{
ASSERT(capturePoint);
TC_LOG_DEBUG("bg.battlefield", "Creating capture point %u", capturePoint->GetEntry());
m_capturePointGUID = capturePoint->GetGUID();
m_capturePointEntry = capturePoint->GetEntry();
// check info existence
GameObjectTemplate const* goinfo = capturePoint->GetGOInfo();
if (goinfo->type != GAMEOBJECT_TYPE_CONTROL_ZONE)
{
TC_LOG_ERROR("misc", "OutdoorPvP: GO %u is not a capture point!", capturePoint->GetEntry());
return false;
}
// get the needed values from goinfo
m_maxValue = goinfo->controlZone.maxTime;
m_maxSpeed = m_maxValue / (goinfo->controlZone.minTime ? goinfo->controlZone.minTime : 60);
m_neutralValuePct = goinfo->controlZone.neutralPercent;
m_minValue = m_maxValue * goinfo->controlZone.neutralPercent / 100;
if (m_team == TEAM_ALLIANCE)
{
m_value = m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE;
}
else
{
m_value = -m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE;
}
return true;
}
GameObject* BfCapturePoint::GetCapturePointGo()
{
return m_Bf->GetGameObject(m_capturePointGUID);
}
bool BfCapturePoint::DelCapturePoint()
{
if (!m_capturePointGUID.IsEmpty())
{
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
capturePoint->SetRespawnTime(0); // not save respawn time
capturePoint->Delete();
capturePoint = nullptr;
}
m_capturePointGUID.Clear();
}
return true;
}
bool BfCapturePoint::Update(uint32 diff)
{
if (!m_capturePointGUID)
return false;
if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
{
float radius = capturePoint->GetGOInfo()->controlZone.radius;
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
{
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end();)
{
if (Player* player = ObjectAccessor::FindPlayer(*itr))
{
if (!capturePoint->IsWithinDistInMap(player, radius) || !player->IsOutdoorPvPActive())
itr = HandlePlayerLeave(player);
else
++itr;
}
else
++itr;
}
}
std::list<Player*> players;
Trinity::AnyPlayerInObjectRangeCheck checker(capturePoint, radius);
Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(capturePoint, players, checker);
Cell::VisitWorldObjects(capturePoint, searcher, radius);
for (std::list<Player*>::iterator itr = players.begin(); itr != players.end(); ++itr)
if ((*itr)->IsOutdoorPvPActive())
if (m_activePlayers[(*itr)->GetTeamId()].insert((*itr)->GetGUID()).second)
HandlePlayerEnter(*itr);
}
// get the difference of numbers
float fact_diff = ((float) m_activePlayers[TEAM_ALLIANCE].size() - (float) m_activePlayers[TEAM_HORDE].size()) * diff / BATTLEFIELD_OBJECTIVE_UPDATE_INTERVAL;
if (G3D::fuzzyEq(fact_diff, 0.0f))
return false;
uint32 Challenger = 0;
float maxDiff = m_maxSpeed * diff;
if (fact_diff < 0)
{
// horde is in majority, but it's already horde-controlled -> no change
if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE && m_value <= -m_maxValue)
return false;
if (fact_diff < -maxDiff)
fact_diff = -maxDiff;
Challenger = HORDE;
}
else
{
// ally is in majority, but it's already ally-controlled -> no change
if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE && m_value >= m_maxValue)
return false;
if (fact_diff > maxDiff)
fact_diff = maxDiff;
Challenger = ALLIANCE;
}
float oldValue = m_value;
TeamId oldTeam = m_team;
m_OldState = m_State;
m_value += fact_diff;
if (m_value < -m_minValue) // red
{
if (m_value < -m_maxValue)
m_value = -m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE;
m_team = TEAM_HORDE;
}
else if (m_value > m_minValue) // blue
{
if (m_value > m_maxValue)
m_value = m_maxValue;
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE;
m_team = TEAM_ALLIANCE;
}
else if (oldValue * m_value <= 0) // grey, go through mid point
{
// if challenger is ally, then n->a challenge
if (Challenger == ALLIANCE)
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE;
// if challenger is horde, then n->h challenge
else if (Challenger == HORDE)
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE;
m_team = TEAM_NEUTRAL;
}
else // grey, did not go through mid point
{
// old phase and current are on the same side, so one team challenges the other
if (Challenger == ALLIANCE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE))
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE;
else if (Challenger == HORDE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE))
m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE;
m_team = TEAM_NEUTRAL;
}
if (G3D::fuzzyNe(m_value, oldValue))
SendChangePhase();
if (m_OldState != m_State)
{
//TC_LOG_ERROR("bg.battlefield", "%u->%u", m_OldState, m_State);
if (oldTeam != m_team)
ChangeTeam(oldTeam);
return true;
}
return false;
}
void BfCapturePoint::SendUpdateWorldState(uint32 field, uint32 value)
{
for (uint8 team = 0; team < BG_TEAMS_COUNT; ++team)
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr) // send to all players present in the area
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->SendUpdateWorldState(field, value);
}
void BfCapturePoint::SendObjectiveComplete(uint32 id, ObjectGuid guid)
{
uint8 team;
switch (m_State)
{
case BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE:
team = TEAM_ALLIANCE;
break;
case BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE:
team = TEAM_HORDE;
break;
default:
return;
}
// send to all players present in the area
for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr)
if (Player* player = ObjectAccessor::FindPlayer(*itr))
player->KilledMonsterCredit(id, guid);
}
bool BfCapturePoint::IsInsideObjective(Player* player) const
{
return m_activePlayers[player->GetTeamId()].find(player->GetGUID()) != m_activePlayers[player->GetTeamId()].end();
}
| conan513/SingleCore_TC | src/server/game/Battlefield/Battlefield.cpp | C++ | gpl-2.0 | 37,310 |
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
import {AjaxResponse} from 'TYPO3/CMS/Core/Ajax/AjaxResponse';
import AjaxRequest = require('TYPO3/CMS/Core/Ajax/AjaxRequest');
import javaScriptHandler = require('TYPO3/CMS/Core/JavaScriptHandler');
import Notification = require('../../Notification');
import Utility = require('../../Utility');
interface Context {
config: Object;
hmac: string;
}
interface Message {
title: string;
message: string;
}
export interface AjaxDispatcherResponse {
hasErrors: boolean;
messages: Message[];
stylesheetFiles: string[];
inlineData: object;
requireJsModules: string[];
scriptCall: string[];
scriptItems?: any[];
}
export class AjaxDispatcher {
private readonly objectGroup: string = null;
constructor(objectGroup: string) {
this.objectGroup = objectGroup;
}
public newRequest(endpoint: string): AjaxRequest {
return new AjaxRequest(endpoint);
}
/**
* @param {String} routeName
*/
public getEndpoint(routeName: string): string {
if (typeof TYPO3.settings.ajaxUrls[routeName] !== 'undefined') {
return TYPO3.settings.ajaxUrls[routeName];
}
throw 'Undefined endpoint for route "' + routeName + '"';
}
public send(request: AjaxRequest, params: Array<string>): Promise<any> {
const sentRequest = request.post(this.createRequestBody(params)).then(async (response: AjaxResponse): Promise<any> => {
return this.processResponse(await response.resolve());
});
sentRequest.catch((reason: Error): void => {
Notification.error('Error ' + reason.message);
});
return sentRequest;
}
private createRequestBody(input: Array<string>): { [key: string]: string } {
const body: { [key: string]: string } = {};
for (let i = 0; i < input.length; i++) {
body['ajax[' + i + ']'] = input[i];
}
body['ajax[context]'] = JSON.stringify(this.getContext());
return body;
}
private getContext(): Context {
let context: Context;
if (typeof TYPO3.settings.FormEngineInline.config[this.objectGroup] !== 'undefined'
&& typeof TYPO3.settings.FormEngineInline.config[this.objectGroup].context !== 'undefined'
) {
context = TYPO3.settings.FormEngineInline.config[this.objectGroup].context;
}
return context;
}
private processResponse(json: AjaxDispatcherResponse): AjaxDispatcherResponse {
if (json.hasErrors) {
for (const message of json.messages) {
Notification.error(message.title, message.message);
}
}
// If there are elements they should be added to the <HEAD> tag (e.g. for RTEhtmlarea):
if (json.stylesheetFiles) {
for (const [index, stylesheetFile] of json.stylesheetFiles.entries()) {
if (!stylesheetFile) {
break;
}
const element = document.createElement('link');
element.rel = 'stylesheet';
element.type = 'text/css';
element.href = stylesheetFile;
document.querySelector('head').appendChild(element);
delete json.stylesheetFiles[index];
}
}
if (typeof json.inlineData === 'object') {
TYPO3.settings.FormEngineInline = Utility.mergeDeep(TYPO3.settings.FormEngineInline, json.inlineData);
}
if (json.scriptItems instanceof Array && json.scriptItems.length > 0) {
javaScriptHandler.processItems(json.scriptItems, true);
}
// @todo deprecate or remove with TYPO3 v12.0
if (typeof json.requireJsModules === 'object') {
for (let requireJsModule of json.requireJsModules) {
new Function(requireJsModule)();
}
}
// TODO: This is subject to be removed
// @todo deprecate or remove with TYPO3 v12.0
if (json.scriptCall && json.scriptCall.length > 0) {
for (const scriptCall of json.scriptCall) {
// eslint-disable-next-line no-eval
eval(scriptCall);
}
}
return json;
}
}
| stweil/TYPO3.CMS | Build/Sources/TypeScript/backend/Resources/Public/TypeScript/FormEngine/InlineRelation/AjaxDispatcher.ts | TypeScript | gpl-2.0 | 4,280 |
// *************************************************************************
//
// Copyright 2004-2010 Bruno PAGES .
//
// This file is part of the BOUML Uml Toolkit.
//
// 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.
//
// e-mail : bouml@free.fr
// home : http://bouml.free.fr
//
// *************************************************************************
#include <stdio.h>
#include "UmlDrag.h"
#include "BrowserNode.h"
const QString UmlDrag::Key = "Bouml/";
QString UmlDrag::postfix;
bool UmlDrag::ro;
UmlDrag::UmlDrag(BrowserNode * bn, QWidget * parent, const char * name)
: QStoredDrag(UmlDrag::Key + bn->drag_key(), parent, name) {
// stay in the same application : can use address directly
QByteArray a(sizeof(bn));
memcpy(a.data(), &bn, sizeof(bn));
setEncodedData(a);
postfix = bn->drag_postfix();
ro = ((bn->parent() != 0) &&
!((BrowserNode *) bn->parent())->is_writable());
}
bool UmlDrag::canDecode(QDragMoveEvent * e, UmlCode type,
bool withpostfix, bool evenro)
{
if (ro && ! evenro)
return FALSE;
return (e->source() != 0) &&
e->provides((withpostfix) ? UmlDrag::Key + QString::number(type) + postfix
: UmlDrag::Key + QString::number(type));
}
bool UmlDrag::canDecode(QDragMoveEvent * e, const QString & type)
{
return !ro && (e->source() != 0) && e->provides(UmlDrag::Key + type);
}
BrowserNode * UmlDrag::decode(QDropEvent * e, UmlCode type,
bool withpostfix)
{
QByteArray payload =
e->data((withpostfix) ? UmlDrag::Key + QString::number(type) + postfix
: UmlDrag::Key + QString::number(type));
if (payload.size()) {
e->accept();
BrowserNode * bn;
memcpy(&bn, payload.data(), sizeof(bn));
return bn;
}
return 0;
}
BrowserNode * UmlDrag::decode(QDropEvent * e, const QString & type)
{
QByteArray payload = e->data(UmlDrag::Key + type);
if (payload.size()) {
e->accept();
BrowserNode * bn;
memcpy(&bn, payload.data(), sizeof(bn));
return bn;
}
return 0;
}
| gregsmirnov/bouml | src/misc/UmlDrag.cpp | C++ | gpl-2.0 | 2,695 |
<?php
/**
*
* Ajax Shoutbox extension for the phpBB Forum Software package.
*
* @copyright (c) 2014 Paul Sohier <http://www.ajax-shoutbox.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* Translated By : Bassel Taha Alhitary - www.alhitary.net
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
//
// Some characters you may want to copy&paste:
// ’ » “ ” …
//
$lang = array_merge(
$lang, array(
'AJAX_SHOUTBOX' => 'الدردشة أجاكس',
'AJAX_SHOUTBOX_MESSAGE' => 'ارسل رسالتك',
'AJAX_SHOUTBOX_ONLY_AJAX' => 'المعذرة , يجب تفعيل الجافا سكربت لكي تعمل هذه الدردشة.',
'AJAX_SHOUTBOX_NO_PERMISSION' => 'لا توجد صلاحية لتنفيذ هذا الأمر',
'AJAX_SHOUTBOX_MESSAGE_EMPTY' => 'الرسالة فارغة',
'AJAX_SHOUTBOX_ERROR' => 'خطأ',
'AJAX_SHOUTBOX_MISSING_ID' => 'لا يُمكن حذف المشاركة',
'AJAX_SHOUTBOX_NO_SUCH_POST' => 'لا يُمكن العثور على المشاركة',
'AJAX_SHOUTBOX_PUSH_NOT_AVAIL' => 'الخدمة عير متوفرة حالياً',
'AJAXSHOUTBOX_BOARD_DATE_FORMAT' => 'My shoutbox date format',
'AJAXSHOUTBOX_BOARD_DATE_FORMAT_EXPLAIN' => 'Specify a date format for just the shoutbox. You should not use a relative date format.',
)
);
| Galixte/ajax-shoutbox-ext | language/ar/ajax_shoutbox.php | PHP | gpl-2.0 | 2,096 |
<?php
/*
$Id: tax_classes.php 1692 2012-02-26 01:26:50Z michael.oscmax@gmail.com $
osCmax e-Commerce
http://www.oscmax.com
Copyright 2000 - 2011 osCmax
Released under the GNU General Public License
*/
define('HEADING_TITLE', 'Tipos de impuestos');
define('TABLE_HEADING_TAX_CLASSES', 'Tipos de impuestos');
define('TABLE_HEADING_ACTION', 'Acción');
define('TEXT_INFO_EDIT_INTRO', 'Realiza los cambios necesarios');
define('TEXT_INFO_CLASS_TITLE', 'Nombre del impuesto:');
define('TEXT_INFO_CLASS_DESCRIPTION', 'Descripción:');
define('TEXT_INFO_DATE_ADDED', 'Fecha creación:');
define('TEXT_INFO_LAST_MODIFIED', 'Última modificación:');
define('TEXT_INFO_INSERT_INTRO', 'Introduce los datos del nuevo tipo de impuesto');
define('TEXT_INFO_DELETE_INTRO', '¿Seguro que quieres eliminar este tipo de impuesto?');
define('TEXT_INFO_HEADING_NEW_TAX_CLASS', 'Nuevo tipo de impuesto');
define('TEXT_INFO_HEADING_EDIT_TAX_CLASS', 'Editar tipo de impuesto');
define('TEXT_INFO_HEADING_DELETE_TAX_CLASS', 'Eliminar tipo de impuesto');
?> | arnabnaha/NHCPharmacy | catalog/admin/includes/languages/espanol/tax_classes.php | PHP | gpl-2.0 | 1,041 |
/* $Id: tag.hpp 55984 2013-01-01 09:34:55Z mordante $ */
/*
Copyright (C) 2011 - 2013 by Sytyi Nick <nsytyi@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* This file contains objects "tag" and "key", which are used to store
* information about tags and keys while annotation parsing.
*/
#ifndef TOOLS_SCHEMA_TAG_HPP_INCLUDED
#define TOOLS_SCHEMA_TAG_HPP_INCLUDED
#include <algorithm>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
class config;
namespace schema_validation{
/**
* class_key is used to save the information about one key.
* Key has next info: name, type, default value or key is mandatory.
*/
class class_key{
public:
class_key():name_(""),type_(""),default_("\"\""),mandatory_(false)
{ }
class_key(const std::string & name,
const std::string &type,
const std::string &def="\"\"")
: name_(name)
, type_(type)
, default_(def)
, mandatory_(def.empty())
{
}
class_key(const config&);
const std::string & get_name() const{
return name_ ;
}
const std::string & get_type() const{
return type_ ;
}
const std::string & get_default() const{
return default_;
}
bool is_mandatory () const{
return mandatory_ ;
}
void set_name(const std::string& name){
name_ = name;
}
void set_type(const std::string& type){
type_ = type;
}
void set_default(const std::string& def){
default_ = def;
if (def.empty()){
mandatory_ = true;
}
}
void set_mandatory(bool mandatory){
mandatory_ = mandatory;
}
/** is used to print key info
* the format is next
* [key]
* name="name"
* type="type"
* default="default"
* mandatory="true/false"
* [/key]
*/
void print(std::ostream& os,int level) const;
/**
*Compares keys by name. Used in std::sort, i.e.
*/
bool operator < ( const class_key& k) const{
return (get_name() < k.get_name());
}
private:
/** Name of key*/
std::string name_;
/** Type of key*/
std::string type_;
/** Default value*/
std::string default_;
/** Shows, if key is a mandatory key.*/
bool mandatory_;
};
/**
* Stores information about tag.
* Each tags is an element of great tag tree. This tree is close to filesystem:
* you can use links and special include directory global/
* Normally root is not mentioned in path.
* Each tag has name, minimum and maximum occasions number,
* and lists of subtags, keys and links.
*/
class class_tag{
public:
typedef std::map<std::string,class_tag> tag_map;
typedef std::pair<std::string,class_tag> tag_map_value;
typedef std::map<std::string,class_key> key_map;
typedef std::pair<std::string,class_key> key_map_value;
typedef std::map<std::string,std::string> link_map;
typedef std::pair<std::string,std::string> link_map_value;
typedef key_map::iterator key_iterator;
typedef std::pair<key_iterator,key_iterator> all_key_iterators;
typedef key_map::const_iterator const_key_iterator;
typedef std::pair<const_key_iterator,const_key_iterator>
all_const_key_iterators;
typedef tag_map::iterator tag_iterator;
typedef std::pair<tag_iterator,tag_iterator> all_tag_iterators;
typedef tag_map::const_iterator const_tag_iterator;
typedef std::pair<const_tag_iterator,const_tag_iterator>
all_const_tag_iterators;
typedef link_map::iterator link_iterator;
typedef std::pair<link_iterator,link_iterator> all_link_iterators;
typedef link_map::const_iterator const_link_iterator;
typedef std::pair<const_link_iterator,const_link_iterator>
all_const_link_iterators;
class_tag()
: name_("")
, min_(0)
, max_(0)
, super_("")
, tags_()
, keys_()
, links_()
{
}
class_tag(const std::string & name,
int min,
int max,
const std::string & super=""
)
: name_(name)
, min_(min)
, max_(max)
, super_(super)
, tags_()
, keys_()
, links_()
{
}
class_tag(const config&);
~class_tag(){ }
/** Prints information about tag to outputstream, recursively
* is used to print tag info
* the format is next
* [tag]
* subtags
* keys
* name="name"
* min="min"
* max="max"
* [/tag]
*/
void print(std::ostream& os);
const std::string & get_name() const{
return name_ ;
}
int get_min() const{
return min_;
}
int get_max() const{
return max_;
}
const std::string & get_super() const{
return super_ ;
}
bool is_extension() const{
return ! super_.empty();
}
void set_name(const std::string& name){
name_ = name;
}
void set_min(int o){
min_ = o;
}
void set_max(int o){
max_ = o;
}
void set_min( std::string const& s){
std::istringstream i(s);
if (!(i >> min_)){
min_ = 0;
}
}
void set_max( std::string const & s){
std::istringstream i(s);
if (!(i >> max_)){
max_ = 0;
}
}
void set_super(std::string const & s){
super_= s;
}
void add_key(const class_key& new_key){
keys_.insert(key_map_value(new_key.get_name(),new_key));
}
void add_tag(const class_tag& new_tag){
tags_.insert(tag_map_value(new_tag.name_,new_tag));
}
void add_link(const std::string & link);
/**
* Tags are usually organized in tree.
* This fuction helps to add tag to his exact place in tree
* @param path - path in subtree to exact place of tag
* @param tag - tag to add
* @param root - root of schema tree - use to support of adding to link.
* Path is getting shotter and shoter with each call.
* Path schould look like tag1/tag2/parent/ Slash at end is mandatory.
*/
void add_tag (const std::string & path,const class_tag & tag,
class_tag &root);
bool operator < ( const class_tag& t) const{
return name_ < t.name_;
}
bool operator == (const class_tag & other) const {
return name_ == other.name_;
}
/**
* Returns pointer to child key
*/
const class_key * find_key(const std::string & name) const;
/**
* Returns pointer to child link
*/
const std::string * find_link(const std::string & name) const;
/**
* Returns pointer to tag using full path to it.
* Also work with links
*/
const class_tag * find_tag(const std::string & fullpath,
const class_tag & root) const;
/**
* Calls the expansion on each child
*/
void expand_all(class_tag &root);
all_const_tag_iterators tags() const{
return all_const_tag_iterators(tags_.begin(),tags_.end());
}
all_const_key_iterators keys() const{
return all_const_key_iterators(keys_.begin(),keys_.end());
}
all_const_link_iterators links() const{
return all_const_link_iterators(links_.begin(),links_.end());
}
void remove_key_by_name(const std::string &name){
keys_.erase (name);
}
/** Removes all keys with this type. Works recursively */
void remove_keys_by_type(const std::string &type);
#ifdef _MSC_VER
// MSVC throws an error if this method is private.
// so, define it as public to prevent that. The error is:
// error C2248: 'schema_validation::class_tag::find_tag' : cannot
// access private member declared in class 'schema_validation::class_tag'
class_tag * find_tag(const std::string & fullpath,
class_tag & root) ;
#endif
// class_tag & operator= (class_tag const& );
private:
/** name of tag*/
std::string name_;
/** number of minimum occasions*/
int min_;
/** number of maximum occasions*/
int max_;
/**
* name of tag to extend "super-tag"
* Extension is smth like inheritance and is used in case
* when you need to use another tag with all his
* keys, childs, etc. But you also want to allow extra subtags of that tags,
* so just linking that tag wouldn't help at all.
*/
std::string super_;
/** children tags*/
tag_map tags_;
/** keys*/
key_map keys_;
/** links to possible children. */
link_map links_;
/**
* the same as class_tag::print(std::ostream&)
* but indents different levels with step space.
* @param os stream to print
* @param level current level of indentation
* @param step step to next indent
*/
void printl(std::ostream &os,int level, int step = 4);
#ifndef _MSC_VER
// this is complementary with the above #ifdef for the MSVC error
class_tag * find_tag(const std::string & fullpath,
class_tag & root) ;
#endif
void add_tags (const tag_map & list){
tags_.insert(list.begin(),list.end());
}
void add_keys (const key_map & list){
keys_.insert(list.begin(),list.end());
}
void add_links (const link_map & list){
links_.insert(list.begin(),list.end());
}
/**
* Copies tags, keys and links of tag to this
*/
void append_super(const class_tag & tag,const std::string & super);
/**
* Expands all "super" copying their data to this.
*/
void expand(class_tag & root);
};
}
#endif // TOOLS_SCHEMA_TAG_HPP_INCLUDED
| RushilPatel/BattleForWesnoth | src/tools/schema/tag.hpp | C++ | gpl-2.0 | 9,062 |
<?php
require_once("include/config.php");
require_once("include/functions.php");
if(!isset($_SESSION['logat'])) $_SESSION['logat'] = 'Nu';
if($_SESSION['logat'] == 'Da')
{
if(isset($_SESSION['nume']) && ctype_alnum($_SESSION['nume']))
$setid = $_SESSION['userid'];
if(isset($setid))
{
if($_SESSION['global']==1 ? $acces=1 : $acces=check_perm("Editare pagini"));
if($acces!=1)
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
}
else
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
if(isset($_POST['submit']))
{
$id = make_safe($_GET['id']);
$galt = make_safe($_POST['galt']);
$link = $_POST['link'];
if(!validateURL($link))
$mesaj = "Adresă web invalidă.";
else
{
$sql="UPDATE `gallery` SET galt='$galt', link='$link' WHERE id='$id'";
mysql_query($sql);
$mesaj = "Datele au fost actualizate!";
}
}
if(isset($_GET['id']) && is_numeric($_GET['id']))
{
$sql = "SELECT * FROM `gallery` WHERE id=".$_GET['id']."";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
$rand = mysql_fetch_object($result);
$id = $rand -> id;
$galt = $rand -> galt;
$link = $rand -> link;
}
else
$nuexista = 1;
}
else
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/editare-sponsori.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<?php include("include/headerinfoadm.php");?>
<link rel="stylesheet" type="text/css" href="js/formValidator/validationEngine.jquery.css" />
</head>
<body>
<div id="contain">
<div id="main">
<?php include("include/headeradm.php");?>
<div id="pagecontent">
<div id="pcontent_f"></div>
<?php if(!isset($nuexista))
{
?>
<br/>
<a href="editare-galerie.php"><img src="images/back.png" class="midalign"/></a> <a href="editare-galerie.php">Înapoi la pagina de administrare a galeriei foto</a>
<br/><br/>
<?php
display_message($mesaj);
?>
<b>Editare imagine galerie foto:</b><br/><br/>
<form action="editare-foto.php?id=<?php echo $_GET['id'];?>" method="post" id="validate">
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
Text alternativ imagine:
<input name="galt" type="text" value="<?php if(isset($galt)) echo $galt?>" class="stfield"/>
<br/><br/>
Link imagine:
<input name="link" type="text" value="<?php if(isset($link)) echo $link?>" class="stfield" data-validation-engine="validate[custom[url]]"/>
<br /><br />
<input name="submit" type="submit" value="Actualizare imagine" />
</form>
<? } else {?>
Comentariul pe care aţi încercat să îl accesaţi nu există!
<?php } ?>
</div>
<?php include("include/footeradm.php");?>
</div>
</div>
<script type="text/javascript" src="js/formValidator/jquery.validationEngine.js"></script>
<script type="text/javascript" src="js/formValidator/jquery.validationEngine-ro.js" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#validate").validationEngine();
});
</script>
</body>
</html>
<?php
} else {
header('Location: http://'.$_SERVER["SERVER_NAME"].'/admiasi/index.php');
}
?> | hodorogandrei/contesteasyplatform | admiasi/editare-foto.php | PHP | gpl-2.0 | 4,821 |
using System.ComponentModel;
using System.Windows;
namespace Filewatcher.GUI
{
public partial class MacroView
{
public string Value { get; set; }
public MacroView()
{
InitializeComponent();
InitalizeExitRequest();
InitializeLocation();
}
private void InitalizeExitRequest()
{
var currDataContext = DataContext as MacroViewModel;
if (currDataContext == null) return;
currDataContext.ExitRequest += (s, eArgs) =>
{
if (eArgs.DialogResult)
Value = eArgs.Value.ToString();
DialogResult = eArgs.DialogResult;
Close();
};
}
private void InitializeLocation()
{
if (Properties.Settings.Default.MACROVIEW_LEFT > 0)
Left = Properties.Settings.Default.MACROVIEW_LEFT;
if (Properties.Settings.Default.MACROVIEW_TOP > 0)
Top = Properties.Settings.Default.MACROVIEW_TOP;
}
private void WindowClosing(object sender, CancelEventArgs e)
{
Properties.Settings.Default.MACROVIEW_LEFT = Left;
Properties.Settings.Default.MACROVIEW_TOP = Top;
Properties.Settings.Default.Save();
}
}
}
| bajak/luba-filewatcher | GUI/Views/MacroView.xaml.cs | C# | gpl-2.0 | 1,364 |
<?php
// ============================================================+
// File name : example_045.php
// Begin : 2008-03-04
// Last Update : 2011-04-15
//
// Description : Example 045 for TCPDF class
// Bookmarks and Table of Content
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// Manor Coach House, Church Hill
// Aldershot, Hants, GU12 4RQ
// UK
// www.tecnick.com
// info@tecnick.com
// ============================================================+
/**
* Creates an example PDF TEST document using TCPDF
*
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Bookmarks and Table of Content
* @author Nicola Asuni
* @since 2008-03-04
*/
require_once ('../config/lang/eng.php');
require_once ('../tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 045');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE . ' 045', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(
PDF_FONT_NAME_MAIN,
'',
PDF_FONT_SIZE_MAIN
));
$pdf->setFooterFont(Array(
PDF_FONT_NAME_DATA,
'',
PDF_FONT_SIZE_DATA
));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings
$pdf->setLanguageArray($l);
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'B', 20);
// add a page
$pdf->AddPage();
// set a bookmark for the current position
$pdf->Bookmark('Chapter 1', 0, 0, '', 'B', array(
0,
64,
128
));
// print a line using Cell()
$pdf->Cell(0, 10, 'Chapter 1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.1', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.2', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Sub-Paragraph 1.2.1', 2, 0, '', 'I', array(
0,
128,
0
));
$pdf->Cell(0, 10, 'Sub-Paragraph 1.2.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.3', 1, 0, '', '', array(
128,
0,
0
));
$pdf->Cell(0, 10, 'Paragraph 1.3', 0, 1, 'L');
// add some pages and bookmarks
for ($i = 2; $i < 12; $i ++) {
$pdf->AddPage();
$pdf->Bookmark('Chapter ' . $i, 0, 0, '', 'B', array(
0,
64,
128
));
$pdf->Cell(0, 10, 'Chapter ' . $i, 0, 1, 'L');
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// add a new page for TOC
$pdf->addTOCPage();
// write the TOC title
$pdf->SetFont('times', 'B', 16);
$pdf->MultiCell(0, 0, 'Table Of Content', 0, 'C', 0, 1, '', '', true, 0);
$pdf->Ln();
$pdf->SetFont('dejavusans', '', 12);
// add a simple Table Of Content at first page
// (check the example n. 59 for the HTML version)
$pdf->addTOC(1, 'courier', '.', 'INDEX', 'B', array(
128,
0,
0
));
// end of TOC page
$pdf->endTOCPage();
// ---------------------------------------------------------
// Close and output PDF document
$pdf->Output('example_045.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+
| memoupao/Fondo-Simon | lib/tcpdf/examples/example_045.php | PHP | gpl-2.0 | 3,857 |
package de.amshaegar.economy.http;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
import de.amshaegar.economy.EcoFlow;
public class WebInterface {
private HttpServer server;
public WebInterface(int port) throws IOException {
server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext("/", new TemplateHttpHandler());
server.createContext("/auth", new AuthHttpHandler());
server.createContext("/intern", new InternHttpHandler());
server.createContext("/intern/ajax", new AjaxHttpHandler());
server.start();
EcoFlow.getPlugin().getLogger().info(String.format("Web interface started on port %d", server.getAddress().getPort()));
}
public void stop() {
server.stop(0);
}
}
| AmShaegar13/EcoFlow | src/de/amshaegar/economy/http/WebInterface.java | Java | gpl-2.0 | 780 |
<?php
/**
* Auto Amazon Links
*
* Generates links of Amazon products just coming out today. You just pick categories and they appear even in JavaScript disabled browsers.
*
* https://en.michaeluno.jp/amazon-auto-links/
* Copyright (c) 2013-2021 Michael Uno
*/
/**
* A scratch class to delete a database table.
*
* @since 4.3.5
*/
class AmazonAutoLinks_Run_Database_Delete_aal_products extends AmazonAutoLinks_Scratch_Base {
/**
* @purpose Deletes the task table and version option.
* @return boolean
*/
public function scratch_uninstall() {
$_oTaskTable = new AmazonAutoLinks_DatabaseTable_aal_products;
$_oTaskTable->uninstall();
return ! $_oTaskTable->tableExists();
}
} | michaeluno/amazon-auto-links | include/core/component/test/run/delete/database/aal_products/AmazonAutoLinks_Run_Database_Delete_aal_products.php | PHP | gpl-2.0 | 745 |