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 /** * @version $Id: edit.php 807 2012-10-02 18:53:43Z jeffchannell $ * @package JCalPro * @subpackage com_jcalpro ********************************************** JCal Pro Copyright (c) 2006-2012 Anything-Digital.com ********************************************** JCalPro is a native Joomla! calendar component for Joomla! JCal Pro was once a fork of the existing Extcalendar component for Joomla! (com_extcal_0_9_2_RC4.zip from mamboguru.com). Extcal (http://sourceforge.net/projects/extcal) was renamed and adapted to become a Mambo/Joomla! component by Matthew Friedman, and further modified by David McKinnis (mamboguru.com) to repair some security holes. 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 header must not be removed. Additional contributions/changes may be added to this header as long as no information is deleted. ********************************************** Get the latest version of JCal Pro at: http://anything-digital.com/ ********************************************** */ defined('JPATH_PLATFORM') or die; JHtml::_('behavior.tooltip'); JHtml::_('behavior.formvalidation'); $fieldFieldset = $this->form->getFieldset('field'); $rulesFieldset = $this->form->getFieldset('rules'); $attrsFieldset = $this->form->getFieldset('attributes'); $hiddenFieldset = $this->form->getFieldset('hidden'); ?> <script type="text/javascript"> Joomla.submitbutton = function(task) { if (task == 'field.cancel' || document.formvalidator.isValid(document.id('field-form'))) { Joomla.submitform(task, document.getElementById('field-form')); } else { alert('<?php echo JCalProHelperFilter::escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));?>'); } } </script> <div id="jcl_component" class="<?php echo $this->viewClass; ?>"> <form action="<?php echo JRoute::_('index.php?option=com_jcalpro&task=field.save&id=' . (int) $this->item->id); ?>" method="post" id="field-form" name="adminForm" class="form-validate"> <div class="width-60 fltlft"> <fieldset class="adminform"> <ul class="adminformlist"> <?php foreach ($fieldFieldset as $name => $field): ?> <li class="jcl_form_label"><?php echo $field->label; ?></li> <li class="jcl_form_input"><?php echo $field->input; ?></li> <?php endforeach; ?> </ul> </fieldset> </div> <div class="width-40 fltlft"> <fieldset class="adminform"> <ul class="adminformlist"> <?php foreach ($attrsFieldset as $name => $field): ?> <li class="jcl_form_label"><?php echo $field->label; ?></li> <li class="jcl_form_input"><?php echo $field->input; ?></li> <?php endforeach; ?> </ul> </fieldset> </div> <div class="width-100 jcl_clear"> <fieldset class="adminform"> <?php echo JText::_('COM_JCALPRO_FIELD_HELP_TEXT'); foreach ($hiddenFieldset as $name => $field) echo $field->input; ?> <input type="hidden" name="task" value="" /> <?php echo JHtml::_('form.token'); ?> </fieldset> </div> <div class="width-100 jcl_clear"> <fieldset class="adminform"> <legend><?php echo JText::_('JGLOBAL_ACTION_PERMISSIONS_LABEL'); ?></legend> <?php foreach ($rulesFieldset as $name => $field) echo $field->input; ?> </fieldset> </div> </form> </div> <?php echo $this->loadTemplate('debug'); ?>
GBayerl/IndoorCycle
administrator/components/com_jcalpro/views/field/tmpl/edit.php
PHP
gpl-2.0
3,477
/* * DAWN OF LIGHT - The first free open source DAoC server emulator * * 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. * */ using System; using System.Collections.Generic; using System.Linq; using DOL.Database; using DOL.GS.Styles; namespace DOL.GS { /// <summary> /// callback handler for a spec that is activated by clicking on an associated icon /// </summary> public interface ISpecActionHandler { void Execute(Specialization ab, GamePlayer player); } /// <summary> /// Specialization can be in some way an ability too and can have icons then /// its level depends from skill points that were spent to it through trainers /// </summary> public class Specialization : NamedSkill { /// <summary> /// Level required for this spec (used for sorting) /// can be negative for sorting, as long as Spec Level is positive it will match /// </summary> private int m_levelRequired = 0; /// <summary> /// Script Constructor /// </summary> public Specialization(string keyname, string displayname, ushort icon) : this(keyname, displayname, icon, icon) { } /// <summary> /// Default constructor /// </summary> public Specialization(string keyname, string displayname, ushort icon, int ID) : base(keyname, displayname, ID, icon, 1, ID) { } /// <summary> /// Level Required for this Specialization /// Don't change this unless you know what you're doing ! /// </summary> public int LevelRequired { get { return m_levelRequired; } set { m_levelRequired = value; } } /// <summary> /// type of skill /// </summary> public override eSkillPage SkillType { get { return eSkillPage.Specialization; } } /// <summary> /// Is this Specialization Trainable ? /// </summary> public virtual bool Trainable { get { return true; } } /// <summary> /// Can This Specialization be saved in Player record ? /// </summary> public virtual bool AllowSave { get { return true; } } /// <summary> /// Is this Specialization Handling Hybrid lists ? /// </summary> public virtual bool HybridSpellList { get { return false; } } #region Getters /// <summary> /// Default getter for SpellLines /// Retrieve spell line depending on advanced class and class hint /// Order by Baseline /// </summary> /// <param name="living"></param> /// <returns></returns> public virtual List<SpellLine> GetSpellLinesForLiving(GameLiving living) { return GetSpellLinesForLiving(living, GetSpecLevelForLiving(living)); } /// <summary> /// Default getter for SpellLines with a "step" hint used to display future upgrade /// Retrieve spell line depending on advanced class and class hint /// Order by Baseline /// </summary> /// <param name="living"></param> /// <param name="step">step is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> public virtual List<SpellLine> PretendSpellLinesForLiving(GameLiving living, int step) { return GetSpellLinesForLiving(living, step); } /// <summary> /// Default getter for SpellLines /// Retrieve spell line depending on advanced class and class hint /// Order by Baseline /// </summary> /// <param name="living"></param> /// <param name="level">level is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> protected virtual List<SpellLine> GetSpellLinesForLiving(GameLiving living, int level) { List<SpellLine> list = new List<SpellLine>(); IList<Tuple<SpellLine, int>> spsl = SkillBase.GetSpecsSpellLines(KeyName); // Get Spell Lines by order of appearance if (living is GamePlayer) { GamePlayer player = (GamePlayer)living; // select only spec line if is advanced class... var tmp = spsl.Where(item => (item.Item1.IsBaseLine || player.CharacterClass.HasAdvancedFromBaseClass())) .OrderBy(item => (item.Item1.IsBaseLine ? 0 : 1)).ThenBy(item => item.Item1.ID); // try with class hint var baseline = tmp.Where(item => item.Item1.IsBaseLine && item.Item2 == player.CharacterClass.ID); if (baseline.Any()) { foreach (Tuple<SpellLine, int> ls in baseline) { ls.Item1.Level = player.Level; list.Add(ls.Item1); } } else { foreach (Tuple<SpellLine, int> ls in tmp.Where(item => item.Item1.IsBaseLine && item.Item2 == 0)) { ls.Item1.Level = player.Level; list.Add(ls.Item1); } } // try spec with class hint var specline = tmp.Where(item => !item.Item1.IsBaseLine && item.Item2 == player.CharacterClass.ID); if (specline.Any()) { foreach (Tuple<SpellLine, int> ls in specline) { ls.Item1.Level = level; list.Add(ls.Item1); } } else { foreach (Tuple<SpellLine, int> ls in tmp.Where(item => !item.Item1.IsBaseLine && item.Item2 == 0)) { ls.Item1.Level = level; list.Add(ls.Item1); } } } else { // default - not a player, add all... foreach(Tuple<SpellLine, int> ls in spsl.OrderBy(item => (item.Item1.IsBaseLine ? 0 : 1)).ThenBy(item => item.Item1.ID)) { // default living spec is (Level * 0.66 + 1) on Live (no real proof...) // here : Level - (Level / 4) = 0.75 if (ls.Item1.IsBaseLine) ls.Item1.Level = living.Level; else ls.Item1.Level = Math.Max(1, living.Level - (living.Level >> 2)); list.Add(ls.Item1); } } return list; } /// <summary> /// Default Getter For Spells /// Retrieve Spell index by SpellLine, List Spell by Level Order /// Select Only enabled Spells by spec or living level constraint. /// </summary> /// <param name="living"></param> /// <returns></returns> public virtual IDictionary<SpellLine, List<Skill>> GetLinesSpellsForLiving(GameLiving living) { return GetLinesSpellsForLiving(living, GetSpecLevelForLiving(living)); } /// <summary> /// Getter For Spells with a "step" hint used to display future upgrade /// Retrieve Spell index by SpellLine, List Spell by Level Order /// Select Only enabled Spells by spec or living level constraint. /// </summary> /// <param name="living"></param> /// <param name="step">step is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> public virtual IDictionary<SpellLine, List<Skill>> PretendLinesSpellsForLiving(GameLiving living, int step) { return GetLinesSpellsForLiving(living, step); } /// <summary> /// Default Getter For Spells /// Retrieve Spell index by SpellLine, List Spell by Level Order /// Select Only enabled Spells by spec or living level constraint. /// </summary> /// <param name="living"></param> /// <param name="level">level is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> protected virtual IDictionary<SpellLine, List<Skill>> GetLinesSpellsForLiving(GameLiving living, int level) { IDictionary<SpellLine, List<Skill>> dict = new Dictionary<SpellLine, List<Skill>>(); foreach (SpellLine sl in GetSpellLinesForLiving(living, level)) { dict.Add(sl, SkillBase.GetSpellList(sl.KeyName) .Where(item => item.Level <= sl.Level) .OrderBy(item => item.Level) .ThenBy(item => item.ID).Cast<Skill>().ToList()); } return dict; } /// <summary> /// Default getter for Ability /// Return Abilities it lists depending on spec level /// Override to change the condition... /// </summary> /// <param name="living"></param> /// <returns></returns> public virtual List<Ability> GetAbilitiesForLiving(GameLiving living) { return GetAbilitiesForLiving(living, GetSpecLevelForLiving(living)); } /// <summary> /// Getter for Ability with a "step" hint used to display future upgrade /// Return Abilities it lists depending on spec level /// Override to change the condition... /// </summary> /// <param name="living"></param> /// <param name="step">step is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> public virtual List<Ability> PretendAbilitiesForLiving(GameLiving living, int step) { return SkillBase.GetSpecAbilityList(KeyName, living is GamePlayer ? ((GamePlayer)living).CharacterClass.ID : 0) .Where(k => k.SpecLevelRequirement <= step) .OrderBy(k => k.SpecLevelRequirement).ToList(); } /// <summary> /// Default getter for Ability /// Return Abilities it lists depending on spec level /// Override to change the condition... /// </summary> /// <param name="living"></param> /// <param name="level">level is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> protected virtual List<Ability> GetAbilitiesForLiving(GameLiving living, int level) { // Select only Enabled and Max Level Abilities List<Ability> abs = SkillBase.GetSpecAbilityList(KeyName, living is GamePlayer ? ((GamePlayer)living).CharacterClass.ID : 0); // Get order of first appearing skills IOrderedEnumerable<Ability> order = abs.GroupBy(item => item.KeyName) .Select(ins => ins.OrderBy(it => it.SpecLevelRequirement).First()) .Where(item => item.SpecLevelRequirement <= level) .OrderBy(item => item.SpecLevelRequirement) .ThenBy(item => item.ID); // Get best of skills List<Ability> best = abs.Where(item => item.SpecLevelRequirement <= level) .GroupBy(item => item.KeyName) .Select(ins => ins.OrderByDescending(it => it.SpecLevelRequirement).First()).ToList(); List<Ability> results = new List<Ability>(); // make some kind of "Join" between the order of appearance and the best abilities. foreach (Ability ab in order) { for (int r = 0 ; r < best.Count ; r++) { if (best[r].KeyName == ab.KeyName) { results.Add(best[r]); best.RemoveAt(r); break; } } } return results; } /// <summary> /// Default Getter For Styles /// Return Styles depending on spec level /// </summary> /// <param name="living"></param> /// <returns></returns> public virtual List<Style> GetStylesForLiving(GameLiving living) { return GetStylesForLiving(living, GetSpecLevelForLiving(living)); } /// <summary> /// Getter For Styles with a "step" hint used to display future upgrade /// Return Styles depending on spec level /// </summary> /// <param name="living"></param> /// <param name="step">step is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> public virtual List<Style> PretendStylesForLiving(GameLiving living, int step) { return GetStylesForLiving(living, step); } /// <summary> /// Default Getter For Styles /// Return Styles depending on spec level /// </summary> /// <param name="living"></param> /// <param name="level">level is only used when called for pretending some level (for trainer display)</param> /// <returns></returns> protected virtual List<Style> GetStylesForLiving(GameLiving living, int level) { // Try with Class ID 0 if no class id styles int classid = 0; if (living is GamePlayer) { classid = ((GamePlayer)living).CharacterClass.ID; } List<Style> styles = null; if (classid == 0) { styles = SkillBase.GetStyleList(KeyName, classid); } else { styles = SkillBase.GetStyleList(KeyName, classid); if (styles.Count == 0) styles = SkillBase.GetStyleList(KeyName, 0); } // Select only enabled Styles and Order them return styles.Where(item => item.SpecLevelRequirement <= level) .OrderBy(item => item.SpecLevelRequirement) .ThenBy(item => item.ID).ToList(); } public virtual int GetSpecLevelForLiving(GameLiving living) { return Level; } #endregion } public class UntrainableSpecialization : Specialization { /// <summary> /// Default constructor /// </summary> public UntrainableSpecialization(string keyname, string displayname, ushort icon, int ID) : base(keyname, displayname, icon, ID) { } /// <summary> /// Is this Specialization Trainable ? /// </summary> public override bool Trainable { get { return false; } } } public class CareerSpecialization : UntrainableSpecialization { /// <summary> /// Default constructor /// </summary> public CareerSpecialization(string keyname, string displayname, ushort icon, int ID) : base(keyname, displayname, icon, ID) { } /// <summary> /// Can This Specialization be saved in Player record ? /// </summary> public override bool AllowSave { get { return false; } } /// <summary> /// Career level are always considered spec'ed up to user level /// </summary> /// <param name="living"></param> /// <returns></returns> public override int GetSpecLevelForLiving(GameLiving living) { return Math.Max(0, (int)living.Level); } } }
dudemanvox/Dawn-of-Light-Server
GameServer/gameutils/Specialization.cs
C#
gpl-2.0
13,792
<?php /** * @defgroup subscription */ /** * @file classes/subscription/InstitutionalSubscription.inc.php * * Copyright (c) 2013 Simon Fraser University Library * Copyright (c) 2003-2013 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @class InstitutionalSubscription * @ingroup subscription * @see InstitutionalSubscriptionDAO * * @brief Basic class describing an institutional subscription. */ import('classes.subscription.Subscription'); define('SUBSCRIPTION_IP_RANGE_RANGE', '-'); define('SUBSCRIPTION_IP_RANGE_WILDCARD', '*'); class InstitutionalSubscription extends Subscription { function InstitutionalSubscription() { parent::Subscription(); } // // Get/set methods // /** * Get the institution name of the institutionalSubscription. * @return string */ function getInstitutionName() { return $this->getData('institutionName'); } /** * Set the institution name of the institutionalSubscription. * @param $institutionName string */ function setInstitutionName($institutionName) { return $this->setData('institutionName', $institutionName); } /** * Get the mailing address of the institutionalSubscription. * @return string */ function getInstitutionMailingAddress() { return $this->getData('mailingAddress'); } /** * Set the mailing address of the institutionalSubscription. * @param $mailingAddress string */ function setInstitutionMailingAddress($mailingAddress) { return $this->setData('mailingAddress', $mailingAddress); } /** * Get institutionalSubscription domain string. * @return string */ function getDomain() { return $this->getData('domain'); } /** * Set institutionalSubscription domain string. * @param $domain string */ function setDomain($domain) { return $this->setData('domain', $domain); } /** * Get institutionalSubscription ip ranges. * @return array */ function getIPRanges() { return $this->getData('ipRanges'); } /** * Get institutionalSubscription ip ranges string. * @return string */ function getIPRangesString() { $ipRanges = $this->getData('ipRanges'); $numRanges = count($ipRanges); $ipRangesString = ''; for($i=0; $i<$numRanges; $i++) { $ipRangesString .= $ipRanges[$i]; if ( $i+1 < $numRanges) $ipRangesString .= '\n'; } return $ipRangesString; } /** * Set institutionalSubscription ip ranges. * @param ipRanges array */ function setIPRanges($ipRanges) { return $this->setData('ipRanges', $ipRanges); } /** * Check whether subscription is valid */ function isValid($domain, $IP, $check = SUBSCRIPTION_DATE_BOTH, $checkDate = null) { $subscriptionDao =& DAORegistry::getDAO('InstitutionalSubscriptionDAO'); return $subscriptionDao->isValidInstitutionalSubscription($domain, $IP, $this->getData('journalId'), $check, $checkDate); } } ?>
ubiquitypress/OJS-Draft-Editorial
classes/subscription/InstitutionalSubscription.inc.php
PHP
gpl-2.0
2,896
<?php ################################################## # # Copyright (c) 2004-2021 OIC Group, Inc. # # This file is part of Exponent # # Exponent 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. # # GPL: http://www.gnu.org/licenses/gpl.txt # ################################################## /** * Smarty {pop} block plugin * * Type: block<br> * Name: pop<br> * Purpose: Set up a pop block * * @param array $params based on expJavascript::panel() * 'id' to differentiate popups * 'width' width of popup, defaults to '300px' * 'type' id type of popup, defaults to 'info', also 'error' & 'alert' * 'buttons' text string of 2 button names separated by ':' * 'title' title of popup * 'close' should popup have a close button (x), defaults to true * 'trigger' what object to base event trigger on, defaults to 'selfpop' which displays when popup is ready * 'on' what 'event' to display popup, defaults to 'load', or 'click' if 'trigger' is set * 'onnogo' what url to browse to when the 'no' button is selected * 'onyesgo' what url to browse to when the 'yes' button is selected * 'fade' seconds duration of popup 'fade' in/out, defaults to false * 'modal' should the popup be 'modal', defaults to true * 'draggable' should the popup be 'draggable', defaults to false * * @param $content * @param \Smarty $smarty * @param $repeat * * @package Smarty-Plugins * @subpackage Block */ function smarty_block_pop($params,$content,&$smarty, &$repeat) { if($content){ $content = json_encode(str_replace("\n", '', str_replace("\r\n", '', trim($content)))); if (isset($params['icon'])) { $icon = $params['icon']; } else { $icon = 'file'; } $width = !empty($params['width']) ? $params['width'] : "800px"; echo '<a class="' . expTheme::buttonStyle() . '" href="#" id="' . $params['id'] . '">' . expTheme::iconStyle('file', $params['text']) . '</a>'; if (isset($params['type'])) { $type = $params['type']; } else { $type = ''; } $script = " $(document).ready(function(){ $('#".$params['id']."').click(function(event) { event.preventDefault(); var message = ".$content."; $.prompt(message, { title: '".$params['title']."', position: { width: '" . $width . "' }, classes: { title: '".$type."', }, buttons: {'".$params['buttons']."': true}, submit: function(e,v,m,f){ // use e.preventDefault() to prevent closing when needed or return false. } }); }); }); "; expJavascript::pushToFoot(array( "unique"=>'pop-'.$params['id'], "jquery"=>"jquery-impromptu", "content"=>$script, )); } } ?>
exponentcms/exponent-cms
framework/plugins/bootstrap/block.pop.php
PHP
gpl-2.0
3,419
<?php /*------------------------------------------- Taxonomies (if enabled) ---------------------------------------------*/ function cr_create_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( "name" => __( "Categories" ), "singular_name" => __( "Category" ), "search_items" => __( "Search Categories" ), "all_items" => __( "All Categories" ), "parent_item" => __( "Parent Category" ), "parent_item_colon" => __( "Parent Category:" ), "edit_item" => __( "Edit Category" ), "update_item" => __( "Update Category" ), "add_new_item" => __( "Add New Category" ), "new_item_name" => __( "New Category Name" ), "menu_name" => __( "Categories" ), ); $args = array( "hierarchical" => true, "labels" => $labels, "show_ui" => true, "show_admin_column" => true, "query_var" => true, "rewrite" => array( "slug" => "cust-review-cat" ), ); register_taxonomy( "cust-review-cat", "cust-review", $args ); } add_action( "init", "cr_create_taxonomies", 0 );
artarmstrong/cpt-customer-reviews
_inc/taxonomies.php
PHP
gpl-2.0
1,138
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" /* COPYING CONDITIONS NOTICE: This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation, and provided that the following conditions are met: * Redistributions of source code must retain this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below). * Redistributions in binary form must reproduce this COPYING CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the PATENT MARKING NOTICE (below), and the PATENT RIGHTS GRANT (below) in the documentation and/or other materials provided with the distribution. 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 NOTICE: TokuDB, Tokutek Fractal Tree Indexing Library. Copyright (C) 2007-2013 Tokutek, Inc. DISCLAIMER: 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. UNIVERSITY PATENT NOTICE: The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it. PATENT MARKING NOTICE: This software is covered by US Patent No. 8,185,551. This software is covered by US Patent No. 8,489,638. PATENT RIGHTS GRANT: "THIS IMPLEMENTATION" means the copyrightable works distributed by Tokutek as part of the Fractal Tree project. "PATENT CLAIMS" means the claims of patents that are owned or licensable by Tokutek, both currently or in the future; and that in the absence of this license would be infringed by THIS IMPLEMENTATION or by using or running THIS IMPLEMENTATION. "PATENT CHALLENGE" shall mean a challenge to the validity, patentability, enforceability and/or non-infringement of any of the PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS. Tokutek hereby grants to you, for the term and geographical scope of the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, transfer, and otherwise run, modify, and propagate the contents of THIS IMPLEMENTATION, where such license applies only to the PATENT CLAIMS. This grant does not include claims that would be infringed only as a consequence of further modifications of THIS IMPLEMENTATION. If you or your agent or licensee institute or order or agree to the institution of patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that THIS IMPLEMENTATION constitutes direct or contributory patent infringement, or inducement of patent infringement, then any rights granted to you under this License shall terminate as of the date such litigation is filed. If you or your agent or exclusive licensee institute or order or agree to the institution of a PATENT CHALLENGE, then Tokutek may terminate any rights granted to you under this License. */ #ident "Copyright (c) 2007-2013 Tokutek Inc. All rights reserved." #include <unistd.h> #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #include <sys/wait.h> #include <toku_race_tools.h> #include "toku_crash.h" #include "toku_atomic.h" enum { MAX_GDB_ARGS = 128 }; static void run_gdb(pid_t parent_pid, const char *gdb_path) { // 3 bytes per intbyte, null byte char pid_buf[sizeof(pid_t) * 3 + 1]; char exe_buf[sizeof(pid_buf) + sizeof("/proc//exe")]; // Get pid and path to executable. int n; n = snprintf(pid_buf, sizeof(pid_buf), "%d", parent_pid); invariant(n >= 0 && n < (int)sizeof(pid_buf)); n = snprintf(exe_buf, sizeof(exe_buf), "/proc/%d/exe", parent_pid); invariant(n >= 0 && n < (int)sizeof(exe_buf)); toku_dup2(2, 1); // redirect output to stderr // Arguments are not dynamic due to possible security holes. execlp(gdb_path, gdb_path, "--batch", "-n", "-ex", "thread", "-ex", "bt", "-ex", "bt full", "-ex", "thread apply all bt", "-ex", "thread apply all bt full", exe_buf, pid_buf, NULL); } static void intermediate_process(pid_t parent_pid, const char *gdb_path) { // Disable generating of core dumps #if defined(HAVE_SYS_PRCTL_H) prctl(PR_SET_DUMPABLE, 0, 0, 0); #endif pid_t worker_pid = fork(); if (worker_pid < 0) { perror("spawn gdb fork: "); goto failure; } if (worker_pid == 0) { // Child (debugger) run_gdb(parent_pid, gdb_path); // Normally run_gdb will not return. // In case it does, kill the process. goto failure; } else { pid_t timeout_pid = fork(); if (timeout_pid < 0) { perror("spawn timeout fork: "); kill(worker_pid, SIGKILL); goto failure; } if (timeout_pid == 0) { sleep(5); // Timeout of 5 seconds goto success; } else { pid_t exited_pid = wait(NULL); // Wait for first child to exit if (exited_pid == worker_pid) { // Kill slower child kill(timeout_pid, SIGKILL); goto success; } else if (exited_pid == timeout_pid) { // Kill slower child kill(worker_pid, SIGKILL); goto failure; // Timed out. } else { perror("error while waiting for gdb or timer to end: "); //Some failure. Kill everything. kill(timeout_pid, SIGKILL); kill(worker_pid, SIGKILL); goto failure; } } } success: _exit(EXIT_SUCCESS); failure: _exit(EXIT_FAILURE); } static void spawn_gdb(const char *gdb_path) { pid_t parent_pid = toku_os_getpid(); #if defined(HAVE_SYS_PRCTL_H) // On systems that require permission for the same user to ptrace, // give permission for this process and (more importantly) all its children to debug this process. prctl(PR_SET_PTRACER, parent_pid, 0, 0, 0); #endif fprintf(stderr, "Attempting to use gdb @[%s] on pid[%d]\n", gdb_path, parent_pid); fflush(stderr); int intermediate_pid = fork(); if (intermediate_pid < 0) { perror("spawn_gdb intermediate process fork: "); } else if (intermediate_pid == 0) { intermediate_process(parent_pid, gdb_path); } else { waitpid(intermediate_pid, NULL, 0); } } void toku_try_gdb_stack_trace(const char *gdb_path) { char default_gdb_path[] = "/usr/bin/gdb"; static bool started = false; if (RUNNING_ON_VALGRIND) { fprintf(stderr, "gdb stack trace skipped due to running under valgrind\n"); fflush(stderr); } else if (toku_sync_bool_compare_and_swap(&started, false, true)) { spawn_gdb(gdb_path ? gdb_path : default_gdb_path); } }
oscarlab/betrfs
portability/toku_crash.cc
C++
gpl-2.0
7,751
<?php class m140409_035700_supplier_products_add_options_field extends CDbMigration { public function up() { $tablePrefix = SnapUtil::config('boxomatic/tablePrefix'); $this->addColumn($tablePrefix.'supplier_products','quantity_options','string'); } public function down() { echo "m140409_035700_supplier_products_add_options_field does not support migration down.\n"; return false; } /* // Use safeUp/safeDown to do migration with transaction public function safeUp() { } public function safeDown() { } */ }
snapfrozen/boxomatic
migrations/m140409_035700_supplier_products_add_options_field.php
PHP
gpl-2.0
534
package com.aoe.sms.client.impl.emay.sp; public class ResultInfo { private String code; private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "ResultInfo [code=" + code + ", message=" + message + "]"; } }
joeyliu616/business-atom
sms/sms-client-impl-emay/src/main/java/com/aoe/sms/client/impl/emay/sp/ResultInfo.java
Java
gpl-2.0
529
#include <unistd.h> #include <string.h> #include <signal.h> #include <sys/wait.h> #include <errno.h> #include <vdr/tools.h> #include <vdr/thread.h> #include "extpipe.h" cExtPipe::cExtPipe(void) { pid = -1; f_stderr = -1; f_stdout= -1; } cExtPipe::~cExtPipe() { int status; Close(status); } bool cExtPipe::Open(const char *Command) { int fd_stdout[2]; int fd_stderr[2]; if (pipe(fd_stdout) < 0) { LOG_ERROR; return false; } if (pipe(fd_stderr) < 0) { close(fd_stdout[0]); close(fd_stdout[1]); LOG_ERROR; return false; } if ((pid = fork()) < 0) // fork failed { LOG_ERROR; close(fd_stdout[0]); close(fd_stdout[1]); close(fd_stderr[0]); close(fd_stderr[1]); return false; } if (pid > 0) // parent process { close(fd_stdout[1]); // close write fd, we need only read fd close(fd_stderr[1]); // close write fd, we need only read fd f_stdout = fd_stdout[0]; f_stderr = fd_stderr[0]; return true; } else // child process { close(fd_stdout[0]); // close read fd, we need only write fd close(fd_stderr[0]); // close read fd, we need only write fd if (dup2(fd_stdout[1], STDOUT_FILENO) == -1) // now redirect { LOG_ERROR; close(fd_stderr[1]); close(fd_stdout[1]); _exit(-1); } if (dup2(fd_stderr[1], STDERR_FILENO) == -1) // now redirect { LOG_ERROR; close(fd_stderr[1]); close(fd_stdout[1]); _exit(-1); } int MaxPossibleFileDescriptors = getdtablesize(); for (int i = STDERR_FILENO + 1; i < MaxPossibleFileDescriptors; i++) close(i); //close all dup'ed filedescriptors if (execl("/bin/sh", "sh", "-c", Command, NULL) == -1) { LOG_ERROR_STR(Command); close(fd_stderr[1]); close(fd_stdout[1]); _exit(-1); } _exit(0); } } int cExtPipe::Close(int &status) { int ret = -1; if (f_stderr!=-1) { close(f_stderr); f_stderr = -1; } if (f_stdout!=-1) { close(f_stdout); f_stdout=-1; } if (pid > 0) { int i = 5; while (i > 0) { ret = waitpid(pid, &status, WNOHANG); if (ret < 0) { if (errno != EINTR && errno != ECHILD) { LOG_ERROR; break; } else if (errno == ECHILD) { ret = pid; break; } } else if (ret == pid) break; i--; cCondWait::SleepMs(100); } if (!i) { kill(pid, SIGKILL); ret = -1; } else if (ret == -1 || !WIFEXITED(status)) ret = -1; pid = -1; } return ret; }
kersten/vdr-plugin-xmltv2vdr
extpipe.cpp
C++
gpl-2.0
3,129
/* * Copyright 1999-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /** * */ import java.rmi.Remote; import java.rmi.RemoteException; /* * Interface with methods to exercise RMI parameter marshalling * and unmarshalling. */ interface CheckUnmarshal extends java.rmi.Remote { public PoisonPill getPoisonPill() throws RemoteException; public Object ping() throws RemoteException; public void passRuntimeExceptionParameter( RuntimeExceptionParameter rep) throws RemoteException; }
TheTypoMaster/Scaper
openjdk/jdk/test/java/rmi/server/Unmarshal/checkUnmarshalOnStopThread/CheckUnmarshall.java
Java
gpl-2.0
1,540
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.test.inlining; import jdk.internal.jvmci.code.*; import com.oracle.graal.debug.*; import com.oracle.graal.debug.Debug.*; import jdk.internal.jvmci.meta.*; import org.junit.*; import com.oracle.graal.compiler.test.*; import com.oracle.graal.graph.*; import com.oracle.graal.graphbuilderconf.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.StructuredGraph.AllowAssumptions; import com.oracle.graal.phases.*; import com.oracle.graal.phases.common.*; import com.oracle.graal.phases.common.inlining.*; import com.oracle.graal.phases.tiers.*; public class InliningTest extends GraalCompilerTest { @Test public void testInvokeStaticInlining() { assertInlined(getGraph("invokeStaticSnippet", false)); assertInlined(getGraph("invokeStaticOnInstanceSnippet", false)); } @SuppressWarnings("all") public static Boolean invokeStaticSnippet(boolean value) { return Boolean.valueOf(value); } @SuppressWarnings("all") public static Boolean invokeStaticOnInstanceSnippet(Boolean obj, boolean value) { return obj.valueOf(value); } @Test public void testStaticBindableInlining() { assertInlined(getGraph("invokeConstructorSnippet", false)); assertInlined(getGraph("invokeFinalMethodSnippet", false)); assertInlined(getGraph("invokeMethodOnFinalClassSnippet", false)); assertInlined(getGraph("invokeMethodOnStaticFinalFieldSnippet", false)); } @Ignore("would need read elimination/EA before inlining") @Test public void testDependentStaticBindableInlining() { assertInlined(getGraph("invokeMethodOnFinalFieldSnippet", false)); assertInlined(getGraph("invokeMethodOnFieldSnippet", false)); } @Test public void testStaticBindableInliningIP() { assertManyMethodInfopoints(assertInlined(getGraph("invokeConstructorSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeFinalMethodSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFinalClassSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnStaticFinalFieldSnippet", true))); } @Ignore("would need read elimination/EA before inlining") @Test public void testDependentStaticBindableInliningIP() { assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFinalFieldSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeMethodOnFieldSnippet", true))); } @SuppressWarnings("all") public static Object invokeConstructorSnippet(int value) { return new SuperClass(value); } @SuppressWarnings("all") public static int invokeFinalMethodSnippet(SuperClass superClass, SubClassA subClassA, FinalSubClass finalSubClass) { return superClass.publicFinalMethod() + subClassA.publicFinalMethod() + finalSubClass.publicFinalMethod() + superClass.protectedFinalMethod() + subClassA.protectedFinalMethod() + finalSubClass.protectedFinalMethod(); } @SuppressWarnings("all") public static int invokeMethodOnFinalClassSnippet(FinalSubClass finalSubClass) { return finalSubClass.publicFinalMethod() + finalSubClass.publicNotOverriddenMethod() + finalSubClass.publicOverriddenMethod() + finalSubClass.protectedFinalMethod() + finalSubClass.protectedNotOverriddenMethod() + finalSubClass.protectedOverriddenMethod(); } @SuppressWarnings("all") public static int invokeMethodOnStaticFinalFieldSnippet() { return StaticFinalFields.NumberStaticFinalField.intValue() + StaticFinalFields.SuperClassStaticFinalField.publicOverriddenMethod() + StaticFinalFields.FinalSubClassStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SingleImplementorStaticFinalField.publicOverriddenMethod() + StaticFinalFields.MultipleImplementorsStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SubClassAStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SubClassBStaticFinalField.publicOverriddenMethod() + StaticFinalFields.SubClassCStaticFinalField.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeMethodOnFinalFieldSnippet() { FinalFields fields = new FinalFields(); return fields.numberFinalField.intValue() + fields.superClassFinalField.publicOverriddenMethod() + fields.finalSubClassFinalField.publicOverriddenMethod() + fields.singleImplementorFinalField.publicOverriddenMethod() + fields.multipleImplementorsFinalField.publicOverriddenMethod() + fields.subClassAFinalField.publicOverriddenMethod() + fields.subClassBFinalField.publicOverriddenMethod() + fields.subClassCFinalField.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeMethodOnFieldSnippet() { Fields fields = new Fields(); return fields.numberField.intValue() + fields.superClassField.publicOverriddenMethod() + fields.finalSubClassField.publicOverriddenMethod() + fields.singleImplementorField.publicOverriddenMethod() + fields.multipleImplementorsField.publicOverriddenMethod() + fields.subClassAField.publicOverriddenMethod() + fields.subClassBField.publicOverriddenMethod() + fields.subClassCField.publicOverriddenMethod(); } public interface Attributes { int getLength(); } public class NullAttributes implements Attributes { @Override public int getLength() { return 0; } } public class TenAttributes implements Attributes { @Override public int getLength() { return 10; } } public int getAttributesLength(Attributes a) { return a.getLength(); } @Test public void testGuardedInline() { NullAttributes nullAttributes = new NullAttributes(); for (int i = 0; i < 10000; i++) { getAttributesLength(nullAttributes); } getAttributesLength(new TenAttributes()); test("getAttributesLength", nullAttributes); test("getAttributesLength", (Object) null); } @Test public void testClassHierarchyAnalysis() { assertInlined(getGraph("invokeLeafClassMethodSnippet", false)); assertInlined(getGraph("invokeConcreteMethodSnippet", false)); assertInlined(getGraph("invokeSingleImplementorInterfaceSnippet", false)); // assertInlined(getGraph("invokeConcreteInterfaceMethodSnippet", false)); assertNotInlined(getGraph("invokeOverriddenPublicMethodSnippet", false)); assertNotInlined(getGraph("invokeOverriddenProtectedMethodSnippet", false)); assertNotInlined(getGraph("invokeOverriddenInterfaceMethodSnippet", false)); } @Test public void testClassHierarchyAnalysisIP() { assertManyMethodInfopoints(assertInlined(getGraph("invokeLeafClassMethodSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeConcreteMethodSnippet", true))); assertManyMethodInfopoints(assertInlined(getGraph("invokeSingleImplementorInterfaceSnippet", true))); //@formatter:off // assertInlineInfopoints(assertInlined(getGraph("invokeConcreteInterfaceMethodSnippet", true))); //@formatter:on assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenPublicMethodSnippet", true))); assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenProtectedMethodSnippet", true))); assertFewMethodInfopoints(assertNotInlined(getGraph("invokeOverriddenInterfaceMethodSnippet", true))); } @SuppressWarnings("all") public static int invokeLeafClassMethodSnippet(SubClassA subClassA) { return subClassA.publicFinalMethod() + subClassA.publicNotOverriddenMethod() + subClassA.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeConcreteMethodSnippet(SuperClass superClass) { return superClass.publicNotOverriddenMethod() + superClass.protectedNotOverriddenMethod(); } @SuppressWarnings("all") public static int invokeSingleImplementorInterfaceSnippet(SingleImplementorInterface testInterface) { return testInterface.publicNotOverriddenMethod() + testInterface.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeConcreteInterfaceMethodSnippet(MultipleImplementorsInterface testInterface) { return testInterface.publicNotOverriddenMethod(); } @SuppressWarnings("all") public static int invokeOverriddenInterfaceMethodSnippet(MultipleImplementorsInterface testInterface) { return testInterface.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeOverriddenPublicMethodSnippet(SuperClass superClass) { return superClass.publicOverriddenMethod(); } @SuppressWarnings("all") public static int invokeOverriddenProtectedMethodSnippet(SuperClass superClass) { return superClass.protectedOverriddenMethod(); } private StructuredGraph getGraph(final String snippet, final boolean eagerInfopointMode) { try (Scope s = Debug.scope("InliningTest", new DebugDumpScope(snippet))) { ResolvedJavaMethod method = getResolvedJavaMethod(snippet); StructuredGraph graph = eagerInfopointMode ? parseDebug(method, AllowAssumptions.YES) : parseEager(method, AllowAssumptions.YES); PhaseSuite<HighTierContext> graphBuilderSuite = eagerInfopointMode ? getCustomGraphBuilderSuite(GraphBuilderConfiguration.getFullDebugDefault(getDefaultGraphBuilderPlugins())) : getDefaultGraphBuilderSuite(); HighTierContext context = new HighTierContext(getProviders(), graphBuilderSuite, OptimisticOptimizations.ALL); Debug.dump(graph, "Graph"); new CanonicalizerPhase().apply(graph, context); new InliningPhase(new CanonicalizerPhase()).apply(graph, context); Debug.dump(graph, "Graph"); new CanonicalizerPhase().apply(graph, context); new DeadCodeEliminationPhase().apply(graph); return graph; } catch (Throwable e) { throw Debug.handle(e); } } private static StructuredGraph assertInlined(StructuredGraph graph) { return assertNotInGraph(graph, Invoke.class); } private static StructuredGraph assertNotInlined(StructuredGraph graph) { return assertInGraph(graph, Invoke.class); } private static StructuredGraph assertNotInGraph(StructuredGraph graph, Class<?> clazz) { for (Node node : graph.getNodes()) { if (clazz.isInstance(node)) { fail(node.toString()); } } return graph; } private static StructuredGraph assertInGraph(StructuredGraph graph, Class<?> clazz) { for (Node node : graph.getNodes()) { if (clazz.isInstance(node)) { return graph; } } fail("Graph does not contain a node of class " + clazz.getName()); return graph; } private static int[] countMethodInfopoints(StructuredGraph graph) { int start = 0; int end = 0; for (FullInfopointNode ipn : graph.getNodes().filter(FullInfopointNode.class)) { if (ipn.getReason() == InfopointReason.METHOD_START) { ++start; } else if (ipn.getReason() == InfopointReason.METHOD_END) { ++end; } } return new int[]{start, end}; } private static StructuredGraph assertManyMethodInfopoints(StructuredGraph graph) { int[] counts = countMethodInfopoints(graph); if (counts[0] <= 1 || counts[1] <= 1) { fail(String.format("Graph contains too few required method boundary infopoints: %d starts, %d ends.", counts[0], counts[1])); } return graph; } private static StructuredGraph assertFewMethodInfopoints(StructuredGraph graph) { int[] counts = countMethodInfopoints(graph); if (counts[0] > 1 || counts[1] > 1) { fail(String.format("Graph contains too many method boundary infopoints: %d starts, %d ends.", counts[0], counts[1])); } return graph; } // some interfaces and classes for testing private interface MultipleImplementorsInterface { int publicNotOverriddenMethod(); int publicOverriddenMethod(); } private interface SingleImplementorInterface { int publicNotOverriddenMethod(); int publicOverriddenMethod(); } private static class SuperClass implements MultipleImplementorsInterface { protected int value; public SuperClass(int value) { this.value = value; } public int publicNotOverriddenMethod() { return value; } public int publicOverriddenMethod() { return value; } protected int protectedNotOverriddenMethod() { return value; } protected int protectedOverriddenMethod() { return value; } public final int publicFinalMethod() { return value + 255; } protected final int protectedFinalMethod() { return value + 255; } } private static class SubClassA extends SuperClass implements SingleImplementorInterface { public SubClassA(int value) { super(value); } @Override public int publicOverriddenMethod() { return value + 2; } @Override protected int protectedOverriddenMethod() { return value * 2; } } private static class SubClassB extends SuperClass { public SubClassB(int value) { super(value); } @Override public int publicOverriddenMethod() { return value + 3; } @Override protected int protectedOverriddenMethod() { return value * 3; } } private static class SubClassC extends SuperClass { public SubClassC(int value) { super(value); } @Override public int publicOverriddenMethod() { return value + 4; } @Override protected int protectedOverriddenMethod() { return value * 4; } } private static final class FinalSubClass extends SuperClass { public FinalSubClass(int value) { super(value); } @Override public int publicOverriddenMethod() { return value + 5; } @Override protected int protectedOverriddenMethod() { return value * 5; } } private static final class StaticFinalFields { private static final Number NumberStaticFinalField = new Integer(1); private static final SuperClass SuperClassStaticFinalField = new SubClassA(2); private static final FinalSubClass FinalSubClassStaticFinalField = new FinalSubClass(3); private static final SingleImplementorInterface SingleImplementorStaticFinalField = new SubClassA(4); private static final MultipleImplementorsInterface MultipleImplementorsStaticFinalField = new SubClassC(5); private static final SubClassA SubClassAStaticFinalField = new SubClassA(6); private static final SubClassB SubClassBStaticFinalField = new SubClassB(7); private static final SubClassC SubClassCStaticFinalField = new SubClassC(8); } private static final class FinalFields { private final Number numberFinalField = new Integer(1); private final SuperClass superClassFinalField = new SubClassA(2); private final FinalSubClass finalSubClassFinalField = new FinalSubClass(3); private final SingleImplementorInterface singleImplementorFinalField = new SubClassA(4); private final MultipleImplementorsInterface multipleImplementorsFinalField = new SubClassC(5); private final SubClassA subClassAFinalField = new SubClassA(6); private final SubClassB subClassBFinalField = new SubClassB(7); private final SubClassC subClassCFinalField = new SubClassC(8); } private static final class Fields { private Number numberField = new Integer(1); private SuperClass superClassField = new SubClassA(2); private FinalSubClass finalSubClassField = new FinalSubClass(3); private SingleImplementorInterface singleImplementorField = new SubClassA(4); private MultipleImplementorsInterface multipleImplementorsField = new SubClassC(5); private SubClassA subClassAField = new SubClassA(6); private SubClassB subClassBField = new SubClassB(7); private SubClassC subClassCField = new SubClassC(8); } }
mur47x111/GraalVM
graal/com.oracle.graal.compiler.test/src/com/oracle/graal/compiler/test/inlining/InliningTest.java
Java
gpl-2.0
18,211
<?php return array( 'version' => '0.9.4.1', 'cluster.messagebus.debug' => false, 'cluster.messagebus.enabled' => false, 'cluster.messagebus.sns.region' => '', 'cluster.messagebus.sns.api_key' => '', 'cluster.messagebus.sns.api_secret' => '', 'cluster.messagebus.sns.topic_arn' => '', 'dbcache.debug' => false, 'dbcache.enabled' => false, 'dbcache.engine' => 'file', 'dbcache.file.gc' => 3600, 'dbcache.file.locking' => false, 'dbcache.lifetime' => 180, 'dbcache.memcached.persistant' => true, 'dbcache.memcached.servers' => array( 0 => '127.0.0.1:11211', ), 'dbcache.reject.cookie' => array( ), 'dbcache.reject.logged' => true, 'dbcache.reject.sql' => array( 0 => 'gdsr_', 1 => 'wp_rg_', 2 => '_wp_session_', ), 'dbcache.reject.uri' => array( ), 'dbcache.reject.words' => array( 0 => '^\\s*insert\\b', 1 => '^\\s*delete\\b', 2 => '^\\s*update\\b', 3 => '^\\s*replace\\b', 4 => '^\\s*create\\b', 5 => '^\\s*alter\\b', 6 => '^\\s*show\\b', 7 => '^\\s*set\\b', 8 => '\\bautoload\\s+=\\s+\'yes\'', 9 => '\\bsql_calc_found_rows\\b', 10 => '\\bfound_rows\\(\\)', 11 => '\\bw3tc_request_data\\b', ), 'objectcache.enabled' => false, 'objectcache.debug' => false, 'objectcache.engine' => 'file', 'objectcache.file.gc' => 3600, 'objectcache.file.locking' => false, 'objectcache.memcached.servers' => array( 0 => '127.0.0.1:11211', ), 'objectcache.memcached.persistant' => true, 'objectcache.groups.global' => array( 0 => 'users', 1 => 'userlogins', 2 => 'usermeta', 3 => 'user_meta', 4 => 'site-transient', 5 => 'site-options', 6 => 'site-lookup', 7 => 'blog-lookup', 8 => 'blog-details', 9 => 'rss', 10 => 'global-posts', ), 'objectcache.groups.nonpersistent' => array( 0 => 'comment', 1 => 'counts', 2 => 'plugins', ), 'objectcache.lifetime' => 180, 'objectcache.purge.all' => false, 'fragmentcache.enabled' => false, 'fragmentcache.debug' => false, 'fragmentcache.engine' => 'file', 'fragmentcache.file.gc' => 3600, 'fragmentcache.file.locking' => false, 'fragmentcache.memcached.servers' => array( 0 => '127.0.0.1:11211', ), 'fragmentcache.memcached.persistant' => true, 'fragmentcache.lifetime' => 180, 'fragmentcache.groups' => array( ), 'pgcache.enabled' => false, 'pgcache.comment_cookie_ttl' => 1800, 'pgcache.debug' => false, 'pgcache.engine' => 'file_generic', 'pgcache.file.gc' => 3600, 'pgcache.file.nfs' => false, 'pgcache.file.locking' => false, 'pgcache.lifetime' => 3600, 'pgcache.memcached.servers' => array( 0 => '127.0.0.1:11211', ), 'pgcache.memcached.persistant' => true, 'pgcache.check.domain' => false, 'pgcache.cache.query' => true, 'pgcache.cache.home' => true, 'pgcache.cache.feed' => false, 'pgcache.cache.nginx_handle_xml' => false, 'pgcache.cache.ssl' => false, 'pgcache.cache.404' => false, 'pgcache.cache.flush' => false, 'pgcache.cache.headers' => array( 0 => 'Last-Modified', 1 => 'Content-Type', 2 => 'X-Pingback', 3 => 'P3P', ), 'pgcache.compatibility' => false, 'pgcache.remove_charset' => false, 'pgcache.accept.uri' => array( 0 => 'sitemap(_index)?\\.xml(\\.gz)?', 1 => '([a-z0-9_\\-]+)?sitemap\\.xsl', 2 => '[a-z0-9_\\-]+-sitemap([0-9]+)?\\.xml(\\.gz)?', ), 'pgcache.accept.files' => array( 0 => 'wp-comments-popup.php', 1 => 'wp-links-opml.php', 2 => 'wp-locations.php', ), 'pgcache.accept.qs' => array( ), 'pgcache.reject.front_page' => false, 'pgcache.reject.logged' => true, 'pgcache.reject.logged_roles' => false, 'pgcache.reject.roles' => array( ), 'pgcache.reject.uri' => array( 0 => 'wp-.*\\.php', 1 => 'index\\.php', ), 'pgcache.reject.ua' => array( ), 'pgcache.reject.cookie' => array( 0 => 'wptouch_switch_toggle', ), 'pgcache.reject.request_head' => false, 'pgcache.purge.front_page' => false, 'pgcache.purge.home' => true, 'pgcache.purge.post' => true, 'pgcache.purge.comments' => false, 'pgcache.purge.author' => false, 'pgcache.purge.terms' => false, 'pgcache.purge.archive.daily' => false, 'pgcache.purge.archive.monthly' => false, 'pgcache.purge.archive.yearly' => false, 'pgcache.purge.feed.blog' => true, 'pgcache.purge.feed.comments' => false, 'pgcache.purge.feed.author' => false, 'pgcache.purge.feed.terms' => false, 'pgcache.purge.feed.types' => array( 0 => 'rss2', ), 'pgcache.purge.postpages_limit' => 10, 'pgcache.purge.pages' => array( ), 'pgcache.purge.sitemap_regex' => '([a-z0-9_\\-]*?)sitemap([a-z0-9_\\-]*)?\\.xml', 'pgcache.prime.enabled' => false, 'pgcache.prime.interval' => 900, 'pgcache.prime.limit' => 10, 'pgcache.prime.sitemap' => '', 'pgcache.prime.post.enabled' => false, 'minify.enabled' => false, 'minify.auto' => true, 'minify.debug' => false, 'minify.engine' => 'file', 'minify.file.gc' => 86400, 'minify.file.nfs' => false, 'minify.file.locking' => false, 'minify.memcached.servers' => array( 0 => '127.0.0.1:11211', ), 'minify.memcached.persistant' => true, 'minify.rewrite' => true, 'minify.options' => array( ), 'minify.symlinks' => array( ), 'minify.lifetime' => 86400, 'minify.upload' => true, 'minify.html.enable' => false, 'minify.html.engine' => 'html', 'minify.html.reject.feed' => false, 'minify.html.inline.css' => false, 'minify.html.inline.js' => false, 'minify.html.strip.crlf' => false, 'minify.html.comments.ignore' => array( 0 => 'google_ad_', 1 => 'RSPEAK_', ), 'minify.css.enable' => true, 'minify.css.engine' => 'css', 'minify.css.combine' => false, 'minify.css.strip.comments' => false, 'minify.css.strip.crlf' => false, 'minify.css.imports' => '', 'minify.css.groups' => array( ), 'minify.js.enable' => true, 'minify.js.engine' => 'js', 'minify.js.combine.header' => false, 'minify.js.header.embed_type' => 'blocking', 'minify.js.combine.body' => false, 'minify.js.body.embed_type' => 'blocking', 'minify.js.combine.footer' => false, 'minify.js.footer.embed_type' => 'blocking', 'minify.js.strip.comments' => false, 'minify.js.strip.crlf' => false, 'minify.js.groups' => array( ), 'minify.yuijs.path.java' => 'java', 'minify.yuijs.path.jar' => 'yuicompressor.jar', 'minify.yuijs.options.line-break' => 5000, 'minify.yuijs.options.nomunge' => false, 'minify.yuijs.options.preserve-semi' => false, 'minify.yuijs.options.disable-optimizations' => false, 'minify.yuicss.path.java' => 'java', 'minify.yuicss.path.jar' => 'yuicompressor.jar', 'minify.yuicss.options.line-break' => 5000, 'minify.ccjs.path.java' => 'java', 'minify.ccjs.path.jar' => 'compiler.jar', 'minify.ccjs.options.compilation_level' => 'SIMPLE_OPTIMIZATIONS', 'minify.ccjs.options.formatting' => '', 'minify.csstidy.options.remove_bslash' => true, 'minify.csstidy.options.compress_colors' => true, 'minify.csstidy.options.compress_font-weight' => true, 'minify.csstidy.options.lowercase_s' => false, 'minify.csstidy.options.optimise_shorthands' => 1, 'minify.csstidy.options.remove_last_;' => false, 'minify.csstidy.options.case_properties' => 1, 'minify.csstidy.options.sort_properties' => false, 'minify.csstidy.options.sort_selectors' => false, 'minify.csstidy.options.merge_selectors' => 2, 'minify.csstidy.options.discard_invalid_properties' => false, 'minify.csstidy.options.css_level' => 'CSS2.1', 'minify.csstidy.options.preserve_css' => false, 'minify.csstidy.options.timestamp' => false, 'minify.csstidy.options.template' => 'default', 'minify.htmltidy.options.clean' => false, 'minify.htmltidy.options.hide-comments' => true, 'minify.htmltidy.options.wrap' => 0, 'minify.reject.logged' => false, 'minify.reject.ua' => array( ), 'minify.reject.uri' => array( ), 'minify.reject.files.js' => array( ), 'minify.reject.files.css' => array( ), 'minify.cache.files' => array( 0 => 'https://ajax.googleapis.com', ), 'cdn.enabled' => false, 'cdn.debug' => false, 'cdn.engine' => 'maxcdn', 'cdn.uploads.enable' => true, 'cdn.includes.enable' => true, 'cdn.includes.files' => '*.css;*.js;*.gif;*.png;*.jpg;*.xml', 'cdn.theme.enable' => true, 'cdn.theme.files' => '*.css;*.js;*.gif;*.png;*.jpg;*.ico;*.ttf;*.otf,*.woff,*.less', 'cdn.minify.enable' => true, 'cdn.custom.enable' => true, 'cdn.custom.files' => array( 0 => 'favicon.ico', 1 => '{wp_content_dir}/gallery/*', 2 => '{wp_content_dir}/uploads/avatars/*', 3 => '{plugins_dir}/wordpress-seo/css/xml-sitemap.xsl', 4 => '{plugins_dir}/wp-minify/min*', 5 => '{plugins_dir}/*.js', 6 => '{plugins_dir}/*.css', 7 => '{plugins_dir}/*.gif', 8 => '{plugins_dir}/*.jpg', 9 => '{plugins_dir}/*.png', ), 'cdn.import.external' => false, 'cdn.import.files' => '', 'cdn.queue.interval' => 900, 'cdn.queue.limit' => 25, 'cdn.force.rewrite' => false, 'cdn.autoupload.enabled' => false, 'cdn.autoupload.interval' => 3600, 'cdn.canonical_header' => false, 'cdn.ftp.host' => '', 'cdn.ftp.user' => '', 'cdn.ftp.pass' => '', 'cdn.ftp.path' => '', 'cdn.ftp.pasv' => false, 'cdn.ftp.domain' => array( ), 'cdn.ftp.ssl' => 'auto', 'cdn.s3.key' => '', 'cdn.s3.secret' => '', 'cdn.s3.bucket' => '', 'cdn.s3.cname' => array( ), 'cdn.s3.ssl' => 'auto', 'cdn.cf.key' => '', 'cdn.cf.secret' => '', 'cdn.cf.bucket' => '', 'cdn.cf.id' => '', 'cdn.cf.cname' => array( ), 'cdn.cf.ssl' => 'auto', 'cdn.cf2.key' => '', 'cdn.cf2.secret' => '', 'cdn.cf2.id' => '', 'cdn.cf2.cname' => array( ), 'cdn.cf2.ssl' => '', 'cdn.rscf.user' => '', 'cdn.rscf.key' => '', 'cdn.rscf.location' => 'us', 'cdn.rscf.container' => '', 'cdn.rscf.cname' => array( ), 'cdn.rscf.ssl' => 'auto', 'cdn.azure.user' => '', 'cdn.azure.key' => '', 'cdn.azure.container' => '', 'cdn.azure.cname' => array( ), 'cdn.azure.ssl' => 'auto', 'cdn.mirror.domain' => array( ), 'cdn.mirror.ssl' => 'auto', 'cdn.netdna.alias' => '', 'cdn.netdna.consumerkey' => '', 'cdn.netdna.consumersecret' => '', 'cdn.netdna.authorization_key' => '', 'cdn.netdna.domain' => array( ), 'cdn.netdna.ssl' => 'auto', 'cdn.netdna.zone_id' => 0, 'cdn.maxcdn.authorization_key' => '', 'cdn.maxcdn.domain' => array( ), 'cdn.maxcdn.ssl' => 'auto', 'cdn.maxcdn.zone_id' => 0, 'cdn.cotendo.username' => '', 'cdn.cotendo.password' => '', 'cdn.cotendo.zones' => array( ), 'cdn.cotendo.domain' => array( ), 'cdn.cotendo.ssl' => 'auto', 'cdn.akamai.username' => '', 'cdn.akamai.password' => '', 'cdn.akamai.email_notification' => array( ), 'cdn.akamai.action' => 'invalidate', 'cdn.akamai.zone' => 'production', 'cdn.akamai.domain' => array( ), 'cdn.akamai.ssl' => 'auto', 'cdn.edgecast.account' => '', 'cdn.edgecast.token' => '', 'cdn.edgecast.domain' => array( ), 'cdn.edgecast.ssl' => 'auto', 'cdn.att.account' => '', 'cdn.att.token' => '', 'cdn.att.domain' => array( ), 'cdn.att.ssl' => 'auto', 'cdn.reject.admins' => false, 'cdn.reject.logged_roles' => false, 'cdn.reject.roles' => array( ), 'cdn.reject.ua' => array( ), 'cdn.reject.uri' => array( ), 'cdn.reject.files' => array( 0 => '{uploads_dir}/wpcf7_captcha/*', 1 => '{uploads_dir}/imagerotator.swf', 2 => '{plugins_dir}/wp-fb-autoconnect/facebook-platform/channel.html', ), 'cdn.reject.ssl' => false, 'cdncache.enabled' => false, 'varnish.enabled' => false, 'varnish.debug' => false, 'varnish.servers' => array( ), 'browsercache.enabled' => true, 'browsercache.no404wp' => false, 'browsercache.no404wp.exceptions' => array( 0 => 'robots\\.txt', 1 => '[a-z0-9_\\-]*sitemap[a-z0-9_\\-]*\\.(xml|xsl|html)(\\.gz)?', ), 'browsercache.cssjs.last_modified' => true, 'browsercache.cssjs.compression' => true, 'browsercache.cssjs.expires' => false, 'browsercache.cssjs.lifetime' => 31536000, 'browsercache.cssjs.nocookies' => false, 'browsercache.cssjs.cache.control' => false, 'browsercache.cssjs.cache.policy' => 'cache_public_maxage', 'browsercache.cssjs.etag' => false, 'browsercache.cssjs.w3tc' => false, 'browsercache.cssjs.replace' => false, 'browsercache.html.compression' => true, 'browsercache.html.last_modified' => true, 'browsercache.html.expires' => false, 'browsercache.html.lifetime' => 3600, 'browsercache.html.cache.control' => false, 'browsercache.html.cache.policy' => 'cache_public_maxage', 'browsercache.html.etag' => false, 'browsercache.html.w3tc' => false, 'browsercache.html.replace' => false, 'browsercache.other.last_modified' => true, 'browsercache.other.compression' => true, 'browsercache.other.expires' => false, 'browsercache.other.lifetime' => 31536000, 'browsercache.other.nocookies' => false, 'browsercache.other.cache.control' => false, 'browsercache.other.cache.policy' => 'cache_public_maxage', 'browsercache.other.etag' => false, 'browsercache.other.w3tc' => false, 'browsercache.other.replace' => false, 'browsercache.timestamp' => '', 'browsercache.replace.exceptions' => array( ), 'mobile.enabled' => false, 'mobile.rgroups' => array( 'high' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'agents' => array( 0 => 'acer\\ s100', 1 => 'android', 2 => 'archos5', 3 => 'bada', 4 => 'bb10', 5 => 'blackberry9500', 6 => 'blackberry9530', 7 => 'blackberry9550', 8 => 'blackberry\\ 9800', 9 => 'cupcake', 10 => 'docomo\\ ht\\-03a', 11 => 'dream', 12 => 'froyo', 13 => 'googlebot-mobile', 14 => 'htc\\ hero', 15 => 'htc\\ magic', 16 => 'htc_dream', 17 => 'htc_magic', 18 => 'iemobile/7.0', 19 => 'incognito', 20 => 'ipad', 21 => 'iphone', 22 => 'ipod', 23 => 'kindle', 24 => 'lg\\-gw620', 25 => 'liquid\\ build', 26 => 'maemo', 27 => 'mot\\-mb200', 28 => 'mot\\-mb300', 29 => 'nexus\\ one', 30 => 'nexus\\ 7', 31 => 'opera\\ mini', 32 => 's8000', 33 => 'samsung\\-s8000', 34 => 'series60.*webkit', 35 => 'series60/5\\.0', 36 => 'sonyericssone10', 37 => 'sonyericssonu20', 38 => 'sonyericssonx10', 39 => 't\\-mobile\\ mytouch\\ 3g', 40 => 't\\-mobile\\ opal', 41 => 'tattoo', 42 => 'touch', 43 => 'webmate', 44 => 'webos', ), ), 'low' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'agents' => array( 0 => '2\\.0\\ mmp', 1 => '240x320', 2 => 'alcatel', 3 => 'amoi', 4 => 'asus', 5 => 'au\\-mic', 6 => 'audiovox', 7 => 'avantgo', 8 => 'benq', 9 => 'bird', 10 => 'blackberry', 11 => 'blazer', 12 => 'cdm', 13 => 'cellphone', 14 => 'danger', 15 => 'ddipocket', 16 => 'docomo', 17 => 'dopod', 18 => 'elaine/3\\.0', 19 => 'ericsson', 20 => 'eudoraweb', 21 => 'fly', 22 => 'haier', 23 => 'hiptop', 24 => 'hp\\.ipaq', 25 => 'htc', 26 => 'huawei', 27 => 'i\\-mobile', 28 => 'iemobile', 29 => 'iemobile/7', 30 => 'iemobile/9', 31 => 'j\\-phone', 32 => 'kddi', 33 => 'konka', 34 => 'kwc', 35 => 'kyocera/wx310k', 36 => 'lenovo', 37 => 'lg', 38 => 'lg/u990', 39 => 'lge\\ vx', 40 => 'midp', 41 => 'midp\\-2\\.0', 42 => 'mmef20', 43 => 'mmp', 44 => 'mobilephone', 45 => 'mot\\-v', 46 => 'motorola', 47 => 'msie\\ 10\\.0', 48 => 'netfront', 49 => 'newgen', 50 => 'newt', 51 => 'nintendo\\ ds', 52 => 'nintendo\\ wii', 53 => 'nitro', 54 => 'nokia', 55 => 'novarra', 56 => 'o2', 57 => 'openweb', 58 => 'opera\\ mobi', 59 => 'opera\\.mobi', 60 => 'p160u', 61 => 'palm', 62 => 'panasonic', 63 => 'pantech', 64 => 'pdxgw', 65 => 'pg', 66 => 'philips', 67 => 'phone', 68 => 'playbook', 69 => 'playstation\\ portable', 70 => 'portalmmm', 71 => '\\bppc\\b', 72 => 'proxinet', 73 => 'psp', 74 => 'qtek', 75 => 'sagem', 76 => 'samsung', 77 => 'sanyo', 78 => 'sch', 79 => 'sch\\-i800', 80 => 'sec', 81 => 'sendo', 82 => 'sgh', 83 => 'sharp', 84 => 'sharp\\-tq\\-gx10', 85 => 'small', 86 => 'smartphone', 87 => 'softbank', 88 => 'sonyericsson', 89 => 'sph', 90 => 'symbian', 91 => 'symbian\\ os', 92 => 'symbianos', 93 => 'toshiba', 94 => 'treo', 95 => 'ts21i\\-10', 96 => 'up\\.browser', 97 => 'up\\.link', 98 => 'uts', 99 => 'vertu', 100 => 'vodafone', 101 => 'wap', 102 => 'willcome', 103 => 'windows\\ ce', 104 => 'windows\\.ce', 105 => 'winwap', 106 => 'xda', 107 => 'xoom', 108 => 'zte', ), ), ), 'referrer.enabled' => false, 'referrer.rgroups' => array( 'search_engines' => array( 'theme' => '', 'enabled' => false, 'redirect' => '', 'referrers' => array( 0 => 'google\\.com', 1 => 'yahoo\\.com', 2 => 'bing\\.com', 3 => 'ask\\.com', 4 => 'msn\\.com', ), ), ), 'common.support' => 'footer', 'common.install' => 0, 'common.tweeted' => false, 'config.check' => true, 'config.path' => '', 'widget.latest.items' => 3, 'widget.latest_news.items' => 5, 'widget.pagespeed.enabled' => true, 'widget.pagespeed.key' => '', 'notes.wp_content_changed_perms' => true, 'notes.wp_content_perms' => false, 'notes.theme_changed' => false, 'notes.wp_upgraded' => false, 'notes.plugins_updated' => false, 'notes.cdn_upload' => false, 'notes.cdn_reupload' => false, 'notes.need_empty_pgcache' => false, 'notes.need_empty_minify' => false, 'notes.need_empty_objectcache' => false, 'notes.root_rules' => true, 'notes.rules' => true, 'notes.pgcache_rules_wpsc' => true, 'notes.support_us' => true, 'notes.no_curl' => true, 'notes.no_zlib' => true, 'notes.zlib_output_compression' => true, 'notes.no_permalink_rules' => true, 'notes.browsercache_rules_no404wp' => true, 'timelimit.email_send' => 180, 'timelimit.varnish_purge' => 300, 'timelimit.cache_flush' => 600, 'timelimit.cache_gc' => 600, 'timelimit.cdn_upload' => 600, 'timelimit.cdn_delete' => 300, 'timelimit.cdn_purge' => 300, 'timelimit.cdn_import' => 600, 'timelimit.cdn_test' => 300, 'timelimit.cdn_container_create' => 300, 'timelimit.domain_rename' => 120, 'timelimit.minify_recommendations' => 600, 'minify.auto.filename_length' => 150, 'minify.auto.disable_filename_length_test' => false, 'common.instance_id' => 857075916, 'common.force_master' => true, 'newrelic.enabled' => false, 'newrelic.api_key' => '', 'newrelic.account_id' => '', 'newrelic.application_id' => 0, 'newrelic.appname' => '', 'newrelic.accept.logged_roles' => true, 'newrelic.accept.roles' => array( 0 => 'contributor', ), 'newrelic.use_php_function' => true, 'notes.new_relic_page_load_notification' => true, 'newrelic.appname_prefix' => 'Child Site - ', 'newrelic.merge_with_network' => true, 'newrelic.cache_time' => 5, 'newrelic.enable_xmit' => false, 'newrelic.use_network_wide_id' => false, 'pgcache.late_init' => false, 'newrelic.include_rum' => true, 'extensions.settings' => array( 'genesis.theme' => array( 'wp_head' => '0', 'genesis_header' => '1', 'genesis_do_nav' => '0', 'genesis_do_subnav' => '0', 'loop_front_page' => '1', 'loop_terms' => '1', 'flush_terms' => '1', 'loop_single' => '1', 'loop_single_excluded' => '', 'loop_single_genesis_comments' => '0', 'loop_single_genesis_pings' => '0', 'sidebar' => '0', 'sidebar_excluded' => '', 'genesis_footer' => '1', 'wp_footer' => '0', 'reject_logged_roles' => '1', 'reject_logged_roles_on_actions' => array( 0 => 'genesis_loop', 1 => 'wp_head', 2 => 'wp_footer', ), 'reject_roles' => array( 0 => 'administrator', ), ), 'feedburner' => array( 'urls' => '', ), ), 'extensions.active' => array( ), 'plugin.license_key' => '', 'plugin.type' => '', );
jnuc093/1_bccw-wordpress
wp-content/w3tc-config/master.php
PHP
gpl-2.0
20,387
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\Setup\Declaration\Schema\Dto\Factories; use Magento\Framework\ObjectManagerInterface; /** * Text DTO element factory. */ class Text implements FactoryInterface { /** * Default text length. */ const DEFAULT_TEXT_LENGTH = 65536; /** * @var ObjectManagerInterface */ private $objectManager; /** * @var string */ private $className; /** * Constructor. * * @param ObjectManagerInterface $objectManager * @param string $className */ public function __construct( ObjectManagerInterface $objectManager, $className = \Magento\Framework\Setup\Declaration\Schema\Dto\Columns\Text::class ) { $this->objectManager = $objectManager; $this->className = $className; } /** * {@inheritdoc} */ public function create(array $data) { if (!isset($data['length'])) { $data['length'] = self::DEFAULT_TEXT_LENGTH; } return $this->objectManager->create($this->className, $data); } }
kunj1988/Magento2
lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Factories/Text.php
PHP
gpl-2.0
1,204
<?php /* @var Title $title */ /* @var WikiaGlobalRegistry $wg */ $commentsCounter = wfMessage( 'oasis-comments-header', $wg->Lang->FormatNum( $countCommentsNested ) )->text(); ?> <h3> <?= wfMessage('article-comments-toc-item')->text() ?> <span><?= wfMessage( 'parentheses', $commentsCounter )->text() ?></span> </h3> <div id="article-comments" class="article-comments"> <? if ( !$isBlocked && $canEdit && $commentingAllowed ): ?> <? if ( $isMiniEditorEnabled ): ?> <?= $app->renderView( 'MiniEditorController', 'Setup' ) ?> <? endif ?> <div id="article-comm-info" class="article-comm-info"></div> <? if ( $isMiniEditorEnabled ): ?> <?= $app->getView( 'MiniEditorController', 'Header', [ 'attributes' => [ 'id' => 'article-comments-minieditor-newpost', 'data-min-height' => 100, 'data-max-height' => 400 ] ])->render() ?> <? endif ?> <div class="session"> <?= $avatar ?> <?= $isAnon ? wfMessage( 'oasis-comments-anonymous-prompt' )->plain() : '' ?> </div> <form action="<?= $title->getLocalURL() ?>" method="post" class="article-comm-form" id="article-comm-form"> <input type="hidden" name="wpArticleId" value="<?= $title->getArticleId() ?>" /> <? if ( $isMiniEditorEnabled ): ?> <?= $app->getView( 'MiniEditorController', 'Editor_Header' )->render() ?> <? endif ?> <textarea name="wpArticleComment" id="article-comm"></textarea> <? if ( $isMiniEditorEnabled ): ?> <?= $app->getView( 'MiniEditorController', 'Editor_Footer' )->render() ?> <? endif ?> <? if ( !$isReadOnly ): ?> <div class="buttons" data-space-type="buttons"> <img src="<?= $ajaxicon ?>" class="throbber" /> <input type="submit" name="wpArticleSubmit" id="article-comm-submit" class="wikia-button actionButton secondary" value="<?= wfMessage( 'article-comments-post' )->plain() ?>" /> </div> <? endif ?> </form> <? if ( $isMiniEditorEnabled ): ?> <?= $app->getView( 'MiniEditorController', 'Footer' )->render() ?> <? endif ?> <? elseif ( $isBlocked ): ?> <p><?= wfMessage( 'article-comments-comment-cannot-add' )->plain() ?></p> <p><?= $reason ?></p> <? elseif ( !$canEdit ): ?> <p class="login"><?= wfMessage( 'article-comments-login', SpecialPage::getTitleFor( 'UserLogin' )->getLocalUrl() )->text() ?></p> <? elseif ( !$commentingAllowed ): ?> <p class="no-comments-allowed"><?= wfMessage( 'article-comments-comment-cannot-add' )->text() ?> </p> <? endif ?> <? if ( $countComments ): ?> <div class="article-comments-pagination upper-pagination"><?= $pagination ?></div> <? endif ?> <?= $app->getView( 'ArticleComments', 'VenusCommentList', [ 'commentListRaw' => $commentListRaw, 'page' => $page, 'useMaster' => false ])->render() ?> <button class="comments-show-more"><?= wfMessage('article-comments-show-more')->plain() ?></button> <? if ( $countComments ): ?> <div class="article-comments-pagination"><?= $pagination ?></div> <? endif ?> </div>
felixonmars/app
extensions/wikia/ArticleComments/modules/templates/ArticleCommentsController_VenusContent.php
PHP
gpl-2.0
2,976
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "lost_city_of_the_tolvir.h" #include "ScriptMgr.h" #include "InstanceScript.h" #include "Player.h" enum eScriptText { YELL_FREE = 0 }; class instance_lost_city_of_the_tolvir : public InstanceMapScript { public: instance_lost_city_of_the_tolvir() : InstanceMapScript("instance_lost_city_of_the_tolvir", 755) { } InstanceScript* GetInstanceScript(InstanceMap* map) const { return new instance_lost_city_of_the_tolvir_InstanceMapScript(map); } struct instance_lost_city_of_the_tolvir_InstanceMapScript : public InstanceScript { instance_lost_city_of_the_tolvir_InstanceMapScript(InstanceMap* map) : InstanceScript(map) { Initialize(); } uint32 Encounter[MAX_ENCOUNTER]; uint64 uiTunnelGUID[6]; uint8 uiTunnelFlag; uint64 uiHusamGUID; uint64 uiLockmawGUID; uint64 uiAughGUID; uint64 uiBarimGUID; uint64 uiBlazeGUID; uint64 uiHarbingerGUID; uint64 uiSiamatGUID; uint64 uiSiamatPlatformGUID; uint32 uiUpdateTimer; bool BarimIsDone; void Initialize() { memset(&Encounter, 0, sizeof(Encounter)); memset(&uiTunnelGUID, 0, sizeof(uiTunnelGUID)); uiTunnelFlag = 0; uiHusamGUID = 0; uiLockmawGUID = 0; uiAughGUID = 0; uiBarimGUID = 0; uiBlazeGUID = 0; uiSiamatGUID = 0; uiHarbingerGUID = 0; uiSiamatPlatformGUID = 0; uiUpdateTimer = 7000; BarimIsDone = false; } void SiamatFree() { if (GameObject* platform = instance->GetGameObject(uiSiamatPlatformGUID)) { platform->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); platform->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); } for (int i = 0; i < 6; ++i) if (Creature* tunnel = instance->GetCreature(uiTunnelGUID[i])) tunnel->SetVisible(true); } void Update(uint32 diff) { if (BarimIsDone) { if (uiUpdateTimer <= diff) { BarimIsDone = false; SiamatFree(); if (Creature* siamat = instance->GetCreature(uiSiamatGUID)) siamat->AI()->Talk(YELL_FREE); } else uiUpdateTimer -= diff; } } bool IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (Encounter[i] == IN_PROGRESS) return true; return false; } void OnGameObjectCreate(GameObject* go) { if (go->GetEntry() == SIAMAT_PLATFORM) { go->setActive(true); uiSiamatPlatformGUID = go->GetGUID(); } } void OnCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { case BOSS_GENERAL_HUSAM: uiHusamGUID = creature->GetGUID(); break; case BOSS_LOCKMAW: uiLockmawGUID = creature->GetGUID(); break; case BOSS_AUGH: uiAughGUID = creature->GetGUID(); break; case BOSS_HIGH_PROPHET_BARIM: uiBarimGUID = creature->GetGUID(); break; case BOSS_SIAMAT: uiSiamatGUID = creature->GetGUID(); break; case NPC_WIND_TUNNEL: { creature->SetVisible(false); creature->SetCanFly(true); uiTunnelGUID[uiTunnelFlag] = creature->GetGUID(); ++uiTunnelFlag; if (uiTunnelFlag >= 6) uiTunnelFlag = 0; } break; } } uint64 GetData64(uint32 type) const { switch (type) { case DATA_GENERAL_HUSAM: return uiSiamatGUID; case DATA_LOCKMAW: return uiLockmawGUID; case DATA_AUGH: return uiAughGUID; case DATA_HIGH_PROPHET_BARIM: return uiBarimGUID; case DATA_BLAZE: return uiBlazeGUID; case DATA_HARBINGER: return uiHarbingerGUID; case DATA_SIAMAT: return uiSiamatGUID; } return 0; } uint32 GetData(uint32 type) const { return Encounter[type]; } void SetData64(uint32 type, uint64 data) { switch (type) { case DATA_HARBINGER: uiHarbingerGUID = data; break; case DATA_BLAZE: uiBlazeGUID = data; break; } } void SetData(uint32 type, uint32 data) { Encounter[type] = data; if (type == DATA_HIGH_PROPHET_BARIM && data == DONE) if (Encounter[DATA_SIAMAT] != DONE) BarimIsDone = true; if (type == DATA_SIAMAT && data == DONE) { SiamatFree(); } if (data == DONE) SaveToDB(); } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::string str_data; std::ostringstream saveStream; saveStream << "P S " << Encounter[0] << " " << Encounter[1] << " " << Encounter[2] << " " << Encounter[3] << " " << Encounter[4]; str_data = saveStream.str(); OUT_SAVE_INST_DATA_COMPLETE; return str_data; } void Load(char const* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; uint16 data0, data1, data2, data3, data4; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2 >> data3 >> data4; if (dataHead1 == 'P' && dataHead2 == 'S') { Encounter[0] = data0; Encounter[1] = data1; Encounter[2] = data2; Encounter[3] = data3; Encounter[4] = data4; for (uint8 data = 0; data < MAX_ENCOUNTER; ++data) { if (Encounter[data] == IN_PROGRESS) Encounter[data] = NOT_STARTED; SetData(data, Encounter[data]); } } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; }; void AddSC_instance_lost_city_of_the_tolvir() { new instance_lost_city_of_the_tolvir(); }
Stenlibg/4.3.4
src/server/scripts/Kalimdor/LostCityOfTheTolvir/instance_lost_city_of_the_tolvir.cpp
C++
gpl-2.0
8,766
/* Updates fields based on checkbox changes */ var PRFtoggleEnabled = function(cbox, id, type) { oldval = cbox.checked ? 0 : 1; var dataS = { "action" : "toggleEnabled", "id": id, "type": type, "oldval": oldval, }; data = $.param(dataS); $.ajax({ type: "POST", dataType: "json", url: site_admin_url + "/plugins/profile/ajax.php", data: data, success: function(result) { cbox.checked = result.newval == 1 ? true : false; try { if (result.newval == oldval) { icon = "<i class='uk-icon-exclamation-triangle'></i>&nbsp;"; } else { icon = "<i class='uk-icon-check'></i>&nbsp;"; } $.UIkit.notify(icon + result.statusMessage, {timeout: 1000,pos:'top-center'}); } catch(err) { $.UIkit.notify("<i class='uk-icon-exclamation-triangle'></i>&nbsp;" + result.statusMessage, {timeout: 1000,pos:'top-center'}); alert(result.statusMessage); } } }); return false; }; /** * Not a toggle function; this updates the 3-part date field with data * from the datepicker. * @param Date d Date object * @param string fld Field Name * @param integer tm_type 12- or 24-hour indicator, 0 = no time field */ function PRF_updateDate(d, fld, tm_type) { document.getElementById(fld + "_month").selectedIndex = d.getMonth() + 1; document.getElementById(fld + "_day").selectedIndex = d.getDate(); document.getElementById(fld + "_year").value = d.getFullYear(); // Update the time, if time fields are present. if (tm_type != 0) { var hour = d.getHours(); var ampm = 0; if (tm_type == "12") { if (hour == 0) { hour = 12; } else if (hour > 12) { hour -= 12; ampm = 1; } document.getElementById(fld + "_ampm").selectedIndex = ampm; } document.getElementById(fld + "_hour").selectedIndex = hour; document.getElementById(fld + "_minute").selectedIndex = d.getMinutes(); } }
leegarner-glfusion/profile
js/toggleEnabled.js
JavaScript
gpl-2.0
2,241
package com.ug.telescopio.fragments; import java.util.ArrayList; import java.util.Arrays; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.ug.telescopio.R; import com.ug.telescopio.activities.CountryDetailActivity; public class CountriesListFragment extends Fragment implements OnItemClickListener { String country = ""; ListView list; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); String[] array_countries = new String[]{"Brasil", "MŽxico", "Colombia", "Argentina", "Perœ", "Venezuela", "Chile", "Ecuador", "Guatemala", "Cuba"}; ArrayList<String> countries = new ArrayList<String>(Arrays.asList(array_countries)); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, countries); list.setAdapter(adapter); list.setOnItemClickListener(this); registerForContextMenu(list); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_countries_list, container, false); list = (ListView)view.findViewById(R.id.listView); return view; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.main, menu); } @Override public void onPrepareOptionsMenu(Menu menu){ boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; MenuItem share = menu.getItem(menu.size()-1); share.setVisible(landscape); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_help: return true; case R.id.action_share: if (!country.equals("")) { String url = "http://es.m.wikipedia.org/wiki/" + country; Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, getResources().getText(R.string.msg_share) + " " + country + " " + url); intent.setType("text/plain"); startActivity(Intent.createChooser(intent, getResources().getText(R.string.action_share))); } return true; default : return super.onOptionsItemSelected(item); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; country = ((TextView) info.targetView).getText().toString(); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.main, menu); } @Override public boolean onContextItemSelected(MenuItem item) { return onOptionsItemSelected(item); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) { country = adapterView.getItemAtPosition(position).toString(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { FragmentManager manager = getActivity().getSupportFragmentManager(); CountryInfoFragment fragment = (CountryInfoFragment) manager.findFragmentById(R.id.fragmentCountryInfo); fragment.loadWebViewContent(country); getActivity().invalidateOptionsMenu(); } else { Intent intent = new Intent(getActivity().getApplicationContext(), CountryDetailActivity.class); intent.putExtra(CountryDetailActivity.COUNTRY, country); startActivity(intent); } } }
ykro/androidmooc-clase2
Demo 8 - navigation drawer pasando contenido a fragmentos/src/com/ug/telescopio/fragments/CountriesListFragment.java
Java
gpl-2.0
4,216
/* * Copyright 2007 Sun Microsystems, Inc. * * This file is part of jVoiceBridge. * * jVoiceBridge is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation and distributed hereunder * to you. * * jVoiceBridge 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/>. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied this * code. */ package com.sun.mc.softphone.media.alsa; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.prefs.Preferences; import com.sun.voip.Logger; import com.sun.mc.softphone.media.AudioServiceProvider; import com.sun.mc.softphone.media.Microphone; import com.sun.mc.softphone.media.NativeLibUtil; import com.sun.mc.softphone.media.Speaker; public class AlsaAudioServiceProvider implements AudioServiceProvider { private static final String ALSA_I386_NAME = "libMediaFrameworkI386.so"; private static final String ALSA_AMD64_NAME = "libMediaFrameworkAmd64.so"; private static AudioDriver audioDriver; private Microphone microphone; private Speaker speaker; public AlsaAudioServiceProvider() throws IOException { audioDriver = new AudioDriverAlsa(); if (System.getProperty("os.arch").contains("amd64")) { NativeLibUtil.loadLibrary(getClass(), ALSA_AMD64_NAME); } else { NativeLibUtil.loadLibrary(getClass(), ALSA_I386_NAME); } } public void initialize(int speakerSampleRate, int speakerChannels, int microphoneSampleRate, int microphoneChannels, int microphoneBufferSize, int speakerBufferSize) throws IOException { shutdown(); // stop old driver if running Logger.println("Initializing audio driver to " + speakerSampleRate + "/" + speakerChannels + " bufferSize " + speakerBufferSize); synchronized (audioDriver) { speaker = new SpeakerAlsaImpl(speakerSampleRate, speakerChannels, speakerBufferSize, audioDriver); microphone = new MicrophoneAlsaImpl(microphoneSampleRate, microphoneChannels, microphoneBufferSize, audioDriver); } } public void shutdown() { synchronized (audioDriver) { audioDriver.stop(); } } public Microphone getMicrophone() { return microphone; } public String[] getMicrophoneList() { return audioDriver.getAvailableOutputDevices(); } public Speaker getSpeaker() { return speaker; } public String[] getSpeakerList() { return audioDriver.getAvailableInputDevices(); } }
damirkusar/jvoicebridge
softphone/src/com/sun/mc/softphone/media/alsa/AlsaAudioServiceProvider.java
Java
gpl-2.0
2,986
#resource, resources, Resources from flask import Blueprint, render_template, request,flash, redirect, url_for from app.{resources}.models import {Resources}, {Resources}Schema {resources} = Blueprint('{resources}', __name__, template_folder='templates') #http://marshmallow.readthedocs.org/en/latest/quickstart.html#declaring-schemas schema = {Resources}Schema() #{Resources} @{resources}.route('/' ) def {resource}_index(): {resources} = {Resources}.query.all() results = schema.dump({resources}, many=True).data return render_template('/{resources}/index.html', results=results) @{resources}.route('/add' , methods=['POST', 'GET']) def {resource}_add(): if request.method == 'POST': #Validate form values by de-serializing the request, http://marshmallow.readthedocs.org/en/latest/quickstart.html#validation form_errors = schema.validate(request.form.to_dict()) if not form_errors: {resource}={Resources}({add_fields}) return add({resource}, success_url = '{resources}.{resource}_index', fail_url = '{resources}.{resource}_add') else: flash(form_errors) return render_template('/{resources}/add.html') @{resources}.route('/update/<int:id>' , methods=['POST', 'GET']) def {resource}_update (id): #Get {resource} by primary key: {resource}={Resources}.query.get_or_404(id) if request.method == 'POST': form_errors = schema.validate(request.form.to_dict()) if not form_errors: {update_fields} return update({resource} , id, success_url = '{resources}.{resource}_index', fail_url = '{resources}.{resource}_update') else: flash(form_errors) return render_template('/{resources}/update.html', {resource}={resource}) @{resources}.route('/delete/<int:id>' , methods=['POST', 'GET']) def {resource}_delete (id): {resource} = {Resources}.query.get_or_404(id) return delete({resource}, fail_url = '{resources}.{resource}_index') #CRUD FUNCTIONS #Arguments are data to add, function to redirect to if the add was successful and if not def add (data, success_url = '', fail_url = ''): add = data.add(data) #if does not return any error if not add : flash("Add was successful") return redirect(url_for(success_url)) else: message=add flash(message) return redirect(url_for(fail_url)) def update (data, id, success_url = '', fail_url = ''): update=data.update() #if does not return any error if not update : flash("Update was successful") return redirect(url_for(success_url)) else: message=update flash(message) return redirect(url_for(fail_url, id=id)) def delete (data, fail_url=''): delete=data.delete(data) if not delete : flash("Delete was successful") else: message=delete flash(message) return redirect(url_for(fail_url))
jstacoder/Flask-Scaffold
scaffold/app/views.py
Python
gpl-2.0
3,123
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2019-04-26 git sha : $Format:%H$ copyright : (C) 2019 by Philipe Borba - Cartographic Engineer @ Brazilian Army email : borba.philipe@eb.mil.br ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ """ import os from PyQt5.QtCore import QCoreApplication from qgis.core import (QgsDataSourceUri, QgsExpression, QgsExpressionContext, QgsExpressionContextUtils, QgsProcessing, QgsProcessingAlgorithm, QgsProcessingOutputMultipleLayers, QgsProcessingParameterExpression, QgsProcessingParameterMultipleLayers, QgsProcessingParameterNumber, QgsProcessingParameterString, QgsProject) from qgis.utils import iface class GroupLayersAlgorithm(QgsProcessingAlgorithm): """ Algorithm to group layers according to primitive, dataset and a category. INPUT_LAYERS: list of QgsVectorLayer CATEGORY_TOKEN: token used to split layer name CATEGORY_TOKEN_INDEX: index of the split list OUTPUT: list of outputs """ INPUT_LAYERS = 'INPUT_LAYERS' CATEGORY_EXPRESSION = 'CATEGORY_EXPRESSION' OUTPUT = 'OUTPUT' def initAlgorithm(self, config): """ Parameter setting. """ self.addParameter( QgsProcessingParameterMultipleLayers( self.INPUT_LAYERS, self.tr('Input Layers'), QgsProcessing.TypeVector ) ) self.addParameter( QgsProcessingParameterExpression( self.CATEGORY_EXPRESSION, self.tr('Expression used to find out the category'), defaultValue="regexp_substr(@layer_name ,'([^_]+)')" ) ) self.addOutput( QgsProcessingOutputMultipleLayers( self.OUTPUT, self.tr('Original reorganized layers') ) ) def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ inputLyrList = self.parameterAsLayerList( parameters, self.INPUT_LAYERS, context ) categoryExpression = self.parameterAsExpression( parameters, self.CATEGORY_EXPRESSION, context ) listSize = len(inputLyrList) progressStep = 100/listSize if listSize else 0 rootNode = QgsProject.instance().layerTreeRoot() inputLyrList.sort(key=lambda x: (x.geometryType(), x.name())) geometryNodeDict = { 0 : self.tr('Point'), 1 : self.tr('Line'), 2 : self.tr('Polygon'), 4 : self.tr('Non spatial') } iface.mapCanvas().freeze(True) for current, lyr in enumerate(inputLyrList): if feedback.isCanceled(): break rootDatabaseNode = self.getLayerRootNode(lyr, rootNode) geometryNode = self.createGroup( geometryNodeDict[lyr.geometryType()], rootDatabaseNode ) categoryNode = self.getLayerCategoryNode( lyr, geometryNode, categoryExpression ) lyrNode = rootNode.findLayer(lyr.id()) myClone = lyrNode.clone() categoryNode.addChildNode(myClone) # not thread safe, must set flag to FlagNoThreading rootNode.removeChildNode(lyrNode) feedback.setProgress(current*progressStep) iface.mapCanvas().freeze(False) return {self.OUTPUT: [i.id() for i in inputLyrList]} def getLayerRootNode(self, lyr, rootNode): """ Finds the database name of the layer and creates (if not exists) a node with the found name. lyr: (QgsVectorLayer) rootNode: (node item) """ uriText = lyr.dataProvider().dataSourceUri() candidateUri = QgsDataSourceUri(uriText) rootNodeName = candidateUri.database() if not rootNodeName: rootNodeName = self.getRootNodeName(uriText) #creates database root return self.createGroup(rootNodeName, rootNode) def getRootNodeName(self, uriText): """ Gets root node name from uri according to provider type. """ if 'memory?' in uriText: rootNodeName = 'memory' elif 'dbname' in uriText: rootNodeName = uriText.replace('dbname=', '').split(' ')[0] elif '|' in uriText: rootNodeName = os.path.dirname(uriText.split(' ')[0].split('|')[0]) else: rootNodeName = 'unrecognised_format' return rootNodeName def getLayerCategoryNode(self, lyr, rootNode, categoryExpression): """ Finds category node based on category expression and creates it (if not exists a node) """ exp = QgsExpression(categoryExpression) context = QgsExpressionContext() context.appendScopes( QgsExpressionContextUtils.globalProjectLayerScopes(lyr) ) if exp.hasParserError(): raise Exception(exp.parserErrorString()) if exp.hasEvalError(): raise ValueError(exp.evalErrorString()) categoryText = exp.evaluate(context) return self.createGroup(categoryText, rootNode) def createGroup(self, groupName, rootNode): """ Create group with the name groupName and parent rootNode. """ groupNode = rootNode.findGroup(groupName) return groupNode if groupNode else rootNode.addGroup(groupName) def name(self): """ Returns the algorithm name, used for identifying the algorithm. This string should be fixed for the algorithm, and must not be localised. The name should be unique within each provider. Names should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'grouplayers' def displayName(self): """ Returns the translated algorithm name, which should be used for any user-visible display of the algorithm name. """ return self.tr('Group Layers') def group(self): """ Returns the name of the group this algorithm belongs to. This string should be localised. """ return self.tr('Layer Management Algorithms') def groupId(self): """ Returns the unique ID of the group this algorithm belongs to. This string should be fixed for the algorithm, and must not be localised. The group id should be unique within each provider. Group id should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'DSGTools: Layer Management Algorithms' def tr(self, string): """ Translates input string. """ return QCoreApplication.translate('GroupLayersAlgorithm', string) def createInstance(self): """ Creates an instance of this class """ return GroupLayersAlgorithm() def flags(self): """ This process is not thread safe due to the fact that removeChildNode method from QgsLayerTreeGroup is not thread safe. """ return super().flags() | QgsProcessingAlgorithm.FlagNoThreading
lcoandrade/DsgTools
core/DSGToolsProcessingAlgs/Algs/LayerManagementAlgs/groupLayersAlgorithm.py
Python
gpl-2.0
8,547
/*************************************************************************************/ /* Copyright 2009 Barcelona Supercomputing Center */ /* */ /* This file is part of the NANOS++ library. */ /* */ /* NANOS++ 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 3 of the License, or */ /* (at your option) any later version. */ /* */ /* NANOS++ 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 NANOS++. If not, see <http://www.gnu.org/licenses/>. */ /*************************************************************************************/ /* <testinfo> test_generator=gens/core-generator </testinfo> */ #include "config.hpp" #include <iostream> #include "smpprocessor.hpp" #include "system.hpp" #include "copydata.hpp" #include <string.h> #include <unistd.h> using namespace std; using namespace nanos; using namespace nanos::ext; typedef struct { int a; std::string b; } hello_world_args; void hello_world ( void *args ); void hello_world ( void *args ) { WD *wd = getMyThreadSafe()->getCurrentWD(); hello_world_args *hargs = ( hello_world_args * ) args; CopyData* cd = wd->getCopies(); if ( (void *)cd[0].getAddress() != (void *)&(hargs->a) ) { std::cout << "Error: CopyData address '" << cd[0].getAddress() << "' does not match argument with address '" << &(hargs->a) << "'." << std::endl; abort(); } else { std::cout << "Checking for CopyData address correctness... PASS" << std::endl; } if ( (void *)( (char *)hargs + (unsigned long)cd[1].getAddress() ) != (void *) &(hargs->b) ) { std::cout << "Error: CopyData address '" << cd[1].getAddress() << "' does not match argument with address '" << &(hargs->b) << "'." << std::endl; abort(); } else { std::cout << "Checking for CopyData address correctness... PASS" << std::endl; } if ( cd[0].getSize() != sizeof(hargs->a) ) { std::cout << "Error: CopyData size '" << cd[0].getSize() << "' does not match argument with size '" << sizeof((hargs->b)) << "'." << std::endl; abort(); } else { std::cout << "Checking for CopyData size correctness... PASS" << std::endl; } if ( cd[1].getSize() != sizeof(hargs->b) ) { std::cout << "Error: CopyData size '" << cd[1].getSize() << "' does not match argument with size '" << sizeof((hargs->b)) << "'." << std::endl; abort(); } else { std::cout << "Checking for CopyData size correctness... PASS" << std::endl; } if ( !cd[0].isInput() ) { std::cout << "Error: CopyData was supposed to be input." << std::endl; abort(); } else { std::cout << "Checking for CopyData direction correctness... PASS" << std::endl; } if ( !cd[1].isOutput() ) { std::cout << "Error: CopyData was supposed to be output." << std::endl; abort(); } else { std::cout << "Checking for CopyData direction correctness... PASS" << std::endl; } if ( !cd[0].isShared() ) { std::cout << "Error: CopyData was supposed to be NANOS_SHARED." << std::endl; abort(); } else { std::cout << "Checking for CopyData sharing... PASS" << std::endl; } if ( !cd[1].isPrivate() ) { std::cout << "Error: CopyData was supposed to be NANOS_PRIVATE." << std::endl; abort(); } else { std::cout << "Checking for CopyData sharing... PASS" << std::endl; } } int main ( int argc, char **argv ) { const char *a = "alex"; hello_world_args *data = new hello_world_args(); data->a = 1; data->b = a; nanos_region_dimension_internal_t dims[2]; dims[0] = (nanos_region_dimension_internal_t) {sizeof(data->a), 0, sizeof(data->a)}; dims[1] = (nanos_region_dimension_internal_t) {sizeof(data->b), 0, sizeof(data->b)}; CopyData cd[2] = { CopyData( (uint64_t)&data->a, NANOS_SHARED, true, false, 1, &dims[0], 0 ), CopyData( (uint64_t)&data->b, NANOS_PRIVATE, true, true, 1, &dims[1], 0 ) }; WD * wd = new WD( new SMPDD( hello_world ), sizeof( hello_world_args ), __alignof__( hello_world_args ), data, 2, cd ); WG *wg = getMyThreadSafe()->getCurrentWD(); wg->addWork( *wd ); sys.setupWD(*wd, (nanos::WD *) wg); sys.submit( *wd ); usleep( 500 ); wg->waitCompletion(); }
robbriggs/masters-project-nanosxx
tests/test/02_core/copies/test_copy_in_out_cpp.cpp
C++
gpl-2.0
5,329
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2014 osCommerce Released under the GNU General Public License */ class cm_paypal_login { var $code; var $group; var $title; var $description; var $sort_order; var $enabled = false; function cm_paypal_login() { global $_GET, $PHP_SELF; $this->signature = 'paypal|paypal_login|1.0|2.3'; $this->code = get_class($this); $this->group = basename(dirname(__FILE__)); $this->title = MODULE_CONTENT_PAYPAL_LOGIN_TITLE; $this->description = MODULE_CONTENT_PAYPAL_LOGIN_DESCRIPTION; if ( defined('MODULE_CONTENT_PAYPAL_LOGIN_STATUS') ) { $this->sort_order = MODULE_CONTENT_PAYPAL_LOGIN_SORT_ORDER; $this->enabled = (MODULE_CONTENT_PAYPAL_LOGIN_STATUS == 'True'); if ( basename($GLOBALS['PHP_SELF']) == 'modules_content.php' ) { $this->description .= $this->getTestLinkInfo(); $this->description .= $this->getShowUrlsInfo(); if ( MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Sandbox' ) { $this->title .= ' [Sandbox]'; } if ( !function_exists('curl_init') ) { $this->description = '<div class="secWarning">' . MODULE_CONTENT_PAYPAL_LOGIN_ERROR_ADMIN_CURL . '</div>' . $this->description; $this->enabled = false; } if ( $this->enabled === true ) { if ( !tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID) || !tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_SECRET) ) { $this->description = '<div class="secWarning">' . MODULE_CONTENT_PAYPAL_LOGIN_ERROR_ADMIN_CONFIGURATION . '</div>' . $this->description; } } } } if ( defined('FILENAME_MODULES') && ($PHP_SELF == 'modules_content.php') && isset($_GET['action']) && ($_GET['action'] == 'install') && isset($_GET['subaction']) && ($_GET['subaction'] == 'conntest') ) { echo $this->getTestConnectionResult(); exit; } } function execute() { global $_GET, $oscTemplate; if ( tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID) && tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_SECRET) ) { if ( isset($_GET['action']) ) { if ( $_GET['action'] == 'paypal_login' ) { $this->preLogin(); } elseif ( $_GET['action'] == 'paypal_login_process' ) { $this->postLogin(); } } $scopes = cm_paypal_login_get_attributes(); $use_scopes = array('openid'); foreach ( explode(';', MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES) as $a ) { foreach ( $scopes as $group => $attributes ) { foreach ( $attributes as $attribute => $scope ) { if ( $a == $attribute ) { if ( !in_array($scope, $use_scopes) ) { $use_scopes[] = $scope; } } } } } ob_start(); include(DIR_WS_MODULES . 'content/' . $this->group . '/templates/paypal_login.php'); $template = ob_get_clean(); $oscTemplate->addContent($template, $this->group); } } function preLogin() { global $_GET, $paypal_login_access_token, $paypal_login_customer_id, $sendto, $billto; $return_url = tep_href_link(FILENAME_LOGIN, '', 'SSL'); if ( isset($_GET['code']) ) { $paypal_login_customer_id = false; $params = array('code' => $_GET['code']); $response_token = $this->getToken($params); if ( !isset($response_token['access_token']) && isset($response_token['refresh_token']) ) { $params = array('refresh_token' => $response_token['refresh_token']); $response_token = $this->getRefreshToken($params); } if ( isset($response_token['access_token']) ) { $params = array('access_token' => $response_token['access_token']); $response = $this->getUserInfo($params); if ( isset($response['email']) ) { $paypal_login_access_token = $response_token['access_token']; tep_session_register('paypal_login_access_token'); $force_login = false; // check if e-mail address exists in database and login or create customer account if ( !isset($_SESSION['customer_id']) ) { $customer_id = 0; $customer_default_address_id = 0; $force_login = true; $email_address = tep_db_prepare_input($response['email']); $check_query = tep_db_query("select customers_id from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($email_address) . "' limit 1"); if (tep_db_num_rows($check_query)) { $check = tep_db_fetch_array($check_query); $customer_id = (int)$check['customers_id']; } else { $customers_firstname = tep_db_prepare_input($response['given_name']); $customers_lastname = tep_db_prepare_input($response['family_name']); $sql_data_array = array('customers_firstname' => $customers_firstname, 'customers_lastname' => $customers_lastname, 'customers_email_address' => $email_address, 'customers_telephone' => '', 'customers_fax' => '', 'customers_newsletter' => '0', 'customers_password' => ''); if ($this->hasAttribute('phone') && isset($response['phone_number']) && tep_not_null($response['phone_number'])) { $customers_telephone = tep_db_prepare_input($response['phone_number']); $sql_data_array['customers_telephone'] = $customers_telephone; } tep_db_perform(TABLE_CUSTOMERS, $sql_data_array); $customer_id = (int)tep_db_insert_id(); tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created) values ('" . (int)$customer_id . "', '0', now())"); } } // check if paypal shipping address exists in the address book $ship_firstname = tep_db_prepare_input($response['given_name']); $ship_lastname = tep_db_prepare_input($response['family_name']); $ship_address = tep_db_prepare_input($response['address']['street_address']); $ship_city = tep_db_prepare_input($response['address']['locality']); $ship_zone = tep_db_prepare_input($response['address']['region']); $ship_zone_id = 0; $ship_postcode = tep_db_prepare_input($response['address']['postal_code']); $ship_country = tep_db_prepare_input($response['address']['country']); $ship_country_id = 0; $ship_address_format_id = 1; $country_query = tep_db_query("select countries_id, address_format_id from " . TABLE_COUNTRIES . " where countries_iso_code_2 = '" . tep_db_input($ship_country) . "' limit 1"); if (tep_db_num_rows($country_query)) { $country = tep_db_fetch_array($country_query); $ship_country_id = $country['countries_id']; $ship_address_format_id = $country['address_format_id']; } if ($ship_country_id > 0) { $zone_query = tep_db_query("select zone_id from " . TABLE_ZONES . " where zone_country_id = '" . (int)$ship_country_id . "' and (zone_name = '" . tep_db_input($ship_zone) . "' or zone_code = '" . tep_db_input($ship_zone) . "') limit 1"); if (tep_db_num_rows($zone_query)) { $zone = tep_db_fetch_array($zone_query); $ship_zone_id = $zone['zone_id']; } } $check_query = tep_db_query("select address_book_id from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$customer_id . "' and entry_firstname = '" . tep_db_input($ship_firstname) . "' and entry_lastname = '" . tep_db_input($ship_lastname) . "' and entry_street_address = '" . tep_db_input($ship_address) . "' and entry_postcode = '" . tep_db_input($ship_postcode) . "' and entry_city = '" . tep_db_input($ship_city) . "' and (entry_state = '" . tep_db_input($ship_zone) . "' or entry_zone_id = '" . (int)$ship_zone_id . "') and entry_country_id = '" . (int)$ship_country_id . "' limit 1"); if (tep_db_num_rows($check_query)) { $check = tep_db_fetch_array($check_query); $sendto = $check['address_book_id']; } else { $sql_data_array = array('customers_id' => $customer_id, 'entry_firstname' => $ship_firstname, 'entry_lastname' => $ship_lastname, 'entry_street_address' => $ship_address, 'entry_postcode' => $ship_postcode, 'entry_city' => $ship_city, 'entry_country_id' => $ship_country_id); if (ACCOUNT_STATE == 'true') { if ($ship_zone_id > 0) { $sql_data_array['entry_zone_id'] = $ship_zone_id; $sql_data_array['entry_state'] = ''; } else { $sql_data_array['entry_zone_id'] = '0'; $sql_data_array['entry_state'] = $ship_zone; } } tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array); $address_id = tep_db_insert_id(); $sendto = $address_id; if ($customer_default_address_id < 1) { tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$address_id . "' where customers_id = '" . (int)$customer_id . "'"); $customer_default_address_id = $address_id; } } if ($force_login == true) { $paypal_login_customer_id = $customer_id; } else { $paypal_login_customer_id = false; } if (!isset($_SESSION['paypal_login_customer_id']) ) { tep_session_register('paypal_login_customer_id'); } $billto = $sendto; if ( !isset($_SESSION['sendto']) ) { tep_session_register('sendto'); } if ( !isset($_SESSION['billto']) ) { tep_session_register('billto'); } $return_url = tep_href_link(FILENAME_LOGIN, 'action=paypal_login_process', 'SSL'); } } } echo '<script>window.opener.location.href="' . str_replace('&amp;', '&', $return_url) . '";window.close();</script>'; exit; } function postLogin() { global $paypal_login_customer_id, $login_customer_id, $language, $payment; if ( isset($_SESSION['paypal_login_customer_id']) ) { if ( $paypal_login_customer_id !== false ) { $login_customer_id = $paypal_login_customer_id; } unset($_SESSION['paypal_login_customer_id']); } // Register PayPal Express Checkout as the default payment method if ( !isset($_SESSION['payment']) || ($payment != 'paypal_express') ) { if (defined('MODULE_PAYMENT_INSTALLED') && tep_not_null(MODULE_PAYMENT_INSTALLED)) { if ( in_array('paypal_express.php', explode(';', MODULE_PAYMENT_INSTALLED)) ) { if ( !class_exists('paypal_express') ) { include(DIR_WS_LANGUAGES . $language . '/modules/payment/paypal_express.php'); include(DIR_WS_MODULES . 'payment/paypal_express.php'); } $ppe = new paypal_express(); if ( $ppe->enabled ) { $payment = 'paypal_express'; tep_session_register('payment'); } } } } } function isEnabled() { return $this->enabled; } function check() { return defined('MODULE_CONTENT_PAYPAL_LOGIN_STATUS'); } function install($parameter = null) { $params = $this->getParams(); if (isset($parameter)) { if (isset($params[$parameter])) { $params = array($parameter => $params[$parameter]); } else { $params = array(); } } foreach ($params as $key => $data) { $sql_data_array = array('configuration_title' => $data['title'], 'configuration_key' => $key, 'configuration_value' => (isset($data['value']) ? $data['value'] : ''), 'configuration_description' => $data['desc'], 'configuration_group_id' => '6', 'sort_order' => '0', 'date_added' => 'now()'); if (isset($data['set_func'])) { $sql_data_array['set_function'] = $data['set_func']; } if (isset($data['use_func'])) { $sql_data_array['use_function'] = $data['use_func']; } tep_db_perform(TABLE_CONFIGURATION, $sql_data_array); } } function remove() { tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')"); } function keys() { $keys = array_keys($this->getParams()); if ($this->check()) { foreach ($keys as $key) { if (!defined($key)) { $this->install($key); } } } return $keys; } function getParams() { $params = array('MODULE_CONTENT_PAYPAL_LOGIN_STATUS' => array('title' => 'Enable Log In with PayPal', 'desc' => 'Do you want to enable the Log In with PayPal module?', 'value' => 'True', 'set_func' => 'tep_cfg_select_option(array(\'True\', \'False\'), '), 'MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID' => array('title' => 'Client ID', 'desc' => 'Your PayPal Application Client ID.'), 'MODULE_CONTENT_PAYPAL_LOGIN_SECRET' => array('title' => 'Secret', 'desc' => 'Your PayPal Application Secret.'), 'MODULE_CONTENT_PAYPAL_LOGIN_THEME' => array('title' => 'Theme', 'desc' => 'Which theme should be used for the button?', 'value' => 'Blue', 'set_func' => 'tep_cfg_select_option(array(\'Blue\', \'Neutral\'), '), 'MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES' => array('title' => 'Information Requested From Customers', 'desc' => 'The attributes the customer must share with you.', 'value' => implode(';', $this->get_default_attributes()), 'use_func' => 'cm_paypal_login_show_attributes', 'set_func' => 'cm_paypal_login_edit_attributes('), 'MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE' => array('title' => 'Server Type', 'desc' => 'Which server should be used? Live for production or Sandbox for testing.', 'value' => 'Live', 'set_func' => 'tep_cfg_select_option(array(\'Live\', \'Sandbox\'), '), 'MODULE_CONTENT_PAYPAL_LOGIN_VERIFY_SSL' => array('title' => 'Verify SSL Certificate', 'desc' => 'Verify gateway server SSL certificate on connection?', 'value' => 'True', 'set_func' => 'tep_cfg_select_option(array(\'True\', \'False\'), '), 'MODULE_CONTENT_PAYPAL_LOGIN_PROXY' => array('title' => 'Proxy Server', 'desc' => 'Send API requests through this proxy server. (host:port, eg: 123.45.67.89:8080 or proxy.example.com:8080)'), 'MODULE_CONTENT_PAYPAL_LOGIN_CONTENT_WIDTH' => array('title' => 'Content Width', 'desc' => 'Should the content be shown in a full or half width container?', 'value' => 'Full', 'set_func' => 'tep_cfg_select_option(array(\'Full\', \'Half\'), '), 'MODULE_CONTENT_PAYPAL_LOGIN_SORT_ORDER' => array('title' => 'Sort order of display', 'desc' => 'Sort order of display. Lowest is displayed first.', 'value' => '0')); return $params; } function sendRequest($url, $parameters = null) { $server = parse_url($url); if ( !isset($server['port']) ) { $server['port'] = ($server['scheme'] == 'https') ? 443 : 80; } if ( !isset($server['path']) ) { $server['path'] = '/'; } $curl = curl_init($server['scheme'] . '://' . $server['host'] . $server['path'] . (isset($server['query']) ? '?' . $server['query'] : '')); curl_setopt($curl, CURLOPT_PORT, $server['port']); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FORBID_REUSE, true); curl_setopt($curl, CURLOPT_FRESH_CONNECT, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters); curl_setopt($curl, CURLOPT_ENCODING, ''); if ( MODULE_CONTENT_PAYPAL_LOGIN_VERIFY_SSL == 'True' ) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); if ( file_exists(DIR_FS_CATALOG . 'ext/modules/payment/paypal/paypal.com.crt') ) { curl_setopt($curl, CURLOPT_CAINFO, DIR_FS_CATALOG . 'ext/modules/payment/paypal/paypal.com.crt'); } elseif ( file_exists(DIR_FS_CATALOG . 'includes/cacert.pem') ) { curl_setopt($curl, CURLOPT_CAINFO, DIR_FS_CATALOG . 'includes/cacert.pem'); } } else { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); } if ( tep_not_null(MODULE_CONTENT_PAYPAL_LOGIN_PROXY) ) { curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, true); curl_setopt($curl, CURLOPT_PROXY, MODULE_CONTENT_PAYPAL_LOGIN_PROXY); } $result = curl_exec($curl); curl_close($curl); return $result; } function getToken($params) { if ( MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live' ) { $api_server = 'api.paypal.com'; } else { $api_server = 'api.sandbox.paypal.com'; } $parameters = array('client_id' => MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID, 'client_secret' => MODULE_CONTENT_PAYPAL_LOGIN_SECRET, 'grant_type' => 'authorization_code', 'code' => $params['code'], 'redirect_uri' => str_replace('&amp;', '&', tep_href_link(FILENAME_LOGIN, 'action=paypal_login', 'SSL'))); $post_string = ''; foreach ($parameters as $key => $value) { $post_string .= $key . '=' . urlencode(utf8_encode(trim($value))) . '&'; } $post_string = substr($post_string, 0, -1); $result = $this->sendRequest('https://' . $api_server . '/v1/identity/openidconnect/tokenservice', $post_string); $result_array = json_decode($result, true); return $result_array; } function getRefreshToken($params) { if ( MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live' ) { $api_server = 'api.paypal.com'; } else { $api_server = 'api.sandbox.paypal.com'; } $parameters = array('client_id' => MODULE_CONTENT_PAYPAL_LOGIN_CLIENT_ID, 'client_secret' => MODULE_CONTENT_PAYPAL_LOGIN_SECRET, 'grant_type' => 'refresh_token', 'refresh_token' => $params['refresh_token']); $post_string = ''; foreach ($parameters as $key => $value) { $post_string .= $key . '=' . urlencode(utf8_encode(trim($value))) . '&'; } $post_string = substr($post_string, 0, -1); $result = $this->sendRequest('https://' . $api_server . '/v1/identity/openidconnect/tokenservice', $post_string); $result_array = json_decode($result, true); return $result_array; } function getUserInfo($params) { if ( MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live' ) { $api_server = 'api.paypal.com'; } else { $api_server = 'api.sandbox.paypal.com'; } $result = $this->sendRequest('https://' . $api_server . '/v1/identity/openidconnect/userinfo/?schema=openid&access_token=' . $params['access_token']); $result_array = json_decode($result, true); return $result_array; } function getTestLinkInfo() { $dialog_title = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_TITLE; $dialog_button_close = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_BUTTON_CLOSE; $dialog_success = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_SUCCESS; $dialog_failed = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_FAILED; $dialog_error = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_ERROR; $dialog_connection_time = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_TIME; $test_url = tep_href_link('modules_content.php', 'module=' . $this->code . '&action=install&subaction=conntest'); $js = <<<EOD <script> $(function() { $('#tcdprogressbar').progressbar({ value: false }); }); function openTestConnectionDialog() { var d = $('<div>').html($('#testConnectionDialog').html()).dialog({ modal: true, title: '{$dialog_title}', buttons: { '{$dialog_button_close}': function () { $(this).dialog('destroy'); } } }); var timeStart = new Date().getTime(); $.ajax({ url: '{$test_url}' }).done(function(data) { if ( data == '1' ) { d.find('#testConnectionDialogProgress').html('<p style="font-weight: bold; color: green;">{$dialog_success}</p>'); } else { d.find('#testConnectionDialogProgress').html('<p style="font-weight: bold; color: red;">{$dialog_failed}</p>'); } }).fail(function() { d.find('#testConnectionDialogProgress').html('<p style="font-weight: bold; color: red;">{$dialog_error}</p>'); }).always(function() { var timeEnd = new Date().getTime(); var timeTook = new Date(0, 0, 0, 0, 0, 0, timeEnd-timeStart); d.find('#testConnectionDialogProgress').append('<p>{$dialog_connection_time} ' + timeTook.getSeconds() + '.' + timeTook.getMilliseconds() + 's</p>'); }); } </script> EOD; $info = '<p><img src="images/icons/locked.gif" border="0">&nbsp;<a href="javascript:openTestConnectionDialog();" style="text-decoration: underline; font-weight: bold;">' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_LINK_TITLE . '</a></p>' . '<div id="testConnectionDialog" style="display: none;"><p>'; if ( MODULE_CONTENT_PAYPAL_LOGIN_SERVER_TYPE == 'Live' ) { $info .= 'Live Server:<br />https://api.paypal.com'; } else { $info .= 'Sandbox Server:<br />https://api.sandbox.paypal.com'; } $info .= '</p><div id="testConnectionDialogProgress"><p>' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_CONNECTION_GENERAL_TEXT . '</p><div id="tcdprogressbar"></div></div></div>' . $js; return $info; } function getTestConnectionResult() { $params = array('code' => 'oscom2_conn_test'); $response = $this->getToken($params); if ( is_array($response) && isset($response['error']) ) { return 1; } return -1; } function getShowUrlsInfo() { $dialog_title = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_TITLE; $dialog_button_close = MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_BUTTON_CLOSE; $js = <<<EOD <script> function openShowUrlsDialog() { var d = $('<div>').html($('#showUrlsDialog').html()).dialog({ autoOpen: false, modal: true, title: '{$dialog_title}', buttons: { '{$dialog_button_close}': function () { $(this).dialog('destroy'); } }, width: 600 }); d.dialog('open'); } </script> EOD; $info = '<p><img src="images/icon_info.gif" border="0">&nbsp;<a href="javascript:openShowUrlsDialog();" style="text-decoration: underline; font-weight: bold;">' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_LINK_TITLE . '</a></p>' . '<div id="showUrlsDialog" style="display: none;">' . ' <p><strong>' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_RETURN_TEXT . '</strong><br /><br />' . htmlspecialchars(str_replace('&amp;', '&', tep_catalog_href_link('login.php', 'action=paypal_login', 'SSL'))) . '</p>' . ' <p><strong>' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_PRIVACY_TEXT . '</strong><br /><br />' . htmlspecialchars(str_replace('&amp;', '&', tep_catalog_href_link('privacy.php', '', 'SSL'))) . '</p>' . ' <p><strong>' . MODULE_CONTENT_PAYPAL_LOGIN_DIALOG_URLS_TERMS_TEXT . '</strong><br /><br />' . htmlspecialchars(str_replace('&amp;', '&', tep_catalog_href_link('conditions.php', '', 'SSL'))) . '</p>' . '</div>' . $js; return $info; } function hasAttribute($attribute) { return in_array($attribute, explode(';', MODULE_CONTENT_PAYPAL_LOGIN_ATTRIBUTES)); } function get_default_attributes() { $data = array(); foreach ( cm_paypal_login_get_attributes() as $group => $attributes ) { foreach ( $attributes as $attribute => $scope ) { $data[] = $attribute; } } return $data; } } function cm_paypal_login_get_attributes() { return array('personal' => array('full_name' => 'profile', 'date_of_birth' => 'profile', 'age_range' => 'https://uri.paypal.com/services/paypalattributes', 'gender' => 'profile'), 'address' => array('email_address' => 'email', 'street_address' => 'address', 'city' => 'address', 'state' => 'address', 'country' => 'address', 'zip_code' => 'address', 'phone' => 'phone'), 'account' => array('account_status' => 'https://uri.paypal.com/services/paypalattributes', 'account_type' => 'https://uri.paypal.com/services/paypalattributes', 'account_creation_date' => 'https://uri.paypal.com/services/paypalattributes', 'time_zone' => 'profile', 'locale' => 'profile', 'language' => 'profile'), 'checkout' => array('seamless_checkout' => 'https://uri.paypal.com/services/expresscheckout')); } function cm_paypal_login_get_required_attributes() { return array('full_name', 'email_address', 'street_address', 'city', 'state', 'country', 'zip_code'); } function cm_paypal_login_show_attributes($text) { $active = explode(';', $text); $output = ''; foreach ( cm_paypal_login_get_attributes() as $group => $attributes ) { foreach ( $attributes as $attribute => $scope ) { if ( in_array($attribute, $active) ) { $output .= constant('MODULE_CONTENT_PAYPAL_LOGIN_ATTR_' . $attribute) . '<br />'; } } } if ( !empty($output) ) { $output = substr($output, 0, -6); } return $output; } function cm_paypal_login_edit_attributes($values, $key) { $values_array = explode(';', $values); $required_array = cm_paypal_login_get_required_attributes(); $output = ''; foreach ( cm_paypal_login_get_attributes() as $group => $attributes ) { $output .= '<strong>' . constant('MODULE_CONTENT_PAYPAL_LOGIN_ATTR_GROUP_' . $group) . '</strong><br />'; foreach ( $attributes as $attribute => $scope ) { if ( in_array($attribute, $required_array) ) { $output .= tep_draw_radio_field('cm_paypal_login_attributes_tmp_' . $attribute, $attribute, true) . '&nbsp;'; } else { $output .= tep_draw_checkbox_field('cm_paypal_login_attributes[]', $attribute, in_array($attribute, $values_array)) . '&nbsp;'; } $output .= constant('MODULE_CONTENT_PAYPAL_LOGIN_ATTR_' . $attribute) . '<br />'; } } if (!empty($output)) { $output = '<br />' . substr($output, 0, -6); } $output .= tep_draw_hidden_field('configuration[' . $key . ']', '', 'id="cmpl_attributes"'); $output .= '<script> function cmpl_update_cfg_value() { var cmpl_selected_attributes = \'\'; if ($(\'input[name^="cm_paypal_login_attributes_tmp_"]\').length > 0) { $(\'input[name^="cm_paypal_login_attributes_tmp_"]\').each(function() { cmpl_selected_attributes += $(this).attr(\'value\') + \';\'; }); } if ($(\'input[name="cm_paypal_login_attributes[]"]\').length > 0) { $(\'input[name="cm_paypal_login_attributes[]"]:checked\').each(function() { cmpl_selected_attributes += $(this).attr(\'value\') + \';\'; }); } if (cmpl_selected_attributes.length > 0) { cmpl_selected_attributes = cmpl_selected_attributes.substring(0, cmpl_selected_attributes.length - 1); } $(\'#cmpl_attributes\').val(cmpl_selected_attributes); } $(function() { cmpl_update_cfg_value(); if ($(\'input[name="cm_paypal_login_attributes[]"]\').length > 0) { $(\'input[name="cm_paypal_login_attributes[]"]\').change(function() { cmpl_update_cfg_value(); }); } }); </script>'; return $output; } ?>
geraldbullard/osCommerce-v2.3.4-Responsive-Admin
includes/modules/content/login/cm_paypal_login.php
PHP
gpl-2.0
31,720
<?php /* @var $this CategoryController */ /* @var $model Category */ $this->breadcrumbs = array( 'Categories' => array('index'), 'Manage', ); Yii::app()->clientScript->registerScript('search', " $('.search-button').click(function(){ $('.search-form').toggle(); return false; }); $('.search-form form').submit(function(){ $('#category-grid').yiiGridView('update', { data: $(this).serialize() }); return false; }); "); ?> <h1>Chuyên mục</h1> <?php echo CHtml::link('Thêm mới', '#', array('class' => 'search-button')); ?> <div class="search-form" style="display:none"> <?php $this->renderPartial('_form', array( 'model' => $model, )); ?> </div><!-- search-form --> <?php $form = $this->beginWidget('CActiveForm', array( 'enableAjaxValidation' => TRUE, )); ?> <?php $this->widget('zii.widgets.grid.CGridView', array( 'id' => 'category-grid', 'dataProvider' => $model->search(), 'filter' => $model, 'selectableRows' => 2, 'columns' => array( array( 'id' => 'autoId', 'class' => 'CCheckBoxColumn', 'selectableRows' => '50', ), array( 'name' => 'id', 'value' => '$data->id', 'type' => 'raw', 'filter' => FALSE, ), array( 'name' => 'name', 'value' => 'CHtml::textField("sortName[$data->id]",$data->name,array("style"=>"width:100%;"))', 'type' => 'raw', ), array( 'name' => 'rank', 'value' => 'CHtml::textField("sortOrder[$data->id]",$data->rank,array("style"=>"width:50px;"))', 'type' => 'raw', 'htmlOptions' => array("width" => "50px"), ), array( 'name' => 'status', 'value' => '$data->status==1?"Hiện":"Ẩn"', 'filter' => array(1 => 'Hiện', 0 => 'Ẩn'), ), array( 'class' => 'CButtonColumn', ), ), )); ?> <script> function reloadGrid(data) { $.fn.yiiGridView.update('category-grid'); } </script> <?php echo CHtml::ajaxSubmitButton('Filter', array('category/ajaxUpdate'), array(), array("style" => "display:none;")); ?> <?php echo CHtml::ajaxSubmitButton('Hiện', array('category/ajaxUpdate', 'act' => 'doActive'), array('success' => 'reloadGrid')); ?> <?php echo CHtml::ajaxSubmitButton('Ẩn', array('category/ajaxUpdate', 'act' => 'doInactive'), array('success' => 'reloadGrid')); ?> <?php echo CHtml::ajaxSubmitButton('Xóa', array('category/ajaxUpdate', 'act' => 'doDelete'), array('success' => 'reloadGrid', 'beforeSend' => 'function(){ return confirm("Bạn có chắc chắn muốn xóa những chuyên mục được chọn?") }',)); ?> <?php echo CHtml::ajaxSubmitButton('Cập nhật thứ hạng', array('category/ajaxUpdate', 'act' => 'doSortOrder'), array('success' => 'reloadGrid')); ?> <?php echo CHtml::ajaxSubmitButton('Cập nhật tên', array('category/ajaxUpdate', 'act' => 'doSortName'), array('success' => 'reloadGrid')); ?> <?php $this->endWidget(); ?>
sonha/camera
protected/views/admin/category/admin.php
PHP
gpl-2.0
3,233
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.support; import java.util.Collection; import java.util.Map; import org.springframework.ui.ModelMap; import org.springframework.validation.DataBinder; /** * A {@link ModelMap} implementation of {@link RedirectAttributes} that formats * values as Strings using a {@link DataBinder}. Also provides a place to store * flash attributes so they can survive a redirect without the need to be * embedded in the redirect URL. * * @author Rossen Stoyanchev * @since 3.1 */ @SuppressWarnings("serial") public class RedirectAttributesModelMap extends ModelMap implements RedirectAttributes { private final DataBinder dataBinder; private final ModelMap flashAttributes = new ModelMap(); /** * Default constructor without a DataBinder. * Attribute values are converted to String via {@link #toString()}. */ public RedirectAttributesModelMap() { this(null); } /** * Constructor with a DataBinder. * @param dataBinder used to format attribute values as Strings */ public RedirectAttributesModelMap(DataBinder dataBinder) { this.dataBinder = dataBinder; } /** * Return the attributes candidate for flash storage or an empty Map. */ @Override public Map<String, ?> getFlashAttributes() { return this.flashAttributes; } /** * {@inheritDoc} * <p>Formats the attribute value as a String before adding it. */ @Override public RedirectAttributesModelMap addAttribute(String attributeName, Object attributeValue) { super.addAttribute(attributeName, formatValue(attributeValue)); return this; } private String formatValue(Object value) { if (value == null) { return null; } return (this.dataBinder != null ? this.dataBinder.convertIfNecessary(value, String.class) : value.toString()); } /** * {@inheritDoc} * <p>Formats the attribute value as a String before adding it. */ @Override public RedirectAttributesModelMap addAttribute(Object attributeValue) { super.addAttribute(attributeValue); return this; } /** * {@inheritDoc} * <p>Each attribute value is formatted as a String before being added. */ @Override public RedirectAttributesModelMap addAllAttributes(Collection<?> attributeValues) { super.addAllAttributes(attributeValues); return this; } /** * {@inheritDoc} * <p>Each attribute value is formatted as a String before being added. */ @Override public RedirectAttributesModelMap addAllAttributes(Map<String, ?> attributes) { if (attributes != null) { for (String key : attributes.keySet()) { addAttribute(key, attributes.get(key)); } } return this; } /** * {@inheritDoc} * <p>Each attribute value is formatted as a String before being merged. */ @Override public RedirectAttributesModelMap mergeAttributes(Map<String, ?> attributes) { if (attributes != null) { for (String key : attributes.keySet()) { if (!containsKey(key)) { addAttribute(key, attributes.get(key)); } } } return this; } @Override public Map<String, Object> asMap() { return this; } /** * {@inheritDoc} * <p>The value is formatted as a String before being added. */ @Override public Object put(String key, Object value) { return super.put(key, formatValue(value)); } /** * {@inheritDoc} * <p>Each value is formatted as a String before being added. */ @Override public void putAll(Map<? extends String, ? extends Object> map) { if (map != null) { for (String key : map.keySet()) { put(key, formatValue(map.get(key))); } } } @Override public RedirectAttributes addFlashAttribute(String attributeName, Object attributeValue) { this.flashAttributes.addAttribute(attributeName, attributeValue); return this; } @Override public RedirectAttributes addFlashAttribute(Object attributeValue) { this.flashAttributes.addAttribute(attributeValue); return this; } }
lamsfoundation/lams
3rdParty_sources/spring/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMap.java
Java
gpl-2.0
4,502
<?php namespace Drupal\contractualisation\Form; use Drupal\Core\Entity\EntityForm; use Drupal\Core\Form\FormStateInterface; /** * Class contractualisationTypeForm. * * @package Drupal\contractualisation\Form */ class contractualisationTypeForm extends EntityForm { /** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); $contractualisation_type = $this->entity; $form['label'] = [ '#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#default_value' => $contractualisation_type->label(), '#description' => $this->t("Label for the Contractualisation type."), '#required' => TRUE, ]; $form['id'] = [ '#type' => 'machine_name', '#default_value' => $contractualisation_type->id(), '#machine_name' => [ 'exists' => '\Drupal\contractualisation\Entity\contractualisationType::load', ], '#disabled' => !$contractualisation_type->isNew(), ]; /* You will need additional form elements for your custom properties. */ return $form; } /** * {@inheritdoc} */ public function save(array $form, FormStateInterface $form_state) { $contractualisation_type = $this->entity; $status = $contractualisation_type->save(); switch ($status) { case SAVED_NEW: drupal_set_message($this->t('Created the %label Contractualisation type.', [ '%label' => $contractualisation_type->label(), ])); break; default: drupal_set_message($this->t('Saved the %label Contractualisation type.', [ '%label' => $contractualisation_type->label(), ])); } $form_state->setRedirectUrl($contractualisation_type->toUrl('collection')); } }
lrakotoarimino/obsfoncier
modules/contractualisation/src/Form/contractualisationTypeForm.php
PHP
gpl-2.0
1,828
package auctionsniper.ui; import auctionsniper.SniperSnapshot; import auctionsniper.SniperState; public enum Column { ITEM_IDENTIFIER("Item") { @Override public Object valueIn(SniperSnapshot snapshot) { return snapshot.itemId; } }, LAST_PRICE("Last Price") { @Override public Object valueIn(SniperSnapshot snapshot) { return snapshot.lastPrice; } }, LAST_BID("Last Bid") { @Override public Object valueIn(SniperSnapshot snapshot) { return snapshot.lastBid; } }, SNIPER_STATE("State") { @Override public Object valueIn(SniperSnapshot snapshot) { return SniperState.textFor(snapshot.state); } }; abstract public Object valueIn(SniperSnapshot snapshot); public final String name; private Column(String name) { this.name = name; } public static Column at(int offset) { return values()[offset]; } }
alevincenzi/goos
src/auctionsniper/ui/Column.java
Java
gpl-2.0
904
<?php get_header(); ?> <div id="breadcumb"> <div class="container"> <?php if (function_exists('dimox_breadcrumbs')) dimox_breadcrumbs();?> </div> </div> <div id="inner-page" <?php post_class(); ?>> <div class="container" id="inner-wrapper"> <?php if (get_post_meta($post->ID, 'sidebar_position', true ) =='left') { ?> <div class="one_fourth" id="sidebar"> <?php if ( !function_exists('dynamic_sidebar') || ! generated_dynamic_sidebar('Page Sidebar') ) ; ?> </div> <div class="three_fourth last" id="page-content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post-layout post-<?php the_ID();?>"> <h2 class="post-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h2> <?php if(has_post_thumbnail()) { ?> <?php $post_thumb = get_post_thumbnail_id(); $post_image = vt_resize( $post_thumb,'' , 700, 220, true );?> <div class="post-image"> <a href="<?php the_permalink();?>" class="post-load"><img src="<?php echo $post_image[url]; ?>" width="<?php echo $post_image[width]; ?>" height="<?php echo $post_image[height]; ?>" alt="<?php the_title();?>" /></a> </div> <?php } else { ?> <?php } ?> <div class="post-content"> <?php global $more; $more = false; ?><?php the_content(); ?><?php $more = true; ?> </div> <div class="post-meta"> <ul class="post-meta-info"> <li class="post-author"><strong><?php _e('Posted By : ','epanel');?></strong><?php the_author();?></li> <li class="post-time"><strong><?php _e('On : ','epanel');?></strong><?php the_time(get_option('ep_blog_date_format')); ?></li> <li class="post-comments"><a href="<?php the_permalink();?>"><?php comments_number( __(' Leave a comment', 'epanel'), __(' One comment', 'epanel'), __(' % comments', 'epanel')); ?></a></li> </ul> </div> <?php wp_link_pages(); ?> </div><!-- End Post layout --> <?php endwhile; endif; ?> <div id="comments"> <?php comments_template(); ?> </div> </div> <div class="clearfix"></div> <?php } else if (get_post_meta($post->ID, 'sidebar_position', true ) =='right') { ?> <div class="three_fourth" id="page-content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post-layout post-<?php the_ID();?>"> <h2 class="post-title"><a href="<?php the_permalink();?>"><?php the_title();?></a></h2> <?php if(has_post_thumbnail()) { ?> <?php $post_thumb = get_post_thumbnail_id(); $post_image = vt_resize( $post_thumb,'' , 700, 220, true );?> <div class="post-image"> <a href="<?php the_permalink();?>" class="post-load"><img src="<?php echo $post_image[url]; ?>" width="<?php echo $post_image[width]; ?>" height="<?php echo $post_image[height]; ?>" alt="<?php the_title();?>" /></a> </div> <?php } else { ?> <?php } ?> <div class="post-content"> <?php global $more; $more = false; ?><?php the_content(); ?><?php $more = true; ?> </div> <div class="post-meta"> <ul class="post-meta-info"> <li class="post-author"><strong><?php _e('Posted By : ','epanel');?></strong><?php the_author();?></li> <li class="post-time"><strong><?php _e('On : ','epanel');?></strong><?php the_time(get_option('ep_blog_date_format')); ?></li> <li class="post-comments"><a href="<?php the_permalink();?>"><?php comments_number( __(' Leave a comment', 'epanel'), __(' One comment', 'epanel'), __(' % comments', 'epanel')); ?></a></li> </ul> </div> <?php wp_link_pages(); ?> </div><!-- End Post layout --> <?php endwhile; endif; ?> <div id="comments"> <?php comments_template(); ?> </div> </div> <div class="one_fourth last" id="sidebar"> <?php if ( !function_exists('dynamic_sidebar') || ! generated_dynamic_sidebar('Page Sidebar') ) ; ?> </div> <div class="clearfix"></div> <?php } else { ?> <p>Please edit this post and select a sidebar position</p> <?php } ?> </div> </div> <?php get_footer();?>
robbiespire/paQui
wp-content/themes/express_store/single.php
PHP
gpl-2.0
4,515
class OrgUnit < ApplicationRecord # -- associations has_many :merkmale, as: :merkmalfor, dependent: :destroy has_many :addresses, as: :addressfor, dependent: :destroy # -- configuration has_ancestry :cache_depth =>true, :orphan_strategy => :adopt acts_as_list :scope => [:ancestry] accepts_nested_attributes_for :merkmale, :addresses, allow_destroy: true validates_associated :merkmale, :addresses # -- validations and callbacks validates :name, presence: true, uniqueness: true def to_s "#{name.to_s}" end end
swobspace/boskop
app/models/org_unit.rb
Ruby
gpl-2.0
545
using System.Collections.Generic; namespace FormGenerator.Fields { /// <summary> /// Class used to represent a tab item. /// </summary> // ReSharper disable once ClassNeverInstantiated.Global - used by IOC. public class TabItem : Field { /// <summary> /// Constructor. /// </summary> public TabItem() : base("TabItem") { } /// <summary> /// Any properties that should not be processed. /// This has been overridden so that the header property will be processed. /// </summary> /// <returns>The list of properties to ignore.</returns> protected override List<string> IgnoredProperties() { List<string> properties = base.IgnoredProperties(); properties.Remove("Header"); return properties; } } }
MotorViper/FormGenerator
FormGenerator/Fields/TabItem.cs
C#
gpl-2.0
875
/* * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "interpreter/interpreter.hpp" #include "memory/resourceArea.hpp" #include "oops/markOop.hpp" #include "oops/method.hpp" #include "oops/oop.inline.hpp" #include "prims/methodHandles.hpp" #include "runtime/frame.inline.hpp" #include "runtime/handles.inline.hpp" #include "runtime/javaCalls.hpp" #include "runtime/monitorChunk.hpp" #include "runtime/os.hpp" #include "runtime/signature.hpp" #include "runtime/stubCodeGenerator.hpp" #include "runtime/stubRoutines.hpp" #include "vmreg_x86.inline.hpp" #ifdef COMPILER1 #include "c1/c1_Runtime1.hpp" #include "runtime/vframeArray.hpp" #endif #ifdef ASSERT void RegisterMap::check_location_valid() { } #endif PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC // Profiling/safepoint support bool frame::safe_for_sender(JavaThread *thread) { address sp = (address)_sp; address fp = (address)_fp; address unextended_sp = (address)_unextended_sp; // consider stack guards when trying to determine "safe" stack pointers static size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0; size_t usable_stack_size = thread->stack_size() - stack_guard_size; // sp must be within the usable part of the stack (not in guards) bool sp_safe = (sp < thread->stack_base()) && (sp >= thread->stack_base() - usable_stack_size); if (!sp_safe) { return false; } // unextended sp must be within the stack and above or equal sp bool unextended_sp_safe = (unextended_sp < thread->stack_base()) && (unextended_sp >= sp); if (!unextended_sp_safe) { return false; } // an fp must be within the stack and above (but not equal) sp // second evaluation on fp+ is added to handle situation where fp is -1 bool fp_safe = (fp < thread->stack_base() && (fp > sp) && (((fp + (return_addr_offset * sizeof(void*))) < thread->stack_base()))); // We know sp/unextended_sp are safe only fp is questionable here // If the current frame is known to the code cache then we can attempt to // to construct the sender and do some validation of it. This goes a long way // toward eliminating issues when we get in frame construction code if (_cb != NULL ) { // First check if frame is complete and tester is reliable // Unfortunately we can only check frame complete for runtime stubs and nmethod // other generic buffer blobs are more problematic so we just assume they are // ok. adapter blobs never have a frame complete and are never ok. if (!_cb->is_frame_complete_at(_pc)) { if (_cb->is_nmethod() || _cb->is_adapter_blob() || _cb->is_runtime_stub()) { return false; } } // Could just be some random pointer within the codeBlob if (!_cb->code_contains(_pc)) { return false; } // Entry frame checks if (is_entry_frame()) { // an entry frame must have a valid fp. if (!fp_safe) return false; // Validate the JavaCallWrapper an entry frame must have address jcw = (address)entry_frame_call_wrapper(); bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > fp); return jcw_safe; } intptr_t* sender_sp = NULL; address sender_pc = NULL; if (is_interpreted_frame()) { // fp must be safe if (!fp_safe) { return false; } sender_pc = (address) this->fp()[return_addr_offset]; sender_sp = (intptr_t*) addr_at(sender_sp_offset); } else { // must be some sort of compiled/runtime frame // fp does not have to be safe (although it could be check for c1?) // check for a valid frame_size, otherwise we are unlikely to get a valid sender_pc if (_cb->frame_size() <= 0) { return false; } sender_sp = _unextended_sp + _cb->frame_size(); // On Intel the return_address is always the word on the stack sender_pc = (address) *(sender_sp-1); } // If the potential sender is the interpreter then we can do some more checking if (Interpreter::contains(sender_pc)) { // ebp is always saved in a recognizable place in any code we generate. However // only if the sender is interpreted/call_stub (c1 too?) are we certain that the saved ebp // is really a frame pointer. intptr_t *saved_fp = (intptr_t*)*(sender_sp - frame::sender_sp_offset); bool saved_fp_safe = ((address)saved_fp < thread->stack_base()) && (saved_fp > sender_sp); if (!saved_fp_safe) { return false; } // construct the potential sender frame sender(sender_sp, saved_fp, sender_pc); return sender.is_interpreted_frame_valid(thread); } // We must always be able to find a recognizable pc CodeBlob* sender_blob = CodeCache::find_blob_unsafe(sender_pc); if (sender_pc == NULL || sender_blob == NULL) { return false; } // Could be a zombie method if (sender_blob->is_zombie() || sender_blob->is_unloaded()) { return false; } // Could just be some random pointer within the codeBlob if (!sender_blob->code_contains(sender_pc)) { return false; } // We should never be able to see an adapter if the current frame is something from code cache if (sender_blob->is_adapter_blob()) { return false; } // Could be the call_stub if (StubRoutines::returns_to_call_stub(sender_pc)) { intptr_t *saved_fp = (intptr_t*)*(sender_sp - frame::sender_sp_offset); bool saved_fp_safe = ((address)saved_fp < thread->stack_base()) && (saved_fp > sender_sp); if (!saved_fp_safe) { return false; } // construct the potential sender frame sender(sender_sp, saved_fp, sender_pc); // Validate the JavaCallWrapper an entry frame must have address jcw = (address)sender.entry_frame_call_wrapper(); bool jcw_safe = (jcw < thread->stack_base()) && ( jcw > (address)sender.fp()); return jcw_safe; } if (sender_blob->is_nmethod()) { nmethod* nm = sender_blob->as_nmethod_or_null(); if (nm != NULL) { if (nm->is_deopt_mh_entry(sender_pc) || nm->is_deopt_entry(sender_pc)) { return false; } } } // If the frame size is 0 something (or less) is bad because every nmethod has a non-zero frame size // because the return address counts against the callee's frame. if (sender_blob->frame_size() <= 0) { assert(!sender_blob->is_nmethod(), "should count return address at least"); return false; } // We should never be able to see anything here except an nmethod. If something in the // code cache (current frame) is called by an entity within the code cache that entity // should not be anything but the call stub (already covered), the interpreter (already covered) // or an nmethod. if (!sender_blob->is_nmethod()) { return false; } // Could put some more validation for the potential non-interpreted sender // frame we'd create by calling sender if I could think of any. Wait for next crash in forte... // One idea is seeing if the sender_pc we have is one that we'd expect to call to current cb // We've validated the potential sender that would be created return true; } // Must be native-compiled frame. Since sender will try and use fp to find // linkages it must be safe if (!fp_safe) { return false; } // Will the pc we fetch be non-zero (which we'll find at the oldest frame) if ( (address) this->fp()[return_addr_offset] == NULL) return false; // could try and do some more potential verification of native frame if we could think of some... return true; } void frame::patch_pc(Thread* thread, address pc) { address* pc_addr = &(((address*) sp())[-1]); if (TracePcPatching) { tty->print_cr("patch_pc at address " INTPTR_FORMAT " [" INTPTR_FORMAT " -> " INTPTR_FORMAT "]", pc_addr, *pc_addr, pc); } // Either the return address is the original one or we are going to // patch in the same address that's already there. assert(_pc == *pc_addr || pc == *pc_addr, "must be"); *pc_addr = pc; _cb = CodeCache::find_blob(pc); address original_pc = nmethod::get_deopt_original_pc(this); if (original_pc != NULL) { assert(original_pc == _pc, "expected original PC to be stored before patching"); _deopt_state = is_deoptimized; // leave _pc as is } else { _deopt_state = not_deoptimized; _pc = pc; } } bool frame::is_interpreted_frame() const { return Interpreter::contains(pc()); } int frame::frame_size(RegisterMap* map) const { frame sender = this->sender(map); return sender.sp() - sp(); } intptr_t* frame::entry_frame_argument_at(int offset) const { // convert offset to index to deal with tsi int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize); // Entry frame's arguments are always in relation to unextended_sp() return &unextended_sp()[index]; } // sender_sp #ifdef CC_INTERP intptr_t* frame::interpreter_frame_sender_sp() const { assert(is_interpreted_frame(), "interpreted frame expected"); // QQQ why does this specialize method exist if frame::sender_sp() does same thing? // seems odd and if we always know interpreted vs. non then sender_sp() is really // doing too much work. return get_interpreterState()->sender_sp(); } // monitor elements BasicObjectLock* frame::interpreter_frame_monitor_begin() const { return get_interpreterState()->monitor_base(); } BasicObjectLock* frame::interpreter_frame_monitor_end() const { return (BasicObjectLock*) get_interpreterState()->stack_base(); } #else // CC_INTERP intptr_t* frame::interpreter_frame_sender_sp() const { assert(is_interpreted_frame(), "interpreted frame expected"); return (intptr_t*) at(interpreter_frame_sender_sp_offset); } void frame::set_interpreter_frame_sender_sp(intptr_t* sender_sp) { assert(is_interpreted_frame(), "interpreted frame expected"); ptr_at_put(interpreter_frame_sender_sp_offset, (intptr_t) sender_sp); } // monitor elements BasicObjectLock* frame::interpreter_frame_monitor_begin() const { return (BasicObjectLock*) addr_at(interpreter_frame_monitor_block_bottom_offset); } BasicObjectLock* frame::interpreter_frame_monitor_end() const { BasicObjectLock* result = (BasicObjectLock*) *addr_at(interpreter_frame_monitor_block_top_offset); // make sure the pointer points inside the frame assert(sp() <= (intptr_t*) result, "monitor end should be above the stack pointer"); assert((intptr_t*) result < fp(), "monitor end should be strictly below the frame pointer"); return result; } void frame::interpreter_frame_set_monitor_end(BasicObjectLock* value) { *((BasicObjectLock**)addr_at(interpreter_frame_monitor_block_top_offset)) = value; } // Used by template based interpreter deoptimization void frame::interpreter_frame_set_last_sp(intptr_t* sp) { *((intptr_t**)addr_at(interpreter_frame_last_sp_offset)) = sp; } #endif // CC_INTERP frame frame::sender_for_entry_frame(RegisterMap* map) const { assert(map != NULL, "map must be set"); // Java frame called from C; skip all C frames and return top C // frame of that chunk as the sender JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor(); assert(!entry_frame_is_first(), "next Java fp must be non zero"); assert(jfa->last_Java_sp() > sp(), "must be above this frame on stack"); map->clear(); assert(map->include_argument_oops(), "should be set by clear"); if (jfa->last_Java_pc() != NULL ) { frame fr(jfa->last_Java_sp(), jfa->last_Java_fp(), jfa->last_Java_pc()); return fr; } frame fr(jfa->last_Java_sp(), jfa->last_Java_fp()); return fr; } //------------------------------------------------------------------------------ // frame::verify_deopt_original_pc // // Verifies the calculated original PC of a deoptimization PC for the // given unextended SP. The unextended SP might also be the saved SP // for MethodHandle call sites. #ifdef ASSERT void frame::verify_deopt_original_pc(nmethod* nm, intptr_t* unextended_sp, bool is_method_handle_return) { frame fr; // This is ugly but it's better than to change {get,set}_original_pc // to take an SP value as argument. And it's only a debugging // method anyway. fr._unextended_sp = unextended_sp; address original_pc = nm->get_original_pc(&fr); assert(nm->insts_contains(original_pc), "original PC must be in nmethod"); assert(nm->is_method_handle_return(original_pc) == is_method_handle_return, "must be"); } #endif //------------------------------------------------------------------------------ // frame::adjust_unextended_sp void frame::adjust_unextended_sp() { // If we are returning to a compiled MethodHandle call site, the // saved_fp will in fact be a saved value of the unextended SP. The // simplest way to tell whether we are returning to such a call site // is as follows: nmethod* sender_nm = (_cb == NULL) ? NULL : _cb->as_nmethod_or_null(); if (sender_nm != NULL) { // If the sender PC is a deoptimization point, get the original // PC. For MethodHandle call site the unextended_sp is stored in // saved_fp. if (sender_nm->is_deopt_mh_entry(_pc)) { DEBUG_ONLY(verify_deopt_mh_original_pc(sender_nm, _fp)); _unextended_sp = _fp; } else if (sender_nm->is_deopt_entry(_pc)) { DEBUG_ONLY(verify_deopt_original_pc(sender_nm, _unextended_sp)); } else if (sender_nm->is_method_handle_return(_pc)) { _unextended_sp = _fp; } } } //------------------------------------------------------------------------------ // frame::update_map_with_saved_link void frame::update_map_with_saved_link(RegisterMap* map, intptr_t** link_addr) { // The interpreter and compiler(s) always save EBP/RBP in a known // location on entry. We must record where that location is // so this if EBP/RBP was live on callout from c2 we can find // the saved copy no matter what it called. // Since the interpreter always saves EBP/RBP if we record where it is then // we don't have to always save EBP/RBP on entry and exit to c2 compiled // code, on entry will be enough. map->set_location(rbp->as_VMReg(), (address) link_addr); #ifdef AMD64 // this is weird "H" ought to be at a higher address however the // oopMaps seems to have the "H" regs at the same address and the // vanilla register. // XXXX make this go away if (true) { map->set_location(rbp->as_VMReg()->next(), (address) link_addr); } #endif // AMD64 } //------------------------------------------------------------------------------ // frame::sender_for_interpreter_frame frame frame::sender_for_interpreter_frame(RegisterMap* map) const { // SP is the raw SP from the sender after adapter or interpreter // extension. intptr_t* sender_sp = this->sender_sp(); // This is the sp before any possible extension (adapter/locals). intptr_t* unextended_sp = interpreter_frame_sender_sp(); #if defined(COMPILER2) || defined(JVMCI) if (map->update_map()) { update_map_with_saved_link(map, (intptr_t**) addr_at(link_offset)); } #endif // COMPILER2 || JVMCI return frame(sender_sp, unextended_sp, link(), sender_pc()); } //------------------------------------------------------------------------------ // frame::sender_for_compiled_frame frame frame::sender_for_compiled_frame(RegisterMap* map) const { assert(map != NULL, "map must be set"); // frame owned by optimizing compiler assert(_cb->frame_size() >= 0, "must have non-zero frame size"); intptr_t* sender_sp = unextended_sp() + _cb->frame_size(); intptr_t* unextended_sp = sender_sp; // On Intel the return_address is always the word on the stack address sender_pc = (address) *(sender_sp-1); // This is the saved value of EBP which may or may not really be an FP. // It is only an FP if the sender is an interpreter frame (or C1?). intptr_t** saved_fp_addr = (intptr_t**) (sender_sp - frame::sender_sp_offset); if (map->update_map()) { // Tell GC to use argument oopmaps for some runtime stubs that need it. // For C1, the runtime stub might not have oop maps, so set this flag // outside of update_register_map. map->set_include_argument_oops(_cb->caller_must_gc_arguments(map->thread())); if (_cb->oop_maps() != NULL) { OopMapSet::update_register_map(this, map); } // Since the prolog does the save and restore of EBP there is no oopmap // for it so we must fill in its location as if there was an oopmap entry // since if our caller was compiled code there could be live jvm state in it. update_map_with_saved_link(map, saved_fp_addr); } assert(sender_sp != sp(), "must have changed"); return frame(sender_sp, unextended_sp, *saved_fp_addr, sender_pc); } //------------------------------------------------------------------------------ // frame::sender frame frame::sender(RegisterMap* map) const { // Default is we done have to follow them. The sender_for_xxx will // update it accordingly map->set_include_argument_oops(false); if (is_entry_frame()) return sender_for_entry_frame(map); if (is_interpreted_frame()) return sender_for_interpreter_frame(map); assert(_cb == CodeCache::find_blob(pc()),"Must be the same"); if (_cb != NULL) { return sender_for_compiled_frame(map); } // Must be native-compiled frame, i.e. the marshaling code for native // methods that exists in the core system. return frame(sender_sp(), link(), sender_pc()); } bool frame::interpreter_frame_equals_unpacked_fp(intptr_t* fp) { assert(is_interpreted_frame(), "must be interpreter frame"); Method* method = interpreter_frame_method(); // When unpacking an optimized frame the frame pointer is // adjusted with: int diff = (method->max_locals() - method->size_of_parameters()) * Interpreter::stackElementWords; return _fp == (fp - diff); } void frame::pd_gc_epilog() { // nothing done here now } bool frame::is_interpreted_frame_valid(JavaThread* thread) const { // QQQ #ifdef CC_INTERP #else assert(is_interpreted_frame(), "Not an interpreted frame"); // These are reasonable sanity checks if (fp() == 0 || (intptr_t(fp()) & (wordSize-1)) != 0) { return false; } if (sp() == 0 || (intptr_t(sp()) & (wordSize-1)) != 0) { return false; } if (fp() + interpreter_frame_initial_sp_offset < sp()) { return false; } // These are hacks to keep us out of trouble. // The problem with these is that they mask other problems if (fp() <= sp()) { // this attempts to deal with unsigned comparison above return false; } // do some validation of frame elements // first the method Method* m = *interpreter_frame_method_addr(); // validate the method we'd find in this potential sender if (!m->is_valid_method()) return false; // stack frames shouldn't be much larger than max_stack elements if (fp() - sp() > 1024 + m->max_stack()*Interpreter::stackElementSize) { return false; } // validate bci/bcx intptr_t bcx = interpreter_frame_bcx(); if (m->validate_bci_from_bcx(bcx) < 0) { return false; } // validate ConstantPoolCache* ConstantPoolCache* cp = *interpreter_frame_cache_addr(); if (cp == NULL || !cp->is_metaspace_object()) return false; // validate locals address locals = (address) *interpreter_frame_locals_addr(); if (locals > thread->stack_base() || locals < (address) fp()) return false; // We'd have to be pretty unlucky to be mislead at this point #endif // CC_INTERP return true; } BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) { #ifdef CC_INTERP // Needed for JVMTI. The result should always be in the // interpreterState object interpreterState istate = get_interpreterState(); #endif // CC_INTERP assert(is_interpreted_frame(), "interpreted frame expected"); Method* method = interpreter_frame_method(); BasicType type = method->result_type(); intptr_t* tos_addr; if (method->is_native()) { // Prior to calling into the runtime to report the method_exit the possible // return value is pushed to the native stack. If the result is a jfloat/jdouble // then ST0 is saved before EAX/EDX. See the note in generate_native_result tos_addr = (intptr_t*)sp(); if (type == T_FLOAT || type == T_DOUBLE) { // QQQ seems like this code is equivalent on the two platforms #ifdef AMD64 // This is times two because we do a push(ltos) after pushing XMM0 // and that takes two interpreter stack slots. tos_addr += 2 * Interpreter::stackElementWords; #else tos_addr += 2; #endif // AMD64 } } else { tos_addr = (intptr_t*)interpreter_frame_tos_address(); } switch (type) { case T_OBJECT : case T_ARRAY : { oop obj; if (method->is_native()) { #ifdef CC_INTERP obj = istate->_oop_temp; #else obj = cast_to_oop(at(interpreter_frame_oop_temp_offset)); #endif // CC_INTERP } else { oop* obj_p = (oop*)tos_addr; obj = (obj_p == NULL) ? (oop)NULL : *obj_p; } assert(obj == NULL || Universe::heap()->is_in(obj), "sanity check"); *oop_result = obj; break; } case T_BOOLEAN : value_result->z = *(jboolean*)tos_addr; break; case T_BYTE : value_result->b = *(jbyte*)tos_addr; break; case T_CHAR : value_result->c = *(jchar*)tos_addr; break; case T_SHORT : value_result->s = *(jshort*)tos_addr; break; case T_INT : value_result->i = *(jint*)tos_addr; break; case T_LONG : value_result->j = *(jlong*)tos_addr; break; case T_FLOAT : { #ifdef AMD64 value_result->f = *(jfloat*)tos_addr; #else if (method->is_native()) { jdouble d = *(jdouble*)tos_addr; // Result was in ST0 so need to convert to jfloat value_result->f = (jfloat)d; } else { value_result->f = *(jfloat*)tos_addr; } #endif // AMD64 break; } case T_DOUBLE : value_result->d = *(jdouble*)tos_addr; break; case T_VOID : /* Nothing to do */ break; default : ShouldNotReachHere(); } return type; } intptr_t* frame::interpreter_frame_tos_at(jint offset) const { int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize); return &interpreter_frame_tos_address()[index]; } #ifndef PRODUCT #define DESCRIBE_FP_OFFSET(name) \ values.describe(frame_no, fp() + frame::name##_offset, #name) void frame::describe_pd(FrameValues& values, int frame_no) { if (is_interpreted_frame()) { DESCRIBE_FP_OFFSET(interpreter_frame_sender_sp); DESCRIBE_FP_OFFSET(interpreter_frame_last_sp); DESCRIBE_FP_OFFSET(interpreter_frame_method); DESCRIBE_FP_OFFSET(interpreter_frame_mdx); DESCRIBE_FP_OFFSET(interpreter_frame_cache); DESCRIBE_FP_OFFSET(interpreter_frame_locals); DESCRIBE_FP_OFFSET(interpreter_frame_bcx); DESCRIBE_FP_OFFSET(interpreter_frame_initial_sp); #ifdef AMD64 } else if (is_entry_frame()) { // This could be more descriptive if we use the enum in // stubGenerator to map to real names but it's most important to // claim these frame slots so the error checking works. for (int i = 0; i < entry_frame_after_call_words; i++) { values.describe(frame_no, fp() - i, err_msg("call_stub word fp - %d", i)); } #endif // AMD64 } } #endif // !PRODUCT intptr_t *frame::initial_deoptimization_info() { // used to reset the saved FP return fp(); } intptr_t* frame::real_fp() const { if (_cb != NULL) { // use the frame size if valid int size = _cb->frame_size(); if (size > 0) { return unextended_sp() + size; } } // else rely on fp() assert(! is_compiled_frame(), "unknown compiled frame size"); return fp(); }
smarr/GraalVM
src/cpu/x86/vm/frame_x86.cpp
C++
gpl-2.0
24,919
""" Default configuration values for certmaster items when not specified in config file. Copyright 2008, Red Hat, Inc see AUTHORS This software may be freely redistributed under the terms of the GNU general public license. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """ from config import BaseConfig, BoolOption, IntOption, Option class CMConfig(BaseConfig): log_level = Option('INFO') listen_addr = Option('') listen_port = IntOption(51235) cadir = Option('/etc/pki/certmaster/ca') cert_dir = Option('/etc/pki/certmaster') certroot = Option('/var/lib/certmaster/certmaster/certs') csrroot = Option('/var/lib/certmaster/certmaster/csrs') cert_extension = Option('cert') autosign = BoolOption(False) sync_certs = BoolOption(False) peering = BoolOption(True) peerroot = Option('/var/lib/certmaster/peers') hash_function = Option('sha256') class MinionConfig(BaseConfig): log_level = Option('INFO') certmaster = Option('certmaster') certmaster_port = IntOption(51235) cert_dir = Option('/etc/pki/certmaster')
jude/certmaster
certmaster/commonconfig.py
Python
gpl-2.0
1,224
<?php //ENGLISH LANGUAGE FILE $lang = array(); global $lang; //Login $lang['anonymous_link'] = 'Click here to view public files anonymously'; $lang['forgotpassword'] = 'Forgot your password?'; $lang['install_folder'] = ''; $lang['signup'] = 'Sign-up for an account'; $lang['welcome'] = 'Welcome to '; $lang['welcome2'] = 'Biofarma Knowledge Sharing Document System'; $lang['welcome_anonymous_title'] = 'system Anonymous Page: List All'; $lang['welcome_anonymous_h1'] = 'system Anonymous Page'; //GLOBAL TERMS $lang['action'] = 'Action'; $lang['all'] = 'Semua'; $lang['anonymous'] = 'Anonymous'; $lang['author'] = 'Penerbit'; $lang['category'] = 'Kategori'; $lang['choose'] = 'Pilih'; $lang['date'] = 'Tanggal'; $lang['days'] = 'hari'; $lang['department'] = 'Divisi'; $lang['edit'] = 'Ubah'; $lang['enter'] = 'Masuk'; $lang['error'] = 'Error'; $lang['file'] = 'File'; $lang['help'] = 'Help'; $lang['home'] = 'Daftar Dokumen'; $lang['installer'] = 'Installer'; $lang['list'] = 'List'; $lang['login'] = 'Login'; $lang['logout'] = 'Logout'; $lang['new'] = 'Baru'; $lang['owner'] = 'Pemilik'; $lang['preferences'] = 'Preferensi'; $lang['password'] = 'Password'; $lang['please'] = 'Tolong'; $lang['profile'] = 'Profile'; $lang['public'] = 'Publik'; $lang['revision'] = 'Revisi'; $lang['search'] = 'Cari Dokumen'; $lang['select'] = 'Pilih'; $lang['sincerely'] = 'Sincerely'; $lang['submit'] = 'Ajukan'; $lang['time'] = 'Waktu'; $lang['type'] = 'Tipe'; $lang['updated'] = 'Terbaharui'; $lang['username'] = 'Username'; $lang['users'] = 'Users'; $lang['value'] = 'Nilai'; $lang['view'] = 'Lihat'; // Areas $lang['area_add_new_category'] = 'Tambah Kategori Baru'; $lang['area_add_new_department'] = 'Tambah Divisi Baru'; $lang['area_add_new_file'] = 'Tambah File Baru'; $lang['area_add_new_udf'] = 'Tambah User Defined Field Baru'; $lang['area_add_new_user'] = 'Tambah User Baru'; $lang['area_admin'] = 'Administrasi'; $lang['area_check_in_file'] = 'Check-in File'; $lang['area_check_out_file'] = 'Download file'; $lang['area_choose_department'] = 'Pilih Divisi'; $lang['area_delete_category'] = 'Hapus Kategori'; $lang['area_deleted_files'] = 'Hapus file'; $lang['area_department_information'] = 'Informasi Divisi'; $lang['area_display_category'] = 'Tampilkan Semua File Dalam Kategori '; $lang['area_document_listing'] = 'Document Listing'; $lang['area_file_delete'] = 'Hapus File'; $lang['area_file_details'] = 'File Details'; $lang['area_file_expiration'] = 'File Kadaluarsa'; $lang['area_personal_profile'] = 'Personal Profil'; $lang['area_reset_password'] = 'Reset Password'; $lang['area_update_category'] = 'Perbaharui Kategori'; $lang['area_update_department'] = 'Perbaharui Divisi'; $lang['area_update_file'] = 'Perbaharui File'; $lang['area_view_category'] = 'Lihat Kategori'; $lang['area_view_history'] = 'History'; // Buttons $lang['button_add_category'] = 'Tambah Kategori'; $lang['button_add_department'] = 'Tambah Divisi'; $lang['button_add_document'] = 'Ajukan Dokumen'; $lang['button_authorize'] = 'Validasi'; $lang['button_back'] = 'Kembali'; $lang['button_cancel'] = 'Batal'; $lang['button_check_in'] = 'Revisi kembali'; $lang['button_clear_status'] = 'Clear Status'; $lang['button_click_here'] = 'Klik disini'; $lang['button_continue'] = 'Lanjutkan'; $lang['button_delete'] = 'Hapus'; $lang['button_delete_files'] = 'Hapus File'; $lang['button_display_category'] = 'Tampilkan Semua File Dalam Kategori Ini'; $lang['button_modify_category'] = 'Modifikasi Kategori'; $lang['button_modify_department'] = 'Modifikasi Divisi'; $lang['button_reject'] = 'Tolak'; $lang['button_reset'] = 'Reset'; $lang['button_resubmit_for_review'] = 'Ajukan Kembali Untuk Review'; $lang['button_save'] = 'Simpan'; $lang['button_undelete'] = 'Batal Hapus'; $lang['button_update'] = 'Perbaharui'; $lang['button_view_department'] = 'Lihat Divisi'; $lang['button_yes'] = 'Ya'; //Email $lang['email_added_to_repository'] = 'added to repository'; $lang['email_a_new_file_has_been_added'] = 'A new file has been authorized'; $lang['email_a_new_file_has_been_rejected'] = 'A new file has been rejected'; $lang['email_automated_document_messenger'] = 'Automated Document Messenger'; $lang['email_because_you_did_not_revise'] = 'because you did not revise it for more than'; $lang['email_comments_regarding_review'] = 'Comments regarding your review of the document'; $lang['email_custom_comment'] = 'Isi komentar'; $lang['email_email_all_users'] = 'E-mail semua user'; $lang['email_email_these_users'] = 'E-mail user ini'; $lang['email_email_whole_department'] = 'E-mail semua divisi'; $lang['email_file_expired'] = 'A File Has Expired'; $lang['email_file_was_rejected_because'] = 'Your file was rejected because you did not revise it for more than'; $lang['email_file_was_rejected_expired'] = 'Your file has expired. Please update the file as soon as possible. Your file may be inaccessible until you do.'; $lang['email_for_the_following_reasons'] = 'for the following reasons'; $lang['email_greeting'] = 'Kepada penerbit'; $lang['email_i_would_like_to_inform'] = 'I would like to inform you that'; $lang['email_note_to_authors'] = 'Catatan untuk penerbit'; $lang['email_revision_days'] = 'Maximum number of days before expiration:'; $lang['email_salute'] = 'Sincerely'; $lang['email_someone_has_requested_password'] = 'Someone has requested a password reset. If you wish to reset your password please follow the link below. If you do not wish to reset your password then simply do nothing and disregard this email.'; $lang['email_status_expired'] = 'Status: Expired'; $lang['email_subject_review_status'] = 'Review status for document '; $lang['email_subject'] = 'Subjek'; $lang['email_thank_you'] = 'Terimakasih'; $lang['email_to'] = 'Kepada'; $lang['email_was_declined_for_publishing_at'] = 'Was declined for publishing at'; $lang['email_was_rejected_from_repository'] = 'Was rejected from repository'; $lang['email_you_can_now_login'] = 'You can now log into your account at this page'; $lang['email_your_account_created'] = 'your document management account was created at'; $lang['email_your_file_has_been_authorized'] = 'Your file has been authorized for publication'; // Labels $lang['label_active'] = 'Aktif'; $lang['label_add'] = 'Tambah'; $lang['label_admin'] = 'Admin'; $lang['label_allowed'] = 'Diperbolehkan'; $lang['label_all_departments'] = 'Set Semua Divisi Ke..'; $lang['label_assign_to'] = 'Diajukan kepada'; $lang['label_author'] = 'Penerbit'; $lang['label_browse_by'] = 'Filter menurut:'; $lang['label_case_sensitive'] = 'Case Sensitive'; $lang['label_checked_out_files'] = 'Checked-Out Files'; $lang['label_check_expiration'] = 'Check Expiration'; $lang['label_comment'] = 'Komentar'; $lang['label_created_date'] = 'Dibuat Tanggal'; $lang['label_default_for_unset'] = 'Default Department Permissions'; $lang['label_delete'] = 'hapus'; $lang['label_delete_undelete'] = 'Hapus/Batal Hapus'; $lang['label_department_authority'] = 'Specific Department Permissions:'; $lang['label_department'] = 'Divisi'; $lang['label_departments'] = 'Divisi - divisi'; $lang['label_department_to_modify'] = 'Department to modify'; $lang['label_description'] = 'Deskripsi'; $lang['label_display'] = 'Tampilkan'; $lang['label_email_address'] = 'Alamat Email'; $lang['label_empty'] = 'Kosong'; $lang['label_exact_phrase'] = 'Exact Phrase'; $lang['label_example'] = 'Contoh'; $lang['label_file_archive'] = 'Arsip File'; $lang['label_file_category'] = 'Kategori File'; $lang['label_file_listing'] = 'Daftar File'; $lang['label_file_location'] = 'Lokasi File'; $lang['label_file_maintenance'] = 'Perbaikan File'; $lang['label_filename'] = 'Namafile'; $lang['label_filetype'] = 'Tipe File'; $lang['label_filetypes'] = 'Tipe-tipe File'; $lang['label_file_name'] = 'Nama File'; $lang['label_first_name'] = 'Nama Depan'; $lang['label_forbidden'] = 'Dilarang'; $lang['label_found_documents'] = 'Dokumen Ditemukan'; $lang['label_id'] = 'ID'; $lang['label_is_admin'] = 'Apakah Admin'; $lang['label_is_reviewer'] = 'Apakah Validator'; $lang['label_last_name'] = 'Nama Belakang'; $lang['label_logged_in_as'] = 'Masuk Sebagai'; $lang['label_moderation'] = 'Moderasi'; $lang['label_modified_date'] = 'Tanggal Diubah'; $lang['label_modify'] = 'Modifikasi'; $lang['label_name'] = 'Nama'; $lang['label_new_password'] = 'Password Baru'; $lang['label_next'] = 'Lanjut'; $lang['label_note_for_revision_log'] = 'Catatan untuk revisi'; $lang['label_page'] = 'Halaman'; $lang['label_phone_number'] = 'No Telp'; $lang['label_plugins'] = 'Plug-Ins'; $lang['label_prev'] = 'Sebelumnya'; $lang['label_radio_button'] = 'Radio Button'; $lang['label_read'] = 'Read'; $lang['label_reassign_to'] = 'Diajukan kembali kepada'; $lang['label_rejected_files'] = 'File-file Ditolak'; $lang['label_rejections'] = 'Penolakan'; $lang['label_reviewer_for'] = 'Validator Untuk Divisi'; $lang['label_reviewer'] = 'Validator'; $lang['label_reviews'] = 'Review'; $lang['label_rights'] = 'Hak'; $lang['label_run_expiration'] = 'Run Expiration Utility'; $lang['label_search_term'] = 'Kata kunci'; $lang['label_select_a_department'] = 'Pilih Divisi'; $lang['label_select_departments'] = 'Pilih Divisi - divisi'; $lang['label_select_one'] = 'Pilih satu'; $lang['label_settings'] = 'Settings'; $lang['label_size'] = 'Ukuran'; $lang['label_specific_permissions'] = 'Specific User Permissions:'; $lang['label_status'] = 'Status'; $lang['label_text'] = 'Text'; $lang['label_update'] = 'Perbaharui'; $lang['label_user_defined_fields'] = ''; $lang['label_user_defined_field'] = ''; $lang['label_users_in_department'] = 'Users in this department'; $lang['label_user'] = 'User'; $lang['label_view'] = 'Tampilkan'; $lang['label_userid'] = 'User ID'; $lang['label_fileid'] = 'File ID'; $lang['label_username'] = 'User Name'; $lang['label_action'] = 'Aksi'; $lang['label_date'] = 'Tanggal'; $lang['label_type_pr_sec'] = 'Tipepe'; //CHM $lang['label_primary_type'] = 'Primary'; //CHM $lang['label_sub_select_list'] = 'Sub-Select List'; //CHM // Messages $lang['message_account_created_add_user'] = 'Your account has been created.'; $lang['message_account_created_password'] = 'Your randomly generated password is'; $lang['message_account_created'] = 'Your account has been created. Please check your email for login information.'; $lang['message_action_cancelled'] = 'Aksi Dibatalkan'; $lang['message_all_actions_successfull'] = 'Berhasil'; $lang['message_an_email_has_been_sent'] = 'An email has been sent to the email address on file with a link that must be followed in order to reset the password.'; $lang['message_anonymous_view'] = 'You have been switched to anonymous view mode'; $lang['message_are_you_sure_remove'] = 'Anda yakin?'; $lang['message_authorized'] = 'Telah di validasi'; $lang['message_category_successfully_added'] = 'Kategori berhasil ditambahakan'; $lang['message_category_successfully_deleted'] = 'Kategori berhasil dihapus'; $lang['message_category_successfully_updated'] = 'Kategori berhasil diperbaharui'; $lang['message_click_to_checkout_document'] = 'Klik untuk revisi kembali dokumen yang dipilih dan mulai mendownload'; $lang['message_config_value_problem'] = 'There is a problem with one of your configuration values. Please check.'; $lang['message_current'] = 'Current'; $lang['message_datadir_problem'] = 'There is a problem with your dataDir. Check to make sure it exists and is writeable'; $lang['message_datadir_problem_exists'] = 'There is a problem with your dataDir setting. It does not appear to exist.'; $lang['message_datadir_problem_writable'] = 'There is a problem with your dataDir setting. It does not appear to be writeable to the web server.'; $lang['message_department_successfully_added'] = 'Divisi berhasil ditambahkan'; $lang['message_department_successfully_updated'] = 'Divisi berhasil diperbaharui'; $lang['message_directory_creation_failed'] = 'Directory Creation Failed'; $lang['message_document_added'] = 'Dokumen berhasil ditambahkan'; $lang['message_document_checked_in'] = 'Documen berhasil diajukan kembali untuk di revisi'; $lang['message_document_checked_out_to_you'] = 'Document yang akan anda revisi kembali'; $lang['message_document_has_been_archived'] = 'Dokumen telah di arsipkan'; $lang['message_documents_expired'] = 'Dokumen kadaluarsa'; $lang['message_documents_rejected'] = 'Dokument ditolak'; $lang['message_document_successfully_deleted'] = 'Dokumen berhasil dihapus'; $lang['message_documents_waiting'] = 'Dokumen menunggu untuk di review'; $lang['message_error_performing_action'] = 'Terjadi kesalahan'; $lang['message_file_authorized'] = 'File berhasil di validasi'; $lang['message_file_does_not_exist'] = 'File tidak ada atau terjadi masalah.'; $lang['message_file_expired'] = 'File kadaluarsa'; $lang['message_file_rejected'] = 'File berhasil ditolak'; $lang['message_folder_error_check'] = 'Folder Error. Check Last Message in status bar for details.'; $lang['message_folder_perms_error'] = 'Folder Permissions Error:'; $lang['message_for_further_assistance'] = 'for further assistance'; $lang['message_found_documents'] = 'dokumen ditemukan'; $lang['message_if_you_are_unable_to_view1'] = 'Klik tombol untuk '; $lang['message_if_you_are_unable_to_view2'] = 'Download'; $lang['message_if_you_are_unable_to_view3'] = '<br> '; $lang['message_initial_import'] = 'Initial Import'; $lang['message_last_message'] = 'Last Message'; $lang['message_latest_version'] = 'Latest version'; $lang['message_need_one_department'] = 'You need at least one department'; $lang['message_no_author_comments_available'] = 'No author comments available'; $lang['message_no_description_available'] = 'Tidak ada deskripsi tersedia'; $lang['message_no_documents_checked_out'] = 'Tidak ada dokumen yang akan di revisi.'; $lang['message_no_files_found'] = 'Tak satupun file ditemukan'; $lang['message_no_information_available'] = 'Tidak ada informasi tersedia '; $lang['message_non_unique_account'] = 'Non-Unique account'; $lang['message_non_unique_key'] = 'Non-Unique key in database.'; $lang['message_nothing_to_do'] = 'Nothing to do'; $lang['message_not_writeable'] = 'Not Writeable!'; $lang['message_once_the_document_has_completed'] = ''; $lang['message_original_version'] = 'Original version'; $lang['message_please_email'] = 'Please email'; $lang['message_please_upload_valid_doc'] = 'Tolong upload dokumen yang valid'; $lang['message_record_exists'] = 'Record already exists. Try again with a different value.'; $lang['message_rejected'] = 'Ditolak'; $lang['message_rejecting_files'] = 'Rejecting files last edited before'; $lang['message_reviewers_comments_re_rejection'] = 'Reviewers comments regarding rejection'; $lang['message_session_error'] = 'Session error. Please login again.'; $lang['message_set_your_new_password'] = 'Set your new password using the form below.'; $lang['message_sorry_demo_mode'] = 'Sorry, demo mode only, you can not do that!'; $lang['message_sorry_not_allowed'] = 'Sorry, you are not allowed do to that!'; $lang['message_that_filetype_not_supported'] = 'File tidak suport'; $lang['message_the_code_you_are_using'] = 'The code you are trying to use to reset your password is no longer valid. Please use this form to reset your password.'; $lang['message_the_file_is_too_large'] = 'The file is too large. Check your OpenDocMan settings. Maximum size is'; $lang['message_the_file_is_too_large_php_ini'] = 'The file is too large for your php server. Check your php.ini configuration for max upload/post/memory. Maximum size is currently: '; $lang['message_there_was_an_error_loggin_you_in'] = 'Maaf username dan password tidak cocok, silahkan login kembali'; $lang['message_there_was_an_error_performing_the_action'] = 'There was an error performing the requested action.'; $lang['message_the_username_you_entered'] = 'The username you entered was not found in our system. Contact us if you have forgotten your username.'; $lang['message_this_file_cannot_be_checked_in'] = 'This file cannot be checked in'; $lang['message_this_file_cannot_be_uploaded'] = 'This file cannot be uploaded properly'; $lang['message_this_operation_cannot_be_done_file'] = 'This operation cannot be done on this file'; $lang['message_this_operation_cannot_be_done_rev'] = 'This operation cannot be done to a revision of a file'; $lang['message_this_page_requires_root'] = 'This page requires root level permission'; $lang['message_this_site_has_high_security'] = 'This site has a high level of security and we cannot retrieve your password for you. You can use this form to reset your password. Enter your username and we will send an email to the email address on file with a link that you must follow to reset your password. At that point you may set it to anything you wish.'; $lang['message_to_view_your_file'] = 'Lihat di tab baru'; $lang['message_udf_cannot_be_blank'] = 'The UDF name cannot be blank'; $lang['message_udf_successfully_added'] = 'User defined field successfully added'; $lang['message_udf_successfully_deleted'] = 'User defined field successfully deleted'; $lang['message_unable_to_determine_root'] = 'Unable to determine the root username. Please check your configuration.'; $lang['message_unable_to_find_file'] = 'Unable to find the requested file'; $lang['message_user_exists'] = 'That user already exists. Please <a href=\'signup.php\'>try again</a>'; $lang['message_user_successfully_added'] = 'User successfully added'; $lang['message_user_successfully_deleted'] = 'User successfully deleted'; $lang['message_user_successfully_updated'] = 'User successfully updated'; $lang['message_wrong_file_checkin'] = 'Wrong file! Please check in the right file.'; $lang['message_you_are_not_administrator'] = 'You are not an administrator'; $lang['message_you_did_not_enter_value'] = 'tolong isi nilai'; $lang['message_you_do_not_have_an_account'] = 'You do not currently have an account. Please contact the administrator to request one.'; $lang['message_you_must_assign_rights'] = 'You must assign view/modify rights to at least one user.'; $lang['message_your_password_has_been_changed'] = 'Your password has been changed.'; $lang['view'] = $lang['label_view']; // Add File Page $lang['addpage_forbidden'] = 'Forbidden'; $lang['addpage_none'] = 'None'; $lang['addpage_view'] = 'View'; $lang['addpage_read'] = 'Read'; $lang['addpage_write'] = 'Write'; $lang['addpage_admin'] = 'Admin'; $lang['addpage_new_file_added'] = 'File berhasil ditambahkan'; $lang['addpage_new'] = 'Baru'; $lang['addpage_uploader'] = 'Uploader'; $lang['addpage_file_missing'] = 'Pilih file untuk di upload'; $lang['addpage_permissions'] = 'Hak akses'; // Edit File Page $lang['editpage_uncheck_all'] = 'Uncheck semua'; $lang['editpage_check_all'] = 'Centang semua'; $lang['editpage_of'] = 'dari'; $lang['editpage_selected'] = 'dipilih'; $lang['editpage_none_selected'] = 'Select options'; $lang['editpage_assign_owner'] = 'Ditujukan untuk user'; $lang['editpage_assign_department'] = 'Ditujukan untuk divisi'; $lang['editpage_filter'] = 'Filter:'; $lang['editpage_keyword'] = 'masukan kata kunci'; $lang['editpage_forbidden'] = 'Forbidden'; $lang['editpage_none'] = 'None'; $lang['editpage_view'] = 'View'; $lang['editpage_read'] = 'Read'; $lang['editpage_write'] = 'Write'; $lang['editpage_admin'] = 'Admin'; // File Permissions Page $lang['filepermissionspage_edit_department_permissions'] = 'Ubah Hak Akses Divisi'; $lang['filepermissionspage_edit_user_permissions'] = 'Ubah Hak Akses User'; // Delete/Undeleta Admin Page $lang['undeletepage_file_permanently_deleted'] = 'File telah dihapus permanen'; $lang['undeletepage_file_undeleted'] = 'File telah dikembalikan'; // Departments Page $lang['departmentpage_department_name_required'] = 'Nama divisi dibutuhkan'; // Details Page $lang['detailspage_view'] = 'Lihat'; $lang['detailspage_check_out'] = 'Revisi kembali'; $lang['detailspage_edit'] = 'Ubah'; $lang['detailspage_delete'] = 'Hapus'; $lang['detailspage_history'] = 'History'; $lang['detailspage_are_sure'] = 'Anda yakin?'; $lang['detailspage_file_checked_out_to'] = 'Checked out to'; // Out Page $lang['outpage_view'] = 'Lihat'; $lang['outpage_ascending'] = 'Ascending'; $lang['outpage_descending'] = 'descending'; $lang['outpage_choose_an_order'] = 'Choose an order'; $lang['outpage_choose'] = 'Pilih'; $lang['category_option_author'] = 'Penerbit'; $lang['category_option_department'] = 'Divisi'; $lang['category_option_category'] = 'Kategori File'; $lang['category_option_default'] = 'Kosong'; // History Page $lang['historypage_category'] = 'Kosong:'; $lang['historypage_file_size'] = 'Ukuran File:'; $lang['historypage_creation_date'] = 'Dibuat tanggal:'; $lang['historypage_owner'] = 'Pemilik:'; $lang['historypage_description'] = 'Deskripsi:'; $lang['historypage_comment'] = 'Komentar:'; $lang['historypage_revision'] = 'Revisi:'; $lang['historypage_original_revision'] = 'Revisi Original'; $lang['historypage_latest'] = 'Terbaru'; $lang['historypage_history'] = 'History'; $lang['historypage_version'] = 'Versi'; $lang['historypage_modification'] = 'Tanggal modifikasi'; $lang['historypage_by'] = 'Oleh'; $lang['historypage_note'] = 'Catatan'; // Profile Page $lang['profilepage_update_profile'] = 'Perbaharui personal profile'; // User Page $lang['userpage_admin'] = 'Admin'; $lang['userpage_are_sure'] = 'Anda yakin akan menghapus '; $lang['userpage_back'] = 'Kembali'; $lang['userpage_button_add_user'] = 'Tambah User'; $lang['userpage_button_cancel'] = 'Batal'; $lang['userpage_button_delete'] = 'Hapus'; $lang['userpage_button_modify'] = 'Modifikasi User'; $lang['userpage_button_show'] = 'Perlihatkan User'; $lang['userpage_button_update'] = 'Perbaharui User'; $lang['userpage_choose_departments'] = 'Pilih Divisi'; $lang['userpage_choose_user'] = 'Pilih User untuk dilihat'; $lang['userpage_confirm_password'] = 'Confirm password'; $lang['userpage_department'] = 'Divisi'; $lang['userpage_email'] = 'E-mail'; $lang['userpage_first_name'] = 'Nama depan'; $lang['userpage_id'] = 'ID'; $lang['userpage_last_name'] = 'Nama belakang'; $lang['userpage_leave_empty'] = 'Kosongkan jika tidak di ubah'; $lang['userpage_modify_user'] = 'Modifikasi User'; $lang['userpage_no'] = 'No'; $lang['userpage_password'] = 'Password'; $lang['userpage_phone_number'] = 'No telp'; $lang['userpage_reviewer'] = 'Validator'; $lang['userpage_reviewer_for'] = 'Validator untuk'; $lang['userpage_show_user'] = 'Tampilkan User: '; $lang['userpage_status_delete'] = 'Hapus'; $lang['userpage_update_user'] = 'Perbaharui User: '; $lang['userpage_update_user_demo'] = 'Sorry, demo mode only, you cant do that'; $lang['userpage_user'] = 'User'; $lang['userpage_user_delete'] = 'Pilih User untuk dihapus'; $lang['userpage_user_info'] = 'Informasiformasi User'; $lang['userpage_username'] = 'Username'; $lang['userpage_yes'] = 'Yes'; // Admin Page $lang['adminpage_edit_filetypes'] = 'Ubah Tipe File'; $lang['adminpage_edit_settings'] = 'Ubah Pengaturan'; $lang['adminpage_reports'] = 'Laporan'; $lang['adminpage_access_log'] = 'Access Log'; $lang['adminpage_reports_file_list'] = 'File List Export'; // Access Log page $lang['accesslogpage_access_log'] = 'Access Log'; $lang['accesslogpage_file_added'] = 'File Added'; $lang['accesslogpage_file_viewed'] = 'File Viewed'; $lang['accesslogpage_file_downloaded'] = 'File Downloaded'; $lang['accesslogpage_file_modified'] = 'File Modified'; $lang['accesslogpage_file_checked_in'] = 'File Checked-in'; $lang['accesslogpage_file_checked_out'] = 'File Checked-out'; $lang['accesslogpage_file_deleted'] = 'File Deleted'; $lang['accesslogpage_file_authorized'] = 'File Authorized'; $lang['accesslogpage_file_rejected'] = 'File Rejected'; $lang['accesslogpage_reserved'] = 'Reserved'; // Check-in Page $lang['checkinpage_file_was_checked_in'] = 'A file has been checked in.'; //Category View Page $lang['categoryviewpage_list_of_files_title'] = 'File diajukan untuk kategori ini:'; //Search Page $lang['searchpage_all_meta'] = 'All non-udf metadata'; // Footer $lang['footer_support'] = 'Support'; $lang['footer_feedback'] = 'Feedback'; $lang['footer_bugs'] = 'Bugs';
ramadhanfebbry/system-app
includes/language/english.php
PHP
gpl-2.0
24,009
#region License /* * Copyright (C) 1999-2015 John Källén. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #endregion using Decompiler.Arch.Mos6502; using Decompiler.Core; using Decompiler.Core.Expressions; using Decompiler.Core.Lib; using Decompiler.Core.Rtl; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decompiler.Environments.C64 { /// <summary> /// Implementation of the C64 platform. /// </summary> public class C64Platform : Platform { private Mos6502ProcessorArchitecture arch; public C64Platform(IServiceProvider services, Mos6502ProcessorArchitecture arch) : base(services, arch) { this.arch = arch; } public override string DefaultCallingConvention { get { return ""; } } public override BitSet CreateImplicitArgumentRegisters() { return Architecture.CreateRegisterBitset(); } public override SystemService FindService(RtlInstruction rtl, ProcessorState state) { return base.FindService(rtl, state); } public override SystemService FindService(int vector, ProcessorState state) { throw new NotImplementedException(); } public override ProcedureBase GetTrampolineDestination(ImageReader imageReader, IRewriterHost host) { return null; } public override ExternalProcedure LookupProcedureByName(string moduleName, string procName) { throw new NotImplementedException(); } public override Address MakeAddressFromConstant(Constant c) { return Address.Ptr16(c.ToUInt16()); } } }
killbug2004/reko
src/Environments/C64/C64Platform.cs
C#
gpl-2.0
2,441
package nl.itopia.corendon.utils; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import nl.itopia.corendon.data.ChooseItem; /** * * @author Wies Kueter */ public class Validation { @FXML private TextField usernameInputfield, firstnameInputfield, lastnameInputfield, passwordInputfield, repeatpasswordInputfield, contactdetailsInputfield, notesInputfield; @FXML private ChoiceBox<ChooseItem> roleDropdownmenu, airportDropdownmenu; @FXML private Button addButton, cancelButton; public static boolean minMax(String field, int min, int max) { if(field.length() >= min && field.length() <= max) { return true; } return false; } public static boolean min(String field, int min) { return field.length() >= min; } public static boolean max(String field, int max) { return field.length() <= max; } public static void errorMessage(TextField field, String message) { field.setText(""); field.setPromptText(message); field.getStyleClass().add("error_prompt"); } }
Biodiscus/Corendon
src/nl/itopia/corendon/utils/Validation.java
Java
gpl-2.0
1,228
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qcommonsequencetypes_p.h" #include "qdocumentcontentvalidator_p.h" #include "qnodebuilder_p.h" #include "qdocumentconstructor_p.h" QT_BEGIN_NAMESPACE using namespace QPatternist; DocumentConstructor::DocumentConstructor(const Expression::Ptr &op) : SingleContainer(op) { } Item DocumentConstructor::evaluateSingleton(const DynamicContext::Ptr &context) const { NodeBuilder::Ptr nodeBuilder(context->nodeBuilder(m_staticBaseURI)); DocumentContentValidator validator(nodeBuilder.data(), context, ConstPtr(this)); const DynamicContext::Ptr receiverContext(context->createReceiverContext(&validator)); validator.startDocument(); m_operand->evaluateToSequenceReceiver(receiverContext); validator.endDocument(); const QAbstractXmlNodeModel::Ptr nm(nodeBuilder->builtDocument()); context->addNodeModel(nm); return nm->root(QXmlNodeModelIndex()); } void DocumentConstructor::evaluateToSequenceReceiver(const DynamicContext::Ptr &context) const { QAbstractXmlReceiver *const receiver = context->outputReceiver(); DocumentContentValidator validator(receiver, context, ConstPtr(this)); const DynamicContext::Ptr receiverContext(context->createReceiverContext(&validator)); validator.startDocument(); m_operand->evaluateToSequenceReceiver(receiverContext); validator.endDocument(); } Expression::Ptr DocumentConstructor::typeCheck(const StaticContext::Ptr &context, const SequenceType::Ptr &reqType) { m_staticBaseURI = context->baseURI(); return SingleContainer::typeCheck(context, reqType); } SequenceType::Ptr DocumentConstructor::staticType() const { return CommonSequenceTypes::ExactlyOneDocumentNode; } SequenceType::List DocumentConstructor::expectedOperandTypes() const { SequenceType::List result; result.append(CommonSequenceTypes::ZeroOrMoreItems); return result; } Expression::Properties DocumentConstructor::properties() const { return DisableElimination | IsNodeConstructor; } ExpressionVisitorResult::Ptr DocumentConstructor::accept(const ExpressionVisitor::Ptr &visitor) const { return visitor->visit(this); } QT_END_NAMESPACE
librelab/qtmoko-test
qtopiacore/qt/src/xmlpatterns/expr/qdocumentconstructor.cpp
C++
gpl-2.0
4,150
/* * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #undef IMPL #include "config.h" #include <WebCore/HTMLNames.h> #include <WebCore/HTMLTableCaptionElement.h> #include <WebCore/JSMainThreadExecState.h> #include <wtf/RefPtr.h> #include <wtf/GetPtr.h> #include "JavaDOMUtils.h" #include <wtf/java/JavaEnv.h> using namespace WebCore; extern "C" { #define IMPL (static_cast<HTMLTableCaptionElement*>(jlong_to_ptr(peer))) // Attributes JNIEXPORT jstring JNICALL Java_com_sun_webkit_dom_HTMLTableCaptionElementImpl_getAlignImpl(JNIEnv* env, jclass, jlong peer) { WebCore::JSMainThreadNullState state; return JavaReturn<String>(env, IMPL->getAttribute(WebCore::HTMLNames::alignAttr)); } JNIEXPORT void JNICALL Java_com_sun_webkit_dom_HTMLTableCaptionElementImpl_setAlignImpl(JNIEnv* env, jclass, jlong peer, jstring value) { WebCore::JSMainThreadNullState state; IMPL->setAttributeWithoutSynchronization(WebCore::HTMLNames::alignAttr, String(env, value)); } }
teamfx/openjfx-8u-dev-rt
modules/web/src/main/native/Source/WebCore/bindings/java/dom3/JavaHTMLTableCaptionElement.cpp
C++
gpl-2.0
2,143
// vim: bs=2:ts=4:sw=4:tw=80:noexpandtab #ifndef FST_XISTREAM_HPP #define FST_XISTREAM_HPP #include "ex.hpp" #include <string> #include <istream> namespace fst { // class that extend/modify istream methods/behaviors // catch ios_base::failure exceptions and throws io_ex class xistream { public: // ctor // del - if true, delete is on dtor xistream(std::istream *is, bool del = true); // dtor virtual ~xistream(); // read up to n bytes xistream &read(char *buf, std::streamsize n); // return a reference to istream std::istream &get_istream() const; // set another istream void set_is(std::istream *is, bool del = true); // extration operator template <typename T> xistream &operator>>(T &val); // use >> to extract // check if it was extracted up to EOF template <typename T> xistream &full_extract(T &val); // use std::getline() void getline(std::string &s); std::istream *operator->() const; protected: std::istream *_is; bool _del; private: // release current istream void release_is(); xistream(const xistream &); xistream operator=(const xistream &); }; /// templates and inline functions /// template <typename T> xistream &xistream::operator>>(T &val) { try { *_is >> val; return *this; } catch (const std::ios_base::failure &e) { throw EX(io_ex, e.what()); } } template <typename T> xistream &xistream::full_extract(T &val) { *this >> val; if (!_is->eof()) throw EX(ex, "full_extract() failed"); return *this; } inline std::istream &xistream::get_istream() const { return *_is; } inline std::istream *xistream::operator->() const { return _is; } } // fst #endif
luporl/fst
include/fst/utils/xistream.hpp
C++
gpl-2.0
1,646
using UnityEngine; using System.Collections; public class Vitoria : MonoBehaviour { public Texture2D creditos; public float velocidade = 0.02f; private float tempo; public void Start() { tempo = Time.time; if (MotorJogo.estado == MotorJogo.Estado.Desligado) MotorJogo.estado = MotorJogo.Estado.EmPausa; } public void OnGUI() { if (creditos == null) return; float largura = Screen.width * 0.8f; float altura = largura * creditos.height / creditos.width; float passado = (Time.time - tempo) * velocidade * altura; GUI.DrawTexture( new Rect( Screen.width * 0.1f, Screen.height * 1.1f - passado, largura, altura ), creditos ); if (passado > altura + Screen.height * 1.2f) MotorJogo.MenuInicial(); } }
marinello/jackietony
src/Assets/Codigos/Interface/Vitoria.cs
C#
gpl-2.0
797
<?php /* * @version $Id: doublons.config.php 246 2013-05-02 13:03:33Z yllen $ ------------------------------------------------------------------------- reports - Additional reports plugin for GLPI Copyright (C) 2003-2013 by the reports Development Team. https://forge.indepnet.net/projects/reports ------------------------------------------------------------------------- LICENSE This file is part of reports. reports 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. reports 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 reports. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ // Original Author of file: Remi Collet // Purpose of file: Generate "doublons" report // ---------------------------------------------------------------------- include ("../../../../inc/includes.php"); Plugin::load('reports'); Session::checkRight("profile","w"); Html::header(__('Duplicate computers', 'reports'), $_SERVER['PHP_SELF'], "config", "plugins"); $types = array(1 => __('MAC'), 2 => __('IP'), 3 => __('Serial number')); if (isset($_POST["delete"]) && isset($_POST['id'])) { $query = "DELETE FROM `glpi_plugin_reports_doublons_backlists` WHERE `id` = '".$_POST['id']."'"; $DB->query($query); } else if (isset($_POST["add"]) && isset($_POST["type"]) && isset($_POST["addr"]) && strlen($_POST["addr"])) { $query = "INSERT INTO `glpi_plugin_reports_doublons_backlists` SET `type` = '".$_POST["type"]."', `addr` = '".trim($_POST["addr"])."', `comment` = '".trim($_POST["comment"])."'"; $DB->query($query); } // Initial creation if (TableExists("glpi_plugin_reports_doublons_backlist")) { $migration = new Migration(160); $migration->renameTable("glpi_plugin_reports_doublons_backlist", "glpi_plugin_reports_doublons_backlists"); $migration->changeField("glpi_plugin_reports_doublons_backlists", "ID", "id", 'autoincrement'); $migration->executeMigration(); } else if (!TableExists("glpi_plugin_reports_doublons_backlists")) { $query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_reports_doublons_backlists` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` int(11) NOT NULL DEFAULT '0', `addr` varchar(255) DEFAULT NULL, `comment` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; $DB->query($query) or die($DB->error()); $query = "INSERT INTO`glpi_plugin_reports_doublons_backlists` (`type`, `addr`, `comment`) VALUES (1, '44:45:53:54:42:00', 'Nortel IPSECSHM Adapter'), (1, 'BA:D0:BE:EF:FA:CE', 'GlobeTrotter Module 3G+ Network Card'), (1, '00:53:45:00:00:00', 'WAN (PPP/SLIP) Interface'), (1, '80:00:60:0F:E8:00', 'Windows Mobile-based'), (2, '127.0.0.1', 'loopback'), (3, 'INVALID', 'from OCSNG'), (3, 'XxXxXxX', 'from IBM')"; $DB->query($query); } // ---------- Form ------------ echo "<div class='center'><table class='tab_cadre' cellpadding='5'>\n"; echo "<tr class='tab_bg_1 center'><th><a href='".GLPI_ROOT."/plugins/reports/front/config.form.php'>". __('Reports plugin configuration', 'reports') . "</a><br />&nbsp;<br />" . sprintf(__('%1$s: %2$s'), __('Report configuration', 'reports'), __('Duplicate computers', 'reports')) . "</th></tr>\n"; $plug = new Plugin(); if ($plug->isActivated('reports')) { echo "<tr class='tab_bg_1 center'><td>"; echo "<a href='./doublons.php'>" .sprintf(__('%1$s - %2$s'), __('Report'), __('Duplicate computers', 'reports'))."</a>"; echo "</td></tr>\n"; } echo "</table>\n"; echo "<form action='".$_SERVER["PHP_SELF"]."' method='post'><br />" . "<table class='tab_cadre' cellpadding='5'>\n" . "<tr class='tab_bg_1 center'><th colspan='4'>".__('Exception list setup', 'reports')."</th>". "</tr>\n" . "<tr class='tab_bg_1 center'><th>" . _n('Type', 'Types', 1) . "</th><th>" . sprintf(__('%1$s / %2$s'), __('IP'), __('MAC')) . "</th>" . "<th>" . __('Comments') . "</th><th>&nbsp;</th></tr>\n"; echo "<tr class='tab_bg_1 center'><td>"; Dropdown::showFromArray("type", $types); echo "</td><td><input type='text' name='addr' size='20'></td><td>". "<input type='text' name='comment' size='40'></td>" . "<td><input type='submit' name='add' value='"._sx('button', 'Add')."' class='submit' ></td></tr>\n"; $query = "SELECT * FROM `glpi_plugin_reports_doublons_backlists` ORDER BY `type`, `addr`"; $res = $DB->query($query); while ($data = $DB->fetch_array($res)) { echo "<tr class='tab_bg_1 center'><td>" . $types[$data["type"]] . "</td>" . "<td>" . $data["addr"] . "</td><td>" . $data["comment"] . "</td><td>"; Html::showSimpleForm($_SERVER["PHP_SELF"], 'delete', _x('button', 'Put in dustbin'), array('id' => $data["id"])); echo "</td></td></tr>\n"; } echo "</table>"; Html::closeForm(); echo "</div>"; Html::footer(); ?>
elitelinux/hack-space
php/plugins/reports/report/doublons/doublons.config.php
PHP
gpl-2.0
5,779
import forge from forge.models.groups import Group class Add(object): def __init__(self,json_args,session): if type(json_args) != type({}): raise TypeError("JSON Arg must be dict type") if 'name' and 'distribution' not in json_args.keys(): raise forge.ArgumentError() self.name = json_args['name'] self.distribution = json_args['distribution'] self.session = session def call(self): group = Group(self.name,self.distribution) self.session.add(group) self.session.commit() return {'name':self.name, 'distribution':self.distribution}
blhughes/forge
forge/commands/group/add.py
Python
gpl-2.0
734
package us.matthewcrocco.smashbrawl; import org.joda.time.DateTime; import us.matthewcrocco.smashbrawl.gui.GuiUtils; import us.matthewcrocco.smashbrawl.util.Console; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; import javafx.scene.control.Alert; import javafx.scene.control.TextInputDialog; public class Config { private static final Properties settings; private static String apiKey; private static String eventName; private static String databaseServer; private static long timeoutWait; private static long dbUpdateTime; static { try { // Loading Config Path p = Paths.get(".", "config", Strings.SETTINGS_FILENAME_DATABASE); if (!Files.exists(p)) throw new FileNotFoundException("[CONFIG] Failed to Locate " + Strings.SETTINGS_FILENAME_DATABASE + "!"); // Load Settings from Config File as Properties settings = new Properties(); settings.load(Files.newInputStream(p)); apiKey = settings.getProperty(Strings.SETTINGS_KEY_APIKEY); if (apiKey == null) throw new IllegalStateException("An API Key Must be Provided!"); dbUpdateTime = determineUpdateTime(settings.getProperty(Strings.SETTINGS_KEY_UPDATE_FREQ, "NORMAL").trim()); timeoutWait = determineTimeout(settings.getProperty(Strings.SETTINGS_KEY_TIMEOUT, "10s").trim()); Console.debug("Update Frequency : " + dbUpdateTime); Console.debug("Timeout Length : " + timeoutWait); databaseServer = settings.getProperty(Strings.SETTINGS_KEY_SERVERHOST, "default").trim(); eventName = settings.getProperty(Strings.SETTINGS_KEY_COLLECTION, "request").trim(); } catch (IOException e) { throw new ExceptionInInitializerError(e); } } /** * Validates Data that was loaded in Initialization. Being called more than once * causes nothing to occur. The validation is only ever done once in an instance. */ public static void load() { eventName(); serverHost(); } public static long updateTimeMillis() { return dbUpdateTime; } public static long timeoutLengthMillis() { return timeoutWait; } /** * Retrieve Orchestrate API Key * * @return */ public static String apiKey() { return apiKey; } /** * Retrieve the Event Name (Name of Database Table) * * @return */ public static String eventName() { if (eventName.isEmpty()) eventName = "request"; if (eventName.equalsIgnoreCase("auto") || eventName.equalsIgnoreCase("request")) { DateTime time = DateTime.now(); String defEventName = String.format("EVENT_%s_%s_%s", time.getDayOfMonth(), time.getMonthOfYear(), time.getYearOfEra()); if (eventName.equalsIgnoreCase("auto")) { eventName = defEventName; } else if (eventName.equalsIgnoreCase("request")) { while (true) { TextInputDialog prompt = new TextInputDialog(defEventName); prompt.initOwner(null); prompt.setTitle("DB Name Request"); prompt.setContentText("Name of Event: "); Optional<String> input = prompt.showAndWait(); eventName = input.orElse(defEventName); if (eventName.trim().isEmpty()) { Alert alert = GuiUtils.buildAlert(Alert.AlertType.ERROR, "Config Error: Invalid DB Name!", "Bad db.properties Value!", "Something must be entered for the Event Name!"); alert.initOwner(null); alert.showAndWait(); } else break; } } Console.debug("Event Name set to " + eventName); } return eventName; } /** * Retrieve the Orchestrate Server Hostname * * @return */ public static String serverHost() { if (databaseServer.equalsIgnoreCase("default") || databaseServer.equalsIgnoreCase("east")) databaseServer = Strings.SETTINGS_SERVERHOST_EAST; else if (databaseServer.equalsIgnoreCase("west")) databaseServer = Strings.SETTINGS_SERVERHOST_WEST; return databaseServer; } private static long determineTimeout(String value) { if (value.equalsIgnoreCase("never") || value.equalsIgnoreCase("-1")) return Long.MAX_VALUE; if (!Character.isDigit(value.charAt(0))) { GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Timeout Value!", "Bad db.properties Value!", value + " is not a valid timeout config value! Defaulting to 10s").show(); Console.bigWarning("Invalid Timeout Value: " + value + " --- Defaulting to 10 second timeout"); return 10_000; } int i = 0; while (Character.isDigit(value.charAt(i))) i++; long timeout = Long.parseLong(value.substring(0, i)); if (value.endsWith("ms") || value.endsWith("millis") || value.endsWith("milliseconds")) { return timeout; } else if (value.endsWith("s") || value.endsWith("seconds")) { // seconds * millis per second = seconds * 1000 return timeout * 1000; } else if (value.endsWith("m") || value.endsWith("min") || value.endsWith("mins") || value.endsWith("minutes")) { // minutes * seconds per minutes * millis per second // minutes * 60 * 1000 = minutes * 60,000 return timeout * 60_000; } else if (value.endsWith("h") || value.endsWith("hr") || value.endsWith("hrs") || value.endsWith("hours")) { // hours * minutes per hour * seconds per minutes * millis per second // hours * 60 * 60 * 1000 = hours * 3,600,000 return timeout * 3_600_000; } GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Timeout Length!", "Bad db.properties Value!", "Invalid Timeout Length! Must be in ms, s, min or hr. Defaulting to 10s.").show(); Console.bigWarning("Bad Timeout Length! Must be ms, s, min or hr... defaulting to 10s"); return 10_000; } private static long determineUpdateTime(String updateFreq) { switch (updateFreq.toUpperCase()) { case "RARELY": return 10_000; case "NORMAL": return 5_000; case "OFTEN": return 3_000; case "ALWAYS": return 2_000; case "ASAP": return 1_000; default: GuiUtils.buildAlert(Alert.AlertType.WARNING, "Config Error: Bad Update Frequency!", "Bad db.properties Value!", "Invalid Frequency Value! Defaulting to OFTEN"); Console.bigWarning("Bad Update Freqency! - " + updateFreq + "... Defaulting to OFTEN"); return 3_000; } } }
Matt529/SmashBrawlManager
src/us/matthewcrocco/smashbrawl/Config.java
Java
gpl-2.0
7,267
jQuery(document).ready(function(){ jQuery("#ResponsiveContactForm").validate({ submitHandler: function(form) { jQuery.ajax({ type: "POST", dataType: "json", url:MyAjax, data:{ action: 'ai_action', fdata : jQuery(document.formValidate).serialize() }, success:function(response) { if(response == 1){ jQuery("#smsg").slideDown(function(){ jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast'); jQuery(this).show().delay(8000).slideUp("fast")}); document.getElementById('ResponsiveContactForm').reset(); refreshCaptcha(); jQuery(".input-xlarge").removeClass("valid"); jQuery(".input-xlarge").next('label.valid').remove(); }else if(response == 2){ jQuery("#fmsg").slideDown(function(){ jQuery(this).show().delay(8000).slideUp("fast")}); jQuery("#captcha").removeClass("valid").addClass("error"); jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error"); jQuery('#captcha').val(''); refreshCaptcha(); }else{ alert(response); } } }); } }); });
andile-admin/new_election
wp-content/plugins/responsive-contact-form/js/ajax.js
JavaScript
gpl-2.0
1,183
/** * TileEntity class of the statue */ package info.jbcs.minecraft.statues; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import pl.asie.lib.block.TileEntityInventory; import java.util.Random; public class TileEntityStatue extends TileEntityInventory { private EntityPlayer clientPlayer; public String skinName = ""; public StatueParameters pose = new StatueParameters(); public Block block = Blocks.stone; public int meta = 0; public int facing = 0; boolean updated = true; void randomize(Random rand){ } @Override public int getSizeInventory() { return 6; } public EntityStatuePlayer getStatue(){ if(clientPlayer==null){ EntityStatuePlayer player=new EntityStatuePlayer(worldObj, skinName); player.ticksExisted=10; player.pose=pose; player.applySkin(skinName, block, facing, meta); clientPlayer=player; for(int i = 0; i < 6; i++) { this.onInventoryUpdate(i); } } return (EntityStatuePlayer)clientPlayer; } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); skinName = nbttagcompound.getString("skin"); pose.readFromNBT(nbttagcompound); block=Block.getBlockById(nbttagcompound.getShort("blockId")); if(block==null) block=Blocks.stone; meta=nbttagcompound.getByte("meta"); facing=nbttagcompound.getByte("face"); updateModel(); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); nbttagcompound.setString("skin", skinName); pose.writeToNBT(nbttagcompound); nbttagcompound.setShort("blockId",(short)Block.getIdFromBlock(block)); nbttagcompound.setByte("meta",(byte)meta); nbttagcompound.setByte("face",(byte)facing); } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return true; } @Override public Packet getDescriptionPacket() { if ((worldObj.getBlockMetadata(xCoord, yCoord, zCoord) & 4) != 0) return null; NBTTagCompound tag = new NBTTagCompound(); writeToNBT(tag); return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag); } @Override public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { readFromNBT(pkt.func_148857_g()); if(worldObj.isRemote && Minecraft.getMinecraft().currentScreen instanceof GuiStatue){ GuiStatue gui=(GuiStatue) Minecraft.getMinecraft().currentScreen; pose.itemLeftA=gui.ila; pose.itemRightA=gui.ira; } } @Override public ItemStack getStackInSlotOnClosing(int i) { return null; } public void updateModel() { if(clientPlayer!=null && worldObj!=null && worldObj.isRemote){ ((EntityStatuePlayer)clientPlayer).applySkin(skinName, block, facing, meta); } updated=false; } @Override public void updateEntity(){ if(updated) return; updated=true; } @Override public boolean hasCustomInventoryName() { return false; } @Override public void onInventoryUpdate(int slot) { if(clientPlayer != null) { clientPlayer.inventory.mainInventory[0]=getStackInSlot(4); clientPlayer.inventory.mainInventory[1]=getStackInSlot(5); clientPlayer.inventory.armorInventory[0]=getStackInSlot(3); clientPlayer.inventory.armorInventory[1]=getStackInSlot(2); clientPlayer.inventory.armorInventory[2]=getStackInSlot(1); clientPlayer.inventory.armorInventory[3]=getStackInSlot(0); } worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); } }
asiekierka/Statues
src/main/java/info/jbcs/minecraft/statues/TileEntityStatue.java
Java
gpl-2.0
3,891
<?php class UtilisateursController extends Zend_Controller_Action { public function init () { } public function inscriptionAction () { $this->view->pageTitle = "Inscription"; $this->view->formInscription = new Application_Form_Inscription(); } }
HamHamFonFon/cv_fonfonland
application/controllers/UtilisateursController.php
PHP
gpl-2.0
267
<div class="col-md-<?php echo $column_size; ?>"> <div class="box<?php if($counter == 0) { echo ' selected'; } ?>" data-option-id="<?php echo $post->post_name; ?>"> <div class="image"> <div class="select"> <div class="vct"> <div class="vctr"> <div class="vctd"> <i class="fa fa-check-circle-o"></i> </div> </div> </div> </div> <img src="<?php the_field('photo'); ?>"> </div> <div class="bar"> <h2 class="title"><?php the_title(); ?></h2> </div> </div> <div class="option-settings"> <?php if(get_field('does_this_skip_steps')) : ?> <?php $skips = get_field('steps_to_skip'); $skip_string = ''; foreach($skips as $skip) : $skip_string .= $skip->post_name.','; endforeach; $skip_string = rtrim($skip_string, ','); ?> <div class="skips" data-steps="<?php echo $skip_string; ?>"></div> <?php endif; ?> </div> </div>
studioaceofspade/conrad-grebel-wordpress
wp-content/themes/premise/option-types/leg-top.php
PHP
gpl-2.0
1,229
<?php /** * Created by PhpStorm. * User: kuibo * Date: 2017/8/30 * Time: 9:17 */ abstract class GP_Entity { protected function _save( $table, $data, $data_format ) { $retval = false; global $wpdb; // Update. if ( ! empty( $this->id ) ) { $result = $wpdb->update( $table, $data, array( 'id' => $this->id ), $data_format, array( '%d' ) ); // Set the notification ID if successful. if ( ! empty( $result ) && ! is_wp_error( $result ) ) { $retval = $this->id; } // Insert. } else { $result = $wpdb->insert( $table, $data, $data_format ); // Set the notification ID if successful. if ( ! empty( $result ) && ! is_wp_error( $result ) ) { $this->id = $wpdb->insert_id; $retval = $wpdb->insert_id; } } // Return the result. return $retval; } }
kuibobo/GamPress
wp-content/plugins/gampress/includes/core/classes/class-gp-entity.php
PHP
gpl-2.0
977
<?php /** * Wp in Progress * * @author WPinProgress * * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0) * It is also available at this URL: http://www.gnu.org/licenses/gpl-3.0.txt */ function alhenalite_post_formats_function() { if ( get_post_type( get_the_ID()) == "page" ) { $postformats = "page"; } else if ( !get_post_format() ) { $postformats = "standard"; } else { $postformats = get_post_format(); } get_template_part( 'core/post-formats/'.$postformats ); } add_action( 'alhenalite_postformat','alhenalite_post_formats_function', 10, 2 ); ?>
How2ForFree/development
wp-content/themes/alhena-lite.1.0.6/alhena-lite/core/templates/post-formats.php
PHP
gpl-2.0
617
/***************************************************************************** Copyright (c) 1995, 2013, Oracle and/or its affiliates. All Rights Reserved. Copyright (c) 2008, 2009 Google Inc. Copyright (c) 2009, Percona Inc. Portions of this file contain modifications contributed and copyrighted by Google, Inc. Those modifications are gratefully acknowledged and are described briefly in the InnoDB documentation. The contributions by Google are incorporated with their permission, and subject to the conditions contained in the file COPYING.Google. Portions of this file contain modifications contributed and copyrighted by Percona Inc.. Those modifications are gratefully acknowledged and are described briefly in the InnoDB documentation. The contributions by Percona Inc. are incorporated with their permission, and subject to the conditions contained in the file COPYING.Percona. 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, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /**************************************************//** @file srv/srv0srv.cc The database server main program Created 10/8/1995 Heikki Tuuri *******************************************************/ /* Dummy comment */ #include "srv0srv.h" #include "ut0mem.h" #include "ut0ut.h" #include "os0proc.h" #include "mem0mem.h" #include "mem0pool.h" #include "sync0sync.h" #include "que0que.h" #include "log0recv.h" #include "pars0pars.h" #include "usr0sess.h" #include "lock0lock.h" #include "trx0purge.h" #include "ibuf0ibuf.h" #include "buf0flu.h" #include "buf0lru.h" #include "btr0sea.h" #include "dict0load.h" #include "dict0boot.h" #include "dict0stats_bg.h" /* dict_stats_event */ #include "srv0start.h" #include "row0mysql.h" #include "ha_prototypes.h" #include "trx0i_s.h" #include "os0sync.h" /* for HAVE_ATOMIC_BUILTINS */ #include "srv0mon.h" #include "ut0crc32.h" #include "mysql/plugin.h" #include "mysql/service_thd_wait.h" /* The following is the maximum allowed duration of a lock wait. */ UNIV_INTERN ulint srv_fatal_semaphore_wait_threshold = 600; /* How much data manipulation language (DML) statements need to be delayed, in microseconds, in order to reduce the lagging of the purge thread. */ UNIV_INTERN ulint srv_dml_needed_delay = 0; UNIV_INTERN ibool srv_monitor_active = FALSE; UNIV_INTERN ibool srv_error_monitor_active = FALSE; UNIV_INTERN ibool srv_buf_dump_thread_active = FALSE; UNIV_INTERN ibool srv_dict_stats_thread_active = FALSE; UNIV_INTERN const char* srv_main_thread_op_info = ""; /** Prefix used by MySQL to indicate pre-5.1 table name encoding */ const char srv_mysql50_table_name_prefix[10] = "#mysql50#"; /* Server parameters which are read from the initfile */ /* The following three are dir paths which are catenated before file names, where the file name itself may also contain a path */ UNIV_INTERN char* srv_data_home = NULL; /** Rollback files directory, can be absolute. */ UNIV_INTERN char* srv_undo_dir = NULL; /** The number of tablespaces to use for rollback segments. */ UNIV_INTERN ulong srv_undo_tablespaces = 8; /** The number of UNDO tablespaces that are open and ready to use. */ UNIV_INTERN ulint srv_undo_tablespaces_open = 8; /* The number of rollback segments to use */ UNIV_INTERN ulong srv_undo_logs = 1; #ifdef UNIV_LOG_ARCHIVE UNIV_INTERN char* srv_arch_dir = NULL; #endif /* UNIV_LOG_ARCHIVE */ /** Set if InnoDB must operate in read-only mode. We don't do any recovery and open all tables in RO mode instead of RW mode. We don't sync the max trx id to disk either. */ UNIV_INTERN my_bool srv_read_only_mode; /** store to its own file each table created by an user; data dictionary tables are in the system tablespace 0 */ UNIV_INTERN my_bool srv_file_per_table; /** The file format to use on new *.ibd files. */ UNIV_INTERN ulint srv_file_format = 0; /** Whether to check file format during startup. A value of UNIV_FORMAT_MAX + 1 means no checking ie. FALSE. The default is to set it to the highest format we support. */ UNIV_INTERN ulint srv_max_file_format_at_startup = UNIV_FORMAT_MAX; #if UNIV_FORMAT_A # error "UNIV_FORMAT_A must be 0!" #endif /** Place locks to records only i.e. do not use next-key locking except on duplicate key checking and foreign key checking */ UNIV_INTERN ibool srv_locks_unsafe_for_binlog = FALSE; /** Sort buffer size in index creation */ UNIV_INTERN ulong srv_sort_buf_size = 1048576; /** Maximum modification log file size for online index creation */ UNIV_INTERN unsigned long long srv_online_max_size; /* If this flag is TRUE, then we will use the native aio of the OS (provided we compiled Innobase with it in), otherwise we will use simulated aio we build below with threads. Currently we support native aio on windows and linux */ UNIV_INTERN my_bool srv_use_native_aio = TRUE; #ifdef __WIN__ /* Windows native condition variables. We use runtime loading / function pointers, because they are not available on Windows Server 2003 and Windows XP/2000. We use condition for events on Windows if possible, even if os_event resembles Windows kernel event object well API-wise. The reason is performance, kernel objects are heavyweights and WaitForSingleObject() is a performance killer causing calling thread to context switch. Besides, Innodb is preallocating large number (often millions) of os_events. With kernel event objects it takes a big chunk out of non-paged pool, which is better suited for tasks like IO than for storing idle event objects. */ UNIV_INTERN ibool srv_use_native_conditions = FALSE; #endif /* __WIN__ */ UNIV_INTERN ulint srv_n_data_files = 0; UNIV_INTERN char** srv_data_file_names = NULL; /* size in database pages */ UNIV_INTERN ulint* srv_data_file_sizes = NULL; /* if TRUE, then we auto-extend the last data file */ UNIV_INTERN ibool srv_auto_extend_last_data_file = FALSE; /* if != 0, this tells the max size auto-extending may increase the last data file size */ UNIV_INTERN ulint srv_last_file_size_max = 0; /* If the last data file is auto-extended, we add this many pages to it at a time */ UNIV_INTERN ulong srv_auto_extend_increment = 8; UNIV_INTERN ulint* srv_data_file_is_raw_partition = NULL; /* If the following is TRUE we do not allow inserts etc. This protects the user from forgetting the 'newraw' keyword to my.cnf */ UNIV_INTERN ibool srv_created_new_raw = FALSE; UNIV_INTERN char* srv_log_group_home_dir = NULL; UNIV_INTERN ulong srv_n_log_files = SRV_N_LOG_FILES_MAX; /* size in database pages */ UNIV_INTERN ib_uint64_t srv_log_file_size = IB_UINT64_MAX; UNIV_INTERN ib_uint64_t srv_log_file_size_requested; /* size in database pages */ UNIV_INTERN ulint srv_log_buffer_size = ULINT_MAX; UNIV_INTERN ulong srv_flush_log_at_trx_commit = 1; UNIV_INTERN uint srv_flush_log_at_timeout = 1; UNIV_INTERN ulong srv_page_size = UNIV_PAGE_SIZE_DEF; UNIV_INTERN ulong srv_page_size_shift = UNIV_PAGE_SIZE_SHIFT_DEF; /* Try to flush dirty pages so as to avoid IO bursts at the checkpoints. */ UNIV_INTERN char srv_adaptive_flushing = TRUE; /** Maximum number of times allowed to conditionally acquire mutex before switching to blocking wait on the mutex */ #define MAX_MUTEX_NOWAIT 20 /** Check whether the number of failed nonblocking mutex acquisition attempts exceeds maximum allowed value. If so, srv_printf_innodb_monitor() will request mutex acquisition with mutex_enter(), which will wait until it gets the mutex. */ #define MUTEX_NOWAIT(mutex_skipped) ((mutex_skipped) < MAX_MUTEX_NOWAIT) /** The sort order table of the MySQL latin1_swedish_ci character set collation */ UNIV_INTERN const byte* srv_latin1_ordering; /* use os/external memory allocator */ UNIV_INTERN my_bool srv_use_sys_malloc = TRUE; /* requested size in kilobytes */ UNIV_INTERN ulint srv_buf_pool_size = ULINT_MAX; /* requested number of buffer pool instances */ UNIV_INTERN ulint srv_buf_pool_instances = 1; /* number of locks to protect buf_pool->page_hash */ UNIV_INTERN ulong srv_n_page_hash_locks = 16; /** Scan depth for LRU flush batch i.e.: number of blocks scanned*/ UNIV_INTERN ulong srv_LRU_scan_depth = 1024; /** whether or not to flush neighbors of a block */ UNIV_INTERN ulong srv_flush_neighbors = 1; /* previously requested size */ UNIV_INTERN ulint srv_buf_pool_old_size; /* current size in kilobytes */ UNIV_INTERN ulint srv_buf_pool_curr_size = 0; /* size in bytes */ UNIV_INTERN ulint srv_mem_pool_size = ULINT_MAX; UNIV_INTERN ulint srv_lock_table_size = ULINT_MAX; /* This parameter is deprecated. Use srv_n_io_[read|write]_threads instead. */ UNIV_INTERN ulint srv_n_file_io_threads = ULINT_MAX; UNIV_INTERN ulint srv_n_read_io_threads = ULINT_MAX; UNIV_INTERN ulint srv_n_write_io_threads = ULINT_MAX; /* Switch to enable random read ahead. */ UNIV_INTERN my_bool srv_random_read_ahead = FALSE; /* User settable value of the number of pages that must be present in the buffer cache and accessed sequentially for InnoDB to trigger a readahead request. */ UNIV_INTERN ulong srv_read_ahead_threshold = 56; #ifdef UNIV_LOG_ARCHIVE UNIV_INTERN ibool srv_log_archive_on = FALSE; UNIV_INTERN ibool srv_archive_recovery = 0; UNIV_INTERN ib_uint64_t srv_archive_recovery_limit_lsn; #endif /* UNIV_LOG_ARCHIVE */ /* This parameter is used to throttle the number of insert buffers that are merged in a batch. By increasing this parameter on a faster disk you can possibly reduce the number of I/O operations performed to complete the merge operation. The value of this parameter is used as is by the background loop when the system is idle (low load), on a busy system the parameter is scaled down by a factor of 4, this is to avoid putting a heavier load on the I/O sub system. */ UNIV_INTERN ulong srv_insert_buffer_batch_size = 20; UNIV_INTERN char* srv_file_flush_method_str = NULL; UNIV_INTERN ulint srv_unix_file_flush_method = SRV_UNIX_FSYNC; UNIV_INTERN ulint srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED; UNIV_INTERN ulint srv_max_n_open_files = 300; /* Number of IO operations per second the server can do */ UNIV_INTERN ulong srv_io_capacity = 200; UNIV_INTERN ulong srv_max_io_capacity = 400; /* The InnoDB main thread tries to keep the ratio of modified pages in the buffer pool to all database pages in the buffer pool smaller than the following number. But it is not guaranteed that the value stays below that during a time of heavy update/insert activity. */ UNIV_INTERN ulong srv_max_buf_pool_modified_pct = 75; UNIV_INTERN ulong srv_max_dirty_pages_pct_lwm = 50; /* This is the percentage of log capacity at which adaptive flushing, if enabled, will kick in. */ UNIV_INTERN ulong srv_adaptive_flushing_lwm = 10; /* Number of iterations over which adaptive flushing is averaged. */ UNIV_INTERN ulong srv_flushing_avg_loops = 30; /* The number of purge threads to use.*/ UNIV_INTERN ulong srv_n_purge_threads = 1; /* the number of pages to purge in one batch */ UNIV_INTERN ulong srv_purge_batch_size = 20; /* Internal setting for "innodb_stats_method". Decides how InnoDB treats NULL value when collecting statistics. By default, it is set to SRV_STATS_NULLS_EQUAL(0), ie. all NULL value are treated equal */ UNIV_INTERN ulong srv_innodb_stats_method = SRV_STATS_NULLS_EQUAL; UNIV_INTERN srv_stats_t srv_stats; /* structure to pass status variables to MySQL */ UNIV_INTERN export_var_t export_vars; /** Normally 0. When nonzero, skip some phases of crash recovery, starting from SRV_FORCE_IGNORE_CORRUPT, so that data can be recovered by SELECT or mysqldump. When this is nonzero, we do not allow any user modifications to the data. */ UNIV_INTERN ulong srv_force_recovery; #ifndef DBUG_OFF /** Inject a crash at different steps of the recovery process. This is for testing and debugging only. */ UNIV_INTERN ulong srv_force_recovery_crash; #endif /* !DBUG_OFF */ /** Print all user-level transactions deadlocks to mysqld stderr */ UNIV_INTERN my_bool srv_print_all_deadlocks = FALSE; /** Enable INFORMATION_SCHEMA.innodb_cmp_per_index */ UNIV_INTERN my_bool srv_cmp_per_index_enabled = FALSE; /* If the following is set to 1 then we do not run purge and insert buffer merge to completion before shutdown. If it is set to 2, do not even flush the buffer pool to data files at the shutdown: we effectively 'crash' InnoDB (but lose no committed transactions). */ UNIV_INTERN ulint srv_fast_shutdown = 0; /* Generate a innodb_status.<pid> file */ UNIV_INTERN ibool srv_innodb_status = FALSE; /* When estimating number of different key values in an index, sample this many index pages, there are 2 ways to calculate statistics: * persistent stats that are calculated by ANALYZE TABLE and saved in the innodb database. * quick transient stats, that are used if persistent stats for the given table/index are not found in the innodb database */ UNIV_INTERN unsigned long long srv_stats_transient_sample_pages = 8; UNIV_INTERN my_bool srv_stats_persistent = TRUE; UNIV_INTERN unsigned long long srv_stats_persistent_sample_pages = 20; UNIV_INTERN my_bool srv_stats_auto_recalc = TRUE; UNIV_INTERN ibool srv_use_doublewrite_buf = TRUE; /** doublewrite buffer is 1MB is size i.e.: it can hold 128 16K pages. The following parameter is the size of the buffer that is used for batch flushing i.e.: LRU flushing and flush_list flushing. The rest of the pages are used for single page flushing. */ UNIV_INTERN ulong srv_doublewrite_batch_size = 120; UNIV_INTERN ulong srv_replication_delay = 0; /*-------------------------------------------*/ UNIV_INTERN ulong srv_n_spin_wait_rounds = 30; UNIV_INTERN ulong srv_spin_wait_delay = 6; UNIV_INTERN ibool srv_priority_boost = TRUE; #ifdef UNIV_DEBUG UNIV_INTERN ibool srv_print_thread_releases = FALSE; UNIV_INTERN ibool srv_print_lock_waits = FALSE; UNIV_INTERN ibool srv_print_buf_io = FALSE; UNIV_INTERN ibool srv_print_log_io = FALSE; UNIV_INTERN ibool srv_print_latch_waits = FALSE; #endif /* UNIV_DEBUG */ static ulint srv_n_rows_inserted_old = 0; static ulint srv_n_rows_updated_old = 0; static ulint srv_n_rows_deleted_old = 0; static ulint srv_n_rows_read_old = 0; UNIV_INTERN ulint srv_truncated_status_writes = 0; UNIV_INTERN ulint srv_available_undo_logs = 0; /* Set the following to 0 if you want InnoDB to write messages on stderr on startup/shutdown. */ UNIV_INTERN ibool srv_print_verbose_log = TRUE; UNIV_INTERN ibool srv_print_innodb_monitor = FALSE; UNIV_INTERN ibool srv_print_innodb_lock_monitor = FALSE; UNIV_INTERN ibool srv_print_innodb_tablespace_monitor = FALSE; UNIV_INTERN ibool srv_print_innodb_table_monitor = FALSE; /* Array of English strings describing the current state of an i/o handler thread */ UNIV_INTERN const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS]; UNIV_INTERN const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS]; UNIV_INTERN time_t srv_last_monitor_time; UNIV_INTERN ib_mutex_t srv_innodb_monitor_mutex; /* Mutex for locking srv_monitor_file. Not created if srv_read_only_mode */ UNIV_INTERN ib_mutex_t srv_monitor_file_mutex; #ifdef UNIV_PFS_MUTEX # ifndef HAVE_ATOMIC_BUILTINS /* Key to register server_mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t server_mutex_key; # endif /* !HAVE_ATOMIC_BUILTINS */ /** Key to register srv_innodb_monitor_mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_innodb_monitor_mutex_key; /** Key to register srv_monitor_file_mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_monitor_file_mutex_key; /** Key to register srv_dict_tmpfile_mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_dict_tmpfile_mutex_key; /** Key to register the mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_misc_tmpfile_mutex_key; /** Key to register srv_sys_t::mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_sys_mutex_key; /** Key to register srv_sys_t::tasks_mutex with performance schema */ UNIV_INTERN mysql_pfs_key_t srv_sys_tasks_mutex_key; #endif /* UNIV_PFS_MUTEX */ /** Temporary file for innodb monitor output */ UNIV_INTERN FILE* srv_monitor_file; /** Mutex for locking srv_dict_tmpfile. Not created if srv_read_only_mode. This mutex has a very high rank; threads reserving it should not be holding any InnoDB latches. */ UNIV_INTERN ib_mutex_t srv_dict_tmpfile_mutex; /** Temporary file for output from the data dictionary */ UNIV_INTERN FILE* srv_dict_tmpfile; /** Mutex for locking srv_misc_tmpfile. Not created if srv_read_only_mode. This mutex has a very low rank; threads reserving it should not acquire any further latches or sleep before releasing this one. */ UNIV_INTERN ib_mutex_t srv_misc_tmpfile_mutex; /** Temporary file for miscellanous diagnostic output */ UNIV_INTERN FILE* srv_misc_tmpfile; UNIV_INTERN ulint srv_main_thread_process_no = 0; UNIV_INTERN ulint srv_main_thread_id = 0; /* The following counts are used by the srv_master_thread. */ /** Iterations of the loop bounded by 'srv_active' label. */ static ulint srv_main_active_loops = 0; /** Iterations of the loop bounded by the 'srv_idle' label. */ static ulint srv_main_idle_loops = 0; /** Iterations of the loop bounded by the 'srv_shutdown' label. */ static ulint srv_main_shutdown_loops = 0; /** Log writes involving flush. */ static ulint srv_log_writes_and_flush = 0; /* This is only ever touched by the master thread. It records the time when the last flush of log file has happened. The master thread ensures that we flush the log files at least once per second. */ static time_t srv_last_log_flush_time; /* Interval in seconds at which various tasks are performed by the master thread when server is active. In order to balance the workload, we should try to keep intervals such that they are not multiple of each other. For example, if we have intervals for various tasks defined as 5, 10, 15, 60 then all tasks will be performed when current_time % 60 == 0 and no tasks will be performed when current_time % 5 != 0. */ # define SRV_MASTER_CHECKPOINT_INTERVAL (7) # define SRV_MASTER_PURGE_INTERVAL (10) #ifdef MEM_PERIODIC_CHECK # define SRV_MASTER_MEM_VALIDATE_INTERVAL (13) #endif /* MEM_PERIODIC_CHECK */ # define SRV_MASTER_DICT_LRU_INTERVAL (47) /** Acquire the system_mutex. */ #define srv_sys_mutex_enter() do { \ mutex_enter(&srv_sys->mutex); \ } while (0) /** Test if the system mutex is owned. */ #define srv_sys_mutex_own() (mutex_own(&srv_sys->mutex) \ && !srv_read_only_mode) /** Release the system mutex. */ #define srv_sys_mutex_exit() do { \ mutex_exit(&srv_sys->mutex); \ } while (0) #define fetch_lock_wait_timeout(trx) \ ((trx)->lock.allowed_to_wait \ ? thd_lock_wait_timeout((trx)->mysql_thd) \ : 0) /* IMPLEMENTATION OF THE SERVER MAIN PROGRAM ========================================= There is the following analogue between this database server and an operating system kernel: DB concept equivalent OS concept ---------- --------------------- transaction -- process; query thread -- thread; lock -- semaphore; kernel -- kernel; query thread execution: (a) without lock mutex reserved -- process executing in user mode; (b) with lock mutex reserved -- process executing in kernel mode; The server has several backgroind threads all running at the same priority as user threads. It periodically checks if here is anything happening in the server which requires intervention of the master thread. Such situations may be, for example, when flushing of dirty blocks is needed in the buffer pool or old version of database rows have to be cleaned away (purged). The user can configure a separate dedicated purge thread(s) too, in which case the master thread does not do any purging. The threads which we call user threads serve the queries of the MySQL server. They run at normal priority. When there is no activity in the system, also the master thread suspends itself to wait for an event making the server totally silent. There is still one complication in our server design. If a background utility thread obtains a resource (e.g., mutex) needed by a user thread, and there is also some other user activity in the system, the user thread may have to wait indefinitely long for the resource, as the OS does not schedule a background thread if there is some other runnable user thread. This problem is called priority inversion in real-time programming. One solution to the priority inversion problem would be to keep record of which thread owns which resource and in the above case boost the priority of the background thread so that it will be scheduled and it can release the resource. This solution is called priority inheritance in real-time programming. A drawback of this solution is that the overhead of acquiring a mutex increases slightly, maybe 0.2 microseconds on a 100 MHz Pentium, because the thread has to call os_thread_get_curr_id. This may be compared to 0.5 microsecond overhead for a mutex lock-unlock pair. Note that the thread cannot store the information in the resource , say mutex, itself, because competing threads could wipe out the information if it is stored before acquiring the mutex, and if it stored afterwards, the information is outdated for the time of one machine instruction, at least. (To be precise, the information could be stored to lock_word in mutex if the machine supports atomic swap.) The above solution with priority inheritance may become actual in the future, currently we do not implement any priority twiddling solution. Our general aim is to reduce the contention of all mutexes by making them more fine grained. The thread table contains information of the current status of each thread existing in the system, and also the event semaphores used in suspending the master thread and utility threads when they have nothing to do. The thread table can be seen as an analogue to the process table in a traditional Unix implementation. */ /** The server system struct */ struct srv_sys_t{ ib_mutex_t tasks_mutex; /*!< variable protecting the tasks queue */ UT_LIST_BASE_NODE_T(que_thr_t) tasks; /*!< task queue */ ib_mutex_t mutex; /*!< variable protecting the fields below. */ ulint n_sys_threads; /*!< size of the sys_threads array */ srv_slot_t* sys_threads; /*!< server thread table */ ulint n_threads_active[SRV_MASTER + 1]; /*!< number of threads active in a thread class */ srv_stats_t::ulint_ctr_1_t activity_count; /*!< For tracking server activity */ }; #ifndef HAVE_ATOMIC_BUILTINS /** Mutex protecting some server global variables. */ UNIV_INTERN ib_mutex_t server_mutex; #endif /* !HAVE_ATOMIC_BUILTINS */ static srv_sys_t* srv_sys = NULL; /** Event to signal the monitor thread. */ UNIV_INTERN os_event_t srv_monitor_event; /** Event to signal the error thread */ UNIV_INTERN os_event_t srv_error_event; /** Event to signal the buffer pool dump/load thread */ UNIV_INTERN os_event_t srv_buf_dump_event; /** The buffer pool dump/load file name */ UNIV_INTERN char* srv_buf_dump_filename; /** Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown and/or load it during startup. */ UNIV_INTERN char srv_buffer_pool_dump_at_shutdown = FALSE; UNIV_INTERN char srv_buffer_pool_load_at_startup = FALSE; /** Slot index in the srv_sys->sys_threads array for the purge thread. */ static const ulint SRV_PURGE_SLOT = 1; /** Slot index in the srv_sys->sys_threads array for the master thread. */ static const ulint SRV_MASTER_SLOT = 0; /*********************************************************************//** Prints counters for work done by srv_master_thread. */ static void srv_print_master_thread_info( /*=========================*/ FILE *file) /* in: output stream */ { fprintf(file, "srv_master_thread loops: %lu srv_active, " "%lu srv_shutdown, %lu srv_idle\n", srv_main_active_loops, srv_main_shutdown_loops, srv_main_idle_loops); fprintf(file, "srv_master_thread log flush and writes: %lu\n", srv_log_writes_and_flush); } /*********************************************************************//** Sets the info describing an i/o thread current state. */ UNIV_INTERN void srv_set_io_thread_op_info( /*======================*/ ulint i, /*!< in: the 'segment' of the i/o thread */ const char* str) /*!< in: constant char string describing the state */ { ut_a(i < SRV_MAX_N_IO_THREADS); srv_io_thread_op_info[i] = str; } /*********************************************************************//** Resets the info describing an i/o thread current state. */ UNIV_INTERN void srv_reset_io_thread_op_info() /*=========================*/ { for (ulint i = 0; i < UT_ARR_SIZE(srv_io_thread_op_info); ++i) { srv_io_thread_op_info[i] = "not started yet"; } } #ifdef UNIV_DEBUG /*********************************************************************//** Validates the type of a thread table slot. @return TRUE if ok */ static ibool srv_thread_type_validate( /*=====================*/ srv_thread_type type) /*!< in: thread type */ { switch (type) { case SRV_NONE: break; case SRV_WORKER: case SRV_PURGE: case SRV_MASTER: return(TRUE); } ut_error; return(FALSE); } #endif /* UNIV_DEBUG */ /*********************************************************************//** Gets the type of a thread table slot. @return thread type */ static srv_thread_type srv_slot_get_type( /*==============*/ const srv_slot_t* slot) /*!< in: thread slot */ { srv_thread_type type = slot->type; ut_ad(srv_thread_type_validate(type)); return(type); } /*********************************************************************//** Reserves a slot in the thread table for the current thread. @return reserved slot */ static srv_slot_t* srv_reserve_slot( /*=============*/ srv_thread_type type) /*!< in: type of the thread */ { srv_slot_t* slot = 0; srv_sys_mutex_enter(); ut_ad(srv_thread_type_validate(type)); switch (type) { case SRV_MASTER: slot = &srv_sys->sys_threads[SRV_MASTER_SLOT]; break; case SRV_PURGE: slot = &srv_sys->sys_threads[SRV_PURGE_SLOT]; break; case SRV_WORKER: /* Find an empty slot, skip the master and purge slots. */ for (slot = &srv_sys->sys_threads[2]; slot->in_use; ++slot) { ut_a(slot < &srv_sys->sys_threads[ srv_sys->n_sys_threads]); } break; case SRV_NONE: ut_error; } ut_a(!slot->in_use); slot->in_use = TRUE; slot->suspended = FALSE; slot->type = type; ut_ad(srv_slot_get_type(slot) == type); ++srv_sys->n_threads_active[type]; srv_sys_mutex_exit(); return(slot); } /*********************************************************************//** Suspends the calling thread to wait for the event in its thread slot. @return the current signal count of the event. */ static ib_int64_t srv_suspend_thread_low( /*===================*/ srv_slot_t* slot) /*!< in/out: thread slot */ { ut_ad(!srv_read_only_mode); ut_ad(srv_sys_mutex_own()); ut_ad(slot->in_use); srv_thread_type type = srv_slot_get_type(slot); switch (type) { case SRV_NONE: ut_error; case SRV_MASTER: /* We have only one master thread and it should be the first entry always. */ ut_a(srv_sys->n_threads_active[type] == 1); break; case SRV_PURGE: /* We have only one purge coordinator thread and it should be the second entry always. */ ut_a(srv_sys->n_threads_active[type] == 1); break; case SRV_WORKER: ut_a(srv_n_purge_threads > 1); ut_a(srv_sys->n_threads_active[type] > 0); break; } ut_a(!slot->suspended); slot->suspended = TRUE; ut_a(srv_sys->n_threads_active[type] > 0); srv_sys->n_threads_active[type]--; return(os_event_reset(slot->event)); } /*********************************************************************//** Suspends the calling thread to wait for the event in its thread slot. @return the current signal count of the event. */ static ib_int64_t srv_suspend_thread( /*===============*/ srv_slot_t* slot) /*!< in/out: thread slot */ { srv_sys_mutex_enter(); ib_int64_t sig_count = srv_suspend_thread_low(slot); srv_sys_mutex_exit(); return(sig_count); } /*********************************************************************//** Releases threads of the type given from suspension in the thread table. NOTE! The server mutex has to be reserved by the caller! @return number of threads released: this may be less than n if not enough threads were suspended at the moment. */ UNIV_INTERN ulint srv_release_threads( /*================*/ srv_thread_type type, /*!< in: thread type */ ulint n) /*!< in: number of threads to release */ { ulint i; ulint count = 0; ut_ad(srv_thread_type_validate(type)); ut_ad(n > 0); srv_sys_mutex_enter(); for (i = 0; i < srv_sys->n_sys_threads; i++) { srv_slot_t* slot; slot = &srv_sys->sys_threads[i]; if (slot->in_use && srv_slot_get_type(slot) == type && slot->suspended) { switch (type) { case SRV_NONE: ut_error; case SRV_MASTER: /* We have only one master thread and it should be the first entry always. */ ut_a(n == 1); ut_a(i == SRV_MASTER_SLOT); ut_a(srv_sys->n_threads_active[type] == 0); break; case SRV_PURGE: /* We have only one purge coordinator thread and it should be the second entry always. */ ut_a(n == 1); ut_a(i == SRV_PURGE_SLOT); ut_a(srv_n_purge_threads > 0); ut_a(srv_sys->n_threads_active[type] == 0); break; case SRV_WORKER: ut_a(srv_n_purge_threads > 1); ut_a(srv_sys->n_threads_active[type] < srv_n_purge_threads - 1); break; } slot->suspended = FALSE; ++srv_sys->n_threads_active[type]; os_event_set(slot->event); if (++count == n) { break; } } } srv_sys_mutex_exit(); return(count); } /*********************************************************************//** Release a thread's slot. */ static void srv_free_slot( /*==========*/ srv_slot_t* slot) /*!< in/out: thread slot */ { srv_sys_mutex_enter(); if (!slot->suspended) { /* Mark the thread as inactive. */ srv_suspend_thread_low(slot); } /* Free the slot for reuse. */ ut_ad(slot->in_use); slot->in_use = FALSE; srv_sys_mutex_exit(); } /*********************************************************************//** Initializes the server. */ UNIV_INTERN void srv_init(void) /*==========*/ { ulint n_sys_threads = 0; ulint srv_sys_sz = sizeof(*srv_sys); #ifndef HAVE_ATOMIC_BUILTINS mutex_create(server_mutex_key, &server_mutex, SYNC_ANY_LATCH); #endif /* !HAVE_ATOMIC_BUILTINS */ mutex_create(srv_innodb_monitor_mutex_key, &srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK); if (!srv_read_only_mode) { /* Number of purge threads + master thread */ n_sys_threads = srv_n_purge_threads + 1; srv_sys_sz += n_sys_threads * sizeof(*srv_sys->sys_threads); } srv_sys = static_cast<srv_sys_t*>(mem_zalloc(srv_sys_sz)); srv_sys->n_sys_threads = n_sys_threads; if (!srv_read_only_mode) { mutex_create(srv_sys_mutex_key, &srv_sys->mutex, SYNC_THREADS); mutex_create(srv_sys_tasks_mutex_key, &srv_sys->tasks_mutex, SYNC_ANY_LATCH); srv_sys->sys_threads = (srv_slot_t*) &srv_sys[1]; for (ulint i = 0; i < srv_sys->n_sys_threads; ++i) { srv_slot_t* slot = &srv_sys->sys_threads[i]; slot->event = os_event_create(); ut_a(slot->event); } srv_error_event = os_event_create(); srv_monitor_event = os_event_create(); srv_buf_dump_event = os_event_create(); UT_LIST_INIT(srv_sys->tasks); } /* page_zip_stat_per_index_mutex is acquired from: 1. page_zip_compress() (after SYNC_FSP) 2. page_zip_decompress() 3. i_s_cmp_per_index_fill_low() (where SYNC_DICT is acquired) 4. innodb_cmp_per_index_update(), no other latches since we do not acquire any other latches while holding this mutex, it can have very low level. We pick SYNC_ANY_LATCH for it. */ mutex_create( page_zip_stat_per_index_mutex_key, &page_zip_stat_per_index_mutex, SYNC_ANY_LATCH); /* Create dummy indexes for infimum and supremum records */ dict_ind_init(); srv_conc_init(); /* Initialize some INFORMATION SCHEMA internal structures */ trx_i_s_cache_init(trx_i_s_cache); ut_crc32_init(); } /*********************************************************************//** Frees the data structures created in srv_init(). */ UNIV_INTERN void srv_free(void) /*==========*/ { srv_conc_free(); /* The mutexes srv_sys->mutex and srv_sys->tasks_mutex should have been freed by sync_close() already. */ mem_free(srv_sys); srv_sys = NULL; trx_i_s_cache_free(trx_i_s_cache); if (!srv_read_only_mode) { os_event_free(srv_buf_dump_event); srv_buf_dump_event = NULL; } } /*********************************************************************//** Initializes the synchronization primitives, memory system, and the thread local storage. */ UNIV_INTERN void srv_general_init(void) /*==================*/ { ut_mem_init(); /* Reset the system variables in the recovery module. */ recv_sys_var_init(); os_sync_init(); sync_init(); mem_init(srv_mem_pool_size); que_init(); row_mysql_init(); } /*********************************************************************//** Normalizes init parameter values to use units we use inside InnoDB. */ static void srv_normalize_init_values(void) /*===========================*/ { ulint n; ulint i; n = srv_n_data_files; for (i = 0; i < n; i++) { srv_data_file_sizes[i] = srv_data_file_sizes[i] * ((1024 * 1024) / UNIV_PAGE_SIZE); } srv_last_file_size_max = srv_last_file_size_max * ((1024 * 1024) / UNIV_PAGE_SIZE); srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE; srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE; srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE); } /*********************************************************************//** Boots the InnoDB server. */ UNIV_INTERN void srv_boot(void) /*==========*/ { /* Transform the init parameter values given by MySQL to use units we use inside InnoDB: */ srv_normalize_init_values(); /* Initialize synchronization primitives, memory management, and thread local storage */ srv_general_init(); /* Initialize this module */ srv_init(); srv_mon_create(); } /******************************************************************//** Refreshes the values used to calculate per-second averages. */ static void srv_refresh_innodb_monitor_stats(void) /*==================================*/ { mutex_enter(&srv_innodb_monitor_mutex); srv_last_monitor_time = time(NULL); os_aio_refresh_stats(); btr_cur_n_sea_old = btr_cur_n_sea; btr_cur_n_non_sea_old = btr_cur_n_non_sea; log_refresh_stats(); buf_refresh_io_stats_all(); srv_n_rows_inserted_old = srv_stats.n_rows_inserted; srv_n_rows_updated_old = srv_stats.n_rows_updated; srv_n_rows_deleted_old = srv_stats.n_rows_deleted; srv_n_rows_read_old = srv_stats.n_rows_read; mutex_exit(&srv_innodb_monitor_mutex); } /******************************************************************//** Outputs to a file the output of the InnoDB Monitor. @return FALSE if not all information printed due to failure to obtain necessary mutex */ UNIV_INTERN ibool srv_printf_innodb_monitor( /*======================*/ FILE* file, /*!< in: output stream */ ibool nowait, /*!< in: whether to wait for the lock_sys_t:: mutex */ ulint* trx_start_pos, /*!< out: file position of the start of the list of active transactions */ ulint* trx_end) /*!< out: file position of the end of the list of active transactions */ { double time_elapsed; time_t current_time; ulint n_reserved; ibool ret; mutex_enter(&srv_innodb_monitor_mutex); current_time = time(NULL); /* We add 0.001 seconds to time_elapsed to prevent division by zero if two users happen to call SHOW ENGINE INNODB STATUS at the same time */ time_elapsed = difftime(current_time, srv_last_monitor_time) + 0.001; srv_last_monitor_time = time(NULL); fputs("\n=====================================\n", file); ut_print_timestamp(file); fprintf(file, " INNODB MONITOR OUTPUT\n" "=====================================\n" "Per second averages calculated from the last %lu seconds\n", (ulong) time_elapsed); fputs("-----------------\n" "BACKGROUND THREAD\n" "-----------------\n", file); srv_print_master_thread_info(file); fputs("----------\n" "SEMAPHORES\n" "----------\n", file); sync_print(file); /* Conceptually, srv_innodb_monitor_mutex has a very high latching order level in sync0sync.h, while dict_foreign_err_mutex has a very low level 135. Therefore we can reserve the latter mutex here without a danger of a deadlock of threads. */ mutex_enter(&dict_foreign_err_mutex); if (!srv_read_only_mode && ftell(dict_foreign_err_file) != 0L) { fputs("------------------------\n" "LATEST FOREIGN KEY ERROR\n" "------------------------\n", file); ut_copy_file(file, dict_foreign_err_file); } mutex_exit(&dict_foreign_err_mutex); /* Only if lock_print_info_summary proceeds correctly, before we call the lock_print_info_all_transactions to print all the lock information. IMPORTANT NOTE: This function acquires the lock mutex on success. */ ret = lock_print_info_summary(file, nowait); if (ret) { if (trx_start_pos) { long t = ftell(file); if (t < 0) { *trx_start_pos = ULINT_UNDEFINED; } else { *trx_start_pos = (ulint) t; } } /* NOTE: If we get here then we have the lock mutex. This function will release the lock mutex that we acquired when we called the lock_print_info_summary() function earlier. */ lock_print_info_all_transactions(file); if (trx_end) { long t = ftell(file); if (t < 0) { *trx_end = ULINT_UNDEFINED; } else { *trx_end = (ulint) t; } } } fputs("--------\n" "FILE I/O\n" "--------\n", file); os_aio_print(file); fputs("-------------------------------------\n" "INSERT BUFFER AND ADAPTIVE HASH INDEX\n" "-------------------------------------\n", file); ibuf_print(file); ha_print_info(file, btr_search_sys->hash_index); fprintf(file, "%.2f hash searches/s, %.2f non-hash searches/s\n", (btr_cur_n_sea - btr_cur_n_sea_old) / time_elapsed, (btr_cur_n_non_sea - btr_cur_n_non_sea_old) / time_elapsed); btr_cur_n_sea_old = btr_cur_n_sea; btr_cur_n_non_sea_old = btr_cur_n_non_sea; fputs("---\n" "LOG\n" "---\n", file); log_print(file); fputs("----------------------\n" "BUFFER POOL AND MEMORY\n" "----------------------\n", file); fprintf(file, "Total memory allocated " ULINTPF "; in additional pool allocated " ULINTPF "\n", ut_total_allocated_memory, mem_pool_get_reserved(mem_comm_pool)); fprintf(file, "Dictionary memory allocated " ULINTPF "\n", dict_sys->size); buf_print_io(file); fputs("--------------\n" "ROW OPERATIONS\n" "--------------\n", file); fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n", (long) srv_conc_get_active_threads(), srv_conc_get_waiting_threads()); /* This is a dirty read, without holding trx_sys->mutex. */ fprintf(file, "%lu read views open inside InnoDB\n", UT_LIST_GET_LEN(trx_sys->view_list)); n_reserved = fil_space_get_n_reserved_extents(0); if (n_reserved > 0) { fprintf(file, "%lu tablespace extents now reserved for" " B-tree split operations\n", (ulong) n_reserved); } #ifdef UNIV_LINUX fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n", (ulong) srv_main_thread_process_no, (ulong) srv_main_thread_id, srv_main_thread_op_info); #else fprintf(file, "Main thread id %lu, state: %s\n", (ulong) srv_main_thread_id, srv_main_thread_op_info); #endif fprintf(file, "Number of rows inserted " ULINTPF ", updated " ULINTPF ", deleted " ULINTPF ", read " ULINTPF "\n", (ulint) srv_stats.n_rows_inserted, (ulint) srv_stats.n_rows_updated, (ulint) srv_stats.n_rows_deleted, (ulint) srv_stats.n_rows_read); fprintf(file, "%.2f inserts/s, %.2f updates/s," " %.2f deletes/s, %.2f reads/s\n", ((ulint) srv_stats.n_rows_inserted - srv_n_rows_inserted_old) / time_elapsed, ((ulint) srv_stats.n_rows_updated - srv_n_rows_updated_old) / time_elapsed, ((ulint) srv_stats.n_rows_deleted - srv_n_rows_deleted_old) / time_elapsed, ((ulint) srv_stats.n_rows_read - srv_n_rows_read_old) / time_elapsed); srv_n_rows_inserted_old = srv_stats.n_rows_inserted; srv_n_rows_updated_old = srv_stats.n_rows_updated; srv_n_rows_deleted_old = srv_stats.n_rows_deleted; srv_n_rows_read_old = srv_stats.n_rows_read; fputs("----------------------------\n" "END OF INNODB MONITOR OUTPUT\n" "============================\n", file); mutex_exit(&srv_innodb_monitor_mutex); fflush(file); return(ret); } /******************************************************************//** Function to pass InnoDB status variables to MySQL */ UNIV_INTERN void srv_export_innodb_status(void) /*==========================*/ { buf_pool_stat_t stat; buf_pools_list_size_t buf_pools_list_size; ulint LRU_len; ulint free_len; ulint flush_list_len; buf_get_total_stat(&stat); buf_get_total_list_len(&LRU_len, &free_len, &flush_list_len); buf_get_total_list_size_in_bytes(&buf_pools_list_size); mutex_enter(&srv_innodb_monitor_mutex); export_vars.innodb_data_pending_reads = os_n_pending_reads; export_vars.innodb_data_pending_writes = os_n_pending_writes; export_vars.innodb_data_pending_fsyncs = fil_n_pending_log_flushes + fil_n_pending_tablespace_flushes; export_vars.innodb_data_fsyncs = os_n_fsyncs; export_vars.innodb_data_read = srv_stats.data_read; export_vars.innodb_data_reads = os_n_file_reads; export_vars.innodb_data_writes = os_n_file_writes; export_vars.innodb_data_written = srv_stats.data_written; export_vars.innodb_buffer_pool_read_requests = stat.n_page_gets; export_vars.innodb_buffer_pool_write_requests = srv_stats.buf_pool_write_requests; export_vars.innodb_buffer_pool_wait_free = srv_stats.buf_pool_wait_free; export_vars.innodb_buffer_pool_pages_flushed = srv_stats.buf_pool_flushed; export_vars.innodb_buffer_pool_reads = srv_stats.buf_pool_reads; export_vars.innodb_buffer_pool_read_ahead_rnd = stat.n_ra_pages_read_rnd; export_vars.innodb_buffer_pool_read_ahead = stat.n_ra_pages_read; export_vars.innodb_buffer_pool_read_ahead_evicted = stat.n_ra_pages_evicted; export_vars.innodb_buffer_pool_pages_data = LRU_len; export_vars.innodb_buffer_pool_bytes_data = buf_pools_list_size.LRU_bytes + buf_pools_list_size.unzip_LRU_bytes; export_vars.innodb_buffer_pool_pages_dirty = flush_list_len; export_vars.innodb_buffer_pool_bytes_dirty = buf_pools_list_size.flush_list_bytes; export_vars.innodb_buffer_pool_pages_free = free_len; #ifdef UNIV_DEBUG export_vars.innodb_buffer_pool_pages_latched = buf_get_latched_pages_number(); #endif /* UNIV_DEBUG */ export_vars.innodb_buffer_pool_pages_total = buf_pool_get_n_pages(); export_vars.innodb_buffer_pool_pages_misc = buf_pool_get_n_pages() - LRU_len - free_len; #ifdef HAVE_ATOMIC_BUILTINS export_vars.innodb_have_atomic_builtins = 1; #else export_vars.innodb_have_atomic_builtins = 0; #endif export_vars.innodb_page_size = UNIV_PAGE_SIZE; export_vars.innodb_log_waits = srv_stats.log_waits; export_vars.innodb_os_log_written = srv_stats.os_log_written; export_vars.innodb_os_log_fsyncs = fil_n_log_flushes; export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes; export_vars.innodb_os_log_pending_writes = srv_stats.os_log_pending_writes; export_vars.innodb_log_write_requests = srv_stats.log_write_requests; export_vars.innodb_log_writes = srv_stats.log_writes; export_vars.innodb_dblwr_pages_written = srv_stats.dblwr_pages_written; export_vars.innodb_dblwr_writes = srv_stats.dblwr_writes; export_vars.innodb_pages_created = stat.n_pages_created; export_vars.innodb_pages_read = stat.n_pages_read; export_vars.innodb_pages_written = stat.n_pages_written; export_vars.innodb_row_lock_waits = srv_stats.n_lock_wait_count; export_vars.innodb_row_lock_current_waits = srv_stats.n_lock_wait_current_count; export_vars.innodb_row_lock_time = srv_stats.n_lock_wait_time / 1000; if (srv_stats.n_lock_wait_count > 0) { export_vars.innodb_row_lock_time_avg = (ulint) (srv_stats.n_lock_wait_time / 1000 / srv_stats.n_lock_wait_count); } else { export_vars.innodb_row_lock_time_avg = 0; } export_vars.innodb_row_lock_time_max = lock_sys->n_lock_max_wait_time / 1000; export_vars.innodb_rows_read = srv_stats.n_rows_read; export_vars.innodb_rows_inserted = srv_stats.n_rows_inserted; export_vars.innodb_rows_updated = srv_stats.n_rows_updated; export_vars.innodb_rows_deleted = srv_stats.n_rows_deleted; export_vars.innodb_num_open_files = fil_n_file_opened; export_vars.innodb_truncated_status_writes = srv_truncated_status_writes; export_vars.innodb_available_undo_logs = srv_available_undo_logs; #ifdef UNIV_DEBUG rw_lock_s_lock(&purge_sys->latch); trx_id_t done_trx_no = purge_sys->done.trx_no; trx_id_t up_limit_id = purge_sys->view ? purge_sys->view->up_limit_id : 0; rw_lock_s_unlock(&purge_sys->latch); if (!done_trx_no || trx_sys->rw_max_trx_id < done_trx_no - 1) { export_vars.innodb_purge_trx_id_age = 0; } else { export_vars.innodb_purge_trx_id_age = (ulint) (trx_sys->rw_max_trx_id - done_trx_no + 1); } if (!up_limit_id || trx_sys->rw_max_trx_id < up_limit_id) { export_vars.innodb_purge_view_trx_id_age = 0; } else { export_vars.innodb_purge_view_trx_id_age = (ulint) (trx_sys->rw_max_trx_id - up_limit_id); } #endif /* UNIV_DEBUG */ mutex_exit(&srv_innodb_monitor_mutex); } /*********************************************************************//** A thread which prints the info output by various InnoDB monitors. @return a dummy parameter */ extern "C" UNIV_INTERN os_thread_ret_t DECLARE_THREAD(srv_monitor_thread)( /*===============================*/ void* arg __attribute__((unused))) /*!< in: a dummy parameter required by os_thread_create */ { ib_int64_t sig_count; double time_elapsed; time_t current_time; time_t last_table_monitor_time; time_t last_tablespace_monitor_time; time_t last_monitor_time; ulint mutex_skipped; ibool last_srv_print_monitor; ut_ad(!srv_read_only_mode); #ifdef UNIV_DEBUG_THREAD_CREATION fprintf(stderr, "Lock timeout thread starts, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ #ifdef UNIV_PFS_THREAD pfs_register_thread(srv_monitor_thread_key); #endif /* UNIV_PFS_THREAD */ srv_monitor_active = TRUE; UT_NOT_USED(arg); srv_last_monitor_time = ut_time(); last_table_monitor_time = ut_time(); last_tablespace_monitor_time = ut_time(); last_monitor_time = ut_time(); mutex_skipped = 0; last_srv_print_monitor = srv_print_innodb_monitor; loop: /* Wake up every 5 seconds to see if we need to print monitor information or if signalled at shutdown. */ sig_count = os_event_reset(srv_monitor_event); os_event_wait_time_low(srv_monitor_event, 5000000, sig_count); current_time = ut_time(); time_elapsed = difftime(current_time, last_monitor_time); if (time_elapsed > 15) { last_monitor_time = ut_time(); if (srv_print_innodb_monitor) { /* Reset mutex_skipped counter everytime srv_print_innodb_monitor changes. This is to ensure we will not be blocked by lock_sys->mutex for short duration information printing, such as requested by sync_array_print_long_waits() */ if (!last_srv_print_monitor) { mutex_skipped = 0; last_srv_print_monitor = TRUE; } if (!srv_printf_innodb_monitor(stderr, MUTEX_NOWAIT(mutex_skipped), NULL, NULL)) { mutex_skipped++; } else { /* Reset the counter */ mutex_skipped = 0; } } else { last_srv_print_monitor = FALSE; } /* We don't create the temp files or associated mutexes in read-only-mode */ if (!srv_read_only_mode && srv_innodb_status) { mutex_enter(&srv_monitor_file_mutex); rewind(srv_monitor_file); if (!srv_printf_innodb_monitor(srv_monitor_file, MUTEX_NOWAIT(mutex_skipped), NULL, NULL)) { mutex_skipped++; } else { mutex_skipped = 0; } os_file_set_eof(srv_monitor_file); mutex_exit(&srv_monitor_file_mutex); } if (srv_print_innodb_tablespace_monitor && difftime(current_time, last_tablespace_monitor_time) > 60) { last_tablespace_monitor_time = ut_time(); fputs("========================" "========================\n", stderr); ut_print_timestamp(stderr); fputs(" INNODB TABLESPACE MONITOR OUTPUT\n" "========================" "========================\n", stderr); fsp_print(0); fputs("Validating tablespace\n", stderr); fsp_validate(0); fputs("Validation ok\n" "---------------------------------------\n" "END OF INNODB TABLESPACE MONITOR OUTPUT\n" "=======================================\n", stderr); } if (srv_print_innodb_table_monitor && difftime(current_time, last_table_monitor_time) > 60) { last_table_monitor_time = ut_time(); fprintf(stderr, "Warning: %s\n", DEPRECATED_MSG_INNODB_TABLE_MONITOR); fputs("===========================================\n", stderr); ut_print_timestamp(stderr); fputs(" INNODB TABLE MONITOR OUTPUT\n" "===========================================\n", stderr); dict_print(); fputs("-----------------------------------\n" "END OF INNODB TABLE MONITOR OUTPUT\n" "==================================\n", stderr); fprintf(stderr, "Warning: %s\n", DEPRECATED_MSG_INNODB_TABLE_MONITOR); } } if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) { goto exit_func; } if (srv_print_innodb_monitor || srv_print_innodb_lock_monitor || srv_print_innodb_tablespace_monitor || srv_print_innodb_table_monitor) { goto loop; } goto loop; exit_func: srv_monitor_active = FALSE; /* We count the number of threads in os_thread_exit(). A created thread should always use that to exit and not use return() to exit. */ os_thread_exit(NULL); OS_THREAD_DUMMY_RETURN; } /*********************************************************************//** A thread which prints warnings about semaphore waits which have lasted too long. These can be used to track bugs which cause hangs. @return a dummy parameter */ extern "C" UNIV_INTERN os_thread_ret_t DECLARE_THREAD(srv_error_monitor_thread)( /*=====================================*/ void* arg __attribute__((unused))) /*!< in: a dummy parameter required by os_thread_create */ { /* number of successive fatal timeouts observed */ ulint fatal_cnt = 0; lsn_t old_lsn; lsn_t new_lsn; ib_int64_t sig_count; /* longest waiting thread for a semaphore */ os_thread_id_t waiter = os_thread_get_curr_id(); os_thread_id_t old_waiter = waiter; /* the semaphore that is being waited for */ const void* sema = NULL; const void* old_sema = NULL; ut_ad(!srv_read_only_mode); old_lsn = srv_start_lsn; #ifdef UNIV_DEBUG_THREAD_CREATION fprintf(stderr, "Error monitor thread starts, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ #ifdef UNIV_PFS_THREAD pfs_register_thread(srv_error_monitor_thread_key); #endif /* UNIV_PFS_THREAD */ srv_error_monitor_active = TRUE; loop: /* Try to track a strange bug reported by Harald Fuchs and others, where the lsn seems to decrease at times */ new_lsn = log_get_lsn(); if (new_lsn < old_lsn) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Error: old log sequence number " LSN_PF " was greater\n" "InnoDB: than the new log sequence number " LSN_PF "!\n" "InnoDB: Please submit a bug report" " to http://bugs.mysql.com\n", old_lsn, new_lsn); ut_ad(0); } old_lsn = new_lsn; if (difftime(time(NULL), srv_last_monitor_time) > 60) { /* We referesh InnoDB Monitor values so that averages are printed from at most 60 last seconds */ srv_refresh_innodb_monitor_stats(); } /* Update the statistics collected for deciding LRU eviction policy. */ buf_LRU_stat_update(); /* In case mutex_exit is not a memory barrier, it is theoretically possible some threads are left waiting though the semaphore is already released. Wake up those threads: */ sync_arr_wake_threads_if_sema_free(); if (sync_array_print_long_waits(&waiter, &sema) && sema == old_sema && os_thread_eq(waiter, old_waiter)) { fatal_cnt++; if (fatal_cnt > 10) { fprintf(stderr, "InnoDB: Error: semaphore wait has lasted" " > %lu seconds\n" "InnoDB: We intentionally crash the server," " because it appears to be hung.\n", (ulong) srv_fatal_semaphore_wait_threshold); ut_error; } } else { fatal_cnt = 0; old_waiter = waiter; old_sema = sema; } /* Flush stderr so that a database user gets the output to possible MySQL error file */ fflush(stderr); sig_count = os_event_reset(srv_error_event); os_event_wait_time_low(srv_error_event, 1000000, sig_count); if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) { goto loop; } srv_error_monitor_active = FALSE; /* We count the number of threads in os_thread_exit(). A created thread should always use that to exit and not use return() to exit. */ os_thread_exit(NULL); OS_THREAD_DUMMY_RETURN; } /******************************************************************//** Increment the server activity count. */ UNIV_INTERN void srv_inc_activity_count(void) /*========================*/ { srv_sys->activity_count.inc(); } /**********************************************************************//** Check whether any background thread is active. If so return the thread type. @return SRV_NONE if all are suspended or have exited, thread type if any are still active. */ UNIV_INTERN srv_thread_type srv_get_active_thread_type(void) /*============================*/ { srv_thread_type ret = SRV_NONE; if (srv_read_only_mode) { return(SRV_NONE); } srv_sys_mutex_enter(); for (ulint i = SRV_WORKER; i <= SRV_MASTER; ++i) { if (srv_sys->n_threads_active[i] != 0) { ret = static_cast<srv_thread_type>(i); break; } } srv_sys_mutex_exit(); /* Check only on shutdown. */ if (ret == SRV_NONE && srv_shutdown_state != SRV_SHUTDOWN_NONE && trx_purge_state() != PURGE_STATE_DISABLED && trx_purge_state() != PURGE_STATE_EXIT) { ret = SRV_PURGE; } return(ret); } /**********************************************************************//** Check whether any background thread are active. If so print which thread is active. Send the threads wakeup signal. @return name of thread that is active or NULL */ UNIV_INTERN const char* srv_any_background_threads_are_active(void) /*=======================================*/ { const char* thread_active = NULL; if (srv_read_only_mode) { return(NULL); } else if (srv_error_monitor_active) { thread_active = "srv_error_monitor_thread"; } else if (lock_sys->timeout_thread_active) { thread_active = "srv_lock_timeout thread"; } else if (srv_monitor_active) { thread_active = "srv_monitor_thread"; } else if (srv_buf_dump_thread_active) { thread_active = "buf_dump_thread"; } else if (srv_dict_stats_thread_active) { thread_active = "dict_stats_thread"; } os_event_set(srv_error_event); os_event_set(srv_monitor_event); os_event_set(srv_buf_dump_event); os_event_set(lock_sys->timeout_event); os_event_set(dict_stats_event); return(thread_active); } /*******************************************************************//** Tells the InnoDB server that there has been activity in the database and wakes up the master thread if it is suspended (not sleeping). Used in the MySQL interface. Note that there is a small chance that the master thread stays suspended (we do not protect our operation with the srv_sys_t->mutex, for performance reasons). */ UNIV_INTERN void srv_active_wake_master_thread(void) /*===============================*/ { if (srv_read_only_mode) { return; } ut_ad(!srv_sys_mutex_own()); srv_inc_activity_count(); if (srv_sys->n_threads_active[SRV_MASTER] == 0) { srv_slot_t* slot; srv_sys_mutex_enter(); slot = &srv_sys->sys_threads[SRV_MASTER_SLOT]; /* Only if the master thread has been started. */ if (slot->in_use) { ut_a(srv_slot_get_type(slot) == SRV_MASTER); if (slot->suspended) { slot->suspended = FALSE; ++srv_sys->n_threads_active[SRV_MASTER]; os_event_set(slot->event); } } srv_sys_mutex_exit(); } } /*******************************************************************//** Tells the purge thread that there has been activity in the database and wakes up the purge thread if it is suspended (not sleeping). Note that there is a small chance that the purge thread stays suspended (we do not protect our check with the srv_sys_t:mutex and the purge_sys->latch, for performance reasons). */ UNIV_INTERN void srv_wake_purge_thread_if_not_active(void) /*=====================================*/ { ut_ad(!srv_sys_mutex_own()); if (purge_sys->state == PURGE_STATE_RUN && srv_sys->n_threads_active[SRV_PURGE] == 0) { srv_release_threads(SRV_PURGE, 1); } } /*******************************************************************//** Wakes up the master thread if it is suspended or being suspended. */ UNIV_INTERN void srv_wake_master_thread(void) /*========================*/ { ut_ad(!srv_sys_mutex_own()); srv_inc_activity_count(); srv_release_threads(SRV_MASTER, 1); } /*******************************************************************//** Get current server activity count. We don't hold srv_sys::mutex while reading this value as it is only used in heuristics. @return activity count. */ UNIV_INTERN ulint srv_get_activity_count(void) /*========================*/ { return(srv_sys->activity_count); } /*******************************************************************//** Check if there has been any activity. @return FALSE if no change in activity counter. */ UNIV_INTERN ibool srv_check_activity( /*===============*/ ulint old_activity_count) /*!< in: old activity count */ { return(srv_sys->activity_count != old_activity_count); } /********************************************************************//** The master thread is tasked to ensure that flush of log file happens once every second in the background. This is to ensure that not more than one second of trxs are lost in case of crash when innodb_flush_logs_at_trx_commit != 1 */ static void srv_sync_log_buffer_in_background(void) /*===================================*/ { time_t current_time = time(NULL); srv_main_thread_op_info = "flushing log"; if (difftime(current_time, srv_last_log_flush_time) >= srv_flush_log_at_timeout) { log_buffer_sync_in_background(TRUE); srv_last_log_flush_time = current_time; srv_log_writes_and_flush++; } } /********************************************************************//** Make room in the table cache by evicting an unused table. @return number of tables evicted. */ static ulint srv_master_evict_from_table_cache( /*==============================*/ ulint pct_check) /*!< in: max percent to check */ { ulint n_tables_evicted = 0; rw_lock_x_lock(&dict_operation_lock); dict_mutex_enter_for_mysql(); n_tables_evicted = dict_make_room_in_cache( innobase_get_table_cache_size(), pct_check); dict_mutex_exit_for_mysql(); rw_lock_x_unlock(&dict_operation_lock); return(n_tables_evicted); } /*********************************************************************//** This function prints progress message every 60 seconds during server shutdown, for any activities that master thread is pending on. */ static void srv_shutdown_print_master_pending( /*==============================*/ ib_time_t* last_print_time, /*!< last time the function print the message */ ulint n_tables_to_drop, /*!< number of tables to be dropped */ ulint n_bytes_merged) /*!< number of change buffer just merged */ { ib_time_t current_time; double time_elapsed; current_time = ut_time(); time_elapsed = ut_difftime(current_time, *last_print_time); if (time_elapsed > 60) { *last_print_time = ut_time(); if (n_tables_to_drop) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Waiting for " "%lu table(s) to be dropped\n", (ulong) n_tables_to_drop); } /* Check change buffer merge, we only wait for change buffer merge if it is a slow shutdown */ if (!srv_fast_shutdown && n_bytes_merged) { ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Waiting for change " "buffer merge to complete\n" " InnoDB: number of bytes of change buffer " "just merged: %lu\n", n_bytes_merged); } } } /*********************************************************************//** Perform the tasks that the master thread is supposed to do when the server is active. There are two types of tasks. The first category is of such tasks which are performed at each inovcation of this function. We assume that this function is called roughly every second when the server is active. The second category is of such tasks which are performed at some interval e.g.: purge, dict_LRU cleanup etc. */ static void srv_master_do_active_tasks(void) /*============================*/ { ib_time_t cur_time = ut_time(); ullint counter_time = ut_time_us(NULL); /* First do the tasks that we are suppose to do at each invocation of this function. */ ++srv_main_active_loops; MONITOR_INC(MONITOR_MASTER_ACTIVE_LOOPS); /* ALTER TABLE in MySQL requires on Unix that the table handler can drop tables lazily after there no longer are SELECT queries to them. */ srv_main_thread_op_info = "doing background drop tables"; row_drop_tables_for_mysql_in_background(); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND, counter_time); if (srv_shutdown_state > 0) { return; } /* make sure that there is enough reusable space in the redo log files */ srv_main_thread_op_info = "checking free log space"; log_free_check(); /* Do an ibuf merge */ srv_main_thread_op_info = "doing insert buffer merge"; counter_time = ut_time_us(NULL); ibuf_contract_in_background(0, FALSE); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time); /* Flush logs if needed */ srv_main_thread_op_info = "flushing log"; srv_sync_log_buffer_in_background(); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time); /* Now see if various tasks that are performed at defined intervals need to be performed. */ #ifdef MEM_PERIODIC_CHECK /* Check magic numbers of every allocated mem block once in SRV_MASTER_MEM_VALIDATE_INTERVAL seconds */ if (cur_time % SRV_MASTER_MEM_VALIDATE_INTERVAL == 0) { mem_validate_all_blocks(); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_MEM_VALIDATE_MICROSECOND, counter_time); } #endif if (srv_shutdown_state > 0) { return; } if (srv_shutdown_state > 0) { return; } if (cur_time % SRV_MASTER_DICT_LRU_INTERVAL == 0) { srv_main_thread_op_info = "enforcing dict cache limit"; srv_master_evict_from_table_cache(50); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time); } if (srv_shutdown_state > 0) { return; } /* Make a new checkpoint */ if (cur_time % SRV_MASTER_CHECKPOINT_INTERVAL == 0) { srv_main_thread_op_info = "making checkpoint"; log_checkpoint(TRUE, FALSE); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_CHECKPOINT_MICROSECOND, counter_time); } } /*********************************************************************//** Perform the tasks that the master thread is supposed to do whenever the server is idle. We do check for the server state during this function and if the server has entered the shutdown phase we may return from the function without completing the required tasks. Note that the server can move to active state when we are executing this function but we don't check for that as we are suppose to perform more or less same tasks when server is active. */ static void srv_master_do_idle_tasks(void) /*==========================*/ { ullint counter_time; ++srv_main_idle_loops; MONITOR_INC(MONITOR_MASTER_IDLE_LOOPS); /* ALTER TABLE in MySQL requires on Unix that the table handler can drop tables lazily after there no longer are SELECT queries to them. */ counter_time = ut_time_us(NULL); srv_main_thread_op_info = "doing background drop tables"; row_drop_tables_for_mysql_in_background(); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND, counter_time); if (srv_shutdown_state > 0) { return; } /* make sure that there is enough reusable space in the redo log files */ srv_main_thread_op_info = "checking free log space"; log_free_check(); /* Do an ibuf merge */ counter_time = ut_time_us(NULL); srv_main_thread_op_info = "doing insert buffer merge"; ibuf_contract_in_background(0, TRUE); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time); if (srv_shutdown_state > 0) { return; } srv_main_thread_op_info = "enforcing dict cache limit"; srv_master_evict_from_table_cache(100); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time); /* Flush logs if needed */ srv_sync_log_buffer_in_background(); MONITOR_INC_TIME_IN_MICRO_SECS( MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time); if (srv_shutdown_state > 0) { return; } /* Make a new checkpoint */ srv_main_thread_op_info = "making checkpoint"; log_checkpoint(TRUE, FALSE); MONITOR_INC_TIME_IN_MICRO_SECS(MONITOR_SRV_CHECKPOINT_MICROSECOND, counter_time); } /*********************************************************************//** Perform the tasks during shutdown. The tasks that we do at shutdown depend on srv_fast_shutdown: 2 => very fast shutdown => do no book keeping 1 => normal shutdown => clear drop table queue and make checkpoint 0 => slow shutdown => in addition to above do complete purge and ibuf merge @return TRUE if some work was done. FALSE otherwise */ static ibool srv_master_do_shutdown_tasks( /*=========================*/ ib_time_t* last_print_time)/*!< last time the function print the message */ { ulint n_bytes_merged = 0; ulint n_tables_to_drop = 0; ut_ad(!srv_read_only_mode); ++srv_main_shutdown_loops; ut_a(srv_shutdown_state > 0); /* In very fast shutdown none of the following is necessary */ if (srv_fast_shutdown == 2) { return(FALSE); } /* ALTER TABLE in MySQL requires on Unix that the table handler can drop tables lazily after there no longer are SELECT queries to them. */ srv_main_thread_op_info = "doing background drop tables"; n_tables_to_drop = row_drop_tables_for_mysql_in_background(); /* make sure that there is enough reusable space in the redo log files */ srv_main_thread_op_info = "checking free log space"; log_free_check(); /* In case of normal shutdown we don't do ibuf merge or purge */ if (srv_fast_shutdown == 1) { goto func_exit; } /* Do an ibuf merge */ srv_main_thread_op_info = "doing insert buffer merge"; n_bytes_merged = ibuf_contract_in_background(0, TRUE); /* Flush logs if needed */ srv_sync_log_buffer_in_background(); func_exit: /* Make a new checkpoint about once in 10 seconds */ srv_main_thread_op_info = "making checkpoint"; log_checkpoint(TRUE, FALSE); /* Print progress message every 60 seconds during shutdown */ if (srv_shutdown_state > 0 && srv_print_verbose_log) { srv_shutdown_print_master_pending( last_print_time, n_tables_to_drop, n_bytes_merged); } return(n_bytes_merged || n_tables_to_drop); } /*********************************************************************//** Puts master thread to sleep. At this point we are using polling to service various activities. Master thread sleeps for one second before checking the state of the server again */ static void srv_master_sleep(void) /*==================*/ { srv_main_thread_op_info = "sleeping"; os_thread_sleep(1000000); srv_main_thread_op_info = ""; } /*********************************************************************//** The master thread controlling the server. @return a dummy parameter */ extern "C" UNIV_INTERN os_thread_ret_t DECLARE_THREAD(srv_master_thread)( /*==============================*/ void* arg __attribute__((unused))) /*!< in: a dummy parameter required by os_thread_create */ { srv_slot_t* slot; ulint old_activity_count = srv_get_activity_count(); ib_time_t last_print_time; ut_ad(!srv_read_only_mode); #ifdef UNIV_DEBUG_THREAD_CREATION fprintf(stderr, "Master thread starts, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ #ifdef UNIV_PFS_THREAD pfs_register_thread(srv_master_thread_key); #endif /* UNIV_PFS_THREAD */ srv_main_thread_process_no = os_proc_get_number(); srv_main_thread_id = os_thread_pf(os_thread_get_curr_id()); slot = srv_reserve_slot(SRV_MASTER); ut_a(slot == srv_sys->sys_threads); last_print_time = ut_time(); loop: if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) { goto suspend_thread; } while (srv_shutdown_state == SRV_SHUTDOWN_NONE) { srv_master_sleep(); MONITOR_INC(MONITOR_MASTER_THREAD_SLEEP); if (srv_check_activity(old_activity_count)) { old_activity_count = srv_get_activity_count(); srv_master_do_active_tasks(); } else { srv_master_do_idle_tasks(); } } while (srv_master_do_shutdown_tasks(&last_print_time)) { /* Shouldn't loop here in case of very fast shutdown */ ut_ad(srv_fast_shutdown < 2); } suspend_thread: srv_main_thread_op_info = "suspending"; srv_suspend_thread(slot); /* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql() waits for database activity to die down when converting < 4.1.x databases, and relies on this string being exactly as it is. InnoDB manual also mentions this string in several places. */ srv_main_thread_op_info = "waiting for server activity"; os_event_wait(slot->event); if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) { os_thread_exit(NULL); } goto loop; OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */ } /*********************************************************************//** Check if purge should stop. @return true if it should shutdown. */ static bool srv_purge_should_exit( /*==============*/ ulint n_purged) /*!< in: pages purged in last batch */ { switch (srv_shutdown_state) { case SRV_SHUTDOWN_NONE: /* Normal operation. */ break; case SRV_SHUTDOWN_CLEANUP: case SRV_SHUTDOWN_EXIT_THREADS: /* Exit unless slow shutdown requested or all done. */ return(srv_fast_shutdown != 0 || n_purged == 0); case SRV_SHUTDOWN_LAST_PHASE: case SRV_SHUTDOWN_FLUSH_PHASE: ut_error; } return(false); } /*********************************************************************//** Fetch and execute a task from the work queue. @return true if a task was executed */ static bool srv_task_execute(void) /*==================*/ { que_thr_t* thr = NULL; ut_ad(!srv_read_only_mode); ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND); mutex_enter(&srv_sys->tasks_mutex); if (UT_LIST_GET_LEN(srv_sys->tasks) > 0) { thr = UT_LIST_GET_FIRST(srv_sys->tasks); ut_a(que_node_get_type(thr->child) == QUE_NODE_PURGE); UT_LIST_REMOVE(queue, srv_sys->tasks, thr); } mutex_exit(&srv_sys->tasks_mutex); if (thr != NULL) { que_run_threads(thr); os_atomic_inc_ulint( &purge_sys->bh_mutex, &purge_sys->n_completed, 1); } return(thr != NULL); } /*********************************************************************//** Worker thread that reads tasks from the work queue and executes them. @return a dummy parameter */ extern "C" UNIV_INTERN os_thread_ret_t DECLARE_THREAD(srv_worker_thread)( /*==============================*/ void* arg __attribute__((unused))) /*!< in: a dummy parameter required by os_thread_create */ { srv_slot_t* slot; ut_ad(!srv_read_only_mode); ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND); #ifdef UNIV_DEBUG_THREAD_CREATION ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: worker thread starting, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ slot = srv_reserve_slot(SRV_WORKER); ut_a(srv_n_purge_threads > 1); srv_sys_mutex_enter(); ut_a(srv_sys->n_threads_active[SRV_WORKER] < srv_n_purge_threads); srv_sys_mutex_exit(); /* We need to ensure that the worker threads exit after the purge coordinator thread. Otherwise the purge coordinaor can end up waiting forever in trx_purge_wait_for_workers_to_complete() */ do { srv_suspend_thread(slot); os_event_wait(slot->event); if (srv_task_execute()) { /* If there are tasks in the queue, wakeup the purge coordinator thread. */ srv_wake_purge_thread_if_not_active(); } /* Note: we are checking the state without holding the purge_sys->latch here. */ } while (purge_sys->state != PURGE_STATE_EXIT); srv_free_slot(slot); rw_lock_x_lock(&purge_sys->latch); ut_a(!purge_sys->running); ut_a(purge_sys->state == PURGE_STATE_EXIT); ut_a(srv_shutdown_state > SRV_SHUTDOWN_NONE); rw_lock_x_unlock(&purge_sys->latch); #ifdef UNIV_DEBUG_THREAD_CREATION ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Purge worker thread exiting, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ /* We count the number of threads in os_thread_exit(). A created thread should always use that to exit and not use return() to exit. */ os_thread_exit(NULL); OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */ } /*********************************************************************//** Do the actual purge operation. @return length of history list before the last purge batch. */ static ulint srv_do_purge( /*=========*/ ulint n_threads, /*!< in: number of threads to use */ ulint* n_total_purged) /*!< in/out: total pages purged */ { ulint n_pages_purged; static ulint count = 0; static ulint n_use_threads = 0; static ulint rseg_history_len = 0; ulint old_activity_count = srv_get_activity_count(); ut_a(n_threads > 0); ut_ad(!srv_read_only_mode); /* Purge until there are no more records to purge and there is no change in configuration or server state. If the user has configured more than one purge thread then we treat that as a pool of threads and only use the extra threads if purge can't keep up with updates. */ if (n_use_threads == 0) { n_use_threads = n_threads; } do { if (trx_sys->rseg_history_len > rseg_history_len || (srv_max_purge_lag > 0 && rseg_history_len > srv_max_purge_lag)) { /* History length is now longer than what it was when we took the last snapshot. Use more threads. */ if (n_use_threads < n_threads) { ++n_use_threads; } } else if (srv_check_activity(old_activity_count) && n_use_threads > 1) { /* History length same or smaller since last snapshot, use fewer threads. */ --n_use_threads; old_activity_count = srv_get_activity_count(); } /* Ensure that the purge threads are less than what was configured. */ ut_a(n_use_threads > 0); ut_a(n_use_threads <= n_threads); /* Take a snapshot of the history list before purge. */ if ((rseg_history_len = trx_sys->rseg_history_len) == 0) { break; } n_pages_purged = trx_purge( n_use_threads, srv_purge_batch_size, false); if (!(count++ % TRX_SYS_N_RSEGS)) { /* Force a truncate of the history list. */ n_pages_purged += trx_purge( 1, srv_purge_batch_size, true); } *n_total_purged += n_pages_purged; } while (!srv_purge_should_exit(n_pages_purged) && n_pages_purged > 0); return(rseg_history_len); } /*********************************************************************//** Suspend the purge coordinator thread. */ static void srv_purge_coordinator_suspend( /*==========================*/ srv_slot_t* slot, /*!< in/out: Purge coordinator thread slot */ ulint rseg_history_len) /*!< in: history list length before last purge */ { ut_ad(!srv_read_only_mode); ut_a(slot->type == SRV_PURGE); bool stop = false; /** Maximum wait time on the purge event, in micro-seconds. */ static const ulint SRV_PURGE_MAX_TIMEOUT = 10000; ib_int64_t sig_count = srv_suspend_thread(slot); do { ulint ret; rw_lock_x_lock(&purge_sys->latch); purge_sys->running = false; rw_lock_x_unlock(&purge_sys->latch); /* We don't wait right away on the the non-timed wait because we want to signal the thread that wants to suspend purge. */ if (stop) { os_event_wait_low(slot->event, sig_count); ret = 0; } else if (rseg_history_len <= trx_sys->rseg_history_len) { ret = os_event_wait_time_low( slot->event, SRV_PURGE_MAX_TIMEOUT, sig_count); } else { /* We don't want to waste time waiting, if the history list increased by the time we got here, unless purge has been stopped. */ ret = 0; } srv_sys_mutex_enter(); /* The thread can be in state !suspended after the timeout but before this check if another thread sent a wakeup signal. */ if (slot->suspended) { slot->suspended = FALSE; ++srv_sys->n_threads_active[slot->type]; ut_a(srv_sys->n_threads_active[slot->type] == 1); } srv_sys_mutex_exit(); sig_count = srv_suspend_thread(slot); rw_lock_x_lock(&purge_sys->latch); stop = (purge_sys->state == PURGE_STATE_STOP); if (!stop) { ut_a(purge_sys->n_stop == 0); purge_sys->running = true; } else { ut_a(purge_sys->n_stop > 0); /* Signal that we are suspended. */ os_event_set(purge_sys->event); } rw_lock_x_unlock(&purge_sys->latch); if (ret == OS_SYNC_TIME_EXCEEDED) { /* No new records added since wait started then simply wait for new records. The magic number 5000 is an approximation for the case where we have cached UNDO log records which prevent truncate of the UNDO segments. */ if (rseg_history_len == trx_sys->rseg_history_len && trx_sys->rseg_history_len < 5000) { stop = true; } } } while (stop); srv_sys_mutex_enter(); if (slot->suspended) { slot->suspended = FALSE; ++srv_sys->n_threads_active[slot->type]; ut_a(srv_sys->n_threads_active[slot->type] == 1); } srv_sys_mutex_exit(); } /*********************************************************************//** Purge coordinator thread that schedules the purge tasks. @return a dummy parameter */ extern "C" UNIV_INTERN os_thread_ret_t DECLARE_THREAD(srv_purge_coordinator_thread)( /*=========================================*/ void* arg __attribute__((unused))) /*!< in: a dummy parameter required by os_thread_create */ { srv_slot_t* slot; ulint n_total_purged = ULINT_UNDEFINED; ut_ad(!srv_read_only_mode); ut_a(srv_n_purge_threads >= 1); ut_a(trx_purge_state() == PURGE_STATE_INIT); ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND); rw_lock_x_lock(&purge_sys->latch); purge_sys->running = true; purge_sys->state = PURGE_STATE_RUN; rw_lock_x_unlock(&purge_sys->latch); #ifdef UNIV_PFS_THREAD pfs_register_thread(srv_purge_thread_key); #endif /* UNIV_PFS_THREAD */ #ifdef UNIV_DEBUG_THREAD_CREATION ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Purge coordinator thread created, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ slot = srv_reserve_slot(SRV_PURGE); ulint rseg_history_len = trx_sys->rseg_history_len; do { /* If there are no records to purge or the last purge didn't purge any records then wait for activity. */ if (purge_sys->state == PURGE_STATE_STOP || n_total_purged == 0) { srv_purge_coordinator_suspend(slot, rseg_history_len); } if (srv_purge_should_exit(n_total_purged)) { ut_a(!slot->suspended); break; } n_total_purged = 0; rseg_history_len = srv_do_purge( srv_n_purge_threads, &n_total_purged); } while (!srv_purge_should_exit(n_total_purged)); /* Ensure that we don't jump out of the loop unless the exit condition is satisfied. */ ut_a(srv_purge_should_exit(n_total_purged)); ulint n_pages_purged = ULINT_MAX; /* Ensure that all records are purged if it is not a fast shutdown. This covers the case where a record can be added after we exit the loop above. */ while (srv_fast_shutdown == 0 && n_pages_purged > 0) { n_pages_purged = trx_purge(1, srv_purge_batch_size, false); } /* Force a truncate of the history list. */ n_pages_purged = trx_purge(1, srv_purge_batch_size, true); ut_a(n_pages_purged == 0 || srv_fast_shutdown != 0); /* The task queue should always be empty, independent of fast shutdown state. */ ut_a(srv_get_task_queue_length() == 0); srv_free_slot(slot); /* Note that we are shutting down. */ rw_lock_x_lock(&purge_sys->latch); purge_sys->state = PURGE_STATE_EXIT; purge_sys->running = false; rw_lock_x_unlock(&purge_sys->latch); #ifdef UNIV_DEBUG_THREAD_CREATION ut_print_timestamp(stderr); fprintf(stderr, " InnoDB: Purge coordinator exiting, id %lu\n", os_thread_pf(os_thread_get_curr_id())); #endif /* UNIV_DEBUG_THREAD_CREATION */ /* Ensure that all the worker threads quit. */ if (srv_n_purge_threads > 1) { srv_release_threads(SRV_WORKER, srv_n_purge_threads - 1); } /* We count the number of threads in os_thread_exit(). A created thread should always use that to exit and not use return() to exit. */ os_thread_exit(NULL); OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */ } /**********************************************************************//** Enqueues a task to server task queue and releases a worker thread, if there is a suspended one. */ UNIV_INTERN void srv_que_task_enqueue_low( /*=====================*/ que_thr_t* thr) /*!< in: query thread */ { ut_ad(!srv_read_only_mode); mutex_enter(&srv_sys->tasks_mutex); UT_LIST_ADD_LAST(queue, srv_sys->tasks, thr); mutex_exit(&srv_sys->tasks_mutex); srv_release_threads(SRV_WORKER, 1); } /**********************************************************************//** Get count of tasks in the queue. @return number of tasks in queue */ UNIV_INTERN ulint srv_get_task_queue_length(void) /*===========================*/ { ulint n_tasks; ut_ad(!srv_read_only_mode); mutex_enter(&srv_sys->tasks_mutex); n_tasks = UT_LIST_GET_LEN(srv_sys->tasks); mutex_exit(&srv_sys->tasks_mutex); return(n_tasks); } /**********************************************************************//** Wakeup the purge threads. */ UNIV_INTERN void srv_purge_wakeup(void) /*==================*/ { ut_ad(!srv_read_only_mode); if (srv_force_recovery < SRV_FORCE_NO_BACKGROUND) { srv_release_threads(SRV_PURGE, 1); if (srv_n_purge_threads > 1) { ulint n_workers = srv_n_purge_threads - 1; srv_release_threads(SRV_WORKER, n_workers); } } }
mmplayer/MySQL
storage/innobase/srv/srv0srv.cc
C++
gpl-2.0
83,571
# -*- coding: utf-8 -*- # Inforevealer # Copyright (C) 2010 Francois Boulogne <fboulogne at april dot 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, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import io, readconf, getinfo, pastebin import os, sys, gettext,string, pexpect,getpass gettext.textdomain('inforevealer') _ = gettext.gettext __version__="0.5.1" def askYesNo(question,default='y'): """ Yes/no question throught a console """ if string.lower(default) == 'y': question = question + " [Y/n]" else: question = question + " [y/N]" ret = string.lower(raw_input(question)) if ret == 'y' or ret == "": answer=True else: answer=False return answer def RunAs(category_info,gui=False): """ Check if root is needed, if user want to be root... """ if gui: from gui import yesNoDialog run_as='user' if os.getuid() == 0: #we are root run_as='root' else: #check if root is needed root_needed=False for i in category_info: if i.root: root_needed=True break if root_needed: #ask if the user want to substitute question=_("""To generate a complete report, root access is needed. Do you want to substitute user?""") if gui: #substitute=yesNoDialog(question=question) substitute=True #It seems more confortable to remove the question else: #substitute=askYesNo(question) substitute=True #It seems more confortable to remove the question if substitute: run_as="substitute" else: run_as="user" else: run_as='user' return run_as def CompleteReportAsRoot(run_as,tmp_configfile,gui=False): """Run a new instance of inforevealer with root priviledge to complete tmp_configfile""" if gui: from gui import askPassword if run_as == "substitute": #find the substitute user command and run the script if pexpect.which('su') != None: message=_("Please, enter the root password.") root_instance = str(pexpect.which('su')) + " - -c \'"+ os.path.abspath(sys.argv[0])+" --runfile "+ tmp_configfile+"\'" elif pexpect.which('sudo') != None: #TODO checkme message=_("Please, enter your user password.") root_instance = str(pexpect.which('sudo')) + ' ' + os.path.abspath(sys.argv[0])+' --runfile '+ tmp_configfile else: sys.stderr.write(_("Error: No substitute user command available.\n")) return 1 ret="" count=0 while ret!=[' \r\n'] and count <3: #Get password count+=1 if gui: password=askPassword(question=message) else: print(message) password=getpass.getpass() if password != False: #askPassword could return False #Run the command #TODO exceptions ? child = pexpect.spawn(root_instance) ret=child.expect([".*:",pexpect.EOF]) #Could we do more ? child.sendline(password) ret = child.readlines() if ret ==[' \r\n']: return 0 message=_("Wrong password.\nThe log will be generated without root priviledge.") if gui: import gtk md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) md.set_title(_("Error")) md.run() md.destroy() else: print(message) def action(category,dumpfile,configfile,tmp_configfile,verbosity,gui=False): if gui: from gui import yesNoDialog ##################### # Write in dumpfile ##################### dumpfile_handler= open(dumpfile,'w') io.print_write_header(dumpfile_handler) dumpfile_handler.write('Category: '+ category+'\n') category_info = readconf.LoadCategoryInfo(configfile,category) #need/want to run commands as... run_as = RunAs(category_info,gui) #detect which distribution the user uses linux_distrib=getinfo.General_info(dumpfile_handler) # In the case of run_as='substitute' # a configuration file is generated # su/sudo is used to run a new instance of inforevealer in append mode # to complete the report tmp_configfile_handler= open(tmp_configfile,'w') for i in category_info: i.write(linux_distrib,verbosity,dumpfile_handler,dumpfile,run_as,tmp_configfile_handler) tmp_configfile_handler.close() #Use su or sudo to complete the report dumpfile_handler.close() #the next function will modify the report, close the dumpfile CompleteReportAsRoot(run_as,tmp_configfile,gui) # Message to close the report dumpfile_handler= open(dumpfile,'a') io.write_title("You didn\'t find what you expected?",dumpfile_handler) dumpfile_handler.write( 'Please, open a bug report on\nhttp://github.com/sciunto/inforevealer\n') dumpfile_handler.close() print( _("The output has been dumped in %s") %dumpfile)
sciunto/inforevealer
src/action.py
Python
gpl-2.0
5,161
(function ($) { $(document).ready(function() { var highestCol = Math.max($('.first-menu .pane-content').height(),$('.middle-menu .pane-content').height(),$('.last-menu .pane-content').height()); /*.first-menu .pane-content, .middle-menu .pane-content, .last-menu .pane-content $('.elements').height(highestCol);*/ alert(highestCol); }); })(jQuery);
l0c0/consulados
sites/all/themes/embajada/equals_height.js
JavaScript
gpl-2.0
372
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarDemographic.data; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.oscarehr.common.dao.RelationshipsDao; import org.oscarehr.common.model.Relationships; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; import oscar.util.ConversionUtils; /** * * @author Jay Gallagher */ public class DemographicRelationship { public DemographicRelationship() { } /** * @param facilityId can be null */ public void addDemographicRelationship(String demographic, String linkingDemographic, String relationship, boolean sdm, boolean emergency, String notes, String providerNo, Integer facilityId) { Relationships relationships = new Relationships(); relationships.setFacilityId(facilityId); relationships.setDemographicNo(ConversionUtils.fromIntString(demographic)); relationships.setRelationDemographicNo(ConversionUtils.fromIntString(linkingDemographic)); relationships.setRelation(relationship); relationships.setSubDecisionMaker(ConversionUtils.toBoolString(sdm)); relationships.setEmergencyContact(ConversionUtils.toBoolString(emergency)); relationships.setNotes(notes); relationships.setCreator(providerNo); relationships.setCreationDate(new Date()); RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); dao.persist(relationships); } public void deleteDemographicRelationship(String id) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); Relationships relationships = dao.find(ConversionUtils.fromIntString(id)); if (relationships == null) MiscUtils.getLogger().error("Unable to find demographic relationship to delete"); relationships.setDeleted(ConversionUtils.toBoolString(Boolean.TRUE)); dao.merge(relationships); } public ArrayList<Map<String, String>> getDemographicRelationships(String demographic) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); List<Relationships> relationships = dao.findByDemographicNumber(ConversionUtils.fromIntString(demographic)); if (relationships.isEmpty()) { MiscUtils.getLogger().warn("Unable to find demographic relationship for demographic " + demographic); return list; } for (Relationships r : relationships) { HashMap<String, String> h = new HashMap<String, String>(); h.put("id", r.getId().toString()); h.put("demographic_no", String.valueOf(r.getRelationDemographicNo())); h.put("relation", r.getRelation()); h.put("sub_decision_maker", r.getSubDecisionMaker()); h.put("emergency_contact", r.getEmergencyContact()); h.put("notes", r.getNotes()); list.add(h); } return list; } public ArrayList<Map<String, String>> getDemographicRelationshipsByID(String id) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); Relationships r = dao.findActive(ConversionUtils.fromIntString(id)); ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>(); if (r == null) { MiscUtils.getLogger().warn("Unable to find demographic relationship for ID " + id); return list; } Map<String, String> h = new HashMap<String, String>(); h.put("demographic_no", ConversionUtils.toIntString(r.getDemographicNo())); h.put("relation_demographic_no", ConversionUtils.toIntString(r.getRelationDemographicNo())); h.put("relation", r.getRelation()); h.put("sub_decision_maker", r.getSubDecisionMaker()); h.put("emergency_contact", r.getEmergencyContact()); h.put("notes", r.getNotes()); list.add(h); return list; } public String getSDM(String demographic) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); List<Relationships> rs = dao.findActiveSubDecisionMaker(ConversionUtils.fromIntString(demographic)); String result = null; for (Relationships r : rs) result = ConversionUtils.toIntString(r.getRelationDemographicNo()); return result; } public List<Map<String, Object>> getDemographicRelationshipsWithNamePhone(String demographic_no) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); List<Relationships> rs = dao.findActiveSubDecisionMaker(ConversionUtils.fromIntString(demographic_no)); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Relationships r : rs) { HashMap<String, Object> h = new HashMap<String, Object>(); String demo = ConversionUtils.toIntString(r.getRelationDemographicNo()); DemographicData dd = new DemographicData(); org.oscarehr.common.model.Demographic demographic = dd.getDemographic(demo); h.put("lastName", demographic.getLastName()); h.put("firstName", demographic.getFirstName()); h.put("phone", demographic.getPhone()); h.put("demographicNo", demo); h.put("relation", r.getRelation()); h.put("subDecisionMaker", ConversionUtils.fromBoolString(r.getSubDecisionMaker())); h.put("emergencyContact", ConversionUtils.fromBoolString(r.getEmergencyContact())); h.put("notes", r.getNotes()); h.put("age", demographic.getAge()); list.add(h); } return list; } public List<Map<String, Object>> getDemographicRelationshipsWithNamePhone(String demographic_no, Integer facilityId) { RelationshipsDao dao = SpringUtils.getBean(RelationshipsDao.class); List<Relationships> rs = dao.findActiveByDemographicNumberAndFacility(ConversionUtils.fromIntString(demographic_no), facilityId); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Relationships r : rs) { HashMap<String, Object> h = new HashMap<String, Object>(); String demo = ConversionUtils.toIntString(r.getRelationDemographicNo()); DemographicData dd = new DemographicData(); org.oscarehr.common.model.Demographic demographic = dd.getDemographic(demo); h.put("lastName", demographic.getLastName()); h.put("firstName", demographic.getFirstName()); h.put("phone", demographic.getPhone()); h.put("demographicNo", demo); h.put("relation", r.getRelation()); h.put("subDecisionMaker", ConversionUtils.fromBoolString(r.getSubDecisionMaker())); h.put("emergencyContact", ConversionUtils.fromBoolString(r.getEmergencyContact())); h.put("notes", r.getNotes()); h.put("age", demographic.getAge()); list.add(h); } return list; } }
hexbinary/landing
src/main/java/oscar/oscarDemographic/data/DemographicRelationship.java
Java
gpl-2.0
7,383
/* This file is part of Warzone 2100. Copyright (C) 1999-2004 Eidos Interactive Copyright (C) 2005-2011 Warzone 2100 Project Warzone 2100 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. Warzone 2100 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 Warzone 2100; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "lib/framework/frame.h" #include "lib/framework/frameresource.h" #include "lib/framework/file.h" #include "bitimage.h" #include "tex.h" static unsigned short LoadTextureFile(const char *FileName) { iV_Image *pSprite; unsigned int i; ASSERT_OR_RETURN( 0, resPresent("IMGPAGE", FileName), "Texture file \"%s\" not preloaded.", FileName); pSprite = (iV_Image*)resGetData("IMGPAGE", FileName); debug(LOG_TEXTURE, "Load texture from resource cache: %s (%d, %d)", FileName, pSprite->width, pSprite->height); /* Have we already uploaded this one? */ for (i = 0; i < _TEX_INDEX; ++i) { if (strcasecmp(FileName, _TEX_PAGE[i].name) == 0) { debug(LOG_TEXTURE, "LoadTextureFile: already uploaded"); return _TEX_PAGE[i].id; } } debug(LOG_TEXTURE, "LoadTextureFile: had to upload texture!"); return pie_AddTexPage(pSprite, FileName, 0, 0, true); } IMAGEFILE *iV_LoadImageFile(const char *fileName) { char *pFileData, *ptr, *dot; unsigned int pFileSize, numImages = 0, i, tPages = 0; IMAGEFILE *ImageFile; char texFileName[PATH_MAX]; if (!loadFile(fileName, &pFileData, &pFileSize)) { debug(LOG_ERROR, "iV_LoadImageFile: failed to open %s", fileName); return NULL; } ptr = pFileData; // count lines, which is identical to number of images while (ptr < pFileData + pFileSize && *ptr != '\0') { numImages += (*ptr == '\n') ? 1 : 0; ptr++; } ImageFile = (IMAGEFILE *)malloc(sizeof(IMAGEFILE) + sizeof(IMAGEDEF) * numImages); ImageFile->ImageDefs = (IMAGEDEF*)(ImageFile + 1); // we allocated extra space for it ptr = pFileData; numImages = 0; while (ptr < pFileData + pFileSize) { int temp, retval; IMAGEDEF *ImageDef = &ImageFile->ImageDefs[numImages]; retval = sscanf(ptr, "%u,%u,%u,%u,%u,%d,%d%n", &ImageDef->TPageID, &ImageDef->Tu, &ImageDef->Tv, &ImageDef->Width, &ImageDef->Height, &ImageDef->XOffset, &ImageDef->YOffset, &temp); if (retval != 7) { break; } ptr += temp; numImages++; // Find number of texture pages to load (no gaps allowed in number series, eg use intfac0, intfac1, etc.!) if (ImageDef->TPageID > tPages) { tPages = ImageDef->TPageID; } while (ptr < pFileData + pFileSize && *ptr++ != '\n') {} // skip rest of line } dot = (char *)strrchr(fileName, '/'); // go to last path character dot++; // skip it strcpy(texFileName, dot); // make a copy dot = strchr(texFileName, '.'); // find extension *dot = '\0'; // then discard it // Load the texture pages. for (i = 0; i <= tPages; i++) { char path[PATH_MAX]; snprintf(path, PATH_MAX, "%s%u.png", texFileName, i); ImageFile->TPageIDs[i] = LoadTextureFile(path); } ImageFile->NumImages = numImages; free(pFileData); return ImageFile; } void iV_FreeImageFile(IMAGEFILE *ImageFile) { free(ImageFile); }
Zarel/warzone2100
lib/ivis_opengl/bitimage.cpp
C++
gpl-2.0
3,617
var events = require("events"), util = require("util"), colors = require("colors"), Firmata = require("firmata").Board, _ = require("lodash"), __ = require("../lib/fn.js"), Repl = require("../lib/repl.js"), serialport = require("serialport"), Pins = require("../lib/board.pins.js"), Options = require("../lib/board.options.js"), // temporal = require("temporal"), board, boards, rport, Serial; boards = []; rport = /usb|acm|^com/i; /** * Process Codes * SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling process * SIGINT 2 Term Interrupt from keyboard * SIGQUIT 3 Core Quit from keyboard * SIGILL 4 Core Illegal Instruction * SIGABRT 6 Core Abort signal from abort(3) * SIGFPE 8 Core Floating point exception * SIGKILL 9 Term Kill signal * SIGSEGV 11 Core Invalid memory reference * SIGPIPE 13 Term Broken pipe: write to pipe with no readers * SIGALRM 14 Term Timer signal from alarm(2) * SIGTERM 15 Term Termination signal * * * * http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Batch/exitcode.html * */ Serial = { used: [], detect: function( callback ) { this.info( "Board", "Connecting..." ); // If a |port| was explicitly provided to the Board constructor, // invoke the detection callback and return immediately if ( this.port ) { callback.call( this, this.port ); return; } serialport.list(function(err, result) { var ports, length; ports = result.filter(function(val) { var available = true; // Match only ports that Arduino cares about // ttyUSB#, cu.usbmodem#, COM# if ( !rport.test(val.comName) ) { available = false; } // Don't allow already used/encountered usb device paths if ( Serial.used.indexOf(val.comName) > -1 ) { available = false; } return available; }).map(function(val) { return val.comName; }); length = ports.length; // If no ports are detected when scanning /dev/, then there is // nothing left to do and we can safely exit the program if ( !length ) { // Alert user that no devices were detected this.error( "Board", "No USB devices detected" ); // Exit the program by sending SIGABRT process.exit(3); // Return (not that it matters, but this is a good way // to indicate to readers of the code that nothing else // will happen in this function) return; } // Continue with connection routine attempts this.info( "Serial", "Found possible serial port" + ( length > 1 ? "s" : "" ), ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call( this, ports[0] ); }.bind(this)); }, connect: function( usb, callback ) { var err, found, connected, eventType; // Add the usb device path to the list of device paths that // are currently in use - this is used by the filter function // above to remove any device paths that we've already encountered // or used to avoid blindly attempting to reconnect on them. Serial.used.push( usb ); try { found = new Firmata( usb, function( error ) { if ( error !== undefined ) { err = error; } // Execute "ready" callback callback.call( this, err, "ready", found ); }.bind(this)); // Made this far, safely connected connected = true; } catch ( error ) { err = error; } if ( err ) { err = err.message || err; } // Determine the type of event that will be passed on to // the board emitter in the callback passed to Serial.detect(...) eventType = connected ? "connected" : "error"; // Execute "connected" callback callback.call( this, err, eventType, found ); } }; /** * Board * @constructor * * @param {Object} opts */ function Board( opts ) { if ( !(this instanceof Board) ) { return new Board( opts ); } // Ensure opts is an object opts = opts || {}; var inject, timer; inject = {}; // Initialize this Board instance with // param specified properties. _.assign( this, opts ); // Easily track state of hardware this.ready = false; // Initialize instance property to reference firmata board this.firmata = null; // Registry of devices by pin address this.register = []; // Identify for connected hardware cache if ( !this.id ) { this.id = __.uid(); } // If no debug flag, default to false // TODO: Remove override this.debug = true; if ( !("debug" in this) ) { this.debug = false; } if ( !("repl" in this) ) { this.repl = true; } // Specially processed pin capabilities object // assigned when board is initialized and ready this.pins = null; // Human readable name (if one can be detected) this.type = ''; // Create a Repl instance and store as // instance property of this firmata/board. // This will reduce the amount of boilerplate // code required to _always_ have a Repl // session available. // // If a sesssion exists, use it // (instead of creating a new session) // if ( this.repl ) { if ( Repl.ref ) { inject[ this.id ] = this; Repl.ref.on( "ready", function() { Repl.ref.inject( inject ); }); this.repl = Repl.ref; } else { inject[ this.id ] = inject.board = this; this.repl = new Repl( inject ); } } // Used for testing only if ( this.mock ) { this.ready = true; this.firmata = new Firmata( this.mock, function() {} ); // NEED A DUMMY OF THE PINS OBJECT // // this.pins = Board.Pins( this ); // Execute "connected" and "ready" callbacks this.emit( "connected", null ); this.emit( "ready", null ); } else if ( opts.firmata ) { // If you already have a connected firmata instance this.firmata = opts.firmata; this.ready = true; this.pins = Board.Pins( this ); this.emit( "connected", null ); this.emit( "ready", null ); } else { Serial.detect.call( this, function( port ) { Serial.connect.call( this, port, function( err, type, firmata ) { if ( err ) { this.error( "Board", err ); } else { // Assign found firmata to instance this.firmata = firmata; this.info( "Board " + ( type === "connected" ? "->" : "<-" ) + " Serialport", type, port.grey ); } if ( type === "connected" ) { // 10 Second timeout... // // If "ready" hasn't fired and cleared the timer within // 10 seconds of the connected event, then it's likely // that Firmata simply isn't loaded onto the board. timer = setTimeout(function() { this.error( "StandardFirmata", "A timeout occurred while connecting to the Board. \n" + "Please check that you've properly loaded StandardFirmata onto the Arduino" ); process.emit("SIGINT"); }.bind(this), 1e5); process.on( "SIGINT", function() { this.warn( "Board", "Closing: firmata, serialport" ); // On ^c, make sure we close the process after the // firmata and serialport are closed. Approx 100ms // TODO: this sucks, need better solution setTimeout(function() { process.exit(); }, 100); }.bind(this)); } if ( type === "ready" ) { clearTimeout( timer ); // Update instance `ready` flag this.ready = true; this.port = port; this.pins = Board.Pins( this ); // In multi-board mode, block the REPL from // activation. This will be started directly // by the Board.Array constructor. if ( !Repl.isBlocked ) { process.stdin.emit( "data", 1 ); } } // emit connect|ready event this.emit( type, err ); }); }); } // Cache instance to allow access from module constructors boards.push( this ); } // Inherit event api util.inherits( Board, events.EventEmitter ); /** * pinMode, analogWrite, analogRead, digitalWrite, digitalRead * * Pass through methods */ [ "pinMode", "analogWrite", "analogRead", "digitalWrite", "digitalRead" ].forEach(function( method ) { Board.prototype[ method ] = function( pin, arg ) { this.firmata[ method ]( pin, arg ); return this; }; }); Board.prototype.serialize = function( filter ) { var blacklist, special; blacklist = this.serialize.blacklist; special = this.serialize.special; return JSON.stringify( this.register.map(function( device ) { return Object.getOwnPropertyNames( device ).reduce(function( data, prop ) { var value = device[ prop ]; if ( blacklist.indexOf(prop) === -1 && typeof value !== "function" ) { data[ prop ] = special[ prop ] ? special[ prop ]( value ) : value; if ( filter ) { data[ prop ] = filter( prop, data[ prop ], device ); } } return data; }, {}); }, this) ); }; Board.prototype.serialize.blacklist = [ "board", "firmata", "_events" ]; Board.prototype.serialize.special = { mode: function(value) { return [ "INPUT", "OUTPUT", "ANALOG", "PWM", "SERVO" ][ value ] || "unknown"; } }; /** * shiftOut * */ Board.prototype.shiftOut = function( dataPin, clockPin, isBigEndian, value ) { var mask, write; write = function( value, mask ) { this.digitalWrite( clockPin, this.firmata.LOW ); this.digitalWrite( dataPin, this.firmata[ value & mask ? "HIGH" : "LOW" ] ); this.digitalWrite( clockPin, this.firmata.HIGH ); }.bind(this); if ( arguments.length === 3 ) { value = arguments[2]; isBigEndian = true; } if ( isBigEndian ) { for ( mask = 128; mask > 0; mask = mask >> 1 ) { write( value, mask ); } } else { for ( mask = 0; mask < 128; mask = mask << 1 ) { write( value, mask ); } } }; Board.prototype.log = function( /* type, module, message [, long description] */ ) { var args = [].slice.call( arguments ), type = args.shift(), module = args.shift(), message = args.shift(), color = Board.prototype.log.types[ type ]; if ( this.debug ) { console.log([ // Timestamp String(+new Date()).grey, // Module, color matches type of log module.magenta, // Message message[ color ], // Miscellaneous args args.join(", ") ].join(" ")); } }; Board.prototype.log.types = { error: "red", fail: "orange", warn: "yellow", info: "cyan" }; // Make shortcuts to all logging methods Object.keys( Board.prototype.log.types ).forEach(function( type ) { Board.prototype[ type ] = function() { var args = [].slice.call( arguments ); args.unshift( type ); this.log.apply( this, args ); }; }); /** * delay, loop, queue * * Pass through methods to temporal */ /* [ "delay", "loop", "queue" ].forEach(function( method ) { Board.prototype[ method ] = function( time, callback ) { temporal[ method ]( time, callback ); return this; }; }); // Alias wait to delay to match existing Johnny-five API Board.prototype.wait = Board.prototype.delay; */ // -----THIS IS A TEMPORARY FIX UNTIL THE ISSUES WITH TEMPORAL ARE RESOLVED----- // Aliasing. // (temporary, while ironing out API details) // The idea is to match existing hardware programming apis // or simply find the words that are most intuitive. // Eventually, there should be a queuing process // for all new callbacks added // // TODO: Repalce with temporal or compulsive API Board.prototype.wait = function( time, callback ) { setTimeout( callback.bind(this), time ); return this; }; Board.prototype.loop = function( time, callback ) { setInterval( callback.bind(this), time ); return this; }; // ---------- // Static API // ---------- // Board.map( val, fromLow, fromHigh, toLow, toHigh ) // // Re-maps a number from one range to another. // Based on arduino map() Board.map = __.map; // Board.constrain( val, lower, upper ) // // Constrains a number to be within a range. // Based on arduino constrain() Board.constrain = __.constrain; // Board.range( upper ) // Board.range( lower, upper ) // Board.range( lower, upper, tick ) // // Returns a new array range // Board.range = __.range; // Board.range.prefixed( prefix, upper ) // Board.range.prefixed( prefix, lower, upper ) // Board.range.prefixed( prefix, lower, upper, tick ) // // Returns a new array range, each value prefixed // Board.range.prefixed = __.range.prefixed; // Board.uid() // // Returns a reasonably unique id string // Board.uid = __.uid; // Board.mount() // Board.mount( index ) // Board.mount( object ) // // Return hardware instance, based on type of param: // @param {arg} // object, user specified // number/index, specified in cache // none, defaults to first in cache // // Notes: // Used to reduce the amount of boilerplate // code required in any given module or program, by // giving the developer the option of omitting an // explicit Board reference in a module // constructor's options Board.mount = function( arg ) { var index = typeof arg === "number" && arg, hardware; // board was explicitly provided if ( arg && arg.board ) { return arg.board; } // index specified, attempt to return // hardware instance. Return null if not // found or not available if ( index ) { hardware = boards[ index ]; return hardware && hardware || null; } // If no arg specified and hardware instances // exist in the cache if ( boards.length ) { return boards[ 0 ]; } // No mountable hardware return null; }; /** * Board.Device * * Initialize a new device instance * * Board.Device is a |this| senstive constructor, * and must be called as: * * Board.Device.call( this, opts ); * * * * TODO: Migrate all constructors to use this * to avoid boilerplate */ Board.Device = function( opts ) { // Board specific properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; // Device/Module instance properties this.id = opts.id || null; // Pin or Pins address(es) opts = Board.Pins.normalize( opts, this.board ); if ( typeof opts.pins !== "undefined" ) { this.pins = opts.pins || []; } if ( typeof opts.pin !== "undefined" ) { this.pin = opts.pin || 0; } this.board.register.push( this ); }; /** * Pin Capability Signature Mapping */ Board.Pins = Pins; Board.Options = Options; // Define a user-safe, unwritable hardware cache access Object.defineProperty( Board, "cache", { get: function() { return boards; } }); /** * Board event constructor. * opts: * type - event type. eg: "read", "change", "up" etc. * target - the instance for which the event fired. * 0..* other properties */ Board.Event = function( opts ) { if ( !(this instanceof Board.Event) ) { return new Board.Event( opts ); } opts = opts || {}; // default event is read this.type = opts.type || "read"; // actual target instance this.target = opts.target || null; // Initialize this Board instance with // param specified properties. _.assign( this, opts ); }; /** * Boards or Board.Array; Used when the program must connect to * more then one board. * * @memberof Board * * @param {Array} ports List of port objects { id: ..., port: ... } * List of id strings (initialized in order) * * @return {Boards} board object references */ Board.Array = function( ports ) { if ( !(this instanceof Board.Array) ) { return new Board.Array( ports ); } if ( !Array.isArray(ports) ) { throw new Error("Expected ports to be an array"); } Array.call( this, ports.length ); var initialized, count; initialized = {}; count = ports.length; // Block initialization of the program's // REPL until all boards are ready. Repl.isBlocked = true; ports.forEach(function( port, k ) { var opts; if ( typeof port === "string" ) { opts = { id: port }; } else { opts = port; } this[ k ] = initialized[ opts.id ] = new Board( opts ); this[ k ].on("ready", function() { this[ k ].info( "Board ID: ", opts.id.green ); this.length++; if ( !--count ) { Repl.isBlocked = false; process.stdin.emit( "data", 1 ); this.emit( "ready", initialized ); } }.bind(this)); }, this); }; util.inherits( Board.Array, events.EventEmitter ); Board.Array.prototype.each = Array.prototype.forEach; module.exports = Board; // References: // http://arduino.cc/en/Main/arduinoBoardUno
pmark/Proboscis
node_modules/johnny-five/lib/board.js
JavaScript
gpl-2.0
17,276
package components.diagram.edit.parts; import org.eclipse.draw2d.Connection; import org.eclipse.gef.EditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ITreeBranchEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; import org.eclipse.gmf.runtime.draw2d.ui.figures.PolylineConnectionEx; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.notation.View; import components.diagram.edit.policies.DataReleationshipItemSemanticEditPolicy; /** * @generated */ public class DataReleationshipEditPart extends ConnectionNodeEditPart implements ITreeBranchEditPart { /** * @generated */ public static final int VISUAL_ID = 4002; /** * @generated */ public DataReleationshipEditPart(View view) { super(view); } /** * @generated */ protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new DataReleationshipItemSemanticEditPolicy()); } /** * @generated */ protected boolean addFixedChild(EditPart childEditPart) { if (childEditPart instanceof DataReleationshipProtocolEditPart) { ((DataReleationshipProtocolEditPart) childEditPart) .setLabel(getPrimaryShape() .getFigureDataReleationshipProtocolFigure()); return true; } return false; } /** * @generated */ protected void addChildVisual(EditPart childEditPart, int index) { if (addFixedChild(childEditPart)) { return; } super.addChildVisual(childEditPart, index); } /** * @generated */ protected boolean removeFixedChild(EditPart childEditPart) { if (childEditPart instanceof DataReleationshipProtocolEditPart) { return true; } return false; } /** * @generated */ protected void removeChildVisual(EditPart childEditPart) { if (removeFixedChild(childEditPart)) { return; } super.removeChildVisual(childEditPart); } /** * Creates figure for this edit part. * * Body of this method does not depend on settings in generation model * so you may safely remove <i>generated</i> tag and modify it. * * @generated */ protected Connection createConnectionFigure() { return new DataReleationshipFigure(); } /** * @generated */ public DataReleationshipFigure getPrimaryShape() { return (DataReleationshipFigure) getFigure(); } /** * @generated */ public class DataReleationshipFigure extends PolylineConnectionEx { /** * @generated */ private WrappingLabel fFigureDataReleationshipProtocolFigure; /** * @generated */ public DataReleationshipFigure() { createContents(); } /** * @generated */ private void createContents() { fFigureDataReleationshipProtocolFigure = new WrappingLabel(); fFigureDataReleationshipProtocolFigure.setText("<...>"); this.add(fFigureDataReleationshipProtocolFigure); } /** * @generated */ public WrappingLabel getFigureDataReleationshipProtocolFigure() { return fFigureDataReleationshipProtocolFigure; } } }
peterbartha/j2eecm
edu.bme.vik.iit.j2eecm.diagram/src/components/diagram/edit/parts/DataReleationshipEditPart.java
Java
gpl-2.0
3,130
class AddMeasuredAtToStreamData < ActiveRecord::Migration def change add_column :stream_data, :measured_at, :datetime end end
nkipreos/solar-monitor
db/migrate/20150102200323_add_measured_at_to_stream_data.rb
Ruby
gpl-2.0
134
using Server.Properties; using Server.WindowsUtils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Server.UserSettings { class LdpUserSettings { private string userPassword; public LdpUserSettings() { InitSettings(); } private void InitSettings() { userPassword = Settings.Default.Password; } public string GetPassword { get { return userPassword; } } public void SetPassword(string password) { Settings.Default.Password = password; Settings.Default.Save(); string success = "User settings: password updated successfully."; LdpLog.Info(success); } } }
tdmitriy/LightDesktopPresenter
Server/Server/UserSettings/LdpUserSettings.cs
C#
gpl-2.0
875
/* * Copyright (C) Azureus Software, Inc, 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 ( see the LICENSE file ). * * 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 */ package com.biglybt.ui.swt.views.tableitems.peers; import com.biglybt.core.peer.impl.PEPeerTransport; import com.biglybt.pif.ui.tables.TableCell; import com.biglybt.pif.ui.tables.TableCellRefreshListener; import com.biglybt.pif.ui.tables.TableColumnInfo; import com.biglybt.ui.swt.views.table.CoreTableColumnSWT; import com.biglybt.core.peermanager.peerdb.PeerItem; public class ColumnPeerNetwork extends CoreTableColumnSWT implements TableCellRefreshListener { /** Default Constructor */ public ColumnPeerNetwork(String table_id) { super("network", POSITION_INVISIBLE, 65, table_id); setRefreshInterval(INTERVAL_INVALID_ONLY); } @Override public void fillTableColumnInfo(TableColumnInfo info) { info.addCategories(new String[] { CAT_PROTOCOL, CAT_CONNECTION, }); } @Override public void refresh(TableCell cell) { Object ds = cell.getDataSource(); String text = ""; Comparable val = null; if (ds instanceof PEPeerTransport) { PEPeerTransport peer = (PEPeerTransport) ds; PeerItem identity = peer.getPeerItemIdentity(); if (identity != null) { val = text = identity.getNetwork(); } } if( !cell.setSortValue( val ) && cell.isValid() ) { return; } cell.setText( text ); } }
BiglySoftware/BiglyBT
uis/src/com/biglybt/ui/swt/views/tableitems/peers/ColumnPeerNetwork.java
Java
gpl-2.0
2,088
<?php # written by: Nicolas MARCHE <nico.marche@free.fr> # project: eBrigade # homepage: http://sourceforge.net/projects/ebrigade/ # version: 2.6 # Copyright (C) 2004, 2011 Nicolas MARCHE # 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 header('Content-Type: text/html; charset=ISO-8859-1'); header("Cache-Control: no-cache"); include_once ("config.php"); check_all(0); $evenement = (isset($_POST['evenement'])?intval($_POST['evenement']):(isset($_GET['evenement'])?intval($_GET['evenement']):"")); writehead(); $msgerr=""; if(isset($_POST['action'])){ $dimNbISActeurs = (isset($_POST['dimNbISActeurs'])?mysql_real_escape_string($_POST['dimNbISActeurs']):0); $dimNbISActeursCom = (isset($_POST['dimNbISActeursCom'])?mysql_real_escape_string($_POST['dimNbISActeursCom']):""); $dimP=(isset($_POST['P'])?mysql_real_escape_string($_POST['P']):0); $dimP1=(isset($_POST['P1'])?mysql_real_escape_string($_POST['P1']):0); $dimP2=(isset($_POST['P2'])?mysql_real_escape_string($_POST['P2']):0.25); $dimE1=(isset($_POST['E1'])?mysql_real_escape_string($_POST['E1']):0.25); $dimE2=(isset($_POST['E2'])?mysql_real_escape_string($_POST['E2']):0.25); $dimI=(isset($_POST['i'])?mysql_real_escape_string($_POST['i']):0); $dimRIS=(isset($_POST['RIS'])?mysql_real_escape_string($_POST['RIS']):0); $dimRISCalc=(isset($_POST['RISCalc'])?mysql_real_escape_string($_POST['RISCalc']):0); $dimNbIS=(isset($_POST['NbIS'])?mysql_real_escape_string($_POST['NbIS']):0); $dimTypeDPS=(isset($_POST['type'])?mysql_real_escape_string($_POST['type']):0); $dimTypeDPSCom=(isset($_POST['commentaire'])?mysql_real_escape_string($_POST['commentaire']):""); $dimSecteurs=(isset($_POST['secteurs'])?mysql_real_escape_string($_POST['secteurs']):0); $dimPostes=(isset($_POST['postes'])?mysql_real_escape_string($_POST['postes']):0); $dimEquipes=(isset($_POST['equipes'])?mysql_real_escape_string($_POST['equipes']):0); $dimBinomes=(isset($_POST['binomes'])?mysql_real_escape_string($_POST['binomes']):0); EvenementSave($_POST); } $row=EvenementDPS($evenement,'data'); $dimNbISActeurs=$row['dimNbISActeurs']; $dimNbISActeursCom=stripslashes($row['dimNbISActeursCom']); $dimI=$row['i']; $dimP=$row['P']; $dimP1=$row['P1']; $dimP2=$row['P2']; $dimE1=$row['E1']; $dimE2=$row['E2']; $dimRIS=$row['RIS']; $dimRISCalc=$row['RISCalc']; $dimNbIS=$row['NbIS']; $dimTypeDPS=stripslashes($row['type']); $dimTypeDPSCom=stripslashes($row['commentaire']); $dimSecteurs=$row['secteurs']; $dimPostes=$row['postes']; $dimEquipes=$row['equipes']; $dimBinomes=$row['binomes']; $effectif=$row['effectif']; $action=(($dimRISCalc>0)?"Modifier":"Enregistrer");// si Modifier >> affiche lien vers impression ?> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery_forms.js"></script> <script type="text/javascript"> $(document).ready(function(){ calcRIS(); var options = { target: '#resultat', url: 'dps_save.php', success: function() { //alert("Dimensionnement enregistré."); } }; $('form#frmDPS').ajaxForm(options); $('input#btGrille').submit(options); $('input').keyup(function(){ calcRIS(); }); $('input[@type=radio]').change(function(){ calcRIS(); }); }); function calcRIS(){ $.post('dps_calc.php', { evenement:$('input[@name=evenement]').fieldValue()[0], P1:$('input[@name=P1]').fieldValue()[0], P2:$('input[@name=P2]').fieldValue()[0], E1:$('input[@name=E1]').fieldValue()[0], E2:$('input[@name=E2]').fieldValue()[0], dimNbISActeurs:$('input[@name=dimNbISActeurs]').fieldValue()[0], dimNbISActeursCom:$('textarea[@name=dimNbISActeursCom]').fieldValue()[0], actionPrint:'<?php echo $action;?>' }, function(data){ $("#resultat").html(data); } ); } function fermerfenetre(){ var obj_window = window.open('', '_self'); obj_window.opener = window; obj_window.focus(); opener=self; self.close(); } </script> <style type='text/css'> div#formulaire{ width:72%; margin-right:28%; } div#resultat{ float:right; width:27%; } div#frmDPSretour{ float:right; width:27%; } #frmDPS table td{ background-color:#ffffff; } #resultat input,#resultat textarea{ background-color:transparent; border:none; FONT-SIZE: 10pt; FONT-FAMILY: Arial; } input:focus, textarea:focus, select:focus{ background-color:#ffffcc; } .TabHeader2{ background-color:orange; } </style> </head> <body> <?php echo "<p style=\"color:red;\">$msgerr</p>"; echo EbDeb("RNMSC-DPS - Dimensionnement"); ?> <p style="text-align:justify; padding:0 1em 0 1em;">Le dimensionnement du dispositif de secours pour les <b>acteurs</b> est de la seule responsabilité du demandeur et/ou de l'autorité de police compétente. <br />Le dimensionnement du dispositif de secours pour le <b>public</b> est régit par le Référentiel National des Missions de Sécurité Civile - Dispositifs Prévisionnels de Secours</p> <p style="text-align:justify; padding:0 1em 0 1em;">Ce calcul de dimensionnement minimal est mis a disposition pour "information". <br />Seule une étude personnalisée de votre manifestation avec une association de sécurité civile permettra de dimensionner <b>votre</b> dispositif prévisionnel de secours</p> <p style="text-align:justify; padding:0 1em 0 1em;">Le nombre d'intervenant correspond au nombre de Secouriste, Equipier Secouriste, Chef d'Equipe, Chef de Poste. <br />Sont exclus: l'encadrement et la logistique.</p> <!-- <h2><blink>A tester...</blink></h2> <p>merci d'envoyer vos commentaire à  <a href="mailto:adpc90@free.fr?subject=Pour Jean-Pierre : RNMSC-DPS">Jean-Pierre</a></p> --> <form action="dps_save.php?tab=2" method="POST" name="dps" id="frmDPS"> <!-- deb resultat --> <div id="resultat"></div> <!-- fin resultat --> <div id="formulaire"> <table border="1"> <tr><th class="TabHeader2" colspan="2">Demande pour les acteurs : </th></tr> <tr> <td style="background-color:#ffffcc;"> <p>Descriptif de la demande pour les acteurs</p> <textarea name="dimNbISActeursCom" style="width:90%;FONT-SIZE: 10pt; FONT-FAMILY: Arial;"><?php echo $dimNbISActeursCom; ?></textarea> <br />Equivalence en nombre d'intervenants secouristes pour les acteurs :<input type="text" name="dimNbISActeurs" id="dimNbISActeurs" value="<?php echo $dimNbISActeurs; ?>" style="background-color:Yellow;"> <br >(Minimum = 4, si un dispositif est demandé pour les acteurs) </td> <td style="background-color:#ffffcc;">&nbsp;</td> </tr> <tr><th colspan="2">&nbsp;</th></tr> <tr><th colspan="2"><b>Dimensionnement pour le public : </b></th></tr> <tr> <td colspan="2"> <p><b>Nota :</b><br />Dans le cas où les acteurs présenteraient un risque différent du public, et en absence d'un dispositif spécifique pour les acteurs, le PAPS n'est pas un dispositif de secours suffisant.</p> </td> </tr> <tr><th><b>Effectif déclaré du public</b></th> <th class="TabHeader">Indicateur P1</th></tr> <tr> <td><input type="text" name="P1" value="<?php echo ($dimP1); ?>" style="background-color:Yellow;"></td> <td><input type="text" name="P" value="" readonly class="result"></td> </tr> <tr> <tr><th class="TabHeader">Activité du rassemblement</th> <th class="TabHeader">Indicateur P2</th></tr> <tr> <td><input type="radio" name="P2" value="0.25" <?php echo ($dimP2==0.25?"checked=\"yes\"":""); ?>>- Public assis : spectacle, cérémonie cultuelle, réunion publique, restauration, rendez-vous sportif...</td> <td>0,25</td> </tr> <tr> <td><input type="radio" name="P2" value="0.30" <?php echo ($dimP2==0.30?"checked=\"yes\"":""); ?>>- Public debout : cérémonie cultuelle, réunion publique, restauration, exposition, foire, salon, comice agricole...</td> <td>0,30</td> </tr> <tr> <td><input type="radio" name="P2" value="0.35" <?php echo ($dimP2==0.35?"checked=\"yes\"":""); ?>>- Public debout : spectacle avec public statique, fête foraine, rendez-vous sportif avec protection du public par rapport à  l'événement...</td> <td>0,35</td> <tr> <td><input type="radio" name="P2" value="0.40" <?php echo ($dimP2==0.40?"checked=\"yes\"":""); ?>>- Public debout : spectacle avec public dynamique, danse, feria, fête votive, carnaval, spectacle de rue, grande parade, rendez-vous sportif sans protection du public par rapport à  l'événement ... <br />- Evénement se déroulant sur plusieurs jours avec présence permanente du public : hébergement sur site ou à  proximité. </td> <td>0,40</td> </tr> <tr> <th class="TabHeader">Caractéristiques de l'environnement ou<br/>de l'accessibilité du site</th> <th class="TabHeader">Indicateur E1</th> </tr> <tr> <td><input type="radio" name="E1" value="0.25" <?php echo ($dimE1==0.25?"checked=\"yes\"":""); ?>>- Structures permanentes : Bâtiment, salle « en dur »,... <br />- Voies publiques, rues,...avec accès dégagés <br />- Conditions d'accès aisés </td> <td>0.25</td> </tr> <tr> <td><input type="radio" name="E1" value="0.30" <?php echo ($dimE1==0.30?"checked=\"yes\"":""); ?>>- Structures non permanentes : gradins, tribunes, chapiteaux,... <br />- Espaces naturels : surface = 2 hectares <br />- Brancardage : 150 m < longueur = 300 m <br />- Terrain en pente sur plus de 100 mètres 0,30</td> <td>0.30</td> </tr> <tr> <td><input type="radio" name="E1" value="0.35" <?php echo ($dimE1==0.35?"checked=\"yes\"":""); ?>>- Espaces naturels : 2 ha < surface = 5 ha <br />- Brancardage : 300 m < longueur = 600 m <br />- Terrain en pente sur plus de 150 mètres <br />- Autres conditions d'accès difficiles</td> <td>0.35</td> </tr> <tr> <td><input type="radio" name="E1" value="0.40" <?php echo ($dimE1==0.40?"checked=\"yes\"":""); ?>>- Espaces naturels : surface > 5 hectares <br />- Brancardage : longueur > 600 mètres <br />- Terrain en pente sur plus de 300 mètres <br />- Autres conditions d'accès difficiles : Talus, escaliers, voies d'accès non carrossables,... <br />- Progression des secours rendue difficile par la présence du public </td> <td>0.40</td> </tr> <tr> <th class="TabHeader">Délai d'intervention des secours publics </th> <th class="TabHeader">Indicateur E2</th> </tr> <tr> <td><input type="radio" name="E2" value="0.25" <?php echo ($dimE2==0.25?"checked=\"yes\"":""); ?>> <= 10 minutes </td> <td>0.25</td> </tr> <tr> <td><input type="radio" name="E2" value="0.30" <?php echo ($dimE2==0.30?"checked=\"yes\"":""); ?>> > 10 minutes et <= <br />20 minutes </td> <td>0.30</td> </tr> <tr> <td><input type="radio" name="E2" value="0.35" <?php echo ($dimE2==0.35?"checked=\"yes\"":""); ?>> > 20 minutes et <br /><= 30 minutes</td> <td>0.35</td> </tr> <tr> <td><input type="radio" name="E2" value="0.40" <?php echo ($dimE2==0.40?"checked=\"yes\"":""); ?>> > 30 minutes</td> <td>0.40</td> </tr> </table> <input type="hidden" name="evenement" value="<?php echo $evenement; ?>"> </form> </div> <h2>Rappel du RNMSC-DPS</h2><p style="text-align:justify; font-size:0.9em;"> Les DPS font partie des missions de sécurité civile dévolues uniquement aux associations agréées de sécurité civile. <br /> En tout état de cause, il incombe à  l'autorité de police compétente, si elle le juge nécessaire ou approprié, de prendre toute disposition en matière de secours à  personnes pour assurer la sécurité lors d'un rassemblement de personnes, sur son territoire de compétences. A ce titre, elle peut imposer à  l'organisateur un DPS dimensionné selon les modalités du présent référentiel national. <br /> En outre, l'organisateur est libre de faire appel, en complément du DPS à  personnes prescrit, à  tout autre moyen humain ou matériel, destiné à  augmenter le niveau de sécurité de la manifestation.</p> </p> <p style="text-decoration:none;font-size:0.8em;">Arrêté du 7 novembre 2006 fixant le référentiel national relatif aux dispositifs prévisionnels de secours<br><a href="http://www.legifrance.gouv.fr/WAspad/UnTexteDeJorf?numjo=INTE0600910A" target="_blank">NOR: INTE0600910A</a> </p><a href="http://www.interieur.gouv.fr/sections/a_l_interieur/defense_et_securite_civiles/autres_acteurs/associations-securite-civile/missions-securite-civile/d-dps/cpsdocument_view" target="_blank" style="text-decoration:none;font-size:0.8em;"> <img src="images/rnmsc_dps.gif" style="float:right;margin:1.5em;" border="0"> Réferentiel National - Missions de Sécurité Civile : Dispositifs Prévisionnels de Secours</a> <br /> <?php echo EbFin(); echo "<input type=submit value='fermer cette page' onclick='fermerfenetre();'> "; ?>
vanessakovalsky/esecouristes
dps.php
PHP
gpl-2.0
12,945
#include "Panel.h" #include "Button.h" #include "Label.h" #include "FieldStatus.h" #include "Field.h" #include <string> ShipPanels::Panel::Panel(int dimension, int x, int y) { this->client = new ClientProcedures(); this->dimension = dimension; this->warning = new Label(); this->rowLabels = new Label[this->dimension]; this->columnLabels = new Label[this->dimension]; this->fields = new Field*[this->dimension]; this->panelId = 0; for (int i = 0; i < this->dimension; i++) { this->fields[i] = new Field[this->dimension]; } this->generateEmptyFields(x, y); } ShipPanels::Panel::~Panel() { delete this->rowLabels; delete this->columnLabels; for (int i = 0; i < this->dimension; i++) { delete this->fields[i]; } delete *this->fields; delete this->client; } void ShipPanels::Panel::generateEmptyFields(int x, int y) { int fieldWidth = 40; int fieldHeight = 40; Drawing::Size *fieldSize = new Drawing::Size(fieldWidth, fieldHeight); int xPos = x + fieldWidth; int yPos = y + fieldHeight; this->warning->Text = "Proszê czekaæ na wygenerowanie plansz do gry."; this->warning->Location = new Drawing::Point(xPos, yPos); this->warning->Size = new Drawing::Size(10 * fieldWidth, 10 * fieldHeight); for (int i = 0; i < this->dimension; i++) { rowLabels[i].Text = getLetterByIndex(i); rowLabels[i].Size = fieldSize; rowLabels[i].Location = new Drawing::Point(xPos, y); columnLabels[i].Text = _itoa(i + 1, new char(), 10); columnLabels[i].Size = fieldSize; columnLabels[i].Location = new Drawing::Point(x, yPos); xPos += fieldWidth; yPos += fieldHeight; } x += fieldWidth; y += fieldHeight; xPos = x; yPos = y; for (int j = 0; j < this->dimension; j++) { for (int i = 0; i < this->dimension; i++) { fields[i][j].Text = ""; fields[i][j].Size = fieldSize; fields[i][j].Location = new Drawing::Point(xPos, yPos); fields[i][j].y = j; fields[i][j].x = i; fields[i][j].Click += new EventHandler::New<Panel>(this, &Panel::field_Click); xPos += fieldWidth; } xPos = x; yPos += fieldHeight; } } void ShipPanels::Panel::disableButtons() { for (int j = 0; j < this->dimension; j++) { for (int i = 0; i < this->dimension; i++) { EnableWindow(fields[i][j].hWnd, FALSE); } } } void ShipPanels::Panel::enableButtons() { for (int j = 0; j < this->dimension; j++) { for (int i = 0; i < this->dimension; i++) { EnableWindow(fields[i][j].hWnd, TRUE); } } } char* ShipPanels::Panel::getLetterByIndex(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; case 3: return "D"; case 4: return "E"; case 5: return "F"; case 6: return "G"; case 7: return "H"; case 8: return "I"; case 9: return "J"; default: return "A"; } } void ShipPanels::Panel::field_Click(void* sender, EventArgs* e) { Field * field = (Field*)sender; if ((field->status != FieldStatus::UNACTIVE) && (field->status != FieldStatus::SHIP)) { PSTR message; int textLength = 30; message = (PSTR)VirtualAlloc((LPVOID)NULL, (DWORD)(textLength + 1), MEM_COMMIT, PAGE_READWRITE); std::string sx = std::to_string(field->x); std::string sy = std::to_string(field->y); std::string contentMessage = "S-" + sx + "," + sy; strcpy(message, contentMessage.c_str()); client->sendActionPackets(message); VirtualFree(message, 0, MEM_RELEASE); } } void ShipPanels::Panel::setFieldBitmaps() { for (int i = 0; i < this->dimension; i++) { for (int j = 0; j < this->dimension; j++) { changeOnSelectable(fields[i][j]); } } } void ShipPanels::Panel::changeOnShip(Field & field) { field.status = FieldStatus::SHIP; changeBitmapOnShip(field.hWnd); } void ShipPanels::Panel::changeOnSelectable(Field & field) { field.status = FieldStatus::ACTIVE; changeBitmapOnSelectable(field.hWnd); } void ShipPanels::Panel::changeOnUnselectable(Field & field) { field.status = FieldStatus::UNACTIVE; changeBitmapOnUnselectable(field.hWnd); } void ShipPanels::Panel::destroyShip(Field & field) { field.status = FieldStatus::SHIP; HBITMAP b = LoadBitmap(Application::hInstance, MAKEINTRESOURCE(IDB_BITMAP11)); SendMessage(field.hWnd, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)b); } void ShipPanels::Panel::changeBitmapOnShip(HWND & fieldHwnd) { HBITMAP b = LoadBitmap(Application::hInstance, MAKEINTRESOURCE(IDB_BITMAP3)); SendMessage(fieldHwnd, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)b); } void ShipPanels::Panel::changeBitmapOnSelectable(HWND & fieldHwnd) { HBITMAP b = LoadBitmap(Application::hInstance, MAKEINTRESOURCE(IDB_BITMAP2)); SendMessage(fieldHwnd, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)b); } void ShipPanels::Panel::changeBitmapOnUnselectable(HWND & fieldHwnd) { HBITMAP b = LoadBitmap(Application::hInstance, MAKEINTRESOURCE(IDB_BITMAP4)); SendMessage(fieldHwnd, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)b); } void ShipPanels::Panel::setID(int id) { this->panelId = id; }
SooLiD/MovieExplorer
ShipGame/Panel.cpp
C++
gpl-2.0
5,051
<?php // +----------------------------------------------------------------------+ // | PHP versions 4 and 5 | // +----------------------------------------------------------------------+ // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, | // | Stig. S. Bakken, Lukas Smith | // | All rights reserved. | // +----------------------------------------------------------------------+ // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB | // | API as well as database abstraction for PHP applications. | // | This LICENSE is in the BSD license style. | // | | // | Redistribution and use in source and binary forms, with or without | // | modification, are permitted provided that the following conditions | // | are met: | // | | // | Redistributions of source code must retain the above copyright | // | notice, this list of conditions and the following disclaimer. | // | | // | Redistributions in binary form must reproduce the above copyright | // | notice, this list of conditions and the following disclaimer in the | // | documentation and/or other materials provided with the distribution. | // | | // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, | // | Lukas Smith nor the names of his contributors may be used to endorse | // | or promote products derived from this software without specific prior| // | written permission. | // | | // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS | // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE | // | REGENTS 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. | // +----------------------------------------------------------------------+ // | Author: Lukas Smith <smith@pooteeweet.org> | // +----------------------------------------------------------------------+ // // $Id: sqlite.php,v 1.8 2006/06/13 22:55:55 lsmith Exp $ // require_once 'MDB2/Driver/Function/Common.php'; /** * MDB2 SQLite driver for the function modules * * @package MDB2 * @category Database * @author Lukas Smith <smith@pooteeweet.org> */ class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common { // {{{ constructor /** * Constructor */ function __construct($db_index) { parent::__construct($db_index); // create all sorts of UDFs } // {{{ now() /** * Return string to call a variable with the current timestamp inside an SQL statement * There are three special variables for current date and time. * * @return string to call a variable with the current timestamp * @access public */ function now($type = 'timestamp') { switch ($type) { case 'time': return 'time(\'now\')'; case 'date': return 'date(\'now\')'; case 'timestamp': default: return 'datetime(\'now\')'; } } // }}} // {{{ substring() /** * return string to call a function to get a substring inside an SQL statement * * @return string to call a function to get a substring * @access public */ function substring($value, $position = 1, $length = null) { if (!is_null($length)) { return "substr($value,$position,$length)"; } return "substr($value,$position,length($value))"; } // }}} // {{{ random() /** * return string to call a function to get random value inside an SQL statement * * @return return string to generate float between 0 and 1 * @access public */ function random() { return '((RANDOM()+2147483648)/4294967296)'; } // }}} } ?>
danielmathiesen/hioa
wp-content/plugins/foliopress-wysiwyg/fckeditor/editor/plugins/kfm/includes/pear/MDB2/Driver/Function/sqlite.php
PHP
gpl-2.0
5,192
// ***************************************************************************** // <ProjectName> ENigMA </ProjectName> // <Description> Extended Numerical Multiphysics Analysis </Description> // <HeadURL> $HeadURL$ </HeadURL> // <LastChangedDate> $LastChangedDate$ </LastChangedDate> // <LastChangedRevision> $LastChangedRevision$ </LastChangedRevision> // <Author> Billy Araujo </Author> // ***************************************************************************** #include "ui_TetrahedronIntersection.h" #include "TetrahedronIntersection.h" #include <vtkEventQtSlotConnect.h> #include <vtkDataObjectToTable.h> #include <vtkQtTableView.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRendererCollection.h> #include <vtkPolyDataMapper.h> #include <vtkPoints.h> #include <vtkPointData.h> #include <vtkTriangle.h> #include <vtkPolyData.h> #include <vtkUnstructuredGrid.h> #include <vtkDataSetMapper.h> #include <vtkCellArray.h> #include <vtkProperty.h> #include <vtkAxesActor.h> #include <vtkTransform.h> #include <vtkVertexGlyphFilter.h> #include "vtkSmartPointer.h" #define VTK_CREATE(type, name) vtkSmartPointer<type> name = vtkSmartPointer<type>::New() // Constructor TetrahedronIntersection::TetrahedronIntersection() { this->ui = new Ui_TetrahedronIntersection; this->ui->setupUi(this); // Qt Table View this->m_tableView = vtkSmartPointer<vtkQtTableView>::New(); // Place the table view in the designer form this->ui->tableFrame->layout()->addWidget(this->m_tableView->GetWidget()); // Mesh VTK_CREATE(vtkDataSetMapper, meshMapper); meshMapper->ImmediateModeRenderingOn(); this->m_meshActor = vtkSmartPointer<vtkActor>::New(); this->m_meshActor->SetMapper(meshMapper); m_meshActor->GetProperty()->SetRepresentationToSurface(); m_meshActor->GetProperty()->LightingOn(); // Point VTK_CREATE(vtkPolyDataMapper, pointMapper); pointMapper->ImmediateModeRenderingOn(); this->m_pointActor = vtkSmartPointer<vtkActor>::New(); this->m_pointActor->SetMapper(pointMapper); m_pointActor->GetProperty()->SetRepresentationToSurface(); m_pointActor->GetProperty()->LightingOn(); m_pointActor->GetProperty()->SetPointSize(5); // Tetrahedron VTK_CREATE(vtkDataSetMapper, tetrahedronMapper); tetrahedronMapper->ImmediateModeRenderingOn(); this->m_tetrahedronActor = vtkSmartPointer<vtkActor>::New(); this->m_tetrahedronActor->SetMapper(tetrahedronMapper); m_tetrahedronActor->GetProperty()->SetRepresentationToSurface(); m_tetrahedronActor->GetProperty()->LightingOn(); // Axes this->m_axesActor = vtkSmartPointer<vtkAxesActor>::New(); // VTK Renderer VTK_CREATE(vtkRenderer, ren); // Add Actor to renderer ren->AddActor(m_axesActor); ren->AddActor(m_meshActor); ren->AddActor(m_pointActor); ren->AddActor(m_tetrahedronActor); // VTK/Qt wedded this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(ren); // Just a bit of Qt interest: Culling off the // point data and handing it to a vtkQtTableView //VTK_CREATE(vtkDataObjectToTable, toTable); //toTable->SetInputConnection(elevation->GetOutputPort()); //toTable->SetFieldType(vtkDataObjectToTable::POINT_DATA); // Here we take the end of the VTK pipeline and give it to a Qt View //this->m_tableView->SetRepresentationFromInputConnection(toTable->GetOutputPort()); // Set up action signals and slots connect(this->ui->actionOpenFile, SIGNAL(triggered()), this, SLOT(slotOpenFile())); connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit())); m_connections = vtkEventQtSlotConnect::New(); this->m_connections->Connect(this->ui->qvtkWidget->GetRenderWindow()->GetInteractor(), vtkCommand::KeyPressEvent, this, SLOT(slotKeyPressed(vtkObject*, unsigned long, void*, void*)), 0, 1.0); // Create a PolyData buildMesh(); drawMesh(); drawPoint(); drawTetrahedron(); }; TetrahedronIntersection::~TetrahedronIntersection() { // The smart pointers should clean up for up } void TetrahedronIntersection::slotKeyPressed(vtkObject *, unsigned long, void *, void *) { vtkRenderWindowInteractor *rwi = this->ui->qvtkWidget->GetRenderWindow()->GetInteractor(); std::string key = rwi->GetKeySym(); // Output the key that was pressed //std::cout << "Pressed " << key << std::endl; if (key == "Right") { m_point.z() += 0.01; drawPoint(); drawTetrahedron(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "Left") { m_point.z() -= 0.01; drawPoint(); drawTetrahedron(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "r" || key == "R") { drawMesh(); drawPoint(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "w" || key == "W") { vtkRenderer* ren = this->ui->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkActor* actor = ren->GetActors()->GetLastActor(); actor->GetProperty()->SetRepresentationToWireframe(); actor->GetProperty()->LightingOff(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } else if (key == "s" || key == "S") { vtkRenderer* ren = this->ui->qvtkWidget->GetRenderWindow()->GetRenderers()->GetFirstRenderer(); vtkActor* actor = ren->GetActors()->GetLastActor(); actor->GetProperty()->SetRepresentationToSurface(); actor->GetProperty()->LightingOn(); this->ui->qvtkWidget->GetRenderWindow()->Render(); } } // Action to be taken upon file open void TetrahedronIntersection::slotOpenFile() { } void TetrahedronIntersection::slotExit() { qApp->exit(); } void TetrahedronIntersection::buildMesh() { std::vector<CMshNode<double> > sNodes; CMshNode<double> aNode1; CMshNode<double> aNode2; CMshNode<double> aNode3; CMshNode<double> aNode4; CMshNode<double> aNode5; CMshNode<double> aNode6; m_point << 0, 0, 0; aNode1 << 1.0, 0.875, 0.125; aNode2 << 0.875, 1.0, 0.125; aNode3 << 1.0, 1.0, 0.125; aNode4 << 1.0, 0.875, 0.25; aNode5 << 0.875, 1.0, 0.25; aNode6 << 1.0, 1.0, 0.25; sNodes.push_back(aNode1); sNodes.push_back(aNode2); sNodes.push_back(aNode3); sNodes.push_back(aNode4); sNodes.push_back(aNode5); sNodes.push_back(aNode6); for (unsigned int i = 0; i < sNodes.size(); ++i) { m_mesh.addNode(i + 1, sNodes[i]); m_point += sNodes[i]; } m_point /= sNodes.size(); CMshElement<double> anElement1(ET_TRIANGLE); CMshElement<double> anElement2(ET_TRIANGLE); CMshElement<double> anElement3(ET_TRIANGLE); CMshElement<double> anElement4(ET_TRIANGLE); CMshElement<double> anElement5(ET_TRIANGLE); CMshElement<double> anElement6(ET_TRIANGLE); CMshElement<double> anElement7(ET_TRIANGLE); CMshElement<double> anElement8(ET_TRIANGLE); // 1 - 2 5 3 anElement1.addNodeId(2); anElement1.addNodeId(5); anElement1.addNodeId(3); m_mesh.addElement(1, anElement1); // 2 - 1 3 6 anElement2.addNodeId(1); anElement2.addNodeId(3); anElement2.addNodeId(6); m_mesh.addElement(2, anElement2); // 3 - 3 5 6 anElement3.addNodeId(3); anElement3.addNodeId(5); anElement3.addNodeId(6); m_mesh.addElement(3, anElement3); // 4 - 1 6 4 anElement4.addNodeId(1); anElement4.addNodeId(6); anElement4.addNodeId(4); m_mesh.addElement(4, anElement4); // 5 - 6 5 4 anElement5.addNodeId(6); anElement5.addNodeId(5); anElement5.addNodeId(4); m_mesh.addElement(5, anElement5); // 6 - 3 1 2 anElement6.addNodeId(3); anElement6.addNodeId(1); anElement6.addNodeId(2); m_mesh.addElement(6, anElement6); // 7 - 4 5 2 anElement7.addNodeId(4); anElement7.addNodeId(5); anElement7.addNodeId(2); m_mesh.addElement(7, anElement7); // 8 - 1 4 2 anElement8.addNodeId(1); anElement8.addNodeId(4); anElement8.addNodeId(2); m_mesh.addElement(8, anElement8); } void TetrahedronIntersection::drawMesh() { VTK_CREATE(vtkPoints, points); for (Integer i = 0; i < m_mesh.nbNodes(); ++i) { Integer aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); points->InsertNextPoint(aNode.x(), aNode.y(), aNode.z()); } VTK_CREATE(vtkUnstructuredGrid, unstructuredGrid); unstructuredGrid->SetPoints(points); for (Integer i = 0; i < m_mesh.nbElements(); ++i) { Integer anElementId = m_mesh.elementId(i); CMshElement<double> anElement = m_mesh.element(anElementId); if (anElement.elementType() == ET_TRIANGLE) { vtkIdType ptIds[] = {static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(0))), static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(1))), static_cast<vtkIdType> (m_mesh.nodeIndex(anElement.nodeId(2)))}; unstructuredGrid->InsertNextCell(VTK_TRIANGLE, 3, ptIds); } } vtkMapper* mapper = m_meshActor->GetMapper(); (reinterpret_cast<vtkDataSetMapper* >(mapper))->SetInputData(unstructuredGrid); } void TetrahedronIntersection::drawPoint() { VTK_CREATE(vtkPoints, points); points->InsertNextPoint(m_point.x(), m_point.y(), m_point.z()); VTK_CREATE(vtkPolyData, pointsPolydata); pointsPolydata->SetPoints(points); VTK_CREATE(vtkVertexGlyphFilter, vertexFilter); vertexFilter->SetInputData(pointsPolydata); vertexFilter->Update(); // Setup colors unsigned char yellow[3] = {255, 255, 0}; VTK_CREATE(vtkUnsignedCharArray, colors); colors->SetNumberOfComponents(3); colors->SetName ("Colors"); colors->InsertNextTypedTuple(yellow); VTK_CREATE(vtkPolyData, polydata); polydata->ShallowCopy(vertexFilter->GetOutput()); polydata->GetPointData()->SetScalars(colors); vtkMapper* mapper = m_pointActor->GetMapper(); (reinterpret_cast<vtkPolyDataMapper* >(mapper))->SetInputData(polydata); } void TetrahedronIntersection::drawTetrahedron() { CGeoTetrahedron<double> aTetrahedron; for (unsigned int i = 0; i < 3; ++i) { unsigned int aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); CGeoCoordinate<double> aVertex = aNode; aTetrahedron.addVertex(aVertex); } CGeoCoordinate<double> aVertex = m_point; aTetrahedron.addVertex(aVertex); // Setup colors unsigned char activeColor[3]; unsigned char red[3] = {255, 0, 0}; unsigned char green[3] = {0, 255, 0}; activeColor[0] = green[0]; activeColor[1] = green[1]; activeColor[2] = green[2]; bool bOK = true; double tol = 1E-5; for (Integer i = 3; i < m_mesh.nbNodes(); ++i) { unsigned int aNodeId = m_mesh.nodeId(i); CMshNode<double> aNode = m_mesh.node(aNodeId); CGeoCoordinate<double> aPoint = aNode; if (aTetrahedron.contains(aPoint, tol)) { bOK = false; break; } } CGeoTriangle<double> aTriangle1; aTriangle1.addVertex(aTetrahedron.vertex(0)); aTriangle1.addVertex(aTetrahedron.vertex(1)); aTriangle1.addVertex(aTetrahedron.vertex(3)); CGeoTriangle<double> aTriangle2; aTriangle2.addVertex(aTetrahedron.vertex(1)); aTriangle2.addVertex(aTetrahedron.vertex(2)); aTriangle2.addVertex(aTetrahedron.vertex(3)); CGeoTriangle<double> aTriangle3; aTriangle3.addVertex(aTetrahedron.vertex(2)); aTriangle3.addVertex(aTetrahedron.vertex(0)); aTriangle3.addVertex(aTetrahedron.vertex(3)); for (Integer i = 3; i < m_mesh.nbElements(); ++i) { Integer anElementId = m_mesh.elementId(i); CMshElement<double> anElement = m_mesh.element(anElementId); if (anElement.elementType() == ET_TRIANGLE) { CGeoTriangle<double> aTriangle; for (Integer j = 0; j < anElement.nbNodeIds(); ++j) { CGeoCoordinate<double> aVertex; aVertex = m_mesh.node(anElement.nodeId(j)); aTriangle.addVertex(aVertex); } CGeoIntersectionType anIntType; if (aTriangle.intersects(aTriangle1, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } if (aTriangle.intersects(aTriangle2, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } if (aTriangle.intersects(aTriangle3, anIntType, tol)) { if (anIntType == IT_INTERNAL) { bOK = false; break; } } } } if (!bOK) { activeColor[0] = red[0]; activeColor[1] = red[1]; activeColor[2] = red[2]; } if (bOK) std::cout << "Tetra: OK!" << std::endl; else std::cout << "Tetra: Not OK!" << std::endl; VTK_CREATE(vtkUnsignedCharArray, colors); colors->SetNumberOfComponents(3); colors->SetName("Colors"); VTK_CREATE(vtkPoints, points); for (unsigned int i = 0; i < 4; ++i) { CGeoCoordinate<double> aVertex = aTetrahedron.vertex(i); points->InsertNextPoint(aVertex.x(), aVertex.y(), aVertex.z()); colors->InsertNextTypedTuple(activeColor); } VTK_CREATE(vtkUnstructuredGrid, unstructuredGrid); unstructuredGrid->SetPoints(points); vtkIdType ptIds[] = {0, 1, 2, 3}; unstructuredGrid->InsertNextCell(VTK_TETRA, 4, ptIds); unstructuredGrid->GetPointData()->SetScalars(colors); vtkMapper* mapper = m_tetrahedronActor->GetMapper(); (reinterpret_cast<vtkDataSetMapper* >(mapper))->SetInputData(unstructuredGrid); }
bjaraujo/ENigMA
trunk/examples/tetrahedronintersection/TetrahedronIntersection.cpp
C++
gpl-2.0
14,797
package org.soaplab.text_mining.kwic; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebServiceClient(name = "kwicService", targetNamespace = "http://soaplab.org/text_mining/kwic", wsdlLocation = "http://ws04.iula.upf.edu/soaplab2-axis/typed/services/text_mining.kwic?wsdl") public class KwicService extends Service { private final static URL KWICSERVICE_WSDL_LOCATION; private final static WebServiceException KWICSERVICE_EXCEPTION; private final static QName KWICSERVICE_QNAME = new QName("http://soaplab.org/text_mining/kwic", "kwicService"); static { URL url = null; WebServiceException e = null; try { url = new URL("http://ws04.iula.upf.edu/soaplab2-axis/typed/services/text_mining.kwic?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } KWICSERVICE_WSDL_LOCATION = url; KWICSERVICE_EXCEPTION = e; } public KwicService() { super(__getWsdlLocation(), KWICSERVICE_QNAME); } public KwicService(WebServiceFeature... features) { super(__getWsdlLocation(), KWICSERVICE_QNAME, features); } public KwicService(URL wsdlLocation) { super(wsdlLocation, KWICSERVICE_QNAME); } public KwicService(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, KWICSERVICE_QNAME, features); } public KwicService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public KwicService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns Kwic */ @WebEndpoint(name = "kwicPort") public Kwic getKwicPort() { return super.getPort(new QName("http://soaplab.org/text_mining/kwic", "kwicPort"), Kwic.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns Kwic */ @WebEndpoint(name = "kwicPort") public Kwic getKwicPort(WebServiceFeature... features) { return super.getPort(new QName("http://soaplab.org/text_mining/kwic", "kwicPort"), Kwic.class, features); } private static URL __getWsdlLocation() { if (KWICSERVICE_EXCEPTION!= null) { throw KWICSERVICE_EXCEPTION; } return KWICSERVICE_WSDL_LOCATION; } }
jaimedelgado/Xtext
src/org/soaplab/text_mining/kwic/KwicService.java
Java
gpl-2.0
2,933
#!/usr/bin/env python #-*- coding: ascii -*- from __future__ import print_function import sys from blib_util import * def build_kfont(build_info): for compiler_info in build_info.compilers: build_a_project("kfont", "kfont", build_info, compiler_info, True) if __name__ == "__main__": cfg = cfg_from_argv(sys.argv) bi = build_info(cfg.compiler, cfg.archs, cfg.cfg) print("Building kfont...") build_kfont(bi)
zhangf911/KlayGE
build_kfont.py
Python
gpl-2.0
435
package com.example.piasy.startup; import com.example.piasy.startup.location.PaintBoardFragment; import com.example.piasy.startup.sensors.LogBoardFragment; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import java.math.BigDecimal; import java.math.RoundingMode; public class MyActivity extends FragmentActivity implements SensorEventListener, Controller { private static final int MODE_NONE = 0; private static final int MODE_SENSOR = 1; private static final int MODE_LOCATION = 2; private int mode = MODE_NONE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mode = MODE_LOCATION; switch (mode) { case MODE_SENSOR: measureSensors(); break; case MODE_LOCATION: measureLocation(); break; default: break; } mStarted = true; } PaintBoardFragment mPainter; LocationManager mLocationManager; LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { mPainter.updateLocation(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; private void measureLocation() { mPainter = new PaintBoardFragment(); getSupportFragmentManager().beginTransaction() .add(android.R.id.content, mPainter, mPainter.getClass().getName()).commit(); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); } LogBoardFragment mLogger; SensorManager mSensorManager; Sensor mAccelerometer, mGravity, mGyroscope, mLinearAcc; private void measureSensors() { mLogger = new LogBoardFragment(); getSupportFragmentManager().beginTransaction() .add(android.R.id.content, mLogger, mLogger.getClass().getName()).commit(); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mLinearAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(this, mLinearAcc, SensorManager.SENSOR_DELAY_UI); } @Override protected void onStart() { super.onStart(); Log.d("xjltest", "MyActivity onStart"); } @Override protected void onRestart() { super.onRestart(); Log.d("xjltest", "MyActivity onRestart"); } @Override protected void onResume() { super.onResume(); Log.d("xjltest", "MyActivity onResume"); } @Override protected void onPause() { super.onPause(); Log.d("xjltest", "MyActivity onPause"); } @Override protected void onStop() { super.onStop(); Log.d("xjltest", "MyActivity onStop"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("xjltest", "MyActivity onDestroy"); if (mSensorManager != null) { mSensorManager.unregisterListener(this); } if (mLocationManager != null) { mLocationManager.removeUpdates(mLocationListener); } } @Override protected void onUserLeaveHint() { super.onUserLeaveHint(); } float [] mLastGravity = null; @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.equals(mAccelerometer)) { mLogger.log("ACCELEROMETER: x = " + cutBit(event.values[0], 2) + " m/s^2, " + "y = " + cutBit(event.values[1], 2) + " m/s^2, " + "z = " + cutBit(event.values[2], 2) + " m/s^2."); if (mLastGravity != null) { mLogger.log("REAL: x = " + cutBit(event.values[0] - mLastGravity[0], 2) + " m/s^2, " + "y = " + cutBit(event.values[1] - mLastGravity[1], 2) + " m/s^2, " + "z = " + cutBit(event.values[2] - mLastGravity[2], 2) + " m/s^2."); } } else if (event.sensor.equals(mGravity)) { mLogger.log("GRAVITY: x = " + cutBit(event.values[0], 2) + " m/s^2, " + "y = " + cutBit(event.values[1], 2) + " m/s^2, " + "z = " + cutBit(event.values[2], 2) + " m/s^2."); mLastGravity = event.values; } else if (event.sensor.equals(mLinearAcc)) { mLogger.log("LINEAR_ACC: x = " + cutBit(event.values[0], 2) + " m/s^2, " + "y = " + cutBit(event.values[1], 2) + " m/s^2, " + "z = " + cutBit(event.values[2], 2) + " m/s^2."); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } private float cutBit(float num, int bit) { return new BigDecimal(num).setScale(bit, RoundingMode.UP).floatValue(); } boolean mStarted = false; @Override public void start() { if (mStarted) { return; } switch (mode) { case MODE_SENSOR: mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(this, mGravity, SensorManager.SENSOR_DELAY_UI); mSensorManager.registerListener(this, mLinearAcc, SensorManager.SENSOR_DELAY_UI); break; case MODE_LOCATION: mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); break; default: break; } mStarted = true; } @Override public void stop() { if (!mStarted) { return; } switch (mode) { case MODE_SENSOR: mSensorManager.unregisterListener(this); break; case MODE_LOCATION: mLocationManager.removeUpdates(mLocationListener); break; default: break; } mStarted = false; } }
Piasy/Graduate
src/GpsEvaluate/Android-client/Gps-Demo/app/src/main/java/com/example/piasy/startup/MyActivity.java
Java
gpl-2.0
7,171
/* thePlatform Video Manager Wordpress Plugin Copyright (C) 2013-2014 thePlatform for Media Inc. 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. Changes ======================================== qaz2wsx3@uw.edu: changed the icon on the post editor's toolbar */ tinymce.PluginManager.add( 'theplatform', function( editor, url ) { // Add a button that opens a window editor.addButton( 'theplatform', { tooltip: 'Embed MPX Media', image: url.substring( 0, url.lastIndexOf( '/js' ) ) + '/images/MediaAMP_button_icon.png', onclick: function() { // Open window var iframeUrl = ajaxurl + "?action=theplatform_media&embed=true&_wpnonce=" + editor.settings.theplatform_media_nonce; tinyMCE.activeEditor = editor; if ( window.innerHeight < 1200 ) height = window.innerHeight - 50; else height = 1024; if ( tinyMCE.majorVersion > 3 ) { editor.windowManager.open( { width: 1220, height: height, url: iframeUrl } ); } else { if ( jQuery( "#tp-embed-dialog" ).length == 0 ) { jQuery( 'body' ).append( '<div id="tp-embed-dialog"></div>' ); } jQuery( "#tp-embed-dialog" ).html( '<iframe src="' + iframeUrl + '" height="100%" width="100%">' ).dialog( { dialogClass: "wp-dialog", modal: true, resizable: true, minWidth: 1024, width: 1220, height: height } ).css( "overflow-y", "hidden" ); } } } ); } ); tinymce.init( { plugins: 'theplatform' } );
uw-it-aca/MediaAMP-video-manager
js/theplatform.tinymce.plugin.js
JavaScript
gpl-2.0
2,087
/* Copyright 2007 MySQL AB, 2008 Sun Microsystems All rights reserved. Use is subject to license terms. The MySQL Connector/J is licensed under the terms of the GPL, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPL as it is applied to this software, see the FLOSS License Exception available on mysql.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; 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc; import java.io.InputStream; import java.io.Reader; import java.sql.Date; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Calendar; import java.util.StringTokenizer; import java.util.TimeZone; /** * Classes that implement this interface represent one row of data from the * MySQL server that might be stored in different ways depending on whether the * result set was streaming (so they wrap a reusable packet), or whether the * result set was cached or via a server-side cursor (so they represent a * byte[][]). * * Notice that <strong>no</strong> bounds checking is expected for implementors * of this interface, it happens in ResultSetImpl. * * @version $Id: $ */ public abstract class ResultSetRow { protected ExceptionInterceptor exceptionInterceptor; protected ResultSetRow(ExceptionInterceptor exceptionInterceptor) { this.exceptionInterceptor = exceptionInterceptor; } /** * The metadata of the fields of this result set. */ protected Field[] metadata; /** * Called during navigation to next row to close all open * streams. */ public abstract void closeOpenStreams(); /** * Returns data at the given index as an InputStream with no * character conversion. * * @param columnIndex * of the column value (starting at 0) to return. * @return the value at the given index as an InputStream or null * if null. * * @throws SQLException if an error occurs while retrieving the value. */ public abstract InputStream getBinaryInputStream(int columnIndex) throws SQLException; /** * Returns the value at the given column (index starts at 0) "raw" (i.e. * as-returned by the server). * * @param index * of the column value (starting at 0) to return. * @return the value for the given column (including NULL if it is) * @throws SQLException * if an error occurs while retrieving the value. */ public abstract byte[] getColumnValue(int index) throws SQLException; protected final java.sql.Date getDateFast(int columnIndex, byte[] dateAsBytes, int offset, int length, ConnectionImpl conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException { int year = 0; int month = 0; int day = 0; try { if (dateAsBytes == null) { return null; } boolean allZeroDate = true; boolean onlyTimePresent = false; for (int i = 0; i < length; i++) { if (dateAsBytes[offset + i] == ':') { onlyTimePresent = true; break; } } for (int i = 0; i < length; i++) { byte b = dateAsBytes[offset + i]; if (b == ' ' || b == '-' || b == '/') { onlyTimePresent = false; } if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') { allZeroDate = false; break; } } if (!onlyTimePresent && allZeroDate) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw SQLError.createSQLException("Value '" + new String(dateAsBytes) + "' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } // We're left with the case of 'round' to a date Java _can_ // represent, which is '0001-01-01'. return rs.fastDateCreate(targetCalendar, 1, 1, 1); } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { // Convert from TIMESTAMP switch (length) { case 29: case 21: case 19: { // java.sql.Timestamp format year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(dateAsBytes, offset + 5, offset + 7); day = StringUtils.getInt(dateAsBytes, offset + 8, offset + 10); return rs.fastDateCreate(targetCalendar, year, month, day); } case 14: case 8: { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(dateAsBytes, offset + 4, offset + 6); day = StringUtils.getInt(dateAsBytes, offset + 6, offset + 8); return rs.fastDateCreate(targetCalendar, year, month, day); } case 12: case 10: case 6: { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 2); if (year <= 69) { year = year + 100; } month = StringUtils.getInt(dateAsBytes, offset + 2, offset + 4); day = StringUtils.getInt(dateAsBytes, offset + 4, offset + 6); return rs.fastDateCreate(targetCalendar, year + 1900, month, day); } case 4: { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4); if (year <= 69) { year = year + 100; } month = StringUtils.getInt(dateAsBytes, offset + 2, offset + 4); return rs.fastDateCreate(targetCalendar, year + 1900, month, 1); } case 2: { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 2); if (year <= 69) { year = year + 100; } return rs.fastDateCreate(targetCalendar, year + 1900, 1, 1); } default: throw SQLError .createSQLException( Messages .getString( "ResultSet.Bad_format_for_Date", new Object[] { new String( dateAsBytes), Constants .integerValueOf(columnIndex + 1) }), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$ } /* endswitch */ } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { if (length == 2 || length == 1) { year = StringUtils.getInt(dateAsBytes, offset, offset + length); if (year <= 69) { year = year + 100; } year += 1900; } else { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4); } return rs.fastDateCreate(targetCalendar, year, 1, 1); } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_TIME) { return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return EPOCH } else { if (length < 10) { if (length == 8) { return rs.fastDateCreate(targetCalendar, 1970, 1, 1); // Return // EPOCH for // TIME } throw SQLError .createSQLException( Messages .getString( "ResultSet.Bad_format_for_Date", new Object[] { new String( dateAsBytes), Constants .integerValueOf(columnIndex + 1) }), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$ } if (length != 18) { year = StringUtils.getInt(dateAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(dateAsBytes, offset + 5, offset + 7); day = StringUtils.getInt(dateAsBytes, offset + 8, offset + 10); } else { // JDK-1.3 timestamp format, not real easy to parse // positionally :p StringTokenizer st = new StringTokenizer(new String( dateAsBytes, offset, length, "ISO8859_1"), "- "); year = Integer.parseInt(st.nextToken()); month = Integer.parseInt(st.nextToken()); day = Integer.parseInt(st.nextToken()); } } return rs.fastDateCreate(targetCalendar, year, month, day); } catch (SQLException sqlEx) { throw sqlEx; // don't re-wrap } catch (Exception e) { SQLException sqlEx = SQLError.createSQLException(Messages.getString( "ResultSet.Bad_format_for_Date", new Object[] { new String(dateAsBytes), Constants.integerValueOf(columnIndex + 1) }), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); //$NON-NLS-1$ sqlEx.initCause(e); throw sqlEx; } } public abstract java.sql.Date getDateFast(int columnIndex, ConnectionImpl conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException; /** * Returns the value at the given column (index starts at 0) as an int. * * * @param index * of the column value (starting at 0) to return. * @return the value for the given column (returns 0 if NULL, use isNull() * to determine if the value was actually NULL) * @throws SQLException * if an error occurs while retrieving the value. */ public abstract int getInt(int columnIndex) throws SQLException; /** * Returns the value at the given column (index starts at 0) as a long. * * * @param index * of the column value (starting at 0) to return. * @return the value for the given column (returns 0 if NULL, use isNull() * to determine if the value was actually NULL) * @throws SQLException * if an error occurs while retrieving the value. */ public abstract long getLong(int columnIndex) throws SQLException; protected java.sql.Date getNativeDate(int columnIndex, byte[] bits, int offset, int length, ConnectionImpl conn, ResultSetImpl rs, Calendar cal) throws SQLException { int year = 0; int month = 0; int day = 0; if (length != 0) { year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8); month = bits[offset + 2]; day = bits[offset + 3]; } if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw SQLError .createSQLException( "Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } year = 1; month = 1; day = 1; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastDateCreate(year, month, day, cal); } return rs.fastDateCreate(cal == null ? rs.getCalendarInstanceForSessionOrNew() : cal, year, month, day); } public abstract Date getNativeDate(int columnIndex, ConnectionImpl conn, ResultSetImpl rs, Calendar cal) throws SQLException; protected Object getNativeDateTimeValue(int columnIndex, byte[] bits, int offset, int length, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException { int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int seconds = 0; int nanos = 0; if (bits == null) { return null; } Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn .getUtcCalendar() : rs.getCalendarInstanceForSessionOrNew(); boolean populatedFromDateTimeValue = false; switch (mysqlType) { case MysqlDefs.FIELD_TYPE_DATETIME: case MysqlDefs.FIELD_TYPE_TIMESTAMP: populatedFromDateTimeValue = true; if (length != 0) { year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8); month = bits[offset + 2]; day = bits[offset + 3]; if (length > 4) { hour = bits[offset + 4]; minute = bits[offset + 5]; seconds = bits[offset + 6]; } if (length > 7) { // MySQL uses microseconds nanos = ((bits[offset + 7] & 0xff) | ((bits[offset + 8] & 0xff) << 8) | ((bits[offset + 9] & 0xff) << 16) | ((bits[offset + 10] & 0xff) << 24)) * 1000; } } break; case MysqlDefs.FIELD_TYPE_DATE: populatedFromDateTimeValue = true; if (bits.length != 0) { year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8); month = bits[offset + 2]; day = bits[offset + 3]; } break; case MysqlDefs.FIELD_TYPE_TIME: populatedFromDateTimeValue = true; if (bits.length != 0) { // bits[0] // skip tm->neg // binaryData.readLong(); // skip daysPart hour = bits[offset + 5]; minute = bits[offset + 6]; seconds = bits[offset + 7]; } year = 1970; month = 1; day = 1; break; default: populatedFromDateTimeValue = false; } switch (jdbcType) { case Types.TIME: if (populatedFromDateTimeValue) { if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimeCreate(hour, minute, seconds, targetCalendar, this.exceptionInterceptor); } Time time = TimeUtil.fastTimeCreate(rs .getCalendarInstanceForSessionOrNew(), hour, minute, seconds, this.exceptionInterceptor); Time adjustedTime = TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, time, conn .getServerTimezoneTZ(), tz, rollForward); return adjustedTime; } return rs.getNativeTimeViaParseConversion(columnIndex + 1, targetCalendar, tz, rollForward); case Types.DATE: if (populatedFromDateTimeValue) { if ((year == 0) && (month == 0) && (day == 0)) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw new SQLException( "Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); } year = 1; month = 1; day = 1; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastDateCreate(year, month, day, targetCalendar); } return rs .fastDateCreate( rs.getCalendarInstanceForSessionOrNew(), year, month, day); } return rs.getNativeDateViaParseConversion(columnIndex + 1); case Types.TIMESTAMP: if (populatedFromDateTimeValue) { if ((year == 0) && (month == 0) && (day == 0)) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw new SQLException( "Value '0000-00-00' can not be represented as java.sql.Timestamp", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); } year = 1; month = 1; day = 1; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimestampCreate(tz, year, month, day, hour, minute, seconds, nanos); } Timestamp ts = rs.fastTimestampCreate(rs .getCalendarInstanceForSessionOrNew(), year, month, day, hour, minute, seconds, nanos); Timestamp adjustedTs = TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, ts, conn .getServerTimezoneTZ(), tz, rollForward); return adjustedTs; } return rs.getNativeTimestampViaParseConversion(columnIndex + 1, targetCalendar, tz, rollForward); default: throw new SQLException( "Internal error - conversion method doesn't support this type", SQLError.SQL_STATE_GENERAL_ERROR); } } public abstract Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException; protected double getNativeDouble(byte[] bits, int offset) { long valueAsLong = (bits[offset + 0] & 0xff) | ((long) (bits[offset + 1] & 0xff) << 8) | ((long) (bits[offset + 2] & 0xff) << 16) | ((long) (bits[offset + 3] & 0xff) << 24) | ((long) (bits[offset + 4] & 0xff) << 32) | ((long) (bits[offset + 5] & 0xff) << 40) | ((long) (bits[offset + 6] & 0xff) << 48) | ((long) (bits[offset + 7] & 0xff) << 56); return Double.longBitsToDouble(valueAsLong); } public abstract double getNativeDouble(int columnIndex) throws SQLException; protected float getNativeFloat(byte[] bits, int offset) { int asInt = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8) | ((bits[offset + 2] & 0xff) << 16) | ((bits[offset + 3] & 0xff) << 24); return Float.intBitsToFloat(asInt); } public abstract float getNativeFloat(int columnIndex) throws SQLException; protected int getNativeInt(byte[] bits, int offset) { int valueAsInt = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8) | ((bits[offset + 2] & 0xff) << 16) | ((bits[offset + 3] & 0xff) << 24); return valueAsInt; } public abstract int getNativeInt(int columnIndex) throws SQLException; protected long getNativeLong(byte[] bits, int offset) { long valueAsLong = (bits[offset + 0] & 0xff) | ((long) (bits[offset + 1] & 0xff) << 8) | ((long) (bits[offset + 2] & 0xff) << 16) | ((long) (bits[offset + 3] & 0xff) << 24) | ((long) (bits[offset + 4] & 0xff) << 32) | ((long) (bits[offset + 5] & 0xff) << 40) | ((long) (bits[offset + 6] & 0xff) << 48) | ((long) (bits[offset + 7] & 0xff) << 56); return valueAsLong; } public abstract long getNativeLong(int columnIndex) throws SQLException; protected short getNativeShort(byte[] bits, int offset) { short asShort = (short) ((bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8)); return asShort; } public abstract short getNativeShort(int columnIndex) throws SQLException; protected Time getNativeTime(int columnIndex, byte[] bits, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException { int hour = 0; int minute = 0; int seconds = 0; if (length != 0) { // bits[0] // skip tm->neg // binaryData.readLong(); // skip daysPart hour = bits[offset + 5]; minute = bits[offset + 6]; seconds = bits[offset + 7]; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimeCreate(hour, minute, seconds, targetCalendar, this.exceptionInterceptor); } Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew(); synchronized (sessionCalendar) { Time time = TimeUtil.fastTimeCreate(sessionCalendar, hour, minute, seconds, this.exceptionInterceptor); Time adjustedTime = TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, time, conn.getServerTimezoneTZ(), tz, rollForward); return adjustedTime; } } public abstract Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException; protected Timestamp getNativeTimestamp(byte[] bits, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException { int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int seconds = 0; int nanos = 0; if (length != 0) { year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8); month = bits[offset + 2]; day = bits[offset + 3]; if (length > 4) { hour = bits[offset + 4]; minute = bits[offset + 5]; seconds = bits[offset + 6]; } if (length > 7) { // MySQL uses microseconds nanos = ((bits[offset + 7] & 0xff) | ((bits[offset + 8] & 0xff) << 8) | ((bits[offset + 9] & 0xff) << 16) | ((bits[offset + 10] & 0xff) << 24)) * 1000; } } if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw SQLError .createSQLException( "Value '0000-00-00' can not be represented as java.sql.Timestamp", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } year = 1; month = 1; day = 1; } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimestampCreate(tz, year, month, day, hour, minute, seconds, nanos); } Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn .getUtcCalendar() : rs.getCalendarInstanceForSessionOrNew(); synchronized (sessionCalendar) { Timestamp ts = rs.fastTimestampCreate(sessionCalendar, year, month, day, hour, minute, seconds, nanos); Timestamp adjustedTs = TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, ts, conn .getServerTimezoneTZ(), tz, rollForward); return adjustedTs; } } public abstract Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException; public abstract Reader getReader(int columnIndex) throws SQLException; /** * Returns the value at the given column (index starts at 0) as a * java.lang.String with the requested encoding, using the given * ConnectionImpl to find character converters. * * @param index * of the column value (starting at 0) to return. * @param encoding * the Java name for the character encoding * @param conn * the connection that created this result set row * * @return the value for the given column (including NULL if it is) as a * String * * @throws SQLException * if an error occurs while retrieving the value. */ public abstract String getString(int index, String encoding, ConnectionImpl conn) throws SQLException; /** * Convenience method for turning a byte[] into a string with the given * encoding. * * @param encoding * the Java encoding name for the byte[] -> char conversion * @param conn * the ConnectionImpl that created the result set * @param value * the String value as a series of bytes, encoded using * "encoding" * @param offset * where to start the decoding * @param length * how many bytes to decode * * @return the String as decoded from bytes with the given encoding * * @throws SQLException * if an error occurs */ protected String getString(String encoding, ConnectionImpl conn, byte[] value, int offset, int length) throws SQLException { String stringVal = null; if ((conn != null) && conn.getUseUnicode()) { try { if (encoding == null) { stringVal = new String(value); } else { SingleByteCharsetConverter converter = conn .getCharsetConverter(encoding); if (converter != null) { stringVal = converter.toString(value, offset, length); } else { stringVal = new String(value, offset, length, encoding); } } } catch (java.io.UnsupportedEncodingException E) { throw SQLError .createSQLException( Messages .getString("ResultSet.Unsupported_character_encoding____101") //$NON-NLS-1$ + encoding + "'.", "0S100", this.exceptionInterceptor); } } else { stringVal = StringUtils.toAsciiString(value, offset, length); } return stringVal; } protected Time getTimeFast(int columnIndex, byte[] timeAsBytes, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException { int hr = 0; int min = 0; int sec = 0; try { if (timeAsBytes == null) { return null; } boolean allZeroTime = true; boolean onlyTimePresent = false; for (int i = 0; i < length; i++) { if (timeAsBytes[offset + i] == ':') { onlyTimePresent = true; break; } } for (int i = 0; i < length; i++) { byte b = timeAsBytes[offset + i]; if (b == ' ' || b == '-' || b == '/') { onlyTimePresent = false; } if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') { allZeroTime = false; break; } } if (!onlyTimePresent && allZeroTime) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw SQLError.createSQLException("Value '" + new String(timeAsBytes) + "' can not be represented as java.sql.Time", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } // We're left with the case of 'round' to a time Java _can_ // represent, which is '00:00:00' return rs.fastTimeCreate(targetCalendar, 0, 0, 0); } Field timeColField = this.metadata[columnIndex]; if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_TIMESTAMP) { switch (length) { case 19: { // YYYY-MM-DD hh:mm:ss hr = StringUtils.getInt(timeAsBytes, offset + length - 8, offset + length - 6); min = StringUtils.getInt(timeAsBytes, offset + length - 5, offset + length - 3); sec = StringUtils.getInt(timeAsBytes, offset + length - 2, offset + length); } break; case 14: case 12: { hr = StringUtils.getInt(timeAsBytes, offset + length - 6, offset + length - 4); min = StringUtils.getInt(timeAsBytes, offset + length - 4, offset + length - 2); sec = StringUtils.getInt(timeAsBytes, offset + length - 2, offset + length); } break; case 10: { hr = StringUtils .getInt(timeAsBytes, offset + 6, offset + 8); min = StringUtils.getInt(timeAsBytes, offset + 8, offset + 10); sec = 0; } break; default: throw SQLError .createSQLException( Messages .getString("ResultSet.Timestamp_too_small_to_convert_to_Time_value_in_column__257") //$NON-NLS-1$ + (columnIndex + 1) + "(" + timeColField + ").", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } /* endswitch */ SQLWarning precisionLost = new SQLWarning( Messages .getString("ResultSet.Precision_lost_converting_TIMESTAMP_to_Time_with_getTime()_on_column__261") //$NON-NLS-1$ + columnIndex + "(" + timeColField + ")."); /* * if (this.warningChain == null) { this.warningChain = * precisionLost; } else { * this.warningChain.setNextWarning(precisionLost); } */ } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATETIME) { hr = StringUtils.getInt(timeAsBytes, offset + 11, offset + 13); min = StringUtils.getInt(timeAsBytes, offset + 14, offset + 16); sec = StringUtils.getInt(timeAsBytes, offset + 17, offset + 19); SQLWarning precisionLost = new SQLWarning( Messages .getString("ResultSet.Precision_lost_converting_DATETIME_to_Time_with_getTime()_on_column__264") //$NON-NLS-1$ + (columnIndex + 1) + "(" + timeColField + ")."); /* * if (this.warningChain == null) { this.warningChain = * precisionLost; } else { * this.warningChain.setNextWarning(precisionLost); } */ } else if (timeColField.getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) { return rs.fastTimeCreate(null, 0, 0, 0); // midnight on the // given // date } else { // convert a String to a Time if ((length != 5) && (length != 8)) { throw SQLError.createSQLException(Messages .getString("ResultSet.Bad_format_for_Time____267") //$NON-NLS-1$ + new String(timeAsBytes) + Messages.getString("ResultSet.___in_column__268") + (columnIndex + 1), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } hr = StringUtils.getInt(timeAsBytes, offset + 0, offset + 2); min = StringUtils.getInt(timeAsBytes, offset + 3, offset + 5); sec = (length == 5) ? 0 : StringUtils.getInt(timeAsBytes, offset + 6, offset + 8); } Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew(); if (!rs.useLegacyDatetimeCode) { return rs.fastTimeCreate(targetCalendar, hr, min, sec); } synchronized (sessionCalendar) { return TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, rs.fastTimeCreate(sessionCalendar, hr, min, sec), conn.getServerTimezoneTZ(), tz, rollForward); } } catch (Exception ex) { SQLException sqlEx = SQLError.createSQLException(ex.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); sqlEx.initCause(ex); throw sqlEx; } } public abstract Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException; protected Timestamp getTimestampFast(int columnIndex, byte[] timestampAsBytes, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException { try { Calendar sessionCalendar = conn.getUseJDBCCompliantTimezoneShift() ? conn .getUtcCalendar() : rs.getCalendarInstanceForSessionOrNew(); synchronized (sessionCalendar) { boolean allZeroTimestamp = true; boolean onlyTimePresent = false; for (int i = 0; i < length; i++) { if (timestampAsBytes[offset + i] == ':') { onlyTimePresent = true; break; } } for (int i = 0; i < length; i++) { byte b = timestampAsBytes[offset + i]; if (b == ' ' || b == '-' || b == '/') { onlyTimePresent = false; } if (b != '0' && b != ' ' && b != ':' && b != '-' && b != '/' && b != '.') { allZeroTimestamp = false; break; } } if (!onlyTimePresent && allZeroTimestamp) { if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL .equals(conn.getZeroDateTimeBehavior())) { return null; } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION .equals(conn.getZeroDateTimeBehavior())) { throw SQLError .createSQLException( "Value '" + timestampAsBytes + "' can not be represented as java.sql.Timestamp", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimestampCreate(tz, 1, 1, 1, 0, 0, 0, 0); } // We're left with the case of 'round' to a date Java _can_ // represent, which is '0001-01-01'. return rs.fastTimestampCreate(null, 1, 1, 1, 0, 0, 0, 0); } else if (this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_YEAR) { if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimestampCreate(tz, StringUtils .getInt(timestampAsBytes, offset, 4), 1, 1, 0, 0, 0, 0); } return TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, rs.fastTimestampCreate( sessionCalendar, StringUtils.getInt( timestampAsBytes, offset, 4), 1, 1, 0, 0, 0, 0), conn.getServerTimezoneTZ(), tz, rollForward); } else { if (timestampAsBytes[offset + length - 1] == '.') { length--; } // Convert from TIMESTAMP or DATE int year = 0; int month = 0; int day = 0; int hour = 0; int minutes = 0; int seconds = 0; int nanos = 0; switch (length) { case 29: case 26: case 25: case 24: case 23: case 22: case 21: case 20: case 19: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(timestampAsBytes, offset + 5, offset + 7); day = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10); hour = StringUtils.getInt(timestampAsBytes, offset + 11, offset + 13); minutes = StringUtils.getInt(timestampAsBytes, offset + 14, offset + 16); seconds = StringUtils.getInt(timestampAsBytes, offset + 17, offset + 19); nanos = 0; if (length > 19) { int decimalIndex = -1; for (int i = 0; i < length; i++) { if (timestampAsBytes[offset + i] == '.') { decimalIndex = i; } } if (decimalIndex != -1) { if ((decimalIndex + 2) <= length) { nanos = StringUtils.getInt( timestampAsBytes, decimalIndex + 1, offset + length); int numDigits = (offset + length) - (decimalIndex + 1); if (numDigits < 9) { int factor = (int)(Math.pow(10, 9 - numDigits)); nanos = nanos * factor; } } else { throw new IllegalArgumentException(); // re-thrown // further // down // with // a // much better error message } } } break; } case 14: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6); day = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8); hour = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10); minutes = StringUtils.getInt(timestampAsBytes, offset + 10, offset + 12); seconds = StringUtils.getInt(timestampAsBytes, offset + 12, offset + 14); break; } case 12: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); if (year <= 69) { year = (year + 100); } year += 1900; month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4); day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6); hour = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8); minutes = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10); seconds = StringUtils.getInt(timestampAsBytes, offset + 10, offset + 12); break; } case 10: { boolean hasDash = false; for (int i = 0; i < length; i++) { if (timestampAsBytes[offset + i] == '-') { hasDash = true; break; } } if ((this.metadata[columnIndex].getMysqlType() == MysqlDefs.FIELD_TYPE_DATE) || hasDash) { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(timestampAsBytes, offset + 5, offset + 7); day = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10); hour = 0; minutes = 0; } else { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); if (year <= 69) { year = (year + 100); } month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4); day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6); hour = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8); minutes = StringUtils.getInt(timestampAsBytes, offset + 8, offset + 10); year += 1900; // two-digit year } break; } case 8: { boolean hasColon = false; for (int i = 0; i < length; i++) { if (timestampAsBytes[offset + i] == ':') { hasColon = true; break; } } if (hasColon) { hour = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); minutes = StringUtils.getInt(timestampAsBytes, offset + 3, offset + 5); seconds = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8); year = 1970; month = 1; day = 1; break; } year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 4); month = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6); day = StringUtils.getInt(timestampAsBytes, offset + 6, offset + 8); year -= 1900; month--; break; } case 6: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); if (year <= 69) { year = (year + 100); } year += 1900; month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4); day = StringUtils.getInt(timestampAsBytes, offset + 4, offset + 6); break; } case 4: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); if (year <= 69) { year = (year + 100); } month = StringUtils.getInt(timestampAsBytes, offset + 2, offset + 4); day = 1; break; } case 2: { year = StringUtils.getInt(timestampAsBytes, offset + 0, offset + 2); if (year <= 69) { year = (year + 100); } year += 1900; month = 1; day = 1; break; } default: throw new java.sql.SQLException( "Bad format for Timestamp '" + new String(timestampAsBytes) + "' in column " + (columnIndex + 1) + ".", SQLError.SQL_STATE_ILLEGAL_ARGUMENT); } if (!rs.useLegacyDatetimeCode) { return TimeUtil.fastTimestampCreate(tz, year, month, day, hour, minutes, seconds, nanos); } return TimeUtil .changeTimezone(conn, sessionCalendar, targetCalendar, rs.fastTimestampCreate( sessionCalendar, year, month, day, hour, minutes, seconds, nanos), conn .getServerTimezoneTZ(), tz, rollForward); } } } catch (Exception e) { SQLException sqlEx = SQLError.createSQLException("Cannot convert value '" + getString(columnIndex, "ISO8859_1", conn) + "' from column " + (columnIndex + 1) + " to TIMESTAMP.", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, this.exceptionInterceptor); sqlEx.initCause(e); throw sqlEx; } } public abstract Timestamp getTimestampFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, ConnectionImpl conn, ResultSetImpl rs) throws SQLException; /** * Could the column value at the given index (which starts at 0) be * interpreted as a floating-point number (has +/-/E/e in it)? * * @param index * of the column value (starting at 0) to check. * * @return true if the column value at the given index looks like it might * be a floating-point number, false if not. * * @throws SQLException * if an error occurs */ public abstract boolean isFloatingPointNumber(int index) throws SQLException; /** * Is the column value at the given index (which starts at 0) NULL? * * @param index * of the column value (starting at 0) to check. * * @return true if the column value is NULL, false if not. * * @throws SQLException * if an error occurs */ public abstract boolean isNull(int index) throws SQLException; /** * Returns the length of the column at the given index (which starts at 0). * * @param index * of the column value (starting at 0) for which to return the * length. * @return the length of the requested column, 0 if null (clients of this * interface should use isNull() beforehand to determine status of * NULL values in the column). * * @throws SQLException */ public abstract long length(int index) throws SQLException; /** * Sets the given column value (only works currently with * ByteArrayRowHolder). * * @param index * index of the column value (starting at 0) to set. * @param value * the (raw) value to set * * @throws SQLException * if an error occurs, or the concrete RowHolder doesn't support * this operation. */ public abstract void setColumnValue(int index, byte[] value) throws SQLException; public ResultSetRow setMetadata(Field[] f) throws SQLException { this.metadata = f; return this; } public abstract int getBytesSize(); }
yyuu/libmysql-java
src/com/mysql/jdbc/ResultSetRow.java
Java
gpl-2.0
42,740
/* * This is the source code of Hermes for Android v. 1.3.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2014. */ package org.hermes.ui.Components; import android.graphics.Canvas; import android.graphics.Paint; import org.hermes.android.AndroidUtilities; public class ProgressView { private Paint innerPaint; private Paint outerPaint; public float currentProgress = 0; public int width; public int height; public float progressHeight = AndroidUtilities.dp(2.0f); public ProgressView() { innerPaint = new Paint(); outerPaint = new Paint(); } public void setProgressColors(int innerColor, int outerColor) { innerPaint.setColor(innerColor); outerPaint.setColor(outerColor); } public void setProgress(float progress) { currentProgress = progress; if (currentProgress < 0) { currentProgress = 0; } else if (currentProgress > 1) { currentProgress = 1; } } public void draw(Canvas canvas) { canvas.drawRect(0, height / 2 - progressHeight / 2.0f, width, height / 2 + progressHeight / 2.0f, innerPaint); canvas.drawRect(0, height / 2 - progressHeight / 2.0f, width * currentProgress, height / 2 + progressHeight / 2.0f, outerPaint); } }
ur0/hermes
TMessagesProj/src/main/java/org/hermes/ui/Components/ProgressView.java
Java
gpl-2.0
1,427
/* ## Copyright (C) 2004-2007 Javier Fernández Baldomero, Mancia Anguita López ## ## This program is free software ## ---------------------------------------------------- ## Author: Javier Fernández Baldomero <jfernand@ugr.es>, Mancia Anguita López ## Keywords: parallel MPI ## ---------------------------------------------------- */ //#define NAME LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS /* * ---------------------------------------------------- * MPITB constant for corresponding MPI symbol * MPI_Attr_get(MPI_COMM_WORLD, LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS) * ---------------------------------------------------- * In order to be more or less implementation-independent, * we try to define all attrkvals that we know of in all implementations * and make them MPI_ANY_TAG==-1 if not defined in this implementation * which will make it fail if used in the incorrect implementation * CAVEAT: notice we rely on the implementation #defining all these symbols * (ie, they're not constants or functions) * ---------------------------------------------------- */ #include "mpitb.h" // buildblocks NARGCHK, etc #include "hConst.h" // GEN_INT/RET_INT system #ifndef LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS #define LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS MPI_ANY_TAG #endif #define NAME LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS GEN_1_INT(NAME) // works if #defined & #undef LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS // doesn't harm if enum DEFUN_DLD(NAME, args, nargout, "LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS MPITB constant for corresp. MPI symbol\n\ \n\ SEE ALSO: MPI_ATTRKVALS\n\ \n\ ") { NARGCHK (NAME,0) RET_1_INT }
ssrb/mpitb
src/LAM_MPI_SSI_COLL_SHMEM_NUM_SEGMENTS.cc
C++
gpl-2.0
1,627
package s03; public class AmStramGram { public static void main(String[] args) { int n=7, k=5; if (args.length == 2) { n = Integer.parseInt(args[0]); k = Integer.parseInt(args[1]); } System.out.println("Winner is " + winnerAmStramGram(n, k)); } // ---------------------------------------------------------- // "Josephus problem" with persons numbered 1..n // Removes every k-th persons (ie skip k-1 persons) // PRE: n>=1, k>=1 // RETURNS: the survivor // Example: n=4, k=2: // '1234 => 1'234 => 1'(2)34 => 1'34 // 1'34 => 13'4 => 13'(4) => 13' // '13 => 1'3 => 1'(3) => 1' ===> survivor: 1 public static int winnerAmStramGram(int n, int k) { List l = new List(); ListItr li = new ListItr(l); for(int i=1;i<=n;i++) { li.insertAfter(i); li.goToNext(); } li.goToFirst(); int saveValue=0; while(l.isEmpty()==false) { int i=k; while(i>1) { li.goToNext(); if(li.isLast()) { li.goToFirst(); } i--; } li.removeAfter(); if(li.isLast()) { li.goToFirst(); } if (li.succ!=null) saveValue=li.consultAfter(); } return saveValue; } // ---------------------------------------------------------- }
liTTleSiG/Algorithmique
src/s03/AmStramGram.java
Java
gpl-2.0
1,360
/*! \file main.cpp \author Standa Kubín \date 31.03.2016 \brief server aplikace pro řízení okenních rolet */ #include <QCoreApplication> #include <QSharedPointer> #include <QThread> #include <QFile> #include <QUdpSocket> #include <QDebug> #include <QSemaphore> class GPIO_CONTROL : public QObject { Q_OBJECT public: enum class GPIO_Type { INPUT, //!< vstup OUTPUT //!< výstup }; GPIO_CONTROL(QObject *pParent, quint16 nGPIO, GPIO_Type eType); virtual ~GPIO_CONTROL(); //! vrátí hodnotu GPIO bool GetValue(); //! nastaví hodnotu GPIO void SetValue(bool bValue); private: QFile m_oFile; //!< soubor pro zápis do nebo čtení z GPIO GPIO_Type m_eGPIO_Type; //!< typ přístupu na GPIO }; class BLIND_THREAD : public QThread { Q_OBJECT public: BLIND_THREAD(quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore); virtual ~BLIND_THREAD(); //! ukončí thread void Stop() { m_bStop = true; } //! vrací true, pokud thread běží bool IsRunning() const { return m_bRunning; } //! vrátí pozici rolety qint32 GetValuePercent() const { return (m_nTargetPosition * 100) / m_sc_nMaximumPositionValue; } //! nastaví pozici rolety void SetValuePercent(qint32 nValuePercent) { m_nTargetPosition = (m_sc_nMaximumPositionValue * nValuePercent) / 100; } //! spustí kalibraci void Calibre() { m_bCalibre = true; } protected: //! vstupní bod nového threadu virtual void run(); private: enum class ACTION { None, //!< neprobíhá žádná akce Calibration, //!< probíhá kalibrace Movement //!< probíhá standardní pohyb na nastavenou pozici }; enum class DIRECTION { DOWN, //!< roleta pojede nahoru UP //!< roleta pojede dolu }; static const quint32 m_sc_nMaximumPositionValue = 10240; //!< počet impulsů krokového motoru pro sjetí rotety ze shora dolů QScopedPointer<GPIO_CONTROL> m_oPulse; //!< GPIO pro řízení otáčení QScopedPointer<GPIO_CONTROL> m_oDirection; //!< GPIO pro nastavení směru otáčení QScopedPointer<GPIO_CONTROL> m_oFB; //!< GPIO pro získání stavu rulety QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources bool m_bRunning; //!< příznak běžícího threadu bool m_bStop; //!< příznak pro ukončení threadu bool m_bCalibre; //!< požadavek na spuštění kalibrace rolety quint32 m_nActualPosition; //!< aktuální pozice rolety quint32 m_nTargetPosition; //!< cílová pozice rolety quint32 m_nTargetPositionWorkingThread; //!< cílová pozice rolety pro m_eAction == ACTION::Movement ACTION m_eAction; //!< aktuální práce threadu //! nastaví směr pohybu void SetDirection(DIRECTION eDirection); //! vygeneruje impuls void GeneratePulse(); //! vrací true, pokud je roleta úplně nahoře bool IsBlindUp(); }; class BLIND : public QObject { Q_OBJECT public: BLIND(QObject *pParent, quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore); virtual ~BLIND() {} //! vrátí pozici rolety qint32 GetValuePercent() const; //! nastaví pozici rolety void SetValuePercent(qint32 nValuePercent); private: QScopedPointer<BLIND_THREAD> m_oWorkingThread; //!< thread řídící motor QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources }; class BLINDS_CONTROLLER : public QObject { Q_OBJECT public: BLINDS_CONTROLLER(QObject *pParent = Q_NULLPTR); virtual ~BLINDS_CONTROLLER() {} private: struct Client { Client() : m_nPort(-1) {} Client(QHostAddress Address, qint32 nPort) : m_Address(Address), m_nPort(nPort) {} QHostAddress m_Address; //!< client address qint32 m_nPort; //!< client port inline bool operator==(const Client& X){ return X.m_Address == m_Address && X.m_nPort == m_nPort; } inline bool operator!=(const Client& X){ return X.m_Address != m_Address || X.m_nPort != m_nPort; } }; QHash<qint32, QSharedPointer<BLIND> > m_arrBlinds; //!< pole tříd pro řízení rolet QUdpSocket m_oUDP_SocketForReceiving; //!< UDP socket bound to the specific port intended for window blind settings receiving QUdpSocket m_oUDP_SocketForSending; //!< UDP socket intended for clients information about the new states QSharedPointer<QSemaphore> m_Semaphore; //!< it controls access to the common HW resources (it limites the number of simultaneously driven window blinds) QList<Client> m_arrClients; //!< list of registered clients (these clients are informed about the changes) private slots: // reakce na příjem UDP paketu void OnUDP_ProcessPendingMessage(); }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QScopedPointer<BLINDS_CONTROLLER> oBLINDS_CONTROLLER(new BLINDS_CONTROLLER()); return a.exec(); } GPIO_CONTROL::GPIO_CONTROL(QObject *pParent, quint16 nGPIO, GPIO_Type eType) : QObject(pParent), m_eGPIO_Type(eType) { // inicializujeme IO QFile oFile("/sys/class/gpio/export"); if(oFile.open(QIODevice::WriteOnly)) { QString strGPIO = QString::number(nGPIO); QString strDirection = "in"; QIODevice::OpenModeFlag eOpenModeFlag = QIODevice::ReadOnly; if(eType == GPIO_Type::OUTPUT) { strDirection = "out"; eOpenModeFlag = QIODevice::WriteOnly; } oFile.write(strGPIO.toLatin1()); oFile.flush(); oFile.close(); oFile.setFileName("/sys/class/gpio/gpio" + strGPIO + "/direction"); forever { if(oFile.open(QIODevice::WriteOnly)) { oFile.write(QString(strDirection).toLatin1()); oFile.flush(); oFile.close(); // otevřeme soubor pro nastavování nebo čtení hodnot m_oFile.setFileName("/sys/class/gpio/gpio" + strGPIO + "/value"); if(!m_oFile.open(eOpenModeFlag)) { qDebug() << "cannot open file" << m_oFile.fileName(); } break; } else { qDebug() << "cannot open file" << oFile.fileName(); } } } else { qDebug() << "cannot open file" << oFile.fileName(); } } GPIO_CONTROL::~GPIO_CONTROL() { m_oFile.close(); } bool GPIO_CONTROL::GetValue() { if(m_oFile.isOpen()) { QByteArray arrData = m_oFile.read(1); if(arrData.count()) { return arrData.at(0) == '1'; } } return false; } void GPIO_CONTROL::SetValue(bool bValue) { if(m_eGPIO_Type == GPIO_Type::OUTPUT) { if(m_oFile.isOpen()) { m_oFile.write(QString(bValue ? "1" : "0").toLatin1()); m_oFile.flush(); } } } BLIND_THREAD::BLIND_THREAD(quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore) : QThread() { m_oPulse.reset(new GPIO_CONTROL(this, nGPIO_Pulse, GPIO_CONTROL::GPIO_Type::OUTPUT)); m_oDirection.reset(new GPIO_CONTROL(this, nGPIO_Direction, GPIO_CONTROL::GPIO_Type::OUTPUT)); m_oFB.reset(new GPIO_CONTROL(this, nGPIO_FB, GPIO_CONTROL::GPIO_Type::INPUT)); m_Semaphore = Semaphore; m_bRunning = false; m_bStop = false; m_bCalibre = false; m_nActualPosition = 0; m_nTargetPosition = 0; m_nTargetPositionWorkingThread = 0; m_eAction = ACTION::None; // spustíme kalibraci Calibre(); } BLIND_THREAD::~BLIND_THREAD() { if(IsRunning()) { Stop(); for(qint32 nTimeoutCounter = 0; nTimeoutCounter < 1000 && IsRunning(); nTimeoutCounter++) { QThread::msleep(1); } Q_ASSERT(!IsRunning()); } } void BLIND_THREAD::run() { m_bRunning = true; while(!m_bStop) { switch(m_eAction) { case ACTION::Calibration: if(IsBlindUp()) { // hotovo m_eAction = ACTION::None; m_nActualPosition = 0; m_bCalibre = false; // it releases HW resource m_Semaphore.data()->release(); } else { GeneratePulse(); } break; case ACTION::Movement: if(m_nActualPosition == m_nTargetPositionWorkingThread) { // hotovo m_eAction = ACTION::None; // it releases HW resource m_Semaphore.data()->release(); } if(m_nActualPosition < m_nTargetPositionWorkingThread) { GeneratePulse(); m_nActualPosition++; } if(m_nActualPosition > m_nTargetPositionWorkingThread) { GeneratePulse(); m_nActualPosition--; } break; case ACTION::None: if(m_bCalibre) { // it tries to acquire HW resource if(m_Semaphore.isNull() || !m_Semaphore.data()->tryAcquire()) { break; } // kalibrace m_eAction = ACTION::Calibration; SetDirection(DIRECTION::UP); break; } if(m_nActualPosition != m_nTargetPosition) { // it tries to acquire HW resource if(m_Semaphore.isNull() || !m_Semaphore.data()->tryAcquire()) { break; } // pohyb m_eAction = ACTION::Movement; m_nTargetPositionWorkingThread = m_nTargetPosition; SetDirection(m_nActualPosition < m_nTargetPositionWorkingThread ? DIRECTION::DOWN : DIRECTION::UP); break; } QThread::msleep(1); break; } } m_bRunning = false; } void BLIND_THREAD::SetDirection(BLIND_THREAD::DIRECTION eDirection) { if(!m_oDirection.isNull()) { m_oDirection.data()->SetValue(eDirection == DIRECTION::DOWN ? 1 : 0); } } void BLIND_THREAD::GeneratePulse() { // maximální rychlost = 1 KHz if(!m_oPulse.isNull()) { m_oPulse.data()->SetValue(true); QThread::usleep(500); m_oPulse.data()->SetValue(false); QThread::usleep(500); } } bool BLIND_THREAD::IsBlindUp() { if(!m_oFB.isNull()) { return m_oFB.data()->GetValue(); } return false; } BLIND::BLIND(QObject *pParent, quint16 nGPIO_Pulse, quint16 nGPIO_Direction, quint16 nGPIO_FB, QSharedPointer<QSemaphore> Semaphore) : QObject(pParent) { m_oWorkingThread.reset(new BLIND_THREAD(nGPIO_Pulse, nGPIO_Direction, nGPIO_FB, Semaphore)); // odstartujeme thread m_oWorkingThread.data()->start(); } qint32 BLIND::GetValuePercent() const { if(!m_oWorkingThread.isNull()) { return m_oWorkingThread.data()->GetValuePercent(); } return 0; } void BLIND::SetValuePercent(qint32 nValuePercent) { if(!m_oWorkingThread.isNull()) { m_oWorkingThread.data()->SetValuePercent(nValuePercent); } } BLINDS_CONTROLLER::BLINDS_CONTROLLER(QObject *pParent) : QObject(pParent) { // it sets the maximum count of simultaneously driven window blinds m_Semaphore.reset(new QSemaphore(2)); // nastavíme rolety m_arrBlinds[1] = QSharedPointer<BLIND>(new BLIND(this, 178, 193, 199, m_Semaphore)); // nastavíme UDP soket pro příjem požaadvků connect(&m_oUDP_SocketForReceiving, SIGNAL(readyRead()), this, SLOT(OnUDP_ProcessPendingMessage()), Qt::UniqueConnection); if(!m_oUDP_SocketForReceiving.bind(5674)) { qDebug() << "cannot bind UDP communication port"; } } void BLINDS_CONTROLLER::OnUDP_ProcessPendingMessage() { QByteArray arrDatagram; QHostAddress SenderAddress; quint16 nSenderPort = 0; while(m_oUDP_SocketForReceiving.hasPendingDatagrams()) { arrDatagram.resize(m_oUDP_SocketForReceiving.pendingDatagramSize()); if(m_oUDP_SocketForReceiving.readDatagram(arrDatagram.data(), arrDatagram.size(), &SenderAddress, &nSenderPort) == -1) { qDebug() << "unable to read UDP datagram"; } else { QStringList arr_strMessages = QString(arrDatagram).split("#"); foreach(QString strMessage, arr_strMessages) { QStringList arr_strMessageData = strMessage.split(";"); if(arr_strMessageData.count() >= 1) { if(arr_strMessageData.at(0) == "set_blind") { if(arr_strMessageData.count() >= 4) { qint32 nID = arr_strMessageData.at(1).toInt(); qint32 nPercentValue = arr_strMessageData.at(2).toInt(); if(m_arrBlinds.contains(nID)) { if(nPercentValue > 100) { nPercentValue = 100; } if(nPercentValue < 0) { nPercentValue = 0; } qDebug() << "blind ID" << nID << "value" << nPercentValue; if(!m_arrBlinds[nID].isNull()) { m_arrBlinds[nID].data()->SetValuePercent(nPercentValue); // send the new value to the other clients Client ClientHasSetTheValue(SenderAddress, arr_strMessageData.at(3).toInt()); foreach(Client ClientToBeInformed, m_arrClients) { if(ClientToBeInformed != ClientHasSetTheValue) { if(!m_oUDP_SocketForSending.writeDatagram(QByteArray(QString("blind_position;" + arr_strMessageData.at(1) + ";" + arr_strMessageData.at(2)).toLatin1() + "#"), ClientToBeInformed.m_Address, ClientToBeInformed.m_nPort) == -1) { qDebug() << "error while sending the new window blind position"; } } } } } else { qDebug() << "unknown blind ID"; } } else { qDebug() << "unknown UDP data format"; } } if(arr_strMessageData.at(0) == "register") { if(arr_strMessageData.count() >= 2) { Client NewClientToBeRegistrated(SenderAddress, arr_strMessageData.at(1).toInt()); qDebug() << "new client registration attempt, client address" << NewClientToBeRegistrated.m_Address << "port" << NewClientToBeRegistrated.m_nPort; if(!m_arrClients.contains(NewClientToBeRegistrated)) { m_arrClients.append(NewClientToBeRegistrated); // refresh the client by the actual window blind positions QHashIterator<qint32, QSharedPointer<BLIND> > iBlinds(m_arrBlinds); while(iBlinds.hasNext()) { iBlinds.next(); if(!m_oUDP_SocketForSending.writeDatagram(QByteArray(QString("blind_position;" + QString::number(iBlinds.key()) + ";" + QString::number(iBlinds.value().data()->GetValuePercent()) + "#").toLatin1()), NewClientToBeRegistrated.m_Address, NewClientToBeRegistrated.m_nPort) == -1) { qDebug() << "error while sending the new window blind position"; } } } } else { qDebug() << "unknown UDP data format"; } } } else { qDebug() << "unknown UDP data format"; } } } } } #include "main.moc"
kubins/WindowBlindsServer
WindowBlindsServer/main.cpp
C++
gpl-2.0
17,517
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Tools\Console\Command; use Symfony\Component\Console\Input\InputArgument, Symfony\Component\Console\Input\InputOption, Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface; use Doctrine\DBAL\Platforms\Keywords\ReservedKeywordsValidator; class ReservedWordsCommand extends Command { private $keywordListClasses = array( 'mysql' => 'Doctrine\DBAL\Platforms\Keywords\MySQLKeywords', 'mssql' => 'Doctrine\DBAL\Platforms\Keywords\MsSQLKeywords', 'sqlite' => 'Doctrine\DBAL\Platforms\Keywords\SQLiteKeywords', 'pgsql' => 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords', 'oracle' => 'Doctrine\DBAL\Platforms\Keywords\OracleKeywords', 'db2' => 'Doctrine\DBAL\Platforms\Keywords\DB2Keywords', ); /** * If you want to add or replace a keywords list use this command * * @param string $name * @param string $class */ public function setKeywordListClass($name, $class) { $this->keywordListClasses[$name] = $class; } /** * @see Console\Command\Command */ protected function configure() { $this ->setName('dbal:reserved-words') ->setDescription('Checks if the current database contains identifiers that are reserved.') ->setDefinition(array( new InputOption( 'list', 'l', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Keyword-List name.' ) )) ->setHelp(<<<EOT Checks if the current database contains tables and columns with names that are identifiers in this dialect or in other SQL dialects. By default SQLite, MySQL, PostgreSQL, MsSQL and Oracle keywords are checked: <info>%command.full_name%</info> If you want to check against specific dialects you can pass them to the command: <info>%command.full_name% mysql pgsql</info> The following keyword lists are currently shipped with Doctrine: * mysql * pgsql * sqlite * oracle * mssql * db2 (Not checked by default) EOT ); } /** * @see Console\Command\Command */ protected function execute(InputInterface $input, OutputInterface $output) { /* @var $conn \Doctrine\DBAL\Connection */ $conn = $this->getHelper('db')->getConnection(); $keywordLists = (array)$input->getOption('list'); if ( ! $keywordLists) { $keywordLists = array('mysql', 'pgsql', 'sqlite', 'oracle', 'mssql'); } $keywords = array(); foreach ($keywordLists as $keywordList) { if (!isset($this->keywordListClasses[$keywordList])) { throw new \InvalidArgumentException( "There exists no keyword list with name '" . $keywordList . "'. ". "Known lists: " . implode(", ", array_keys($this->keywordListClasses)) ); } $class = $this->keywordListClasses[$keywordList]; $keywords[] = new $class; } $output->write('Checking keyword violations for <comment>' . implode(", ", $keywordLists) . "</comment>...", true); /* @var $schema \Doctrine\DBAL\Schema\Schema */ $schema = $conn->getSchemaManager()->createSchema(); $visitor = new ReservedKeywordsValidator($keywords); $schema->visit($visitor); $violations = $visitor->getViolations(); if (count($violations) == 0) { $output->write("No reserved keywords violations have been found!", true); } else { $output->write('There are <error>' . count($violations) . '</error> reserved keyword violations in your database schema:', true); foreach ($violations as $violation) { $output->write(' - ' . $violation, true); } } } }
jeanlopes7/mostra-ifrs-poa
libraries/Doctrine/DBAL/Tools/Console/Command/ReservedWordsCommand.php
PHP
gpl-2.0
4,931
/* * Copyright (C) 2016-2022 ActionTech. * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher. */ package com.actiontech.dble.services.manager.response; import com.actiontech.dble.config.Fields; import com.actiontech.dble.config.model.SystemConfig; import com.actiontech.dble.net.mysql.*; import com.actiontech.dble.services.manager.ManagerService; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import static com.actiontech.dble.backend.mysql.PacketUtil.getField; import static com.actiontech.dble.backend.mysql.PacketUtil.getHeader; public final class ShowLoadDataErrorFile { private ShowLoadDataErrorFile() { } private static final int FIELD_COUNT = 1; private static final ResultSetHeaderPacket HEADER = getHeader(FIELD_COUNT); private static final FieldPacket[] FIELDS = new FieldPacket[FIELD_COUNT]; private static final EOFPacket EOF = new EOFPacket(); public static void execute(ManagerService service) { int i = 0; byte packetId = 0; HEADER.setPacketId(++packetId); FIELDS[i] = getField("error_load_data_file", Fields.FIELD_TYPE_VAR_STRING); FIELDS[i].setPacketId(++packetId); EOF.setPacketId(++packetId); ByteBuffer buffer = service.allocate(); // write header buffer = HEADER.write(buffer, service, true); // write fields for (FieldPacket field : FIELDS) { buffer = field.write(buffer, service, true); } // write eof buffer = EOF.write(buffer, service, true); // write rows String filePath = SystemConfig.getInstance().getHomePath() + File.separator + "temp" + File.separator + "error"; List<String> errorFileList = new ArrayList<>(); getErrorFile(filePath, errorFileList); for (String errorFilePath : errorFileList) { RowDataPacket row = new RowDataPacket(FIELD_COUNT); row.add(errorFilePath.getBytes()); row.setPacketId(++packetId); buffer = row.write(buffer, service, true); } // write last eof EOFRowPacket lastEof = new EOFRowPacket(); lastEof.setPacketId(++packetId); lastEof.write(buffer, service); } private static void getErrorFile(String filePath, List<String> errorFileList) { File dirFile = new File(filePath); if (!dirFile.exists()) { return; } File[] fileList = dirFile.listFiles(); if (fileList != null) { for (File file : fileList) { if (file.isFile() && file.exists()) { errorFileList.add(file.getPath()); } else if (file.isDirectory()) { getErrorFile(file.getPath(), errorFileList); } } } } }
actiontech/dble
src/main/java/com/actiontech/dble/services/manager/response/ShowLoadDataErrorFile.java
Java
gpl-2.0
2,876
// -*- c++ -*- //***************************************************************************** /** @file: CErrorInfo.cc * * @author Alexander Dreyer * @date 2006-03-06 * * This file defines the class CErrorInfo, which to conver error coedes to * meaningful text. * * @par Copyright: * (c) 2006 by The PolyBoRi Team **/ //***************************************************************************** // load header file #include <polybori/except/CErrorInfo.h> BEGIN_NAMESPACE_PBORI CErrorInfo::errortext_type CErrorInfo::pErrorText[CTypes::last_error]; // default constructor (call once for text initialization) CErrorInfo::CErrorInfo() { PBORI_TRACE_FUNC( "CErrorInfo()" ); pErrorText[CTypes::alright] = "No error."; pErrorText[CTypes::failed] = "Unspecified error."; pErrorText[CTypes::no_ring] = "No polynomial ring structure defined."; pErrorText[CTypes::invalid] = "Invalid operation called."; pErrorText[CTypes::out_of_bounds] = "Variable index out of bounds."; pErrorText[CTypes::io_error] = "I/O error."; pErrorText[CTypes::monomial_zero] = "Monomial operation resulted in zero."; pErrorText[CTypes::illegal_on_zero] = "Illegal operation on zero diagram or (sub-)polynomial."; pErrorText[CTypes::division_by_zero] = "Division by zero."; pErrorText[CTypes::invalid_ite] = "Node index must be smaller than top indices of then- and else-branch."; pErrorText[CTypes::not_implemented] = "Sorry! Functionality not implemented yet."; pErrorText[CTypes::matrix_size_exceeded] = "Built-in matrix-size exceeded!"; } // convert error code to description text CErrorInfo::errortext_type CErrorInfo::text(errornum_type num) { PBORI_TRACE_FUNC( "CErrorInfo::text(errornum_type) const" ); if PBORI_UNLIKELY(num < 0 || num >= CTypes::last_error) return "Unknown error occured."; return pErrorText[num]; } // initialize array of error names static CErrorInfo init_error_info; END_NAMESPACE_PBORI
BRiAl/BRiAl
libbrial/src/CErrorInfo.cc
C++
gpl-2.0
1,958
<?php /** * @package AcyMailing for Joomla! * @version 4.9.0 * @author acyba.com * @copyright (C) 2009-2015 ACYBA S.A.R.L. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php class listsmailType{ var $type = 'news'; function load(){ $db = JFactory::getDBO(); $query = 'SELECT a.listid as listid,COUNT(a.mailid) as total FROM `#__acymailing_mail` as c'; $query .= ' JOIN `#__acymailing_listmail` as a ON a.mailid = c.mailid'; $query .= ' WHERE c.type = \''.$this->type.'\' GROUP BY a.listid'; $db->setQuery($query); $alllists = $db->loadObjectList('listid'); $allnames = array(); if(!empty($alllists)){ $db->setQuery('SELECT name,listid FROM `#__acymailing_list` WHERE listid IN ('.implode(',',array_keys($alllists)).') ORDER BY ordering ASC'); $allnames = $db->loadObjectList('listid'); } $this->values = array(); $this->values[] = JHTML::_('select.option', '0', JText::_('ALL_LISTS') ); foreach($allnames as $listid => $oneName){ $this->values[] = JHTML::_('select.option', $listid, $oneName->name.' ( '.$alllists[$listid]->total.' )' ); } } function display($map,$value){ $this->load(); return JHTML::_('select.genericlist', $this->values, $map, 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', (int) $value ); } }
tpiechota/gmusicireland
administrator/components/com_acymailing/types/listsmail.php
PHP
gpl-2.0
1,402
<?php function wooccm_ccf_custom_checkout_process() { global $woocommerce; $options = get_option( 'wccs_settings' ); if( count( $options['buttons'] ) == 0 ) return; foreach( $options['buttons'] as $btn ) { foreach( $woocommerce->cart->cart_contents as $key => $values ) { $multiproductsx = $btn['single_p']; $show_field_single = $btn['single_px']; $multiproductsx_cat = $btn['single_p_cat']; $show_field_single_cat = $btn['single_px_cat']; $productsarraycm[] = $values['product_id']; // Products // hide field // show field without more if( !empty($btn['single_px']) && empty($btn['more_content']) ) { $show_field_array = explode('||',$show_field_single); if( in_array($values['product_id'], $show_field_array) && ( count($woocommerce->cart->cart_contents) < 2) ) { if( !empty ($btn['checkbox']) && !empty( $btn['label'] ) && ($btn['type'] !== 'changename') ) { if( empty( $_POST[''.$btn['cow'].''] ) ) { wc_add_notice( __( '<strong>'.wpml_string_wccm_pro($btn['label']).'</strong> is a required field.' ), 'error' ); } } } } // Category // hide field $terms = get_the_terms( $values['product_id'], 'product_cat' ); if( !empty( $terms ) ) { foreach( $terms as $term ) { $categoryarraycm[] = $term->slug; // without more // show field without more if( !empty($btn['single_px_cat']) && empty($btn['more_content']) ) { $show_field_array_cat = explode('||',$show_field_single_cat); if( in_array($term->slug, $show_field_array_cat) && ( count($woocommerce->cart->cart_contents) < 2 ) ) { if( !empty ($btn['checkbox']) && !empty( $btn['label'] ) && ($btn['type'] !== 'changename') ) { if( empty( $_POST[''.$btn['cow'].''] ) ) { wc_add_notice( __( '<strong>'.wpml_string_wccm_pro($btn['label']).'</strong> is a required field.' ), 'error' ); } } } } } } } // end cart // =========================================================================================== // Products // hide field // show field with more if( !empty($btn['single_px']) && !empty($btn['more_content']) ) { $show_field_array = explode('||',$show_field_single); if(array_intersect($productsarraycm, $show_field_array) ){ if( !empty ($btn['checkbox']) && !empty( $btn['label'] ) && ($btn['type'] !== 'changename') ) { if( empty( $_POST[''.$btn['cow'].''] ) ) { wc_add_notice( __( '<strong>'.wpml_string_wccm_pro($btn['label']).'</strong> is a required field.' ), 'error' ); } } } } // Category // hide field // with more // show field with more if ( !empty($btn['single_px_cat']) && !empty($btn['more_content']) ) { $show_field_array_cat = explode('||',$show_field_single_cat); if(array_intersect($categoryarraycm, $show_field_array_cat) ){ if ( !empty ($btn['checkbox']) && !empty( $btn['label'] ) && ($btn['type'] !== 'changename') ) { if( empty( $_POST[''.$btn['cow'].''] ) ) { wc_add_notice( __( '<strong>'.wpml_string_wccm_pro($btn['label']).'</strong> is a required field.' ), 'error' ); } } } } $categoryarraycm = ''; $productsarraycm = ''; } } ?>
xjhpaopao/wp_elephant_rv
wp-content/plugins/woocommerce-checkout-manager/includes/templates/functions/required/add_required.php
PHP
gpl-2.0
3,239
//-------------------------------------------------------------------------- // Copyright (C) 2014-2015 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2012-2013 Sourcefire, Inc. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public 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-1301, USA. //-------------------------------------------------------------------------- /* ** Author(s): Hui Cao <huica@cisco.com> ** ** NOTES ** 9.25.2012 - Initial Source Code. Hui Cao */ #include "file_mime_process.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_mime_config.h" #include "file_mime_decode.h" #include "file_api/file_api.h" #include "file_api/file_flows.h" #include "main/snort_types.h" #include "search_engines/search_tool.h" #include "protocols/packet.h" #include "detection/detection_util.h" #include "framework/data_bus.h" #include "utils/util.h" #include "utils/snort_bounds.h" struct MimeToken { const char* name; int name_len; int search_id; } ; enum MimeHdrEnum { HDR_CONTENT_TYPE = 0, HDR_CONT_TRANS_ENC, HDR_CONT_DISP, HDR_LAST }; const MimeToken mime_hdrs[] = { { "Content-type:", 13, HDR_CONTENT_TYPE }, { "Content-Transfer-Encoding:", 26, HDR_CONT_TRANS_ENC }, { "Content-Disposition:", 20, HDR_CONT_DISP }, { NULL, 0, 0 } }; struct MIMESearch { const char* name; int name_len; } ; struct MIMESearchInfo { int id; int index; int length; } ; MIMESearchInfo mime_search_info; SearchTool* mime_hdr_search_mpse = nullptr; MIMESearch mime_hdr_search[HDR_LAST]; MIMESearch* mime_current_search = NULL; void get_mime_eol(const uint8_t* ptr, const uint8_t* end, const uint8_t** eol, const uint8_t** eolm) { const uint8_t* tmp_eol; const uint8_t* tmp_eolm; assert(eol and eolm); if ( !ptr or !end ) { *eol = *eolm = end; return; } tmp_eol = (uint8_t*)memchr(ptr, '\n', end - ptr); if (tmp_eol == NULL) { tmp_eol = end; tmp_eolm = end; } else { /* end of line marker (eolm) should point to marker and * end of line (eol) should point to end of marker */ if ((tmp_eol > ptr) && (*(tmp_eol - 1) == '\r')) { tmp_eolm = tmp_eol - 1; } else { tmp_eolm = tmp_eol; } /* move past newline */ tmp_eol++; } *eol = tmp_eol; *eolm = tmp_eolm; } /* * Callback function for string search * * @param id id in array of search strings from mime_config.cmds * @param index index in array of search strings from mime_config.cmds * @param data buffer passed in to search function * * @return response * @retval 1 commands caller to stop searching */ static int search_str_found(void* id, void*, int index, void*, void*) { int search_id = (int)(uintptr_t)id; mime_search_info.id = search_id; mime_search_info.index = index; mime_search_info.length = mime_current_search[search_id].name_len; /* Returning non-zero stops search, which is okay since we only look for one at a time */ return 1; } void MimeSession::setup_decode(const char* data, int size, bool cnt_xf) { /* Check for Encoding Type */ if ( decode_conf && decode_conf->is_decoding_enabled()) { if (decode_state == NULL) { decode_state = new MimeDecode(decode_conf); } if (decode_state != NULL) { decode_state->process_decode_type(data, size, cnt_xf); state_flags |= MIME_FLAG_EMAIL_ATTACH; } } } /* * Handle Headers - Data or Mime * * @param packet standard Packet structure * * @param i index into p->payload buffer to start looking at data * * @return i index into p->payload where we stopped looking at data */ const uint8_t* MimeSession::process_mime_header(const uint8_t* ptr, const uint8_t* data_end_marker) { const uint8_t* eol = data_end_marker; const uint8_t* eolm = eol; const uint8_t* colon; const uint8_t* content_type_ptr = NULL; const uint8_t* cont_trans_enc = NULL; const uint8_t* cont_disp = NULL; int header_found; const uint8_t* start_hdr; start_hdr = ptr; /* if we got a content-type in a previous packet and are * folding, the boundary still needs to be checked for */ if (state_flags & MIME_FLAG_IN_CONTENT_TYPE) content_type_ptr = ptr; if (state_flags & MIME_FLAG_IN_CONT_TRANS_ENC) cont_trans_enc = ptr; if (state_flags & MIME_FLAG_IN_CONT_DISP) cont_disp = ptr; while (ptr < data_end_marker) { int header_name_len; int max_header_name_len = 0; get_mime_eol(ptr, data_end_marker, &eol, &eolm); /* got a line with only end of line marker should signify end of header */ if (eolm == ptr) { /* reset global header state values */ state_flags &= ~(MIME_FLAG_FOLDING | MIME_FLAG_IN_CONTENT_TYPE | MIME_FLAG_DATA_HEADER_CONT | MIME_FLAG_IN_CONT_TRANS_ENC ); data_state = STATE_DATA_BODY; /* if no headers, treat as data */ if (ptr == start_hdr) return eolm; else return eol; } /* if we're not folding, see if we should interpret line as a data line * instead of a header line */ if (!(state_flags & (MIME_FLAG_FOLDING | MIME_FLAG_DATA_HEADER_CONT))) { char got_non_printable_in_header_name = 0; /* if we're not folding and the first char is a space or * colon, it's not a header */ if (isspace((int)*ptr) || *ptr == ':') { data_state = STATE_DATA_BODY; return ptr; } /* look for header field colon - if we're not folding then we need * to find a header which will be all printables (except colon) * followed by a colon */ colon = ptr; while ((colon < eolm) && (*colon != ':')) { if (((int)*colon < 33) || ((int)*colon > 126)) got_non_printable_in_header_name = 1; colon++; } /* Check for Exim 4.32 exploit where number of chars before colon is greater than 64 */ header_name_len = colon - ptr; if ((colon < eolm) && (header_name_len > MAX_HEADER_NAME_LEN)) { max_header_name_len = header_name_len; } /* If the end on line marker and end of line are the same, assume * header was truncated, so stay in data header state */ if ((eolm != eol) && ((colon == eolm) || got_non_printable_in_header_name)) { /* no colon or got spaces in header name (won't be interpreted as a header) * assume we're in the body */ state_flags &= ~(MIME_FLAG_FOLDING | MIME_FLAG_IN_CONTENT_TYPE | MIME_FLAG_DATA_HEADER_CONT |MIME_FLAG_IN_CONT_TRANS_ENC); data_state = STATE_DATA_BODY; return ptr; } if (tolower((int)*ptr) == 'c') { mime_current_search = &mime_hdr_search[0]; header_found = mime_hdr_search_mpse->find( (const char*)ptr, eolm - ptr, search_str_found, true); /* Headers must start at beginning of line */ if ((header_found > 0) && (mime_search_info.index == 0)) { switch (mime_search_info.id) { case HDR_CONTENT_TYPE: content_type_ptr = ptr + mime_search_info.length; state_flags |= MIME_FLAG_IN_CONTENT_TYPE; break; case HDR_CONT_TRANS_ENC: cont_trans_enc = ptr + mime_search_info.length; state_flags |= MIME_FLAG_IN_CONT_TRANS_ENC; break; case HDR_CONT_DISP: cont_disp = ptr + mime_search_info.length; state_flags |= MIME_FLAG_IN_CONT_DISP; break; default: break; } } } else if (tolower((int)*ptr) == 'e') { if ((eolm - ptr) >= 9) { if (strncasecmp((const char*)ptr, "Encoding:", 9) == 0) { cont_trans_enc = ptr + 9; state_flags |= MIME_FLAG_IN_CONT_TRANS_ENC; } } } } else { state_flags &= ~MIME_FLAG_DATA_HEADER_CONT; } int ret = handle_header_line(ptr, eol, max_header_name_len); if (ret < 0) return NULL; else if (ret > 0) { /* assume we guessed wrong and are in the body */ data_state = STATE_DATA_BODY; state_flags &= ~(MIME_FLAG_FOLDING | MIME_FLAG_IN_CONTENT_TYPE | MIME_FLAG_DATA_HEADER_CONT | MIME_FLAG_IN_CONT_TRANS_ENC | MIME_FLAG_IN_CONT_DISP); return ptr; } /* check for folding * if char on next line is a space and not \n or \r\n, we are folding */ if ((eol < data_end_marker) && isspace((int)eol[0]) && (eol[0] != '\n')) { if ((eol < (data_end_marker - 1)) && (eol[0] != '\r') && (eol[1] != '\n')) { state_flags |= MIME_FLAG_FOLDING; } else { state_flags &= ~MIME_FLAG_FOLDING; } } else if (eol != eolm) { state_flags &= ~MIME_FLAG_FOLDING; } /* check if we're in a content-type header and not folding. if so we have the whole * header line/lines for content-type - see if we got a multipart with boundary * we don't check each folded line, but wait until we have the complete header * because boundary=BOUNDARY can be split across mulitple folded lines before * or after the '=' */ if ((state_flags & (MIME_FLAG_IN_CONTENT_TYPE | MIME_FLAG_FOLDING)) == MIME_FLAG_IN_CONTENT_TYPE) { if ((data_state == STATE_MIME_HEADER) && !(state_flags & MIME_FLAG_EMAIL_ATTACH)) { setup_decode((const char*)content_type_ptr, (eolm - content_type_ptr), false); } state_flags &= ~MIME_FLAG_IN_CONTENT_TYPE; content_type_ptr = NULL; } else if ((state_flags & (MIME_FLAG_IN_CONT_TRANS_ENC | MIME_FLAG_FOLDING)) == MIME_FLAG_IN_CONT_TRANS_ENC) { setup_decode((const char*)cont_trans_enc, (eolm - cont_trans_enc), true); state_flags &= ~MIME_FLAG_IN_CONT_TRANS_ENC; cont_trans_enc = NULL; } else if (((state_flags & (MIME_FLAG_IN_CONT_DISP | MIME_FLAG_FOLDING)) == MIME_FLAG_IN_CONT_DISP) && cont_disp) { bool disp_cont = (state_flags & MIME_FLAG_IN_CONT_DISP_CONT) ? true : false; if (log_config->log_filename && log_state ) { log_state->log_file_name(cont_disp, eolm - cont_disp, &disp_cont); } if (disp_cont) { state_flags |= MIME_FLAG_IN_CONT_DISP_CONT; } else { state_flags &= ~MIME_FLAG_IN_CONT_DISP; state_flags &= ~MIME_FLAG_IN_CONT_DISP_CONT; } cont_disp = NULL; } data_state = STATE_DATA_HEADER; ptr = eol; if (ptr == data_end_marker) state_flags |= MIME_FLAG_DATA_HEADER_CONT; } return ptr; } /* Get the end of data body (excluding boundary)*/ static const uint8_t* GetDataEnd(const uint8_t* data_start, const uint8_t* data_end_marker) { /* '\r\n' + '--' + MIME boundary string */ const int Max_Search = 4 + MAX_MIME_BOUNDARY_LEN; uint8_t* start; /*Exclude 2 bytes because either \r\n or '--' at the end */ uint8_t* end = (uint8_t*)data_end_marker - 2; /*Search for the start of boundary, should be less than boundary length*/ if (end > data_start + Max_Search) start = end - Max_Search; else start = (uint8_t*)data_start; while (end > start) { if (*(--end) != '\n') continue; if ((*(end+1) == '-') && (*(end+2) == '-')) { if ((end > start) && (*(end-1) == '\r')) return (end - 1); else return end; } break; } return data_end_marker; } /* * Handle DATA_BODY state * @param packet standard Packet structure * @param i index into p->payload buffer to start looking at data * @return i index into p->payload where we stopped looking at data */ const uint8_t* MimeSession::process_mime_body(const uint8_t* ptr, const uint8_t* data_end, bool is_data_end) { if (state_flags & MIME_FLAG_EMAIL_ATTACH) { const uint8_t* attach_start = ptr; const uint8_t* attach_end; if (is_data_end ) { attach_end = GetDataEnd(ptr, data_end); } else { attach_end = data_end; } if (( attach_start < attach_end ) && decode_state) { if (decode_state->decode_data(attach_start, attach_end) == DECODE_FAIL ) { decode_alert(); } } } if (is_data_end) { data_state = STATE_MIME_HEADER; state_flags &= ~MIME_FLAG_EMAIL_ATTACH; } return data_end; } /* * Reset MIME session state */ void MimeSession::reset_mime_state() { data_state = STATE_DATA_INIT; state_flags = 0; if (decode_state) decode_state->clear_decode_state(); } const uint8_t* MimeSession::process_mime_data_paf( Flow* flow, const uint8_t* start, const uint8_t* end, bool upload, FilePosition position) { bool done_data = is_end_of_data(flow); /* if we've just entered the data state, check for a dot + end of line * if found, no data */ if ( data_state == STATE_DATA_INIT ) { if ((start < end) && (*start == '.')) { const uint8_t* eol = NULL; const uint8_t* eolm = NULL; get_mime_eol(start, end, &eol, &eolm); /* this means we got a real end of line and not just end of payload * and that the dot is only char on line */ if ((eolm != end) && (eolm == (start + 1))) { /* if we're normalizing and not ignoring data copy data end marker * and dot to alt buffer */ if (normalize_data(start, end) < 0) return NULL; reset_mime_state(); return eol; } } if (data_state == STATE_DATA_INIT) data_state = STATE_DATA_HEADER; /* XXX A line starting with a '.' that isn't followed by a '.' is * deleted (RFC 821 - 4.5.2. TRANSPARENCY). If data starts with * '. text', i.e a dot followed by white space then text, some * servers consider it data header and some data body. * Postfix and Qmail will consider the start of data: * . text\r\n * . text\r\n * to be part of the header and the effect will be that of a * folded line with the '.' deleted. Exchange will put the same * in the body which seems more reasonable. */ } // FIXIT-L why is this being set? we don't search file data until // we set it again below after decoding. can it be deleted? if ( decode_conf && (!decode_conf->is_ignore_data())) set_file_data((uint8_t*)start, (end - start)); if (data_state == STATE_DATA_HEADER) { #ifdef DEBUG_MSGS if (data_state == STATE_DATA_HEADER) { DEBUG_WRAP(DebugMessage(DEBUG_FILE, "DATA HEADER STATE ~~~~~~~~~~~~~~~~~~~~~~\n"); ); } else { DEBUG_WRAP(DebugMessage(DEBUG_FILE, "DATA UNKNOWN STATE ~~~~~~~~~~~~~~~~~~~~~\n"); ); } #endif start = process_mime_header(start, end); if (start == NULL) return NULL; } if (normalize_data(start, end) < 0) return NULL; /* now we shouldn't have to worry about copying any data to the alt buffer * * only mime headers if we find them and only if we're ignoring data */ while ((start != NULL) && (start < end)) { switch (data_state) { case STATE_MIME_HEADER: DEBUG_WRAP(DebugMessage(DEBUG_FILE, "MIME HEADER STATE ~~~~~~~~~~~~~~~~~~~~~~\n"); ); start = process_mime_header(start, end); break; case STATE_DATA_BODY: DEBUG_WRAP(DebugMessage(DEBUG_FILE, "DATA BODY STATE ~~~~~~~~~~~~~~~~~~~~~~~~\n"); ); start = process_mime_body(start, end, isFileEnd(position) ); break; } } /* We have either reached the end of MIME header or end of MIME encoded data*/ if ((decode_state) != NULL) { DecodeConfig* conf= decode_conf; uint8_t* buffer = NULL; uint32_t buf_size = 0; decode_state->get_decoded_data(&buffer, &buf_size); if (conf) { int detection_size = decode_state->get_detection_depth(); set_file_data(buffer, (uint16_t)detection_size); } /*Process file type/file signature*/ FileFlows* file_flows = FileFlows::get_file_flows(flow); if (file_flows && file_flows->file_process(buffer, buf_size, position, upload) && (isFileStart(position)) && log_state) { log_state->set_file_name_from_log(flow); } decode_state->reset_decoded_bytes(); } /* if we got the data end reset state, otherwise we're probably still in the data * * to expect more data in next packet */ if (done_data) { reset_mime_state(); reset_state(flow); } return end; } // Main function for mime processing // This should be called when mime data is available const uint8_t* MimeSession::process_mime_data(Flow* flow, const uint8_t* start, int data_size, bool upload, FilePosition position) { const uint8_t* attach_start = start; const uint8_t* attach_end; const uint8_t* data_end_marker = start + data_size; if (position != SNORT_FILE_POSITION_UNKNOWN) { process_mime_data_paf(flow, attach_start, data_end_marker, upload, position); return data_end_marker; } initFilePosition(&position, get_file_processed_size(flow)); /* look for boundary */ while (start < data_end_marker) { /*Found the boundary, start processing data*/ if (process_mime_paf_data(&(mime_boundary), *start)) { attach_end = start; finalFilePosition(&position); process_mime_data_paf(flow, attach_start, attach_end, upload, position); position = SNORT_FILE_START; attach_start = start + 1; } start++; } if ((start == data_end_marker) && (attach_start < data_end_marker)) { updateFilePosition(&position, get_file_processed_size(flow)); process_mime_data_paf(flow, attach_start, data_end_marker, upload, position); } return data_end_marker; } int MimeSession::get_data_state() { return data_state; } void MimeSession::set_data_state(int state) { data_state = state; } MailLogState* MimeSession::get_log_state() { return log_state; } /* * This is the initialization function for mime processing. * This should be called when snort initializes */ void MimeSession::init(void) { const MimeToken* tmp; /* Header search */ mime_hdr_search_mpse = new SearchTool(); if (mime_hdr_search_mpse == NULL) { // FIXIT-M make configurable or at least fall back to any // available search engine FatalError("Could not instantiate ac_bnfa search engine.\n"); } for (tmp = &mime_hdrs[0]; tmp->name != NULL; tmp++) { mime_hdr_search[tmp->search_id].name = tmp->name; mime_hdr_search[tmp->search_id].name_len = tmp->name_len; mime_hdr_search_mpse->add(tmp->name, tmp->name_len, tmp->search_id); } mime_hdr_search_mpse->prep(); } // Free anything that needs it before shutting down preprocessor void MimeSession::exit(void) { if (mime_hdr_search_mpse != NULL) delete mime_hdr_search_mpse; } MimeSession::MimeSession(DecodeConfig* dconf, MailLogConfig* lconf) { decode_conf = dconf; log_config = lconf; log_state = new MailLogState(log_config); reset_mime_paf_state(&mime_boundary); } MimeSession::~MimeSession() { if ( decode_state ) delete(decode_state); if ( log_state ) delete(log_state); }
gavares/snort3
src/mime/file_mime_process.cc
C++
gpl-2.0
22,083
@section('title') Edit course {{$courseName}} @stop @include('includes.header') {{ Form::open(array('url' => $url, 'method' => 'PUT')) }} {{ Form::label('name', 'Course name') }} {{ Form::text('name',$courseName) }} {{ Form::submit('Save change!') }} {{ Form::close() }} @include('includes.footer')
VeeSot/yalms
app/views/pages/course/edit.blade.php
PHP
gpl-2.0
335
package fiuba.algo3.model.map; import fiuba.algo3.model.exceptions.CannotOccupyTileException; import fiuba.algo3.model.exceptions.NotEnoughRoomException; import fiuba.algo3.model.occupant.Occupant; import fiuba.algo3.model.occupant.units.TerranTransportVessel; import fiuba.algo3.model.occupant.units.Unit; public class Earth extends Tile{ public Earth(Coordinates coordinates){ super(coordinates); info = "Earth. . "; } public void put(Occupant newOccupant) throws CannotOccupyTileException, NotEnoughRoomException { if(occupied && occupant.canTransport()){ TerranTransportVessel occAsTransport = (TerranTransportVessel) occupant; occAsTransport.addUnit((Unit) newOccupant); } else if (!occupied && newOccupant.canOccupyEarth()){ occupied = true; occupant = newOccupant; } else { throw new CannotOccupyTileException(); } } }
algoCraftDeveloperTeam/algosIII_tpFinal
src/fiuba/algo3/model/map/Earth.java
Java
gpl-2.0
864
// This file is part of the GOfax.IP project - https://github.com/MatteoMynet/gofaxip // Copyright (C) 2014 GONICUS GmbH, Germany - http://www.gonicus.de // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; 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-1301, USA. package logger import ( "log" "log/syslog" ) const ( LOG_PRIORITY = syslog.LOG_DAEMON | syslog.LOG_INFO LOG_FLAGS = log.Lshortfile ) var ( Logger *log.Logger ) func init() { var err error log.SetFlags(LOG_FLAGS) Logger, err = syslog.NewLogger(LOG_PRIORITY, LOG_FLAGS) if err != nil { log.Fatal(err) } }
MatteoMynet/gofaxip
gofaxlib/logger/logger.go
GO
gpl-2.0
1,154
// add_provider.cpp // // Edit a Davit Provider. // // (C) Copyright 2007 Fred Gleason <fredg@paravelsystems.com> // // $Id: add_provider.cpp,v 1.2 2007/11/19 16:53:29 fredg Exp $ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // #include <qpushbutton.h> #include <qlabel.h> #include <qsqldatabase.h> #include <qmessagebox.h> #include <math.h> #include <add_provider.h> AddProvider::AddProvider(QString *bname,QWidget *parent,const char *name) : QDialog(parent,name,true) { add_business_name=bname; // // Fix the Window Size // setMinimumWidth(sizeHint().width()); setMinimumHeight(sizeHint().height()); setMaximumWidth(sizeHint().width()); setMaximumHeight(sizeHint().height()); setCaption("Davit - Add Provider"); // // Create Fonts // QFont label_font=QFont("Helvetica",12,QFont::Bold); label_font.setPixelSize(12); QFont font=QFont("Helvetica",12,QFont::Normal); font.setPixelSize(12); // // Station Call // add_business_name_edit=new QLineEdit(this,"add_business_name_edit"); add_business_name_edit->setGeometry(110,10,sizeHint().width()-120,20); add_business_name_edit->setFont(font); add_business_name_edit->setMaxLength(64); QLabel *label=new QLabel(add_business_name_edit,"Business Name:", this,"add_business_name_label"); label->setGeometry(10,10,95,20); label->setAlignment(AlignRight|AlignVCenter); label->setFont(label_font); // // OK Button // QPushButton *button=new QPushButton(this,"ok_button"); button->setGeometry(sizeHint().width()-180,sizeHint().height()-60,80,50); button->setDefault(true); button->setFont(label_font); button->setText("&OK"); connect(button,SIGNAL(clicked()),this,SLOT(okData())); // // Cancel Button // button=new QPushButton(this,"cancel_button"); button->setGeometry(sizeHint().width()-90,sizeHint().height()-60,80,50); button->setFont(label_font); button->setText("&Cancel"); connect(button,SIGNAL(clicked()),this,SLOT(cancelData())); } AddProvider::~AddProvider() { } QSize AddProvider::sizeHint() const { return QSize(400,110); } QSizePolicy AddProvider::sizePolicy() const { return QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); } void AddProvider::okData() { QString sql= QString().sprintf("select BUSINESS_NAME from PROVIDERS \ where BUSINESS_NAME=\"%s\"", (const char *)add_business_name_edit->text()); QSqlQuery *q=new QSqlQuery(sql); if(q->first()) { QMessageBox::warning(this,"Provider Exists", "That provider already exists!"); delete q; return; } delete q; *add_business_name=add_business_name_edit->text(); done(0); } void AddProvider::cancelData() { done(-1); }
ElvishArtisan/davit
davit/add_provider.cpp
C++
gpl-2.0
3,329
/* Copyright (c) 2002, 2016, Oracle and/or its affiliates. Copyright (c) 2011, 2020, MariaDB 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 St, Fifth Floor, Boston, MA 02110-1335 USA */ #include "mariadb.h" /* NO_EMBEDDED_ACCESS_CHECKS */ #include "sql_priv.h" #include "unireg.h" #include "sql_prepare.h" #include "sql_cache.h" // query_cache_* #include "probes_mysql.h" #include "sql_show.h" // append_identifier #include "sql_db.h" // mysql_opt_change_db, mysql_change_db #include "sql_array.h" // Dynamic_array #include "log_event.h" // Query_log_event #include "sql_derived.h" // mysql_handle_derived #include "sql_cte.h" #include "sql_select.h" // Virtual_tmp_table #include "opt_trace.h" #include "my_json_writer.h" #ifdef USE_PRAGMA_IMPLEMENTATION #pragma implementation #endif #include "sp_head.h" #include "sp.h" #include "sp_pcontext.h" #include "sp_rcontext.h" #include "sp_cache.h" #include "set_var.h" #include "sql_parse.h" // cleanup_items #include "sql_base.h" // close_thread_tables #include "transaction.h" // trans_commit_stmt #include "sql_audit.h" #include "debug_sync.h" #ifdef WITH_WSREP #include "wsrep_trans_observer.h" #endif /* WITH_WSREP */ /* Sufficient max length of printed destinations and frame offsets (all uints). */ #define SP_INSTR_UINT_MAXLEN 8 #define SP_STMT_PRINT_MAXLEN 40 #include <my_user.h> #include "mysql/psi/mysql_statement.h" #include "mysql/psi/mysql_sp.h" #ifdef HAVE_PSI_INTERFACE void init_sp_psi_keys() { const char *category= "sp"; const int num __attribute__((unused)) = __LINE__ + 3; PSI_server->register_statement(category, & sp_instr_stmt::psi_info, 1); PSI_server->register_statement(category, & sp_instr_set::psi_info, 1); PSI_server->register_statement(category, & sp_instr_set_trigger_field::psi_info, 1); PSI_server->register_statement(category, & sp_instr_jump::psi_info, 1); PSI_server->register_statement(category, & sp_instr_jump_if_not::psi_info, 1); PSI_server->register_statement(category, & sp_instr_freturn::psi_info, 1); PSI_server->register_statement(category, & sp_instr_preturn::psi_info, 1); PSI_server->register_statement(category, & sp_instr_hpush_jump::psi_info, 1); PSI_server->register_statement(category, & sp_instr_hpop::psi_info, 1); PSI_server->register_statement(category, & sp_instr_hreturn::psi_info, 1); PSI_server->register_statement(category, & sp_instr_cpush::psi_info, 1); PSI_server->register_statement(category, & sp_instr_cpop::psi_info, 1); PSI_server->register_statement(category, & sp_instr_copen::psi_info, 1); PSI_server->register_statement(category, & sp_instr_cclose::psi_info, 1); PSI_server->register_statement(category, & sp_instr_cfetch::psi_info, 1); PSI_server->register_statement(category, & sp_instr_agg_cfetch::psi_info, 1); PSI_server->register_statement(category, & sp_instr_cursor_copy_struct::psi_info, 1); PSI_server->register_statement(category, & sp_instr_error::psi_info, 1); PSI_server->register_statement(category, & sp_instr_set_case_expr::psi_info, 1); DBUG_ASSERT(SP_PSI_STATEMENT_INFO_COUNT == __LINE__ - num); } #endif #ifdef HAVE_PSI_SP_INTERFACE #define MYSQL_RUN_SP(SP,CODE) \ do { \ PSI_sp_locker_state psi_state; \ PSI_sp_locker *locker= MYSQL_START_SP(&psi_state, (SP)->m_sp_share); \ CODE; \ MYSQL_END_SP(locker); \ } while(0) #else #define MYSQL_RUN_SP(SP, CODE) do { CODE; } while(0) #endif extern "C" uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first); /** Helper function which operates on a THD object to set the query start_time to the current time. @param[in, out] thd The session object */ static void reset_start_time_for_sp(THD *thd) { if (!thd->in_sub_stmt) thd->set_start_time(); } bool Item_splocal::append_for_log(THD *thd, String *str) { if (fix_fields_if_needed(thd, NULL)) return true; if (limit_clause_param) return str->append_ulonglong(val_uint()); /* ROW variables are currently not allowed in select_list, e.g.: SELECT row_variable; ROW variables can appear in query parts where name is not important, e.g.: SELECT ROW(1,2)=row_variable FROM t1; So we can skip using NAME_CONST() and use ROW() constants directly. */ if (type_handler() == &type_handler_row) return append_value_for_log(thd, str); if (str->append(STRING_WITH_LEN(" NAME_CONST('")) || str->append(&m_name) || str->append(STRING_WITH_LEN("',"))) return true; return append_value_for_log(thd, str) || str->append(')'); } bool Item_splocal::append_value_for_log(THD *thd, String *str) { StringBuffer<STRING_BUFFER_USUAL_SIZE> str_value_holder(&my_charset_latin1); Item *item= this_item(); String *str_value= item->type_handler()->print_item_value(thd, item, &str_value_holder); return (str_value ? str->append(*str_value) : str->append(NULL_clex_str)); } bool Item_splocal_row_field::append_for_log(THD *thd, String *str) { if (fix_fields_if_needed(thd, NULL)) return true; if (limit_clause_param) return str->append_ulonglong(val_uint()); if (str->append(STRING_WITH_LEN(" NAME_CONST('")) || str->append(&m_name) || str->append('.') || str->append(&m_field_name) || str->append(STRING_WITH_LEN("',"))) return true; return append_value_for_log(thd, str) || str->append(')'); } /** Returns a combination of: - sp_head::MULTI_RESULTS: added if the 'cmd' is a command that might result in multiple result sets being sent back. - sp_head::CONTAINS_DYNAMIC_SQL: added if 'cmd' is one of PREPARE, EXECUTE, DEALLOCATE. */ uint sp_get_flags_for_command(LEX *lex) { uint flags; switch (lex->sql_command) { case SQLCOM_SELECT: if (lex->result && !lex->analyze_stmt) { flags= 0; /* This is a SELECT with INTO clause */ break; } /* fallthrough */ case SQLCOM_ANALYZE: case SQLCOM_OPTIMIZE: case SQLCOM_PRELOAD_KEYS: case SQLCOM_ASSIGN_TO_KEYCACHE: case SQLCOM_CHECKSUM: case SQLCOM_CHECK: case SQLCOM_HA_READ: case SQLCOM_SHOW_AUTHORS: case SQLCOM_SHOW_BINLOGS: case SQLCOM_SHOW_BINLOG_EVENTS: case SQLCOM_SHOW_RELAYLOG_EVENTS: case SQLCOM_SHOW_CHARSETS: case SQLCOM_SHOW_COLLATIONS: case SQLCOM_SHOW_CONTRIBUTORS: case SQLCOM_SHOW_CREATE: case SQLCOM_SHOW_CREATE_DB: case SQLCOM_SHOW_CREATE_FUNC: case SQLCOM_SHOW_CREATE_PROC: case SQLCOM_SHOW_CREATE_PACKAGE: case SQLCOM_SHOW_CREATE_PACKAGE_BODY: case SQLCOM_SHOW_CREATE_EVENT: case SQLCOM_SHOW_CREATE_TRIGGER: case SQLCOM_SHOW_CREATE_USER: case SQLCOM_SHOW_DATABASES: case SQLCOM_SHOW_ERRORS: case SQLCOM_SHOW_EXPLAIN: case SQLCOM_SHOW_FIELDS: case SQLCOM_SHOW_FUNC_CODE: case SQLCOM_SHOW_GENERIC: case SQLCOM_SHOW_GRANTS: case SQLCOM_SHOW_ENGINE_STATUS: case SQLCOM_SHOW_ENGINE_LOGS: case SQLCOM_SHOW_ENGINE_MUTEX: case SQLCOM_SHOW_EVENTS: case SQLCOM_SHOW_KEYS: case SQLCOM_SHOW_BINLOG_STAT: case SQLCOM_SHOW_OPEN_TABLES: case SQLCOM_SHOW_PRIVILEGES: case SQLCOM_SHOW_PROCESSLIST: case SQLCOM_SHOW_PROC_CODE: case SQLCOM_SHOW_PACKAGE_BODY_CODE: case SQLCOM_SHOW_SLAVE_HOSTS: case SQLCOM_SHOW_SLAVE_STAT: case SQLCOM_SHOW_STATUS: case SQLCOM_SHOW_STATUS_FUNC: case SQLCOM_SHOW_STATUS_PROC: case SQLCOM_SHOW_STATUS_PACKAGE: case SQLCOM_SHOW_STATUS_PACKAGE_BODY: case SQLCOM_SHOW_STORAGE_ENGINES: case SQLCOM_SHOW_TABLES: case SQLCOM_SHOW_TABLE_STATUS: case SQLCOM_SHOW_VARIABLES: case SQLCOM_SHOW_WARNS: case SQLCOM_REPAIR: flags= sp_head::MULTI_RESULTS; break; /* EXECUTE statement may return a result set, but doesn't have to. We can't, however, know it in advance, and therefore must add this statement here. This is ok, as is equivalent to a result-set statement within an IF condition. */ case SQLCOM_EXECUTE: case SQLCOM_EXECUTE_IMMEDIATE: flags= sp_head::MULTI_RESULTS | sp_head::CONTAINS_DYNAMIC_SQL; break; case SQLCOM_PREPARE: case SQLCOM_DEALLOCATE_PREPARE: flags= sp_head::CONTAINS_DYNAMIC_SQL; break; case SQLCOM_CREATE_TABLE: case SQLCOM_CREATE_SEQUENCE: if (lex->tmp_table()) flags= 0; else flags= sp_head::HAS_COMMIT_OR_ROLLBACK; break; case SQLCOM_DROP_TABLE: case SQLCOM_DROP_SEQUENCE: if (lex->tmp_table()) flags= 0; else flags= sp_head::HAS_COMMIT_OR_ROLLBACK; break; case SQLCOM_FLUSH: flags= sp_head::HAS_SQLCOM_FLUSH; break; case SQLCOM_RESET: flags= sp_head::HAS_SQLCOM_RESET; break; case SQLCOM_CREATE_INDEX: case SQLCOM_CREATE_DB: case SQLCOM_CREATE_PACKAGE: case SQLCOM_CREATE_PACKAGE_BODY: case SQLCOM_CREATE_VIEW: case SQLCOM_CREATE_TRIGGER: case SQLCOM_CREATE_USER: case SQLCOM_CREATE_ROLE: case SQLCOM_ALTER_TABLE: case SQLCOM_ALTER_SEQUENCE: case SQLCOM_ALTER_USER: case SQLCOM_GRANT: case SQLCOM_GRANT_ROLE: case SQLCOM_REVOKE: case SQLCOM_REVOKE_ROLE: case SQLCOM_BEGIN: case SQLCOM_RENAME_TABLE: case SQLCOM_RENAME_USER: case SQLCOM_DROP_INDEX: case SQLCOM_DROP_DB: case SQLCOM_DROP_PACKAGE: case SQLCOM_DROP_PACKAGE_BODY: case SQLCOM_REVOKE_ALL: case SQLCOM_DROP_USER: case SQLCOM_DROP_ROLE: case SQLCOM_DROP_VIEW: case SQLCOM_DROP_TRIGGER: case SQLCOM_TRUNCATE: case SQLCOM_COMMIT: case SQLCOM_ROLLBACK: case SQLCOM_LOAD: case SQLCOM_LOCK_TABLES: case SQLCOM_CREATE_PROCEDURE: case SQLCOM_CREATE_SPFUNCTION: case SQLCOM_ALTER_PROCEDURE: case SQLCOM_ALTER_FUNCTION: case SQLCOM_DROP_PROCEDURE: case SQLCOM_DROP_FUNCTION: case SQLCOM_CREATE_EVENT: case SQLCOM_ALTER_EVENT: case SQLCOM_DROP_EVENT: case SQLCOM_INSTALL_PLUGIN: case SQLCOM_UNINSTALL_PLUGIN: flags= sp_head::HAS_COMMIT_OR_ROLLBACK; break; case SQLCOM_DELETE: case SQLCOM_DELETE_MULTI: case SQLCOM_INSERT: case SQLCOM_REPLACE: case SQLCOM_REPLACE_SELECT: case SQLCOM_INSERT_SELECT: { /* DELETE normally doesn't return resultset, but there are 3 exceptions: - DELETE ... RETURNING - EXPLAIN DELETE ... - ANALYZE DELETE ... */ if (!lex->has_returning() && !lex->describe && !lex->analyze_stmt) flags= 0; else flags= sp_head::MULTI_RESULTS; break; } case SQLCOM_UPDATE: case SQLCOM_UPDATE_MULTI: { if (!lex->describe && !lex->analyze_stmt) flags= 0; else flags= sp_head::MULTI_RESULTS; break; } default: flags= 0; break; } return flags; } /** Prepare an Item for evaluation (call of fix_fields). @param it_addr pointer on item refernce @param cols expected number of elements (1 for scalar, >=1 for ROWs) @retval NULL error @retval non-NULL prepared item */ Item *THD::sp_prepare_func_item(Item **it_addr, uint cols) { DBUG_ENTER("THD::sp_prepare_func_item"); Item *res= sp_fix_func_item(it_addr); if (res && res->check_cols(cols)) DBUG_RETURN(NULL); DBUG_RETURN(res); } /** Fix an Item for evaluation for SP. */ Item *THD::sp_fix_func_item(Item **it_addr) { DBUG_ENTER("THD::sp_fix_func_item"); if ((*it_addr)->fix_fields_if_needed(this, it_addr)) { DBUG_PRINT("info", ("fix_fields() failed")); DBUG_RETURN(NULL); } it_addr= (*it_addr)->this_item_addr(this, it_addr); if ((*it_addr)->fix_fields_if_needed(this, it_addr)) { DBUG_PRINT("info", ("fix_fields() failed")); DBUG_RETURN(NULL); } DBUG_RETURN(*it_addr); } /** Evaluate an expression and store the result in the field. @param result_field the field to store the result @param expr_item_ptr the root item of the expression @retval FALSE on success @retval TRUE on error */ bool THD::sp_eval_expr(Field *result_field, Item **expr_item_ptr) { DBUG_ENTER("THD::sp_eval_expr"); DBUG_ASSERT(*expr_item_ptr); Sp_eval_expr_state state(this); /* Save the value in the field. Convert the value if needed. */ DBUG_RETURN(result_field->sp_prepare_and_store_item(this, expr_item_ptr)); } /** Create temporary sp_name object from MDL key. @note The lifetime of this object is bound to the lifetime of the MDL_key. This should be fine as sp_name objects created by this constructor are mainly used for SP-cache lookups. @param key MDL key containing database and routine name. @param qname_buff Buffer to be used for storing quoted routine name (should be at least 2*NAME_LEN+1+1 bytes). */ sp_name::sp_name(const MDL_key *key, char *qname_buff) :Database_qualified_name(key->db_name(), key->db_name_length(), key->name(), key->name_length()), m_explicit_name(false) { if (m_db.length) strxmov(qname_buff, m_db.str, ".", m_name.str, NullS); else strmov(qname_buff, m_name.str); } /** Check that the name 'ident' is ok. It's assumed to be an 'ident' from the parser, so we only have to check length and trailing spaces. The former is a standard requirement (and 'show status' assumes a non-empty name), the latter is a mysql:ism as trailing spaces are removed by get_field(). @retval TRUE bad name @retval FALSE name is ok */ bool check_routine_name(const LEX_CSTRING *ident) { DBUG_ASSERT(ident); DBUG_ASSERT(ident->str); if (!ident->str[0] || ident->str[ident->length-1] == ' ') { my_error(ER_SP_WRONG_NAME, MYF(0), ident->str); return TRUE; } if (check_ident_length(ident)) return TRUE; return FALSE; } /* * * sp_head * */ sp_head *sp_head::create(sp_package *parent, const Sp_handler *handler, enum_sp_aggregate_type agg_type) { MEM_ROOT own_root; init_sql_alloc(key_memory_sp_head_main_root, &own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, MYF(0)); sp_head *sp; if (!(sp= new (&own_root) sp_head(&own_root, parent, handler, agg_type))) free_root(&own_root, MYF(0)); return sp; } void sp_head::destroy(sp_head *sp) { if (sp) { /* Make a copy of main_mem_root as free_root will free the sp */ MEM_ROOT own_root= sp->main_mem_root; DBUG_PRINT("info", ("mem_root %p moved to %p", &sp->mem_root, &own_root)); delete sp; free_root(&own_root, MYF(0)); } } /* * * sp_head * */ sp_head::sp_head(MEM_ROOT *mem_root_arg, sp_package *parent, const Sp_handler *sph, enum_sp_aggregate_type agg_type) :Query_arena(NULL, STMT_INITIALIZED_FOR_SP), Database_qualified_name(&null_clex_str, &null_clex_str), main_mem_root(*mem_root_arg), m_parent(parent), m_handler(sph), m_flags(0), m_tmp_query(NULL), m_explicit_name(false), /* FIXME: the only use case when name is NULL is events, and it should be rewritten soon. Remove the else part and replace 'if' with an assert when this is done. */ m_qname(null_clex_str), m_params(null_clex_str), m_body(null_clex_str), m_body_utf8(null_clex_str), m_defstr(null_clex_str), m_sp_cache_version(0), m_creation_ctx(0), unsafe_flags(0), m_created(0), m_modified(0), m_recursion_level(0), m_next_cached_sp(0), m_param_begin(NULL), m_param_end(NULL), m_body_begin(NULL), m_thd_root(NULL), m_thd(NULL), m_pcont(new (&main_mem_root) sp_pcontext()), m_cont_level(0) { mem_root= &main_mem_root; set_chistics_agg_type(agg_type); m_first_instance= this; m_first_free_instance= this; m_last_cached_sp= this; m_return_field_def.charset = NULL; DBUG_ENTER("sp_head::sp_head"); m_security_ctx.init(); m_backpatch.empty(); m_backpatch_goto.empty(); m_cont_backpatch.empty(); m_lex.empty(); my_init_dynamic_array(key_memory_sp_head_main_root, &m_instr, sizeof(sp_instr *), 16, 8, MYF(0)); my_hash_init(key_memory_sp_head_main_root, &m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0); my_hash_init(key_memory_sp_head_main_root, &m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key, 0, 0); DBUG_VOID_RETURN; } sp_package *sp_package::create(LEX *top_level_lex, const sp_name *name, const Sp_handler *sph) { MEM_ROOT own_root; init_sql_alloc(key_memory_sp_head_main_root, &own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC, MYF(0)); sp_package *sp; if (!(sp= new (&own_root) sp_package(&own_root, top_level_lex, name, sph))) free_root(&own_root, MYF(0)); return sp; } sp_package::sp_package(MEM_ROOT *mem_root_arg, LEX *top_level_lex, const sp_name *name, const Sp_handler *sph) :sp_head(mem_root_arg, NULL, sph, DEFAULT_AGGREGATE), m_current_routine(NULL), m_top_level_lex(top_level_lex), m_rcontext(NULL), m_invoked_subroutine_count(0), m_is_instantiated(false), m_is_cloning_routine(false) { init_sp_name(name); } sp_package::~sp_package() { m_routine_implementations.cleanup(); m_routine_declarations.cleanup(); m_body= null_clex_str; if (m_current_routine) sp_head::destroy(m_current_routine->sphead); delete m_rcontext; } /* Test if two routines have equal specifications */ bool sp_head::eq_routine_spec(const sp_head *sp) const { // TODO: Add tests for equal return data types (in case of FUNCTION) // TODO: Add tests for equal argument data types return m_handler->type() == sp->m_handler->type() && m_pcont->context_var_count() == sp->m_pcont->context_var_count(); } bool sp_package::validate_after_parser(THD *thd) { if (m_handler->type() != SP_TYPE_PACKAGE_BODY) return false; sp_head *sp= sp_cache_lookup(&thd->sp_package_spec_cache, this); sp_package *spec= sp ? sp->get_package() : NULL; DBUG_ASSERT(spec); // CREATE PACKAGE must already be cached return validate_public_routines(thd, spec) || validate_private_routines(thd); } bool sp_package::validate_public_routines(THD *thd, sp_package *spec) { /* Check that all routines declared in CREATE PACKAGE have implementations in CREATE PACKAGE BODY. */ List_iterator<LEX> it(spec->m_routine_declarations); for (LEX *lex; (lex= it++); ) { bool found= false; DBUG_ASSERT(lex->sphead); List_iterator<LEX> it2(m_routine_implementations); for (LEX *lex2; (lex2= it2++); ) { DBUG_ASSERT(lex2->sphead); if (Sp_handler::eq_routine_name(lex2->sphead->m_name, lex->sphead->m_name) && lex2->sphead->eq_routine_spec(lex->sphead)) { found= true; break; } } if (!found) { my_error(ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY, MYF(0), ErrConvDQName(lex->sphead).ptr()); return true; } } return false; } bool sp_package::validate_private_routines(THD *thd) { /* Check that all forwad declarations in CREATE PACKAGE BODY have implementations. */ List_iterator<LEX> it(m_routine_declarations); for (LEX *lex; (lex= it++); ) { bool found= false; DBUG_ASSERT(lex->sphead); List_iterator<LEX> it2(m_routine_implementations); for (LEX *lex2; (lex2= it2++); ) { DBUG_ASSERT(lex2->sphead); if (Sp_handler::eq_routine_name(lex2->sphead->m_name, lex->sphead->m_name) && lex2->sphead->eq_routine_spec(lex->sphead)) { found= true; break; } } if (!found) { my_error(ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED, MYF(0), ErrConvDQName(lex->sphead).ptr()); return true; } } return false; } LEX *sp_package::LexList::find(const LEX_CSTRING &name, enum_sp_type type) { List_iterator<LEX> it(*this); for (LEX *lex; (lex= it++); ) { DBUG_ASSERT(lex->sphead); const char *dot; if (lex->sphead->m_handler->type() == type && (dot= strrchr(lex->sphead->m_name.str, '.'))) { size_t ofs= dot + 1 - lex->sphead->m_name.str; LEX_CSTRING non_qualified_sphead_name= lex->sphead->m_name; non_qualified_sphead_name.str+= ofs; non_qualified_sphead_name.length-= ofs; if (Sp_handler::eq_routine_name(non_qualified_sphead_name, name)) return lex; } } return NULL; } LEX *sp_package::LexList::find_qualified(const LEX_CSTRING &name, enum_sp_type type) { List_iterator<LEX> it(*this); for (LEX *lex; (lex= it++); ) { DBUG_ASSERT(lex->sphead); if (lex->sphead->m_handler->type() == type && Sp_handler::eq_routine_name(lex->sphead->m_name, name)) return lex; } return NULL; } void sp_package::init_psi_share() { List_iterator<LEX> it(m_routine_implementations); for (LEX *lex; (lex= it++); ) { DBUG_ASSERT(lex->sphead); lex->sphead->init_psi_share(); } sp_head::init_psi_share(); } void sp_head::init(LEX *lex) { DBUG_ENTER("sp_head::init"); lex->spcont= m_pcont; if (!lex->spcont) DBUG_VOID_RETURN; /* Altough trg_table_fields list is used only in triggers we init for all types of stored procedures to simplify reset_lex()/restore_lex() code. */ lex->trg_table_fields.empty(); DBUG_VOID_RETURN; } void sp_head::init_sp_name(const sp_name *spname) { DBUG_ENTER("sp_head::init_sp_name"); /* Must be initialized in the parser. */ DBUG_ASSERT(spname && spname->m_db.str && spname->m_db.length); /* We have to copy strings to get them into the right memroot. */ Database_qualified_name::copy(&main_mem_root, spname->m_db, spname->m_name); m_explicit_name= spname->m_explicit_name; DBUG_VOID_RETURN; } void sp_head::init_psi_share() { m_sp_share= MYSQL_GET_SP_SHARE(m_handler->type(), m_db.str, static_cast<uint>(m_db.length), m_name.str, static_cast<uint>(m_name.length)); } void sp_head::set_body_start(THD *thd, const char *begin_ptr) { m_body_begin= begin_ptr; thd->m_parser_state->m_lip.body_utf8_start(thd, begin_ptr); } void sp_head::set_stmt_end(THD *thd) { Lex_input_stream *lip= & thd->m_parser_state->m_lip; /* shortcut */ const char *end_ptr= lip->get_cpp_ptr(); /* shortcut */ /* Make the string of parameters. */ if (m_param_begin && m_param_end) { m_params.length= m_param_end - m_param_begin; m_params.str= thd->strmake(m_param_begin, m_params.length); } /* Remember end pointer for further dumping of whole statement. */ thd->lex->stmt_definition_end= end_ptr; /* Make the string of body (in the original character set). */ m_body.length= end_ptr - m_body_begin; m_body.str= thd->strmake(m_body_begin, m_body.length); trim_whitespace(thd->charset(), &m_body); /* Make the string of UTF-body. */ lip->body_utf8_append(end_ptr); m_body_utf8.length= lip->get_body_utf8_length(); m_body_utf8.str= thd->strmake(lip->get_body_utf8_str(), m_body_utf8.length); trim_whitespace(thd->charset(), &m_body_utf8); /* Make the string of whole stored-program-definition query (in the original character set). */ m_defstr.length= end_ptr - lip->get_cpp_buf(); m_defstr.str= thd->strmake(lip->get_cpp_buf(), m_defstr.length); trim_whitespace(thd->charset(), &m_defstr); } sp_head::~sp_head() { LEX *lex; sp_instr *i; DBUG_ENTER("sp_head::~sp_head"); /* sp_head::restore_thd_mem_root() must already have been called. */ DBUG_ASSERT(m_thd == NULL); for (uint ip = 0 ; (i = get_instr(ip)) ; ip++) delete i; delete_dynamic(&m_instr); delete m_pcont; free_items(); /* If we have non-empty LEX stack then we just came out of parser with error. Now we should delete all auxilary LEXes and restore original THD::lex. It is safe to not update LEX::ptr because further query string parsing and execution will be stopped anyway. */ while ((lex= (LEX *)m_lex.pop())) { THD *thd= lex->thd; thd->lex->sphead= NULL; lex_end(thd->lex); delete thd->lex; thd->lex= lex; } my_hash_free(&m_sptabs); my_hash_free(&m_sroutines); sp_head::destroy(m_next_cached_sp); DBUG_VOID_RETURN; } void sp_package::LexList::cleanup() { List_iterator<LEX> it(*this); for (LEX *lex; (lex= it++); ) { lex_end(lex); delete lex; } } /** This is only used for result fields from functions (both during fix_length_and_dec() and evaluation). */ Field * sp_head::create_result_field(uint field_max_length, const LEX_CSTRING *field_name, TABLE *table) const { Field *field; LEX_CSTRING name; DBUG_ENTER("sp_head::create_result_field"); /* m_return_field_def.length is always set to the field length calculated by the parser, according to the RETURNS clause. See prepare_create_field() in sql_table.cc. Value examples, depending on data type: - 11 for INT (character representation length) - 20 for BIGINT (character representation length) - 22 for DOUBLE (character representation length) - N for CHAR(N) CHARACTER SET latin1 (octet length) - 3*N for CHAR(N) CHARACTER SET utf8 (octet length) - 8 for blob-alike data types (packed length !!!) field_max_length is also set according to the data type in the RETURNS clause but can have different values depending on the execution stage: 1. During direct execution: field_max_length is 0, because Item_func_sp::fix_length_and_dec() has not been called yet, so Item_func_sp::max_length is 0 by default. 2a. During PREPARE: field_max_length is 0, because Item_func_sp::fix_length_and_dec() has not been called yet. It's called after create_result_field(). 2b. During EXEC: field_max_length is set to the maximum possible octet length of the RETURNS data type. - N for CHAR(N) CHARACTER SET latin1 (octet length) - 3*N for CHAR(N) CHARACTER SET utf8 (octet length) - 255 for TINYBLOB (octet length, not packed length !!!) Perhaps we should refactor prepare_create_field() to set Create_field::length to maximum octet length for BLOBs, instead of packed length). Note, for integer data types, field_max_length can be bigger than the user specified length, e.g. a field of the INT(1) data type is translated to the item with max_length=11. */ DBUG_ASSERT(field_max_length <= m_return_field_def.length || m_return_field_def.type_handler()->cmp_type() == INT_RESULT || (current_thd->stmt_arena->is_stmt_execute() && m_return_field_def.length == 8 && (m_return_field_def.pack_flag & (FIELDFLAG_BLOB|FIELDFLAG_GEOM)))); if (field_name) name= *field_name; else name= m_name; field= m_return_field_def.make_field(table->s, /* TABLE_SHARE ptr */ table->in_use->mem_root, &name); field->vcol_info= m_return_field_def.vcol_info; if (field) field->init(table); DBUG_RETURN(field); } int cmp_rqp_locations(Rewritable_query_parameter * const *a, Rewritable_query_parameter * const *b) { return (int)((*a)->pos_in_query - (*b)->pos_in_query); } /* StoredRoutinesBinlogging This paragraph applies only to statement-based binlogging. Row-based binlogging does not need anything special like this. Top-down overview: 1. Statements Statements that have is_update_query(stmt) == TRUE are written into the binary log verbatim. Examples: UPDATE tbl SET tbl.x = spfunc_w_side_effects() UPDATE tbl SET tbl.x=1 WHERE spfunc_w_side_effect_that_returns_false(tbl.y) Statements that have is_update_query(stmt) == FALSE (e.g. SELECTs) are not written into binary log. Instead we catch function calls the statement makes and write it into binary log separately (see #3). 2. PROCEDURE calls CALL statements are not written into binary log. Instead * Any FUNCTION invocation (in SET, IF, WHILE, OPEN CURSOR and other SP instructions) is written into binlog separately. * Each statement executed in SP is binlogged separately, according to rules in #1, with the exception that we modify query string: we replace uses of SP local variables with NAME_CONST('spvar_name', <spvar-value>) calls. This substitution is done in subst_spvars(). 3. FUNCTION calls In sp_head::execute_function(), we check * If this function invocation is done from a statement that is written into the binary log. * If there were any attempts to write events to the binary log during function execution (grep for start_union_events and stop_union_events) If the answers are No and Yes, we write the function call into the binary log as "SELECT spfunc(<param1value>, <param2value>, ...)" 4. Miscellaneous issues. 4.1 User variables. When we call mysql_bin_log.write() for an SP statement, thd->user_var_events must hold set<{var_name, value}> pairs for all user variables used during the statement execution. This set is produced by tracking user variable reads during statement execution. For SPs, this has the following implications: 1) thd->user_var_events may contain events from several SP statements and needs to be valid after exection of these statements was finished. In order to achieve that, we * Allocate user_var_events array elements on appropriate mem_root (grep for user_var_events_alloc). * Use is_query_in_union() to determine if user_var_event is created. 2) We need to empty thd->user_var_events after we have wrote a function call. This is currently done by making reset_dynamic(&thd->user_var_events); calls in several different places. (TODO cosider moving this into mysql_bin_log.write() function) 4.2 Auto_increment storage in binlog As we may write two statements to binlog from one single logical statement (case of "SELECT func1(),func2()": it is binlogged as "SELECT func1()" and then "SELECT func2()"), we need to reset auto_increment binlog variables after each binlogged SELECT. Otherwise, the auto_increment value of the first SELECT would be used for the second too. */ /** Replace thd->query{_length} with a string that one can write to the binlog. The binlog-suitable string is produced by replacing references to SP local variables with NAME_CONST('sp_var_name', value) calls. @param thd Current thread. @param instr Instruction (we look for Item_splocal instances in instr->free_list) @param query_str Original query string @return - FALSE on success. thd->query{_length} either has been appropriately replaced or there is no need for replacements. - TRUE out of memory error. */ static bool subst_spvars(THD *thd, sp_instr *instr, LEX_STRING *query_str) { DBUG_ENTER("subst_spvars"); Dynamic_array<Rewritable_query_parameter*> rewritables(PSI_INSTRUMENT_MEM); char *pbuf; StringBuffer<512> qbuf; Copy_query_with_rewrite acc(thd, query_str->str, query_str->length, &qbuf); /* Find rewritable Items used in this statement */ for (Item *item= instr->free_list; item; item= item->next) { Rewritable_query_parameter *rqp= item->get_rewritable_query_parameter(); if (rqp && rqp->pos_in_query) rewritables.append(rqp); } if (!rewritables.elements()) DBUG_RETURN(FALSE); rewritables.sort(cmp_rqp_locations); thd->query_name_consts= (uint)rewritables.elements(); for (Rewritable_query_parameter **rqp= rewritables.front(); rqp <= rewritables.back(); rqp++) { if (acc.append(*rqp)) DBUG_RETURN(TRUE); } if (acc.finalize()) DBUG_RETURN(TRUE); /* Allocate additional space at the end of the new query string for the query_cache_send_result_to_client function. The query buffer layout is: buffer :== <statement> The input statement(s) '\0' Terminating null char <length> Length of following current database name 2 <db_name> Name of current database <flags> Flags struct */ size_t buf_len= (qbuf.length() + 1 + QUERY_CACHE_DB_LENGTH_SIZE + thd->db.length + QUERY_CACHE_FLAGS_SIZE + 1); if ((pbuf= (char *) alloc_root(thd->mem_root, buf_len))) { char *ptr= pbuf + qbuf.length(); memcpy(pbuf, qbuf.ptr(), qbuf.length()); *ptr= 0; int2store(ptr+1, thd->db.length); } else DBUG_RETURN(TRUE); thd->set_query(pbuf, qbuf.length()); DBUG_RETURN(FALSE); } void Sp_handler_procedure::recursion_level_error(THD *thd, const sp_head *sp) const { my_error(ER_SP_RECURSION_LIMIT, MYF(0), static_cast<int>(thd->variables.max_sp_recursion_depth), sp->m_name.str); } /** Execute the routine. The main instruction jump loop is there. Assume the parameters already set. @param thd Thread context. @param merge_da_on_success Flag specifying if Warning Info should be propagated to the caller on Completion Condition or not. @todo - Will write this SP statement into binlog separately (TODO: consider changing the condition to "not inside event union") @return Error status. @retval FALSE on success @retval TRUE on error */ bool sp_head::execute(THD *thd, bool merge_da_on_success) { DBUG_ENTER("sp_head::execute"); char saved_cur_db_name_buf[SAFE_NAME_LEN+1]; LEX_STRING saved_cur_db_name= { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) }; bool cur_db_changed= FALSE; sp_rcontext *ctx= thd->spcont; bool err_status= FALSE; uint ip= 0; sql_mode_t save_sql_mode; // TODO(cvicentiu) See if you can drop this bit. This is used to resume // execution from where we left off. if (m_chistics.agg_type == GROUP_AGGREGATE) ip= thd->spcont->instr_ptr; bool save_abort_on_warning; Query_arena *old_arena; /* per-instruction arena */ MEM_ROOT execute_mem_root; Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP), backup_arena; query_id_t old_query_id; CSET_STRING old_query; TABLE *old_derived_tables; TABLE *old_rec_tables; LEX *old_lex; Item_change_list old_change_list; String old_packet; uint old_server_status; const uint status_backup_mask= SERVER_STATUS_CURSOR_EXISTS | SERVER_STATUS_LAST_ROW_SENT; MEM_ROOT *user_var_events_alloc_saved= 0; Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer; Object_creation_ctx *UNINIT_VAR(saved_creation_ctx); Diagnostics_area *da= thd->get_stmt_da(); Warning_info sp_wi(da->warning_info_id(), false, true); /* this 7*STACK_MIN_SIZE is a complex matter with a long history (see it!) */ if (check_stack_overrun(thd, 7 * STACK_MIN_SIZE, (uchar*)&old_packet)) DBUG_RETURN(TRUE); opt_trace_disable_if_no_security_context_access(thd); /* init per-instruction memroot */ init_sql_alloc(key_memory_sp_head_execute_root, &execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(0)); DBUG_ASSERT(!(m_flags & IS_INVOKED)); m_flags|= IS_INVOKED; if (m_parent) m_parent->m_invoked_subroutine_count++; m_first_instance->m_first_free_instance= m_next_cached_sp; if (m_next_cached_sp) { DBUG_PRINT("info", ("first free for %p ++: %p->%p level: %lu flags %x", m_first_instance, this, m_next_cached_sp, m_next_cached_sp->m_recursion_level, m_next_cached_sp->m_flags)); } /* Check that if there are not any instances after this one then pointer to the last instance points on this instance or if there are some instances after this one then recursion level of next instance greater then recursion level of current instance on 1 */ DBUG_ASSERT((m_next_cached_sp == 0 && m_first_instance->m_last_cached_sp == this) || (m_recursion_level + 1 == m_next_cached_sp->m_recursion_level)); /* NOTE: The SQL Standard does not specify the context that should be preserved for stored routines. However, at SAP/Walldorf meeting it was decided that current database should be preserved. */ if (m_db.length && (err_status= mysql_opt_change_db(thd, &m_db, &saved_cur_db_name, FALSE, &cur_db_changed))) { goto done; } thd->is_slave_error= 0; old_arena= thd->stmt_arena; /* Push a new warning information area. */ da->copy_sql_conditions_to_wi(thd, &sp_wi); da->push_warning_info(&sp_wi); /* Switch query context. This has to be done early as this is sometimes allocated on THD::mem_root */ if (m_creation_ctx) saved_creation_ctx= m_creation_ctx->set_n_backup(thd); /* We have to save/restore this info when we are changing call level to be able properly do close_thread_tables() in instructions. */ old_query_id= thd->query_id; old_query= thd->query_string; old_derived_tables= thd->derived_tables; thd->derived_tables= 0; old_rec_tables= thd->rec_tables; thd->rec_tables= 0; save_sql_mode= thd->variables.sql_mode; thd->variables.sql_mode= m_sql_mode; save_abort_on_warning= thd->abort_on_warning; thd->abort_on_warning= 0; /** When inside a substatement (a stored function or trigger statement), clear the metadata observer in THD, if any. Remember the value of the observer here, to be able to restore it when leaving the substatement. We reset the observer to suppress errors when a substatement uses temporary tables. If a temporary table does not exist at start of the main statement, it's not prelocked and thus is not validated with other prelocked tables. Later on, when the temporary table is opened, metadata versions mismatch, expectedly. The proper solution for the problem is to re-validate tables of substatements (Bug#12257, Bug#27011, Bug#32868, Bug#33000), but it's not implemented yet. */ thd->m_reprepare_observer= 0; /* It is also more efficient to save/restore current thd->lex once when do it in each instruction */ old_lex= thd->lex; /* We should also save Item tree change list to avoid rollback something too early in the calling query. */ thd->Item_change_list::move_elements_to(&old_change_list); /* Cursors will use thd->packet, so they may corrupt data which was prepared for sending by upper level. OTOH cursors in the same routine can share this buffer safely so let use use routine-local packet instead of having own packet buffer for each cursor. It is probably safe to use same thd->convert_buff everywhere. */ old_packet.swap(thd->packet); old_server_status= thd->server_status & status_backup_mask; /* Switch to per-instruction arena here. We can do it since we cleanup arena after every instruction. */ thd->set_n_backup_active_arena(&execute_arena, &backup_arena); /* Save callers arena in order to store instruction results and out parameters in it later during sp_eval_func_item() */ thd->spcont->callers_arena= &backup_arena; #if defined(ENABLED_PROFILING) /* Discard the initial part of executing routines. */ thd->profiling.discard_current_query(); #endif sp_instr *i; DEBUG_SYNC(thd, "sp_head_execute_before_loop"); do { #if defined(ENABLED_PROFILING) /* Treat each "instr" of a routine as discrete unit that could be profiled. Profiling only records information for segments of code that set the source of the query, and almost all kinds of instructions in s-p do not. */ thd->profiling.finish_current_query(); thd->profiling.start_new_query("continuing inside routine"); #endif /* get_instr returns NULL when we're done. */ i = get_instr(ip); if (i == NULL) { #if defined(ENABLED_PROFILING) thd->profiling.discard_current_query(); #endif thd->spcont->quit_func= TRUE; break; } /* Reset number of warnings for this query. */ thd->get_stmt_da()->reset_for_next_command(); DBUG_PRINT("execute", ("Instruction %u", ip)); /* We need to reset start_time to allow for time to flow inside a stored procedure. This is only done for SP since time is suppose to be constant during execution of triggers and functions. */ reset_start_time_for_sp(thd); /* We have to set thd->stmt_arena before executing the instruction to store in the instruction free_list all new items, created during the first execution (for example expanding of '*' or the items made during other permanent subquery transformations). */ thd->stmt_arena= i; /* Will write this SP statement into binlog separately. TODO: consider changing the condition to "not inside event union". */ if (thd->locked_tables_mode <= LTM_LOCK_TABLES) { user_var_events_alloc_saved= thd->user_var_events_alloc; thd->user_var_events_alloc= thd->mem_root; } sql_digest_state *parent_digest= thd->m_digest; thd->m_digest= NULL; #ifdef WITH_WSREP if (WSREP(thd) && thd->wsrep_next_trx_id() == WSREP_UNDEFINED_TRX_ID) { thd->set_wsrep_next_trx_id(thd->query_id); WSREP_DEBUG("assigned new next trx ID for SP, trx id: %" PRIu64, thd->wsrep_next_trx_id()); } #endif /* WITH_WSREP */ #ifdef HAVE_PSI_STATEMENT_INTERFACE PSI_statement_locker_state state; PSI_statement_locker *parent_locker; PSI_statement_info *psi_info = i->get_psi_info(); parent_locker= thd->m_statement_psi; thd->m_statement_psi= MYSQL_START_STATEMENT(& state, psi_info->m_key, thd->db.str, thd->db.length, thd->charset(), m_sp_share); #endif err_status= i->execute(thd, &ip); #ifdef HAVE_PSI_STATEMENT_INTERFACE MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da()); thd->m_statement_psi= parent_locker; #endif #ifdef WITH_WSREP if (WSREP(thd)) { if (((thd->wsrep_trx().state() == wsrep::transaction::s_executing || thd->in_sub_stmt) && (thd->is_fatal_error || thd->killed))) { WSREP_DEBUG("SP abort err status %d in sub %d trx state %d", err_status, thd->in_sub_stmt, thd->wsrep_trx().state()); err_status= 1; thd->is_fatal_error= 1; /* SP was killed, and it is not due to a wsrep conflict. We skip after_command hook at this point because otherwise it clears the error, and cleans up the whole transaction. For now we just return and finish our handling once we are back to mysql_parse. Same applies to a SP execution, which was aborted due to wsrep related conflict, but which is executing as sub statement. SP in sub statement level should not commit not rollback, we have to call for rollback is up-most SP level. */ WSREP_DEBUG("Skipping after_command hook for killed SP"); } else { const bool must_replay= wsrep_must_replay(thd); if (must_replay) { WSREP_DEBUG("MUST_REPLAY set after SP, err_status %d trx state: %d", err_status, thd->wsrep_trx().state()); } if (wsrep_thd_is_local(thd)) (void) wsrep_after_statement(thd); /* Reset the return code to zero if the transaction was replayed successfully. */ if (must_replay && !wsrep_current_error(thd)) { err_status= 0; thd->get_stmt_da()->reset_diagnostics_area(); } /* Final wsrep error status for statement is known only after wsrep_after_statement() call. If the error is set, override error in thd diagnostics area and reset wsrep client_state error so that the error does not get propagated via client-server protocol. */ if (wsrep_current_error(thd)) { wsrep_override_error(thd, wsrep_current_error(thd), wsrep_current_error_status(thd)); thd->wsrep_cs().reset_error(); /* Reset also thd->killed if it has been set during BF abort. */ if (thd->killed == KILL_QUERY) thd->killed= NOT_KILLED; /* if failed transaction was not replayed, must return with error from here */ if (!must_replay) err_status = 1; } } } #endif /* WITH_WSREP */ thd->m_digest= parent_digest; if (i->free_list) cleanup_items(i->free_list); /* If we've set thd->user_var_events_alloc to mem_root of this SP statement, clean all the events allocated in it. */ if (thd->locked_tables_mode <= LTM_LOCK_TABLES) { reset_dynamic(&thd->user_var_events); thd->user_var_events_alloc= user_var_events_alloc_saved; } /* we should cleanup free_list and memroot, used by instruction */ thd->cleanup_after_query(); free_root(&execute_mem_root, MYF(0)); /* Find and process SQL handlers unless it is a fatal error (fatal errors are not catchable by SQL handlers) or the connection has been killed during execution. */ if (likely(!thd->is_fatal_error) && likely(!thd->killed_errno()) && ctx->handle_sql_condition(thd, &ip, i)) { err_status= FALSE; } /* Reset sp_rcontext::end_partial_result_set flag. */ ctx->end_partial_result_set= FALSE; } while (!err_status && likely(!thd->killed) && likely(!thd->is_fatal_error) && !thd->spcont->pause_state); #if defined(ENABLED_PROFILING) thd->profiling.finish_current_query(); thd->profiling.start_new_query("tail end of routine"); #endif /* Restore query context. */ if (m_creation_ctx) m_creation_ctx->restore_env(thd, saved_creation_ctx); /* Restore arena. */ thd->restore_active_arena(&execute_arena, &backup_arena); /* Only pop cursors when we're done with group aggregate running. */ if (m_chistics.agg_type != GROUP_AGGREGATE || (m_chistics.agg_type == GROUP_AGGREGATE && thd->spcont->quit_func)) thd->spcont->pop_all_cursors(thd); // To avoid memory leaks after an error /* Restore all saved */ if (m_chistics.agg_type == GROUP_AGGREGATE) thd->spcont->instr_ptr= ip; thd->server_status= (thd->server_status & ~status_backup_mask) | old_server_status; old_packet.swap(thd->packet); DBUG_ASSERT(thd->Item_change_list::is_empty()); old_change_list.move_elements_to(thd); thd->lex= old_lex; thd->set_query_id(old_query_id); thd->set_query_inner(old_query); DBUG_ASSERT(!thd->derived_tables); thd->derived_tables= old_derived_tables; thd->rec_tables= old_rec_tables; thd->variables.sql_mode= save_sql_mode; thd->abort_on_warning= save_abort_on_warning; thd->m_reprepare_observer= save_reprepare_observer; thd->stmt_arena= old_arena; state= STMT_EXECUTED; /* Restore the caller's original warning information area: - warnings generated during trigger execution should not be propagated to the caller on success; - if there was an exception during execution, warning info should be propagated to the caller in any case. */ da->pop_warning_info(); if (err_status || merge_da_on_success) { /* If a routine body is empty or if a routine did not generate any warnings, do not duplicate our own contents by appending the contents of the called routine. We know that the called routine did not change its warning info. On the other hand, if the routine body is not empty and some statement in the routine generates a warning or uses tables, warning info is guaranteed to have changed. In this case we know that the routine warning info contains only new warnings, and thus we perform a copy. */ if (da->warning_info_changed(&sp_wi)) { /* If the invocation of the routine was a standalone statement, rather than a sub-statement, in other words, if it's a CALL of a procedure, rather than invocation of a function or a trigger, we need to clear the current contents of the caller's warning info. This is per MySQL rules: if a statement generates a warning, warnings from the previous statement are flushed. Normally it's done in push_warning(). However, here we don't use push_warning() to avoid invocation of condition handlers or escalation of warnings to errors. */ da->opt_clear_warning_info(thd->query_id); da->copy_sql_conditions_from_wi(thd, &sp_wi); da->remove_marked_sql_conditions(); if (i != NULL) push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SP_STACK_TRACE, ER_THD(thd, ER_SP_STACK_TRACE), i->m_lineno, m_qname.str != NULL ? m_qname.str : "anonymous block"); } } done: DBUG_PRINT("info", ("err_status: %d killed: %d is_slave_error: %d report_error: %d", err_status, thd->killed, thd->is_slave_error, thd->is_error())); if (thd->killed) err_status= TRUE; /* If the DB has changed, the pointer has changed too, but the original thd->db will then have been freed */ if (cur_db_changed && thd->killed != KILL_CONNECTION) { /* Force switching back to the saved current database, because it may be NULL. In this case, mysql_change_db() would generate an error. */ err_status|= mysql_change_db(thd, (LEX_CSTRING*)&saved_cur_db_name, TRUE) != 0; } m_flags&= ~IS_INVOKED; if (m_parent) m_parent->m_invoked_subroutine_count--; DBUG_PRINT("info", ("first free for %p --: %p->%p, level: %lu, flags %x", m_first_instance, m_first_instance->m_first_free_instance, this, m_recursion_level, m_flags)); /* Check that we have one of following: 1) there are not free instances which means that this instance is last in the list of instances (pointer to the last instance point on it and ther are not other instances after this one in the list) 2) There are some free instances which mean that first free instance should go just after this one and recursion level of that free instance should be on 1 more then recursion level of this instance. */ DBUG_ASSERT((m_first_instance->m_first_free_instance == 0 && this == m_first_instance->m_last_cached_sp && m_next_cached_sp == 0) || (m_first_instance->m_first_free_instance != 0 && m_first_instance->m_first_free_instance == m_next_cached_sp && m_first_instance->m_first_free_instance->m_recursion_level == m_recursion_level + 1)); m_first_instance->m_first_free_instance= this; DBUG_RETURN(err_status); } #ifndef NO_EMBEDDED_ACCESS_CHECKS /** set_routine_security_ctx() changes routine security context, and checks if there is an EXECUTE privilege in new context. If there is no EXECUTE privilege, it changes the context back and returns a error. @param thd thread handle @param sp stored routine to change the context for @param save_ctx pointer to an old security context @todo - Cache if the definer has the right to use the object on the first usage and only reset the cache if someone does a GRANT statement that 'may' affect this. @retval TRUE if there was a error, and the context wasn't changed. @retval FALSE if the context was changed. */ bool set_routine_security_ctx(THD *thd, sp_head *sp, Security_context **save_ctx) { *save_ctx= 0; if (sp->suid() != SP_IS_NOT_SUID && sp->m_security_ctx.change_security_context(thd, &sp->m_definer.user, &sp->m_definer.host, &sp->m_db, save_ctx)) return TRUE; /* If we changed context to run as another user, we need to check the access right for the new context again as someone may have revoked the right to use the procedure from this user. TODO: Cache if the definer has the right to use the object on the first usage and only reset the cache if someone does a GRANT statement that 'may' affect this. */ if (*save_ctx && sp->check_execute_access(thd)) { sp->m_security_ctx.restore_security_context(thd, *save_ctx); *save_ctx= 0; return TRUE; } return FALSE; } #endif // ! NO_EMBEDDED_ACCESS_CHECKS bool sp_head::check_execute_access(THD *thd) const { return m_parent ? m_parent->check_execute_access(thd) : check_routine_access(thd, EXECUTE_ACL, &m_db, &m_name, m_handler, false); } /** Create rcontext optionally using the routine security. This is important for sql_mode=ORACLE to make sure that the invoker has access to the tables mentioned in the %TYPE references. In non-Oracle sql_modes we do not need access to any tables, so we can omit the security context switch for performance purposes. @param thd @param ret_value @retval NULL - error (access denided or EOM) @retval !NULL - success (the invoker has rights to all %TYPE tables) */ sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value, Row_definition_list *defs, bool switch_security_ctx) { if (!(m_flags & HAS_COLUMN_TYPE_REFS)) return sp_rcontext::create(thd, this, m_pcont, ret_value, *defs); sp_rcontext *res= NULL; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_security_ctx; if (switch_security_ctx && set_routine_security_ctx(thd, this, &save_security_ctx)) return NULL; #endif if (!defs->resolve_type_refs(thd)) res= sp_rcontext::create(thd, this, m_pcont, ret_value, *defs); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (switch_security_ctx) m_security_ctx.restore_security_context(thd, save_security_ctx); #endif return res; } sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value, List<Item> *args) { DBUG_ASSERT(args); Row_definition_list defs; m_pcont->retrieve_field_definitions(&defs); if (defs.adjust_formal_params_to_actual_params(thd, args)) return NULL; return rcontext_create(thd, ret_value, &defs, true); } sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value, Item **args, uint arg_count) { Row_definition_list defs; m_pcont->retrieve_field_definitions(&defs); if (defs.adjust_formal_params_to_actual_params(thd, args, arg_count)) return NULL; return rcontext_create(thd, ret_value, &defs, true); } /** Execute trigger stored program. - changes security context for triggers - switch to new memroot - call sp_head::execute - restore old memroot - restores security context @param thd Thread handle @param db database name @param table table name @param grant_info GRANT_INFO structure to be filled with information about definer's privileges on subject table @todo - TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a trigger. @retval FALSE on success @retval TRUE on error */ bool sp_head::execute_trigger(THD *thd, const LEX_CSTRING *db_name, const LEX_CSTRING *table_name, GRANT_INFO *grant_info) { sp_rcontext *octx = thd->spcont; sp_rcontext *nctx = NULL; bool err_status= FALSE; MEM_ROOT call_mem_root; Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP); Query_arena backup_arena; DBUG_ENTER("sp_head::execute_trigger"); DBUG_PRINT("info", ("trigger %s", m_name.str)); #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_ctx= NULL; if (suid() != SP_IS_NOT_SUID && m_security_ctx.change_security_context(thd, &m_definer.user, &m_definer.host, &m_db, &save_ctx)) DBUG_RETURN(TRUE); /* Fetch information about table-level privileges for subject table into GRANT_INFO instance. The access check itself will happen in Item_trigger_field, where this information will be used along with information about column-level privileges. */ fill_effective_table_privileges(thd, grant_info, db_name->str, table_name->str); /* Check that the definer has TRIGGER privilege on the subject table. */ if (!(grant_info->privilege & TRIGGER_ACL)) { char priv_desc[128]; get_privilege_desc(priv_desc, sizeof(priv_desc), TRIGGER_ACL); my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), priv_desc, thd->security_ctx->priv_user, thd->security_ctx->host_or_ip, table_name->str); m_security_ctx.restore_security_context(thd, save_ctx); DBUG_RETURN(TRUE); } #endif // NO_EMBEDDED_ACCESS_CHECKS /* Prepare arena and memroot for objects which lifetime is whole duration of trigger call (sp_rcontext, it's tables and items, sp_cursor and Item_cache holders for case expressions). We can't use caller's arena/memroot for those objects because in this case some fixed amount of memory will be consumed for each trigger invocation and so statements which involve lot of them will hog memory. TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a trigger. */ init_sql_alloc(key_memory_sp_head_call_root, &call_mem_root, MEM_ROOT_BLOCK_SIZE, 0, MYF(0)); thd->set_n_backup_active_arena(&call_arena, &backup_arena); Row_definition_list defs; m_pcont->retrieve_field_definitions(&defs); if (!(nctx= rcontext_create(thd, NULL, &defs, false))) { err_status= TRUE; goto err_with_cleanup; } thd->spcont= nctx; MYSQL_RUN_SP(this, err_status= execute(thd, FALSE)); err_with_cleanup: thd->restore_active_arena(&call_arena, &backup_arena); #ifndef NO_EMBEDDED_ACCESS_CHECKS m_security_ctx.restore_security_context(thd, save_ctx); #endif // NO_EMBEDDED_ACCESS_CHECKS delete nctx; call_arena.free_items(); free_root(&call_mem_root, MYF(0)); thd->spcont= octx; if (thd->killed) thd->send_kill_message(); DBUG_RETURN(err_status); } /* Execute the package initialization section. */ bool sp_package::instantiate_if_needed(THD *thd) { List<Item> args; if (m_is_instantiated) return false; /* Set m_is_instantiated to true early, to avoid recursion in case if the package initialization section calls routines from the same package. */ m_is_instantiated= true; /* Check that the initialization section doesn't contain Dynamic SQL and doesn't return result sets: such stored procedures can't be called from a function or trigger. */ if (thd->in_sub_stmt) { const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ? "trigger" : "function"); if (is_not_allowed_in_function(where)) goto err; } args.elements= 0; if (execute_procedure(thd, &args)) goto err; return false; err: m_is_instantiated= false; return true; } /** Execute a function. - evaluate parameters - changes security context for SUID routines - switch to new memroot - call sp_head::execute - restore old memroot - evaluate the return value - restores security context @param thd Thread handle @param argp Passed arguments (these are items from containing statement?) @param argcount Number of passed arguments. We need to check if this is correct. @param return_value_fld Save result here. @todo We should create sp_rcontext once per command and reuse it on subsequent executions of a function/trigger. @todo In future we should associate call arena/mem_root with sp_rcontext and allocate all these objects (and sp_rcontext itself) on it directly rather than juggle with arenas. @retval FALSE on success @retval TRUE on error */ bool sp_head::execute_function(THD *thd, Item **argp, uint argcount, Field *return_value_fld, sp_rcontext **func_ctx, Query_arena *call_arena) { ulonglong UNINIT_VAR(binlog_save_options); bool need_binlog_call= FALSE; uint arg_no; sp_rcontext *octx = thd->spcont; char buf[STRING_BUFFER_USUAL_SIZE]; String binlog_buf(buf, sizeof(buf), &my_charset_bin); bool err_status= FALSE; Query_arena backup_arena; DBUG_ENTER("sp_head::execute_function"); DBUG_PRINT("info", ("function %s", m_name.str)); if (m_parent && m_parent->instantiate_if_needed(thd)) DBUG_RETURN(true); /* Check that the function is called with all specified arguments. If it is not, use my_error() to report an error, or it will not terminate the invoking query properly. */ if (argcount != m_pcont->context_var_count()) { /* Need to use my_error here, or it will not terminate the invoking query properly. */ my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "FUNCTION", ErrConvDQName(this).ptr(), m_pcont->context_var_count(), argcount); DBUG_RETURN(TRUE); } /* Prepare arena and memroot for objects which lifetime is whole duration of function call (sp_rcontext, it's tables and items, sp_cursor and Item_cache holders for case expressions). We can't use caller's arena/memroot for those objects because in this case some fixed amount of memory will be consumed for each function/trigger invocation and so statements which involve lot of them will hog memory. TODO: we should create sp_rcontext once per command and reuse it on subsequent executions of a function/trigger. */ if (!(*func_ctx)) { thd->set_n_backup_active_arena(call_arena, &backup_arena); if (!(*func_ctx= rcontext_create(thd, return_value_fld, argp, argcount))) { thd->restore_active_arena(call_arena, &backup_arena); err_status= TRUE; goto err_with_cleanup; } /* We have to switch temporarily back to callers arena/memroot. Function arguments belong to the caller and so the may reference memory which they will allocate during calculation long after this function call will be finished (e.g. in Item::cleanup()). */ thd->restore_active_arena(call_arena, &backup_arena); } /* Pass arguments. */ for (arg_no= 0; arg_no < argcount; arg_no++) { /* Arguments must be fixed in Item_func_sp::fix_fields */ DBUG_ASSERT(argp[arg_no]->fixed()); err_status= bind_input_param(thd, argp[arg_no], arg_no, *func_ctx, TRUE); if (err_status) goto err_with_cleanup; } /* If row-based binlogging, we don't need to binlog the function's call, let each substatement be binlogged its way. */ need_binlog_call= mysql_bin_log.is_open() && (thd->variables.option_bits & OPTION_BIN_LOG) && !thd->is_current_stmt_binlog_format_row(); /* Remember the original arguments for unrolled replication of functions before they are changed by execution. */ if (need_binlog_call) { binlog_buf.length(0); binlog_buf.append(STRING_WITH_LEN("SELECT ")); append_identifier(thd, &binlog_buf, &m_db); binlog_buf.append('.'); append_identifier(thd, &binlog_buf, &m_name); binlog_buf.append('('); for (arg_no= 0; arg_no < argcount; arg_no++) { String str_value_holder; String *str_value; if (arg_no) binlog_buf.append(','); Item_field *item= (*func_ctx)->get_parameter(arg_no); str_value= item->type_handler()->print_item_value(thd, item, &str_value_holder); if (str_value) binlog_buf.append(*str_value); else binlog_buf.append(NULL_clex_str); } binlog_buf.append(')'); } thd->spcont= *func_ctx; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_security_ctx; if (set_routine_security_ctx(thd, this, &save_security_ctx)) { err_status= TRUE; goto err_with_cleanup; } #endif if (need_binlog_call) { query_id_t q; reset_dynamic(&thd->user_var_events); /* In case of artificially constructed events for function calls we have separate union for each such event and hence can't use query_id of real calling statement as the start of all these unions (this will break logic of replication of user-defined variables). So we use artifical value which is guaranteed to be greater than all query_id's of all statements belonging to previous events/unions. Possible alternative to this is logging of all function invocations as one select and not resetting THD::user_var_events before each invocation. */ q= get_query_id(); mysql_bin_log.start_union_events(thd, q + 1); binlog_save_options= thd->variables.option_bits; thd->variables.option_bits&= ~OPTION_BIN_LOG; } opt_trace_disable_if_no_stored_proc_func_access(thd, this); /* Switch to call arena/mem_root so objects like sp_cursor or Item_cache holders for case expressions can be allocated on it. TODO: In future we should associate call arena/mem_root with sp_rcontext and allocate all these objects (and sp_rcontext itself) on it directly rather than juggle with arenas. */ thd->set_n_backup_active_arena(call_arena, &backup_arena); MYSQL_RUN_SP(this, err_status= execute(thd, TRUE)); thd->restore_active_arena(call_arena, &backup_arena); if (need_binlog_call) { mysql_bin_log.stop_union_events(thd); thd->variables.option_bits= binlog_save_options; if (thd->binlog_evt_union.unioned_events) { int errcode = query_error_code(thd, thd->killed == NOT_KILLED); Query_log_event qinfo(thd, binlog_buf.ptr(), binlog_buf.length(), thd->binlog_evt_union.unioned_events_trans, FALSE, FALSE, errcode); if (mysql_bin_log.write(&qinfo) && thd->binlog_evt_union.unioned_events_trans) { push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, "Invoked ROUTINE modified a transactional table but MySQL " "failed to reflect this change in the binary log"); err_status= TRUE; } reset_dynamic(&thd->user_var_events); /* Forget those values, in case more function calls are binlogged: */ thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0; thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty(); } } if (!err_status && thd->spcont->quit_func) { /* We need result only in function but not in trigger */ if (!(*func_ctx)->is_return_value_set()) { my_error(ER_SP_NORETURNEND, MYF(0), m_name.str); err_status= TRUE; } else { /* Copy back all OUT or INOUT values to the previous frame, or set global user variables */ for (arg_no= 0; arg_no < argcount; arg_no++) { err_status= bind_output_param(thd, argp[arg_no], arg_no, octx, *func_ctx); if (err_status) break; } } } #ifndef NO_EMBEDDED_ACCESS_CHECKS m_security_ctx.restore_security_context(thd, save_security_ctx); #endif err_with_cleanup: thd->spcont= octx; /* If not insided a procedure and a function printing warning messsages. */ if (need_binlog_call && thd->spcont == NULL && !thd->binlog_evt_union.do_union) thd->issue_unsafe_warnings(); DBUG_RETURN(err_status); } /** Execute a procedure. The function does the following steps: - Set all parameters - changes security context for SUID routines - call sp_head::execute - copy back values of INOUT and OUT parameters - restores security context @param thd Thread handle @param args List of values passed as arguments. @retval FALSE on success @retval TRUE on error */ bool sp_head::execute_procedure(THD *thd, List<Item> *args) { bool err_status= FALSE; uint params = m_pcont->context_var_count(); /* Query start time may be reset in a multi-stmt SP; keep this for later. */ ulonglong utime_before_sp_exec= thd->utime_after_lock; sp_rcontext *save_spcont, *octx; sp_rcontext *nctx = NULL; bool save_enable_slow_log; bool save_log_general= false; sp_package *pkg= get_package(); DBUG_ENTER("sp_head::execute_procedure"); DBUG_PRINT("info", ("procedure %s", m_name.str)); if (m_parent && m_parent->instantiate_if_needed(thd)) DBUG_RETURN(true); if (args->elements != params) { my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE", ErrConvDQName(this).ptr(), params, args->elements); DBUG_RETURN(TRUE); } save_spcont= octx= thd->spcont; if (! octx) { /* Create a temporary old context. */ if (!(octx= rcontext_create(thd, NULL, args))) { DBUG_PRINT("error", ("Could not create octx")); DBUG_RETURN(TRUE); } thd->spcont= octx; /* set callers_arena to thd, for upper-level function to work */ thd->spcont->callers_arena= thd; } if (!pkg) { if (!(nctx= rcontext_create(thd, NULL, args))) { delete nctx; /* Delete nctx if it was init() that failed. */ thd->spcont= save_spcont; DBUG_RETURN(TRUE); } } else { if (!pkg->m_rcontext) { Query_arena backup_arena; thd->set_n_backup_active_arena(this, &backup_arena); nctx= pkg->rcontext_create(thd, NULL, args); thd->restore_active_arena(this, &backup_arena); if (!nctx) { thd->spcont= save_spcont; DBUG_RETURN(TRUE); } pkg->m_rcontext= nctx; } else nctx= pkg->m_rcontext; } if (params > 0) { List_iterator<Item> it_args(*args); DBUG_PRINT("info",(" %.*s: eval args", (int) m_name.length, m_name.str)); for (uint i= 0 ; i < params ; i++) { Item *arg_item= it_args++; if (!arg_item) break; err_status= bind_input_param(thd, arg_item, i, nctx, FALSE); if (err_status) break; } /* Okay, got values for all arguments. Close tables that might be used by arguments evaluation. If arguments evaluation required prelocking mode, we'll leave it here. */ thd->lex->unit.cleanup(); if (!thd->in_sub_stmt) { thd->get_stmt_da()->set_overwrite_status(true); thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd); thd->get_stmt_da()->set_overwrite_status(false); } close_thread_tables(thd); thd_proc_info(thd, 0); if (! thd->in_sub_stmt) { if (thd->transaction_rollback_request) { trans_rollback_implicit(thd); thd->release_transactional_locks(); } else if (! thd->in_multi_stmt_transaction_mode()) thd->release_transactional_locks(); else thd->mdl_context.release_statement_locks(); } thd->rollback_item_tree_changes(); DBUG_PRINT("info",(" %.*s: eval args done", (int) m_name.length, m_name.str)); } save_enable_slow_log= thd->enable_slow_log; /* Disable slow log if: - Slow logging is enabled (no change needed) - This is a normal SP (not event log) - If we have not explicitely disabled logging of SP */ if (save_enable_slow_log && ((!(m_flags & LOG_SLOW_STATEMENTS) && (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_SP)))) { DBUG_PRINT("info", ("Disabling slow log for the execution")); thd->enable_slow_log= FALSE; } /* Disable general log if: - If general log is enabled (no change needed) - This is a normal SP (not event log) - If we have not explicitely disabled logging of SP */ if (!(thd->variables.option_bits & OPTION_LOG_OFF) && (!(m_flags & LOG_GENERAL_LOG) && (thd->variables.log_disabled_statements & LOG_DISABLE_SP))) { DBUG_PRINT("info", ("Disabling general log for the execution")); save_log_general= true; /* disable this bit */ thd->variables.option_bits |= OPTION_LOG_OFF; } thd->spcont= nctx; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *save_security_ctx= 0; if (!err_status) err_status= set_routine_security_ctx(thd, this, &save_security_ctx); #endif opt_trace_disable_if_no_stored_proc_func_access(thd, this); if (!err_status) MYSQL_RUN_SP(this, err_status= execute(thd, TRUE)); if (save_log_general) thd->variables.option_bits &= ~OPTION_LOG_OFF; thd->enable_slow_log= save_enable_slow_log; /* In the case when we weren't able to employ reuse mechanism for OUT/INOUT paranmeters, we should reallocate memory. This allocation should be done on the arena which will live through all execution of calling routine. */ thd->spcont->callers_arena= octx->callers_arena; if (!err_status && params > 0) { List_iterator<Item> it_args(*args); /* Copy back all OUT or INOUT values to the previous frame, or set global user variables */ for (uint i= 0 ; i < params ; i++) { Item *arg_item= it_args++; if (!arg_item) break; err_status= bind_output_param(thd, arg_item, i, octx, nctx); if (err_status) break; } } #ifndef NO_EMBEDDED_ACCESS_CHECKS if (save_security_ctx) m_security_ctx.restore_security_context(thd, save_security_ctx); #endif if (!save_spcont) delete octx; if (!pkg) delete nctx; thd->spcont= save_spcont; thd->utime_after_lock= utime_before_sp_exec; /* If not insided a procedure and a function printing warning messsages. */ bool need_binlog_call= mysql_bin_log.is_open() && (thd->variables.option_bits & OPTION_BIN_LOG) && !thd->is_current_stmt_binlog_format_row(); if (need_binlog_call && thd->spcont == NULL && !thd->binlog_evt_union.do_union) thd->issue_unsafe_warnings(); DBUG_RETURN(err_status); } bool sp_head::bind_input_param(THD *thd, Item *arg_item, uint arg_no, sp_rcontext *nctx, bool is_function) { DBUG_ENTER("sp_head::bind_input_param"); sp_variable *spvar= m_pcont->find_variable(arg_no); if (!spvar) DBUG_RETURN(FALSE); if (spvar->mode != sp_variable::MODE_IN) { Settable_routine_parameter *srp= arg_item->get_settable_routine_parameter(); if (!srp) { my_error(ER_SP_NOT_VAR_ARG, MYF(0), arg_no+1, ErrConvDQName(this).ptr()); DBUG_RETURN(TRUE); } if (is_function) { /* Check if the function is called from SELECT/INSERT/UPDATE/DELETE query and parameter is OUT or INOUT. If yes, it is an invalid call - throw error. */ if (thd->lex->sql_command == SQLCOM_SELECT || thd->lex->sql_command == SQLCOM_INSERT || thd->lex->sql_command == SQLCOM_INSERT_SELECT || thd->lex->sql_command == SQLCOM_UPDATE || thd->lex->sql_command == SQLCOM_DELETE) { my_error(ER_SF_OUT_INOUT_ARG_NOT_ALLOWED, MYF(0), arg_no+1, m_name.str); DBUG_RETURN(TRUE); } } srp->set_required_privilege(spvar->mode == sp_variable::MODE_INOUT); } if (spvar->mode == sp_variable::MODE_OUT) { Item_null *null_item= new (thd->mem_root) Item_null(thd); Item *tmp_item= null_item; if (!null_item || nctx->set_parameter(thd, arg_no, &tmp_item)) { DBUG_PRINT("error", ("set variable failed")); DBUG_RETURN(TRUE); } } else { if (nctx->set_parameter(thd, arg_no, &arg_item)) { DBUG_PRINT("error", ("set variable 2 failed")); DBUG_RETURN(TRUE); } } TRANSACT_TRACKER(add_trx_state_from_thd(thd)); DBUG_RETURN(FALSE); } bool sp_head::bind_output_param(THD *thd, Item *arg_item, uint arg_no, sp_rcontext *octx, sp_rcontext *nctx) { DBUG_ENTER("sp_head::bind_output_param"); sp_variable *spvar= m_pcont->find_variable(arg_no); if (spvar->mode == sp_variable::MODE_IN) DBUG_RETURN(FALSE); Settable_routine_parameter *srp= arg_item->get_settable_routine_parameter(); DBUG_ASSERT(srp); if (srp->set_value(thd, octx, nctx->get_variable_addr(arg_no))) { DBUG_PRINT("error", ("set value failed")); DBUG_RETURN(TRUE); } Send_field *out_param_info= new (thd->mem_root) Send_field(thd, nctx->get_parameter(arg_no)); out_param_info->db_name= m_db; out_param_info->table_name= m_name; out_param_info->org_table_name= m_name; out_param_info->col_name= spvar->name; out_param_info->org_col_name= spvar->name; srp->set_out_param_info(out_param_info); DBUG_RETURN(FALSE); } /** Reset lex during parsing, before we parse a sub statement. @param thd Thread handler. @return Error state @retval true An error occurred. @retval false Success. */ bool sp_head::reset_lex(THD *thd, sp_lex_local *sublex) { DBUG_ENTER("sp_head::reset_lex"); LEX *oldlex= thd->lex; thd->set_local_lex(sublex); DBUG_RETURN(m_lex.push_front(oldlex)); } bool sp_head::reset_lex(THD *thd) { DBUG_ENTER("sp_head::reset_lex"); sp_lex_local *sublex= new (thd->mem_root) sp_lex_local(thd, thd->lex); DBUG_RETURN(sublex ? reset_lex(thd, sublex) : true); } /** Restore lex during parsing, after we have parsed a sub statement. @param thd Thread handle @param oldlex The upper level lex we're near to restore to @param sublex The local lex we're near to restore from @return @retval TRUE failure @retval FALSE success */ bool sp_head::merge_lex(THD *thd, LEX *oldlex, LEX *sublex) { DBUG_ENTER("sp_head::merge_lex"); sublex->set_trg_event_type_for_tables(); oldlex->trg_table_fields.push_back(&sublex->trg_table_fields); /* If this substatement is unsafe, the entire routine is too. */ DBUG_PRINT("info", ("sublex->get_stmt_unsafe_flags: 0x%x", sublex->get_stmt_unsafe_flags())); unsafe_flags|= sublex->get_stmt_unsafe_flags(); /* Add routines which are used by statement to respective set for this routine. */ if (sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines)) DBUG_RETURN(TRUE); /* If this substatement is a update query, then mark MODIFIES_DATA */ if (is_update_query(sublex->sql_command)) m_flags|= MODIFIES_DATA; /* Merge tables used by this statement (but not by its functions or procedures) to multiset of tables used by this routine. */ merge_table_list(thd, sublex->query_tables, sublex); /* Merge lists of PS parameters. */ oldlex->param_list.append(&sublex->param_list); DBUG_RETURN(FALSE); } /** Put the instruction on the backpatch list, associated with the label. */ int sp_head::push_backpatch(THD *thd, sp_instr *i, sp_label *lab, List<bp_t> *list, backpatch_instr_type itype) { bp_t *bp= (bp_t *) thd->alloc(sizeof(bp_t)); if (!bp) return 1; bp->lab= lab; bp->instr= i; bp->instr_type= itype; return list->push_front(bp); } int sp_head::push_backpatch(THD *thd, sp_instr *i, sp_label *lab) { return push_backpatch(thd, i, lab, &m_backpatch, GOTO); } int sp_head::push_backpatch_goto(THD *thd, sp_pcontext *ctx, sp_label *lab) { uint ip= instructions(); /* Add cpop/hpop : they will be removed or updated later if target is in the same block or not */ sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, ctx, 0); if (hpop == NULL || add_instr(hpop)) return true; if (push_backpatch(thd, hpop, lab, &m_backpatch_goto, HPOP)) return true; sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, ctx, 0); if (cpop == NULL || add_instr(cpop)) return true; if (push_backpatch(thd, cpop, lab, &m_backpatch_goto, CPOP)) return true; // Add jump with ip=0. IP will be updated when label is found. sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(ip, ctx); if (i == NULL || add_instr(i)) return true; if (push_backpatch(thd, i, lab, &m_backpatch_goto, GOTO)) return true; return false; } /** Update all instruction with this label in the backpatch list to the current position. */ void sp_head::backpatch(sp_label *lab) { bp_t *bp; uint dest= instructions(); List_iterator_fast<bp_t> li(m_backpatch); DBUG_ENTER("sp_head::backpatch"); while ((bp= li++)) { if (bp->lab == lab) { DBUG_PRINT("info", ("backpatch: (m_ip %d, label %p <%s>) to dest %d", bp->instr->m_ip, lab, lab->name.str, dest)); bp->instr->backpatch(dest, lab->ctx); } } DBUG_VOID_RETURN; } void sp_head::backpatch_goto(THD *thd, sp_label *lab,sp_label *lab_begin_block) { bp_t *bp; uint dest= instructions(); List_iterator<bp_t> li(m_backpatch_goto); DBUG_ENTER("sp_head::backpatch_goto"); while ((bp= li++)) { if (bp->instr->m_ip < lab_begin_block->ip || bp->instr->m_ip > lab->ip) { /* Update only jump target from the beginning of the block where the label is defined. */ continue; } if (lex_string_cmp(system_charset_info, &bp->lab->name, &lab->name) == 0) { if (bp->instr_type == GOTO) { DBUG_PRINT("info", ("backpatch_goto: (m_ip %d, label %p <%s>) to dest %d", bp->instr->m_ip, lab, lab->name.str, dest)); bp->instr->backpatch(dest, lab->ctx); // Jump resolved, remove from the list li.remove(); continue; } if (bp->instr_type == CPOP) { uint n= bp->instr->m_ctx->diff_cursors(lab_begin_block->ctx, true); if (n == 0) { // Remove cpop instr replace_instr_to_nop(thd,bp->instr->m_ip); } else { // update count of cpop static_cast<sp_instr_cpop*>(bp->instr)->update_count(n); n= 1; } li.remove(); continue; } if (bp->instr_type == HPOP) { uint n= bp->instr->m_ctx->diff_handlers(lab_begin_block->ctx, true); if (n == 0) { // Remove hpop instr replace_instr_to_nop(thd,bp->instr->m_ip); } else { // update count of cpop static_cast<sp_instr_hpop*>(bp->instr)->update_count(n); n= 1; } li.remove(); continue; } } } DBUG_VOID_RETURN; } bool sp_head::check_unresolved_goto() { DBUG_ENTER("sp_head::check_unresolved_goto"); bool has_unresolved_label=false; if (m_backpatch_goto.elements > 0) { List_iterator_fast<bp_t> li(m_backpatch_goto); while (bp_t* bp= li++) { if (bp->instr_type == GOTO) { my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "GOTO", bp->lab->name.str); has_unresolved_label=true; } } } DBUG_RETURN(has_unresolved_label); } int sp_head::new_cont_backpatch(sp_instr_opt_meta *i) { m_cont_level+= 1; if (i) { /* Use the cont. destination slot to store the level */ i->m_cont_dest= m_cont_level; if (m_cont_backpatch.push_front(i)) return 1; } return 0; } int sp_head::add_cont_backpatch(sp_instr_opt_meta *i) { i->m_cont_dest= m_cont_level; return m_cont_backpatch.push_front(i); } void sp_head::do_cont_backpatch() { uint dest= instructions(); uint lev= m_cont_level--; sp_instr_opt_meta *i; while ((i= m_cont_backpatch.head()) && i->m_cont_dest == lev) { i->m_cont_dest= dest; (void)m_cont_backpatch.pop(); } } bool sp_head::sp_add_instr_cpush_for_cursors(THD *thd, sp_pcontext *pcontext) { for (uint i= 0; i < pcontext->frame_cursor_count(); i++) { const sp_pcursor *c= pcontext->get_cursor_by_local_frame_offset(i); sp_instr_cpush *instr= new (thd->mem_root) sp_instr_cpush(instructions(), pcontext, c->lex(), pcontext->cursor_offset() + i); if (instr == NULL || add_instr(instr)) return true; } return false; } void sp_head::set_chistics(const st_sp_chistics &chistics) { m_chistics.set(chistics); if (m_chistics.comment.length == 0) m_chistics.comment.str= 0; else m_chistics.comment.str= strmake_root(mem_root, m_chistics.comment.str, m_chistics.comment.length); } void sp_head::set_c_chistics(const st_sp_chistics &chistics) { // Set all chistics but preserve agg_type. enum_sp_aggregate_type save_agg_type= agg_type(); set_chistics(chistics); set_chistics_agg_type(save_agg_type); } void sp_head::set_info(longlong created, longlong modified, const st_sp_chistics &chistics, sql_mode_t sql_mode) { m_created= created; m_modified= modified; set_chistics(chistics); m_sql_mode= sql_mode; } void sp_head::reset_thd_mem_root(THD *thd) { DBUG_ENTER("sp_head::reset_thd_mem_root"); m_thd_root= thd->mem_root; thd->mem_root= &main_mem_root; DBUG_PRINT("info", ("mem_root %p moved to thd mem root %p", &mem_root, &thd->mem_root)); free_list= thd->free_list; // Keep the old list thd->free_list= NULL; // Start a new one m_thd= thd; DBUG_VOID_RETURN; } void sp_head::restore_thd_mem_root(THD *thd) { DBUG_ENTER("sp_head::restore_thd_mem_root"); /* In some cases our parser detects a syntax error and calls LEX::cleanup_lex_after_parse_error() method only after finishing parsing the whole routine. In such a situation sp_head::restore_thd_mem_root() will be called twice - the first time as part of normal parsing process and the second time by cleanup_lex_after_parse_error(). To avoid ruining active arena/mem_root state in this case we skip restoration of old arena/mem_root if this method has been already called for this routine. */ if (!m_thd) DBUG_VOID_RETURN; Item *flist= free_list; // The old list set_query_arena(thd); // Get new free_list and mem_root state= STMT_INITIALIZED_FOR_SP; DBUG_PRINT("info", ("mem_root %p returned from thd mem root %p", &mem_root, &thd->mem_root)); thd->free_list= flist; // Restore the old one thd->mem_root= m_thd_root; m_thd= NULL; DBUG_VOID_RETURN; } /** Check if a user has access right to a routine. @param thd Thread handler @param sp SP @param full_access Set to 1 if the user has SELECT right to the 'mysql.proc' able or is the owner of the routine @retval false ok @retval true error */ bool check_show_routine_access(THD *thd, sp_head *sp, bool *full_access) { TABLE_LIST tables; bzero((char*) &tables,sizeof(tables)); tables.db= MYSQL_SCHEMA_NAME; tables.table_name= MYSQL_PROC_NAME; tables.alias= MYSQL_PROC_NAME; *full_access= ((!check_table_access(thd, SELECT_ACL, &tables, FALSE, 1, TRUE) && (tables.grant.privilege & SELECT_ACL) != NO_ACL) || /* Check if user owns the routine. */ (!strcmp(sp->m_definer.user.str, thd->security_ctx->priv_user) && !strcmp(sp->m_definer.host.str, thd->security_ctx->priv_host)) || /* Check if current role or any of the sub-granted roles own the routine. */ (sp->m_definer.host.length == 0 && (!strcmp(sp->m_definer.user.str, thd->security_ctx->priv_role) || check_role_is_granted(thd->security_ctx->priv_role, NULL, sp->m_definer.user.str)))); if (!*full_access) return check_some_routine_access(thd, sp->m_db.str, sp->m_name.str, sp->m_handler); return 0; } /** Collect metadata for SHOW CREATE statement for stored routines. @param thd Thread context. @param sph Stored routine handler @param fields Item list to populate @return Error status. @retval FALSE on success @retval TRUE on error */ void sp_head::show_create_routine_get_fields(THD *thd, const Sp_handler *sph, List<Item> *fields) { const char *col1_caption= sph->show_create_routine_col1_caption(); const char *col3_caption= sph->show_create_routine_col3_caption(); MEM_ROOT *mem_root= thd->mem_root; /* Send header. */ fields->push_back(new (mem_root) Item_empty_string(thd, col1_caption, NAME_CHAR_LEN), mem_root); fields->push_back(new (mem_root) Item_empty_string(thd, "sql_mode", 256), mem_root); { /* NOTE: SQL statement field must be not less than 1024 in order not to confuse old clients. */ Item_empty_string *stmt_fld= new (mem_root) Item_empty_string(thd, col3_caption, 1024); stmt_fld->set_maybe_null(); fields->push_back(stmt_fld, mem_root); } fields->push_back(new (mem_root) Item_empty_string(thd, "character_set_client", MY_CS_NAME_SIZE), mem_root); fields->push_back(new (mem_root) Item_empty_string(thd, "collation_connection", MY_CS_NAME_SIZE), mem_root); fields->push_back(new (mem_root) Item_empty_string(thd, "Database Collation", MY_CS_NAME_SIZE), mem_root); } /** Implement SHOW CREATE statement for stored routines. @param thd Thread context. @param sph Stored routine handler @return Error status. @retval FALSE on success @retval TRUE on error */ bool sp_head::show_create_routine(THD *thd, const Sp_handler *sph) { const char *col1_caption= sph->show_create_routine_col1_caption(); const char *col3_caption= sph->show_create_routine_col3_caption(); bool err_status; Protocol *protocol= thd->protocol; List<Item> fields; LEX_CSTRING sql_mode; bool full_access; MEM_ROOT *mem_root= thd->mem_root; DBUG_ENTER("sp_head::show_create_routine"); DBUG_PRINT("info", ("routine %s", m_name.str)); if (check_show_routine_access(thd, this, &full_access)) DBUG_RETURN(TRUE); sql_mode_string_representation(thd, m_sql_mode, &sql_mode); /* Send header. */ fields.push_back(new (mem_root) Item_empty_string(thd, col1_caption, NAME_CHAR_LEN), thd->mem_root); fields.push_back(new (mem_root) Item_empty_string(thd, "sql_mode", (uint)sql_mode.length), thd->mem_root); { /* NOTE: SQL statement field must be not less than 1024 in order not to confuse old clients. */ Item_empty_string *stmt_fld= new (mem_root) Item_empty_string(thd, col3_caption, (uint)MY_MAX(m_defstr.length, 1024)); stmt_fld->set_maybe_null(); fields.push_back(stmt_fld, thd->mem_root); } fields.push_back(new (mem_root) Item_empty_string(thd, "character_set_client", MY_CS_NAME_SIZE), thd->mem_root); fields.push_back(new (mem_root) Item_empty_string(thd, "collation_connection", MY_CS_NAME_SIZE), thd->mem_root); fields.push_back(new (mem_root) Item_empty_string(thd, "Database Collation", MY_CS_NAME_SIZE), thd->mem_root); if (protocol->send_result_set_metadata(&fields, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) { DBUG_RETURN(TRUE); } /* Send data. */ protocol->prepare_for_resend(); protocol->store(m_name.str, m_name.length, system_charset_info); protocol->store(sql_mode.str, sql_mode.length, system_charset_info); if (full_access) protocol->store(m_defstr.str, m_defstr.length, m_creation_ctx->get_client_cs()); else protocol->store_null(); protocol->store(&m_creation_ctx->get_client_cs()->cs_name, system_charset_info); protocol->store(&m_creation_ctx->get_connection_cl()->coll_name, system_charset_info); protocol->store(&m_creation_ctx->get_db_cl()->coll_name, system_charset_info); err_status= protocol->write(); if (!err_status) my_eof(thd); DBUG_RETURN(err_status); } /** Add instruction to SP. @param instr Instruction */ int sp_head::add_instr(sp_instr *instr) { instr->free_list= m_thd->free_list; m_thd->free_list= 0; /* Memory root of every instruction is designated for permanent transformations (optimizations) made on the parsed tree during the first execution. It points to the memory root of the entire stored procedure, as their life span is equal. */ instr->mem_root= &main_mem_root; instr->m_lineno= m_thd->m_parser_state->m_lip.yylineno; return insert_dynamic(&m_instr, (uchar*)&instr); } bool sp_head::add_instr_jump(THD *thd, sp_pcontext *spcont) { sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(instructions(), spcont); return i == NULL || add_instr(i); } bool sp_head::add_instr_jump(THD *thd, sp_pcontext *spcont, uint dest) { sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(instructions(), spcont, dest); return i == NULL || add_instr(i); } bool sp_head::add_instr_jump_forward_with_backpatch(THD *thd, sp_pcontext *spcont, sp_label *lab) { sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(instructions(), spcont); if (i == NULL || add_instr(i)) return true; push_backpatch(thd, i, lab); return false; } bool sp_head::add_instr_freturn(THD *thd, sp_pcontext *spcont, Item *item, LEX *lex) { sp_instr_freturn *i= new (thd->mem_root) sp_instr_freturn(instructions(), spcont, item, m_return_field_def.type_handler(), lex); if (i == NULL || add_instr(i)) return true; m_flags|= sp_head::HAS_RETURN; return false; } bool sp_head::add_instr_preturn(THD *thd, sp_pcontext *spcont) { sp_instr_preturn *i= new (thd->mem_root) sp_instr_preturn(instructions(), spcont); if (i == NULL || add_instr(i)) return true; return false; } /* Replace an instruction at position to "no operation". @param thd - use mem_root of this THD for "new". @param ip - position of the operation @returns - true on error, false on success When we need to remove an instruction that during compilation appeared to be useless (typically as useless jump), we replace it to a jump to exactly the next instruction. Such jumps are later removed during sp_head::optimize(). QQ: Perhaps we need a dedicated sp_instr_nop for this purpose. */ bool sp_head::replace_instr_to_nop(THD *thd, uint ip) { sp_instr *instr= get_instr(ip); sp_instr_jump *nop= new (thd->mem_root) sp_instr_jump(instr->m_ip, instr->m_ctx, instr->m_ip + 1); if (!nop) return true; delete instr; set_dynamic(&m_instr, (uchar *) &nop, ip); return false; } /** Do some minimal optimization of the code: -# Mark used instructions -# While doing this, shortcut jumps to jump instructions -# Compact the code, removing unused instructions. This is the main mark and move loop; it relies on the following methods in sp_instr and its subclasses: - opt_mark() : Mark instruction as reachable - opt_shortcut_jump(): Shortcut jumps to the final destination; used by opt_mark(). - opt_move() : Update moved instruction - set_destination() : Set the new destination (jump instructions only) */ void sp_head::optimize() { List<sp_instr> bp; sp_instr *i; uint src, dst; DBUG_EXECUTE_IF("sp_head_optimize_disable", return; ); opt_mark(); bp.empty(); src= dst= 0; while ((i= get_instr(src))) { if (! i->marked) { delete i; src+= 1; } else { if (src != dst) { /* Move the instruction and update prev. jumps */ sp_instr *ibp; List_iterator_fast<sp_instr> li(bp); set_dynamic(&m_instr, (uchar*)&i, dst); while ((ibp= li++)) { sp_instr_opt_meta *im= static_cast<sp_instr_opt_meta *>(ibp); im->set_destination(src, dst); } } i->opt_move(dst, &bp); src+= 1; dst+= 1; } } m_instr.elements= dst; bp.empty(); } void sp_head::add_mark_lead(uint ip, List<sp_instr> *leads) { sp_instr *i= get_instr(ip); if (i && ! i->marked) leads->push_front(i); } void sp_head::opt_mark() { uint ip; sp_instr *i; List<sp_instr> leads; /* Forward flow analysis algorithm in the instruction graph: - first, add the entry point in the graph (the first instruction) to the 'leads' list of paths to explore. - while there are still leads to explore: - pick one lead, and follow the path forward. Mark instruction reached. Stop only if the end of the routine is reached, or the path converge to code already explored (marked). - while following a path, collect in the 'leads' list any fork to another path (caused by conditional jumps instructions), so that these paths can be explored as well. */ /* Add the entry point */ i= get_instr(0); leads.push_front(i); /* For each path of code ... */ while (leads.elements != 0) { i= leads.pop(); /* Mark the entire path, collecting new leads. */ while (i && ! i->marked) { ip= i->opt_mark(this, & leads); i= get_instr(ip); } } } #ifndef DBUG_OFF /** Return the routine instructions as a result set. @return 0 if ok, !=0 on error. */ int sp_head::show_routine_code(THD *thd) { Protocol *protocol= thd->protocol; char buff[2048]; String buffer(buff, sizeof(buff), system_charset_info); List<Item> field_list; sp_instr *i; bool full_access; int res= 0; uint ip; DBUG_ENTER("sp_head::show_routine_code"); DBUG_PRINT("info", ("procedure: %s", m_name.str)); if (check_show_routine_access(thd, this, &full_access) || !full_access) DBUG_RETURN(1); field_list.push_back(new (thd->mem_root) Item_uint(thd, "Pos", 9), thd->mem_root); // 1024 is for not to confuse old clients field_list.push_back(new (thd->mem_root) Item_empty_string(thd, "Instruction", MY_MAX(buffer.length(), 1024)), thd->mem_root); if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(1); for (ip= 0; (i = get_instr(ip)) ; ip++) { /* Consistency check. If these are different something went wrong during optimization. */ if (ip != i->m_ip) { const char *format= "Instruction at position %u has m_ip=%u"; char tmp[sizeof(format) + 2*SP_INSTR_UINT_MAXLEN + 1]; my_snprintf(tmp, sizeof(tmp), format, ip, i->m_ip); /* Since this is for debugging purposes only, we don't bother to introduce a special error code for it. */ push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, tmp); } protocol->prepare_for_resend(); protocol->store_long(ip); buffer.set("", 0, system_charset_info); i->print(&buffer); protocol->store(buffer.ptr(), buffer.length(), system_charset_info); if ((res= protocol->write())) break; } if (!res) my_eof(thd); DBUG_RETURN(res); } #endif // ifndef DBUG_OFF /** Prepare LEX and thread for execution of instruction, if requested open and lock LEX's tables, execute instruction's core function, perform cleanup afterwards. @param thd thread context @param nextp out - next instruction @param open_tables if TRUE then check read access to tables in LEX's table list and open and lock them (used in instructions which need to calculate some expression and don't execute complete statement). @param sp_instr instruction for which we prepare context, and which core function execute by calling its exec_core() method. @note We are not saving/restoring some parts of THD which may need this because we do this once for whole routine execution in sp_head::execute(). @return 0/non-0 - Success/Failure */ int sp_lex_keeper::reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, sp_instr* instr) { int res= 0; DBUG_ENTER("reset_lex_and_exec_core"); /* The flag is saved at the entry to the following substatement. It's reset further in the common code part. It's merged with the saved parent's value at the exit of this func. */ bool parent_modified_non_trans_table= thd->transaction->stmt.modified_non_trans_table; unsigned int parent_unsafe_rollback_flags= thd->transaction->stmt.m_unsafe_rollback_flags; thd->transaction->stmt.modified_non_trans_table= FALSE; thd->transaction->stmt.m_unsafe_rollback_flags= 0; DBUG_ASSERT(!thd->derived_tables); DBUG_ASSERT(thd->Item_change_list::is_empty()); /* Use our own lex. We should not save old value since it is saved/restored in sp_head::execute() when we are entering/leaving routine. */ thd->lex= m_lex; thd->set_query_id(next_query_id()); if (thd->locked_tables_mode <= LTM_LOCK_TABLES) { /* This statement will enter/leave prelocked mode on its own. Entering prelocked mode changes table list and related members of LEX, so we'll need to restore them. */ if (lex_query_tables_own_last) { /* We've already entered/left prelocked mode with this statement. Attach the list of tables that need to be prelocked and mark m_lex as having such list attached. */ *lex_query_tables_own_last= prelocking_tables; m_lex->mark_as_requiring_prelocking(lex_query_tables_own_last); } } reinit_stmt_before_use(thd, m_lex); #ifndef EMBEDDED_LIBRARY /* If there was instruction which changed tracking state, the result of changed tracking state send to client in OK packed. So it changes result sent to client and probably can be different independent on query text. So we can't cache such results. */ if ((thd->client_capabilities & CLIENT_SESSION_TRACK) && (thd->server_status & SERVER_SESSION_STATE_CHANGED)) thd->lex->safe_to_cache_query= 0; #endif Opt_trace_start ots(thd); ots.init(thd, m_lex->query_tables, SQLCOM_SELECT, &m_lex->var_list, NULL, 0, thd->variables.character_set_client); Json_writer_object trace_command(thd); Json_writer_array trace_command_steps(thd, "steps"); if (open_tables) res= instr->exec_open_and_lock_tables(thd, m_lex->query_tables); if (likely(!res)) { res= instr->exec_core(thd, nextp); DBUG_PRINT("info",("exec_core returned: %d", res)); } /* Call after unit->cleanup() to close open table key read. */ if (open_tables) { m_lex->unit.cleanup(); /* Here we also commit or rollback the current statement. */ if (! thd->in_sub_stmt) { thd->get_stmt_da()->set_overwrite_status(true); thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd); thd->get_stmt_da()->set_overwrite_status(false); } close_thread_tables(thd); thd_proc_info(thd, 0); if (! thd->in_sub_stmt) { if (thd->transaction_rollback_request) { trans_rollback_implicit(thd); thd->release_transactional_locks(); } else if (! thd->in_multi_stmt_transaction_mode()) thd->release_transactional_locks(); else thd->mdl_context.release_statement_locks(); } } //TODO: why is this here if log_slow_query is in sp_instr_stmt::execute? delete_explain_query(m_lex); if (m_lex->query_tables_own_last) { /* We've entered and left prelocking mode when executing statement stored in m_lex. m_lex->query_tables(->next_global)* list now has a 'tail' - a list of tables that are added for prelocking. (If this is the first execution, the 'tail' was added by open_tables(), otherwise we've attached it above in this function). Now we'll save the 'tail', and detach it. */ lex_query_tables_own_last= m_lex->query_tables_own_last; prelocking_tables= *lex_query_tables_own_last; *lex_query_tables_own_last= NULL; m_lex->mark_as_requiring_prelocking(NULL); } thd->rollback_item_tree_changes(); /* Update the state of the active arena if no errors on open_tables stage. */ if (likely(!res) || likely(!thd->is_error())) thd->stmt_arena->state= Query_arena::STMT_EXECUTED; /* Merge here with the saved parent's values what is needed from the substatement gained */ thd->transaction->stmt.modified_non_trans_table |= parent_modified_non_trans_table; thd->transaction->stmt.m_unsafe_rollback_flags |= parent_unsafe_rollback_flags; TRANSACT_TRACKER(add_trx_state_from_thd(thd)); /* Unlike for PS we should not call Item's destructors for newly created items after execution of each instruction in stored routine. This is because SP often create Item (like Item_int, Item_string etc...) when they want to store some value in local variable, pass return value and etc... So their life time should be longer than one instruction. cleanup_items() is called in sp_head::execute() */ thd->lex->restore_set_statement_var(); DBUG_RETURN(res || thd->is_error()); } int sp_lex_keeper::cursor_reset_lex_and_exec_core(THD *thd, uint *nextp, bool open_tables, sp_instr *instr) { Query_arena *old_arena= thd->stmt_arena; /* Get the Query_arena from the cursor statement LEX, which contains the free_list of the query, so new items (if any) are stored in the right free_list, and we can cleanup after each cursor operation, e.g. open or cursor_copy_struct (for cursor%ROWTYPE variables). */ thd->stmt_arena= m_lex->query_arena(); int res= reset_lex_and_exec_core(thd, nextp, open_tables, instr); cleanup_items(thd->stmt_arena->free_list); thd->stmt_arena= old_arena; return res; } /* sp_instr class functions */ int sp_instr::exec_open_and_lock_tables(THD *thd, TABLE_LIST *tables) { int result; /* Check whenever we have access to tables for this statement and open and lock them before executing instructions core function. */ if (thd->open_temporary_tables(tables) || check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE) || open_and_lock_tables(thd, tables, TRUE, 0)) result= -1; else result= 0; /* Prepare all derived tables/views to catch possible errors. */ if (!result) result= mysql_handle_derived(thd->lex, DT_PREPARE) ? -1 : 0; return result; } uint sp_instr::get_cont_dest() const { return (m_ip+1); } int sp_instr::exec_core(THD *thd, uint *nextp) { DBUG_ASSERT(0); return 0; } /* sp_instr_stmt class functions */ PSI_statement_info sp_instr_stmt::psi_info= { 0, "stmt", 0}; int sp_instr_stmt::execute(THD *thd, uint *nextp) { int res; bool save_enable_slow_log; const CSET_STRING query_backup= thd->query_string; Sub_statement_state backup_state; DBUG_ENTER("sp_instr_stmt::execute"); DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command())); MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, m_query.str, static_cast<uint>(m_query.length)); #if defined(ENABLED_PROFILING) /* This s-p instr is profilable and will be captured. */ thd->profiling.set_query_source(m_query.str, m_query.length); #endif save_enable_slow_log= thd->enable_slow_log; thd->store_slow_query_state(&backup_state); if (!(res= alloc_query(thd, m_query.str, m_query.length)) && !(res=subst_spvars(thd, this, &m_query))) { /* (the order of query cache and subst_spvars calls is irrelevant because queries with SP vars can't be cached) */ general_log_write(thd, COM_QUERY, thd->query(), thd->query_length()); if (query_cache_send_result_to_client(thd, thd->query(), thd->query_length()) <= 0) { thd->reset_slow_query_state(); res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this); bool log_slow= !res && thd->enable_slow_log; /* Finalize server status flags after executing a statement. */ if (log_slow || thd->get_stmt_da()->is_eof()) thd->update_server_status(); if (thd->get_stmt_da()->is_eof()) thd->protocol->end_statement(); query_cache_end_of_result(thd); mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS, thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0, command_name[COM_QUERY].str); if (log_slow) log_slow_statement(thd); /* Restore enable_slow_log, that can be changed by a admin or call command */ thd->enable_slow_log= save_enable_slow_log; /* Add the number of rows to thd for the 'call' statistics */ thd->add_slow_query_state(&backup_state); } else { /* change statistics */ enum_sql_command save_sql_command= thd->lex->sql_command; thd->lex->sql_command= SQLCOM_SELECT; status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]); thd->update_stats(); thd->lex->sql_command= save_sql_command; *nextp= m_ip+1; } thd->set_query(query_backup); thd->query_name_consts= 0; if (likely(!thd->is_error())) { res= 0; thd->get_stmt_da()->reset_diagnostics_area(); } } DBUG_RETURN(res || thd->is_error()); } void sp_instr_stmt::print(String *str) { size_t i, len; /* stmt CMD "..." */ if (str->reserve(SP_STMT_PRINT_MAXLEN+SP_INSTR_UINT_MAXLEN+8)) return; str->qs_append(STRING_WITH_LEN("stmt ")); str->qs_append((uint)m_lex_keeper.sql_command()); str->qs_append(STRING_WITH_LEN(" \"")); len= m_query.length; /* Print the query string (but not too much of it), just to indicate which statement it is. */ if (len > SP_STMT_PRINT_MAXLEN) len= SP_STMT_PRINT_MAXLEN-3; /* Copy the query string and replace '\n' with ' ' in the process */ for (i= 0 ; i < len ; i++) { char c= m_query.str[i]; if (c == '\n') c= ' '; str->qs_append(c); } if (m_query.length > SP_STMT_PRINT_MAXLEN) str->qs_append(STRING_WITH_LEN("...")); /* Indicate truncated string */ str->qs_append('"'); } int sp_instr_stmt::exec_core(THD *thd, uint *nextp) { MYSQL_QUERY_EXEC_START(thd->query(), thd->thread_id, thd->get_db(), &thd->security_ctx->priv_user[0], (char *)thd->security_ctx->host_or_ip, 3); int res= mysql_execute_command(thd); MYSQL_QUERY_EXEC_DONE(res); *nextp= m_ip+1; return res; } /* sp_instr_set class functions */ PSI_statement_info sp_instr_set::psi_info= { 0, "set", 0}; int sp_instr_set::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_set::execute"); DBUG_PRINT("info", ("offset: %u", m_offset)); DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this)); } sp_rcontext *sp_instr_set::get_rcontext(THD *thd) const { return m_rcontext_handler->get_rcontext(thd->spcont); } int sp_instr_set::exec_core(THD *thd, uint *nextp) { int res= get_rcontext(thd)->set_variable(thd, m_offset, &m_value); delete_explain_query(thd->lex); *nextp = m_ip+1; return res; } void sp_instr_set::print(String *str) { /* set name@offset ... */ size_t rsrv = SP_INSTR_UINT_MAXLEN+6; sp_variable *var = m_ctx->find_variable(m_offset); const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix(); /* 'var' should always be non-null, but just in case... */ if (var) rsrv+= var->name.length + prefix->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("set ")); str->qs_append(prefix->str, prefix->length); if (var) { str->qs_append(&var->name); str->qs_append('@'); } str->qs_append(m_offset); str->qs_append(' '); m_value->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } /* sp_instr_set_field class functions */ int sp_instr_set_row_field::exec_core(THD *thd, uint *nextp) { int res= get_rcontext(thd)->set_variable_row_field(thd, m_offset, m_field_offset, &m_value); delete_explain_query(thd->lex); *nextp= m_ip + 1; return res; } void sp_instr_set_row_field::print(String *str) { /* set name@offset[field_offset] ... */ size_t rsrv= SP_INSTR_UINT_MAXLEN + 6 + 6 + 3; sp_variable *var= m_ctx->find_variable(m_offset); const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix(); DBUG_ASSERT(var); DBUG_ASSERT(var->field_def.is_row()); const Column_definition *def= var->field_def.row_field_definitions()->elem(m_field_offset); DBUG_ASSERT(def); rsrv+= var->name.length + def->field_name.length + prefix->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("set ")); str->qs_append(prefix); str->qs_append(&var->name); str->qs_append('.'); str->qs_append(&def->field_name); str->qs_append('@'); str->qs_append(m_offset); str->qs_append('['); str->qs_append(m_field_offset); str->qs_append(']'); str->qs_append(' '); m_value->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } /* sp_instr_set_field_by_name class functions */ int sp_instr_set_row_field_by_name::exec_core(THD *thd, uint *nextp) { int res= get_rcontext(thd)->set_variable_row_field_by_name(thd, m_offset, m_field_name, &m_value); delete_explain_query(thd->lex); *nextp= m_ip + 1; return res; } void sp_instr_set_row_field_by_name::print(String *str) { /* set name.field@offset["field"] ... */ size_t rsrv= SP_INSTR_UINT_MAXLEN + 6 + 6 + 3 + 2; sp_variable *var= m_ctx->find_variable(m_offset); const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix(); DBUG_ASSERT(var); DBUG_ASSERT(var->field_def.is_table_rowtype_ref() || var->field_def.is_cursor_rowtype_ref()); rsrv+= var->name.length + 2 * m_field_name.length + prefix->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("set ")); str->qs_append(prefix); str->qs_append(&var->name); str->qs_append('.'); str->qs_append(&m_field_name); str->qs_append('@'); str->qs_append(m_offset); str->qs_append("[\"",2); str->qs_append(&m_field_name); str->qs_append("\"]",2); str->qs_append(' '); m_value->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } /* sp_instr_set_trigger_field class functions */ PSI_statement_info sp_instr_set_trigger_field::psi_info= { 0, "set_trigger_field", 0}; int sp_instr_set_trigger_field::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_set_trigger_field::execute"); thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL; DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this)); } int sp_instr_set_trigger_field::exec_core(THD *thd, uint *nextp) { Abort_on_warning_instant_set aws(thd, thd->is_strict_mode() && !thd->lex->ignore); const int res= (trigger_field->set_value(thd, &value) ? -1 : 0); *nextp = m_ip+1; return res; } void sp_instr_set_trigger_field::print(String *str) { str->append(STRING_WITH_LEN("set_trigger_field ")); trigger_field->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); str->append(STRING_WITH_LEN(":=")); value->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } /* sp_instr_opt_meta */ uint sp_instr_opt_meta::get_cont_dest() const { return m_cont_dest; } /* sp_instr_jump class functions */ PSI_statement_info sp_instr_jump::psi_info= { 0, "jump", 0}; int sp_instr_jump::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_jump::execute"); DBUG_PRINT("info", ("destination: %u", m_dest)); *nextp= m_dest; DBUG_RETURN(0); } void sp_instr_jump::print(String *str) { /* jump dest */ if (str->reserve(SP_INSTR_UINT_MAXLEN+5)) return; str->qs_append(STRING_WITH_LEN("jump ")); str->qs_append(m_dest); } uint sp_instr_jump::opt_mark(sp_head *sp, List<sp_instr> *leads) { m_dest= opt_shortcut_jump(sp, this); if (m_dest != m_ip+1) /* Jumping to following instruction? */ marked= 1; m_optdest= sp->get_instr(m_dest); return m_dest; } uint sp_instr_jump::opt_shortcut_jump(sp_head *sp, sp_instr *start) { uint dest= m_dest; sp_instr *i; while ((i= sp->get_instr(dest))) { uint ndest; if (start == i || this == i) break; ndest= i->opt_shortcut_jump(sp, start); if (ndest == dest) break; dest= ndest; } return dest; } void sp_instr_jump::opt_move(uint dst, List<sp_instr> *bp) { if (m_dest > m_ip) bp->push_back(this); // Forward else if (m_optdest) m_dest= m_optdest->m_ip; // Backward m_ip= dst; } /* sp_instr_jump_if_not class functions */ PSI_statement_info sp_instr_jump_if_not::psi_info= { 0, "jump_if_not", 0}; int sp_instr_jump_if_not::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_jump_if_not::execute"); DBUG_PRINT("info", ("destination: %u", m_dest)); DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this)); } int sp_instr_jump_if_not::exec_core(THD *thd, uint *nextp) { Item *it; int res; it= thd->sp_prepare_func_item(&m_expr); if (! it) { res= -1; } else { res= 0; if (! it->val_bool()) *nextp = m_dest; else *nextp = m_ip+1; } return res; } void sp_instr_jump_if_not::print(String *str) { /* jump_if_not dest(cont) ... */ if (str->reserve(2*SP_INSTR_UINT_MAXLEN+14+32)) // Add some for the expr. too return; str->qs_append(STRING_WITH_LEN("jump_if_not ")); str->qs_append(m_dest); str->qs_append('('); str->qs_append(m_cont_dest); str->qs_append(STRING_WITH_LEN(") ")); m_expr->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } uint sp_instr_jump_if_not::opt_mark(sp_head *sp, List<sp_instr> *leads) { sp_instr *i; marked= 1; if ((i= sp->get_instr(m_dest))) { m_dest= i->opt_shortcut_jump(sp, this); m_optdest= sp->get_instr(m_dest); } sp->add_mark_lead(m_dest, leads); if ((i= sp->get_instr(m_cont_dest))) { m_cont_dest= i->opt_shortcut_jump(sp, this); m_cont_optdest= sp->get_instr(m_cont_dest); } sp->add_mark_lead(m_cont_dest, leads); return m_ip+1; } void sp_instr_jump_if_not::opt_move(uint dst, List<sp_instr> *bp) { /* cont. destinations may point backwards after shortcutting jumps during the mark phase. If it's still pointing forwards, only push this for backpatching if sp_instr_jump::opt_move() will not do it (i.e. if the m_dest points backwards). */ if (m_cont_dest > m_ip) { // Forward if (m_dest < m_ip) bp->push_back(this); } else if (m_cont_optdest) m_cont_dest= m_cont_optdest->m_ip; // Backward /* This will take care of m_dest and m_ip */ sp_instr_jump::opt_move(dst, bp); } /* sp_instr_freturn class functions */ PSI_statement_info sp_instr_freturn::psi_info= { 0, "freturn", 0}; int sp_instr_freturn::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_freturn::execute"); DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this)); } int sp_instr_freturn::exec_core(THD *thd, uint *nextp) { /* RETURN is a "procedure statement" (in terms of the SQL standard). That means, Diagnostics Area should be clean before its execution. */ if (!(thd->variables.sql_mode & MODE_ORACLE)) { /* Don't clean warnings in ORACLE mode, as they are needed for SQLCODE and SQLERRM: BEGIN SELECT a INTO a FROM t1; RETURN 'No exception ' || SQLCODE || ' ' || SQLERRM; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN 'Exception ' || SQLCODE || ' ' || SQLERRM; END; */ Diagnostics_area *da= thd->get_stmt_da(); da->clear_warning_info(da->warning_info_id()); } /* Change <next instruction pointer>, so that this will be the last instruction in the stored function. */ *nextp= UINT_MAX; /* Evaluate the value of return expression and store it in current runtime context. NOTE: It's necessary to evaluate result item right here, because we must do it in scope of execution the current context/block. */ return thd->spcont->set_return_value(thd, &m_value); } void sp_instr_freturn::print(String *str) { /* freturn type expr... */ if (str->reserve(1024+8+32)) // Add some for the expr. too return; str->qs_append(STRING_WITH_LEN("freturn ")); LEX_CSTRING name= m_type_handler->name().lex_cstring(); str->qs_append(&name); str->qs_append(' '); m_value->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } /* sp_instr_preturn class functions */ PSI_statement_info sp_instr_preturn::psi_info= { 0, "preturn", 0}; int sp_instr_preturn::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_preturn::execute"); *nextp= UINT_MAX; DBUG_RETURN(0); } void sp_instr_preturn::print(String *str) { str->append(STRING_WITH_LEN("preturn")); } /* sp_instr_hpush_jump class functions */ PSI_statement_info sp_instr_hpush_jump::psi_info= { 0, "hpush_jump", 0}; int sp_instr_hpush_jump::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_hpush_jump::execute"); int ret= thd->spcont->push_handler(this); *nextp= m_dest; DBUG_RETURN(ret); } void sp_instr_hpush_jump::print(String *str) { /* hpush_jump dest fsize type */ if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 21)) return; str->qs_append(STRING_WITH_LEN("hpush_jump ")); str->qs_append(m_dest); str->qs_append(' '); str->qs_append(m_frame); switch (m_handler->type) { case sp_handler::EXIT: str->qs_append(STRING_WITH_LEN(" EXIT")); break; case sp_handler::CONTINUE: str->qs_append(STRING_WITH_LEN(" CONTINUE")); break; default: // The handler type must be either CONTINUE or EXIT. DBUG_ASSERT(0); } } uint sp_instr_hpush_jump::opt_mark(sp_head *sp, List<sp_instr> *leads) { sp_instr *i; marked= 1; if ((i= sp->get_instr(m_dest))) { m_dest= i->opt_shortcut_jump(sp, this); m_optdest= sp->get_instr(m_dest); } sp->add_mark_lead(m_dest, leads); /* For continue handlers, all instructions in the scope of the handler are possible leads. For example, the instruction after freturn might be executed if the freturn triggers the condition handled by the continue handler. m_dest marks the start of the handler scope. It's added as a lead above, so we start on m_dest+1 here. m_opt_hpop is the hpop marking the end of the handler scope. */ if (m_handler->type == sp_handler::CONTINUE) { for (uint scope_ip= m_dest+1; scope_ip <= m_opt_hpop; scope_ip++) sp->add_mark_lead(scope_ip, leads); } return m_ip+1; } /* sp_instr_hpop class functions */ PSI_statement_info sp_instr_hpop::psi_info= { 0, "hpop", 0}; int sp_instr_hpop::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_hpop::execute"); thd->spcont->pop_handlers(m_count); *nextp= m_ip+1; DBUG_RETURN(0); } void sp_instr_hpop::print(String *str) { /* hpop count */ if (str->reserve(SP_INSTR_UINT_MAXLEN+5)) return; str->qs_append(STRING_WITH_LEN("hpop ")); str->qs_append(m_count); } /* sp_instr_hreturn class functions */ PSI_statement_info sp_instr_hreturn::psi_info= { 0, "hreturn", 0}; int sp_instr_hreturn::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_hreturn::execute"); uint continue_ip= thd->spcont->exit_handler(thd->get_stmt_da()); *nextp= m_dest ? m_dest : continue_ip; DBUG_RETURN(0); } void sp_instr_hreturn::print(String *str) { /* hreturn framesize dest */ if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 9)) return; str->qs_append(STRING_WITH_LEN("hreturn ")); if (m_dest) { // NOTE: this is legacy: hreturn instruction for EXIT handler // should print out 0 as frame index. str->qs_append(STRING_WITH_LEN("0 ")); str->qs_append(m_dest); } else { str->qs_append(m_frame); } } uint sp_instr_hreturn::opt_mark(sp_head *sp, List<sp_instr> *leads) { marked= 1; if (m_dest) { /* This is an EXIT handler; next instruction step is in m_dest. */ return m_dest; } /* This is a CONTINUE handler; next instruction step will come from the handler stack and not from opt_mark. */ return UINT_MAX; } /* sp_instr_cpush class functions */ PSI_statement_info sp_instr_cpush::psi_info= { 0, "cpush", 0}; int sp_instr_cpush::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_cpush::execute"); sp_cursor::reset(thd, &m_lex_keeper); m_lex_keeper.disable_query_cache(); thd->spcont->push_cursor(this); *nextp= m_ip+1; DBUG_RETURN(false); } void sp_instr_cpush::print(String *str) { const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor); /* cpush name@offset */ size_t rsrv= SP_INSTR_UINT_MAXLEN+7; if (cursor_name) rsrv+= cursor_name->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("cpush ")); if (cursor_name) { str->qs_append(cursor_name->str, cursor_name->length); str->qs_append('@'); } str->qs_append(m_cursor); } /* sp_instr_cpop class functions */ PSI_statement_info sp_instr_cpop::psi_info= { 0, "cpop", 0}; int sp_instr_cpop::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_cpop::execute"); thd->spcont->pop_cursors(thd, m_count); *nextp= m_ip+1; DBUG_RETURN(0); } void sp_instr_cpop::print(String *str) { /* cpop count */ if (str->reserve(SP_INSTR_UINT_MAXLEN+5)) return; str->qs_append(STRING_WITH_LEN("cpop ")); str->qs_append(m_count); } /* sp_instr_copen class functions */ /** @todo Assert that we either have an error or a cursor */ PSI_statement_info sp_instr_copen::psi_info= { 0, "copen", 0}; int sp_instr_copen::execute(THD *thd, uint *nextp) { /* We don't store a pointer to the cursor in the instruction to be able to reuse the same instruction among different threads in future. */ sp_cursor *c= thd->spcont->get_cursor(m_cursor); int res; DBUG_ENTER("sp_instr_copen::execute"); if (! c) res= -1; else { sp_lex_keeper *lex_keeper= c->get_lex_keeper(); res= lex_keeper->cursor_reset_lex_and_exec_core(thd, nextp, FALSE, this); /* TODO: Assert here that we either have an error or a cursor */ } DBUG_RETURN(res); } int sp_instr_copen::exec_core(THD *thd, uint *nextp) { sp_cursor *c= thd->spcont->get_cursor(m_cursor); int res= c->open(thd); *nextp= m_ip+1; return res; } void sp_instr_copen::print(String *str) { const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor); /* copen name@offset */ size_t rsrv= SP_INSTR_UINT_MAXLEN+7; if (cursor_name) rsrv+= cursor_name->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("copen ")); if (cursor_name) { str->qs_append(cursor_name->str, cursor_name->length); str->qs_append('@'); } str->qs_append(m_cursor); } /* sp_instr_cclose class functions */ PSI_statement_info sp_instr_cclose::psi_info= { 0, "cclose", 0}; int sp_instr_cclose::execute(THD *thd, uint *nextp) { sp_cursor *c= thd->spcont->get_cursor(m_cursor); int res; DBUG_ENTER("sp_instr_cclose::execute"); if (! c) res= -1; else res= c->close(thd); *nextp= m_ip+1; DBUG_RETURN(res); } void sp_instr_cclose::print(String *str) { const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor); /* cclose name@offset */ size_t rsrv= SP_INSTR_UINT_MAXLEN+8; if (cursor_name) rsrv+= cursor_name->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("cclose ")); if (cursor_name) { str->qs_append(cursor_name->str, cursor_name->length); str->qs_append('@'); } str->qs_append(m_cursor); } /* sp_instr_cfetch class functions */ PSI_statement_info sp_instr_cfetch::psi_info= { 0, "cfetch", 0}; int sp_instr_cfetch::execute(THD *thd, uint *nextp) { sp_cursor *c= thd->spcont->get_cursor(m_cursor); int res; Query_arena backup_arena; DBUG_ENTER("sp_instr_cfetch::execute"); res= c ? c->fetch(thd, &m_varlist, m_error_on_no_data) : -1; *nextp= m_ip+1; DBUG_RETURN(res); } void sp_instr_cfetch::print(String *str) { List_iterator_fast<sp_variable> li(m_varlist); sp_variable *pv; const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor); /* cfetch name@offset vars... */ size_t rsrv= SP_INSTR_UINT_MAXLEN+8; if (cursor_name) rsrv+= cursor_name->length; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("cfetch ")); if (cursor_name) { str->qs_append(cursor_name->str, cursor_name->length); str->qs_append('@'); } str->qs_append(m_cursor); while ((pv= li++)) { if (str->reserve(pv->name.length+SP_INSTR_UINT_MAXLEN+2)) return; str->qs_append(' '); str->qs_append(&pv->name); str->qs_append('@'); str->qs_append(pv->offset); } } /* sp_instr_agg_cfetch class functions */ PSI_statement_info sp_instr_agg_cfetch::psi_info= { 0, "agg_cfetch", 0}; int sp_instr_agg_cfetch::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_agg_cfetch::execute"); int res= 0; if (!thd->spcont->instr_ptr) { *nextp= m_ip+1; thd->spcont->instr_ptr= m_ip + 1; } else if (!thd->spcont->pause_state) thd->spcont->pause_state= TRUE; else { thd->spcont->pause_state= FALSE; if (thd->server_status & SERVER_STATUS_LAST_ROW_SENT) { my_message(ER_SP_FETCH_NO_DATA, ER_THD(thd, ER_SP_FETCH_NO_DATA), MYF(0)); res= -1; thd->spcont->quit_func= TRUE; } else *nextp= m_ip + 1; } DBUG_RETURN(res); } void sp_instr_agg_cfetch::print(String *str) { uint rsrv= SP_INSTR_UINT_MAXLEN+11; if (str->reserve(rsrv)) return; str->qs_append(STRING_WITH_LEN("agg_cfetch")); } /* sp_instr_cursor_copy_struct class functions */ /** This methods processes cursor %ROWTYPE declarations, e.g.: CURSOR cur IS SELECT * FROM t1; rec cur%ROWTYPE; and does the following: - opens the cursor without copying data (materialization). - copies the cursor structure to the associated %ROWTYPE variable. */ PSI_statement_info sp_instr_cursor_copy_struct::psi_info= { 0, "cursor_copy_struct", 0}; int sp_instr_cursor_copy_struct::exec_core(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_cursor_copy_struct::exec_core"); int ret= 0; Item_field_row *row= (Item_field_row*) thd->spcont->get_variable(m_var); DBUG_ASSERT(row->type_handler() == &type_handler_row); /* Copy structure only once. If the cursor%ROWTYPE variable is declared inside a LOOP block, it gets its structure on the first loop interation and remembers the structure for all consequent loop iterations. It we recreated the structure on every iteration, we would get potential memory leaks, and it would be less efficient. */ if (!row->arguments()) { sp_cursor tmp(thd, &m_lex_keeper, true); // Open the cursor without copying data if (!(ret= tmp.open(thd))) { Row_definition_list defs; /* Create row elements on the caller arena. It's the same arena that was used during sp_rcontext::create(). This puts cursor%ROWTYPE elements on the same mem_root where explicit ROW elements and table%ROWTYPE reside: - tmp.export_structure() allocates new Spvar_definition instances and their components (such as TYPELIBs). - row->row_create_items() creates new Item_field instances. They all are created on the same mem_root. */ Query_arena current_arena; thd->set_n_backup_active_arena(thd->spcont->callers_arena, &current_arena); if (!(ret= tmp.export_structure(thd, &defs))) row->row_create_items(thd, &defs); thd->restore_active_arena(thd->spcont->callers_arena, &current_arena); tmp.close(thd); } } *nextp= m_ip + 1; DBUG_RETURN(ret); } int sp_instr_cursor_copy_struct::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_cursor_copy_struct::execute"); int ret= m_lex_keeper.cursor_reset_lex_and_exec_core(thd, nextp, FALSE, this); DBUG_RETURN(ret); } void sp_instr_cursor_copy_struct::print(String *str) { sp_variable *var= m_ctx->find_variable(m_var); const LEX_CSTRING *name= m_ctx->find_cursor(m_cursor); str->append(STRING_WITH_LEN("cursor_copy_struct ")); str->append(name); str->append(' '); str->append(&var->name); str->append('@'); str->append_ulonglong(m_var); } /* sp_instr_error class functions */ PSI_statement_info sp_instr_error::psi_info= { 0, "error", 0}; int sp_instr_error::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_error::execute"); my_message(m_errcode, ER_THD(thd, m_errcode), MYF(0)); WSREP_DEBUG("sp_instr_error: %s %d", ER_THD(thd, m_errcode), thd->is_error()); *nextp= m_ip+1; DBUG_RETURN(-1); } void sp_instr_error::print(String *str) { /* error code */ if (str->reserve(SP_INSTR_UINT_MAXLEN+6)) return; str->qs_append(STRING_WITH_LEN("error ")); str->qs_append(m_errcode); } /************************************************************************** sp_instr_set_case_expr class implementation **************************************************************************/ PSI_statement_info sp_instr_set_case_expr::psi_info= { 0, "set_case_expr", 0}; int sp_instr_set_case_expr::execute(THD *thd, uint *nextp) { DBUG_ENTER("sp_instr_set_case_expr::execute"); DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this)); } int sp_instr_set_case_expr::exec_core(THD *thd, uint *nextp) { int res= thd->spcont->set_case_expr(thd, m_case_expr_id, &m_case_expr); if (res && !thd->spcont->get_case_expr(m_case_expr_id)) { /* Failed to evaluate the value, the case expression is still not initialized. Set to NULL so we can continue. */ Item *null_item= new (thd->mem_root) Item_null(thd); if (!null_item || thd->spcont->set_case_expr(thd, m_case_expr_id, &null_item)) { /* If this also failed, we have to abort. */ my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATAL)); } } else *nextp= m_ip+1; return res; } void sp_instr_set_case_expr::print(String *str) { /* set_case_expr (cont) id ... */ str->reserve(2*SP_INSTR_UINT_MAXLEN+18+32); // Add some extra for expr too str->qs_append(STRING_WITH_LEN("set_case_expr (")); str->qs_append(m_cont_dest); str->qs_append(STRING_WITH_LEN(") ")); str->qs_append(m_case_expr_id); str->qs_append(' '); m_case_expr->print(str, enum_query_type(QT_ORDINARY | QT_ITEM_ORIGINAL_FUNC_NULLIF)); } uint sp_instr_set_case_expr::opt_mark(sp_head *sp, List<sp_instr> *leads) { sp_instr *i; marked= 1; if ((i= sp->get_instr(m_cont_dest))) { m_cont_dest= i->opt_shortcut_jump(sp, this); m_cont_optdest= sp->get_instr(m_cont_dest); } sp->add_mark_lead(m_cont_dest, leads); return m_ip+1; } void sp_instr_set_case_expr::opt_move(uint dst, List<sp_instr> *bp) { if (m_cont_dest > m_ip) bp->push_back(this); // Forward else if (m_cont_optdest) m_cont_dest= m_cont_optdest->m_ip; // Backward m_ip= dst; } /* ------------------------------------------------------------------ */ /* Structure that represent all instances of one table in optimized multi-set of tables used by routine. */ typedef struct st_sp_table { /* Multi-set key: db_name\0table_name\0alias\0 - for normal tables db_name\0table_name\0 - for temporary tables */ LEX_STRING qname; size_t db_length, table_name_length; bool temp; /* true if corresponds to a temporary table */ thr_lock_type lock_type; /* lock type used for prelocking */ uint lock_count; uint query_lock_count; uint8 trg_event_map; my_bool for_insert_data; } SP_TABLE; uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first) { SP_TABLE *tab= (SP_TABLE *)ptr; *plen= tab->qname.length; return (uchar *)tab->qname.str; } /** Merge the list of tables used by some query into the multi-set of tables used by routine. @param thd thread context @param table table list @param lex_for_tmp_check LEX of the query for which we are merging table list. @note This method will use LEX provided to check whenever we are creating temporary table and mark it as such in target multi-set. @retval TRUE Success @retval FALSE Error */ bool sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check) { SP_TABLE *tab; if ((lex_for_tmp_check->sql_command == SQLCOM_DROP_TABLE || lex_for_tmp_check->sql_command == SQLCOM_DROP_SEQUENCE) && lex_for_tmp_check->tmp_table()) return TRUE; for (uint i= 0 ; i < m_sptabs.records ; i++) { tab= (SP_TABLE*) my_hash_element(&m_sptabs, i); tab->query_lock_count= 0; } for (; table ; table= table->next_global) if (!table->derived && !table->schema_table && !table->table_function) { /* Structure of key for the multi-set is "db\0table\0alias\0". Since "alias" part can have arbitrary length we use String object to construct the key. By default String will use buffer allocated on stack with NAME_LEN bytes reserved for alias, since in most cases it is going to be smaller than NAME_LEN bytes. */ char tname_buff[(SAFE_NAME_LEN + 1) * 3]; String tname(tname_buff, sizeof(tname_buff), &my_charset_bin); uint temp_table_key_length; tname.length(0); tname.append(&table->db); tname.append('\0'); tname.append(&table->table_name); tname.append('\0'); temp_table_key_length= tname.length(); tname.append(&table->alias); tname.append('\0'); /* Upgrade the lock type because this table list will be used only in pre-locked mode, in which DELAYED inserts are always converted to normal inserts. */ if (table->lock_type == TL_WRITE_DELAYED) table->lock_type= TL_WRITE; /* We ignore alias when we check if table was already marked as temporary (and therefore should not be prelocked). Otherwise we will erroneously treat table with same name but with different alias as non-temporary. */ if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(), tname.length())) || ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(), temp_table_key_length)) && tab->temp)) { if (tab->lock_type < table->lock_type) tab->lock_type= table->lock_type; // Use the table with the highest lock type tab->query_lock_count++; if (tab->query_lock_count > tab->lock_count) tab->lock_count++; tab->trg_event_map|= table->trg_event_map; tab->for_insert_data|= table->for_insert_data; } else { if (!(tab= (SP_TABLE *)thd->calloc(sizeof(SP_TABLE)))) return FALSE; if ((lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE || lex_for_tmp_check->sql_command == SQLCOM_CREATE_SEQUENCE) && lex_for_tmp_check->query_tables == table && lex_for_tmp_check->tmp_table()) { tab->temp= TRUE; tab->qname.length= temp_table_key_length; } else tab->qname.length= tname.length(); tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length); if (!tab->qname.str) return FALSE; tab->table_name_length= table->table_name.length; tab->db_length= table->db.length; tab->lock_type= table->lock_type; tab->lock_count= tab->query_lock_count= 1; tab->trg_event_map= table->trg_event_map; tab->for_insert_data= table->for_insert_data; if (my_hash_insert(&m_sptabs, (uchar *)tab)) return FALSE; } } return TRUE; } /** Add tables used by routine to the table list. Converts multi-set of tables used by this routine to table list and adds this list to the end of table list specified by 'query_tables_last_ptr'. Elements of list will be allocated in PS memroot, so this list will be persistent between PS executions. @param[in] thd Thread context @param[in,out] query_tables_last_ptr Pointer to the next_global member of last element of the list where tables will be added (or to its root). @param[in] belong_to_view Uppermost view which uses this routine, 0 if none. @retval TRUE if some elements were added @retval FALSE otherwise. */ bool sp_head::add_used_tables_to_table_list(THD *thd, TABLE_LIST ***query_tables_last_ptr, TABLE_LIST *belong_to_view) { uint i; Query_arena *arena, backup; bool result= FALSE; DBUG_ENTER("sp_head::add_used_tables_to_table_list"); /* Use persistent arena for table list allocation to be PS/SP friendly. Note that we also have to copy database/table names and alias to PS/SP memory since current instance of sp_head object can pass away before next execution of PS/SP for which tables are added to prelocking list. This will be fixed by introducing of proper invalidation mechanism once new TDC is ready. */ arena= thd->activate_stmt_arena_if_needed(&backup); for (i=0 ; i < m_sptabs.records ; i++) { char *tab_buff, *key_buff; SP_TABLE *stab= (SP_TABLE*) my_hash_element(&m_sptabs, i); LEX_CSTRING db_name; if (stab->temp) continue; if (!(tab_buff= (char *)thd->alloc(ALIGN_SIZE(sizeof(TABLE_LIST)) * stab->lock_count)) || !(key_buff= (char*)thd->memdup(stab->qname.str, stab->qname.length))) DBUG_RETURN(FALSE); db_name.str= key_buff; db_name.length= stab->db_length; for (uint j= 0; j < stab->lock_count; j++) { TABLE_LIST *table= (TABLE_LIST *)tab_buff; LEX_CSTRING table_name= { key_buff + stab->db_length + 1, stab->table_name_length }; LEX_CSTRING alias= { table_name.str + table_name.length + 1, strlen(table_name.str + table_name.length + 1) }; table->init_one_table_for_prelocking(&db_name, &table_name, &alias, stab->lock_type, TABLE_LIST::PRELOCK_ROUTINE, belong_to_view, stab->trg_event_map, query_tables_last_ptr, stab->for_insert_data); tab_buff+= ALIGN_SIZE(sizeof(TABLE_LIST)); result= TRUE; } } if (arena) thd->restore_active_arena(arena, &backup); DBUG_RETURN(result); } /** Simple function for adding an explicitly named (systems) table to the global table list, e.g. "mysql", "proc". */ TABLE_LIST * sp_add_to_query_tables(THD *thd, LEX *lex, const LEX_CSTRING *db, const LEX_CSTRING *name, thr_lock_type locktype, enum_mdl_type mdl_type) { TABLE_LIST *table; if (!(table= (TABLE_LIST *)thd->calloc(sizeof(TABLE_LIST)))) return NULL; if (!thd->make_lex_string(&table->db, db->str, db->length) || !thd->make_lex_string(&table->table_name, name->str, name->length) || !thd->make_lex_string(&table->alias, name->str, name->length)) return NULL; table->lock_type= locktype; table->select_lex= lex->current_select; table->cacheable_table= 1; MDL_REQUEST_INIT(&table->mdl_request, MDL_key::TABLE, table->db.str, table->table_name.str, mdl_type, MDL_TRANSACTION); lex->add_to_query_tables(table); return table; } Item *sp_head::adjust_assignment_source(THD *thd, Item *val, Item *val2) { return val ? val : val2 ? val2 : new (thd->mem_root) Item_null(thd); } /** Helper action for a SET statement. Used to push a SP local variable into the assignment list. @param var_type the SP local variable @param val the value being assigned to the variable @return TRUE if error, FALSE otherwise. */ bool sp_head::set_local_variable(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, Item *val, LEX *lex, bool responsible_to_free_lex) { if (!(val= adjust_assignment_source(thd, val, spv->default_value))) return true; if (val->walk(&Item::unknown_splocal_processor, false, NULL)) return true; sp_instr_set *sp_set= new (thd->mem_root) sp_instr_set(instructions(), spcont, rh, spv->offset, val, lex, responsible_to_free_lex); return sp_set == NULL || add_instr(sp_set); } /** Similar to set_local_variable(), but for ROW variable fields. */ bool sp_head::set_local_variable_row_field(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, uint field_idx, Item *val, LEX *lex) { if (!(val= adjust_assignment_source(thd, val, NULL))) return true; sp_instr_set_row_field *sp_set= new (thd->mem_root) sp_instr_set_row_field(instructions(), spcont, rh, spv->offset, field_idx, val, lex, true); return sp_set == NULL || add_instr(sp_set); } bool sp_head::set_local_variable_row_field_by_name(THD *thd, sp_pcontext *spcont, const Sp_rcontext_handler *rh, sp_variable *spv, const LEX_CSTRING *field_name, Item *val, LEX *lex) { if (!(val= adjust_assignment_source(thd, val, NULL))) return true; sp_instr_set_row_field_by_name *sp_set= new (thd->mem_root) sp_instr_set_row_field_by_name(instructions(), spcont, rh, spv->offset, *field_name, val, lex, true); return sp_set == NULL || add_instr(sp_set); } bool sp_head::add_open_cursor(THD *thd, sp_pcontext *spcont, uint offset, sp_pcontext *param_spcont, List<sp_assignment_lex> *parameters) { /* The caller must make sure that the number of formal parameters matches the number of actual parameters. */ DBUG_ASSERT((param_spcont ? param_spcont->context_var_count() : 0) == (parameters ? parameters->elements : 0)); if (parameters && add_set_cursor_param_variables(thd, param_spcont, parameters)) return true; sp_instr_copen *i= new (thd->mem_root) sp_instr_copen(instructions(), spcont, offset); return i == NULL || add_instr(i); } bool sp_head::add_for_loop_open_cursor(THD *thd, sp_pcontext *spcont, sp_variable *index, const sp_pcursor *pcursor, uint coffset, sp_assignment_lex *param_lex, Item_args *parameters) { if (parameters && add_set_for_loop_cursor_param_variables(thd, pcursor->param_context(), param_lex, parameters)) return true; sp_instr *instr_copy_struct= new (thd->mem_root) sp_instr_cursor_copy_struct(instructions(), spcont, coffset, pcursor->lex(), index->offset); if (instr_copy_struct == NULL || add_instr(instr_copy_struct)) return true; sp_instr_copen *instr_copen= new (thd->mem_root) sp_instr_copen(instructions(), spcont, coffset); if (instr_copen == NULL || add_instr(instr_copen)) return true; sp_instr_cfetch *instr_cfetch= new (thd->mem_root) sp_instr_cfetch(instructions(), spcont, coffset, false); if (instr_cfetch == NULL || add_instr(instr_cfetch)) return true; instr_cfetch->add_to_varlist(index); return false; } bool sp_head::add_set_for_loop_cursor_param_variables(THD *thd, sp_pcontext *param_spcont, sp_assignment_lex *param_lex, Item_args *parameters) { DBUG_ASSERT(param_spcont->context_var_count() == parameters->argument_count()); for (uint idx= 0; idx < parameters->argument_count(); idx ++) { /* param_lex is shared between multiple items (cursor parameters). Only the last sp_instr_set is responsible for freeing param_lex. See more comments in LEX::sp_for_loop_cursor_declarations in sql_lex.cc. */ bool last= idx + 1 == parameters->argument_count(); sp_variable *spvar= param_spcont->get_context_variable(idx); if (set_local_variable(thd, param_spcont, &sp_rcontext_handler_local, spvar, parameters->arguments()[idx], param_lex, last)) return true; } return false; } bool sp_head::spvar_fill_row(THD *thd, sp_variable *spvar, Row_definition_list *defs) { spvar->field_def.set_row_field_definitions(defs); spvar->field_def.field_name= spvar->name; if (fill_spvar_definition(thd, &spvar->field_def)) return true; row_fill_field_definitions(thd, defs); return false; } bool sp_head::spvar_fill_type_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &table, const LEX_CSTRING &col) { Qualified_column_ident *ref; if (!(ref= new (thd->mem_root) Qualified_column_ident(&table, &col))) return true; fill_spvar_using_type_reference(spvar, ref); return false; } bool sp_head::spvar_fill_type_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &db, const LEX_CSTRING &table, const LEX_CSTRING &col) { Qualified_column_ident *ref; if (!(ref= new (thd->mem_root) Qualified_column_ident(thd, &db, &table, &col))) return true; fill_spvar_using_type_reference(spvar, ref); return false; } bool sp_head::spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &table) { Table_ident *ref; if (!(ref= new (thd->mem_root) Table_ident(&table))) return true; fill_spvar_using_table_rowtype_reference(thd, spvar, ref); return false; } bool sp_head::spvar_fill_table_rowtype_reference(THD *thd, sp_variable *spvar, const LEX_CSTRING &db, const LEX_CSTRING &table) { Table_ident *ref; if (!(ref= new (thd->mem_root) Table_ident(thd, &db, &table, false))) return true; fill_spvar_using_table_rowtype_reference(thd, spvar, ref); return false; } bool sp_head::check_group_aggregate_instructions_forbid() const { if (unlikely(m_flags & sp_head::HAS_AGGREGATE_INSTR)) { my_error(ER_NOT_AGGREGATE_FUNCTION, MYF(0)); return true; } return false; } bool sp_head::check_group_aggregate_instructions_require() const { if (unlikely(!(m_flags & HAS_AGGREGATE_INSTR))) { my_error(ER_INVALID_AGGREGATE_FUNCTION, MYF(0)); return true; } return false; } bool sp_head::check_group_aggregate_instructions_function() const { return agg_type() == GROUP_AGGREGATE ? check_group_aggregate_instructions_require() : check_group_aggregate_instructions_forbid(); } /* In Oracle mode stored routines have an optional name at the end of a declaration: PROCEDURE p1 AS BEGIN NULL END p1; Check that the first p1 and the last p1 match. */ bool sp_head::check_package_routine_end_name(const LEX_CSTRING &end_name) const { LEX_CSTRING non_qualified_name= m_name; const char *errpos; size_t ofs; if (!end_name.length) return false; // No end name if (!(errpos= strrchr(m_name.str, '.'))) { errpos= m_name.str; goto err; } errpos++; ofs= errpos - m_name.str; non_qualified_name.str+= ofs; non_qualified_name.length-= ofs; if (Sp_handler::eq_routine_name(end_name, non_qualified_name)) return false; err: my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0), end_name.str, errpos); return true; } bool sp_head::check_standalone_routine_end_name(const sp_name *end_name) const { if (end_name && !end_name->eq(this)) { my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0), ErrConvDQName(end_name).ptr(), ErrConvDQName(this).ptr()); return true; } return false; } ulong sp_head::sp_cache_version() const { return m_parent ? m_parent->sp_cache_version() : m_sp_cache_version; }
MariaDB/server
sql/sp_head.cc
C++
gpl-2.0
158,392
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QXmlInputSource> #include <QMessageBox> #include <U2Core/AppContext.h> #include <U2Core/GUrlUtils.h> #include <U2Core/L10n.h> #include <U2Core/LoadRemoteDocumentTask.h> #include <U2Core/Log.h> #include <U2Core/MultiTask.h> #include <U2Core/Settings.h> #include <U2Core/U2OpStatusUtils.h> #include <U2Core/U2SafePoints.h> #include <U2Gui/HelpButton.h> #include <QPushButton> #include <U2Gui/LastUsedDirHelper.h> #include <U2Gui/U2FileDialog.h> #include "DownloadRemoteFileDialog.h" #include "OpenViewTask.h" #include "ui_DownloadRemoteFileDialog.h" static const QString SAVE_DIR("downloadremotefiledialog/savedir"); static const QString HINT_STYLE_SHEET = "color:green; font:bold"; namespace U2 { QString DownloadRemoteFileDialog::defaultDB(""); DownloadRemoteFileDialog::DownloadRemoteFileDialog(QWidget *p):QDialog(p), isQueryDB(false) { ui = new Ui_DownloadRemoteFileDialog; ui->setupUi(this); new HelpButton(this, ui->buttonBox, "19766692"); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->formatBox->hide(); ui->formatLabel->hide(); adjustSize(); RemoteDBRegistry& registry = RemoteDBRegistry::getRemoteDBRegistry(); const QList<QString> dataBases = registry.getDBs(); foreach(const QString& dbName, dataBases) { ui->databasesBox->addItem(dbName, dbName); } if (!defaultDB.isEmpty()) { int index = ui->databasesBox->findData(defaultDB); if (index != -1){ ui->databasesBox->setCurrentIndex(index); } } ui->hintLabel->setStyleSheet( HINT_STYLE_SHEET ); connect(ui->databasesBox, SIGNAL(currentIndexChanged ( int)), SLOT( sl_onDbChanged())); connect(ui->saveFilenameToolButton, SIGNAL(clicked()), SLOT(sl_saveFilenameButtonClicked())); connect(ui->hintLabel, SIGNAL(linkActivated(const QString&)), SLOT(sl_linkActivated(const QString& ))); sl_onDbChanged(); setSaveFilename(); } DownloadRemoteFileDialog::DownloadRemoteFileDialog( const QString& id, const QString& dbId, QWidget *p /* = NULL*/ ) :QDialog(p), isQueryDB(false) { ui = new Ui_DownloadRemoteFileDialog; ui->setupUi(this); new HelpButton(this, ui->buttonBox, "19766704"); ui->formatBox->addItem(GENBANK_FORMAT); ui->formatBox->addItem(FASTA_FORMAT); connect(ui->formatBox, SIGNAL(currentIndexChanged(const QString &)), SLOT(sl_formatChanged(const QString &))); adjustSize(); ui->databasesBox->clear(); const QString dbName = dbId == EntrezUtils::NCBI_DB_PROTEIN ? RemoteDBRegistry::GENBANK_PROTEIN : RemoteDBRegistry::GENBANK_DNA; ui->databasesBox->addItem(dbName,dbName); ui->idLineEdit->setText(id); ui->idLineEdit->setReadOnly(true); delete ui->hintLabel; ui->hintLabel = NULL; setMinimumSize( 500, 0 ); connect(ui->saveFilenameToolButton, SIGNAL(clicked()), SLOT(sl_saveFilenameButtonClicked())); setSaveFilename(); } const QString DOWNLOAD_REMOTE_FILE_DOMAIN = "DownloadRemoteFileDialog"; void DownloadRemoteFileDialog::sl_saveFilenameButtonClicked() { LastUsedDirHelper lod(DOWNLOAD_REMOTE_FILE_DOMAIN); QString filename = U2FileDialog::getExistingDirectory(this, tr("Select folder to save"), lod.dir); if(!filename.isEmpty()) { ui->saveFilenameLineEdit->setText(filename); lod.url = filename; } } static const QString DEFAULT_FILENAME = "file.format"; void DownloadRemoteFileDialog::setSaveFilename() { QString dir = AppContext::getSettings()->getValue(SAVE_DIR, "").value<QString>(); if(dir.isEmpty()) { dir = LoadRemoteDocumentTask::getDefaultDownloadDirectory(); assert(!dir.isEmpty()); } ui->saveFilenameLineEdit->setText(QDir::toNativeSeparators(dir)); } QString DownloadRemoteFileDialog::getResourceId() const { return ui->idLineEdit->text().trimmed(); } QString DownloadRemoteFileDialog::getDBId() const { int curIdx = ui->databasesBox->currentIndex(); if (curIdx == -1){ return QString(""); } return ui->databasesBox->itemData(curIdx).toString(); } QString DownloadRemoteFileDialog::getFullpath() const { return ui->saveFilenameLineEdit->text(); } void DownloadRemoteFileDialog::accept() { defaultDB = getDBId(); QString resourceId = getResourceId(); if( resourceId.isEmpty() ) { QMessageBox::critical(this, L10N::errorTitle(), tr("Resource id is empty!")); ui->idLineEdit->setFocus(); return; } QString fullPath = getFullpath(); if( ui->saveFilenameLineEdit->text().isEmpty() ) { QMessageBox::critical(this, L10N::errorTitle(), tr("No folder selected for saving file!")); ui->saveFilenameLineEdit->setFocus(); return; } U2OpStatus2Log os; fullPath = GUrlUtils::prepareDirLocation(fullPath, os); if (fullPath.isEmpty()) { QMessageBox::critical(this, L10N::errorTitle(), os.getError()); ui->saveFilenameLineEdit->setFocus(); return; } QString dbId = getDBId(); QStringList resIds = resourceId.split(QRegExp("[\\s,;]+")); QList<Task*> tasks; QString fileFormat; if (ui->formatBox->count() > 0) { fileFormat = ui->formatBox->currentText(); } QVariantMap hints; hints.insert(FORCE_DOWNLOAD_SEQUENCE_HINT, ui->chbForceDownloadSequence->isVisible() && ui->chbForceDownloadSequence->isChecked()); int taskCount = 0; bool addToProject = ui->chbAddToProjectCheck->isChecked(); if (addToProject && resIds.size() >= 100) { QString message = tr("There are more than 100 files found for download.\nAre you sure you want to open all of them?"); int button = QMessageBox::question(QApplication::activeWindow(), tr("Warning"), message, tr("Cancel"), tr("Open anyway"), tr("Don't open")); if (button == 0) { return; // return to dialog } else if (button == 2) { addToProject = false; } } foreach (const QString &resId, resIds) { LoadRemoteDocumentMode mode = LoadRemoteDocumentMode_LoadOnly; if (addToProject) { mode = taskCount < OpenViewTask::MAX_DOC_NUMBER_TO_OPEN_VIEWS ? LoadRemoteDocumentMode_OpenView : LoadRemoteDocumentMode_AddToProject; } tasks.append(new LoadRemoteDocumentAndAddToProjectTask(resId, dbId, fullPath, fileFormat, hints, mode)); taskCount++; } AppContext::getTaskScheduler()->registerTopLevelTask(new MultiTask(tr("Download remote documents"), tasks)); QDialog::accept(); } DownloadRemoteFileDialog::~DownloadRemoteFileDialog() { AppContext::getSettings()->setValue(SAVE_DIR, ui->saveFilenameLineEdit->text()); delete ui; } bool DownloadRemoteFileDialog::isNcbiDb(const QString &dbId) const { return dbId == RemoteDBRegistry::GENBANK_DNA || dbId == RemoteDBRegistry::GENBANK_PROTEIN; } void DownloadRemoteFileDialog::sl_onDbChanged(){ QString dbId = getDBId(); QString hint; QString description; ui->chbForceDownloadSequence->setVisible(isNcbiDb(dbId)); RemoteDBRegistry& registry = RemoteDBRegistry::getRemoteDBRegistry(); hint = description = registry.getHint(dbId); setupHintText( hint ); ui->idLineEdit->setToolTip(description); } void DownloadRemoteFileDialog::sl_formatChanged(const QString &format) { ui->chbForceDownloadSequence->setVisible(GENBANK_FORMAT == format); } void DownloadRemoteFileDialog::sl_linkActivated( const QString& link ){ if (!link.isEmpty()){ ui->idLineEdit->setText(link); } } void DownloadRemoteFileDialog::setupHintText( const QString &text ) { SAFE_POINT( NULL != ui && NULL != ui->hintLabel, "Invalid dialog content!", ); const QString hintStart( tr( "Hint: " ) ); const QString hintSample = ( text.isEmpty( ) ? tr( "Use database unique identifier." ) : text ) + "<br>"; const QString hintEnd( tr( "You can download multiple items by separating IDs with space " "or semicolon." ) ); ui->hintLabel->setText( hintStart + hintSample + hintEnd ); } } //namespace
ggrekhov/ugene
src/corelibs/U2Gui/src/util/DownloadRemoteFileDialog.cpp
C++
gpl-2.0
9,132
class AddScraperwikiNameToAuthorities < ActiveRecord::Migration[4.2] def self.up add_column :authorities, :scraperwiki_name, :string end def self.down remove_column :authorities, :scraperwiki_name end end
openaustralia/planningalerts
db/migrate/20120819091645_add_scraperwiki_name_to_authorities.rb
Ruby
gpl-2.0
222
""" OK resolveurl XBMC Addon Copyright (C) 2016 Seberoth Version 0.0.2 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/>. """ import json, urllib from resolveurl import common from lib import helpers from resolveurl.resolver import ResolveUrl, ResolverError class OKResolver(ResolveUrl): name = "ok.ru" domains = ['ok.ru', 'odnoklassniki.ru'] pattern = '(?://|\.)(ok\.ru|odnoklassniki\.ru)/(?:videoembed|video)/(\d+)' header = {"User-Agent": common.OPERA_USER_AGENT} qual_map = {'ultra': '2160', 'quad': '1440', 'full': '1080', 'hd': '720', 'sd': '480', 'low': '360', 'lowest': '240', 'mobile': '144'} def __init__(self): self.net = common.Net() def get_media_url(self, host, media_id): vids = self.__get_Metadata(media_id) sources = [] for entry in vids['urls']: quality = self.__replaceQuality(entry['name']) sources.append((quality, entry['url'])) try: sources.sort(key=lambda x: int(x[0]), reverse=True) except: pass source = helpers.pick_source(sources) source = source.encode('utf-8') + helpers.append_headers(self.header) return source def __replaceQuality(self, qual): return self.qual_map.get(qual.lower(), '000') def __get_Metadata(self, media_id): url = "http://www.ok.ru/dk" data = {'cmd': 'videoPlayerMetadata', 'mid': media_id} data = urllib.urlencode(data) html = self.net.http_POST(url, data, headers=self.header).content json_data = json.loads(html) if 'error' in json_data: raise ResolverError('File Not Found or removed') info = dict() info['urls'] = [] for entry in json_data['videos']: info['urls'].append(entry) return info def get_url(self, host, media_id): return self._default_get_url(host, media_id, 'http://{host}/videoembed/{media_id}')
felipenaselva/felipe.repository
script.module.resolveurl/lib/resolveurl/plugins/ok.py
Python
gpl-2.0
2,491
#include <vector> #include <fstream> #include <logger.h> #include <iupnpdevicedelegate.h> #include <cupnpservice.h> #include <crapidxmlhelper.h> #include "cmediaserverdelegate.h" #define XSTR(x) #x #define STR(x) XSTR(x) #define UPNP_MEDIA_SERVER_DEVICE_TYPE "urn:schemas-upnp-org:device:MediaServer:1" #define UPNP_MEDIA_SERVER_SERVICE_CDS "urn:schemas-upnp-org:service:ContentDirectory:1" #define UPNP_MEDIA_SERVER_SERVICE_ID "urn:upnp-org:serviceId:ContentDirectory" #define RESOURCE_MEDIA_SERVER_CDS_PATH STR(RESOURCE_PATH)"/resources/mediaServerCDS.xml" #define MEDIA_SERVER_CDS_PATH "/service/mediaServerCDS.xml" #define MEDIA_SERVER_CDC_PATH "/control/contentdirectory.xml" //#define RESOURCE_MEDIA_SERVER_ROOT STR(RESOURCE_PATH)"/resources/mediaServerRoot.xml" static std::map<std::string, CUPnPService *> l_serviceList; CMediaServerDelegate::CMediaServerDelegate(const std::string &uuid, const std::string &friendlyName, const std::string &manufacturer, const std::string &manufacturerUrl) : m_uuid(uuid), m_friendlyName(friendlyName), m_manufacturer(manufacturer), m_manufacturerUrl(manufacturerUrl) { registerServices(); } CMediaServerDelegate::~CMediaServerDelegate() { auto service_it = l_serviceList.begin(); for(;service_it != l_serviceList.end(); service_it++) { delete service_it->second; } l_serviceList.clear(); } const char *CMediaServerDelegate::getDeviceType() const { return UPNP_MEDIA_SERVER_DEVICE_TYPE; } const char *CMediaServerDelegate::getFriendlyName() const { return m_friendlyName.data(); } const char *CMediaServerDelegate::getManufacturer() const { return m_manufacturer.data(); } const char *CMediaServerDelegate::getManufacturerUrl() const { return m_manufacturerUrl.data(); } const char *CMediaServerDelegate::getUuid() const { return m_uuid.data(); } bool CMediaServerDelegate::onAction(const CUPnPAction &action) { return false; } std::map<std::string, CUPnPService *> CMediaServerDelegate::getServiceList() const { return l_serviceList; } bool CMediaServerDelegate::addService(CUPnPService *service) { if(l_serviceList.find(service->getType()) == l_serviceList.end()) { l_serviceList.insert(std::pair<std::string, CUPnPService *>(service->getType(), service)); return true; } return false; } void CMediaServerDelegate::registerServices() { // There are three services in the MediaServer:1 // ContentDirectory:1.0 (required) // ConnectionManager:1.0 (required) // AVTransport:1.0 (optional) registerService(UPNP_MEDIA_SERVER_SERVICE_CDS, UPNP_MEDIA_SERVER_SERVICE_ID, MEDIA_SERVER_CDS_PATH, RESOURCE_MEDIA_SERVER_CDS_PATH, MEDIA_SERVER_CDC_PATH); //registerConnectionManager(); //AVTransport(); } bool CMediaServerDelegate::registerService(const std::string &type, const std::string &id, const std::string &scpdServerPath, const std::string &descrXmlPath, const std::string &controlPath) { std::string xmlContent; if(loadFile(descrXmlPath, xmlContent)) { try { CUPnPService *service = CUPnPService::create(&(xmlContent)[0]); if(service) { service->setType(type); service->setId(id); service->setSCPDPath(scpdServerPath); service->setControlPath(controlPath); return addService(service); } else { LOGGER_ERROR("Error while parsing device services."); } } catch(const rapidxml::parse_error &err) { LOGGER_ERROR("XML parse error. what='" << err.what() << "'"); } } else { LOGGER_ERROR("Error reading file. descrXmlPath=" << descrXmlPath); } return false; } bool CMediaServerDelegate::loadFile(const std::string &filePath, std::string &fileContent) { std::ifstream istream(filePath); if(istream.is_open()) { istream.seekg(0, std::ios::end); size_t strSize = (1 + istream.tellg()); fileContent.reserve(strSize); istream.seekg(0, std::ios::beg); fileContent.assign(std::istreambuf_iterator<char>(istream), std::istreambuf_iterator<char>()); fileContent[strSize-1] = '\0'; return true; } return false; }
vrbincs/storm
smediaserver/cmediaserverdelegate.cpp
C++
gpl-2.0
4,748
/*************************************************************************** file : axle.cpp created : Sun Mar 19 00:05:09 CET 2000 copyright : (C) 2000 by Eric Espie email : torcs@free.fr version : $Id$ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "sim.h" static const char *AxleSect[2] = {SECT_FRNTAXLE, SECT_REARAXLE}; void SimAxleConfig(tCar *car, int index) { void *hdle = car->params; tdble rollCenter; tAxle *axle = &(car->axle[index]); axle->xpos = GfParmGetNum(hdle, AxleSect[index], PRM_XPOS, (char*)NULL, 0); axle->I = GfParmGetNum(hdle, AxleSect[index], PRM_INERTIA, (char*)NULL, 0.15); rollCenter = GfParmGetNum(hdle, AxleSect[index], PRM_ROLLCENTER, (char*)NULL, 0.15); car->wheel[index*2].rollCenter = car->wheel[index*2+1].rollCenter = rollCenter; if (index == 0) { SimSuspConfig(hdle, SECT_FRNTARB, &(axle->arbSusp), 0, 0); } else { SimSuspConfig(hdle, SECT_REARARB, &(axle->arbSusp), 0, 0); } car->wheel[index*2].feedBack.I += axle->I / 2.0; car->wheel[index*2+1].feedBack.I += axle->I / 2.0; } void SimAxleUpdate(tCar *car, int index) { tAxle *axle = &(car->axle[index]); tdble str, stl, sgn; str = car->wheel[index*2].susp.x; stl = car->wheel[index*2+1].susp.x; sgn = SIGN(stl - str); #if 0 axle->arbSusp.x = fabs(stl - str); SimSuspCheckIn(&(axle->arbSusp)); SimSuspUpdate(&(axle->arbSusp)); #else axle->arbSusp.x = fabs(stl - str); if (axle->arbSusp.x > axle->arbSusp.spring.xMax) { axle->arbSusp.x = axle->arbSusp.spring.xMax; } axle->arbSusp.force = - axle->arbSusp.x *axle->arbSusp.spring.K; //axle->arbSusp.force = pow (axle->arbSusp.x *axle->arbSusp.spring.K , 4.0); #endif car->wheel[index*2].axleFz = sgn * axle->arbSusp.force; car->wheel[index*2+1].axleFz = - sgn * axle->arbSusp.force; // printf ("%f %f %f ", stl, str, axle->arbSusp.force); // if (index==0) { // printf ("# SUSP\n"); // } }
jeremybennett/torcs
src/modules/simu/simuv3/axle.cpp
C++
gpl-2.0
2,750
<?php // Translations can be filed in the /languages/ directory load_theme_textdomain( 'covasolutions', TEMPLATEPATH . '/languages' ); $locale = get_locale(); $locale_file = TEMPLATEPATH . "/languages/$locale.php"; if ( is_readable($locale_file) ) require_once($locale_file); // Add RSS links to <head> section automatic_feed_links(); // Clean up the <head> function removeHeadLinks() { remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wlwmanifest_link'); } add_action('init', 'removeHeadLinks'); remove_action('wp_head', 'wp_generator'); if (function_exists('register_sidebar')) { register_sidebar(array( 'name' => __('Sidebar Widgets','covasolutions' ), 'id' => 'sidebar-widgets', 'description' => __( 'These are widgets for the sidebar.','covasolutions' ), 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2>', 'after_title' => '</h2>' )); } add_theme_support( 'post-formats', array('aside', 'gallery', 'link', 'image', 'quote', 'status', 'audio', 'chat', 'video')); // Add 3.1 post format theme support. if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 70, 70, true ); // default Post Thumbnail dimensions (cropped) } //custom excerpt filter length for homepage function custom_excerpt_length( $length ) { return 20; } add_filter( 'excerpt_length', 'custom_excerpt_length', 20 ); ?>
gilsondesign/covasolutions
wp-content/themes/CovaSolutions/functions.php
PHP
gpl-2.0
1,598
/* * Balance.hpp * * Created on: Apr 24, 2014 * Author: f3r0x */ #ifndef BALANCE_HPP_ #define BALANCE_HPP_ // BalanceSheet #include "SheetItem.hpp" namespace bs { class Balance { private: std::string name; SheetItem assets; SheetItem liabilities; public: Balance(); Balance(std::string name); virtual ~Balance(); void init(); void print(); }; } /* namespace bs */ #endif /* BALANCE_HPP_ */
VirtualChicken/BalanceSheet
BalanceSheet/include/Balance.hpp
C++
gpl-2.0
417
import F2 from '@antv/f2'; fetch('https://gw.alipayobjects.com/os/antfincdn/N81gEpw2Ef/income.json') .then(res => res.json()) .then(data => { const chart = new F2.Chart({ id: 'container', pixelRatio: window.devicePixelRatio }); chart.source(data, { time: { type: 'timeCat', range: [ 0, 1 ], tickCount: 3 } }); chart.axis('time', { label: function label(text, index, total) { const textCfg = {}; if (index === 0) { textCfg.textAlign = 'left'; } else if (index === total - 1) { textCfg.textAlign = 'right'; } return textCfg; } }); chart.guide().point({ position: [ '2014-01-03', 6.763 ] }); chart.guide().text({ position: [ '2014-01-03', 6.763 ], content: '受稳健货币政策影响,协定存款利\n率居高不下,收益率达6.763%', style: { textAlign: 'left', lineHeight: 16, fontSize: 10 }, offsetX: 10 }); chart.guide().point({ position: [ '2013-05-31', 2.093 ] }); chart.guide().text({ position: [ '2013-05-31', 2.093 ], content: '余额宝刚成立时,并未达到\n目标资产配置,故收益率较低', style: { textAlign: 'left', lineHeight: 16, fontSize: 10 }, offsetX: 10, offsetY: -10 }); chart.guide().point({ position: [ '2016-09-04', 2.321 ] }); chart.guide().text({ position: [ '2016-09-04', 2.321 ], content: '受积极货币政策的影响,收益率降\n到历史最低2.321%', style: { textBaseline: 'bottom', lineHeight: 16, fontSize: 10 }, offsetY: -20 }); chart.line().position('time*rate'); chart.render(); });
antvis/g2-mobile
examples/component/guide/demo/point.js
JavaScript
gpl-2.0
1,844
<?php /** * The template for displaying 404 pages (not found). * * @package fortunato */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <section class="error-404 not-found"> <header class="page-header"> <h1 class="page-title"><?php _e( 'Oops! That page can&rsquo;t be found.', 'fortunato' ); ?></h1> </header><!-- .page-header --> <div class="page-content"> <p><?php _e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'fortunato' ); ?></p> <?php get_search_form(); ?> <?php the_widget( 'WP_Widget_Recent_Posts' ); ?> <?php /* translators: %1$s: smiley */ $archive_content = '<p>' . sprintf( __( 'Try looking in the monthly archives. %1$s', 'fortunato' ), convert_smilies( ':)' ) ) . '</p>'; the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" ); ?> <?php the_widget( 'WP_Widget_Tag_Cloud' ); ?> </div><!-- .page-content --> </section><!-- .error-404 --> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
albertoquijano/JesusGiles
wp-content/themes/fortunato/404.php
PHP
gpl-2.0
1,184
require 'rails_helper' RSpec.describe Webui::UserController do let!(:user) { create(:confirmed_user, login: 'tom') } let!(:non_admin_user) { create(:confirmed_user, login: 'moi') } let!(:admin_user) { create(:admin_user, login: 'king') } let(:deleted_user) { create(:deleted_user) } let!(:non_admin_user_request) { create(:bs_request, priority: 'critical', creator: non_admin_user, commenter: non_admin_user) } it { is_expected.to use_before_action(:require_login) } it { is_expected.to use_before_action(:require_admin) } describe 'GET #index' do before do login admin_user get :index end it { is_expected.to render_template('webui/user/index') } end describe 'GET #show' do shared_examples 'a non existent account' do before do request.env['HTTP_REFERER'] = root_url # Needed for the redirect_to(root_url) get :show, params: { user: user } end it { expect(controller).to set_flash[:error].to("User not found #{user}") } it { expect(response).to redirect_to(root_url) } end context 'when the current user is admin' do before { login admin_user } it 'deleted users are shown' do get :show, params: { user: deleted_user } expect(response).to render_template('webui/user/show') end describe 'showing a non valid users' do subject(:user) { 'INVALID_USER' } it_should_behave_like 'a non existent account' end end context "when the current user isn't admin" do before { login non_admin_user } describe 'showing a deleted user' do subject(:user) { deleted_user } it_should_behave_like 'a non existent account' end describe 'showing an invalid user' do subject(:user) { 'INVALID_USER' } it_should_behave_like 'a non existent account' end describe 'showing someone else' do it 'does not include requests' do get :show, params: { user: admin_user } expect(assigns(:reviews)).to be_nil end end end end describe 'GET #user_edit' do before do login admin_user get :edit, params: { user: user } end it { is_expected.to render_template('webui/user/edit') } end describe 'GET #home' do skip end describe 'POST #save' do context 'when user is updating its own profile' do context 'with valid data' do before do login user post :save, params: { user: { login: user.login, realname: 'another real name', email: 'new_valid@email.es', state: 'locked', ignore_auth_services: true } } user.reload end it { expect(flash[:success]).to eq("User data for user '#{user.login}' successfully updated.") } it { expect(user.realname).to eq('another real name') } it { expect(user.email).to eq('new_valid@email.es') } it { expect(user.state).to eq('confirmed') } it { expect(user.ignore_auth_services).to be false } it { is_expected.to redirect_to user_show_path(user) } end context 'with invalid data' do before do login user post :save, params: { user: { login: user.login, realname: 'another real name', email: 'invalid' } } user.reload end it { expect(flash[:error]).to eq("Couldn't update user: Validation failed: Email must be a valid email address.") } it { expect(user.realname).to eq(user.realname) } it { expect(user.email).to eq(user.email) } it { expect(user.state).to eq('confirmed') } it { is_expected.to redirect_to user_show_path(user) } end end context "when user is trying to update another user's profile" do before do login user post :save, params: { user: { login: non_admin_user.login, realname: 'another real name', email: 'new_valid@email.es' } } non_admin_user.reload end it { expect(non_admin_user.realname).not_to eq('another real name') } it { expect(non_admin_user.email).not_to eq('new_valid@email.es') } it { expect(flash[:error]).to eq("Can't edit #{non_admin_user.login}") } it { is_expected.to redirect_to(root_url) } end context "when admin is updating another user's profile" do let(:old_global_role) { create(:role, global: true, title: 'old_global_role') } let(:new_global_roles) { create_list(:role, 2, global: true) } let(:local_roles) { create_list(:role, 2) } before do user.roles << old_global_role user.roles << local_roles login admin_user post :save, params: { user: { login: user.login, realname: 'another real name', email: 'new_valid@email.es', state: 'locked', role_ids: new_global_roles.pluck(:id), ignore_auth_services: 'true' } } user.reload end it { expect(user.realname).to eq('another real name') } it { expect(user.email).to eq('new_valid@email.es') } it { expect(user.state).to eq('locked') } it { expect(user.ignore_auth_services).to be true } it { is_expected.to redirect_to user_show_path(user) } it "updates the user's roles" do expect(user.roles).not_to include(old_global_role) expect(user.roles).to include(*new_global_roles) end it 'does not remove non global roles' do expect(user.roles).to include(*local_roles) end end context 'when roles parameter is empty' do let(:old_global_role) { create(:role, global: true, title: 'old_global_role') } let(:local_roles) { create_list(:role, 2) } before do user.roles << old_global_role user.roles << local_roles login admin_user # Rails form helper sends an empty string in an array if no checkbox was marked post :save, params: { user: { login: user.login, email: 'new_valid@email.es', role_ids: [''] } } user.reload end it 'drops all global roles' do expect(user.roles).to match_array local_roles end end context 'when state and roles are not passed as parameter' do let(:old_global_role) { create(:role, global: true, title: 'old_global_role') } before do user.roles << old_global_role login admin_user post :save, params: { user: { login: user.login, email: 'new_valid@email.es' } } user.reload end it 'keeps the old state' do expect(user.state).to eq('confirmed') end it 'does not drop the roles' do expect(user.roles).to match_array old_global_role end end context 'when LDAP mode is enabled' do let!(:old_realname) { user.realname } let!(:old_email) { user.email } let(:http_request) do post :save, params: { user: { login: user.login, realname: 'another real name', email: 'new_valid@email.es' } } end before do stub_const('CONFIG', CONFIG.merge('ldap_mode' => :on)) end describe 'as an admin user' do before do login admin_user http_request user.reload end it { expect(user.realname).to eq(old_realname) } it { expect(user.email).to eq(old_email) } end describe 'as a user' do before do login user http_request user.reload end it { expect(controller).to set_flash[:error] } it { expect(user.realname).to eq(old_realname) } it { expect(user.email).to eq(old_email) } end describe 'but user is configured to authorize locally' do before do user.update(ignore_auth_services: true) login user http_request user.reload end it { expect(user.realname).to eq('another real name') } it { expect(user.email).to eq('new_valid@email.es') } end end end describe 'PATCH #update' do let(:deleted_user) { create(:user, state: 'deleted') } context 'called by an admin user' do before do login(admin_user) end it 'updates the state of a user' do patch :update, params: { user: { login: user.login, state: 'locked' } } expect(user.reload.state).to eq('locked') end it 'marks users to be ignored from LDAP authentication' do patch :update, params: { user: { login: user.login, ignore_auth_services: true } } expect(user.reload.ignore_auth_services).to be true end it 'updates deleted users' do patch :update, params: { user: { login: deleted_user.login, state: 'confirmed' } } expect(user.reload.state).to eq('confirmed') end it 'handles validation errors' do patch :update, params: { user: { login: user.login, state: 'foo' } } expect(user.reload.state).to eq('confirmed') expect(flash[:error]).to eq("Updating user '#{user.login}' failed: State is not included in the list") end it 'applies the Admin role properly' do patch :update, params: { user: { login: user.login, make_admin: true } } expect(user.roles.find_by(title: 'Admin')).not_to be_nil end end context 'called by a user that is not admin' do let(:non_admin_user) { create(:confirmed_user) } before do login(non_admin_user) end it 'does not update a user' do patch :update, params: { user: { login: user.login, state: 'locked' } } expect(user.reload.state).to eq('confirmed') end end end describe 'DELETE #delete' do context 'called by an admin user' do before do login(admin_user) end it "changes the state to 'deleted'" do delete :delete, params: { user: { login: user.login } } expect(user.reload.state).to eq('deleted') end it 'handles validation errors' do user.update_attributes(email: 'invalid') user.save!(validate: false) delete :delete, params: { user: { login: user.login } } expect(user.reload.state).to eq('confirmed') expect(flash[:error]).to eq("Marking user '#{user.login}' as deleted failed: Email must be a valid email address") end end context 'called by a user that is not admin' do let(:non_admin_user) { create(:confirmed_user) } before do login(non_admin_user) end it "does not changes the state to 'deleted'" do delete :delete, params: { user: { login: user.login } } expect(user.reload.state).to eq('confirmed') end end end describe 'GET #save_dialog' do skip end describe 'GET #icon' do let(:user) { create(:confirmed_user, login: 'iconic') } it 'loads big icon without param' do get :icon, params: { user: user.login } expect(response.body.size).to be > 2000 end it 'loads small icon with param' do get :icon, params: { user: user.login, size: 20 } expect(response.body.size).to be < 1000 end end describe 'POST #register' do let!(:new_user) { build(:user, login: 'moi_new') } context 'when existing user is already registered with this login' do before do already_registered_user = create(:confirmed_user, login: 'previous_user') post :register, params: { login: already_registered_user.login, email: already_registered_user.email, password: 'buildservice' } end it { expect(flash[:error]).not_to be nil } it { expect(response).to redirect_to root_path } end context 'when home project creation enabled' do before do allow(Configuration).to receive(:allow_user_to_create_home_project).and_return(true) post :register, params: { login: new_user.login, email: new_user.email, password: 'buildservice' } end it { expect(flash[:success]).to eq("The account '#{new_user.login}' is now active.") } it { expect(response).to redirect_to project_show_path(new_user.home_project) } end context 'when home project creation disabled' do before do allow(Configuration).to receive(:allow_user_to_create_home_project).and_return(false) post :register, params: { login: new_user.login, email: new_user.email, password: 'buildservice' } end it { expect(flash[:success]).to eq("The account '#{new_user.login}' is now active.") } it { expect(response).to redirect_to root_path } end end describe 'GET #register_user' do skip end describe 'GET #password_dialog' do skip end describe 'POST #change_password' do before do login non_admin_user stub_const('CONFIG', CONFIG.merge('ldap_mode' => :on)) post :change_password end it 'shows an error message when in LDAP mode' do expect(controller).to set_flash[:error] end end describe 'GET #autocomplete' do let!(:user) { create(:user, login: 'foobar') } it 'returns user login' do get :autocomplete, params: { term: 'foo', format: :json } expect(JSON.parse(response.body)).to match_array(['foobar']) end end describe 'GET #tokens' do let!(:user) { create(:user, login: 'foobaz') } it 'returns user token as array of hash' do get :tokens, params: { q: 'foo', format: :json } expect(JSON.parse(response.body)).to match_array(['name' => 'foobaz']) end end describe 'GET #notifications' do skip end describe 'GET #update_notifications' do skip end describe 'GET #list_users(prefix = nil, hash = nil)' do skip end end
mschnitzer/open-build-service
src/api/spec/controllers/webui/user_controller_spec.rb
Ruby
gpl-2.0
13,823
<?php /** * Smarty Internal Plugin Compile While * Compiles the {while} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile While Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_While extends Smarty_Internal_CompileBase { /** * Compiles code for the {while} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code * @throws \SmartyCompilerException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { $compiler->loopNesting++; // check and get attributes $_attr = $this->getAttributes($compiler, $args); $this->openTag($compiler, 'while', $compiler->nocache); if (!array_key_exists("if condition", $parameter)) { $compiler->trigger_template_error("missing while condition", null, true); } // maybe nocache because of nocache variables $compiler->nocache = $compiler->nocache | $compiler->tag_nocache; if (is_array($parameter['if condition'])) { if ($compiler->nocache) { $_nocache = ',true'; // create nocache var to make it know for further compiling if (is_array($parameter['if condition']['var'])) { $var = $parameter['if condition']['var']['var']; } else { $var = $parameter['if condition']['var']; } $compiler->setNocacheInVariable($var); } else { $_nocache = ''; } $assignCompiler = new Smarty_Internal_Compile_Assign(); $assignAttr = array(); $assignAttr[]['value'] = $parameter['if condition']['value']; if (is_array($parameter['if condition']['var'])) { $assignAttr[]['var'] = $parameter['if condition']['var']['var']; $_output = "<?php while (" . $parameter['if condition']['value'] . ") {?>"; $_output .= $assignCompiler->compile($assignAttr, $compiler, array('smarty_internal_index' => $parameter['if condition']['var']['smarty_internal_index'])); } else { $assignAttr[]['var'] = $parameter['if condition']['var']; $_output = "<?php while (" . $parameter['if condition']['value'] . ") {?>"; $_output .= $assignCompiler->compile($assignAttr, $compiler, array()); } return $_output; } else { return "<?php\n while ({$parameter['if condition']}) {?>"; } } } /** * Smarty Internal Plugin Compile Whileclose Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Whileclose extends Smarty_Internal_CompileBase { /** * Compiles code for the {/while} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * * @return string compiled code */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler) { $compiler->loopNesting--; // must endblock be nocache? if ($compiler->nocache) { $compiler->tag_nocache = true; } $compiler->nocache = $this->closeTag($compiler, array('while')); return "<?php }?>\n"; } }
a-v-k/phpBugTracker
inc/Smarty/libs/sysplugins/smarty_internal_compile_while.php
PHP
gpl-2.0
3,651
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2010-2012 Oregon <http://www.oregoncore.com/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "Language.h" #include "Database/DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "GossipDef.h" #include "SpellAuras.h" #include "UpdateMask.h" #include "ObjectAccessor.h" #include "Creature.h" #include "MapManager.h" #include "Pet.h" #include "BattlegroundMgr.h" #include "Battleground.h" #include "Guild.h" #include "ScriptMgr.h" void WorldSession::HandleTabardVendorActivateOpcode(WorldPacket & recv_data) { uint64 guid; recv_data >> guid; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TABARDDESIGNER); if (!unit) { sLog->outDebug("WORLD: HandleTabardVendorActivateOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); SendTabardVendorActivate(guid); } void WorldSession::SendTabardVendorActivate(uint64 guid) { WorldPacket data(MSG_TABARDVENDOR_ACTIVATE, 8); data << guid; SendPacket(&data); } void WorldSession::HandleBankerActivateOpcode(WorldPacket & recv_data) { sLog->outDebug( "WORLD: Received CMSG_BANKER_ACTIVATE"); uint64 guid; recv_data >> guid; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_BANKER); if (!unit) { sLog->outDebug("WORLD: HandleBankerActivateOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); SendShowBank(guid); } void WorldSession::SendShowBank(uint64 guid) { WorldPacket data(SMSG_SHOW_BANK, 8); data << guid; SendPacket(&data); } void WorldSession::HandleTrainerListOpcode(WorldPacket & recv_data) { uint64 guid; recv_data >> guid; SendTrainerList(guid); } void WorldSession::SendTrainerList(uint64 guid) { std::string str = GetSkyFireString(LANG_NPC_TAINER_HELLO); SendTrainerList(guid, str); } void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) { sLog->outDebug("WORLD: SendTrainerList"); Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); if (!unit) { sLog->outDebug("WORLD: SendTrainerList - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); // trainer list loaded at check; if (!unit->isCanTrainingOf(_player, true)) return; CreatureTemplate const *ci = unit->GetCreatureTemplate(); if (!ci) { sLog->outDebug("WORLD: SendTrainerList - (GUID: %u) NO CREATUREINFO!", GUID_LOPART(guid)); return; } TrainerSpellData const* trainer_spells = unit->GetTrainerSpells(); if (!trainer_spells) { sLog->outDebug("WORLD: SendTrainerList - Training spells not found for creature (GUID: %u Entry: %u)", GUID_LOPART(guid), unit->GetEntry()); return; } WorldPacket data(SMSG_TRAINER_LIST, 8+4+4+trainer_spells->spellList.size()*38 + strTitle.size()+1); data << guid; data << uint32(trainer_spells->trainerType); size_t count_pos = data.wpos(); data << uint32(trainer_spells->spellList.size()); // reputation discount float fDiscountMod = _player->GetReputationPriceDiscount(unit); uint32 count = 0; for (TrainerSpellList::const_iterator itr = trainer_spells->spellList.begin(); itr != trainer_spells->spellList.end(); ++itr) { TrainerSpell const* tSpell = *itr; if (!_player->IsSpellFitByClassAndRace(tSpell->spell)) continue; ++count; bool primary_prof_first_rank = sSpellMgr->IsPrimaryProfessionFirstRankSpell(tSpell->spell); SpellChainNode const* chain_node = sSpellMgr->GetSpellChainNode(tSpell->spell); uint32 req_spell = sSpellMgr->GetSpellRequired(tSpell->spell); data << uint32(tSpell->spell); data << uint8(_player->GetTrainerSpellState(tSpell)); data << uint32(floor(tSpell->spellcost * fDiscountMod)); data << uint32(primary_prof_first_rank ? 1 : 0); // primary prof. learn confirmation dialog data << uint32(primary_prof_first_rank ? 1 : 0); // must be equal prev. field to have learn button in enabled state data << uint8(tSpell->reqlevel); data << uint32(tSpell->reqskill); data << uint32(tSpell->reqskillvalue); data << uint32(chain_node && chain_node->prev ? chain_node->prev : req_spell); data << uint32(chain_node && chain_node->prev ? req_spell : 0); data << uint32(0); } data << strTitle; data.put<uint32>(count_pos, count); SendPacket(&data); } void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recv_data) { uint64 guid; uint32 spellId = 0; recv_data >> guid >> spellId; sLog->outDebug("WORLD: Received CMSG_TRAINER_BUY_SPELL NpcGUID=%u, learn spell id is: %u", uint32(GUID_LOPART(guid)), spellId); Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); if (!unit) { sLog->outDebug("WORLD: HandleTrainerBuySpellOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); if (!unit->isCanTrainingOf(_player, true)) return; // check present spell in trainer spell list TrainerSpellData const* trainer_spells = unit->GetTrainerSpells(); if (!trainer_spells) return; // not found, cheat? TrainerSpell const* trainer_spell = trainer_spells->Find(spellId); if (!trainer_spell) return; // can't be learn, cheat? Or double learn with lags... if (_player->GetTrainerSpellState(trainer_spell) != TRAINER_SPELL_GREEN) return; // apply reputation discount uint32 nSpellCost = uint32(floor(trainer_spell->spellcost * _player->GetReputationPriceDiscount(unit))); // check money requirement if (_player->GetMoney() < nSpellCost) return; WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12); // visual effect on trainer data << uint64(guid) << uint32(0xB3); SendPacket(&data); data.Initialize(SMSG_PLAY_SPELL_IMPACT, 12); // visual effect on player data << uint64(_player->GetGUID()) << uint32(0x016A); SendPacket(&data); _player->ModifyMoney(-int32(nSpellCost)); // learn explicitly to prevent lost money at lags, learning spell will be only show spell animation _player->learnSpell(trainer_spell->spell); data.Initialize(SMSG_TRAINER_BUY_SUCCEEDED, 12); data << uint64(guid) << uint32(spellId); SendPacket(&data); } void WorldSession::HandleGossipHelloOpcode(WorldPacket & recv_data) { sLog->outDebug("WORLD: Received CMSG_GOSSIP_HELLO"); uint64 guid; recv_data >> guid; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE); if (!unit) { sLog->outDebug("WORLD: HandleGossipHelloOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } GetPlayer()->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); // remove fake death //if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) // GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); if (unit->isArmorer() || unit->isCivilian() || unit->isQuestGiver() || unit->isServiceProvider()) { unit->StopMoving(); } // If spiritguide, no need for gossip menu, just put player into resurrect queue if (unit->isSpiritGuide()) { BattleGround *bg = _player->GetBattleGround(); if (bg) { bg->AddPlayerToResurrectQueue(unit->GetGUID(), _player->GetGUID()); sBattleGroundMgr->SendAreaSpiritHealerQueryOpcode(_player, bg, unit->GetGUID()); return; } } if (!sScriptMgr->GossipHello(_player, unit)) { _player->TalkedToCreature(unit->GetEntry(), unit->GetGUID()); _player->PrepareGossipMenu(unit, unit->GetCreatureTemplate()->GossipMenuId); _player->SendPreparedGossip(unit); } } /*void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket & recv_data) { sLog->outDebug("WORLD: CMSG_GOSSIP_SELECT_OPTION"); uint32 option; uint32 unk; uint64 guid; std::string code = ""; recv_data >> guid >> unk >> option; if (_player->PlayerTalkClass->GossipOptionCoded(option)) { sLog->outDebug("reading string"); recv_data >> code; sLog->outDebug("string read: %s", code.c_str()); } Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_NONE); if (!unit) { sLog->outDebug("WORLD: HandleGossipSelectOptionOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); if (!code.empty()) { if (!sScriptMgr->GossipSelectWithCode(_player, unit, _player->PlayerTalkClass->GossipOptionSender (option), _player->PlayerTalkClass->GossipOptionAction(option), code.c_str())) unit->OnGossipSelect (_player, option); } else { if (!sScriptMgr->GossipSelect (_player, unit, _player->PlayerTalkClass->GossipOptionSender (option), _player->PlayerTalkClass->GossipOptionAction (option))) unit->OnGossipSelect (_player, option); } }*/ void WorldSession::HandleSpiritHealerActivateOpcode(WorldPacket & recv_data) { sLog->outDebug("WORLD: CMSG_SPIRIT_HEALER_ACTIVATE"); uint64 guid; recv_data >> guid; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_SPIRITHEALER); if (!unit) { sLog->outDebug("WORLD: HandleSpiritHealerActivateOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(guid))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); SendSpiritResurrect(); } void WorldSession::SendSpiritResurrect() { _player->ResurrectPlayer(0.5f, true); _player->DurabilityLossAll(0.25f, true); // get corpse nearest graveyard WorldSafeLocsEntry const *corpseGrave = NULL; Corpse *corpse = _player->GetCorpse(); if (corpse) corpseGrave = sObjectMgr->GetClosestGraveYard( corpse->GetPositionX(), corpse->GetPositionY(), corpse->GetPositionZ(), corpse->GetMapId(), _player->GetTeam()); // now can spawn bones _player->SpawnCorpseBones(); // teleport to nearest from corpse graveyard, if different from nearest to player ghost if (corpseGrave) { WorldSafeLocsEntry const *ghostGrave = sObjectMgr->GetClosestGraveYard( _player->GetPositionX(), _player->GetPositionY(), _player->GetPositionZ(), _player->GetMapId(), _player->GetTeam()); if (corpseGrave != ghostGrave) _player->TeleportTo(corpseGrave->map_id, corpseGrave->x, corpseGrave->y, corpseGrave->z, _player->GetOrientation()); // or update at original position else _player->UpdateObjectVisibility(); } // or update at original position else _player->UpdateObjectVisibility(); } void WorldSession::HandleBinderActivateOpcode(WorldPacket & recv_data) { uint64 npcGUID; recv_data >> npcGUID; if (!GetPlayer()->IsInWorld() || !GetPlayer()->isAlive()) return; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_INNKEEPER); if (!unit) { sLog->outDebug("WORLD: HandleBinderActivateOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); SendBindPoint(unit); } void WorldSession::SendBindPoint(Creature *npc) { // prevent set homebind to instances in any case if (GetPlayer()->GetMap()->Instanceable()) return; // send spell for bind 3286 bind magic npc->CastSpell(_player, 3286, true); // Bind WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8+4)); data << npc->GetGUID(); data << uint32(3286); // Bind SendPacket(&data); _player->PlayerTalkClass->CloseGossip(); } //Need fix void WorldSession::HandleListStabledPetsOpcode(WorldPacket & recv_data) { sLog->outDebug("WORLD: Recv MSG_LIST_STABLED_PETS"); uint64 npcGUID; recv_data >> npcGUID; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_STABLEMASTER); if (!unit) { sLog->outDebug("WORLD: HandleListStabledPetsOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); // remove mounts this fix bug where getting pet from stable while mounted deletes pet. if (GetPlayer()->IsMounted()) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_MOUNTED); SendStablePet(npcGUID); } void WorldSession::SendStablePet(uint64 guid) { sLog->outDebug("WORLD: Recv MSG_LIST_STABLED_PETS Send."); WorldPacket data(MSG_LIST_STABLED_PETS, 200); // guess size data << uint64 (guid); Pet *pet = _player->GetPet(); data << uint8(0); // place holder for slot show number data << uint8(GetPlayer()->m_stableSlots); uint8 num = 0; // counter for place holder // not let move dead pet in slot if (pet && pet->isAlive() && pet->getPetType() == HUNTER_PET) { data << uint32(pet->GetCharmInfo()->GetPetNumber()); data << uint32(pet->GetEntry()); data << uint32(pet->getLevel()); data << pet->GetName(); // petname data << uint32(pet->GetLoyaltyLevel()); // loyalty data << uint8(0x01); // client slot 1 == current pet (0) ++num; } // 0 1 2 3 4 5 6 QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT owner, slot, id, entry, level, loyalty, name FROM character_pet WHERE owner = '%u' AND slot > 0 AND slot < 3", _player->GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); data << uint32(fields[2].GetUInt32()); // petnumber data << uint32(fields[3].GetUInt32()); // creature entry data << uint32(fields[4].GetUInt32()); // level data << fields[6].GetString(); // name data << uint32(fields[5].GetUInt32()); // loyalty data << uint8(fields[1].GetUInt32()+1); // slot ++num; }while (result->NextRow()); } data.put<uint8>(8, num); // set real data to placeholder SendPacket(&data); } void WorldSession::HandleStablePet(WorldPacket & recv_data) { sLog->outDebug("WORLD: Recv CMSG_STABLE_PET"); uint64 npcGUID; recv_data >> npcGUID; if (!GetPlayer()->isAlive()) return; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_STABLEMASTER); if (!unit) { sLog->outDebug("WORLD: HandleStablePet - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); Pet *pet = _player->GetPet(); WorldPacket data(SMSG_STABLE_RESULT, 200); // guess size // can't place in stable dead pet if (!pet||!pet->isAlive()||pet->getPetType() != HUNTER_PET) { data << uint8(0x06); SendPacket(&data); return; } uint32 free_slot = 1; QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT owner, slot, id FROM character_pet WHERE owner = '%u' AND slot > 0 AND slot < 3 ORDER BY slot ", _player->GetGUIDLow()); if (result) { do { Field *fields = result->Fetch(); uint32 slot = fields[1].GetUInt32(); if (slot == free_slot) // this slot not free ++free_slot; }while (result->NextRow()); } if (free_slot > 0 && free_slot <= GetPlayer()->m_stableSlots) { _player->RemovePet(pet, PetSaveMode(free_slot)); data << uint8(0x08); } else data << uint8(0x06); SendPacket(&data); } void WorldSession::HandleUnstablePet(WorldPacket & recv_data) { sLog->outDebug("WORLD: Recv CMSG_UNSTABLE_PET."); uint64 npcGUID; uint32 petnumber; recv_data >> npcGUID >> petnumber; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_STABLEMASTER); if (!unit) { sLog->outDebug("WORLD: HandleUnstablePet - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); WorldPacket data(SMSG_STABLE_RESULT, 200); // guess size Pet* pet = _player->GetPet(); if (pet && pet->isAlive()) { uint8 i = 0x06; data << uint8(i); SendPacket(&data); return; } // delete dead pet if (pet) _player->RemovePet(pet, PET_SAVE_AS_DELETED); Pet *newpet = NULL; QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT entry FROM character_pet WHERE owner = '%u' AND id = '%u' AND slot > 0 AND slot < 3", _player->GetGUIDLow(), petnumber); if (result) { Field *fields = result->Fetch(); uint32 petentry = fields[0].GetUInt32(); newpet = new Pet(_player, HUNTER_PET); if (!newpet->LoadPetFromDB(_player, petentry, petnumber)) { delete newpet; newpet = NULL; } } if (newpet) data << uint8(0x09); else data << uint8(0x06); SendPacket(&data); } void WorldSession::HandleBuyStableSlot(WorldPacket & recv_data) { sLog->outDebug("WORLD: Recv CMSG_BUY_STABLE_SLOT."); uint64 npcGUID; recv_data >> npcGUID; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_STABLEMASTER); if (!unit) { sLog->outDebug("WORLD: HandleBuyStableSlot - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); WorldPacket data(SMSG_STABLE_RESULT, 200); if (GetPlayer()->m_stableSlots < 2) // max slots amount = 2 { StableSlotPricesEntry const *SlotPrice = sStableSlotPricesStore.LookupEntry(GetPlayer()->m_stableSlots+1); if (_player->GetMoney() >= SlotPrice->Price) { ++GetPlayer()->m_stableSlots; _player->ModifyMoney(-int32(SlotPrice->Price)); data << uint8(0x0A); // success buy } else data << uint8(0x06); } else data << uint8(0x06); SendPacket(&data); } void WorldSession::HandleStableRevivePet(WorldPacket &/* recv_data */) { sLog->outDebug("HandleStableRevivePet: Not implemented"); } void WorldSession::HandleStableSwapPet(WorldPacket & recv_data) { sLog->outDebug("WORLD: Recv CMSG_STABLE_SWAP_PET."); uint64 npcGUID; uint32 pet_number; recv_data >> npcGUID >> pet_number; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_STABLEMASTER); if (!unit) { sLog->outDebug("WORLD: HandleStableSwapPet - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); WorldPacket data(SMSG_STABLE_RESULT, 200); // guess size Pet* pet = _player->GetPet(); if (!pet || pet->getPetType() != HUNTER_PET) return; // find swapped pet slot in stable QueryResult_AutoPtr result = CharacterDatabase.PQuery("SELECT slot, entry FROM character_pet WHERE owner = '%u' AND id = '%u'", _player->GetGUIDLow(), pet_number); if (!result) return; Field *fields = result->Fetch(); uint32 slot = fields[0].GetUInt32(); uint32 petentry = fields[1].GetUInt32(); // move alive pet to slot or delele dead pet _player->RemovePet(pet, pet->isAlive() ? PetSaveMode(slot) : PET_SAVE_AS_DELETED); // summon unstabled pet Pet *newpet = new Pet(_player); if (!newpet->LoadPetFromDB(_player, petentry, pet_number)) { delete newpet; data << uint8(0x06); } else data << uint8(0x09); SendPacket(&data); } void WorldSession::HandleRepairItemOpcode(WorldPacket & recv_data) { sLog->outDebug("WORLD: CMSG_REPAIR_ITEM"); uint64 npcGUID, itemGUID; uint8 guildBank; // new in 2.3.2, bool that means from guild bank money recv_data >> npcGUID >> itemGUID >> guildBank; Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(npcGUID, UNIT_NPC_FLAG_REPAIR); if (!unit) { sLog->outDebug("WORLD: HandleRepairItemOpcode - Unit (GUID: %u) not found or you can not interact with him.", uint32(GUID_LOPART(npcGUID))); return; } // remove fake death if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); // reputation discount float discountMod = _player->GetReputationPriceDiscount(unit); uint32 TotalCost = 0; if (itemGUID) { sLog->outDebug("ITEM: Repair item, itemGUID = %u, npcGUID = %u", GUID_LOPART(itemGUID), GUID_LOPART(npcGUID)); Item* item = _player->GetItemByGuid(itemGUID); if (item) TotalCost= _player->DurabilityRepair(item->GetPos(), true, discountMod, guildBank>0?true:false); } else { sLog->outDebug("ITEM: Repair all items, npcGUID = %u", GUID_LOPART(npcGUID)); TotalCost = _player->DurabilityRepairAll(true, discountMod, guildBank>0?true:false); } if (guildBank) { uint32 GuildId = _player->GetGuildId(); if (!GuildId) return; Guild *pGuild = sObjectMgr->GetGuildById(GuildId); if (!pGuild) return; pGuild->LogBankEvent(GUILD_BANK_LOG_REPAIR_MONEY, 0, _player->GetGUIDLow(), TotalCost); pGuild->SendMoneyInfo(this, _player->GetGUIDLow()); } }
Bootz/SF1
src/server/game/Server/Protocol/Handlers/NPCHandler.cpp
C++
gpl-2.0
24,991
package edu.neu.leetcode.array; public class BestTimeToBuyAndSellStockII { public static int maxProfit(int[] prices) { int res = 0, high = prices.length - 1; for (int i = prices.length - 1; i > 0; i--) { if (prices[i - 1] < prices[i]) { if (i - 1 == 0) { res += prices[high] - prices[i - 1]; break; } else { continue; } } if (high > i) { res += prices[high] - prices[i]; } high = i - 1; } return res; } }
mahaotian/LeetCode
src/edu/neu/leetcode/array/BestTimeToBuyAndSellStockII.java
Java
gpl-2.0
630
<?php /** * Tạo 1 section mới trong Customizer */ function customizer_header($wp_customize) { // Tao section $wp_customize->add_section( 'section_header', array( 'title' => 'Header - Phần trên', 'description' => 'Tùy chỉnh Header (Phần trên cùng trang): menu, hotline', 'priority' => 24 ) ); // menu font, size, color $wp_customize->add_setting( AIO_HEADER_MENU_FONT, array( 'default' => get_theme_mod(AIO_HEADER_MENU_FONT, 'Georgia'), 'transport' => 'postMessage' ) ); $wp_customize->add_control( AIO_HEADER_MENU_FONT, array( 'label' => 'Menu chính - Font chữ', 'section' => 'section_header', 'type' => 'select', 'choices' => json_decode(AIO_GENERAL_FONTS), 'settings' => AIO_HEADER_MENU_FONT ) ); $wp_customize->add_setting( AIO_HEADER_MENU_FONT_SIZE, array( 'default' => get_theme_mod(AIO_HEADER_MENU_FONT_SIZE, 20), 'transport' => 'postMessage' ) ); $temp = array('14px', '16px', '18px', '20px', '22px', '24px', '26px', '28px'); $temp = array_combine($temp, $temp); $wp_customize->add_control( AIO_HEADER_MENU_FONT_SIZE, array( 'label' => 'Menu chính - Cỡ chữ', 'section' => 'section_header', 'type' => 'select', 'choices' => $temp, 'settings' => AIO_HEADER_MENU_FONT_SIZE ) ); $wp_customize->add_setting( AIO_HEADER_MENU_FONT_COLOR, array( 'default' => get_theme_mod(AIO_HEADER_MENU_FONT_COLOR, 'orange'), 'transport' => 'postMessage' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, AIO_HEADER_MENU_FONT_COLOR, array( 'label' => 'Menu chính - Màu chữ', 'section' => 'section_header', 'settings' => AIO_HEADER_MENU_FONT_COLOR, ) ) ); $wp_customize->add_setting( AIO_HEADER_MENU_HOVER_FONT_COLOR, array( 'default' => get_theme_mod(AIO_HEADER_MENU_HOVER_FONT_COLOR, 'orange'), 'transport' => 'postMessage' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, AIO_HEADER_MENU_HOVER_FONT_COLOR, array( 'label' => 'Menu chính - Màu chữ khi hover/active', 'section' => 'section_header', 'settings' => AIO_HEADER_MENU_HOVER_FONT_COLOR, ) ) ); // hotline font, size, color $wp_customize->add_setting( AIO_HEADER_HOTLINE_FONT, array( 'default' => get_theme_mod(AIO_HEADER_HOTLINE_FONT, 'Georgia'), 'transport' => 'postMessage' ) ); $wp_customize->add_control( AIO_HEADER_HOTLINE_FONT, array( 'label' => 'Hotline - Font chữ', 'section' => 'section_header', 'type' => 'select', 'choices' => json_decode(AIO_GENERAL_FONTS), 'settings' => AIO_HEADER_HOTLINE_FONT ) ); $wp_customize->add_setting( AIO_HEADER_HOTLINE_FONT_SIZE, array( 'default' => get_theme_mod(AIO_HEADER_HOTLINE_FONT_SIZE, 20), 'transport' => 'postMessage' ) ); $temp = array('14px', '16px', '18px', '20px', '22px', '24px', '26px', '28px'); $temp = array_combine($temp, $temp); $wp_customize->add_control( AIO_HEADER_HOTLINE_FONT_SIZE, array( 'label' => 'Hotline - Cỡ chữ', 'section' => 'section_header', 'type' => 'select', 'choices' => $temp, 'settings' => AIO_HEADER_HOTLINE_FONT_SIZE ) ); $wp_customize->add_setting( AIO_HEADER_HOTLINE_FONT_COLOR, array( 'default' => get_theme_mod(AIO_HEADER_HOTLINE_FONT_COLOR, 'orange'), 'transport' => 'postMessage' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, AIO_HEADER_HOTLINE_FONT_COLOR, array( 'label' => 'Hotline - Màu chữ', 'section' => 'section_header', 'settings' => AIO_HEADER_HOTLINE_FONT_COLOR, ) ) ); } add_action('customize_register', 'customizer_header');
ptsondev/stdcib
wp-content/themes/faceshop/customize/header.php
PHP
gpl-2.0
4,529
using ProjectManager.Entity; using ProjectManager.Entity.Identity; namespace ProjectManager.Common.DAL.Repositories { public interface IUserRepository : IGenericRepository<ApplicationUser> { } }
nktlitvinenko/STP-Laba-PM
ProjectManager.Common/DAL/Repositories/IUserRepository.cs
C#
gpl-2.0
203
from functions.str import w_str from wtypes.control import WEvalRequired, WRaisedException, WReturnValue from wtypes.exception import WException from wtypes.magic_macro import WMagicMacro from wtypes.boolean import WBoolean class WAssert(WMagicMacro): def call_magic_macro(self, exprs, scope): if len(exprs) != 1: raise Exception( "Macro assert expected 1 argument. " "Got {} instead.".format(len(exprs))) expr = exprs[0] src = w_str(expr) def callback(_value): if _value is WBoolean.false: return WRaisedException( exception=WException(f'Assertion failed: {src}')) return WReturnValue(expr=_value) return WEvalRequired(expr=expr, callback=callback)
izrik/wodehouse
macros/assert_.py
Python
gpl-2.0
802
/* * Copyright (C) 2008-2019 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/>. */ /* ScriptData Name: npc_commandscript %Complete: 100 Comment: All npc related commands Category: commandscripts EndScriptData */ #include "ScriptMgr.h" #include "Chat.h" #include "CreatureAI.h" #include "CreatureGroups.h" #include "DatabaseEnv.h" #include "FollowMovementGenerator.h" #include "GameTime.h" #include "Language.h" #include "Log.h" #include "Map.h" #include "MotionMaster.h" #include "MovementDefines.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Pet.h" #include "Player.h" #include "RBAC.h" #include "Transport.h" #include "World.h" #include "WorldSession.h" #include <boost/core/demangle.hpp> #include <typeinfo> bool HandleNpcSpawnGroup(ChatHandler* handler, char const* args) { if (!*args) return false; bool ignoreRespawn = false; bool force = false; uint32 groupId = 0; // Decode arguments char* arg = strtok((char*)args, " "); while (arg) { std::string thisArg = arg; std::transform(thisArg.begin(), thisArg.end(), thisArg.begin(), ::tolower); if (thisArg == "ignorerespawn") ignoreRespawn = true; else if (thisArg == "force") force = true; else if (thisArg.empty() || !(std::count_if(thisArg.begin(), thisArg.end(), ::isdigit) == (int)thisArg.size())) return false; else groupId = atoi(thisArg.c_str()); arg = strtok(nullptr, " "); } Player* player = handler->GetSession()->GetPlayer(); std::vector <WorldObject*> creatureList; if (!player->GetMap()->SpawnGroupSpawn(groupId, ignoreRespawn, force, &creatureList)) { handler->PSendSysMessage(LANG_SPAWNGROUP_BADGROUP, groupId); handler->SetSentErrorMessage(true); return false; } handler->PSendSysMessage(LANG_SPAWNGROUP_SPAWNCOUNT, creatureList.size()); return true; } bool HandleNpcDespawnGroup(ChatHandler* handler, char const* args) { if (!*args) return false; bool deleteRespawnTimes = false; uint32 groupId = 0; // Decode arguments char* arg = strtok((char*)args, " "); while (arg) { std::string thisArg = arg; std::transform(thisArg.begin(), thisArg.end(), thisArg.begin(), ::tolower); if (thisArg == "removerespawntime") deleteRespawnTimes = true; else if (thisArg.empty() || !(std::count_if(thisArg.begin(), thisArg.end(), ::isdigit) == (int)thisArg.size())) return false; else groupId = atoi(thisArg.c_str()); arg = strtok(nullptr, " "); } Player* player = handler->GetSession()->GetPlayer(); size_t n = 0; if (!player->GetMap()->SpawnGroupDespawn(groupId, deleteRespawnTimes, &n)) { handler->PSendSysMessage(LANG_SPAWNGROUP_BADGROUP, groupId); handler->SetSentErrorMessage(true); return false; } handler->PSendSysMessage("Despawned a total of %zu objects.", n); return true; } class npc_commandscript : public CommandScript { public: npc_commandscript() : CommandScript("npc_commandscript") { } std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> npcAddCommandTable = { { "formation", rbac::RBAC_PERM_COMMAND_NPC_ADD_FORMATION, false, &HandleNpcAddFormationCommand, "" }, { "item", rbac::RBAC_PERM_COMMAND_NPC_ADD_ITEM, false, &HandleNpcAddVendorItemCommand, "" }, { "move", rbac::RBAC_PERM_COMMAND_NPC_ADD_MOVE, false, &HandleNpcAddMoveCommand, "" }, { "temp", rbac::RBAC_PERM_COMMAND_NPC_ADD_TEMP, false, &HandleNpcAddTempSpawnCommand, "" }, //{ "weapon", rbac::RBAC_PERM_COMMAND_NPC_ADD_WEAPON, false, &HandleNpcAddWeaponCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, &HandleNpcAddCommand, "" }, }; static std::vector<ChatCommand> npcDeleteCommandTable = { { "item", rbac::RBAC_PERM_COMMAND_NPC_DELETE_ITEM, false, &HandleNpcDeleteVendorItemCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, &HandleNpcDeleteCommand, "" }, }; static std::vector<ChatCommand> npcFollowCommandTable = { { "stop", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW_STOP, false, &HandleNpcUnFollowCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, &HandleNpcFollowCommand, "" }, }; static std::vector<ChatCommand> npcSetCommandTable = { { "allowmove", rbac::RBAC_PERM_COMMAND_NPC_SET_ALLOWMOVE, false, &HandleNpcSetAllowMovementCommand, "" }, { "entry", rbac::RBAC_PERM_COMMAND_NPC_SET_ENTRY, false, &HandleNpcSetEntryCommand, "" }, { "factionid", rbac::RBAC_PERM_COMMAND_NPC_SET_FACTIONID, false, &HandleNpcSetFactionIdCommand, "" }, { "flag", rbac::RBAC_PERM_COMMAND_NPC_SET_FLAG, false, &HandleNpcSetFlagCommand, "" }, { "level", rbac::RBAC_PERM_COMMAND_NPC_SET_LEVEL, false, &HandleNpcSetLevelCommand, "" }, { "link", rbac::RBAC_PERM_COMMAND_NPC_SET_LINK, false, &HandleNpcSetLinkCommand, "" }, { "model", rbac::RBAC_PERM_COMMAND_NPC_SET_MODEL, false, &HandleNpcSetModelCommand, "" }, { "movetype", rbac::RBAC_PERM_COMMAND_NPC_SET_MOVETYPE, false, &HandleNpcSetMoveTypeCommand, "" }, { "phase", rbac::RBAC_PERM_COMMAND_NPC_SET_PHASE, false, &HandleNpcSetPhaseCommand, "" }, { "spawndist", rbac::RBAC_PERM_COMMAND_NPC_SET_SPAWNDIST, false, &HandleNpcSetSpawnDistCommand, "" }, { "spawntime", rbac::RBAC_PERM_COMMAND_NPC_SET_SPAWNTIME, false, &HandleNpcSetSpawnTimeCommand, "" }, { "data", rbac::RBAC_PERM_COMMAND_NPC_SET_DATA, false, &HandleNpcSetDataCommand, "" }, }; static std::vector<ChatCommand> npcCommandTable = { { "info", rbac::RBAC_PERM_COMMAND_NPC_INFO, false, &HandleNpcInfoCommand, "" }, { "near", rbac::RBAC_PERM_COMMAND_NPC_NEAR, false, &HandleNpcNearCommand, "" }, { "move", rbac::RBAC_PERM_COMMAND_NPC_MOVE, false, &HandleNpcMoveCommand, "" }, { "playemote", rbac::RBAC_PERM_COMMAND_NPC_PLAYEMOTE, false, &HandleNpcPlayEmoteCommand, "" }, { "say", rbac::RBAC_PERM_COMMAND_NPC_SAY, false, &HandleNpcSayCommand, "" }, { "textemote", rbac::RBAC_PERM_COMMAND_NPC_TEXTEMOTE, false, &HandleNpcTextEmoteCommand, "" }, { "whisper", rbac::RBAC_PERM_COMMAND_NPC_WHISPER, false, &HandleNpcWhisperCommand, "" }, { "yell", rbac::RBAC_PERM_COMMAND_NPC_YELL, false, &HandleNpcYellCommand, "" }, { "tame", rbac::RBAC_PERM_COMMAND_NPC_TAME, false, &HandleNpcTameCommand, "" }, { "spawngroup", rbac::RBAC_PERM_COMMAND_NPC_SPAWNGROUP, false, &HandleNpcSpawnGroup, "" }, { "despawngroup", rbac::RBAC_PERM_COMMAND_NPC_DESPAWNGROUP, false, &HandleNpcDespawnGroup, "" }, { "add", rbac::RBAC_PERM_COMMAND_NPC_ADD, false, nullptr, "", npcAddCommandTable }, { "delete", rbac::RBAC_PERM_COMMAND_NPC_DELETE, false, nullptr, "", npcDeleteCommandTable }, { "follow", rbac::RBAC_PERM_COMMAND_NPC_FOLLOW, false, nullptr, "", npcFollowCommandTable }, { "set", rbac::RBAC_PERM_COMMAND_NPC_SET, false, nullptr, "", npcSetCommandTable }, { "evade", rbac::RBAC_PERM_COMMAND_NPC_EVADE, false, &HandleNpcEvadeCommand, "" }, { "showloot", rbac::RBAC_PERM_COMMAND_NPC_SHOWLOOT, false, &HandleNpcShowLootCommand, "" }, }; static std::vector<ChatCommand> commandTable = { { "npc", rbac::RBAC_PERM_COMMAND_NPC, false, nullptr, "", npcCommandTable }, }; return commandTable; } //add spawn of creature static bool HandleNpcAddCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* charID = handler->extractKeyFromLink((char*)args, "Hcreature_entry"); if (!charID) return false; uint32 id = atoul(charID); if (!sObjectMgr->GetCreatureTemplate(id)) return false; Player* chr = handler->GetSession()->GetPlayer(); Map* map = chr->GetMap(); if (Transport* trans = chr->GetTransport()) { ObjectGuid::LowType guid = map->GenerateLowGuid<HighGuid::Unit>(); CreatureData& data = sObjectMgr->NewOrExistCreatureData(guid); data.spawnId = guid; data.id = id; data.phaseMask = chr->GetPhaseMaskForSpawn(); data.spawnPoint.Relocate(chr->GetTransOffsetX(), chr->GetTransOffsetY(), chr->GetTransOffsetZ(), chr->GetTransOffsetO()); if (Creature* creature = trans->CreateNPCPassenger(guid, &data)) { creature->SaveToDB(trans->GetGOInfo()->moTransport.mapID, 1 << map->GetSpawnMode(), chr->GetPhaseMaskForSpawn()); sObjectMgr->AddCreatureToGrid(guid, &data); } return true; } Creature* creature = new Creature(); if (!creature->Create(map->GenerateLowGuid<HighGuid::Unit>(), map, chr->GetPhaseMaskForSpawn(), id, *chr)) { delete creature; return false; } creature->SaveToDB(map->GetId(), (1 << map->GetSpawnMode()), chr->GetPhaseMaskForSpawn()); ObjectGuid::LowType db_guid = creature->GetSpawnId(); // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells() // current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior creature->CleanupsBeforeDelete(); delete creature; creature = new Creature(); if (!creature->LoadFromDB(db_guid, map, true, true)) { delete creature; return false; } sObjectMgr->AddCreatureToGrid(db_guid, sObjectMgr->GetCreatureData(db_guid)); return true; } //add item in vendorlist static bool HandleNpcAddVendorItemCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* pitem = handler->extractKeyFromLink((char*)args, "Hitem"); if (!pitem) { handler->SendSysMessage(LANG_COMMAND_NEEDITEMSEND); handler->SetSentErrorMessage(true); return false; } int32 item_int = atol(pitem); if (item_int <= 0) return false; uint32 itemId = item_int; char* fmaxcount = strtok(nullptr, " "); //add maxcount, default: 0 uint32 maxcount = 0; if (fmaxcount) maxcount = atoul(fmaxcount); char* fincrtime = strtok(nullptr, " "); //add incrtime, default: 0 uint32 incrtime = 0; if (fincrtime) incrtime = atoul(fincrtime); char* fextendedcost = strtok(nullptr, " "); //add ExtendedCost, default: 0 uint32 extendedcost = fextendedcost ? atoul(fextendedcost) : 0; Creature* vendor = handler->getSelectedCreature(); if (!vendor) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } uint32 vendor_entry = vendor->GetEntry(); if (!sObjectMgr->IsVendorItemValid(vendor_entry, itemId, maxcount, incrtime, extendedcost, handler->GetSession()->GetPlayer())) { handler->SetSentErrorMessage(true); return false; } sObjectMgr->AddVendorItem(vendor_entry, itemId, maxcount, incrtime, extendedcost); ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId); handler->PSendSysMessage(LANG_ITEM_ADDED_TO_LIST, itemId, itemTemplate->Name1.c_str(), maxcount, incrtime, extendedcost); return true; } //add move for creature static bool HandleNpcAddMoveCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* guidStr = strtok((char*)args, " "); char* waitStr = strtok((char*)nullptr, " "); ObjectGuid::LowType lowGuid = atoul(guidStr); // attempt check creature existence by DB data CreatureData const* data = sObjectMgr->GetCreatureData(lowGuid); if (!data) { handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowGuid); handler->SetSentErrorMessage(true); return false; } int wait = waitStr ? atoi(waitStr) : 0; if (wait < 0) wait = 0; // Update movement type PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE); stmt->setUInt8(0, uint8(WAYPOINT_MOTION_TYPE)); stmt->setUInt32(1, lowGuid); WorldDatabase.Execute(stmt); handler->SendSysMessage(LANG_WAYPOINT_ADDED); return true; } static bool HandleNpcSetAllowMovementCommand(ChatHandler* handler, char const* /*args*/) { if (sWorld->getAllowMovement()) { sWorld->SetAllowMovement(false); handler->SendSysMessage(LANG_CREATURE_MOVE_DISABLED); } else { sWorld->SetAllowMovement(true); handler->SendSysMessage(LANG_CREATURE_MOVE_ENABLED); } return true; } static bool HandleNpcSetEntryCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint32 newEntryNum = atoul(args); if (!newEntryNum) return false; Unit* unit = handler->getSelectedUnit(); if (!unit || unit->GetTypeId() != TYPEID_UNIT) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } Creature* creature = unit->ToCreature(); if (creature->UpdateEntry(newEntryNum)) handler->SendSysMessage(LANG_DONE); else handler->SendSysMessage(LANG_ERROR); return true; } //change level of creature or pet static bool HandleNpcSetLevelCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint8 lvl = (uint8) atoi(args); if (lvl < 1 || lvl > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL) + 3) { handler->SendSysMessage(LANG_BAD_VALUE); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); if (!creature || creature->IsPet()) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->SetMaxHealth(100 + 30*lvl); creature->SetHealth(100 + 30*lvl); creature->SetLevel(lvl); creature->SaveToDB(); return true; } static bool HandleNpcDeleteCommand(ChatHandler* handler, char const* args) { Creature* creature = nullptr; if (*args) { // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r char* cId = handler->extractKeyFromLink((char*)args, "Hcreature"); if (!cId) return false; ObjectGuid::LowType lowguid = atoul(cId); if (!lowguid) return false; // force respawn to make sure we find something handler->GetSession()->GetPlayer()->GetMap()->ForceRespawn(SPAWN_TYPE_CREATURE, lowguid); // then try to find it creature = handler->GetCreatureFromPlayerMapByDbGuid(lowguid); } else creature = handler->getSelectedCreature(); if (!creature || creature->IsPet() || creature->IsTotem()) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } if (TempSummon* summon = creature->ToTempSummon()) summon->UnSummon(); else { // Delete the creature creature->CombatStop(); creature->DeleteFromDB(); creature->AddObjectToRemoveList(); } handler->SendSysMessage(LANG_COMMAND_DELCREATMESSAGE); return true; } //del item from vendor list static bool HandleNpcDeleteVendorItemCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Creature* vendor = handler->getSelectedCreature(); if (!vendor || !vendor->IsVendor()) { handler->SendSysMessage(LANG_COMMAND_VENDORSELECTION); handler->SetSentErrorMessage(true); return false; } char* pitem = handler->extractKeyFromLink((char*)args, "Hitem"); if (!pitem) { handler->SendSysMessage(LANG_COMMAND_NEEDITEMSEND); handler->SetSentErrorMessage(true); return false; } uint32 itemId = atoul(pitem); if (!sObjectMgr->RemoveVendorItem(vendor->GetEntry(), itemId)) { handler->PSendSysMessage(LANG_ITEM_NOT_IN_LIST, itemId); handler->SetSentErrorMessage(true); return false; } ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId); handler->PSendSysMessage(LANG_ITEM_DELETED_FROM_LIST, itemId, itemTemplate->Name1.c_str()); return true; } //set faction of creature static bool HandleNpcSetFactionIdCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint32 factionId = atoul(args); if (!sFactionTemplateStore.LookupEntry(factionId)) { handler->PSendSysMessage(LANG_WRONG_FACTION, factionId); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->SetFaction(factionId); // Faction is set in creature_template - not inside creature // Update in memory.. if (CreatureTemplate const* cinfo = creature->GetCreatureTemplate()) const_cast<CreatureTemplate*>(cinfo)->faction = factionId; // ..and DB PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_FACTION); stmt->setUInt16(0, uint16(factionId)); stmt->setUInt32(1, creature->GetEntry()); WorldDatabase.Execute(stmt); return true; } //set npcflag of creature static bool HandleNpcSetFlagCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint32 npcFlags = (uint32) atoi(args); Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->SetUInt32Value(UNIT_NPC_FLAGS, npcFlags); PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_NPCFLAG); stmt->setUInt32(0, npcFlags); stmt->setUInt32(1, creature->GetEntry()); WorldDatabase.Execute(stmt); handler->SendSysMessage(LANG_VALUE_SAVED_REJOIN); return true; } //set data of creature for testing scripting static bool HandleNpcSetDataCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* arg1 = strtok((char*)args, " "); char* arg2 = strtok((char*)nullptr, ""); if (!arg1 || !arg2) return false; uint32 data_1 = (uint32)atoi(arg1); uint32 data_2 = (uint32)atoi(arg2); if (!data_1 || !data_2) return false; Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->AI()->SetData(data_1, data_2); std::string AIorScript = !creature->GetAIName().empty() ? "AI type: " + creature->GetAIName() : (!creature->GetScriptName().empty() ? "Script Name: " + creature->GetScriptName() : "No AI or Script Name Set"); handler->PSendSysMessage(LANG_NPC_SETDATA, creature->GetGUID().GetCounter(), creature->GetEntry(), creature->GetName().c_str(), data_1, data_2, AIorScript.c_str()); return true; } //npc follow handling static bool HandleNpcFollowCommand(ChatHandler* handler, char const* /*args*/) { Player* player = handler->GetSession()->GetPlayer(); Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->PSendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } // Follow player - Using pet's default dist and angle creature->GetMotionMaster()->MoveFollow(player, PET_FOLLOW_DIST, creature->GetFollowAngle()); handler->PSendSysMessage(LANG_CREATURE_FOLLOW_YOU_NOW, creature->GetName().c_str()); return true; } static bool HandleNpcInfoCommand(ChatHandler* handler, char const* /*args*/) { Creature* target = handler->getSelectedCreature(); if (!target) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } CreatureTemplate const* cInfo = target->GetCreatureTemplate(); uint32 faction = target->GetFaction(); uint32 npcflags = target->GetUInt32Value(UNIT_NPC_FLAGS); uint32 mechanicImmuneMask = cInfo->MechanicImmuneMask; uint32 displayid = target->GetDisplayId(); uint32 nativeid = target->GetNativeDisplayId(); uint32 entry = target->GetEntry(); int64 curRespawnDelay = target->GetRespawnCompatibilityMode() ? target->GetRespawnTimeEx() - GameTime::GetGameTime() : target->GetMap()->GetCreatureRespawnTime(target->GetSpawnId()) - GameTime::GetGameTime(); if (curRespawnDelay < 0) curRespawnDelay = 0; std::string curRespawnDelayStr = secsToTimeString(uint64(curRespawnDelay), true); std::string defRespawnDelayStr = secsToTimeString(target->GetRespawnDelay(), true); handler->PSendSysMessage(LANG_NPCINFO_CHAR, target->GetName().c_str(), target->GetSpawnId(), target->GetGUID().GetCounter(), entry, faction, npcflags, displayid, nativeid); if (target->GetCreatureData() && target->GetCreatureData()->spawnGroupData->groupId) { SpawnGroupTemplateData const* const groupData = target->GetCreatureData()->spawnGroupData; handler->PSendSysMessage(LANG_SPAWNINFO_GROUP_ID, groupData->name.c_str(), groupData->groupId, groupData->flags, target->GetMap()->IsSpawnGroupActive(groupData->groupId)); } handler->PSendSysMessage(LANG_SPAWNINFO_COMPATIBILITY_MODE, target->GetRespawnCompatibilityMode()); handler->PSendSysMessage(LANG_NPCINFO_LEVEL, target->getLevel()); handler->PSendSysMessage(LANG_NPCINFO_EQUIPMENT, target->GetCurrentEquipmentId(), target->GetOriginalEquipmentId()); handler->PSendSysMessage(LANG_NPCINFO_HEALTH, target->GetCreateHealth(), target->GetMaxHealth(), target->GetHealth()); handler->PSendSysMessage(LANG_NPCINFO_MOVEMENT_DATA, target->GetMovementTemplate().ToString().c_str()); handler->PSendSysMessage(LANG_NPCINFO_UNIT_FIELD_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS)); for (UnitFlags flag : EnumUtils::Iterate<UnitFlags>()) if (target->GetUInt32Value(UNIT_FIELD_FLAGS) & flag) handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag); handler->PSendSysMessage(LANG_NPCINFO_FLAGS, target->GetUInt32Value(UNIT_FIELD_FLAGS_2), target->GetUInt32Value(UNIT_DYNAMIC_FLAGS), target->GetFaction()); handler->PSendSysMessage(LANG_COMMAND_RAWPAWNTIMES, defRespawnDelayStr.c_str(), curRespawnDelayStr.c_str()); handler->PSendSysMessage(LANG_NPCINFO_LOOT, cInfo->lootid, cInfo->pickpocketLootId, cInfo->SkinLootId); handler->PSendSysMessage(LANG_NPCINFO_DUNGEON_ID, target->GetInstanceId()); handler->PSendSysMessage(LANG_NPCINFO_PHASEMASK, target->GetPhaseMask()); handler->PSendSysMessage(LANG_NPCINFO_ARMOR, target->GetArmor()); handler->PSendSysMessage(LANG_NPCINFO_POSITION, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ()); handler->PSendSysMessage(LANG_OBJECTINFO_AIINFO, target->GetAIName().c_str(), target->GetScriptName().c_str()); handler->PSendSysMessage(LANG_NPCINFO_REACTSTATE, DescribeReactState(target->GetReactState())); if (CreatureAI const* ai = target->AI()) handler->PSendSysMessage(LANG_OBJECTINFO_AITYPE, boost::core::demangle(typeid(*ai).name()).c_str()); handler->PSendSysMessage(LANG_NPCINFO_FLAGS_EXTRA, cInfo->flags_extra); for (CreatureFlagsExtra flag : EnumUtils::Iterate<CreatureFlagsExtra>()) if (cInfo->flags_extra & flag) handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag); for (NPCFlags flag : EnumUtils::Iterate<NPCFlags>()) if (npcflags & flag) handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(flag), flag); handler->PSendSysMessage(LANG_NPCINFO_MECHANIC_IMMUNE, mechanicImmuneMask); for (Mechanics m : EnumUtils::Iterate<Mechanics>()) if (m && (mechanicImmuneMask & (1 << (m-1)))) handler->PSendSysMessage("* %s (0x%X)", EnumUtils::ToTitle(m), m); return true; } static bool HandleNpcNearCommand(ChatHandler* handler, char const* args) { float distance = (!*args) ? 10.0f : float((atof(args))); uint32 count = 0; Player* player = handler->GetSession()->GetPlayer(); PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_NEAREST); stmt->setFloat(0, player->GetPositionX()); stmt->setFloat(1, player->GetPositionY()); stmt->setFloat(2, player->GetPositionZ()); stmt->setUInt32(3, player->GetMapId()); stmt->setFloat(4, player->GetPositionX()); stmt->setFloat(5, player->GetPositionY()); stmt->setFloat(6, player->GetPositionZ()); stmt->setFloat(7, distance * distance); PreparedQueryResult result = WorldDatabase.Query(stmt); if (result) { do { Field* fields = result->Fetch(); ObjectGuid::LowType guid = fields[0].GetUInt32(); uint32 entry = fields[1].GetUInt32(); float x = fields[2].GetFloat(); float y = fields[3].GetFloat(); float z = fields[4].GetFloat(); uint16 mapId = fields[5].GetUInt16(); CreatureTemplate const* creatureTemplate = sObjectMgr->GetCreatureTemplate(entry); if (!creatureTemplate) continue; handler->PSendSysMessage(LANG_CREATURE_LIST_CHAT, guid, guid, creatureTemplate->Name.c_str(), x, y, z, mapId, "", ""); ++count; } while (result->NextRow()); } handler->PSendSysMessage(LANG_COMMAND_NEAR_NPC_MESSAGE, distance, count); return true; } //move selected creature static bool HandleNpcMoveCommand(ChatHandler* handler, char const* args) { ObjectGuid::LowType lowguid = 0; Creature* creature = handler->getSelectedCreature(); Player const* player = handler->GetSession()->GetPlayer(); if (!player) return false; if (creature) lowguid = creature->GetSpawnId(); else { // number or [name] Shift-click form |color|Hcreature:creature_guid|h[name]|h|r char* cId = handler->extractKeyFromLink((char*)args, "Hcreature"); if (!cId) return false; lowguid = atoul(cId); } // Attempting creature load from DB data CreatureData const* data = sObjectMgr->GetCreatureData(lowguid); if (!data) { handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid); handler->SetSentErrorMessage(true); return false; } if (player->GetMapId() != data->spawnPoint.GetMapId()) { handler->PSendSysMessage(LANG_COMMAND_CREATUREATSAMEMAP, lowguid); handler->SetSentErrorMessage(true); return false; } // update position in memory sObjectMgr->RemoveCreatureFromGrid(lowguid, data); const_cast<CreatureData*>(data)->spawnPoint.Relocate(*player); sObjectMgr->AddCreatureToGrid(lowguid, data); // update position in DB PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_POSITION); stmt->setFloat(0, player->GetPositionX()); stmt->setFloat(1, player->GetPositionY()); stmt->setFloat(2, player->GetPositionZ()); stmt->setFloat(3, player->GetOrientation()); stmt->setUInt32(4, lowguid); WorldDatabase.Execute(stmt); // respawn selected creature at the new location if (creature) { if (creature->IsAlive()) creature->setDeathState(JUST_DIED); creature->Respawn(true); if (!creature->GetRespawnCompatibilityMode()) creature->AddObjectToRemoveList(); } handler->PSendSysMessage(LANG_COMMAND_CREATUREMOVED); return true; } //play npc emote static bool HandleNpcPlayEmoteCommand(ChatHandler* handler, char const* args) { uint32 emote = atoi((char*)args); Creature* target = handler->getSelectedCreature(); if (!target) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } target->SetUInt32Value(UNIT_NPC_EMOTESTATE, emote); return true; } //set model of creature static bool HandleNpcSetModelCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint32 displayId = atoul(args); Creature* creature = handler->getSelectedCreature(); if (!creature || creature->IsPet()) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } if (!sCreatureDisplayInfoStore.LookupEntry(displayId)) { handler->PSendSysMessage(LANG_COMMAND_INVALID_PARAM, args); handler->SetSentErrorMessage(true); return false; } creature->SetDisplayId(displayId); creature->SetNativeDisplayId(displayId); creature->SaveToDB(); return true; } /**HandleNpcSetMoveTypeCommand * Set the movement type for an NPC.<br/> * <br/> * Valid movement types are: * <ul> * <li> stay - NPC wont move </li> * <li> random - NPC will move randomly according to the spawndist </li> * <li> way - NPC will move with given waypoints set </li> * </ul> * additional parameter: NODEL - so no waypoints are deleted, if you * change the movement type */ static bool HandleNpcSetMoveTypeCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // 3 arguments: // GUID (optional - you can also select the creature) // stay|random|way (determines the kind of movement) // NODEL (optional - tells the system NOT to delete any waypoints) // this is very handy if you want to do waypoints, that are // later switched on/off according to special events (like escort // quests, etc) char* guid_str = strtok((char*)args, " "); char* type_str = strtok((char*)nullptr, " "); char* dontdel_str = strtok((char*)nullptr, " "); bool doNotDelete = false; if (!guid_str) return false; ObjectGuid::LowType lowguid = 0; Creature* creature = nullptr; if (dontdel_str) { //TC_LOG_ERROR("misc", "DEBUG: All 3 params are set"); // All 3 params are set // GUID // type // doNotDEL if (stricmp(dontdel_str, "NODEL") == 0) { //TC_LOG_ERROR("misc", "DEBUG: doNotDelete = true;"); doNotDelete = true; } } else { // Only 2 params - but maybe NODEL is set if (type_str) { TC_LOG_ERROR("misc", "DEBUG: Only 2 params "); if (stricmp(type_str, "NODEL") == 0) { //TC_LOG_ERROR("misc", "DEBUG: type_str, NODEL "); doNotDelete = true; type_str = nullptr; } } } if (!type_str) // case .setmovetype $move_type (with selected creature) { type_str = guid_str; creature = handler->getSelectedCreature(); if (!creature || creature->IsPet()) return false; lowguid = creature->GetSpawnId(); } else // case .setmovetype #creature_guid $move_type (with selected creature) { lowguid = atoul(guid_str); if (lowguid) creature = handler->GetCreatureFromPlayerMapByDbGuid(lowguid); // attempt check creature existence by DB data if (!creature) { CreatureData const* data = sObjectMgr->GetCreatureData(lowguid); if (!data) { handler->PSendSysMessage(LANG_COMMAND_CREATGUIDNOTFOUND, lowguid); handler->SetSentErrorMessage(true); return false; } } else { lowguid = creature->GetSpawnId(); } } // now lowguid is low guid really existed creature // and creature point (maybe) to this creature or nullptr MovementGeneratorType move_type; std::string type = type_str; if (type == "stay") move_type = IDLE_MOTION_TYPE; else if (type == "random") move_type = RANDOM_MOTION_TYPE; else if (type == "way") move_type = WAYPOINT_MOTION_TYPE; else return false; // update movement type //if (doNotDelete == false) // WaypointMgr.DeletePath(lowguid); if (creature) { // update movement type if (doNotDelete == false) creature->LoadPath(0); creature->SetDefaultMovementType(move_type); creature->GetMotionMaster()->Initialize(); if (creature->IsAlive()) // dead creature will reset movement generator at respawn { creature->setDeathState(JUST_DIED); creature->Respawn(); } creature->SaveToDB(); } if (doNotDelete == false) { handler->PSendSysMessage(LANG_MOVE_TYPE_SET, type_str); } else { handler->PSendSysMessage(LANG_MOVE_TYPE_SET_NODEL, type_str); } return true; } //npc phasemask handling //change phasemask of creature or pet static bool HandleNpcSetPhaseCommand(ChatHandler* handler, char const* args) { if (!*args) return false; uint32 phasemask = atoul(args); if (phasemask == 0) { handler->SendSysMessage(LANG_BAD_VALUE); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->SetPhaseMask(phasemask, true); if (!creature->IsPet()) creature->SaveToDB(); return true; } //set spawn dist of creature static bool HandleNpcSetSpawnDistCommand(ChatHandler* handler, char const* args) { if (!*args) return false; float option = (float)(atof((char*)args)); if (option < 0.0f) { handler->SendSysMessage(LANG_BAD_VALUE); return false; } MovementGeneratorType mtype = IDLE_MOTION_TYPE; if (option >0.0f) mtype = RANDOM_MOTION_TYPE; Creature* creature = handler->getSelectedCreature(); ObjectGuid::LowType guidLow = 0; if (creature) guidLow = creature->GetSpawnId(); else return false; creature->SetRespawnRadius((float)option); creature->SetDefaultMovementType(mtype); creature->GetMotionMaster()->Initialize(); if (creature->IsAlive()) // dead creature will reset movement generator at respawn { creature->setDeathState(JUST_DIED); creature->Respawn(); } PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_DISTANCE); stmt->setFloat(0, option); stmt->setUInt8(1, uint8(mtype)); stmt->setUInt32(2, guidLow); WorldDatabase.Execute(stmt); handler->PSendSysMessage(LANG_COMMAND_SPAWNDIST, option); return true; } //spawn time handling static bool HandleNpcSetSpawnTimeCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* stime = strtok((char*)args, " "); if (!stime) return false; int spawnTime = atoi(stime); if (spawnTime < 0) { handler->SendSysMessage(LANG_BAD_VALUE); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); ObjectGuid::LowType guidLow = 0; if (creature) guidLow = creature->GetSpawnId(); else return false; PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS); stmt->setUInt32(0, uint32(spawnTime)); stmt->setUInt32(1, guidLow); WorldDatabase.Execute(stmt); creature->SetRespawnDelay((uint32)spawnTime); handler->PSendSysMessage(LANG_COMMAND_SPAWNTIME, spawnTime); return true; } static bool HandleNpcSayCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->Say(args, LANG_UNIVERSAL); // make some emotes char lastchar = args[strlen(args) - 1]; switch (lastchar) { case '?': creature->HandleEmoteCommand(EMOTE_ONESHOT_QUESTION); break; case '!': creature->HandleEmoteCommand(EMOTE_ONESHOT_EXCLAMATION); break; default: creature->HandleEmoteCommand(EMOTE_ONESHOT_TALK); break; } return true; } //show text emote by creature in chat static bool HandleNpcTextEmoteCommand(ChatHandler* handler, char const* args) { if (!*args) return false; Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->TextEmote(args); return true; } // npc unfollow handling static bool HandleNpcUnFollowCommand(ChatHandler* handler, char const* /*args*/) { Player* player = handler->GetSession()->GetPlayer(); Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->PSendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } MovementGenerator* movement = creature->GetMotionMaster()->GetMovementGenerator([player](MovementGenerator const* a) -> bool { if (a->GetMovementGeneratorType() == FOLLOW_MOTION_TYPE) { FollowMovementGenerator const* followMovement = dynamic_cast<FollowMovementGenerator const*>(a); return followMovement && followMovement->GetTarget() == player; } return false; }); if (!movement) { handler->PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU, creature->GetName().c_str()); handler->SetSentErrorMessage(true); return false; } creature->GetMotionMaster()->Remove(movement); handler->PSendSysMessage(LANG_CREATURE_NOT_FOLLOW_YOU_NOW, creature->GetName().c_str()); return true; } // make npc whisper to player static bool HandleNpcWhisperCommand(ChatHandler* handler, char const* args) { if (!*args) { handler->SendSysMessage(LANG_CMD_SYNTAX); handler->SetSentErrorMessage(true); return false; } char* receiver_str = strtok((char*)args, " "); char* text = strtok(nullptr, ""); if (!receiver_str || !text) { handler->SendSysMessage(LANG_CMD_SYNTAX); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } ObjectGuid receiver_guid(HighGuid::Player, uint32(atoul(receiver_str))); // check online security Player* receiver = ObjectAccessor::FindPlayer(receiver_guid); if (handler->HasLowerSecurity(receiver, ObjectGuid::Empty)) return false; creature->Whisper(text, LANG_UNIVERSAL, receiver); return true; } static bool HandleNpcYellCommand(ChatHandler* handler, char const* args) { if (!*args) { handler->SendSysMessage(LANG_CMD_SYNTAX); handler->SetSentErrorMessage(true); return false; } Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } creature->Yell(args, LANG_UNIVERSAL); // make an emote creature->HandleEmoteCommand(EMOTE_ONESHOT_SHOUT); return true; } // add creature, temp only static bool HandleNpcAddTempSpawnCommand(ChatHandler* handler, char const* args) { if (!*args) return false; bool loot = false; char const* spawntype_str = strtok((char*)args, " "); char const* entry_str = strtok(nullptr, ""); if (stricmp(spawntype_str, "LOOT") == 0) loot = true; else if (stricmp(spawntype_str, "NOLOOT") == 0) loot = false; else entry_str = args; char* charID = handler->extractKeyFromLink((char*)entry_str, "Hcreature_entry"); if (!charID) return false; Player* chr = handler->GetSession()->GetPlayer(); uint32 id = atoul(charID); if (!id) return false; if (!sObjectMgr->GetCreatureTemplate(id)) return false; chr->SummonCreature(id, *chr, loot ? TEMPSUMMON_CORPSE_TIMED_DESPAWN : TEMPSUMMON_CORPSE_DESPAWN, 30 * IN_MILLISECONDS); return true; } //npc tame handling static bool HandleNpcTameCommand(ChatHandler* handler, char const* /*args*/) { Creature* creatureTarget = handler->getSelectedCreature(); if (!creatureTarget || creatureTarget->IsPet()) { handler->PSendSysMessage (LANG_SELECT_CREATURE); handler->SetSentErrorMessage (true); return false; } Player* player = handler->GetSession()->GetPlayer(); if (player->GetPetGUID()) { handler->SendSysMessage (LANG_YOU_ALREADY_HAVE_PET); handler->SetSentErrorMessage (true); return false; } CreatureTemplate const* cInfo = creatureTarget->GetCreatureTemplate(); if (!cInfo->IsTameable (player->CanTameExoticPets())) { handler->PSendSysMessage (LANG_CREATURE_NON_TAMEABLE, cInfo->Entry); handler->SetSentErrorMessage (true); return false; } // Everything looks OK, create new pet Pet* pet = player->CreateTamedPetFrom(creatureTarget); if (!pet) { handler->PSendSysMessage (LANG_CREATURE_NON_TAMEABLE, cInfo->Entry); handler->SetSentErrorMessage (true); return false; } // place pet before player float x, y, z; player->GetClosePoint (x, y, z, creatureTarget->GetCombatReach(), CONTACT_DISTANCE); pet->Relocate(x, y, z, float(M_PI) - player->GetOrientation()); // set pet to defensive mode by default (some classes can't control controlled pets in fact). pet->SetReactState(REACT_DEFENSIVE); // calculate proper level uint8 level = std::max<uint8>(player->getLevel()-5, creatureTarget->getLevel()); // prepare visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1); // add to world pet->GetMap()->AddToMap(pet->ToCreature()); // visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level); // caster have pet now player->SetMinion(pet, true); pet->SavePetToDB(PET_SAVE_AS_CURRENT); player->PetSpellInitialize(); return true; } static bool HandleNpcEvadeCommand(ChatHandler* handler, char const* args) { Creature* creatureTarget = handler->getSelectedCreature(); if (!creatureTarget || creatureTarget->IsPet()) { handler->PSendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } if (!creatureTarget->IsAIEnabled()) { handler->PSendSysMessage(LANG_CREATURE_NOT_AI_ENABLED); handler->SetSentErrorMessage(true); return false; } char* type_str = args ? strtok((char*)args, " ") : nullptr; char* force_str = args ? strtok(nullptr, " ") : nullptr; CreatureAI::EvadeReason why = CreatureAI::EVADE_REASON_OTHER; bool force = false; if (type_str) { if (stricmp(type_str, "NO_HOSTILES") == 0 || stricmp(type_str, "EVADE_REASON_NO_HOSTILES") == 0) why = CreatureAI::EVADE_REASON_NO_HOSTILES; else if (stricmp(type_str, "BOUNDARY") == 0 || stricmp(type_str, "EVADE_REASON_BOUNDARY") == 0) why = CreatureAI::EVADE_REASON_BOUNDARY; else if (stricmp(type_str, "SEQUENCE_BREAK") == 0 || stricmp(type_str, "EVADE_REASON_SEQUENCE_BREAK") == 0) why = CreatureAI::EVADE_REASON_SEQUENCE_BREAK; else if (stricmp(type_str, "FORCE") == 0) force = true; if (!force && force_str) if (stricmp(force_str, "FORCE") == 0) force = true; } if (force) creatureTarget->ClearUnitState(UNIT_STATE_EVADE); creatureTarget->AI()->EnterEvadeMode(why); return true; } static void _ShowLootEntry(ChatHandler* handler, uint32 itemId, uint8 itemCount, bool alternateString = false) { ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId); ItemLocale const* itemLocale = sObjectMgr->GetItemLocale(itemId); char const* name = nullptr; if (itemLocale) name = itemLocale->Name[handler->GetSessionDbcLocale()].c_str(); if ((!name || !*name) && itemTemplate) name = itemTemplate->Name1.c_str(); if (!name) name = "Unknown item"; handler->PSendSysMessage(alternateString ? LANG_COMMAND_NPC_SHOWLOOT_ENTRY_2 : LANG_COMMAND_NPC_SHOWLOOT_ENTRY, itemCount, ItemQualityColors[itemTemplate ? itemTemplate->Quality : uint32(ITEM_QUALITY_POOR)], itemId, name, itemId); } static void _IterateNotNormalLootMap(ChatHandler* handler, NotNormalLootItemMap const& map, std::vector<LootItem> const& items) { for (NotNormalLootItemMap::value_type const& pair : map) { if (!pair.second) continue; ObjectGuid guid = ObjectGuid::Create<HighGuid::Player>(pair.first); Player const* player = ObjectAccessor::FindConnectedPlayer(guid); handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_SUBLABEL, player ? player->GetName() : Trinity::StringFormat("Offline player (GuidLow 0x%08x)", pair.first).c_str(), pair.second->size()); for (auto it = pair.second->cbegin(); it != pair.second->cend(); ++it) { LootItem const& item = items[it->index]; if (!(it->is_looted) && !item.is_looted) _ShowLootEntry(handler, item.itemid, item.count, true); } } } static bool HandleNpcShowLootCommand(ChatHandler* handler, char const* args) { Creature* creatureTarget = handler->getSelectedCreature(); if (!creatureTarget || creatureTarget->IsPet()) { handler->PSendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } Loot const& loot = creatureTarget->loot; if (!creatureTarget->isDead() || loot.empty()) { handler->PSendSysMessage(LANG_COMMAND_NOT_DEAD_OR_NO_LOOT, creatureTarget->GetName()); handler->SetSentErrorMessage(true); return false; } handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_HEADER, creatureTarget->GetName(), creatureTarget->GetEntry()); handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_MONEY, loot.gold / GOLD, (loot.gold%GOLD) / SILVER, loot.gold%SILVER); if (strcmp(args, "all")) // nonzero from strcmp <-> not equal { handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Standard items", loot.items.size()); for (LootItem const& item : loot.items) if (!item.is_looted) _ShowLootEntry(handler, item.itemid, item.count); handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Quest items", loot.quest_items.size()); for (LootItem const& item : loot.quest_items) if (!item.is_looted) _ShowLootEntry(handler, item.itemid, item.count); } else { handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL, "Standard items", loot.items.size()); for (LootItem const& item : loot.items) if (!item.is_looted && !item.freeforall && item.conditions.empty()) _ShowLootEntry(handler, item.itemid, item.count); if (!loot.GetPlayerQuestItems().empty()) { handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "Per-player quest items"); _IterateNotNormalLootMap(handler, loot.GetPlayerQuestItems(), loot.quest_items); } if (!loot.GetPlayerFFAItems().empty()) { handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "FFA items per allowed player"); _IterateNotNormalLootMap(handler, loot.GetPlayerFFAItems(), loot.items); } if (!loot.GetPlayerNonQuestNonFFAConditionalItems().empty()) { handler->PSendSysMessage(LANG_COMMAND_NPC_SHOWLOOT_LABEL_2, "Per-player conditional items"); _IterateNotNormalLootMap(handler, loot.GetPlayerNonQuestNonFFAConditionalItems(), loot.items); } } return true; } static bool HandleNpcAddFormationCommand(ChatHandler* handler, char const* args) { if (!*args) return false; ObjectGuid::LowType leaderGUID = atoul(args); Creature* creature = handler->getSelectedCreature(); if (!creature || !creature->GetSpawnId()) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } ObjectGuid::LowType lowguid = creature->GetSpawnId(); if (creature->GetFormation()) { handler->PSendSysMessage("Selected creature is already member of group %u", creature->GetFormation()->GetLeaderSpawnId()); return false; } if (!lowguid) return false; Player* chr = handler->GetSession()->GetPlayer(); float followAngle = (creature->GetAbsoluteAngle(chr) - chr->GetOrientation()) * 180.0f / float(M_PI); float followDist = std::sqrt(std::pow(chr->GetPositionX() - creature->GetPositionX(), 2.f) + std::pow(chr->GetPositionY() - creature->GetPositionY(), 2.f)); uint32 groupAI = 0; sFormationMgr->AddFormationMember(lowguid, followAngle, followDist, leaderGUID, groupAI); creature->SearchFormation(); PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_CREATURE_FORMATION); stmt->setUInt32(0, leaderGUID); stmt->setUInt32(1, lowguid); stmt->setFloat (2, followAngle); stmt->setFloat (3, followDist); stmt->setUInt32(4, groupAI); WorldDatabase.Execute(stmt); handler->PSendSysMessage("Creature %u added to formation with leader %u", lowguid, leaderGUID); return true; } static bool HandleNpcSetLinkCommand(ChatHandler* handler, char const* args) { if (!*args) return false; ObjectGuid::LowType linkguid = atoul(args); Creature* creature = handler->getSelectedCreature(); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); handler->SetSentErrorMessage(true); return false; } if (!creature->GetSpawnId()) { handler->PSendSysMessage("Selected creature %u isn't in creature table", creature->GetGUID().GetCounter()); handler->SetSentErrorMessage(true); return false; } if (!sObjectMgr->SetCreatureLinkedRespawn(creature->GetSpawnId(), linkguid)) { handler->PSendSysMessage("Selected creature can't link with guid '%u'", linkguid); handler->SetSentErrorMessage(true); return false; } handler->PSendSysMessage("LinkGUID '%u' added to creature with DBTableGUID: '%u'", linkguid, creature->GetSpawnId()); return true; } /// @todo NpcCommands that need to be fixed : static bool HandleNpcAddWeaponCommand(ChatHandler* /*handler*/, char const* /*args*/) { /*if (!*args) return false; uint64 guid = handler->GetSession()->GetPlayer()->GetSelection(); if (guid == 0) { handler->SendSysMessage(LANG_NO_SELECTION); return true; } Creature* creature = ObjectAccessor::GetCreature(*handler->GetSession()->GetPlayer(), guid); if (!creature) { handler->SendSysMessage(LANG_SELECT_CREATURE); return true; } char* pSlotID = strtok((char*)args, " "); if (!pSlotID) return false; char* pItemID = strtok(nullptr, " "); if (!pItemID) return false; uint32 ItemID = atoi(pItemID); uint32 SlotID = atoi(pSlotID); ItemTemplate* tmpItem = sObjectMgr->GetItemTemplate(ItemID); bool added = false; if (tmpItem) { switch (SlotID) { case 1: creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY, ItemID); added = true; break; case 2: creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_01, ItemID); added = true; break; case 3: creature->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_DISPLAY_02, ItemID); added = true; break; default: handler->PSendSysMessage(LANG_ITEM_SLOT_NOT_EXIST, SlotID); added = false; break; } if (added) handler->PSendSysMessage(LANG_ITEM_ADDED_TO_SLOT, ItemID, tmpItem->Name1, SlotID); } else { handler->PSendSysMessage(LANG_ITEM_NOT_FOUND, ItemID); return true; } */ return true; } }; void AddSC_npc_commandscript() { new npc_commandscript(); }
chaodhib/TrinityCore
src/server/scripts/Commands/cs_npc.cpp
C++
gpl-2.0
60,070
<?php //Custom user module class ThemexUser { public static $data; public static $id=__CLASS__; //Init module public static function init() { //refresh module data self::refresh(); //ajax actions add_action('wp_ajax_nopriv_themex_register', array(__CLASS__,'registerUser')); add_action('wp_ajax_nopriv_themex_login', array(__CLASS__,'loginUser')); add_action('wp_ajax_nopriv_themex_password', array(__CLASS__,'recoverUser')); //admin bar add_filter('show_admin_bar', array(__CLASS__,'renderAdminBar')); //get users data add_action('wp', array(__CLASS__,'initUser'), 1); add_action('admin_init', array(__CLASS__,'initUser')); //save user data add_action('template_redirect', array(__CLASS__,'saveData')); //activate user add_action('template_redirect', array(__CLASS__,'activateUser')); //set avatar add_filter('get_avatar', array(__CLASS__,'getAvatar'), 10, 5); //show register page add_filter('template_include', array(__CLASS__,'renderLoginPage'), 100, 1); //set login title add_filter('wp_title', array(__CLASS__,'setLoginTitle'), 10, 2); //profile image add_filter('show_user_profile', array(__CLASS__,'renderAvatar')); add_filter('edit_user_profile', array(__CLASS__,'renderAvatar')); add_action('edit_user_profile_update', array(__CLASS__,'saveAvatar')); add_action('personal_options_update', array(__CLASS__,'saveAvatar')); //profile text add_filter('show_user_profile', array(__CLASS__,'renderBiography')); add_filter('edit_user_profile', array(__CLASS__,'renderBiography')); //facebook login if(self::getOption('facebook_login')) { add_action('wp_footer', array(__CLASS__,'loadFacebookAPI')); add_action('init', array(__CLASS__,'renderFacebookPage')); add_filter('init', array(__CLASS__,'loginFacebookUser'), 90); add_action('wp_logout', array(__CLASS__,'logoutFacebookUser')); } } //Refresh module stored data public static function refresh() { self::$data=ThemexCore::getOption(self::$id); self::$data['register_page_url']=ThemexCore::generateURL(ThemexCore::$components['rewrite_rules']['register']['name']); self::$data['messages']=array(); } //Save module static data public static function save() { ThemexCore::updateOption(self::$id,self::$data); } //Save module settings public static function saveSettings($data) { //refresh stored data self::refresh(); //search for widget areas options foreach($data as $key=>$value) { if($key==self::$id) { self::$data=$value; } } //save static data self::save(); } //Render settings public static function renderSettings($slug) { //get module stored data self::refresh(); $options=array( array( 'type' => 'checkbox', 'id' => self::$id.'[facebook_login]', 'default' => isset(self::$data['facebook_login'])?self::$data['facebook_login']:'false', 'description' => __('Check this option to allow users to sign in with Facebook.','academy'), 'name' => __('Enable Facebook Connect','academy'), 'attributes' => array('class'=>'themex_parent'), ), array( 'type' => 'text', 'id' => self::$id.'[facebook_id]', 'default' => isset(self::$data['facebook_id'])?self::$data['facebook_id']:'', 'name' => __('Facebook Application ID','academy'), 'attributes' => array('class'=>'themex_child'), 'hidden' => true, ), array( 'type' => 'text', 'id' => self::$id.'[facebook_secret]', 'default' => isset(self::$data['facebook_secret'])?self::$data['facebook_secret']:'', 'name' => __('Facebook Application Secret','academy'), 'attributes' => array('class'=>'themex_child'), 'hidden' => true, ), array( 'type' => 'checkbox', 'id' => self::$id.'[confirmation]', 'default' => isset(self::$data['confirmation'])?self::$data['confirmation']:'false', 'description' => __('Check this option if user email confirmation required.','academy'), 'name' => __('Enable Email Confirmation','academy'), ), array( 'type' => 'checkbox', 'id' => self::$id.'[captcha]', 'default' => isset(self::$data['captcha'])?self::$data['captcha']:'false', 'description' => __('Check this option to enable captcha protection.','academy'), 'name' => __('Enable Captcha Protection','academy'), ), array( 'type' => 'textarea', 'id' => self::$id.'[register_message]', 'name' => __('Registration Message','academy'), 'description' => __('Message that is sent to user after registration. Use %username%, %password% and %link% codes to show them in the message text.','academy'), 'default' => isset(self::$data['register_message'])?self::$data['register_message']:'', ), array( 'type' => 'textarea', 'id' => self::$id.'[password_message]', 'name' => __('Password Reset Message','academy'), 'description' => __('Message that is sent when user lost the password. Use %username% and %link% codes to show them in the message text.','academy'), 'default' => isset(self::$data['password_message'])?self::$data['password_message']:'', ), ); $out='<div class="'.$slug.'">'; foreach($options as $option) { $out.=ThemexInterface::renderOption($option); } $out.='</div>'; return $out; } //Init users data public static function initUser() { self::$data['user']=wp_get_current_user(); self::$data['current_user']=self::$data['user']; self::$data['profile_page_url']=get_author_posts_url(get_current_user_id()); if(get_query_var('author')) { self::$data['current_user']=get_userdata(get_query_var('author')); } } //Render admin bar public static function renderAdminBar() { if(current_user_can('edit_posts') && get_user_option('show_admin_bar_front', get_current_user_id())!='false') { return true; } return false; } //Render register page public static function renderLoginPage($template) { if(ThemexUser::isLoginPage()) { if(self::userActive()) { wp_redirect(self::$data['profile_page_url']); exit; } else { $template = THEME_PATH.'template-register.php'; } } return $template; } //Set login title public static function setLoginTitle($title, $sep) { if(ThemexUser::isLoginPage()) { if(get_option('users_can_register')) { $title=__('Registration', 'academy'); } else { $title=__('Authorization', 'academy'); } $title.=' '.$sep.' '; } return $title; } //Get Avatar public static function getAvatar($avatar, $user, $size, $default, $alt) { if(isset($user->user_id)) { $user=$user->user_id; } $avatar_id=get_user_meta($user, 'avatar', true); $default=wp_get_attachment_image_src( $avatar_id, 'thumbnail'); if(!isset($default[0])) { $default[0]=THEME_URI.'images/avatar.png'; } return '<img src="'.$default[0].'" class="avatar" width="'.$size.'" alt="'.$alt.'" />'; } //Render Avatar public static function renderAvatar($user) { $out=''; if(current_user_can('manage_options')) { $out='<table class="form-table"><tbody><tr>'; $out.='<th><label for="avatar">'.__('Profile Photo', 'academy').'</label></th><td><div class="themex_avatar">'; $out.=get_avatar( $user->ID ); $out.='<input type="hidden" name="avatar" /><a href="#" class="button upload_button">'.__('Upload','academy').'</a>'; $out.='</div></td></tr></tbody></table>'; } echo $out; } //Save Avatar public static function saveAvatar($user) { global $wpdb; if(isset($_POST['avatar']) && !empty($_POST['avatar']) && current_user_can('manage_options')) { $src=esc_url($_POST['avatar']); $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$src'"; $avatar = $wpdb->get_var($query); update_user_meta( $user, 'avatar', $avatar); } } //Render Biography public static function renderBiography($user) { $out='<table class="form-table"><tbody><tr>'; $out.='<th><label for="description">'.__('Profile Text', 'academy').'</label></th><td>'; ob_start(); ThemexInterface::renderEditor('description', wpautop(get_user_meta( $user->ID, 'description', true))); $out.=ob_get_contents(); ob_end_clean(); $out.='</tr></td></tbody></table>'; echo $out; } //Login user public static function loginUser() { self::refresh(); parse_str($_POST['data'], $creds); self::$data['messages']=array(); $creds['remember']=true; $user=wp_signon($creds, false); self::$data['messages']=array(); if(is_wp_error($user) || empty($creds['user_login']) || empty($creds['user_password'])){ self::$data['messages'][]=__('Invalid username or password','academy'); } else if(array_shift($user->roles)=='inactive') { self::$data['messages'][]=__('This account is not activated', 'academy'); } else { self::renderMessages('<a href="'.get_author_posts_url($user->ID).'" class="redirect"></a>'); } if(!empty(self::$data['messages'])){ wp_logout(); self::renderMessages(); } die(); } //Register user public static function registerUser() { self::refresh(); parse_str($_POST['data'], $userdata); self::$data['messages']=array(); if(isset(self::$data['captcha']) && self::$data['captcha']=='true') { session_start(); $posted_code=md5($userdata['captcha']); $session_code = $_SESSION['captcha']; if($session_code!=$posted_code) { self::$data['messages'][]=__('Verification code is incorrect','academy'); } } if(empty($userdata['user_email']) || empty($userdata['user_email']) || empty($userdata['user_password']) || empty($userdata['user_password_repeat'])) { self::$data['messages'][]=__('Please fill in all fields.','academy'); } else { if(!is_email($userdata['user_email'])) { self::$data['messages'][]=__('Invalid email address.','academy'); } else if(email_exists($userdata['user_email'])) { self::$data['messages'][]=__('This email is already in use.','academy'); } if(!validate_username($userdata['user_login'])) { self::$data['messages'][]=__('Invalid character used in username.','academy'); } else if(username_exists($userdata['user_login'])) { self::$data['messages'][]=__('This username is already taken.','academy'); } if(strlen($userdata['user_password'])<4) { self::$data['messages'][]=__('Password must be at least 4 characters long.','academy'); } else if(strlen($userdata['user_password'])>16) { self::$data['messages'][]=__('Password must be not more than 16 characters long.','academy'); } else if(preg_match("/^([a-zA-Z0-9]{1,20})$/",$userdata['user_password'])==0) { self::$data['messages'][]=__('Invalid character used in password.','academy'); } else if($userdata['user_password']!=$userdata['user_password_repeat']) { self::$data['messages'][]=__('Passwords do not match.','academy'); } if(!isset($userdata['register_url'])) { self::$data['messages'][]=__('Registration page does not exist.','academy'); } } if(!empty(self::$data['messages'])){ self::renderMessages(); } else { $user=wp_create_user($userdata['user_login'], $userdata['user_password'], $userdata['user_email']); wp_new_user_notification($user); $mail_message=self::$data['register_message']; $confirm_code=''; if(empty($mail_message)) { $mail_message='Hi, %username%! Welcome to '.get_bloginfo('name').'.'; } if(isset(self::$data['confirmation']) && self::$data['confirmation']=='true') { $message=__('Registration complete! Check your mailbox to activate the account.','academy'); $subject=__('Account Confirmation','academy'); $confirm_code=md5(uniqid()); $user=new WP_User($user); $user->remove_role(get_option('default_role')); $user->add_role('inactive'); add_user_meta($user->ID, 'activation_code', $confirm_code, true); if(intval(substr($userdata['register_url'], -1))==1) { $userdata['register_url'].='&'; } else { $userdata['register_url'].='?'; } $mail_message=str_replace('%link%', $userdata['register_url'].'activate='.urlencode($confirm_code), $mail_message); } else { wp_signon($userdata, false); $message='<a href="'.get_author_posts_url($user).'" class="redirect"></a>'; $subject=__('Registration Complete','academy'); } $mail_message=str_replace('%username%', $userdata['user_login'], $mail_message); $mail_message=str_replace('%password%', $userdata['user_password'], $mail_message); self::sendEmail($userdata['user_email'], $subject, themex_html($mail_message)); self::renderMessages($message); } die(); } //Recover user password public static function recoverUser() { global $wpdb, $current_site; parse_str($_POST['data'], $userdata); self::$data['messages']=array(); if(email_exists(sanitize_email($userdata['user_email']))) { $user=get_user_by('email', sanitize_email($userdata['user_email'])); do_action('lostpassword_post'); $user_login=$user->user_login; $user_email=$user->user_email; do_action('retrieve_password', $user_login); $allow=apply_filters('allow_password_reset', true, $user->ID); if(!$allow || is_wp_error($allow)) { self::$data['messages'][]=__('Password recovery not allowed','academy'); self::renderMessages(); } else { $key=$wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login)); if ( empty($key) ) { $key = wp_generate_password(20, false); do_action('retrieve_password_key', $user_login, $key); $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login)); } $link=network_site_url('wp-login.php?action=rp&key='.urlencode($key).'&login='.urlencode($user_login),'login'); $mail_message=self::$data['password_message']; if(empty($mail_message)) { $mail_message='Hi, %username%! To reset your password, visit the following link: %link%.'; } $mail_message=str_replace('%username%', $user->user_login, $mail_message); $mail_message=str_replace('%link%', $link, $mail_message); if(self::sendEmail($user_email, __('Password Recovery','academy'), themex_html($mail_message))) { self::renderMessages(__('Password reset link is sent','academy')); } else { self::$data['messages'][]=__('Error sending email','academy'); } } } else { self::$data['messages'][]=__('Invalid email address','academy'); } if(!empty(self::$data['messages'])) { self::renderMessages(); } die(); } //Save Profile public static function saveData() { //check author if(!is_author()) { return; } //change avatar if (isset($_FILES['avatar']) && $_FILES['avatar']['name']!='') { require_once(ABSPATH.'wp-admin/includes/image.php'); $uploads = wp_upload_dir(); $filetype=wp_check_filetype($_FILES['avatar']['name'], null ); $filename=basename('avatar_'.self::$data['user']->ID.'.'.$filetype['ext']); $filepath=$uploads['path'].'/'.$filename; if ($filetype['ext']!='png' && $filetype['ext']!='jpg' && $filetype['ext']!='jpeg') { self::$data['messages'][]=__('Only JPG and PNG images are allowed.','academy'); } else if(is_uploaded_file($_FILES['avatar']['tmp_name'])) { //remove previous avatar wp_delete_attachment(self::$data['user']->avatar); if(move_uploaded_file($_FILES['avatar']['tmp_name'], $filepath)) { $attachment = array( 'guid' => $uploads['url'].'/'.$filename, 'post_mime_type' => $filetype['type'], 'post_title' => sanitize_title(current(explode('.', $filename))), 'post_content' => '', 'post_status' => 'inherit', ); //set new avatar self::$data['user']->avatar=wp_insert_attachment( $attachment, $attachment['guid'], 0 ); update_user_meta(self::$data['user']->ID, 'avatar', self::$data['user']->avatar); update_post_meta(self::$data['user']->avatar, '_wp_attached_file', substr($uploads['subdir'], 1).'/'.$filename); //generate thumbnail $metadata=wp_generate_attachment_metadata(self::$data['user']->avatar, $filepath); wp_update_attachment_metadata(self::$data['user']->avatar, $metadata); } } else { self::$data['messages'][]=__('This image is too large for uploading.','academy'); } } //text fields if(isset(ThemexCore::$components['profile_fields'])) { foreach(ThemexCore::$components['profile_fields'] as $field_name) { if(isset($_POST['user_'.$field_name])) { self::$data['user']->$field_name=sanitize_text_field($_POST['user_'.$field_name]); update_user_meta(self::$data['user']->ID, $field_name, self::$data['user']->$field_name); self::$data['user']->$field_name=themex_stripslashes(self::$data['user']->$field_name); } } } //description if(isset($_POST['user_description'])) { self::$data['user']->description=wp_kses(wpautop($_POST['user_description']), array( 'strong' => array(), 'em' => array(), 'a' => array( 'href' => array(), 'title' => array(), 'target' => array(), ), 'p' => array(), 'br' => array(), )); update_user_meta(self::$data['user']->ID, 'description', self::$data['user']->description ); self::$data['user']->description=themex_stripslashes(self::$data['user']->description); } } //Activate User public static function activateUser() { if(isset($_GET['activate'])) { $users=get_users(array( 'meta_key' => 'activation_code', 'meta_value' => sanitize_text_field($_GET['activate']), )); if(isset($users[0])) { $users[0]->remove_role('inactive'); $users[0]->add_role(get_option('default_role')); update_user_meta($users[0]->ID, 'activation_code', ''); self::$data['account_activated']=true; } } } //Send Email public static function sendEmail($to, $subject, $message) { $headers = "MIME-Version: 1.0" . PHP_EOL; $headers .= "Content-Type: text/html; charset=UTF-8".PHP_EOL; if(wp_mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=', $message, $headers)) { return true; } return false; } //Check active user public static function userActive() { if(is_user_logged_in() && array_shift(self::$data['user']->roles)!='inactive') { return true; } return false; } //Check profile page public static function isProfilePage() { return get_query_var('author') && self::$data['user']->ID==get_query_var('author'); } //Check login page public static function isLoginPage() { if(get_query_var(ThemexCore::$components['rewrite_rules']['register']['name'])) { return true; } return false; } //Render messages public static function renderMessages($success_message=null) { $out=''; if(isset($success_message)) { $out.='<div class="success"><ul><li>'.$success_message.'</li></ul></div>'; } else { $out.='<div class="error"><ul>'; foreach(self::$data['messages'] as $message) { $out.='<li>'.$message.'</li>'; } $out.='</ul></div>'; } echo $out; } //Get full name public static function getFullName($user) { $out=''; if($user->first_name!='') { $out.=$user->first_name.' '; } $out.=$user->last_name; return $out; } //Get description public static function getDescription($description='') { $divider=strpos($description, '</p>'); if($divider!==false) { return substr($description, 0, $divider).'</p>'; } return $description; } //Load Facebook API public static function loadFacebookAPI($logout=false) { $out='<div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = function() { FB.init({ appId : "'.self::getOption('facebook_id').'", channelUrl : "'.home_url('?facebook=1').'", status : true, cookie : true, xfbml : true, oauth : true });'; if($logout) { $out.='FB.getLoginStatus(function(response) { if (response.status === "connected") { FB.logout(function(response) { window.location.href="'.home_url().'"; }); } else { window.location.href="'.home_url().'"; } });'; } $out.='}; (function(d){ var js, id = "facebook-jssdk"; if (d.getElementById(id)) {return;} js = d.createElement("script"); js.id = id; js.async = true; js.src = "//connect.facebook.net/'.self::getFacebookLocale().'/all.js"; d.getElementsByTagName("head")[0].appendChild(js); }(document)); </script>'; echo $out; } //Get Facebook locale public static function getFacebookLocale() { $locale = get_locale(); $locales = array( 'ca_ES', 'cs_CZ', 'cy_GB', 'da_DK', 'de_DE', 'eu_ES', 'en_PI', 'en_UD', 'ck_US', 'en_US', 'es_LA', 'es_CL', 'es_CO', 'es_ES', 'es_MX', 'es_VE', 'fb_FI', 'fi_FI', 'fr_FR', 'gl_ES', 'hu_HU', 'it_IT', 'ja_JP', 'ko_KR', 'nb_NO', 'nn_NO', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'ro_RO', 'ru_RU', 'sk_SK', 'sl_SI', 'sv_SE', 'th_TH', 'tr_TR', 'ku_TR', 'zh_CN', 'zh_HK', 'zh_TW', 'fb_LT', 'af_ZA', 'sq_AL', 'hy_AM', 'az_AZ', 'be_BY', 'bn_IN', 'bs_BA', 'bg_BG', 'hr_HR', 'nl_BE', 'en_GB', 'eo_EO', 'et_EE', 'fo_FO', 'fr_CA', 'ka_GE', 'el_GR', 'gu_IN', 'hi_IN', 'is_IS', 'id_ID', 'ga_IE', 'jv_ID', 'kn_IN', 'kk_KZ', 'la_VA', 'lv_LV', 'li_NL', 'lt_LT', 'mk_MK', 'mg_MG', 'ms_MY', 'mt_MT', 'mr_IN', 'mn_MN', 'ne_NP', 'pa_IN', 'rm_CH', 'sa_IN', 'sr_RS', 'so_SO', 'sw_KE', 'tl_PH', 'ta_IN', 'tt_RU', 'te_IN', 'ml_IN', 'uk_UA', 'uz_UZ', 'vi_VN', 'xh_ZA', 'zu_ZA', 'km_KH', 'tg_TJ', 'ar_AR', 'he_IL', 'ur_PK', 'fa_IR', 'sy_SY', 'yi_DE', 'gn_PY', 'qu_PE', 'ay_BO', 'se_NO', 'ps_AF', 'tl_ST', ); $locale = str_replace('-', '_', $locale); if(strlen($locale)==2) { $locale = strtolower($locale).'_'.strtoupper($locale); } if (!in_array($locale, $locales)) { $locale='en_US'; } return $locale; } //Render Facebook page public static function renderFacebookPage() { if (isset($_GET['facebook'])) { $limit=60*60*24*365; header('Pragma: public'); header('Cache-Control: max-age='.$limit); header('Expires: '.gmdate('D, d M Y H:i:s', time()+$limit).' GMT'); echo '<script src="//connect.facebook.net/'.self::getFacebookLocale().'/all.js"></script>'; exit; } } //Login Facebook user public static function loginFacebookUser() { if(!is_user_logged_in() && isset($_COOKIE['fbsr_'.self::getOption('facebook_id')])) { $cookie=self::parseFacebookCookie(); if(isset($cookie['user_id'])) { $users=get_users(array( 'meta_key' => 'facebook_id', 'meta_value' => $cookie['user_id'], )); if(!empty($users) && $users[0]->ID!=1) { wp_set_auth_cookie($users[0]->ID, true); wp_redirect(self::$data['register_page_url']); exit(); } else { $profile=self::getFacebookProfile($cookie['user_id'], array( 'fields' => 'username,first_name,last_name,email', 'code' => $cookie['code'], 'sslverify' => 0, )); if(isset($profile['email'])) { if(!isset($profile['username'])) { if(isset($profile['first_name'])) { $profile['username']=$profile['first_name']; } else if(isset($profile['last_name'])) { $profile['username']=$profile['last_name']; } } $profile['username']=sanitize_user($profile['username']); while(username_exists($profile['username'])) { $profile['username'].=rand(0,9); } $user=wp_create_user($profile['username'], wp_generate_password(10), $profile['email']); if(!is_wp_error($user) && $user!=1) { wp_set_auth_cookie($user, true); add_user_meta($user, 'facebook_id', $profile['id'], true); if(isset($profile['first_name'])) { update_user_meta($user, 'first_name', $profile['first_name']); } if(isset($profile['last_name'])) { update_user_meta($user, 'last_name', $profile['last_name']); } } wp_redirect(self::$data['register_page_url']); exit(); } } } } } //Logout Facebook user public static function logoutFacebookUser() { if(isset($_COOKIE['fbsr_'.self::getOption('facebook_id')])) { $domain = '.'.parse_url(home_url('/'), PHP_URL_HOST); setcookie('fbsr_'.self::getOption('facebook_id'), ' ', time()-31536000, '/', $domain); $out='<html><head></head><body>'; ob_start(); self::loadFacebookAPI(true); $out.=ob_get_contents(); ob_end_clean(); $out.='</body></html>'; echo $out; exit(); } } //Get Facebook profile public static function getFacebookProfile($ID, $fields=array()) { if (!empty($fields['code'])) { $response=wp_remote_get('https://graph.facebook.com/oauth/access_token?client_id='.self::getOption('facebook_id').'&redirect_uri=&client_secret='.self::getOption('facebook_secret').'&code='.$fields['code'], array('sslverify' => false)); if (!is_wp_error($response) && wp_remote_retrieve_response_code($response)==200) { parse_str($response['body'], $response); $fields['access_token']=$response['access_token']; } else { return false; } } $url='https://graph.facebook.com/'.$ID.'?'.http_build_query($fields); $response=wp_remote_get($url, $fields); if (!is_wp_error($response) && $response) { $response=json_decode($response['body'], true); return $response; } return false; } //Parse Facebook cookie public static function parseFacebookCookie() { $cookie = array(); if(list($encoded_sign, $payload)=explode('.', $_COOKIE['fbsr_'.self::getOption('facebook_id')], 2)){ $sign=base64_decode(strtr($encoded_sign, '-_', '+/')); if (hash_hmac('sha256', $payload, self::getOption('facebook_secret'), true)==$sign){ $cookie=json_decode(base64_decode(strtr($payload, '-_', '+/')), true); } } return $cookie; } //Get module option public static function getOption($ID, $default='') { if(isset(self::$data[$ID])) { return self::$data[$ID]; } return $default; } }
ibrahimcesar/makersSchool
framework/classes/themex.user.php
PHP
gpl-2.0
26,061
/* Copyleft (C) 2005 Hio Perroni Filho xperroni@yahoo.com ICQ: 2490863 This file is part of ChatterBean. ChatterBean 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. ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt). */ package bitoflife.chatterbean.text; import java.util.Arrays; /** */ public class Sentence { /* Attributes */ private String original; private Integer[] mappings; // The index mappings of normalized elements to original elements. private String normalized; private String[] splitted; // The normalized entry, splitted in an array of words. public static final Sentence ASTERISK = new Sentence(" * ", new Integer[] {0, 2}, " * "); /* Constructors */ public Sentence(String original, Integer[] mappings, String normalized) { setOriginal(original); setMappings(mappings); setNormalized(normalized); } /** Constructs a Sentence out of a non-normalized input string. */ public Sentence(String original) { this(original, null, null); } /* Methods */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof Sentence)) return false; Sentence compared = (Sentence) obj; return (original.equals(compared.original) && Arrays.equals(mappings, compared.mappings) && normalized.equals(compared.normalized)); } /** Gets the number of individual words contained by the Sentence. */ public int length() { return splitted.length; } /** Returns the normalized as an array of String words. */ public String[] normalized() { return splitted; } /** Gets the (index)th word of the Sentence, in its normalized form. */ public String normalized(int index) { return splitted[index]; } public String original(int beginIndex, int endIndex) { if (beginIndex < 0) throw new ArrayIndexOutOfBoundsException(beginIndex); while (beginIndex >= 0 && mappings[beginIndex] == null) beginIndex--; int n = mappings.length; while (endIndex < n && mappings[endIndex] == null) endIndex++; if (endIndex >= n) endIndex = n - 1; String value = original.substring(mappings[beginIndex], mappings[endIndex] + 1); value = value.replaceAll("^[^A-Za-z0-9]+|[^A-Za-z0-9]+$", " "); return value; } /** Returns a string representation of the Sentence. This is useful for printing the state of Sentence objects during tests. @return A string formed of three bracket-separated sections: the original sentence string, the normalized-to-original word mapping array, and the normalized string. */ public String toString() { return "[" + original + "]" + Arrays.toString(mappings) + "[" + normalized + "]"; } /** Returns a trimmed version of the original Sentence string. @return A trimmed version of the original Sentence string. */ public String trimOriginal() { return original.trim(); } /* Properties */ public Integer[] getMappings() { return mappings; } public void setMappings(Integer[] mappings) { this.mappings = mappings; } /** Gets the Sentence in its normalized form. */ public String getNormalized() { return normalized; } public void setNormalized(String normalized) { this.normalized = normalized; if (normalized != null) splitted = normalized.trim().split(" "); } /** Gets the Sentence, in its original, unformatted form. */ public String getOriginal() { return original; } public void setOriginal(String original) { this.original = original; } }
WonderBeat/vasilich
alice-src/bitoflife/chatterbean/text/Sentence.java
Java
gpl-2.0
4,272