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
package models; public class Disparo { public int partida; public int jugador; public int x; public int y; }
iturrioz/izan-pirata
app/models/Disparo.java
Java
gpl-2.0
126
// @(#)$Id: JMLMap.java-generic,v 1.34 2005/12/24 21:20:31 chalin Exp $ // Copyright (C) 2005 Iowa State University // // This file is part of the runtime library of the Java Modeling Language. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1, // of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with JML; see the file LesserGPL.txt. If not, write to the Free // Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA. package org.jmlspecs.models; import java.util.Enumeration; /** Maps (i.e., binary relations that are functional) from non-null * elements of {@link Object} to non-null elements of {@link * JMLType}. The first type, <kbd>Object</kbd>, is called * the domain type of the map; the second type, * <kbd>JMLType</kbd>, is called the range type of the map. A * map can be seen as a set of pairs, of form <em>(dv, rv)</em>, * consisting of an element of the domain type, <em>dv</em>, and an * element of the range type, <em>rv</em>. Alternatively, it can be * seen as a function that maps each element of the domain to some of * elements of the range type. * * <p> This type is a subtype of {@link * JMLObjectToValueRelation}, and as such as can be treated as a * binary relation or a set valued function also. See the * documentation for {@link JMLObjectToValueRelation} and for the * methods inherited from this supertype for more information. * * <p> This type considers elements <kbd>val</kbd> and <kbd>dv</kbd> * of the domain type, to be distinct just when * <kbd>_val_not_equal_to_dv_</kbd>. It considers elements of * <kbd>r</kbd> and <kbd>rv</kbd> of the range type to be distinct * just when <kbd>_r_not_equal_to_rv_</kbd>. Cloning takes place for * the domain or range elements if the corresponding domain or range * type is {@link JMLType}. * * @version $Revision: 1.34 $ * @author Gary T. Leavens * @author Clyde Ruby * @see JMLCollection * @see JMLType * @see JMLObjectToValueRelation * @see JMLObjectToValueRelationEnumerator * @see JMLObjectToValueRelationImageEnumerator * @see JMLValueSet * @see JMLObjectSet * @see JMLObjectToObjectMap * @see JMLValueToObjectMap * @see JMLObjectToValueMap * @see JMLValueToValueMap * @see JMLObjectToValueRelation#toFunction() */ //-@ immutable public /*@ pure @*/ // FIXME: adapt this file to non-null-by-default and remove the following modifier. /*@ nullable_by_default @*/ class JMLObjectToValueMap extends JMLObjectToValueRelation { /*@ public invariant isaFunction(); @ public invariant_redundantly @ (\forall Object dv; isDefinedAt(dv); @ elementImage(dv).int_size() == 1); @*/ /** Initialize this map to be the empty mapping. * @see #EMPTY */ /*@ public normal_behavior @ assignable theRelation, owner, elementType, containsNull; @ ensures theRelation.equals(new JMLValueSet()); @ ensures_redundantly theRelation.isEmpty(); @*/ public JMLObjectToValueMap() { super(); } /** Initialize this map to be a mapping that maps the given domain * element to the given range element. * @see #singletonMap(Object, JMLType) * @see #JMLObjectToValueMap(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ assignable theRelation, owner, elementType, containsNull; @ ensures (theRelation.int_size() == 1) && elementImage(dv).has(rv); @ ensures_redundantly isDefinedAt(dv); @*/ public JMLObjectToValueMap(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { super(dv, rv); } /** Initialize this map to be a mapping that maps the key in the * given pair to the value in that pair. * @see #singletonMap(JMLObjectValuePair) * @see #JMLObjectToValueMap(Object, JMLType) */ /*@ public normal_behavior @ requires pair != null; @ assignable theRelation, owner, elementType, containsNull; @ ensures (theRelation.int_size() == 1) @ && elementImage(pair.key).has(pair.value); @ ensures_redundantly isDefinedAt(pair.key); @*/ public JMLObjectToValueMap(/*@ non_null @*/ JMLObjectValuePair pair) { super(pair.key, pair.value); } /** Initialize this map based on the representation values given. */ //@ requires ipset != null && dom != null && 0 <= sz; //@ assignable theRelation, owner, elementType, containsNull; //@ ensures imagePairSet_ == ipset && domain_ == dom && size_ == sz; protected JMLObjectToValueMap(JMLValueSet ipset, JMLObjectSet dom, int sz) { super(ipset, dom, sz); } /** The empty JMLObjectToValueMap. * @see #JMLObjectToValueMap() */ public static final /*@ non_null @*/ JMLObjectToValueMap EMPTY = new JMLObjectToValueMap(); /** Return the singleton map containing the given association. * @see #JMLObjectToValueMap(Object, JMLType) * @see #singletonMap(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ ensures \result != null @ && \result.equals(new JMLObjectToValueMap(dv, rv)); @*/ public static /*@ pure @*/ /*@ non_null @*/ JMLObjectToValueMap singletonMap(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { return new JMLObjectToValueMap(dv, rv); } /** Return the singleton map containing the association described * by the given pair. * @see #JMLObjectToValueMap(JMLObjectValuePair) * @see #singletonMap(Object, JMLType) */ /*@ public normal_behavior @ requires pair != null; @ ensures \result != null @ && \result.equals(new JMLObjectToValueMap(pair)); @*/ public static /*@ pure @*/ /*@ non_null @*/ JMLObjectToValueMap singletonMap(/*@ non_null @*/ JMLObjectValuePair pair) { return new JMLObjectToValueMap(pair); } /** Tells whether this relation is a function. */ /*@ also @ public normal_behavior @ ensures \result; @*/ //@ pure public boolean isaFunction() { return true; } /** Return the range element corresponding to dv, if there is one. * * @param dv the domain element for which an association is * sought (the key to the table). * @exception JMLNoSuchElementException when dv is not associated * to any range element by this. * @see JMLObjectToValueRelation#isDefinedAt * @see JMLObjectToValueRelation#elementImage * @see JMLObjectToValueRelation#image */ /*@ public normal_behavior @ requires isDefinedAt(dv); @ ensures elementImage(dv).has(\result); @ also @ public exceptional_behavior @ requires !isDefinedAt(dv); @ signals_only JMLNoSuchElementException; @*/ public /*@ non_null @*/ JMLType apply(Object dv) throws JMLNoSuchElementException { JMLValueSet img = elementImage(dv); if (img.int_size() == 1) { JMLType res = img.choose(); //@ assume res != null; return res; } else { throw new JMLNoSuchElementException("Map not defined at " + dv); } } //@ nowarn NonNullResult; /*@ also @ public normal_behavior @ ensures \result instanceof JMLObjectToValueMap @ && ((JMLObjectToValueMap)\result) @ .theRelation.equals(this.theRelation); @*/ //@ pure public /*@ non_null @*/ Object clone() { return new JMLObjectToValueMap(imagePairSet_, domain_, size_); } //@ nowarn Post; /** Return a new map that is like this but maps the given domain * element to the given range element. Any previously existing * mapping for the domain element is removed first. * @see JMLObjectToValueRelation#insert(JMLObjectValuePair) */ /*@ public normal_behavior @ requires dv != null && rv != null; @ requires !isDefinedAt(dv) ==> int_size() < Integer.MAX_VALUE; @ ensures \result.equals(this.removeDomainElement(dv).add(dv, rv)); @*/ public /*@ non_null @*/ JMLObjectToValueMap extend(/*@ non_null @*/ Object dv, /*@ non_null @*/ JMLType rv) { JMLObjectToValueMap newMap = this.removeDomainElement(dv); newMap = newMap.disjointUnion(new JMLObjectToValueMap(dv, rv)); return newMap; } //@ nowarn Exception; /** Return a new map that is like this but has no association for the * given domain element. * @see JMLObjectToValueRelation#removeFromDomain */ /*@ public normal_behavior @ ensures \result.equals(removeFromDomain(dv).toFunction()); @ ensures_redundantly !isDefinedAt(dv) ==> \result.equals(this); @*/ public /*@ non_null @*/ JMLObjectToValueMap removeDomainElement(Object dv) { return super.removeFromDomain(dv).toFunction(); } /** Return a new map that is the composition of this and the given * map. The composition is done in the usual order; that is, if * the given map maps x to y and this maps y to z, then the * result maps x to z. * @see #compose(JMLObjectToObjectMap) */ /*@ public normal_behavior @ requires othMap != null; @ ensures (\forall JMLValueValuePair pair; ; @ \result.theRelation.has(pair) @ == (\exists Object val; @ othMap.elementImage(pair.key).has(val); @ this.elementImage(val).has(pair.value) @ ) @ ); @*/ public /*@ non_null @*/ JMLValueToValueMap compose(/*@ non_null @*/ JMLValueToObjectMap othMap) { return super.compose(othMap).toFunction(); } /** Return a new map that is the composition of this and the given * map. The composition is done in the usual order; that is, if * the given map maps x to y and this maps y to z, then the * result maps x to z. * @see #compose(JMLValueToObjectMap) */ /*@ public normal_behavior @ requires othMap != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == (\exists Object val; @ othMap.elementImage(pair.key).has(val); @ this.elementImage(val).has(pair.value) @ ) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap compose(/*@ non_null @*/ JMLObjectToObjectMap othMap) { return super.compose(othMap).toFunction(); } /** Return a new map that only maps elements in the given domain * to the corresponding range elements in this map. * @see #rangeRestrictedTo * @see JMLObjectToValueRelation#restrictDomainTo */ /*@ public normal_behavior @ requires dom != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ dom.has(pair.key) @ && elementImage(pair.key).has(pair.value) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap restrictedTo(/*@ non_null @*/ JMLObjectSet dom) { return super.restrictDomainTo(dom).toFunction(); } /** Return a new map that is like this map but only contains * associations that map to range elements in the given set. * @see #restrictedTo * @see JMLObjectToValueRelation#restrictRangeTo */ /*@ public normal_behavior @ requires rng != null; @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ rng.has(pair.value) @ && elementImage(pair.key).has(pair.value) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap rangeRestrictedTo(/*@ non_null @*/ JMLValueSet rng) { return super.restrictRangeTo(rng).toFunction(); } /** Return a new map that is like the union of the given map and * this map, except that if both define a mapping for a given domain * element, then only the mapping in the given map is retained. * @see #clashReplaceUnion * @see #disjointUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null; @ requires int_size() @ <= Integer.MAX_VALUE - othMap.difference(this).int_size(); @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ othMap.elementImage(pair.key).has(pair.value) @ || (!othMap.isDefinedAt(pair.key) @ && this.elementImage(pair.key).has(pair.value)) @ ); @*/ public /*@ non_null @*/ JMLObjectToValueMap extendUnion(/*@ non_null @*/ JMLObjectToValueMap othMap) throws IllegalStateException { JMLObjectToValueMap newMap = this.restrictedTo(this.domain_.difference(othMap.domain_)); if (newMap.size_ <= Integer.MAX_VALUE - othMap.size_) { return new JMLObjectToValueMap(newMap.imagePairSet_ .union(othMap.imagePairSet_), newMap.domain_ .union(othMap.domain_), newMap.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } } /** Return a new map that is like the union of the given map and * this map, except that if both define a mapping for a given * domain element, then each of these clashes is replaced by a * mapping from the domain element in question to the given range * element. * @param othMap the other map. * @param errval the range element to use when clashes occur. * @see #extendUnion * @see #disjointUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null && errval != null; @ requires int_size() @ <= Integer.MAX_VALUE - othMap.difference(this).int_size(); @ ensures (\forall JMLObjectValuePair pair; ; @ \result.theRelation.has(pair) @ == @ (!othMap.isDefinedAt(pair.key) @ && this.elementImage(pair.key).has(pair.value)) @ || (!this.isDefinedAt(pair.key) @ && othMap.elementImage(pair.key) @ .has(pair.value)) @ || (this.isDefinedAt(pair.key) @ && othMap.isDefinedAt(pair.key) @ && pair.value .equals(errval)) @ ); @ implies_that @ requires othMap != null && errval != null; @*/ public /*@ non_null @*/ JMLObjectToValueMap clashReplaceUnion(JMLObjectToValueMap othMap, JMLType errval) throws IllegalStateException { JMLObjectSet overlap = this.domain_.intersection(othMap.domain_); Enumeration overlapEnum = overlap.elements(); othMap = othMap.restrictedTo(othMap.domain_.difference(overlap)); JMLObjectToValueMap newMap = this.restrictedTo(this.domain_.difference(overlap)); JMLObjectToValueRelation newRel; if (newMap.size_ <= Integer.MAX_VALUE - othMap.size_) { newRel = new JMLObjectToValueRelation(newMap.imagePairSet_ .union(othMap .imagePairSet_), newMap.domain_ .union(othMap.domain_), newMap.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } Object dv; while (overlapEnum.hasMoreElements()) { //@ assume overlapEnum.moreElements; Object oo = overlapEnum.nextElement(); //@ assume oo != null && oo instanceof Object; dv = oo; newRel = newRel.add(dv, errval); } return newRel.toFunction(); } //@ nowarn Exception; /** Return a map that is the disjoint union of this and othMap. * @param othMap the other mapping * @exception JMLMapException the ranges of this and othMap have elements * in common (i.e., when they interesect). * @see #extendUnion * @see #clashReplaceUnion * @see JMLObjectToValueRelation#union */ /*@ public normal_behavior @ requires othMap != null @ && this.domain().intersection(othMap.domain()).isEmpty(); @ requires int_size() <= Integer.MAX_VALUE - othMap.int_size(); @ ensures \result.equals(this.union(othMap)); @ also @ public exceptional_behavior @ requires othMap != null @ && !this.domain().intersection(othMap.domain()).isEmpty(); @ signals_only JMLMapException; @*/ public /*@ non_null @*/ JMLObjectToValueMap disjointUnion(/*@ non_null @*/ JMLObjectToValueMap othMap) throws JMLMapException, IllegalStateException { JMLObjectSet overlappingDom = domain_.intersection(othMap.domain_); if (overlappingDom.isEmpty()) { if (this.size_ <= Integer.MAX_VALUE - othMap.size_) { return new JMLObjectToValueMap(this.imagePairSet_ .union(othMap .imagePairSet_), this.domain_ .union(othMap.domain_), this.size_ + othMap.size_); } else { throw new IllegalStateException(TOO_BIG_TO_UNION); } } else { throw new JMLMapException("Overlapping domains in " + " disjointUnion operation", overlappingDom); } } }
shunghsiyu/OpenJML_XOR
OpenJML/runtime/org/jmlspecs/models/JMLObjectToValueMap.java
Java
gpl-2.0
20,391
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script src="<?php echo base_url();?>themes/poverty/js/html5placeholder.jquery.js"></script> <script language="javascript"> jQuery(function(){ jQuery(':input[placeholder]').placeholder(); $( "#dp1" ).datepicker({ showOn: "button", buttonImage: "<?php echo base_url();?>themes/poverty/images/calender_icon.gif", buttonImageOnly: true, minDate: 0, dateFormat: 'yy-mm-dd' }); }); </script> <!-- Start: Content Part --> <div id="content"> <div class="lsize"> <div class="post_a_req"> <div class="l_panel"> <ul class="list_02"> <?php if($this->session->userdata('post_request_approval')==1):?> <li class="active"><a href="<?php echo site_url('/post_a_request/');?>">Post a Request</a></li> <li><a href="<?php echo site_url('/request_published/');?>">Request Published </a></li> <?php endif;?> <?php if($this->session->userdata('dir_approval')==1):?> <li><a href="<?php echo site_url('/directory_page/submit_details/');?>">Submit Directory Listing</a></li> <li><a href="<?php echo site_url('/directory_page/manage_listing/');?>">Manage Directory LIsting </a></li> <?php endif;?> <li><a href="<?php echo site_url('/manage_account/');?>">Manage Account</a></li> <li><a href="<?php echo site_url('/notifications/');?>">Notifications</a></li> </ul> </div> <div class="r_panel"> <div class="content_bg"> <div class="bor_02"> <div class="bor_02"> <div class="bor_02"> <h3>Post a <b>request</b><br /> <span>Want to sign up fill out this form!</span></h3> <div class="text_part form"> <?php if (isset($request_form_errors)):echo "<div id='error'>".$request_form_errors."</div>";endif; ?> <form method="post" action="<?php echo site_url('/post_a_request/submit/');?>" name="frm_Post_A_Request" enctype="multipart/form-data"> <div class="col_01"> <label>Name of Request <input type="text" class="input" id="txtNameOfRequest" name="txtNameOfRequest" placeholder="e.g. A Winter Jacket For A Child" value="<?php echo set_value('txtNameOfRequest');?>" /> </label> <label>Description <textarea name="txtDescription" id="txtDescription" cols="" rows="" class="hei_02"><?php echo set_value('txtDescription');?></textarea> </label> <label>Security Code <?php echo $recaptcha_html; ?></label> </div> <div class="col_01"> <label>Photo <input type="file" size="35" tabindex="5" name="filePhoto" id="filePhoto"/> </label> <label>Quantity Required <input type="text" class="input" placeholder="Type required quantity" id="txtQuantity" name="txtQuantity" value="<?php echo set_value('txtQuantity');?>" /> </label> <label>Deadline <input type="text" class="input" readonly="readonly" name="txtDeadline" placeholder="Select last date" value="<?php echo set_value('txtDeadline');?>" style="width:80%;" id="dp1"/> </label> </div> <div class="clear"></div> <input type="Submit" value="Post a Request" /> </form> </div> </div> </div> </div> </div> </div> <div class="clear"></div> </div> <div id="social_media"> <ul> <li class="facebook"><a href="<?php echo get_setting('facebook_social_link');?>" target="_blank">Facebook</a></li> <li class="twitter"><a href="<?php echo get_setting('twitter_social_link');?>" target="_blank">Twitter</a></li> <li class="g_plus"><a href="<?php echo get_setting('google_social_link');?>" target="_blank">Google Plus</a></li> <li class="you_tube"><a href="<?php echo get_setting('youtube_social_link');?>" target="_blank">You Tube</a></li> </ul> <div class="clear"></div> </div> </div> </div> <!-- End: Content Part -->
bhupindersingh/lloh.co.uk
application/frontend/views/poverty/post_a_request.php
PHP
gpl-2.0
4,868
////////////////////////////////////////////////////////////////////////////// // Copyright 2004-2014, SenseGraphics AB // // This file is part of H3D API. // // H3D API 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. // // H3D API 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 H3D API; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // A commercial license is also available. Please contact us at // www.sensegraphics.com for more information. // // /// \file FreeImageLoader.cpp /// \brief CPP file for FreeImageLoader, a image loader using the FreeImage /// library to read images. /// // ////////////////////////////////////////////////////////////////////////////// #include <H3D/FreeImageLoader.h> #ifdef HAVE_FREEIMAGE #include <H3DUtil/FreeImageImage.h> #include <FreeImage.h> using namespace H3D; // Add this node to the H3DNodeDatabase system. H3DNodeDatabase FreeImageLoader::database( "FreeImageLoader", &(newInstance<FreeImageLoader>), typeid( FreeImageLoader ) ); H3DImageLoaderNode::FileReaderRegistration FreeImageLoader::reader_registration( "FreeImageLoader", &(newImageLoaderNode< FreeImageLoader >), &FreeImageLoader::supportsFileType, &FreeImageLoader::supportsStreamType ); bool FreeImageLoader::supportsFileType( const string &url ) { FREE_IMAGE_FORMAT format = FreeImage_GetFileType( url.c_str() ); return format != FIF_UNKNOWN; } bool FreeImageLoader::supportsStreamType( istream &is ) { FREE_IMAGE_FORMAT format = FreeImage_GetFileTypeFromHandle ( FreeImageImage::getIStreamIO(), static_cast<fi_handle>(&is) ); return format != FIF_UNKNOWN; } #endif // HAVE_FREEIMAGE
JakeFountain/H3DAPIwithOculusSupport
src/FreeImageLoader.cpp
C++
gpl-2.0
2,411
๏ปฟ<?php /* Copyright 2005 Flรกvio Ribeiro This file is part of OCOMON. OCOMON 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. OCOMON 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 Foobar; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */session_start(); include ("../../includes/include_geral.inc.php"); include ("../../includes/include_geral_II.inc.php"); include ('includes/header.php'); $_SESSION['s_page_invmon'] = $_SERVER['PHP_SELF']; $cab = new headers; $cab->set_title(TRANS('TTL_INVMON')); $auth = new auth; $auth->testa_user($_SESSION['s_usuario'],$_SESSION['s_nivel'],$_SESSION['s_nivel_desc'],2); $hoje = date("Y-m-d H:i:s"); $cor = TD_COLOR; $cor1 = TD_COLOR; $cor3 = BODY_COLOR; $query = $QRY["vencimentos_full"]; $result = mysql_query($query); //----------------TABELA -----------------// print "<br><br><p align='center'>".TRANS('TTL_PREVIEWS_EXP_GUARANTEE_FULL').": <a href='estat_vencimentos.php'>".TRANS('SHOW_ONLY_3_YEARS')."</a></p>"; print "<table cellspacing='0' border='1' align='center' style=\"{border-collapse:collapse;}\">"; print "<tr><td ><b>".TRANS('COL_DATE_2')."</b></td><td ><b>".TRANS('COL_AMOUNT')."</b></td><td ><b>".TRANS('COL_TYPE_2')."</b></td><td ><b>".TRANS('COL_MODEL_2')."</b></td></tr>"; //-----------------FINAL DA TABELA -----------------------// $tt_garant = 0; while ($row=mysql_fetch_array($result)) { $temp1 = explode(" ",$row['vencimento']); $temp = explode(" ",datab($row['vencimento'])); $vencimento1 = $temp1[0]; $vencimento = $temp[0]; $tt_garant+= $row['quantidade']; print "<tr><td ><a onClick=\"popup('mostra_consulta_comp.php?VENCIMENTO=".$vencimento1."')\">".$vencimento."</a></td>". "<td align='center'><a onClick=\"popup('mostra_consulta_comp.php?VENCIMENTO=".$vencimento1."')\">".$row['quantidade']."</a></td>". "<td >".$row['tipo']."</td><td >".$row['fabricante']." ".$row['modelo']."</td></tr>"; } // while print "<tr><td ><b>".TRANS('COL_OVERALL')."</b></td><td colspan='3'><b>".$tt_garant."</b></td></tr>"; print "</table><br><br>"; print "<TABLE width='80%' align='center'>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td ></TD></tr>"; print "<tr><td width='80%' align='center'><b>".TRANS('SLOGAN_OCOMON')." <a href='http://www.yip.com.br' target='_blank'>".TRANS('COMPANY')."</a>.</b></td></tr>"; print "</TABLE>"; print "</BODY>"; print "</HTML>"; ?>
danfmsouza/yipservicedesk
invmon/geral/estat_vencimentos_full.php
PHP
gpl-2.0
3,077
<? $sub_menu = "300100"; include_once('./_common.php'); if ($w == 'u') check_demo(); auth_check($auth[$sub_menu], 'w'); if ($_POST['admin_password']) { if ($member['mb_password'] != sql_password($_POST['admin_password'])) { alert('๊ด€๋ฆฌ์ž ํŒจ์Šค์›Œ๋“œ๊ฐ€ ํ‹€๋ฆฝ๋‹ˆ๋‹ค.'); } } else { alert('๊ด€๋ฆฌ์ž ํŒจ์Šค์›Œ๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.'); } if (!$_POST['gr_id']) { alert('๊ทธ๋ฃน ID๋Š” ๋ฐ˜๋“œ์‹œ ์„ ํƒํ•˜์„ธ์š”.'); } if (!$bo_table) { alert('๊ฒŒ์‹œํŒ TABLE๋ช…์€ ๋ฐ˜๋“œ์‹œ ์ž…๋ ฅํ•˜์„ธ์š”.'); } if (!preg_match("/^([A-Za-z0-9_]{1,20})$/", $bo_table)) { alert('๊ฒŒ์‹œํŒ TABLE๋ช…์€ ๊ณต๋ฐฑ์—†์ด ์˜๋ฌธ์ž, ์ˆซ์ž, _ ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. (20์ž ์ด๋‚ด)'); } if (!$_POST['bo_subject']) { alert('๊ฒŒ์‹œํŒ ์ œ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”.'); } if ($file = $_POST['bo_include_head']) { if (!preg_match("/\.(php|htm['l']?)$/i", $file)) { alert('์ƒ๋‹จ ํŒŒ์ผ ๊ฒฝ๋กœ๊ฐ€ php, html ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.'); } } if ($file = $_POST['bo_include_tail']) { if (!preg_match("/\.(php|htm['l']?)$/i", $file)) { alert('ํ•˜๋‹จ ํŒŒ์ผ ๊ฒฝ๋กœ๊ฐ€ php, html ํŒŒ์ผ์ด ์•„๋‹™๋‹ˆ๋‹ค.'); } } $board_path = G4_DATA_PATH.'/file/'.$bo_table; // ๊ฒŒ์‹œํŒ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ @mkdir($board_path, 0707); @chmod($board_path, 0707); // ๋””๋ ‰ํ† ๋ฆฌ์— ์žˆ๋Š” ํŒŒ์ผ์˜ ๋ชฉ๋ก์„ ๋ณด์ด์ง€ ์•Š๊ฒŒ ํ•œ๋‹ค. $file = $board_path . '/index.php'; $f = @fopen($file, 'w'); @fwrite($f, ''); @fclose($f); @chmod($file, 0606); // ๋ถ„๋ฅ˜์— & ๋‚˜ = ๋Š” ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€ํ•˜๋ฏ€๋กœ 2๋ฐ”์ดํŠธ๋กœ ๋ฐ”๊พผ๋‹ค. $src_char = array('&', '='); $dst_char = array('๏ผ†', 'ใ€“'); $bo_category_list = str_replace($src_char, $dst_char, $bo_category_list); $sql_common = " gr_id = '{$_POST['gr_id']}', bo_subject = '{$_POST['bo_subject']}', bo_device = '{$_POST['bo_device']}', bo_admin = '{$_POST['bo_admin']}', bo_list_level = '{$_POST['bo_list_level']}', bo_read_level = '{$_POST['bo_read_level']}', bo_write_level = '{$_POST['bo_write_level']}', bo_reply_level = '{$_POST['bo_reply_level']}', bo_comment_level = '{$_POST['bo_comment_level']}', bo_html_level = '{$_POST['bo_html_level']}', bo_link_level = '{$_POST['bo_link_level']}', bo_count_modify = '{$_POST['bo_count_modify']}', bo_count_delete = '{$_POST['bo_count_delete']}', bo_upload_level = '{$_POST['bo_upload_level']}', bo_download_level = '{$_POST['bo_download_level']}', bo_read_point = '{$_POST['bo_read_point']}', bo_write_point = '{$_POST['bo_write_point']}', bo_comment_point = '{$_POST['bo_comment_point']}', bo_download_point = '{$_POST['bo_download_point']}', bo_use_category = '{$_POST['bo_use_category']}', bo_category_list = '{$_POST['bo_category_list']}', bo_use_sideview = '{$_POST['bo_use_sideview']}', bo_use_file_content = '{$_POST['bo_use_file_content']}', bo_use_secret = '{$_POST['bo_use_secret']}', bo_use_dhtml_editor = '{$_POST['bo_use_dhtml_editor']}', bo_use_rss_view = '{$_POST['bo_use_rss_view']}', bo_use_good = '{$_POST['bo_use_good']}', bo_use_nogood = '{$_POST['bo_use_nogood']}', bo_use_name = '{$_POST['bo_use_name']}', bo_use_signature = '{$_POST['bo_use_signature']}', bo_use_ip_view = '{$_POST['bo_use_ip_view']}', bo_use_list_view = '{$_POST['bo_use_list_view']}', bo_use_list_content = '{$_POST['bo_use_list_content']}', bo_use_email = '{$_POST['bo_use_email']}', bo_table_width = '{$_POST['bo_table_width']}', bo_subject_len = '{$_POST['bo_subject_len']}', bo_page_rows = '{$_POST['bo_page_rows']}', bo_new = '{$_POST['bo_new']}', bo_hot = '{$_POST['bo_hot']}', bo_image_width = '{$_POST['bo_image_width']}', bo_skin = '{$_POST['bo_skin']}', bo_include_head = '{$_POST['bo_include_head']}', bo_include_tail = '{$_POST['bo_include_tail']}', bo_content_head = '{$_POST['bo_content_head']}', bo_content_tail = '{$_POST['bo_content_tail']}', bo_insert_content = '{$_POST['bo_insert_content']}', bo_gallery_cols = '{$_POST['bo_gallery_cols']}', bo_upload_count = '{$_POST['bo_upload_count']}', bo_upload_size = '{$_POST['bo_upload_size']}', bo_reply_order = '{$_POST['bo_reply_order']}', bo_use_search = '{$_POST['bo_use_search']}', bo_order_search = '{$_POST['bo_order_search']}', bo_write_min = '{$_POST['bo_write_min']}', bo_write_max = '{$_POST['bo_write_max']}', bo_comment_min = '{$_POST['bo_comment_min']}', bo_comment_max = '{$_POST['bo_comment_max']}', bo_sort_field = '{$_POST['bo_sort_field']}', bo_1_subj = '{$_POST['bo_1_subj']}', bo_2_subj = '{$_POST['bo_2_subj']}', bo_3_subj = '{$_POST['bo_3_subj']}', bo_4_subj = '{$_POST['bo_4_subj']}', bo_5_subj = '{$_POST['bo_5_subj']}', bo_6_subj = '{$_POST['bo_6_subj']}', bo_7_subj = '{$_POST['bo_7_subj']}', bo_8_subj = '{$_POST['bo_8_subj']}', bo_9_subj = '{$_POST['bo_9_subj']}', bo_10_subj = '{$_POST['bo_10_subj']}', bo_1 = '{$_POST['bo_1']}', bo_2 = '{$_POST['bo_2']}', bo_3 = '{$_POST['bo_3']}', bo_4 = '{$_POST['bo_4']}', bo_5 = '{$_POST['bo_5']}', bo_6 = '{$_POST['bo_6']}', bo_7 = '{$_POST['bo_7']}', bo_8 = '{$_POST['bo_8']}', bo_9 = '{$_POST['bo_9']}', bo_10 = '{$_POST['bo_10']}' "; if ($w == '') { $row = sql_fetch(" select count(*) as cnt from {$g4['board_table']} where bo_table = '{$bo_table}' "); if ($row['cnt']) alert($bo_table.' ์€(๋Š”) ์ด๋ฏธ ์กด์žฌํ•˜๋Š” TABLE ์ž…๋‹ˆ๋‹ค.'); $sql = " insert into {$g4['board_table']} set bo_table = '{$bo_table}', bo_count_write = '0', bo_count_comment = '0', $sql_common "; sql_query($sql); // ๊ฒŒ์‹œํŒ ํ…Œ์ด๋ธ” ์ƒ์„ฑ $file = file('./sql_write.sql'); $sql = implode($file, "\n"); $create_table = $g4['write_prefix'] . $bo_table; // sql_board.sql ํŒŒ์ผ์˜ ํ…Œ์ด๋ธ”๋ช…์„ ๋ณ€ํ™˜ $source = array('/__TABLE_NAME__/', '/;/'); $target = array($create_table, ''); $sql = preg_replace($source, $target, $sql); sql_query($sql, FALSE); } else if ($w == 'u') { // ๊ฒŒ์‹œํŒ์˜ ๊ธ€ ์ˆ˜ $sql = " select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 0 "; $row = sql_fetch($sql); $bo_count_write = $row['cnt']; // ๊ฒŒ์‹œํŒ์˜ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜ $sql = " select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 1 "; $row = sql_fetch($sql); $bo_count_comment = $row['cnt']; // ๊ธ€์ˆ˜ ์กฐ์ • if (isset($_POST['proc_count'])) { // ์›๊ธ€์„ ์–ป์Šต๋‹ˆ๋‹ค. $sql = " select wr_id from {$g4['write_prefix']}{$bo_table} where wr_is_comment = 0 "; $result = sql_query($sql); for ($i=0; $row=sql_fetch_array($result); $i++) { // ์ฝ”๋ฉ˜ํŠธ์ˆ˜๋ฅผ ์–ป์Šต๋‹ˆ๋‹ค. $sql2 = " select count(*) as cnt from {$g4['write_prefix']}$bo_table where wr_parent = '{$row['wr_id']}' and wr_is_comment = 1 "; $row2 = sql_fetch($sql2); sql_query(" update {$g4['write_prefix']}{$bo_table} set wr_comment = '{$row2['cnt']}' where wr_id = '{$row['wr_id']}' "); } } // ๊ณต์ง€์‚ฌํ•ญ์—๋Š” ๋“ฑ๋ก๋˜์–ด ์žˆ์ง€๋งŒ ์‹ค์ œ ์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ธ€ ์•„์ด๋””๋Š” ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. $bo_notice = ""; $lf = ""; if ($board['bo_notice']) { $tmp_array = explode("\n", $board['bo_notice']); for ($i=0; $i<count($tmp_array); $i++) { $tmp_wr_id = trim($tmp_array[$i]); $row = sql_fetch(" select count(*) as cnt from {$g4['write_prefix']}{$bo_table} where wr_id = '{$tmp_wr_id}' "); if ($row['cnt']) { $bo_notice .= $lf . $tmp_wr_id; $lf = "\n"; } } } $sql = " update {$g4['board_table']} set bo_notice = '{$bo_notice}', bo_count_write = '{$bo_count_write}', bo_count_comment = '{$bo_count_comment}', {$sql_common} where bo_table = '{$bo_table}' "; sql_query($sql); } // ๊ฐ™์€ ๊ทธ๋ฃน๋‚ด ๊ฒŒ์‹œํŒ ๋™์ผ ์˜ต์…˜ ์ ์šฉ $fields = ""; if (is_checked('chk_use')) $fields .= " , bo_use = '{$bo_use}' "; if (is_checked('chk_admin')) $fields .= " , bo_admin = '{$bo_admin}' "; if (is_checked('chk_list_level')) $fields .= " , bo_list_level = '{$bo_list_level}' "; if (is_checked('chk_read_level')) $fields .= " , bo_read_level = '{$bo_read_level}' "; if (is_checked('chk_write_level')) $fields .= " , bo_write_level = '{$bo_write_level}' "; if (is_checked('chk_reply_level')) $fields .= " , bo_reply_level = '{$bo_reply_level}' "; if (is_checked('chk_comment_level')) $fields .= " , bo_comment_level = '{$bo_comment_level}' "; if (is_checked('chk_link_level')) $fields .= " , bo_link_level = '{$bo_link_level}' "; if (is_checked('chk_upload_level')) $fields .= " , bo_upload_level = '{$bo_upload_level}' "; if (is_checked('chk_download_level')) $fields .= " , bo_download_level = '{$bo_download_level}' "; if (is_checked('chk_html_level')) $fields .= " , bo_html_level = '{$bo_html_level}' "; if (is_checked('chk_count_modify')) $fields .= " , bo_count_modify = '{$bo_count_modify}' "; if (is_checked('chk_count_delete')) $fields .= " , bo_count_delete = '{$bo_count_delete}' "; if (is_checked('chk_read_point')) $fields .= " , bo_read_point = '{$bo_read_point}' "; if (is_checked('chk_write_point')) $fields .= " , bo_write_point = '{$bo_write_point}' "; if (is_checked('chk_comment_point')) $fields .= " , bo_comment_point = '{$bo_comment_point}' "; if (is_checked('chk_download_point')) $fields .= " , bo_download_point = '{$bo_download_point}' "; if (is_checked('chk_category_list')) { $fields .= " , bo_category_list = '{$bo_category_list}' "; $fields .= " , bo_use_category = '{$bo_use_category}' "; } if (is_checked('chk_use_sideview')) $fields .= " , bo_use_sideview = '{$bo_use_sideview}' "; if (is_checked('chk_use_file_content')) $fields .= " , bo_use_file_content = '{$bo_use_file_content}' "; if (is_checked('chk_use_secret')) $fields .= " , bo_use_secret = '{$bo_use_secret}' "; if (is_checked('chk_use_dhtml_editor')) $fields .= " , bo_use_dhtml_editor = '{$bo_use_dhtml_editor}' "; if (is_checked('chk_use_rss_view')) $fields .= " , bo_use_rss_view = '{$bo_use_rss_view}' "; if (is_checked('chk_use_good')) $fields .= " , bo_use_good = '{$bo_use_good}' "; if (is_checked('chk_use_nogood')) $fields .= " , bo_use_nogood = '{$bo_use_nogood}' "; if (is_checked('chk_use_name')) $fields .= " , bo_use_name = '{$bo_use_name}' "; if (is_checked('chk_use_signature')) $fields .= " , bo_use_signature = '{$bo_use_signature}' "; if (is_checked('chk_use_ip_view')) $fields .= " , bo_use_ip_view = '{$bo_use_ip_view}' "; if (is_checked('chk_use_list_view')) $fields .= " , bo_use_list_view = '{$bo_use_list_view}' "; if (is_checked('chk_use_list_content')) $fields .= " , bo_use_list_content = '{$bo_use_list_content}' "; if (is_checked('chk_use_email')) $fields .= " , bo_use_email = '{$bo_use_email}' "; if (is_checked('chk_skin')) $fields .= " , bo_skin = '{$bo_skin}' "; if (is_checked('chk_gallery_cols')) $fields .= " , bo_gallery_cols = '{$bo_gallery_cols}' "; if (is_checked('chk_table_width')) $fields .= " , bo_table_width = '{$bo_table_width}' "; if (is_checked('chk_page_rows')) $fields .= " , bo_page_rows = '{$bo_page_rows}' "; if (is_checked('chk_subject_len')) $fields .= " , bo_subject_len = '{$bo_subject_len}' "; if (is_checked('chk_new')) $fields .= " , bo_new = '{$bo_new}' "; if (is_checked('chk_hot')) $fields .= " , bo_hot = '{$bo_hot}' "; if (is_checked('chk_image_width')) $fields .= " , bo_image_width = '{$bo_image_width}' "; if (is_checked('chk_reply_order')) $fields .= " , bo_reply_order = '{$bo_reply_order}' "; if (is_checked('chk_sort_field')) $fields .= " , bo_sort_field = '{$bo_sort_field}' "; if (is_checked('chk_write_min')) $fields .= " , bo_write_min = '{$bo_write_min}' "; if (is_checked('chk_write_max')) $fields .= " , bo_write_max = '{$bo_write_max}' "; if (is_checked('chk_comment_min')) $fields .= " , bo_comment_min = '{$bo_comment_min}' "; if (is_checked('chk_comment_max')) $fields .= " , bo_comment_max = '{$bo_comment_max}' "; if (is_checked('chk_upload_count')) $fields .= " , bo_upload_count = '{$bo_upload_count}' "; if (is_checked('chk_upload_size')) $fields .= " , bo_upload_size = '{$bo_upload_size}' "; if (is_checked('chk_include_head')) $fields .= " , bo_include_head = '{$bo_include_head}' "; if (is_checked('chk_include_tail')) $fields .= " , bo_include_tail = '{$bo_include_tail}' "; if (is_checked('chk_content_head')) $fields .= " , bo_content_head = '{$bo_content_head}' "; if (is_checked('chk_content_tail')) $fields .= " , bo_content_tail = '{$bo_content_tail}' "; if (is_checked('chk_insert_content')) $fields .= " , bo_insert_content = '{$bo_insert_content}' "; if (is_checked('chk_use_search')) $fields .= " , bo_use_search = '{$bo_use_search}' "; if (is_checked('chk_order_search')) $fields .= " , bo_order_search = '{$bo_order_search}' "; for ($i=1; $i<=10; $i++) { if (is_checked('chk_'.$i)) { $fields .= " , bo_{$i}_subj = '".$_POST['bo_'.$i.'_subj']."' "; $fields .= " , bo_{$i} = '".$_POST['bo_'.$i]."' "; } } if ($fields) { $sql = " update {$g4['board_table']} set bo_table = bo_table {$fields} where gr_id = '$gr_id' "; sql_query($sql); } delete_cache_latest($bo_table); goto_url("./board_form.php?w=u&bo_table={$bo_table}&amp;{$qstr}"); ?>
gnuboard/sanso
adm/board_form_update.php
PHP
gpl-2.0
15,251
package com.wernicke.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(params); httpPost.setEntity(uefe); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString() + json); } // return JSON String return jObj; } }
3ch01c/heracles
android/src/com/wernicke/utils/JSONParser.java
Java
gpl-2.0
2,870
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER */ #include <threads/TestThreads_Category.hpp> #include <TestViewMapping_a.hpp>
pastewka/lammps
lib/kokkos/core/unit_test/threads/TestThreads_ViewMapping_a.cpp
C++
gpl-2.0
2,057
๏ปฟusing System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Integration.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyProduct("Integration.Tests")] [assembly: AssemblyCopyright("Copyright ยฉ Hewlett-Packard Company 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("43c64bba-2946-4a18-9874-d1e05c2e10ad")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
12-South-Studios/realmmud
Source/Database/Integration.Tests/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,417
package com.example.gramos.raportiti; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; import static android.location.LocationManager.GPS_PROVIDER; @SuppressLint("Registered") public class GPSTracker extends Service implements LocationListener { private final Context aContext; // GPS status private boolean canGetLocation = false; private Location location; // location(lokacioni) private double latitude; // latitude(gjeresia) private double longitude; // longitude(gjatesia) // The minimum distance to change Updates in meters (distanca minimale per me e ba update coor.) private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds (koha minimale qe duhet me ba update) private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute public GPSTracker(Context context){ this.aContext = context; getLocation(); } @SuppressWarnings("UnusedReturnValue") private Location getLocation(){ try { LocationManager locationManager = (LocationManager) aContext.getSystemService(LOCATION_SERVICE); // getting GPS status boolean isGPSEnabled = locationManager.isProviderEnabled(GPS_PROVIDER); // getting network status boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); //noinspection StatementWithEmptyBody if(!isGPSEnabled && !isNetworkEnabled){ // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); } // if GPS Enabled get lat/long using GPS services if(isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); location = locationManager.getLastKnownLocation(GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e){ e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } */ /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will launch Settings Options **/ public void showOneButtonDialog(){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(aContext); // setting dialog title dialogBuilder.setTitle("GPS is required!"); // setting dialog message dialogBuilder.setMessage("Please, go to the Settings button. Hurry up :)!! "); dialogBuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); aContext.startActivity(intent); } }); // on pressing cancel button dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // showing alert message dialogBuilder.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public IBinder onBind(Intent intent) { return null; } }
opendatakosovo/android-dev
RaportiTi/app/src/main/java/com/example/gramos/raportiti/GPSTracker.java
Java
gpl-2.0
6,019
if(typeof(simileTimeplot)=="undefined") { window.simileTimeplot = { records : [], js : {} }; // jQuery("head").append('<script src="http://api.simile-widgets.org/timeplot/1.1/timeplot-api.js"></script>'); } (function($) { var red = new Timeplot.Color('#B9121B'); var lightRed = new Timeplot.Color('#cc8080'); var blue = new Timeplot.Color('#193441'); var green = new Timeplot.Color('#468966'); var lightGreen = new Timeplot.Color('#5C832F'); var gridColor = new Timeplot.Color('#000000'); var timeGeometry = new Timeplot.DefaultTimeGeometry({ gridColor: gridColor, axisLabelsPlacement: "bottom" }); var valueGeometry = new Timeplot.DefaultValueGeometry({ gridColor: gridColor, axisLabelsPlacement: "left" }); var simileTimeplotResizeTimerID = null; var simileTimeplots = []; $(window).resize(function() { if (simileTimeplotResizeTimerID == null) { simileTimeplotResizeTimerID = window.setTimeout(function() { simileTimeplotResizeTimerID = null; for(var i=0;i<simileTimeplots.length;++i) { simileTimeplots[i].repaint(); } }, 300); } }); simileTimeplot.js = { SMWSimile_FillData : function(data, eventSource) { var evt = null, evts = new Array(); for(var i=0;i<data.length;++i) { evt = new Timeplot.DefaultEventSource.NumericEvent( SimileAjax.DateTime.parseIso8601DateTime(data[i].start),data[i].values); evts[i] = evt; } eventSource.addMany(evts); }, SMWSimile_FillEvent : function(data, eventSource) { var evt = null, evts = new Array(); for(var i=0;i<data.length;++i) { evt = new Timeline.DefaultEventSource.Event({ id: undefined, start: SimileAjax.DateTime.parseIso8601DateTime(data[i].start), end: data[i].end ? SimileAjax.DateTime.parseIso8601DateTime(data[i].end): null, text: data[i].title, link: data[i].link, description: data[i].description }); evt._obj = data[i]; evt.getProperty = function(name) { return this._obj[name]; }; evts[i] = evt; } eventSource.addMany(evts); }, renderTimeplot : function() { var plotInfo = []; var eventSource = null; var eventSourceEvt = null; for(var i=0;i<simileTimeplot.records.length;++i) { eventSource = new Timeplot.DefaultEventSource(); eventSourceEvt = new Timeplot.DefaultEventSource(); plotInfo.push( Timeplot.createPlotInfo({ id: "plotEvents" + i, eventSource: eventSourceEvt, timeGeometry: timeGeometry, lineColor: red }) ); for(var j=0;j<simileTimeplot.records[i].count;++j) { plotInfo.push( Timeplot.createPlotInfo({ id: "plot" + i + j, dataSource: new Timeplot.ColumnSource(eventSource, j + 1), valueGeometry: valueGeometry, lineColor: green, dotColor: lightGreen, timeGeometry: timeGeometry, showValues: true }) ); } simileTimeplots.push( Timeplot.create(document.getElementById(simileTimeplot.records[i].div), plotInfo) ); simileTimeplot.js.SMWSimile_FillData(simileTimeplot.records[i].data, eventSource); simileTimeplot.js.SMWSimile_FillEvent(simileTimeplot.records[i].data, eventSourceEvt); } } }; $(document).ready(function(){ simileTimeplot.js.renderTimeplot(); }); })(jQuery);
ontoprise/HaloSMWExtension
extensions/SRFPlus/Simile/scripts/Simile_TimeplotWiki.js
JavaScript
gpl-2.0
3,263
<?php /* core/themes/stable/templates/block/block--system-messages-block.html.twig */ class __TwigTemplate_886740968f827ac8f8ad8553cb8fe62217c4c4c2ec3a7a043b3d35b9acb03e84 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/stable/templates/block/block--system-messages-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 13,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for the messages block.*/ /* **/ /* * Removes wrapper elements from block so that empty block does not appear when*/ /* * there are no messages.*/ /* **/ /* * Available variables:*/ /* * - content: The content of this block.*/ /* *//* */ /* #}*/ /* {{ content }}*/ /* */
nhinq/drupal8
sites/default/files/php/twig/f4bf8926_block--system-messages-block.html.twig_7a0dc1dc8ea56b701f7e4dd579608cdd9d8ad000d4a12d7ea6ca73e50dbb13dd/82014522767b3de45407812e92ff9e01963812469ce6e716fdb44803f716dc8f.php
PHP
gpl-2.0
2,313
package com.fantasia.core; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { // ๅ…จๅฑ€ๆ•ฐ็ป„ private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public MD5() { } // ่ฟ”ๅ›žๅฝขๅผไธบๆ•ฐๅญ—่ทŸๅญ—็ฌฆไธฒ private static String byteToArrayString(byte bByte) { int iRet = bByte; // System.out.println("iRet="+iRet); if (iRet < 0) { iRet += 256; } int iD1 = iRet / 16; int iD2 = iRet % 16; return strDigits[iD1] + strDigits[iD2]; } // ่ฝฌๆขๅญ—่Š‚ๆ•ฐ็ป„ไธบ16่ฟ›ๅˆถๅญ—ไธฒ private static String byteToString(byte[] bByte) { StringBuffer sBuffer = new StringBuffer(); for (int i = 0; i < bByte.length; i++) { sBuffer.append(byteToArrayString(bByte[i])); } return sBuffer.toString(); } public static String GetMD5Code(String strObj) { String resultString = null; try { resultString = new String(strObj); MessageDigest md = MessageDigest.getInstance("MD5"); // md.digest() ่ฏฅๅ‡ฝๆ•ฐ่ฟ”ๅ›žๅ€ผไธบๅญ˜ๆ”พๅ“ˆๅธŒๅ€ผ็ป“ๆžœ็š„byteๆ•ฐ็ป„ resultString = byteToString(md.digest(strObj.getBytes())); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return resultString; } }
jiangrenwen/KPI
kpi/src/main/java/com/fantasia/core/MD5.java
Java
gpl-2.0
1,314
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'feature-image' ); $url = $thumb['0']; ?> <div class="feature-image overlay-black" style="background-image: url(<?=$url?>);"> <div class="page-banner"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1 class="text-reverse text-uppercase" style="margin:0;">Digital Government Transformation</h1> </div> </div> </div> </div> <div class="vertical-center"> <div class="container"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <h1 class="entry-title text-reverse text-center"><?php the_title(); ?></h1> </div> </div> </div> </div> <?php echo do_shortcode('[image-attribution]'); ?> </div> <section class="content"> <div class="container"> <div class="row"> <div class="col-sm-8"> <?php while (have_posts()) : the_post(); ?> <article <?php post_class(); ?>> <div class="social-sharing"> <?php echo do_shortcode('[marketo-share-custom]');?> </div> <div class="entry-meta"> <p class="hidden-sm hidden-md hidden-lg">By <span><?php if(function_exists('coauthors')) coauthors();?></span> / <?php the_time('F j, Y') ?> / <?php Roots\Sage\Extras\blog_the_categories(); ?></p> <ul class="hidden-xs"> <li class="categories"> <?php $categories = get_the_category(); $separator = ', '; $output = ''; if ( ! empty( $categories ) ) { foreach( $categories as $category ) { $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator; } echo trim( $output, $separator ); } ?> </li> <li class="date"><?php the_time('F j, Y') ?></li> <?php global $post; $author_id=$post->post_author; foreach( get_coauthors() as $coauthor ): ?> <li class="headshot"><?php echo get_avatar( $coauthor->user_email, '50' ); ?></li> <li class="author">By <?php echo $coauthor->display_name; ?></li> <?php endforeach; ?> </ul> </div> <?php the_content(); ?> <hr/> <div class="row next-prev-posts"> <?php $prev_post = get_previous_post(); if (!empty( $prev_post )): ?> <div class="col-sm-6"> <div class="margin-bottom-15 thumb"><span>Next Article</span><a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_post_thumbnail($prev_post->ID, 'post-thumbnail', array('class'=>'img-responsive')); ?></a></div> <div class="category-name"> <?php $cats = get_the_category( $prev_post->ID ); echo $cats[0]->cat_name; for ($i = 1; $i < count($cats); $i++) {echo ', ' . $cats[$i]->cat_name ;} ?> </div> <h5><a href="<?php echo get_permalink( $prev_post->ID ); ?>"><?php echo get_the_title( $prev_post->ID ); ?></a></h5> <p><small><?php echo get_the_time( 'F j, Y', $prev_post->ID ); ?></small></p> </div> <?php endif; ?> <?php $next_post = get_next_post(); if (!empty( $next_post )): ?> <div class="col-sm-6"> <div class="margin-bottom-15 thumb"><span>Previous Article</span><a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_post_thumbnail($next_post->ID, 'post-thumbnail', array('class'=>'img-responsive')); ?></a></div> <div class="category-name"> <?php $cats = get_the_category( $next_post->ID ); echo $cats[0]->cat_name; for ($i = 1; $i < count($cats); $i++) {echo ', ' . $cats[$i]->cat_name ;} ?> </div> <h5><a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo get_the_title( $next_post->ID ); ?></a></h5> <p><small><?php echo get_the_time( 'F j, Y', $next_post->ID ); ?></small></p> </div> <?php endif; ?> </div> <!-- Begin Outbrain --> <div class="OUTBRAIN hidden-xs" data-widget-id="NA"></div> <script type="text/javascript" async="async" src="https://widgets.outbrain.com/outbrain.js"></script> </article> <?php endwhile; ?> </div> <div class="col-sm-4 hidden-xs"> <?php echo do_shortcode('[newsletter-sidebar]'); ?> <?php $args = array( 'post_type' => 'post', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Articles</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); $url = $thumb['0'];?> <li> <div class="article-img-container"> <img src="<?=$url?>" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br><small><?php the_time('F j, Y') ?></small> </div> </li> <?php } } echo '<li><a href="/digital-government-transformation">View All Articles <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $args = array( 'post_type' => 'socrata_videos', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Videos</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <li> <div class="article-img-container"> <img src="https://img.youtube.com/vi/<?php $meta = get_socrata_videos_meta(); echo $meta[1]; ?>/default.jpg" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li> <?php } } echo '<li><a href="/videos">View All Videos <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $args = array( 'post_type' => 'case_study', 'order' => 'desc', 'posts_per_page' => 3, 'post_status' => 'publish', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Recent Case Studies</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); $url = $thumb['0'];?> <li> <div class="article-img-container"> <img src="<?=$url?>" class="img-responsive"> </div> <div class="article-title-container"> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> </div> </li> <?php } } echo '<li><a href="/case-studies">View All Case Studies <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { // no posts found } /* Restore original Post Data */ wp_reset_postdata(); ?> <?php $today = strtotime('today UTC'); $event_meta_query = array( 'relation' => 'AND', array( 'key' => 'socrata_events_endtime', 'value' => $today, 'compare' => '>=', ) ); $args = array( 'post_type' => 'socrata_events', 'posts_per_page' => 3, 'post_status' => 'publish', 'ignore_sticky_posts' => true, 'meta_key' => 'socrata_events_endtime', 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_query' => $event_meta_query ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { echo '<ul class="no-bullets sidebar-list">'; echo '<li><h5>Upcoming Events</h5></li>'; while ( $the_query->have_posts() ) { $the_query->the_post(); { ?> <?php if ( has_term( 'socrata-event','socrata_events_cat' ) ) { ?> <li><small style="text-transform: uppercase;"><?php events_the_categories(); ?></small><br><a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br><small><?php echo rwmb_meta( 'socrata_events_displaydate' );?></small></li> <?php } else { ?> <li><small style="text-transform: uppercase;"><?php events_the_categories(); ?></small><br> <?php $url = rwmb_meta( 'socrata_events_url' ); if ($url) { ?> <a href="<?php echo $url;?>" target="_blank"><?php the_title(); ?></a> <?php } else { ?> <?php the_title(); ?> <?php } ?> <br><small><?php echo rwmb_meta( 'socrata_events_displaydate' );?></small> </li> <?php } ?> <?php } } echo '<li><a href="/events">View All Events <i class="fa fa-arrow-circle-o-right"></i></a></li>'; echo '</ul>'; } else { ?> <ul class="no-bullets sidebar-list"> <li><h5>Upcoming Events</h5></li> <li>No events at this time.</li> </ul> <?php } /* Restore original Post Data */ wp_reset_postdata(); ?> </div> </div> </div> </section>
Socratacom/marketing-site
wp-content/themes/sage/templates/content-single.php
PHP
gpl-2.0
9,873
<?php /** * @package Joomla.Administrator * @subpackage Template.hathor * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include the component HTML helpers. JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html'); JHtml::_('behavior.multiselect'); $user = JFactory::getUser(); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); ?> <form action="<?php echo JRoute::_('index.php?option=com_messages&view=messages'); ?>" method="post" name="adminForm" id="adminForm"> <?php if (!empty( $this->sidebar)) : ?> <div id="j-sidebar-container" class="span2"> <?php echo $this->sidebar; ?> </div> <div id="j-main-container" class="span10"> <?php else : ?> <div id="j-main-container"> <?php endif;?> <fieldset id="filter-bar"> <legend class="element-invisible"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></legend> <div class="filter-search"> <label class="filter-search-lbl" for="filter_search"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></label> <input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_MESSAGES_SEARCH_IN_SUBJECT'); ?>" /> <button type="submit"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button> <button type="button" onclick="document.getElementById('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button> </div> <div class="filter-select"> <label class="selectlabel" for="filter_state"> <?php echo JText::_('JOPTION_SELECT_PUBLISHED'); ?> </label> <select name="filter_state" id="filter_state"> <option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option> <?php echo JHtml::_('select.options', MessagesHelper::getStateOptions(), 'value', 'text', $this->state->get('filter.state'));?> </select> <button type="submit" id="filter-go"> <?php echo JText::_('JSUBMIT'); ?></button> </div> </fieldset> <div class="clr"> </div> <table class="adminlist"> <thead> <tr> <th class="checkmark-col"> <input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" /> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_SUBJECT', 'a.subject', $listDirn, $listOrder); ?> </th> <th class="width-5"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_READ', 'a.state', $listDirn, $listOrder); ?> </th> <th class="width-15"> <?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_FROM', 'a.user_id_from', $listDirn, $listOrder); ?> </th> <th class="nowrap width-20"> <?php echo JHtml::_('grid.sort', 'JDATE', 'a.date_time', $listDirn, $listOrder); ?> </th> </tr> </thead> <tbody> <?php foreach ($this->items as $i => $item) : $canChange = $user->authorise('core.edit.state', 'com_messages'); ?> <tr class="row<?php echo $i % 2; ?>"> <td> <?php echo JHtml::_('grid.id', $i, $item->message_id); ?> </td> <td> <a href="<?php echo JRoute::_('index.php?option=com_messages&view=message&message_id='.(int) $item->message_id); ?>"> <?php echo $this->escape($item->subject); ?></a> </td> <td class="center"> <?php echo JHtml::_('messages.state', $item->state, $i, $canChange); ?> </td> <td> <?php echo $item->user_from; ?> </td> <td> <?php echo JHtml::_('date', $item->date_time, JText::_('DATE_FORMAT_LC2')); ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php echo $this->pagination->getListFooter(); ?> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
subtext/joomla-cms
administrator/templates/hathor/html/com_messages/messages/default.php
PHP
gpl-2.0
4,185
<?php $this->placeholder('secBar')->captureStart(); ?> <section id="portal" class="navbar-wrapper<?php echo ($this->usuarioLogado ? ' fixed':'');?>"> <div class="container"> <a class="btn pull-left" target="_top" rel="acceso portal da educaรงรฃo" href="http://educadores.educacao.ba.gov.br"> <h4 class="link-cinza-claro"> <b class="link-cinza-escuro">educacao</b>.ba.gov.br </h4> </a> <ul class="list-inline hidden-sm hidden-xs pull-right"> <li> <a class="btn link-laranja hover-laranja" target="_top" href="http://escolas.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> escolas </a> </li> <li> <a class="btn link-verde hover-verde" target="_top" href="http://estudantes.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> estudantes </a> </li> <li> <a class="btn link-vermelho hover-vermelho" target="_top" href="http://educadores.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> educadores </a> </li> <li> <a class="btn link-azul hover-azul" target="_top" href="http://institucional.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> institucional </a> </li> <li> <a class="btn link-roxo hover-roxo" target="_top" href="http://municipios.educacao.ba.gov.br/"> <i class="fa fa-caret-right fa-lg"></i> municรญpios </a> </li> </ul> <!-- <ul class="list-inline navbar-toggle pull-right" style="padding: 0;"> <li><a class="btn link-laranja" target="_top" href="http://escolas.educacao.ba.gov.br/"><i class="fa fa-university fa-lg"></i></a></li> <li><a class="btn link-verde" target="_top" href="http://estudantes.educacao.ba.gov.br/"><i class="fa fa-child fa-lg"></i></a></li> <li><a class="btn link-vermelho" target="_top" href="http://educadores.educacao.ba.gov.br/"><i class="fa fa-users fa-lg"></i></a></li> <li><a class="btn link-azul" target="_top" href="http://institucional.educacao.ba.gov.br/"><i class="fa fa-building fa-lg"></i></a></li> <li><a class="btn link-roxo" target="_top" href="http://municipios.educacao.ba.gov.br/"><i class="fa fa-building-o fa-lg"></i></a></li> </ul> <iframe src="http://educadores.educacao.ba.gov.br/ambiente_educacional" id="portal_educacao" frameborder="0" height="38" width="100%" scrolling="no" style="display:none"></iframe> --> </div> </section> <?php $this->placeholder('secBar')->captureEnd(); ?>
redeanisioteixeira/aew_github
aew_sec/application/layouts/scripts/geral/_sec-bar.php
PHP
gpl-2.0
3,050
from rest_framework import permissions class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Only allow owners of an object to view or edit it return obj.owner == request.user
lesavoie/nagiosservice
controlserver/servicelevelinterface/permissions.py
Python
gpl-2.0
238
<?php return array( 'extends' => 'root', 'css' => array( //'vendor/bootstrap.min.css', //'vendor/bootstrap-accessibility.css', //'bootstrap-custom.css', 'compiled.css', 'vendor/font-awesome.min.css', 'vendor/bootstrap-slider.css', 'print.css:print', 'ol.css' ), 'js' => array( 'vendor/base64.js:lt IE 10', // btoa polyfill 'vendor/jquery.min.js', 'vendor/bootstrap.min.js', 'vendor/bootstrap-accessibility.min.js', //'vendor/bootlint.min.js', 'vendor/typeahead.js', 'vendor/validator.min.js', 'vendor/rc4.js', 'common.js', 'lightbox.js', ), 'less' => array( 'active' => false, 'compiled.less' ), 'favicon' => 'vufind-favicon.ico', 'helpers' => array( 'factories' => array( 'flashmessages' => 'VuFind\View\Helper\Bootstrap3\Factory::getFlashmessages', 'layoutclass' => 'VuFind\View\Helper\Bootstrap3\Factory::getLayoutClass', ), 'invokables' => array( 'highlight' => 'VuFind\View\Helper\Bootstrap3\Highlight', 'search' => 'VuFind\View\Helper\Bootstrap3\Search', 'vudl' => 'VuDL\View\Helper\Bootstrap3\VuDL', ) ) );
paulusova/VuFind-2.x
themes/bootstrap3/theme.config.php
PHP
gpl-2.0
1,306
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2011 TrilliumEMU <http://www.trilliumemu.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "BattlegroundAB.h" #include "BattlegroundWS.h" #include "BattlegroundIC.h" #include "BattlegroundSA.h" #include "BattlegroundAV.h" #include "Vehicle.h" class achievement_storm_glory : public AchievementCriteriaScript { public: achievement_storm_glory() : AchievementCriteriaScript("achievement_storm_glory") { } bool OnCheck(Player* source, Unit* /*target*/) { if (source->GetBattlegroundTypeId() != BATTLEGROUND_EY) return false; Battleground *pEotS = source->GetBattleground(); if (!pEotS) return false; return pEotS->IsAllNodesConrolledByTeam(source->GetTeam()); } }; class achievement_resilient_victory : public AchievementCriteriaScript { public: achievement_resilient_victory() : AchievementCriteriaScript("achievement_resilient_victory") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (bg->GetTypeID(true) != BATTLEGROUND_AB) return false; if (!static_cast<BattlegroundAB*>(bg)->IsTeamScores500Disadvantage(source->GetTeam())) return false; return true; } }; class achievement_bg_control_all_nodes : public AchievementCriteriaScript { public: achievement_bg_control_all_nodes() : AchievementCriteriaScript("achievement_bg_control_all_nodes") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (!bg->IsAllNodesConrolledByTeam(source->GetTeam())) return false; return true; } }; class achievement_save_the_day : public AchievementCriteriaScript { public: achievement_save_the_day() : AchievementCriteriaScript("achievement_save_the_day") { } bool OnCheck(Player* source, Unit* target) { if (!target) return false; if (Player const* player = target->ToPlayer()) { if (source->GetBattlegroundTypeId() != BATTLEGROUND_WS || !source->GetBattleground()) return false; BattlegroundWS* pWSG = static_cast<BattlegroundWS*>(source->GetBattleground()); if (pWSG->GetFlagState(player->GetTeam()) == BG_WS_FLAG_STATE_ON_BASE) return true; } return false; } }; class achievement_bg_ic_resource_glut : public AchievementCriteriaScript { public: achievement_bg_ic_resource_glut() : AchievementCriteriaScript("achievement_bg_ic_resource_glut") { } bool OnCheck(Player* source, Unit* /*target*/) { if (source->HasAura(SPELL_OIL_REFINERY) && source->HasAura(SPELL_QUARRY)) return true; return false; } }; class achievement_bg_ic_glaive_grave : public AchievementCriteriaScript { public: achievement_bg_ic_glaive_grave() : AchievementCriteriaScript("achievement_bg_ic_glaive_grave") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_GLAIVE_THROWER_H || vehicle->GetEntry() == NPC_GLAIVE_THROWER_A) return true; } return false; } }; class achievement_bg_ic_mowed_down : public AchievementCriteriaScript { public: achievement_bg_ic_mowed_down() : AchievementCriteriaScript("achievement_bg_ic_mowed_down") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_KEEP_CANNON) return true; } return false; } }; class achievement_bg_sa_artillery : public AchievementCriteriaScript { public: achievement_bg_sa_artillery() : AchievementCriteriaScript("achievement_bg_sa_artillery") { } bool OnCheck(Player* source, Unit* /*target*/) { if (Creature* vehicle = source->GetVehicleCreatureBase()) { if (vehicle->GetEntry() == NPC_ANTI_PERSONNAL_CANNON) return true; } return false; } }; class achievement_arena_kills : public AchievementCriteriaScript { public: achievement_arena_kills(char const* name, uint8 arenaType) : AchievementCriteriaScript(name), _arenaType(arenaType) { } bool OnCheck(Player* source, Unit* /*target*/) { // this checks GetBattleground() for NULL already if (!source->InArena()) return false; return source->GetBattleground()->GetArenaType() == _arenaType; } private: uint8 const _arenaType; }; class achievement_sickly_gazelle : public AchievementCriteriaScript { public: achievement_sickly_gazelle() : AchievementCriteriaScript("achievement_sickly_gazelle") { } bool OnCheck(Player* /*source*/, Unit* target) { if (!target) return false; if (Player* victim = target->ToPlayer()) if (victim->IsMounted()) return true; return false; } }; class achievement_everything_counts : public AchievementCriteriaScript { public: achievement_everything_counts() : AchievementCriteriaScript("achievement_everything_counts") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (source->GetBattlegroundTypeId() != BATTLEGROUND_AV) return false; if (static_cast<BattlegroundAV*>(bg)->IsBothMinesControlledByTeam(source->GetTeam())) return true; return false; } }; class achievement_bg_av_perfection : public AchievementCriteriaScript { public: achievement_bg_av_perfection() : AchievementCriteriaScript("achievement_bg_av_perfection") { } bool OnCheck(Player* source, Unit* /*target*/) { Battleground* bg = source->GetBattleground(); if (!bg) return false; if (source->GetBattlegroundTypeId() != BATTLEGROUND_AV) return false; if (static_cast<BattlegroundAV*>(bg)->IsAllTowersControlledAndCaptainAlive(source->GetTeam())) return true; return false; } }; class achievement_wg_didnt_stand_a_chance : public AchievementCriteriaScript { public: achievement_wg_didnt_stand_a_chance() : AchievementCriteriaScript("achievement_wg_didnt_stand_a_chance") { } bool OnCheck(Player* source, Unit* target) { if (!target) return false; if (Player* victim = target->ToPlayer()) { if (!victim->IsMounted()) return false; if (Vehicle* vehicle = source->GetVehicle()) if (vehicle->GetVehicleInfo()->m_ID == 244) // Wintergrasp Tower Cannon return true; } return false; } }; class achievement_bg_sa_defense_of_ancients : public AchievementCriteriaScript { public: achievement_bg_sa_defense_of_ancients() : AchievementCriteriaScript("achievement_bg_sa_defense_of_ancients") { } bool OnCheck(Player* player, Unit* /*target*/) { if (!player) return false; Battleground* battleground = player->GetBattleground(); if (!battleground) return false; if (player->GetTeamId() == static_cast<BattlegroundSA*>(battleground)->Attackers) return false; if (!static_cast<BattlegroundSA*>(battleground)->gateDestroyed) return true; return false; } }; void AddSC_achievement_scripts() { new achievement_storm_glory(); new achievement_resilient_victory(); new achievement_bg_control_all_nodes(); new achievement_save_the_day(); new achievement_bg_ic_resource_glut(); new achievement_bg_ic_glaive_grave(); new achievement_bg_ic_mowed_down(); new achievement_bg_sa_artillery(); new achievement_sickly_gazelle(); new achievement_wg_didnt_stand_a_chance(); new achievement_everything_counts(); new achievement_bg_av_perfection(); new achievement_arena_kills("achievement_arena_2v2_kills", ARENA_TYPE_2v2); new achievement_arena_kills("achievement_arena_3v3_kills", ARENA_TYPE_3v3); new achievement_arena_kills("achievement_arena_5v5_kills", ARENA_TYPE_5v5); new achievement_bg_sa_defense_of_ancients(); }
AwkwardDev/TrilliumEMU
src/server/scripts/World/achievement_scripts.cpp
C++
gpl-2.0
9,912
<?php include_once(INCLUDE_DIR.'staff/login.header.php'); defined('OSTSCPINC') or die('Invalid path'); $info = ($_POST)?Format::htmlchars($_POST):array(); ?> <div id="loginBox"> <div class="tape"></div> <div id="blur"> <div id="background"></div> </div> <h1 id="logo"><a href="index.php"> <span class="valign-helper"></span> <img src="logo.php?login" alt="osTicket :: <?php echo __('Agent Password Reset');?>" /> </a></h1> <h3><?php echo Format::htmlchars($msg); ?></h3> <form action="pwreset.php" method="post"> <?php csrf_token(); ?> <input type="hidden" name="do" value="newpasswd"/> <input type="hidden" name="token" value="<?php echo Format::htmlchars($_REQUEST['token']); ?>"/> <fieldset> <input type="text" name="userid" id="name" value="<?php echo $info['userid']; ?>" placeholder="<?php echo __('Email or Username'); ?>" autocorrect="off" autocapitalize="off"/> </fieldset> <input class="submit" type="submit" name="submit" value="Login"/> </form> <div id="company"> <div class="content"> <?php echo __('Copyright'); ?> &copy; <?php echo Format::htmlchars($ost->company) ?: date('Y'); ?> </div> </div> </div> <div id="poweredBy"><?php echo __('Powered by'); ?> <a href="http://www.osticket.com" target="_blank"> <img alt="osTicket" src="images/osticket-grey.png" class="osticket-logo"> </a> </div> <script> document.addEventListener('DOMContentLoaded', function() { if (undefined === window.getComputedStyle(document.documentElement).backgroundBlendMode) { document.getElementById('background-compat').style.display = 'block'; document.getElementById('loginBox').style.backgroundColor = 'white'; } }); </script> </body> </html>
garyns/osTicket-lyn
include/staff/pwreset.login.php
PHP
gpl-2.0
1,896
/* * $Id$ * * DEBUG: section 28 Access Control * AUTHOR: Duane Wessels * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * 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, USA. * * * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org> */ #include "squid.h" #include "acl/CertificateData.h" #include "acl/Checklist.h" #include "wordlist.h" ACLCertificateData::ACLCertificateData(SSLGETATTRIBUTE *sslStrategy) : attribute (NULL), values (), sslAttributeCall (sslStrategy) {} ACLCertificateData::ACLCertificateData(ACLCertificateData const &old) : attribute (NULL), values (old.values), sslAttributeCall (old.sslAttributeCall) { if (old.attribute) attribute = xstrdup (old.attribute); } template<class T> inline void xRefFree(T &thing) { xfree (thing); } ACLCertificateData::~ACLCertificateData() { safe_free (attribute); } template<class T> inline int splaystrcmp (T&l, T&r) { return strcmp ((char *)l,(char *)r); } bool ACLCertificateData::match(SSL *ssl) { if (!ssl) return 0; char const *value = sslAttributeCall(ssl, attribute); if (value == NULL) return 0; return values.match(value); } static void aclDumpAttributeListWalkee(char * const & node_data, void *outlist) { /* outlist is really a wordlist ** */ wordlistAdd((wordlist **)outlist, node_data); } wordlist * ACLCertificateData::dump() { wordlist *wl = NULL; wordlistAdd(&wl, attribute); /* damn this is VERY inefficient for long ACL lists... filling * a wordlist this way costs Sum(1,N) iterations. For instance * a 1000-elements list will be filled in 499500 iterations. */ /* XXX FIXME: don't break abstraction */ values.values->walk(aclDumpAttributeListWalkee, &wl); return wl; } void ACLCertificateData::parse() { char *newAttribute = strtokFile(); if (!newAttribute) self_destruct(); /* an acl must use consistent attributes in all config lines */ if (attribute) { if (strcasecmp(newAttribute, attribute) != 0) self_destruct(); } else attribute = xstrdup(newAttribute); values.parse(); } bool ACLCertificateData::empty() const { return values.empty(); } ACLData<SSL *> * ACLCertificateData::clone() const { /* Splay trees don't clone yet. */ return new ACLCertificateData(*this); }
schmurfy/squid
src/acl/CertificateData.cc
C++
gpl-2.0
3,610
<?php /*-----------------------------------------------------------------------------------*/ /* This theme supports WooCommerce, woo! */ /*-----------------------------------------------------------------------------------*/ add_action( 'after_setup_theme', 'woocommerce_support' ); function woocommerce_support() { add_theme_support( 'woocommerce' ); } /*-----------------------------------------------------------------------------------*/ /* Any WooCommerce overrides and functions can be found here /*-----------------------------------------------------------------------------------*/ // Add html5 shim add_action('wp_head', 'wootique_html5_shim'); function wootique_html5_shim() { ?> <!-- Load Google HTML5 shim to provide support for <IE9 --> <!--[if lt IE 9]> <script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <?php } // Disable WooCommerce styles if ( version_compare( WOOCOMMERCE_VERSION, "2.1" ) >= 0 ) { // WooCommerce 2.1 or above is active add_filter( 'woocommerce_enqueue_styles', '__return_false' ); } else { // WooCommerce is less than 2.1 define( 'WOOCOMMERCE_USE_CSS', false ); } /*-----------------------------------------------------------------------------------*/ /* Header /*-----------------------------------------------------------------------------------*/ // Hook in the search add_action('woo_nav_before', 'wootique_header_search'); function wootique_header_search() { ?> <div id="search-top"> <form role="search" method="get" id="searchform" class="searchform" action="<?php echo home_url(); ?>"> <label class="screen-reader-text" for="s"><?php _e('Search for:', 'woothemes'); ?></label> <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" class="field s" placeholder="<?php _e('Cari Kuliner', 'woothemes'); ?>" /> <input type="image" class="submit btn" name="submit" value="<?php _e('Search', 'woothemes'); ?>" src="<?php echo get_template_directory_uri(); ?>/images/ico-search.png"> <?php if ( wootique_get_woo_option( 'woo_header_search_scope' ) == 'products' ) { echo '<input type="hidden" name="post_type" value="product" />'; } else { echo '<input type="hidden" name="post_type" value="post" />'; } ?> </form> <div class="fix"></div> </div><!-- /.search-top --> <?php } // Remove WC sidebar remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10); // Adjust markup on all WooCommerce pages remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10); remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10); add_action('woocommerce_before_main_content', 'woostore_before_content', 10); add_action('woocommerce_after_main_content', 'woostore_after_content', 20); // Fix the layout etc function woostore_before_content() { ?> <!-- #content Starts --> <?php woo_content_before(); ?> <div id="content" class="col-full"> <!-- #main Starts --> <?php woo_main_before(); ?> <div id="main" class="col-left"> <?php } function woostore_after_content() { ?> <?php if ( is_search() && is_post_type_archive() ) { add_filter( 'woo_pagination_args', 'woocommerceframework_add_search_fragment', 10 ); } ?> <?php woo_pagenav(); ?> </div><!-- /#main --> <?php woo_main_after(); ?> </div><!-- /#content --> <?php woo_content_after(); ?> <?php } function woocommerceframework_add_search_fragment ( $settings ) { $settings['add_fragment'] = '&post_type=product'; return $settings; } // End woocommerceframework_add_search_fragment() // Add the WC sidebar in the right place add_action( 'woo_main_after', 'woocommerce_get_sidebar', 10); // Remove breadcrumb (we're using the WooFramework default breadcrumb) remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0); add_action( 'woocommerce_before_main_content', 'woostore_breadcrumb', 01, 0); function woostore_breadcrumb() { if ( wootique_get_woo_option( 'woo_breadcrumbs_show' ) == 'true' ) { woo_breadcrumbs(); } } // Remove pagination (we're using the WooFramework default pagination) remove_action( 'woocommerce_pagination', 'woocommerce_pagination', 10 ); // <2.0 remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 ); // 2.0+ // Adjust the star rating in the sidebar add_filter('woocommerce_star_rating_size_sidebar', 'woostore_star_sidebar'); function woostore_star_sidebar() { return 12; } // Adjust the star rating in the recent reviews add_filter('woocommerce_star_rating_size_recent_reviews', 'woostore_star_reviews'); function woostore_star_reviews() { return 12; } // Change columns in product loop to 3 add_filter('loop_shop_columns', 'woostore_loop_columns'); function woostore_loop_columns() { return 3; } // Change columns in related products output to 3 remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20); add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20); if ( ! function_exists('woocommerce_output_related_products') && version_compare( WOOCOMMERCE_VERSION, "2.1" ) < 0 ) { function woocommerce_output_related_products() { woocommerce_related_products( 3,3 ); } } add_filter( 'woocommerce_output_related_products_args', 'wootique_related_products' ); function wootique_related_products() { $args = array( 'posts_per_page' => 3, 'columns' => 3, ); return $args; } if ( ! function_exists( 'woo_upsell_display' ) ) { function woo_upsell_display() { // Display up sells in correct layout. woocommerce_upsell_display( -1, 3 ); } } remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15 ); add_action( 'woocommerce_after_single_product_summary', 'woo_upsell_display', 15 ); // If theme lightbox is enabled, disable the WooCommerce lightbox and make product images prettyPhoto galleries /*add_action( 'wp_footer', 'woocommerce_prettyphoto' ); function woocommerce_prettyphoto() { if ( wootique_get_woo_option( 'woo_enable_lightbox' ) == "true" ) { update_option( 'woocommerce_enable_lightbox', false ); ?> <script> jQuery(document).ready(function(){ jQuery('.images a').attr('rel', 'prettyPhoto[product-gallery]'); }); </script> <?php } }*/ // Move the price below the excerpt on the single product page remove_action( 'woocommerce_template_single_summary', 'woocommerce_template_single_price', 10, 2); add_action( 'woocommerce_template_single_summary', 'woocommerce_template_single_price', 25, 2); // Display 12 products per page add_filter('loop_shop_per_page', create_function('$cols', 'return 12;')); add_action('woo_nav_after', 'woocommerce_cart_link', 10); add_action('woo_nav_after', 'wootique_checkout_button', 10); function woocommerce_cart_link() { global $woocommerce; ?> <a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="'<?php _e( 'View your shopping cart', 'woothemes' ); ?>'" class="cart-button"> <span><?php echo sprintf(_n( '%d item &ndash; ', '%d items &ndash; ', $woocommerce->cart->get_cart_contents_count(), 'woothemes'), $woocommerce->cart->get_cart_contents_count()) . $woocommerce->cart->get_cart_total(); ?></span> </a> <?php } function wootique_checkout_button() { global $woocommerce; ?> <?php if (sizeof($woocommerce->cart->cart_contents)>0) : echo '<a href="'.$woocommerce->cart->get_checkout_url().'" class="checkout-link">'.__('Checkout','woothemes').'</a>'; endif; ?> <?php } add_filter('add_to_cart_fragments', 'header_add_to_cart_fragment'); function header_add_to_cart_fragment( $fragments ) { global $woocommerce; ob_start(); woocommerce_cart_link(); $fragments['.cart-button'] = ob_get_clean(); return $fragments; }
jarqo/wootique
wp-content/themes/wootique/includes/theme-woocommerce.php
PHP
gpl-2.0
7,820
using System; using System.Text; using System.Collections; using Server; using Server.Prompts; using Server.Gumps; using Server.Network; using Server.Items; using Server.Misc; namespace Server.Mobiles { public interface ITownCrierEntryList { ArrayList Entries{ get; } TownCrierEntry GetRandomEntry(); TownCrierEntry AddEntry( string[] lines, TimeSpan duration ); void RemoveEntry( TownCrierEntry entry ); } public class GlobalTownCrierEntryList : ITownCrierEntryList { private static GlobalTownCrierEntryList m_Instance; public static void Initialize() { Server.Commands.Register( "TownCriers", AccessLevel.GameMaster, new CommandEventHandler( TownCriers_OnCommand ) ); } [Usage( "TownCriers" )] [Description( "Manages the global town crier list." )] public static void TownCriers_OnCommand( CommandEventArgs e ) { e.Mobile.SendGump( new TownCrierGump( e.Mobile, Instance ) ); } public static GlobalTownCrierEntryList Instance { get { if ( m_Instance == null ) m_Instance = new GlobalTownCrierEntryList(); return m_Instance; } } public bool IsEmpty{ get{ return ( m_Entries == null || m_Entries.Count == 0 ); } } public GlobalTownCrierEntryList() { } private ArrayList m_Entries; public ArrayList Entries { get{ return m_Entries; } } public TownCrierEntry GetRandomEntry() { if ( m_Entries == null || m_Entries.Count == 0 ) return null; for ( int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i ) { if ( i >= m_Entries.Count ) continue; TownCrierEntry tce = (TownCrierEntry)m_Entries[i]; if ( tce.Expired ) RemoveEntry( tce ); } if ( m_Entries == null || m_Entries.Count == 0 ) return null; return (TownCrierEntry)m_Entries[Utility.Random( m_Entries.Count )]; } public TownCrierEntry AddEntry( string[] lines, TimeSpan duration ) { if ( m_Entries == null ) m_Entries = new ArrayList(); TownCrierEntry tce = new TownCrierEntry( lines, duration ); m_Entries.Add( tce ); ArrayList instances = TownCrier.Instances; for ( int i = 0; i < instances.Count; ++i ) ((TownCrier)instances[i]).ForceBeginAutoShout(); return tce; } public void RemoveEntry( TownCrierEntry tce ) { if ( m_Entries == null ) return; m_Entries.Remove( tce ); if ( m_Entries.Count == 0 ) m_Entries = null; } } public class TownCrierEntry { private string[] m_Lines; private DateTime m_ExpireTime; public string[] Lines{ get{ return m_Lines; } } public DateTime ExpireTime{ get{ return m_ExpireTime; } } public bool Expired{ get{ return ( Core.Now >= m_ExpireTime ); } } public TownCrierEntry( string[] lines, TimeSpan duration ) { m_Lines = lines; if ( duration < TimeSpan.Zero ) duration = TimeSpan.Zero; else if ( duration > TimeSpan.FromDays( 365.0 ) ) duration = TimeSpan.FromDays( 365.0 ); m_ExpireTime = Core.Now + duration; } } public class TownCrierDurationPrompt : Prompt { private ITownCrierEntryList m_Owner; public TownCrierDurationPrompt( ITownCrierEntryList owner ) { m_Owner = owner; } public override void OnResponse( Mobile from, string text ) { TimeSpan ts; try { ts = TimeSpan.Parse( text ); } catch { from.SendMessage( "Value was not properly formatted. Use: <hours:minutes:seconds>" ); from.SendGump( new TownCrierGump( from, m_Owner ) ); return; } if ( ts < TimeSpan.Zero ) ts = TimeSpan.Zero; from.SendMessage( "Duration set to: {0}", ts ); from.SendMessage( "Enter the first line to shout:" ); from.Prompt = new TownCrierLinesPrompt( m_Owner, null, new ArrayList(), ts ); } public override void OnCancel( Mobile from ) { from.SendLocalizedMessage( 502980 ); // Message entry cancelled. from.SendGump( new TownCrierGump( from, m_Owner ) ); } } public class TownCrierLinesPrompt : Prompt { private ITownCrierEntryList m_Owner; private TownCrierEntry m_Entry; private ArrayList m_Lines; private TimeSpan m_Duration; public TownCrierLinesPrompt( ITownCrierEntryList owner, TownCrierEntry entry, ArrayList lines, TimeSpan duration ) { m_Owner = owner; m_Entry = entry; m_Lines = lines; m_Duration = duration; } public override void OnResponse( Mobile from, string text ) { m_Lines.Add( text ); from.SendMessage( "Enter the next line to shout, or press <ESC> if the message is finished." ); from.Prompt = new TownCrierLinesPrompt( m_Owner, m_Entry, m_Lines, m_Duration ); } public override void OnCancel( Mobile from ) { if ( m_Entry != null ) m_Owner.RemoveEntry( m_Entry ); if ( m_Lines.Count > 0 ) { m_Owner.AddEntry( (string[])m_Lines.ToArray( typeof( string ) ), m_Duration ); from.SendMessage( "Message has been set." ); } else { if ( m_Entry != null ) from.SendMessage( "Message deleted." ); else from.SendLocalizedMessage( 502980 ); // Message entry cancelled. } from.SendGump( new TownCrierGump( from, m_Owner ) ); } } public class TownCrierGump : Gump { private Mobile m_From; private ITownCrierEntryList m_Owner; public override void OnResponse( NetState sender, RelayInfo info ) { if ( info.ButtonID == 1 ) { m_From.SendMessage( "Enter the duration for the new message. Format: <hours:minutes:seconds>" ); m_From.Prompt = new TownCrierDurationPrompt( m_Owner ); } else if ( info.ButtonID > 1 ) { ArrayList entries = m_Owner.Entries; int index = info.ButtonID - 2; if ( entries != null && index < entries.Count ) { TownCrierEntry tce = (TownCrierEntry)entries[index]; TimeSpan ts = tce.ExpireTime - Core.Now; if ( ts < TimeSpan.Zero ) ts = TimeSpan.Zero; m_From.SendMessage( "Editing entry #{0}.", index + 1 ); m_From.SendMessage( "Enter the first line to shout:" ); m_From.Prompt = new TownCrierLinesPrompt( m_Owner, tce, new ArrayList(), ts ); } } } public TownCrierGump( Mobile from, ITownCrierEntryList owner ) : base( 50, 50 ) { m_From = from; m_Owner = owner; from.CloseGump( typeof( TownCrierGump ) ); AddPage( 0 ); ArrayList entries = owner.Entries; owner.GetRandomEntry(); // force expiration checks int count = 0; if ( entries != null ) count = entries.Count; AddImageTiled( 0, 0, 300, 38 + (count == 0 ? 20 : (count * 85)), 0xA40 ); AddAlphaRegion( 1, 1, 298, 36 + (count == 0 ? 20 : (count * 85)) ); AddHtml( 8, 8, 300 - 8 - 30, 20, "<basefont color=#FFFFFF><center>TOWN CRIER MESSAGES</center></basefont>", false, false ); AddButton( 300 - 8 - 30, 8, 0xFAB, 0xFAD, 1, GumpButtonType.Reply, 0 ); if ( count == 0 ) { AddHtml( 8, 30, 284, 20, "<basefont color=#FFFFFF>The crier has no news.</basefont>", false, false ); } else { for ( int i = 0; i < entries.Count; ++i ) { TownCrierEntry tce = (TownCrierEntry)entries[i]; TimeSpan toExpire = tce.ExpireTime - Core.Now; if ( toExpire < TimeSpan.Zero ) toExpire = TimeSpan.Zero; StringBuilder sb = new StringBuilder(); sb.Append( "[Expires: " ); if ( toExpire.TotalHours >= 1 ) { sb.Append( (int)toExpire.TotalHours ); sb.Append( ':' ); sb.Append( toExpire.Minutes.ToString( "D2" ) ); } else { sb.Append( toExpire.Minutes ); } sb.Append( ':' ); sb.Append( toExpire.Seconds.ToString( "D2" ) ); sb.Append( "] " ); for ( int j = 0; j < tce.Lines.Length; ++j ) { if ( j > 0 ) sb.Append( "<br>" ); sb.Append( tce.Lines[j] ); } AddHtml( 8, 35 + (i * 85), 254, 80, sb.ToString(), true, true ); AddButton( 300 - 8 - 26, 35 + (i * 85), 0x15E1, 0x15E5, 2 + i, GumpButtonType.Reply, 0 ); } } } } public class TownCrier : Mobile, ITownCrierEntryList { private ArrayList m_Entries; private Timer m_NewsTimer; private Timer m_AutoShoutTimer; public ArrayList Entries { get{ return m_Entries; } } public TownCrierEntry GetRandomEntry() { if ( m_Entries == null || m_Entries.Count == 0 ) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); for ( int i = m_Entries.Count - 1; m_Entries != null && i >= 0; --i ) { if ( i >= m_Entries.Count ) continue; TownCrierEntry tce = (TownCrierEntry)m_Entries[i]; if ( tce.Expired ) RemoveEntry( tce ); } if ( m_Entries == null || m_Entries.Count == 0 ) return GlobalTownCrierEntryList.Instance.GetRandomEntry(); TownCrierEntry entry = GlobalTownCrierEntryList.Instance.GetRandomEntry(); if ( entry == null || Utility.RandomBool() ) entry = (TownCrierEntry)m_Entries[Utility.Random( m_Entries.Count )]; return entry; } public void ForceBeginAutoShout() { if ( m_AutoShoutTimer == null ) m_AutoShoutTimer = Timer.DelayCall( TimeSpan.FromSeconds( 5.0 ), TimeSpan.FromMinutes( 1.0 ), new TimerCallback( AutoShout_Callback ) ); } public TownCrierEntry AddEntry( string[] lines, TimeSpan duration ) { if ( m_Entries == null ) m_Entries = new ArrayList(); TownCrierEntry tce = new TownCrierEntry( lines, duration ); m_Entries.Add( tce ); if ( m_AutoShoutTimer == null ) m_AutoShoutTimer = Timer.DelayCall( TimeSpan.FromSeconds( 5.0 ), TimeSpan.FromMinutes( 1.0 ), new TimerCallback( AutoShout_Callback ) ); return tce; } public void RemoveEntry( TownCrierEntry tce ) { if ( m_Entries == null ) return; m_Entries.Remove( tce ); if ( m_Entries.Count == 0 ) m_Entries = null; if ( m_Entries == null && GlobalTownCrierEntryList.Instance.IsEmpty ) { if ( m_AutoShoutTimer != null ) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } } private void AutoShout_Callback() { TownCrierEntry tce = GetRandomEntry(); if ( tce == null ) { if ( m_AutoShoutTimer != null ) m_AutoShoutTimer.Stop(); m_AutoShoutTimer = null; } else if ( m_NewsTimer == null ) { m_NewsTimer = Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 3.0 ), new TimerStateCallback( ShoutNews_Callback ), new object[]{ tce, 0 } ); PublicOverheadMessage( MessageType.Regular, 0x3B2, 502976 ); // Hear ye! Hear ye! } } private void ShoutNews_Callback( object state ) { object[] states = (object[])state; TownCrierEntry tce = (TownCrierEntry)states[0]; int index = (int)states[1]; if ( index < 0 || index >= tce.Lines.Length ) { if ( m_NewsTimer != null ) m_NewsTimer.Stop(); m_NewsTimer = null; } else { PublicOverheadMessage( MessageType.Regular, 0x3B2, false, tce.Lines[index] ); states[1] = index + 1; } } public override void OnDoubleClick( Mobile from ) { if ( from.AccessLevel >= AccessLevel.GameMaster ) from.SendGump( new TownCrierGump( from, this ) ); else base.OnDoubleClick( from ); } public override bool HandlesOnSpeech( Mobile from ) { return ( m_NewsTimer == null && from.Alive && InRange( from, 12 ) ); } public override void OnSpeech( SpeechEventArgs e ) { if ( m_NewsTimer == null && e.HasKeyword( 0x30 ) && e.Mobile.Alive && InRange( e.Mobile, 12 ) ) // *news* { Direction = GetDirectionTo( e.Mobile ); TownCrierEntry tce = GetRandomEntry(); if ( tce == null ) { PublicOverheadMessage( MessageType.Regular, 0x3B2, 1005643 ); // I have no news at this time. } else { m_NewsTimer = Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), TimeSpan.FromSeconds( 3.0 ), new TimerStateCallback( ShoutNews_Callback ), new object[]{ tce, 0 } ); PublicOverheadMessage( MessageType.Regular, 0x3B2, 502978 ); // Some of the latest news! } } } private static ArrayList m_Instances = new ArrayList(); public static ArrayList Instances { get{ return m_Instances; } } [Constructable] public TownCrier() { m_Instances.Add( this ); InitStats( 100, 100, 25 ); Title = "the town crier"; Hue = Utility.RandomSkinHue(); if ( !Core.AOS ) NameHue = 0x35; if ( this.Female = Utility.RandomBool() ) { this.Body = 0x191; this.Name = NameList.RandomName( "female" ); } else { this.Body = 0x190; this.Name = NameList.RandomName( "male" ); } AddItem( new FancyShirt( Utility.RandomBlueHue() ) ); Item skirt; switch ( Utility.Random( 2 ) ) { case 0: skirt = new Skirt(); break; default: case 1: skirt = new Kilt(); break; } skirt.Hue = Utility.RandomGreenHue(); AddItem( skirt ); AddItem( new FeatheredHat( Utility.RandomGreenHue() ) ); Item boots; switch ( Utility.Random( 2 ) ) { case 0: boots = new Boots(); break; default: case 1: boots = new ThighBoots(); break; } AddItem( boots ); Item hair = new Item( Utility.RandomList( 0x203B, 0x2049, 0x2048, 0x204A ) ); hair.Hue = Utility.RandomNondyedHue(); hair.Layer = Layer.Hair; hair.Movable = false; AddItem( hair ); } public override bool CanBeDamaged() { return false; } public override void OnDelete() { m_Instances.Remove( this ); base.OnDelete(); } public TownCrier( Serial serial ) : base( serial ) { m_Instances.Add( this ); } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); /*int version = */reader.ReadInt(); if ( Core.AOS && NameHue == 0x35 ) NameHue = -1; } } }
brodock/sunuo
scripts/legacy/Mobiles/Townfolk/TownCrier.cs
C#
gpl-2.0
13,658
<?php /** * Copyright ยฉ Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\GroupedProduct\Model\Product\Link\CollectionProvider; class Grouped implements \Magento\Catalog\Model\ProductLink\CollectionProviderInterface { /** * {@inheritdoc} */ public function getLinkedProducts(\Magento\Catalog\Model\Product $product) { return $product->getTypeInstance()->getAssociatedProducts($product); } }
kunj1988/Magento2
app/code/Magento/GroupedProduct/Model/Product/Link/CollectionProvider/Grouped.php
PHP
gpl-2.0
476
/* * Copyright (C) 2004 * Swiss Federal Institute of Technology, Lausanne. All rights reserved. * * Author: Roland Philippsen <roland dot philippsen at gmx dot net> * Autonomous Systems Lab <http://asl.epfl.ch/> * * 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 */ #ifndef OCAMERA_HPP #define OCAMERA_HPP #include <npm/gfx/Camera.hpp> namespace sfl { class DynamicWindow; } class OCamera : public npm::Camera { public: OCamera(const std::string & name, const sfl::DynamicWindow & dwa); virtual void ConfigureView(npm::View & view); private: const sfl::DynamicWindow & m_dwa; }; #endif // OCAMERA_HPP
poftwaresatent/sfl2
npm/ext/expo02/OCamera.hpp
C++
gpl-2.0
1,314
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2014 # Gmail:liuzheng712 # __author__ = 'liuzheng' from django.conf.urls import patterns, include, url from django.contrib import admin import os urlpatterns = patterns('', # Examples: # url(r'^$', 'pyHBase.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'pyHBase.views.index'), url(r'^admin/(.*)$', 'pyHBase.views.admin'), url(r'^DJadmin/', include(admin.site.urls)), url(r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/css').replace('\\', '/')}), url(r'^js/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/js').replace('\\', '/')}), url(r'^img/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), '../templates/img').replace('\\', '/')}), (r'^api/', include('api.urls')), )
liuzheng712/pyHBaseadmin
pyHBase/pyHBase/urls.py
Python
gpl-2.0
1,013
package com.opentravelsoft.entity.product; import com.opentravelsoft.util.MD5; /** * * @author <a herf="mailto:zhangsitao@gmail.com">Steven Zhang</a> * @version $Revision: 1.1 $ $Date: 2009/03/01 16:23:32 $ */ public class NetPayEntity { /** * ๅ•†ๆˆทๅท๏ผŒ่ฟ™้‡Œไธบๆต‹่ฏ•ๅ•†ๆˆทๅท1001๏ผŒๆ›ฟๆขไธบ่‡ชๅทฑ็š„ๅ•†ๆˆทๅท(่€็‰ˆๅ•†ๆˆทๅทไธบ4ไฝๆˆ–5ไฝ,ๆ–ฐ็‰ˆไธบ8ไฝ)ๅณๅฏ */ private String mid; /** * ๅฆ‚ๆžœๆ‚จ่ฟ˜ๆฒกๆœ‰่ฎพ็ฝฎMD5ๅฏ†้’ฅ่ฏท็™ป้™†ๆˆ‘ไปฌไธบๆ‚จๆไพ›ๅ•†ๆˆทๅŽๅฐ๏ผŒ<br> * ๅœฐๅ€๏ผšhttps://merchant3.chinabank.com.cn/ * ็™ป้™†ๅŽๅœจไธŠ้ข็š„ๅฏผ่ˆชๆ ้‡Œๅฏ่ƒฝๆ‰พๅˆฐโ€œB2Cโ€๏ผŒๅœจไบŒ็บงๅฏผ่ˆชๆ ้‡Œๆœ‰โ€œMD5ๅฏ†้’ฅ่ฎพ็ฝฎโ€ * ๅปบ่ฎฎๆ‚จ่ฎพ็ฝฎไธ€ไธช16ไฝไปฅไธŠ็š„ๅฏ†้’ฅๆˆ–ๆ›ด้ซ˜๏ผŒๅฏ†้’ฅๆœ€ๅคš64ไฝ๏ผŒไฝ†่ฎพ็ฝฎ16ไฝๅทฒ็ป่ถณๅคŸไบ† */ private String key; /** ๅ•†ๆˆท่‡ชๅฎšไน‰่ฟ”ๅ›žๆŽฅๆ”ถๆ”ฏไป˜็ป“ๆžœ็š„้กต้ข */ private String url; /** ่ฎขๅ•ๅท */ private String oid; /** ่ฎขๅ•้‡‘้ข */ private String amount; /** ๅธ็ง */ private String moneytype; /** ๅฏนๆ‹ผๅ‡‘ไธฒMD5็ง้’ฅๅŠ ๅฏ†ๅŽ็š„ๅ€ผ */ private String md5info; /** ๆ”ถ่ดงไบบ */ private String rcvname; /** ๆ”ถ่ดงๅœฐๅ€ */ private String rcvaddr; /** ๆ”ถ่ดงไบบ็”ต่ฏ */ private String rcvtel; /** ๆ”ถ่ดงไบบ้‚ฎ็ผ– */ private String rcvpost; /** ๆ”ถ่ดงไบบ้‚ฎไปถ */ private String rcvemail; /** ๆ”ถ่ดงไบบๆ‰‹ๆœบๅท */ private String rcvmobile; // ------------------------------------------------------------------------- /** ่ฎข่ดงไบบๅง“ๅ */ private String ordername; /** ่ฎข่ดงไบบๅœฐๅ€ */ private String orderaddr; /** ่ฎข่ดงไบบ็”ต่ฏ */ private String ordertel; /** ่ฎข่ดงไบบ้‚ฎ็ผ– */ private String orderpost; /** ่ฎข่ดงไบบ้‚ฎไปถ */ private String orderemail; /** ่ฎข่ดงไบบๆ‰‹ๆœบๅท */ private String ordermobile; // ------------------------------------------------------------------------- /** ๅค‡ๆณจๅญ—ๆฎต1 */ private String remark1; /** ๅค‡ๆณจๅญ—ๆฎต2 */ private String remark2; public NetPayEntity() { // ๅˆๅง‹ๅŒ–ๅฎšไน‰ๅ‚ๆ•ฐ mid = "1001"; url = "http://www.opentravelsoft.com/ReceivePay.action"; key = "test"; moneytype = "CNY"; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getMoneytype() { return moneytype; } public void setMoneytype(String moneytype) { this.moneytype = moneytype; } public String getMd5info() { return md5info; } public void setMd5info(String md5info) { this.md5info = md5info; } public String getRcvname() { return rcvname; } public void setRcvname(String rcvname) { this.rcvname = rcvname; } public String getRcvaddr() { return rcvaddr; } public void setRcvaddr(String rcvaddr) { this.rcvaddr = rcvaddr; } public String getRcvtel() { return rcvtel; } public void setRcvtel(String rcvtel) { this.rcvtel = rcvtel; } public String getRcvpost() { return rcvpost; } public void setRcvpost(String rcvpost) { this.rcvpost = rcvpost; } public String getRcvemail() { return rcvemail; } public void setRcvemail(String rcvemail) { this.rcvemail = rcvemail; } public String getRcvmobile() { return rcvmobile; } public void setRcvmobile(String rcvmobile) { this.rcvmobile = rcvmobile; } public String getOrdername() { return ordername; } public void setOrdername(String ordername) { this.ordername = ordername; } public String getOrderaddr() { return orderaddr; } public void setOrderaddr(String orderaddr) { this.orderaddr = orderaddr; } public String getOrdertel() { return ordertel; } public void setOrdertel(String ordertel) { this.ordertel = ordertel; } public String getOrderpost() { return orderpost; } public void setOrderpost(String orderpost) { this.orderpost = orderpost; } public String getOrderemail() { return orderemail; } public void setOrderemail(String orderemail) { this.orderemail = orderemail; } public String getOrdermobile() { return ordermobile; } public void setOrdermobile(String ordermobile) { this.ordermobile = ordermobile; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public void refreshMd5key() { String text = amount + moneytype + oid + mid + url + key; // ๆ‹ผๅ‡‘ๅŠ ๅฏ†ไธฒ md5info = new MD5().getMD5ofStr(text); // // ็ฝ‘้“ถๆ”ฏไป˜ๅนณๅฐๅฏนMD5ๅ€ผๅช่ฎคๅคงๅ†™ๅญ—็ฌฆไธฒ๏ผŒๆ‰€ไปฅๅฐๅ†™็š„MD5ๅ€ผๅพ—่ฝฌๆขไธบๅคงๅ†™ } }
stevenzh/tourismwork
src/modules/model/src/main/java/com/opentravelsoft/entity/product/NetPayEntity.java
Java
gpl-2.0
5,861
<?php /** * All the functions releated to databases is here. * * This file will include stuff like, connect, write, read, remove etc. * * @category Database * @package ControlPanel * @author Dennis &lt;dennistryy3@gmail.com> * @copyright 2014 Dennis Planting */ class Commands { /** * Broadcast a message. * * @param string $message The message to broadcast. * @param string $name Incase you want a different name then the default select it here. <i>Default is "Server"</i> * @param string $default If you want to send a broadcast through the vanilla command or through a plugin like Essentials. * * @return If the command was successfully sent or not. */ function broadcast($message, $name="", $default=false) { } } ?>
ExpandH/EMCP
Core/Function/Plugins/Commands.php
PHP
gpl-2.0
817
package CtrLayer; import ModelLayer.*; /** * Controller for anythign related to Person management. * * @author Jacob Pedersen * @version (11-12-2014) dd-mm-yyyy */ public class PersonController { private PersonContainer personContainer; /** * Constructor for objects of class PersonController */ public PersonController() { personContainer = PersonContainer.getPersonContainer(); addTestPeople(); } /** * Create a new worker and add it to the person container. * @param name the workers name. * @param adress the workes adress. * @param phoneNumber the workes phone number. * @param email The workers e-mail. * @param age The workers age. * @param isLeader if the worker is a leader or not. * @param role The workes role in the company * @param department The department which the worker works in. * @return true if the worker was added successfully. false if not. */ public boolean addWorker(String name, String adress, String phoneNumber, String email, int age, boolean isLeader, String role, String department) { if(personContainer.findPersonByPhoneNumber(phoneNumber) == null) { int id = personContainer.getLastId() + 1; Worker worker = new Worker(id, name, adress, phoneNumber, email, age, isLeader, role, department); personContainer.addWorker(worker); return true; } return false; } /** * Create a new customer and add it to the person container. * @param name the customers name. * @param adress the customers adress. * @param phoneNumber the customers phone number. * @param email The customers e-mail. * @param age The customers age. * @return true if the worker was added successfully. false if not. */ public boolean addCustomer(String name, String adress, String phoneNumber, String email, int age) { if(personContainer.findPersonByPhoneNumber(phoneNumber) == null) { int id = personContainer.getLastId() + 1; Customer customer = new Customer(id, name, adress, phoneNumber, email, age); personContainer.addCustomer(customer); return true; } return false; } /** * Remove a specific person given by it's id. * @param id The persons id. * @return true if the person was removed successfully. false if not. */ public boolean removePersonById(int id) { return personContainer.removePerson(id); } /** * Remove a specific person given by it's phone number. * @param phoneNumber The persons phone number. * @return true if the person was found successfully. false if not. */ public boolean removePersonByPhoneNumber(String phoneNumber) { Person person = personContainer.findPersonByPhoneNumber(phoneNumber); if(person != null) { int id = person.getId(); return personContainer.removePerson(id); } return false; } /** * Find a specific person by the given id. * @param id The persons id. * @return The person if the person was found successfully. null if not. */ public Person findPerson(int id) { return personContainer.findPersonById(id); } /** * Find a specific person by the given phone number. * @param id The persons phone number. * @return The person if the person was found successfully. null if not. */ public Person findPersonByPhoneNumber(String phoneNumber) { return personContainer.findPersonByPhoneNumber(phoneNumber); } /** * Checks if the person is of the type Customer or not * @param person The person to check. * @return true if the person is of the type Customer. false if not. */ public boolean isCustomer(Person person) { if(person instanceof Customer) { return true; } return false; } /** * Add money to a customers balance. * @param person The customer to add the money to of the type person. * @param amount The amount to add to the custoemr. */ public boolean addToCustomerBalanceById(Person person, double amount) { if(isCustomer(person)) { Customer customer = (Customer)person; customer.addToBalance(amount); return true; } return false; } public void addTestPeople() { addWorker("Hans", "Hansevej", "27834173", "gud@gudenet.dk", 20, true, "boss", "all"); addWorker("Jens", "Hansevej", "27834174", "guden@gudenet.dk", 20, true, "boss", "all"); addCustomer("Sofie", "Sofievej", "88888888", "sofie@sofienet.dk", 20); } }
dmab0914-Gruppe-2/Vestbjerg-Byggecenter
src/CtrLayer/PersonController.java
Java
gpl-2.0
4,942
package containernode import ( "math/rand" "sort" "github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/leafnodes" "github.com/obieq/goar/db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/types" ) type subjectOrContainerNode struct { containerNode *ContainerNode subjectNode leafnodes.SubjectNode } func (n subjectOrContainerNode) text() string { if n.containerNode != nil { return n.containerNode.Text() } else { return n.subjectNode.Text() } } type CollatedNodes struct { Containers []*ContainerNode Subject leafnodes.SubjectNode } type ContainerNode struct { text string flag types.FlagType codeLocation types.CodeLocation setupNodes []leafnodes.BasicNode subjectAndContainerNodes []subjectOrContainerNode } func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { return &ContainerNode{ text: text, flag: flag, codeLocation: codeLocation, } } func (container *ContainerNode) Shuffle(r *rand.Rand) { sort.Sort(container) permutation := r.Perm(len(container.subjectAndContainerNodes)) shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) for i, j := range permutation { shuffledNodes[i] = container.subjectAndContainerNodes[j] } container.subjectAndContainerNodes = shuffledNodes } func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { if node.flag == types.FlagTypePending { return false } shouldUnfocus := false for _, subjectOrContainerNode := range node.subjectAndContainerNodes { if subjectOrContainerNode.containerNode != nil { shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus } else { shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus } } if shouldUnfocus { if node.flag == types.FlagTypeFocused { node.flag = types.FlagTypeNone } return true } return node.flag == types.FlagTypeFocused } func (node *ContainerNode) Collate() []CollatedNodes { return node.collate([]*ContainerNode{}) } func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { collated := make([]CollatedNodes, 0) containers := make([]*ContainerNode, len(enclosingContainers)) copy(containers, enclosingContainers) containers = append(containers, node) for _, subjectOrContainer := range node.subjectAndContainerNodes { if subjectOrContainer.containerNode != nil { collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) } else { collated = append(collated, CollatedNodes{ Containers: containers, Subject: subjectOrContainer.subjectNode, }) } } return collated } func (node *ContainerNode) PushContainerNode(container *ContainerNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) } func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) } func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { node.setupNodes = append(node.setupNodes, setupNode) } func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { nodes := []leafnodes.BasicNode{} for _, setupNode := range node.setupNodes { if setupNode.Type() == nodeType { nodes = append(nodes, setupNode) } } return nodes } func (node *ContainerNode) Text() string { return node.text } func (node *ContainerNode) CodeLocation() types.CodeLocation { return node.codeLocation } func (node *ContainerNode) Flag() types.FlagType { return node.flag } //sort.Interface func (node *ContainerNode) Len() int { return len(node.subjectAndContainerNodes) } func (node *ContainerNode) Less(i, j int) bool { return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() } func (node *ContainerNode) Swap(i, j int) { node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] }
obieq/goar
db/couchbase/Godeps/_workspace/src/github.com/onsi/ginkgo/internal/containernode/container_node.go
GO
gpl-2.0
4,264
<?php /** * The template for displaying archive pages * * @link https://codex.wordpress.org/Template_Hierarchy * * @package whank */ get_header(); ?> <?php do_action( 'whank_before_body_content' ); ?> <div id="primary" class="content-area col-md-8"> <main id="main" class="site-main"> <div class="container-fluid"> <div class="row"> <div class="archive page"> <?php if ( have_posts() ) : ?> <header class="page-header page-title text-center"> <?php the_archive_title( '<h2 class="page-title">', '</h2>' ); the_archive_description( '<div class="archive-description">', '</div>' ); ?> </header><!-- .page-header --> <div class=""> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); endwhile; get_template_part( 'navigation', 'none'); ?> </div> <?php the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </div> <!-- archive page div end --> </div> <!-- row end --> </div> <!-- container-fluid --> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); do_action( 'whank_before_body_content' ); get_footer();
saazaan7/whank
archive.php
PHP
gpl-2.0
1,581
# # upgrade_bootloader_gui.py: gui bootloader dialog for upgrades # # Copyright (C) 2002, 2007 Red Hat, 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. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author(s): Jeremy Katz <katzj@redhat.com> # # must replace with explcit form so update disks will work from iw_gui import * import gtk from booty import checkbootloader from storage.devices import devicePathToName from constants import * import gettext _ = lambda x: gettext.ldgettext("anaconda", x) import logging log = logging.getLogger("anaconda") class UpgradeBootloaderWindow (InstallWindow): windowTitle = N_("Upgrade Boot Loader Configuration") def getPrev(self): pass def getNext(self): if self.nobl_radio.get_active(): self.dispatch.skipStep("bootloadersetup", skip = 1) self.dispatch.skipStep("bootloader", skip = 1) self.dispatch.skipStep("bootloaderadvanced", skip = 1) self.dispatch.skipStep("instbootloader", skip = 1) elif self.newbl_radio.get_active(): self.dispatch.skipStep("bootloadersetup", skip = 0) self.dispatch.skipStep("bootloader", skip = 0) self.dispatch.skipStep("bootloaderadvanced", skip = 0) self.dispatch.skipStep("instbootloader", skip = 0) self.bl.doUpgradeOnly = 0 else: self.dispatch.skipStep("bootloadersetup", skip = 0) self.dispatch.skipStep("bootloader", skip = 1) self.dispatch.skipStep("bootloaderadvanced", skip = 1) self.dispatch.skipStep("instbootloader", skip = 0) self.bl.doUpgradeOnly = 1 if self.type == "GRUB": self.bl.useGrubVal = 1 else: self.bl.useGrubVal = 0 self.bl.setDevice(devicePathToName(self.bootDev)) def _newToLibata(self, rootPath): # NOTE: any changes here need to be done in upgrade_bootloader_text too try: f = open("/proc/modules", "r") buf = f.read() if buf.find("libata") == -1: return False except: log.debug("error reading /proc/modules") pass try: f = open(rootPath + "/etc/modprobe.conf") except: log.debug("error reading /etc/modprobe.conf") return False modlines = f.readlines() f.close() try: f = open("/tmp/scsidisks") except: log.debug("error reading /tmp/scsidisks") return False mods = [] for l in f.readlines(): (disk, mod) = l.split() if mod.strip() not in mods: mods.append(mod.strip()) f.close() for l in modlines: stripped = l.strip() if stripped == "" or stripped[0] == "#": continue if stripped.find("scsi_hostadapter") != -1: mod = stripped.split()[-1] if mod in mods: mods.remove(mod) if len(mods) > 0: return True return False def getScreen(self, anaconda): self.dispatch = anaconda.dispatch self.bl = anaconda.id.bootloader newToLibata = self._newToLibata(anaconda.rootPath) (self.type, self.bootDev) = \ checkbootloader.getBootloaderTypeAndBoot(anaconda.rootPath, storage=anaconda.id.storage) self.update_radio = gtk.RadioButton(None, _("_Update boot loader configuration")) updatestr = _("This will update your current boot loader.") if newToLibata or (self.type is None or self.bootDev is None): if newToLibata: current = _("Due to system changes, your boot loader " "configuration can not be automatically updated.") else: current = _("The installer is unable to detect the boot loader " "currently in use on your system.") self.update_label = gtk.Label("%s" % (updatestr,)) self.update_radio.set_sensitive(False) self.update_label.set_sensitive(False) update = 0 else: current = _("The installer has detected the %(type)s boot loader " "currently installed on %(bootDev)s.") \ % {'type': self.type, 'bootDev': self.bootDev} self.update_label = gtk.Label("%s %s" % (updatestr, _("This is the recommended option."))) self.update_radio.set_active(False) update = 1 self.newbl_radio = gtk.RadioButton(self.update_radio, _("_Create new boot loader " "configuration")) self.newbl_label = gtk.Label(_("This option creates a " "new boot loader configuration. If " "you wish to switch boot loaders, you " "should choose this.")) self.newbl_radio.set_active(False) self.nobl_radio = gtk.RadioButton(self.update_radio, _("_Skip boot loader updating")) self.nobl_label = gtk.Label(_("This option makes no changes to boot " "loader configuration. If you are " "using a third party boot loader, you " "should choose this.")) self.nobl_radio.set_active(False) for label in [self.update_label, self.nobl_label, self.newbl_label]: label.set_alignment(0.8, 0) label.set_size_request(275, -1) label.set_line_wrap(True) str = _("What would you like to do?") # if they have one, the default is to update, otherwise the # default is to not touch anything if update == 1: default = self.update_radio elif newToLibata: default = self.newbl_radio else: default = self.nobl_radio if not self.dispatch.stepInSkipList("bootloader"): self.newbl_radio.set_active(True) elif self.dispatch.stepInSkipList("instbootloader"): self.nobl_radio.set_active(True) else: default.set_active(True) box = gtk.VBox(False, 5) label = gtk.Label(current) label.set_line_wrap(True) label.set_alignment(0.5, 0.0) label.set_size_request(300, -1) label2 = gtk.Label(str) label2.set_line_wrap(True) label2.set_alignment(0.5, 0.0) label2.set_size_request(300, -1) box.pack_start(label, False) box.pack_start(label2, False, padding = 10) box.pack_start(self.update_radio, False) box.pack_start(self.update_label, False) box.pack_start(self.nobl_radio, False) box.pack_start(self.nobl_label, False) box.pack_start(self.newbl_radio, False) box.pack_start(self.newbl_label, False) a = gtk.Alignment(0.2, 0.1) a.add(box) return a
icomfort/anaconda
iw/upgrade_bootloader_gui.py
Python
gpl-2.0
7,815
/* * 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/>. */ /* * Scripts for spells with SPELLFAMILY_GENERIC spells used by items. * Ordered alphabetically using scriptname. * Scriptnames of files in this file should be prefixed with "spell_item_". */ #include "Player.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "SpellAuraEffects.h" #include "SkillDiscovery.h" #include "Battleground.h" // Generic script for handling item dummy effects which trigger another spell. class spell_item_trigger_spell : public SpellScriptLoader { private: uint32 _triggeredSpellId; public: spell_item_trigger_spell(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_item_trigger_spell_SpellScript : public SpellScript { PrepareSpellScript(spell_item_trigger_spell_SpellScript); private: uint32 _triggeredSpellId; public: spell_item_trigger_spell_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Item* item = GetCastItem()) caster->CastSpell(caster, _triggeredSpellId, true, item); } void Register() { OnEffectHit += SpellEffectFn(spell_item_trigger_spell_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_trigger_spell_SpellScript(_triggeredSpellId); } }; enum AegisOfPreservation { SPELL_AEGIS_HEAL = 23781 }; // 23780 - Aegis of Preservation class spell_item_aegis_of_preservation : public SpellScriptLoader { public: spell_item_aegis_of_preservation() : SpellScriptLoader("spell_item_aegis_of_preservation") { } class spell_item_aegis_of_preservation_AuraScript : public AuraScript { PrepareAuraScript(spell_item_aegis_of_preservation_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_AEGIS_HEAL)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_aegis_of_preservation_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_PROC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_item_aegis_of_preservation_AuraScript(); } }; // 26400 - Arcane Shroud class spell_item_arcane_shroud : public SpellScriptLoader { public: spell_item_arcane_shroud() : SpellScriptLoader("spell_item_arcane_shroud") { } class spell_item_arcane_shroud_AuraScript : public AuraScript { PrepareAuraScript(spell_item_arcane_shroud_AuraScript); void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) { int32 diff = GetUnitOwner()->getLevel() - 60; if (diff > 0) amount += 2 * diff; } void Register() { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_item_arcane_shroud_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_THREAT); } }; AuraScript* GetAuraScript() const { return new spell_item_arcane_shroud_AuraScript(); } }; // 64411 - Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings) enum BlessingOfAncientKings { SPELL_PROTECTION_OF_ANCIENT_KINGS = 64413 }; class spell_item_blessing_of_ancient_kings : public SpellScriptLoader { public: spell_item_blessing_of_ancient_kings() : SpellScriptLoader("spell_item_blessing_of_ancient_kings") { } class spell_item_blessing_of_ancient_kings_AuraScript : public AuraScript { PrepareAuraScript(spell_item_blessing_of_ancient_kings_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_PROTECTION_OF_ANCIENT_KINGS)) return false; return true; } bool CheckProc(ProcEventInfo& eventInfo) { return eventInfo.GetProcTarget(); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 absorb = int32(CalculatePct(eventInfo.GetHealInfo()->GetHeal(), 15.0f)); if (AuraEffect* protEff = eventInfo.GetProcTarget()->GetAuraEffect(SPELL_PROTECTION_OF_ANCIENT_KINGS, 0, eventInfo.GetActor()->GetGUID())) { // The shield can grow to a maximum size of 20,000 damage absorbtion protEff->SetAmount(std::min<int32>(protEff->GetAmount() + absorb, 20000)); // Refresh and return to prevent replacing the aura aurEff->GetBase()->RefreshDuration(); } else GetTarget()->CastCustomSpell(SPELL_PROTECTION_OF_ANCIENT_KINGS, SPELLVALUE_BASE_POINT0, absorb, eventInfo.GetProcTarget(), true, NULL, aurEff); } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_blessing_of_ancient_kings_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_blessing_of_ancient_kings_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_blessing_of_ancient_kings_AuraScript(); } }; // 8342 - Defibrillate (Goblin Jumper Cables) have 33% chance on success // 22999 - Defibrillate (Goblin Jumper Cables XL) have 50% chance on success // 54732 - Defibrillate (Gnomish Army Knife) have 67% chance on success enum Defibrillate { SPELL_GOBLIN_JUMPER_CABLES_FAIL = 8338, SPELL_GOBLIN_JUMPER_CABLES_XL_FAIL = 23055 }; class spell_item_defibrillate : public SpellScriptLoader { public: spell_item_defibrillate(char const* name, uint8 chance, uint32 failSpell = 0) : SpellScriptLoader(name), _chance(chance), _failSpell(failSpell) { } class spell_item_defibrillate_SpellScript : public SpellScript { PrepareSpellScript(spell_item_defibrillate_SpellScript); public: spell_item_defibrillate_SpellScript(uint8 chance, uint32 failSpell) : SpellScript(), _chance(chance), _failSpell(failSpell) { } bool Validate(SpellInfo const* /*spellInfo*/) { if (_failSpell && !sSpellMgr->GetSpellInfo(_failSpell)) return false; return true; } void HandleScript(SpellEffIndex effIndex) { if (roll_chance_i(_chance)) { PreventHitDefaultEffect(effIndex); if (_failSpell) GetCaster()->CastSpell(GetCaster(), _failSpell, true, GetCastItem()); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_defibrillate_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_RESURRECT); } private: uint8 _chance; uint32 _failSpell; }; SpellScript* GetSpellScript() const { return new spell_item_defibrillate_SpellScript(_chance, _failSpell); } private: uint8 _chance; uint32 _failSpell; }; enum DesperateDefense { SPELL_DESPERATE_RAGE = 33898 }; // 33896 - Desperate Defense class spell_item_desperate_defense : public SpellScriptLoader { public: spell_item_desperate_defense() : SpellScriptLoader("spell_item_desperate_defense") { } class spell_item_desperate_defense_AuraScript : public AuraScript { PrepareAuraScript(spell_item_desperate_defense_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_DESPERATE_RAGE)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_desperate_defense_AuraScript::HandleProc, EFFECT_2, SPELL_AURA_PROC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_item_desperate_defense_AuraScript(); } }; // http://www.wowhead.com/item=6522 Deviate Fish // 8063 Deviate Fish enum DeviateFishSpells { SPELL_SLEEPY = 8064, SPELL_INVIGORATE = 8065, SPELL_SHRINK = 8066, SPELL_PARTY_TIME = 8067, SPELL_HEALTHY_SPIRIT = 8068, }; class spell_item_deviate_fish : public SpellScriptLoader { public: spell_item_deviate_fish() : SpellScriptLoader("spell_item_deviate_fish") { } class spell_item_deviate_fish_SpellScript : public SpellScript { PrepareSpellScript(spell_item_deviate_fish_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { for (uint32 spellId = SPELL_SLEEPY; spellId <= SPELL_HEALTHY_SPIRIT; ++spellId) if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = urand(SPELL_SLEEPY, SPELL_HEALTHY_SPIRIT); caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_deviate_fish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_deviate_fish_SpellScript(); } }; // http://www.wowhead.com/item=47499 Flask of the North // 67019 Flask of the North enum FlaskOfTheNorthSpells { SPELL_FLASK_OF_THE_NORTH_SP = 67016, SPELL_FLASK_OF_THE_NORTH_AP = 67017, SPELL_FLASK_OF_THE_NORTH_STR = 67018, }; class spell_item_flask_of_the_north : public SpellScriptLoader { public: spell_item_flask_of_the_north() : SpellScriptLoader("spell_item_flask_of_the_north") { } class spell_item_flask_of_the_north_SpellScript : public SpellScript { PrepareSpellScript(spell_item_flask_of_the_north_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_SP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_STR)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); std::vector<uint32> possibleSpells; switch (caster->getClass()) { case CLASS_WARLOCK: case CLASS_MAGE: case CLASS_PRIEST: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); break; case CLASS_DEATH_KNIGHT: case CLASS_WARRIOR: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR); break; case CLASS_ROGUE: case CLASS_HUNTER: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP); break; case CLASS_DRUID: case CLASS_PALADIN: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_STR); break; case CLASS_SHAMAN: possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_SP); possibleSpells.push_back(SPELL_FLASK_OF_THE_NORTH_AP); break; } caster->CastSpell(caster, possibleSpells[irand(0, (possibleSpells.size() - 1))], true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_flask_of_the_north_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_flask_of_the_north_SpellScript(); } }; // http://www.wowhead.com/item=10645 Gnomish Death Ray // 13280 Gnomish Death Ray enum GnomishDeathRay { SPELL_GNOMISH_DEATH_RAY_SELF = 13493, SPELL_GNOMISH_DEATH_RAY_TARGET = 13279, }; class spell_item_gnomish_death_ray : public SpellScriptLoader { public: spell_item_gnomish_death_ray() : SpellScriptLoader("spell_item_gnomish_death_ray") { } class spell_item_gnomish_death_ray_SpellScript : public SpellScript { PrepareSpellScript(spell_item_gnomish_death_ray_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_SELF) || !sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_TARGET)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { if (urand(0, 99) < 15) caster->CastSpell(caster, SPELL_GNOMISH_DEATH_RAY_SELF, true, NULL); // failure else caster->CastSpell(target, SPELL_GNOMISH_DEATH_RAY_TARGET, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_gnomish_death_ray_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_gnomish_death_ray_SpellScript(); } }; // http://www.wowhead.com/item=27388 Mr. Pinchy // 33060 Make a Wish enum MakeAWish { SPELL_MR_PINCHYS_BLESSING = 33053, SPELL_SUMMON_MIGHTY_MR_PINCHY = 33057, SPELL_SUMMON_FURIOUS_MR_PINCHY = 33059, SPELL_TINY_MAGICAL_CRAWDAD = 33062, SPELL_MR_PINCHYS_GIFT = 33064, }; class spell_item_make_a_wish : public SpellScriptLoader { public: spell_item_make_a_wish() : SpellScriptLoader("spell_item_make_a_wish") { } class spell_item_make_a_wish_SpellScript : public SpellScript { PrepareSpellScript(spell_item_make_a_wish_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_BLESSING) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_MIGHTY_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FURIOUS_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_TINY_MAGICAL_CRAWDAD) || !sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_GIFT)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_MR_PINCHYS_GIFT; switch (urand(1, 5)) { case 1: spellId = SPELL_MR_PINCHYS_BLESSING; break; case 2: spellId = SPELL_SUMMON_MIGHTY_MR_PINCHY; break; case 3: spellId = SPELL_SUMMON_FURIOUS_MR_PINCHY; break; case 4: spellId = SPELL_TINY_MAGICAL_CRAWDAD; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_make_a_wish_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_make_a_wish_SpellScript(); } }; // http://www.wowhead.com/item=32686 Mingo's Fortune Giblets // 40802 Mingo's Fortune Generator class spell_item_mingos_fortune_generator : public SpellScriptLoader { public: spell_item_mingos_fortune_generator() : SpellScriptLoader("spell_item_mingos_fortune_generator") { } class spell_item_mingos_fortune_generator_SpellScript : public SpellScript { PrepareSpellScript(spell_item_mingos_fortune_generator_SpellScript); void HandleDummy(SpellEffIndex effIndex) { // Selecting one from Bloodstained Fortune item uint32 newitemid; switch (urand(1, 20)) { case 1: newitemid = 32688; break; case 2: newitemid = 32689; break; case 3: newitemid = 32690; break; case 4: newitemid = 32691; break; case 5: newitemid = 32692; break; case 6: newitemid = 32693; break; case 7: newitemid = 32700; break; case 8: newitemid = 32701; break; case 9: newitemid = 32702; break; case 10: newitemid = 32703; break; case 11: newitemid = 32704; break; case 12: newitemid = 32705; break; case 13: newitemid = 32706; break; case 14: newitemid = 32707; break; case 15: newitemid = 32708; break; case 16: newitemid = 32709; break; case 17: newitemid = 32710; break; case 18: newitemid = 32711; break; case 19: newitemid = 32712; break; case 20: newitemid = 32713; break; default: return; } CreateItem(effIndex, newitemid); } void Register() { OnEffectHit += SpellEffectFn(spell_item_mingos_fortune_generator_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_mingos_fortune_generator_SpellScript(); } }; // 71875, 71877 - Item - Black Bruise: Necrotic Touch Proc enum NecroticTouch { SPELL_ITEM_NECROTIC_TOUCH_PROC = 71879 }; class spell_item_necrotic_touch : public SpellScriptLoader { public: spell_item_necrotic_touch() : SpellScriptLoader("spell_item_necrotic_touch") { } class spell_item_necrotic_touch_AuraScript : public AuraScript { PrepareAuraScript(spell_item_necrotic_touch_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_ITEM_NECROTIC_TOUCH_PROC)) return false; return true; } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 bp = CalculatePct(int32(eventInfo.GetDamageInfo()->GetDamage()), aurEff->GetAmount()); GetTarget()->CastCustomSpell(SPELL_ITEM_NECROTIC_TOUCH_PROC, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, NULL, aurEff); } void Register() { OnEffectProc += AuraEffectProcFn(spell_item_necrotic_touch_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_necrotic_touch_AuraScript(); } }; // http://www.wowhead.com/item=10720 Gnomish Net-o-Matic Projector // 13120 Net-o-Matic enum NetOMaticSpells { SPELL_NET_O_MATIC_TRIGGERED1 = 16566, SPELL_NET_O_MATIC_TRIGGERED2 = 13119, SPELL_NET_O_MATIC_TRIGGERED3 = 13099, }; class spell_item_net_o_matic : public SpellScriptLoader { public: spell_item_net_o_matic() : SpellScriptLoader("spell_item_net_o_matic") { } class spell_item_net_o_matic_SpellScript : public SpellScript { PrepareSpellScript(spell_item_net_o_matic_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) { uint32 spellId = SPELL_NET_O_MATIC_TRIGGERED3; uint32 roll = urand(0, 99); if (roll < 2) // 2% for 30 sec self root (off-like chance unknown) spellId = SPELL_NET_O_MATIC_TRIGGERED1; else if (roll < 4) // 2% for 20 sec root, charge to target (off-like chance unknown) spellId = SPELL_NET_O_MATIC_TRIGGERED2; GetCaster()->CastSpell(target, spellId, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_net_o_matic_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_net_o_matic_SpellScript(); } }; // http://www.wowhead.com/item=8529 Noggenfogger Elixir // 16589 Noggenfogger Elixir enum NoggenfoggerElixirSpells { SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1 = 16595, SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2 = 16593, SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3 = 16591, }; class spell_item_noggenfogger_elixir : public SpellScriptLoader { public: spell_item_noggenfogger_elixir() : SpellScriptLoader("spell_item_noggenfogger_elixir") { } class spell_item_noggenfogger_elixir_SpellScript : public SpellScript { PrepareSpellScript(spell_item_noggenfogger_elixir_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3; switch (urand(1, 3)) { case 1: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_noggenfogger_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_noggenfogger_elixir_SpellScript(); } }; // 17512 - Piccolo of the Flaming Fire class spell_item_piccolo_of_the_flaming_fire : public SpellScriptLoader { public: spell_item_piccolo_of_the_flaming_fire() : SpellScriptLoader("spell_item_piccolo_of_the_flaming_fire") { } class spell_item_piccolo_of_the_flaming_fire_SpellScript : public SpellScript { PrepareSpellScript(spell_item_piccolo_of_the_flaming_fire_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Player* target = GetHitPlayer()) target->HandleEmoteCommand(EMOTE_STATE_DANCE); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_piccolo_of_the_flaming_fire_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_piccolo_of_the_flaming_fire_SpellScript(); } }; // http://www.wowhead.com/item=6657 Savory Deviate Delight // 8213 Savory Deviate Delight enum SavoryDeviateDelight { SPELL_FLIP_OUT_MALE = 8219, SPELL_FLIP_OUT_FEMALE = 8220, SPELL_YAAARRRR_MALE = 8221, SPELL_YAAARRRR_FEMALE = 8222, }; class spell_item_savory_deviate_delight : public SpellScriptLoader { public: spell_item_savory_deviate_delight() : SpellScriptLoader("spell_item_savory_deviate_delight") { } class spell_item_savory_deviate_delight_SpellScript : public SpellScript { PrepareSpellScript(spell_item_savory_deviate_delight_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { for (uint32 spellId = SPELL_FLIP_OUT_MALE; spellId <= SPELL_YAAARRRR_FEMALE; ++spellId) if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = 0; switch (urand(1, 2)) { // Flip Out - ninja case 1: spellId = (caster->getGender() == GENDER_MALE ? SPELL_FLIP_OUT_MALE : SPELL_FLIP_OUT_FEMALE); break; // Yaaarrrr - pirate case 2: spellId = (caster->getGender() == GENDER_MALE ? SPELL_YAAARRRR_MALE : SPELL_YAAARRRR_FEMALE); break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_savory_deviate_delight_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_savory_deviate_delight_SpellScript(); } }; // 48129 - Scroll of Recall // 60320 - Scroll of Recall II // 60321 - Scroll of Recall III enum ScrollOfRecall { SPELL_SCROLL_OF_RECALL_I = 48129, SPELL_SCROLL_OF_RECALL_II = 60320, SPELL_SCROLL_OF_RECALL_III = 60321, SPELL_LOST = 60444, SPELL_SCROLL_OF_RECALL_FAIL_ALLIANCE_1 = 60323, SPELL_SCROLL_OF_RECALL_FAIL_HORDE_1 = 60328, }; class spell_item_scroll_of_recall : public SpellScriptLoader { public: spell_item_scroll_of_recall() : SpellScriptLoader("spell_item_scroll_of_recall") { } class spell_item_scroll_of_recall_SpellScript : public SpellScript { PrepareSpellScript(spell_item_scroll_of_recall_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleScript(SpellEffIndex effIndex) { Unit* caster = GetCaster(); uint8 maxSafeLevel = 0; switch (GetSpellInfo()->Id) { case SPELL_SCROLL_OF_RECALL_I: // Scroll of Recall maxSafeLevel = 40; break; case SPELL_SCROLL_OF_RECALL_II: // Scroll of Recall II maxSafeLevel = 70; break; case SPELL_SCROLL_OF_RECALL_III: // Scroll of Recal III maxSafeLevel = 80; break; default: break; } if (caster->getLevel() > maxSafeLevel) { caster->CastSpell(caster, SPELL_LOST, true); // ALLIANCE from 60323 to 60330 - HORDE from 60328 to 60335 uint32 spellId = SPELL_SCROLL_OF_RECALL_FAIL_ALLIANCE_1; if (GetCaster()->ToPlayer()->GetTeam() == HORDE) spellId = SPELL_SCROLL_OF_RECALL_FAIL_HORDE_1; GetCaster()->CastSpell(GetCaster(), spellId + urand(0, 7), true); PreventHitDefaultEffect(effIndex); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_scroll_of_recall_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_TELEPORT_UNITS); } }; SpellScript* GetSpellScript() const { return new spell_item_scroll_of_recall_SpellScript(); } }; // 71169 - Shadow's Fate (Shadowmourne questline) enum ShadowsFate { SPELL_SOUL_FEAST = 71203, QUEST_A_FEAST_OF_SOULS = 24547 }; class spell_item_shadows_fate : public SpellScriptLoader { public: spell_item_shadows_fate() : SpellScriptLoader("spell_item_shadows_fate") { } class spell_item_shadows_fate_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadows_fate_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_FEAST)) return false; if (!sObjectMgr->GetQuestTemplate(QUEST_A_FEAST_OF_SOULS)) return false; return true; } bool Load() { _procTarget = NULL; return true; } bool CheckProc(ProcEventInfo& /*eventInfo*/) { _procTarget = GetCaster(); return _procTarget && _procTarget->GetTypeId() == TYPEID_PLAYER && _procTarget->ToPlayer()->GetQuestStatus(QUEST_A_FEAST_OF_SOULS) == QUEST_STATUS_INCOMPLETE; } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); GetTarget()->CastSpell(_procTarget, SPELL_SOUL_FEAST, true); } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_shadows_fate_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_shadows_fate_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } private: Unit* _procTarget; }; AuraScript* GetAuraScript() const { return new spell_item_shadows_fate_AuraScript(); } }; enum Shadowmourne { SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE = 71904, SPELL_SHADOWMOURNE_SOUL_FRAGMENT = 71905, SPELL_SHADOWMOURNE_VISUAL_LOW = 72521, SPELL_SHADOWMOURNE_VISUAL_HIGH = 72523, SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF = 73422, }; // 71903 - Item - Shadowmourne Legendary class spell_item_shadowmourne : public SpellScriptLoader { public: spell_item_shadowmourne() : SpellScriptLoader("spell_item_shadowmourne") { } class spell_item_shadowmourne_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadowmourne_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) return false; if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) return false; return true; } bool CheckProc(ProcEventInfo& eventInfo) { if (GetTarget()->HasAura(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) // cant collect shards while under effect of Chaos Bane buff return false; return eventInfo.GetProcTarget() && eventInfo.GetProcTarget()->isAlive(); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, NULL, aurEff); // this can't be handled in AuraScript of SoulFragments because we need to know victim if (Aura* soulFragments = GetTarget()->GetAura(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) { if (soulFragments->GetStackAmount() >= 10) { GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, NULL, aurEff); soulFragments->Remove(); } } } void Register() { DoCheckProc += AuraCheckProcFn(spell_item_shadowmourne_AuraScript::CheckProc); OnEffectProc += AuraEffectProcFn(spell_item_shadowmourne_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } }; AuraScript* GetAuraScript() const { return new spell_item_shadowmourne_AuraScript(); } }; // 71905 - Soul Fragment class spell_item_shadowmourne_soul_fragment : public SpellScriptLoader { public: spell_item_shadowmourne_soul_fragment() : SpellScriptLoader("spell_item_shadowmourne_soul_fragment") { } class spell_item_shadowmourne_soul_fragment_AuraScript : public AuraScript { PrepareAuraScript(spell_item_shadowmourne_soul_fragment_AuraScript); bool Validate(SpellInfo const* /*spellInfo*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_LOW) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_HIGH) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) return false; return true; } void OnStackChange(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); switch (GetStackAmount()) { case 1: target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_LOW, true); break; case 6: target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW); target->CastSpell(target, SPELL_SHADOWMOURNE_VISUAL_HIGH, true); break; case 10: target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH); target->CastSpell(target, SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF, true); break; default: break; } } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW); target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_HIGH); } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_item_shadowmourne_soul_fragment_AuraScript::OnStackChange, EFFECT_0, SPELL_AURA_MOD_STAT, AuraEffectHandleModes(AURA_EFFECT_HANDLE_REAL | AURA_EFFECT_HANDLE_REAPPLY)); AfterEffectRemove += AuraEffectRemoveFn(spell_item_shadowmourne_soul_fragment_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_STAT, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_item_shadowmourne_soul_fragment_AuraScript(); } }; // http://www.wowhead.com/item=7734 Six Demon Bag // 14537 Six Demon Bag enum SixDemonBagSpells { SPELL_FROSTBOLT = 11538, SPELL_POLYMORPH = 14621, SPELL_SUMMON_FELHOUND_MINION = 14642, SPELL_FIREBALL = 15662, SPELL_CHAIN_LIGHTNING = 21179, SPELL_ENVELOPING_WINDS = 25189, }; class spell_item_six_demon_bag : public SpellScriptLoader { public: spell_item_six_demon_bag() : SpellScriptLoader("spell_item_six_demon_bag") { } class spell_item_six_demon_bag_SpellScript : public SpellScript { PrepareSpellScript(spell_item_six_demon_bag_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FROSTBOLT) || !sSpellMgr->GetSpellInfo(SPELL_POLYMORPH) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FELHOUND_MINION) || !sSpellMgr->GetSpellInfo(SPELL_FIREBALL) || !sSpellMgr->GetSpellInfo(SPELL_CHAIN_LIGHTNING) || !sSpellMgr->GetSpellInfo(SPELL_ENVELOPING_WINDS)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { uint32 spellId = 0; uint32 rand = urand(0, 99); if (rand < 25) // Fireball (25% chance) spellId = SPELL_FIREBALL; else if (rand < 50) // Frostball (25% chance) spellId = SPELL_FROSTBOLT; else if (rand < 70) // Chain Lighting (20% chance) spellId = SPELL_CHAIN_LIGHTNING; else if (rand < 80) // Polymorph (10% chance) { spellId = SPELL_POLYMORPH; if (urand(0, 100) <= 30) // 30% chance to self-cast target = caster; } else if (rand < 95) // Enveloping Winds (15% chance) spellId = SPELL_ENVELOPING_WINDS; else // Summon Felhund minion (5% chance) { spellId = SPELL_SUMMON_FELHOUND_MINION; target = caster; } caster->CastSpell(target, spellId, true, GetCastItem()); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_six_demon_bag_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_six_demon_bag_SpellScript(); } }; // 28862 - The Eye of Diminution class spell_item_the_eye_of_diminution : public SpellScriptLoader { public: spell_item_the_eye_of_diminution() : SpellScriptLoader("spell_item_the_eye_of_diminution") { } class spell_item_the_eye_of_diminution_AuraScript : public AuraScript { PrepareAuraScript(spell_item_the_eye_of_diminution_AuraScript); void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) { int32 diff = GetUnitOwner()->getLevel() - 60; if (diff > 0) amount += diff; } void Register() { DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_item_the_eye_of_diminution_AuraScript::CalculateAmount, EFFECT_0, SPELL_AURA_MOD_THREAT); } }; AuraScript* GetAuraScript() const { return new spell_item_the_eye_of_diminution_AuraScript(); } }; // http://www.wowhead.com/item=44012 Underbelly Elixir // 59640 Underbelly Elixir enum UnderbellyElixirSpells { SPELL_UNDERBELLY_ELIXIR_TRIGGERED1 = 59645, SPELL_UNDERBELLY_ELIXIR_TRIGGERED2 = 59831, SPELL_UNDERBELLY_ELIXIR_TRIGGERED3 = 59843, }; class spell_item_underbelly_elixir : public SpellScriptLoader { public: spell_item_underbelly_elixir() : SpellScriptLoader("spell_item_underbelly_elixir") { } class spell_item_underbelly_elixir_SpellScript : public SpellScript { PrepareSpellScript(spell_item_underbelly_elixir_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED3)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED3; switch (urand(1, 3)) { case 1: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED2; break; } caster->CastSpell(caster, spellId, true, NULL); } void Register() { OnEffectHit += SpellEffectFn(spell_item_underbelly_elixir_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_underbelly_elixir_SpellScript(); } }; enum AirRifleSpells { SPELL_AIR_RIFLE_HOLD_VISUAL = 65582, SPELL_AIR_RIFLE_SHOOT = 67532, SPELL_AIR_RIFLE_SHOOT_SELF = 65577, }; class spell_item_red_rider_air_rifle : public SpellScriptLoader { public: spell_item_red_rider_air_rifle() : SpellScriptLoader("spell_item_red_rider_air_rifle") { } class spell_item_red_rider_air_rifle_SpellScript : public SpellScript { PrepareSpellScript(spell_item_red_rider_air_rifle_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_HOLD_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT_SELF)) return false; return true; } void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) { caster->CastSpell(caster, SPELL_AIR_RIFLE_HOLD_VISUAL, true); // needed because this spell shares GCD with its triggered spells (which must not be cast with triggered flag) if (Player* player = caster->ToPlayer()) player->GetGlobalCooldownMgr().CancelGlobalCooldown(GetSpellInfo()); if (urand(0, 4)) caster->CastSpell(target, SPELL_AIR_RIFLE_SHOOT, false); else caster->CastSpell(caster, SPELL_AIR_RIFLE_SHOOT_SELF, false); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_red_rider_air_rifle_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_red_rider_air_rifle_SpellScript(); } }; enum GenericData { SPELL_ARCANITE_DRAGONLING = 19804, SPELL_BATTLE_CHICKEN = 13166, SPELL_MECHANICAL_DRAGONLING = 4073, SPELL_MITHRIL_MECHANICAL_DRAGONLING = 12749, }; enum CreateHeartCandy { ITEM_HEART_CANDY_1 = 21818, ITEM_HEART_CANDY_2 = 21817, ITEM_HEART_CANDY_3 = 21821, ITEM_HEART_CANDY_4 = 21819, ITEM_HEART_CANDY_5 = 21816, ITEM_HEART_CANDY_6 = 21823, ITEM_HEART_CANDY_7 = 21822, ITEM_HEART_CANDY_8 = 21820, }; class spell_item_create_heart_candy : public SpellScriptLoader { public: spell_item_create_heart_candy() : SpellScriptLoader("spell_item_create_heart_candy") { } class spell_item_create_heart_candy_SpellScript : public SpellScript { PrepareSpellScript(spell_item_create_heart_candy_SpellScript); void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Player* target = GetHitPlayer()) { static const uint32 items[] = {ITEM_HEART_CANDY_1, ITEM_HEART_CANDY_2, ITEM_HEART_CANDY_3, ITEM_HEART_CANDY_4, ITEM_HEART_CANDY_5, ITEM_HEART_CANDY_6, ITEM_HEART_CANDY_7, ITEM_HEART_CANDY_8}; target->AddItem(items[urand(0, 7)], 1); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_create_heart_candy_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_create_heart_candy_SpellScript(); } }; class spell_item_book_of_glyph_mastery : public SpellScriptLoader { public: spell_item_book_of_glyph_mastery() : SpellScriptLoader("spell_item_book_of_glyph_mastery") {} class spell_item_book_of_glyph_mastery_SpellScript : public SpellScript { PrepareSpellScript(spell_item_book_of_glyph_mastery_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } SpellCastResult CheckRequirement() { if (HasDiscoveredAllSpells(GetSpellInfo()->Id, GetCaster()->ToPlayer())) { SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_LEARNED_EVERYTHING); return SPELL_FAILED_CUSTOM_ERROR; } return SPELL_CAST_OK; } void HandleScript(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); uint32 spellId = GetSpellInfo()->Id; // learn random explicit discovery recipe (if any) if (uint32 discoveredSpellId = GetExplicitDiscoverySpell(spellId, caster)) caster->learnSpell(discoveredSpellId, false); } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_book_of_glyph_mastery_SpellScript::CheckRequirement); OnEffectHitTarget += SpellEffectFn(spell_item_book_of_glyph_mastery_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_item_book_of_glyph_mastery_SpellScript(); } }; enum GiftOfTheHarvester { NPC_GHOUL = 28845, MAX_GHOULS = 5, }; class spell_item_gift_of_the_harvester : public SpellScriptLoader { public: spell_item_gift_of_the_harvester() : SpellScriptLoader("spell_item_gift_of_the_harvester") {} class spell_item_gift_of_the_harvester_SpellScript : public SpellScript { PrepareSpellScript(spell_item_gift_of_the_harvester_SpellScript); SpellCastResult CheckRequirement() { std::list<Creature*> ghouls; GetCaster()->GetAllMinionsByEntry(ghouls, NPC_GHOUL); if (ghouls.size() >= MAX_GHOULS) { SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_TOO_MANY_GHOULS); return SPELL_FAILED_CUSTOM_ERROR; } return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_gift_of_the_harvester_SpellScript::CheckRequirement); } }; SpellScript* GetSpellScript() const { return new spell_item_gift_of_the_harvester_SpellScript(); } }; enum Sinkholes { NPC_SOUTH_SINKHOLE = 25664, NPC_NORTHEAST_SINKHOLE = 25665, NPC_NORTHWEST_SINKHOLE = 25666, }; class spell_item_map_of_the_geyser_fields : public SpellScriptLoader { public: spell_item_map_of_the_geyser_fields() : SpellScriptLoader("spell_item_map_of_the_geyser_fields") {} class spell_item_map_of_the_geyser_fields_SpellScript : public SpellScript { PrepareSpellScript(spell_item_map_of_the_geyser_fields_SpellScript); SpellCastResult CheckSinkholes() { Unit* caster = GetCaster(); if (caster->FindNearestCreature(NPC_SOUTH_SINKHOLE, 30.0f, true) || caster->FindNearestCreature(NPC_NORTHEAST_SINKHOLE, 30.0f, true) || caster->FindNearestCreature(NPC_NORTHWEST_SINKHOLE, 30.0f, true)) return SPELL_CAST_OK; SetCustomCastResultMessage(SPELL_CUSTOM_ERROR_MUST_BE_CLOSE_TO_SINKHOLE); return SPELL_FAILED_CUSTOM_ERROR; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_map_of_the_geyser_fields_SpellScript::CheckSinkholes); } }; SpellScript* GetSpellScript() const { return new spell_item_map_of_the_geyser_fields_SpellScript(); } }; enum VanquishedClutchesSpells { SPELL_CRUSHER = 64982, SPELL_CONSTRICTOR = 64983, SPELL_CORRUPTOR = 64984, }; class spell_item_vanquished_clutches : public SpellScriptLoader { public: spell_item_vanquished_clutches() : SpellScriptLoader("spell_item_vanquished_clutches") { } class spell_item_vanquished_clutches_SpellScript : public SpellScript { PrepareSpellScript(spell_item_vanquished_clutches_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CRUSHER) || !sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR) || !sSpellMgr->GetSpellInfo(SPELL_CORRUPTOR)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { uint32 spellId = RAND(SPELL_CRUSHER, SPELL_CONSTRICTOR, SPELL_CORRUPTOR); Unit* caster = GetCaster(); caster->CastSpell(caster, spellId, true); } void Register() { OnEffectHit += SpellEffectFn(spell_item_vanquished_clutches_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_vanquished_clutches_SpellScript(); } }; enum AshbringerSounds { SOUND_ASHBRINGER_1 = 8906, // "I was pure once" SOUND_ASHBRINGER_2 = 8907, // "Fought for righteousness" SOUND_ASHBRINGER_3 = 8908, // "I was once called Ashbringer" SOUND_ASHBRINGER_4 = 8920, // "Betrayed by my order" SOUND_ASHBRINGER_5 = 8921, // "Destroyed by Kel'Thuzad" SOUND_ASHBRINGER_6 = 8922, // "Made to serve" SOUND_ASHBRINGER_7 = 8923, // "My son watched me die" SOUND_ASHBRINGER_8 = 8924, // "Crusades fed his rage" SOUND_ASHBRINGER_9 = 8925, // "Truth is unknown to him" SOUND_ASHBRINGER_10 = 8926, // "Scarlet Crusade is pure no longer" SOUND_ASHBRINGER_11 = 8927, // "Balnazzar's crusade corrupted my son" SOUND_ASHBRINGER_12 = 8928, // "Kill them all!" }; class spell_item_ashbringer : public SpellScriptLoader { public: spell_item_ashbringer() : SpellScriptLoader("spell_item_ashbringer") {} class spell_item_ashbringer_SpellScript : public SpellScript { PrepareSpellScript(spell_item_ashbringer_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void OnDummyEffect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Player* player = GetCaster()->ToPlayer(); uint32 sound_id = RAND( SOUND_ASHBRINGER_1, SOUND_ASHBRINGER_2, SOUND_ASHBRINGER_3, SOUND_ASHBRINGER_4, SOUND_ASHBRINGER_5, SOUND_ASHBRINGER_6, SOUND_ASHBRINGER_7, SOUND_ASHBRINGER_8, SOUND_ASHBRINGER_9, SOUND_ASHBRINGER_10, SOUND_ASHBRINGER_11, SOUND_ASHBRINGER_12 ); // Ashbringers effect (spellID 28441) retriggers every 5 seconds, with a chance of making it say one of the above 12 sounds if (urand(0, 60) < 1) player->PlayDirectSound(sound_id, player); } void Register() { OnEffectHit += SpellEffectFn(spell_item_ashbringer_SpellScript::OnDummyEffect, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_ashbringer_SpellScript(); } }; enum MagicEater { SPELL_WILD_MAGIC = 58891, SPELL_WELL_FED_1 = 57288, SPELL_WELL_FED_2 = 57139, SPELL_WELL_FED_3 = 57111, SPELL_WELL_FED_4 = 57286, SPELL_WELL_FED_5 = 57291, }; class spell_magic_eater_food : public SpellScriptLoader { public: spell_magic_eater_food() : SpellScriptLoader("spell_magic_eater_food") {} class spell_magic_eater_food_AuraScript : public AuraScript { PrepareAuraScript(spell_magic_eater_food_AuraScript); void HandleTriggerSpell(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); Unit* target = GetTarget(); switch (urand(0, 5)) { case 0: target->CastSpell(target, SPELL_WILD_MAGIC, true); break; case 1: target->CastSpell(target, SPELL_WELL_FED_1, true); break; case 2: target->CastSpell(target, SPELL_WELL_FED_2, true); break; case 3: target->CastSpell(target, SPELL_WELL_FED_3, true); break; case 4: target->CastSpell(target, SPELL_WELL_FED_4, true); break; case 5: target->CastSpell(target, SPELL_WELL_FED_5, true); break; } } void Register() { OnEffectPeriodic += AuraEffectPeriodicFn(spell_magic_eater_food_AuraScript::HandleTriggerSpell, EFFECT_1, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const { return new spell_magic_eater_food_AuraScript(); } }; class spell_item_shimmering_vessel : public SpellScriptLoader { public: spell_item_shimmering_vessel() : SpellScriptLoader("spell_item_shimmering_vessel") { } class spell_item_shimmering_vessel_SpellScript : public SpellScript { PrepareSpellScript(spell_item_shimmering_vessel_SpellScript); void HandleDummy(SpellEffIndex /* effIndex */) { if (Creature* target = GetHitCreature()) target->setDeathState(JUST_RESPAWNED); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_shimmering_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_shimmering_vessel_SpellScript(); } }; enum PurifyHelboarMeat { SPELL_SUMMON_PURIFIED_HELBOAR_MEAT = 29277, SPELL_SUMMON_TOXIC_HELBOAR_MEAT = 29278, }; class spell_item_purify_helboar_meat : public SpellScriptLoader { public: spell_item_purify_helboar_meat() : SpellScriptLoader("spell_item_purify_helboar_meat") { } class spell_item_purify_helboar_meat_SpellScript : public SpellScript { PrepareSpellScript(spell_item_purify_helboar_meat_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PURIFIED_HELBOAR_MEAT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_TOXIC_HELBOAR_MEAT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, NULL); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_purify_helboar_meat_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_purify_helboar_meat_SpellScript(); } }; enum CrystalPrison { OBJECT_IMPRISONED_DOOMGUARD = 179644, }; class spell_item_crystal_prison_dummy_dnd : public SpellScriptLoader { public: spell_item_crystal_prison_dummy_dnd() : SpellScriptLoader("spell_item_crystal_prison_dummy_dnd") { } class spell_item_crystal_prison_dummy_dnd_SpellScript : public SpellScript { PrepareSpellScript(spell_item_crystal_prison_dummy_dnd_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sObjectMgr->GetGameObjectTemplate(OBJECT_IMPRISONED_DOOMGUARD)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (Creature* target = GetHitCreature()) if (target->isDead() && !target->isPet()) { GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), 0, 0, 0, 0, uint32(target->GetRespawnTime()-time(NULL))); target->DespawnOrUnsummon(); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_crystal_prison_dummy_dnd_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_crystal_prison_dummy_dnd_SpellScript(); } }; enum ReindeerTransformation { SPELL_FLYING_REINDEER_310 = 44827, SPELL_FLYING_REINDEER_280 = 44825, SPELL_FLYING_REINDEER_60 = 44824, SPELL_REINDEER_100 = 25859, SPELL_REINDEER_60 = 25858, }; class spell_item_reindeer_transformation : public SpellScriptLoader { public: spell_item_reindeer_transformation() : SpellScriptLoader("spell_item_reindeer_transformation") { } class spell_item_reindeer_transformation_SpellScript : public SpellScript { PrepareSpellScript(spell_item_reindeer_transformation_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_310) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_280) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_60) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_100) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_60)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (caster->HasAuraType(SPELL_AURA_MOUNTED)) { float flyspeed = caster->GetSpeedRate(MOVE_FLIGHT); float speed = caster->GetSpeedRate(MOVE_RUN); caster->RemoveAurasByType(SPELL_AURA_MOUNTED); //5 different spells used depending on mounted speed and if mount can fly or not if (flyspeed >= 4.1f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_310, true); //310% flying Reindeer else if (flyspeed >= 3.8f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_280, true); //280% flying Reindeer else if (flyspeed >= 1.6f) // Flying Reindeer caster->CastSpell(caster, SPELL_FLYING_REINDEER_60, true); //60% flying Reindeer else if (speed >= 2.0f) // Reindeer caster->CastSpell(caster, SPELL_REINDEER_100, true); //100% ground Reindeer else // Reindeer caster->CastSpell(caster, SPELL_REINDEER_60, true); //60% ground Reindeer } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_reindeer_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_reindeer_transformation_SpellScript(); } }; enum NighInvulnerability { SPELL_NIGH_INVULNERABILITY = 30456, SPELL_COMPLETE_VULNERABILITY = 30457, }; class spell_item_nigh_invulnerability : public SpellScriptLoader { public: spell_item_nigh_invulnerability() : SpellScriptLoader("spell_item_nigh_invulnerability") { } class spell_item_nigh_invulnerability_SpellScript : public SpellScript { PrepareSpellScript(spell_item_nigh_invulnerability_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NIGH_INVULNERABILITY) || !sSpellMgr->GetSpellInfo(SPELL_COMPLETE_VULNERABILITY)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (Item* castItem = GetCastItem()) { if (roll_chance_i(86)) // Nigh-Invulnerability - success caster->CastSpell(caster, SPELL_NIGH_INVULNERABILITY, true, castItem); else // Complete Vulnerability - backfire in 14% casts caster->CastSpell(caster, SPELL_COMPLETE_VULNERABILITY, true, castItem); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_nigh_invulnerability_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_nigh_invulnerability_SpellScript(); } }; enum Poultryzer { SPELL_POULTRYIZER_SUCCESS = 30501, SPELL_POULTRYIZER_BACKFIRE = 30504, }; class spell_item_poultryizer : public SpellScriptLoader { public: spell_item_poultryizer() : SpellScriptLoader("spell_item_poultryizer") { } class spell_item_poultryizer_SpellScript : public SpellScript { PrepareSpellScript(spell_item_poultryizer_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_BACKFIRE)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (GetCastItem() && GetHitUnit()) GetCaster()->CastSpell(GetHitUnit(), roll_chance_i(80) ? SPELL_POULTRYIZER_SUCCESS : SPELL_POULTRYIZER_BACKFIRE, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_poultryizer_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_poultryizer_SpellScript(); } }; enum SocretharsStone { SPELL_SOCRETHAR_TO_SEAT = 35743, SPELL_SOCRETHAR_FROM_SEAT = 35744, }; class spell_item_socrethars_stone : public SpellScriptLoader { public: spell_item_socrethars_stone() : SpellScriptLoader("spell_item_socrethars_stone") { } class spell_item_socrethars_stone_SpellScript : public SpellScript { PrepareSpellScript(spell_item_socrethars_stone_SpellScript); bool Load() { return (GetCaster()->GetAreaId() == 3900 || GetCaster()->GetAreaId() == 3742); } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_TO_SEAT) || !sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_FROM_SEAT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); switch (caster->GetAreaId()) { case 3900: caster->CastSpell(caster, SPELL_SOCRETHAR_TO_SEAT, true); break; case 3742: caster->CastSpell(caster, SPELL_SOCRETHAR_FROM_SEAT, true); break; default: return; } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_socrethars_stone_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_socrethars_stone_SpellScript(); } }; enum DemonBroiledSurprise { QUEST_SUPER_HOT_STEW = 11379, SPELL_CREATE_DEMON_BROILED_SURPRISE = 43753, NPC_ABYSSAL_FLAMEBRINGER = 19973, }; class spell_item_demon_broiled_surprise : public SpellScriptLoader { public: spell_item_demon_broiled_surprise() : SpellScriptLoader("spell_item_demon_broiled_surprise") { } class spell_item_demon_broiled_surprise_SpellScript : public SpellScript { PrepareSpellScript(spell_item_demon_broiled_surprise_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_DEMON_BROILED_SURPRISE) || !sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) || !sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW)) return false; return true; } bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* player = GetCaster(); player->CastSpell(player, SPELL_CREATE_DEMON_BROILED_SURPRISE, false); } SpellCastResult CheckRequirement() { Player* player = GetCaster()->ToPlayer(); if (player->GetQuestStatus(QUEST_SUPER_HOT_STEW) != QUEST_STATUS_INCOMPLETE) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; if (Creature* creature = player->FindNearestCreature(NPC_ABYSSAL_FLAMEBRINGER, 10, false)) if (creature->isDead()) return SPELL_CAST_OK; return SPELL_FAILED_NOT_HERE; } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_demon_broiled_surprise_SpellScript::HandleDummy, EFFECT_1, SPELL_EFFECT_DUMMY); OnCheckCast += SpellCheckCastFn(spell_item_demon_broiled_surprise_SpellScript::CheckRequirement); } }; SpellScript* GetSpellScript() const { return new spell_item_demon_broiled_surprise_SpellScript(); } }; enum CompleteRaptorCapture { SPELL_RAPTOR_CAPTURE_CREDIT = 42337, }; class spell_item_complete_raptor_capture : public SpellScriptLoader { public: spell_item_complete_raptor_capture() : SpellScriptLoader("spell_item_complete_raptor_capture") { } class spell_item_complete_raptor_capture_SpellScript : public SpellScript { PrepareSpellScript(spell_item_complete_raptor_capture_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_RAPTOR_CAPTURE_CREDIT)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (GetHitCreature()) { GetHitCreature()->DespawnOrUnsummon(); //cast spell Raptor Capture Credit caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, NULL); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_complete_raptor_capture_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_complete_raptor_capture_SpellScript(); } }; enum ImpaleLeviroth { NPC_LEVIROTH = 26452, SPELL_LEVIROTH_SELF_IMPALE = 49882, }; class spell_item_impale_leviroth : public SpellScriptLoader { public: spell_item_impale_leviroth() : SpellScriptLoader("spell_item_impale_leviroth") { } class spell_item_impale_leviroth_SpellScript : public SpellScript { PrepareSpellScript(spell_item_impale_leviroth_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sObjectMgr->GetCreatureTemplate(NPC_LEVIROTH)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { if (Unit* target = GetHitCreature()) if (target->GetEntry() == NPC_LEVIROTH && !target->HealthBelowPct(95)) target->CastSpell(target, SPELL_LEVIROTH_SELF_IMPALE, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_impale_leviroth_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_impale_leviroth_SpellScript(); } }; enum BrewfestMountTransformation { SPELL_MOUNT_RAM_100 = 43900, SPELL_MOUNT_RAM_60 = 43899, SPELL_MOUNT_KODO_100 = 49379, SPELL_MOUNT_KODO_60 = 49378, SPELL_BREWFEST_MOUNT_TRANSFORM = 49357, SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE = 52845, }; class spell_item_brewfest_mount_transformation : public SpellScriptLoader { public: spell_item_brewfest_mount_transformation() : SpellScriptLoader("spell_item_brewfest_mount_transformation") { } class spell_item_brewfest_mount_transformation_SpellScript : public SpellScript { PrepareSpellScript(spell_item_brewfest_mount_transformation_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_60) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_60)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (caster->HasAuraType(SPELL_AURA_MOUNTED)) { caster->RemoveAurasByType(SPELL_AURA_MOUNTED); uint32 spell_id; switch (GetSpellInfo()->Id) { case SPELL_BREWFEST_MOUNT_TRANSFORM: if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f) spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100; else spell_id = caster->GetTeam() == ALLIANCE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60; break; case SPELL_BREWFEST_MOUNT_TRANSFORM_REVERSE: if (caster->GetSpeedRate(MOVE_RUN) >= 2.0f) spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_100 : SPELL_MOUNT_KODO_100; else spell_id = caster->GetTeam() == HORDE ? SPELL_MOUNT_RAM_60 : SPELL_MOUNT_KODO_60; break; default: return; } caster->CastSpell(caster, spell_id, true); } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_brewfest_mount_transformation_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_brewfest_mount_transformation_SpellScript(); } }; enum NitroBoots { SPELL_NITRO_BOOTS_SUCCESS = 54861, SPELL_NITRO_BOOTS_BACKFIRE = 46014, }; class spell_item_nitro_boots : public SpellScriptLoader { public: spell_item_nitro_boots() : SpellScriptLoader("spell_item_nitro_boots") { } class spell_item_nitro_boots_SpellScript : public SpellScript { PrepareSpellScript(spell_item_nitro_boots_SpellScript); bool Load() { if (!GetCastItem()) return false; return true; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOTS_BACKFIRE)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); bool success = caster->GetMap()->IsDungeon() || roll_chance_i(95); caster->CastSpell(caster, success ? SPELL_NITRO_BOOTS_SUCCESS : SPELL_NITRO_BOOTS_BACKFIRE, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_nitro_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_nitro_boots_SpellScript(); } }; enum TeachLanguage { SPELL_LEARN_GNOMISH_BINARY = 50242, SPELL_LEARN_GOBLIN_BINARY = 50246, }; class spell_item_teach_language : public SpellScriptLoader { public: spell_item_teach_language() : SpellScriptLoader("spell_item_teach_language") { } class spell_item_teach_language_SpellScript : public SpellScript { PrepareSpellScript(spell_item_teach_language_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_LEARN_GNOMISH_BINARY) || !sSpellMgr->GetSpellInfo(SPELL_LEARN_GOBLIN_BINARY)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (roll_chance_i(34)) caster->CastSpell(caster, caster->GetTeam() == ALLIANCE ? SPELL_LEARN_GNOMISH_BINARY : SPELL_LEARN_GOBLIN_BINARY, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_teach_language_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_teach_language_SpellScript(); } }; enum RocketBoots { SPELL_ROCKET_BOOTS_PROC = 30452, }; class spell_item_rocket_boots : public SpellScriptLoader { public: spell_item_rocket_boots() : SpellScriptLoader("spell_item_rocket_boots") { } class spell_item_rocket_boots_SpellScript : public SpellScript { PrepareSpellScript(spell_item_rocket_boots_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_BOOTS_PROC)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (Battleground* bg = caster->GetBattleground()) bg->EventPlayerDroppedFlag(caster); caster->RemoveSpellCooldown(SPELL_ROCKET_BOOTS_PROC); caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, NULL); } SpellCastResult CheckCast() { if (GetCaster()->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; return SPELL_CAST_OK; } void Register() { OnCheckCast += SpellCheckCastFn(spell_item_rocket_boots_SpellScript::CheckCast); OnEffectHitTarget += SpellEffectFn(spell_item_rocket_boots_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_rocket_boots_SpellScript(); } }; enum PygmyOil { SPELL_PYGMY_OIL_PYGMY_AURA = 53806, SPELL_PYGMY_OIL_SMALLER_AURA = 53805, }; class spell_item_pygmy_oil : public SpellScriptLoader { public: spell_item_pygmy_oil() : SpellScriptLoader("spell_item_pygmy_oil") { } class spell_item_pygmy_oil_SpellScript : public SpellScript { PrepareSpellScript(spell_item_pygmy_oil_SpellScript); bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_PYGMY_AURA) || !sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_SMALLER_AURA)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); if (Aura* aura = caster->GetAura(SPELL_PYGMY_OIL_PYGMY_AURA)) aura->RefreshDuration(); else { aura = caster->GetAura(SPELL_PYGMY_OIL_SMALLER_AURA); if (!aura || aura->GetStackAmount() < 5 || !roll_chance_i(50)) caster->CastSpell(caster, SPELL_PYGMY_OIL_SMALLER_AURA, true); else { aura->Remove(); caster->CastSpell(caster, SPELL_PYGMY_OIL_PYGMY_AURA, true); } } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_pygmy_oil_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_pygmy_oil_SpellScript(); } }; class spell_item_unusual_compass : public SpellScriptLoader { public: spell_item_unusual_compass() : SpellScriptLoader("spell_item_unusual_compass") { } class spell_item_unusual_compass_SpellScript : public SpellScript { PrepareSpellScript(spell_item_unusual_compass_SpellScript); void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); caster->SetFacingTo(frand(0.0f, 62832.0f) / 10000.0f); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_unusual_compass_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_unusual_compass_SpellScript(); } }; enum ChickenCover { SPELL_CHICKEN_NET = 51959, SPELL_CAPTURE_CHICKEN_ESCAPE = 51037, QUEST_CHICKEN_PARTY = 12702, QUEST_FLOWN_THE_COOP = 12532, }; class spell_item_chicken_cover : public SpellScriptLoader { public: spell_item_chicken_cover() : SpellScriptLoader("spell_item_chicken_cover") { } class spell_item_chicken_cover_SpellScript : public SpellScript { PrepareSpellScript(spell_item_chicken_cover_SpellScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_PLAYER; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_CHICKEN_NET) || !sSpellMgr->GetSpellInfo(SPELL_CAPTURE_CHICKEN_ESCAPE) || !sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) || !sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Player* caster = GetCaster()->ToPlayer(); if (Unit* target = GetHitUnit()) { if (!target->HasAura(SPELL_CHICKEN_NET) && (caster->GetQuestStatus(QUEST_CHICKEN_PARTY) == QUEST_STATUS_INCOMPLETE || caster->GetQuestStatus(QUEST_FLOWN_THE_COOP) == QUEST_STATUS_INCOMPLETE)) { caster->CastSpell(caster, SPELL_CAPTURE_CHICKEN_ESCAPE, true); target->Kill(target); } } } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_chicken_cover_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_chicken_cover_SpellScript(); } }; enum Refocus { SPELL_AIMED_SHOT = 19434, SPELL_MULTISHOT = 2643, SPELL_VOLLEY = 42243, }; class spell_item_refocus : public SpellScriptLoader { public: spell_item_refocus() : SpellScriptLoader("spell_item_refocus") { } class spell_item_refocus_SpellScript : public SpellScript { PrepareSpellScript(spell_item_refocus_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { Player* caster = GetCaster()->ToPlayer(); if (!caster || caster->getClass() != CLASS_HUNTER) return; if (caster->HasSpellCooldown(SPELL_AIMED_SHOT)) caster->RemoveSpellCooldown(SPELL_AIMED_SHOT, true); if (caster->HasSpellCooldown(SPELL_MULTISHOT)) caster->RemoveSpellCooldown(SPELL_MULTISHOT, true); if (caster->HasSpellCooldown(SPELL_VOLLEY)) caster->RemoveSpellCooldown(SPELL_VOLLEY, true); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_refocus_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_refocus_SpellScript(); } }; class spell_item_muisek_vessel : public SpellScriptLoader { public: spell_item_muisek_vessel() : SpellScriptLoader("spell_item_muisek_vessel") { } class spell_item_muisek_vessel_SpellScript : public SpellScript { PrepareSpellScript(spell_item_muisek_vessel_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (Creature* target = GetHitCreature()) if (target->isDead()) target->DespawnOrUnsummon(); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_muisek_vessel_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_muisek_vessel_SpellScript(); } }; enum GreatmothersSoulcather { SPELL_FORCE_CAST_SUMMON_GNOME_SOUL = 46486, }; class spell_item_greatmothers_soulcatcher : public SpellScriptLoader { public: spell_item_greatmothers_soulcatcher() : SpellScriptLoader("spell_item_greatmothers_soulcatcher") { } class spell_item_greatmothers_soulcatcher_SpellScript : public SpellScript { PrepareSpellScript(spell_item_greatmothers_soulcatcher_SpellScript); void HandleDummy(SpellEffIndex /*effIndex*/) { if (GetHitUnit()) GetCaster()->CastSpell(GetCaster(), SPELL_FORCE_CAST_SUMMON_GNOME_SOUL); } void Register() { OnEffectHitTarget += SpellEffectFn(spell_item_greatmothers_soulcatcher_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_greatmothers_soulcatcher_SpellScript(); } }; class spell_item_healthstone : public SpellScriptLoader { public: spell_item_healthstone() : SpellScriptLoader("spell_item_healthstone") { } class spell_item_healthstone_SpellScript : public SpellScript { PrepareSpellScript(spell_item_healthstone_SpellScript); bool inSoulburn; bool Load() { inSoulburn = false; return true; } void HandleOnHit(SpellEffIndex effIndex) { Unit* caster = GetCaster(); if (!caster) return; uint32 amount = CalculatePct(caster->GetCreateHealth(), GetSpellInfo()->Effects[effIndex].BasePoints); SetEffectDamage(amount); if (inSoulburn) caster->CastSpell(caster, 79437, true); } void HandleOnCast() { if (Unit* caster = GetCaster()) if (caster->HasAura(74434)) { inSoulburn = true; caster->RemoveAurasDueToSpell(74434); } } void Register() { OnEffectLaunchTarget += SpellEffectFn(spell_item_healthstone_SpellScript::HandleOnHit, EFFECT_0, SPELL_EFFECT_HEAL); OnCast += SpellCastFn(spell_item_healthstone_SpellScript::HandleOnCast); } }; SpellScript* GetSpellScript() const { return new spell_item_healthstone_SpellScript(); } }; enum FlaskOfTheEnchancementSpells { SPELL_FLASK_OF_ENHANCEMENT_STR = 79638, SPELL_FLASK_OF_ENHANCEMENT_AP = 79639, SPELL_FLASK_OF_ENHANCEMENT_SP = 79640, }; class spell_item_flask_of_enhancement : public SpellScriptLoader { public: spell_item_flask_of_enhancement() : SpellScriptLoader("spell_item_flask_of_enhancement") { } class spell_item_flask_of_enhancement_SpellScript : public SpellScript { PrepareSpellScript(spell_item_flask_of_enhancement_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_STR) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_ENHANCEMENT_SP)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if(caster->GetStat(STAT_AGILITY) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_STRENGTH))) // Druid CAC { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_AP, true, NULL); } else if(caster->GetStat(STAT_STRENGTH) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_AGILITY))) // PALA CAC { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_STR, true, NULL); } else if(caster->GetStat(STAT_INTELLECT) > std::max(caster->GetStat(STAT_AGILITY),caster->GetStat(STAT_STRENGTH))) // PALA Heal { caster->CastSpell(caster, SPELL_FLASK_OF_ENHANCEMENT_SP, true, NULL); } } void Register() { OnEffectHit += SpellEffectFn(spell_item_flask_of_enhancement_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_flask_of_enhancement_SpellScript(); } }; // http://cata.openwow.com/spell=82175 enum synapse_springs_spells { SYNAPSE_SPRINGS_SPELLS_AGI = 96228, SYNAPSE_SPRINGS_SPELLS_STR = 96229, SYNAPSE_SPRINGS_SPELLS_SP = 96230, }; class spell_item_synapse_springs : public SpellScriptLoader { public: spell_item_synapse_springs() : SpellScriptLoader("spell_item_synapse_springs") { } class spell_item_synapse_springs_SpellScript : public SpellScript { PrepareSpellScript(spell_item_synapse_springs_SpellScript); bool Validate(SpellInfo const* /*spellEntry*/) { if (!sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_STR) || !sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_AGI) || !sSpellMgr->GetSpellInfo(SYNAPSE_SPRINGS_SPELLS_SP)) return false; return true; } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); if(caster->GetStat(STAT_INTELLECT) > std::max(caster->GetStat(STAT_AGILITY),caster->GetStat(STAT_STRENGTH))) // Intel Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_SP, true, NULL); } else if(caster->GetStat(STAT_AGILITY) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_STRENGTH))) // Agi Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_AGI, true, NULL); } else if(caster->GetStat(STAT_STRENGTH) > std::max(caster->GetStat(STAT_INTELLECT),caster->GetStat(STAT_AGILITY))) // Strengh Stats { caster->CastSpell(caster, SYNAPSE_SPRINGS_SPELLS_STR, true, NULL); } } void Register() { OnEffectHit += SpellEffectFn(spell_item_synapse_springs_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new spell_item_synapse_springs_SpellScript(); } }; // http://cata.openwow.com/spell=82627 // http://www.wowhead.com/spell=84427#comments Bad side Effect enum grounded_plasma_shield_spells { SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS = 82627, // Proc 18k absorb SPELL_REVERSED_SHIELD = 82406, // Debuff Side Effect 1 //TODO SPELL_MAGNETIZED = 82403, // Debuff Side Effect 2 SPELL_PAINFUL_SHOCK = 82407, // Debuff Side Effect 3 Active le buff 4 SPELL_PLASMA_MISFIRE = 94549, // Debuff Side Effect 4 }; class grounded_plasma_shield : public SpellScriptLoader { public: grounded_plasma_shield() : SpellScriptLoader("grounded_plasma_shield") { } class grounded_plasma_shield_SpellScript : public SpellScript { PrepareSpellScript(grounded_plasma_shield_SpellScript); bool Load() { if (GetCastItem()) return false; return true; } bool Validate(SpellInfo const* /*spell*/) { if (!sSpellMgr->GetSpellInfo(SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_REVERSED_SHIELD) || !sSpellMgr->GetSpellInfo(SPELL_MAGNETIZED) || !sSpellMgr->GetSpellInfo(SPELL_PAINFUL_SHOCK)) return false; return true; } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); // Need more random 1/4 bad sideeffect spells caster->CastSpell(caster, roll_chance_i(95) ? SPELL_GROUNDED_PLASMA_SHIELD_SUCCESS : SPELL_REVERSED_SHIELD, true, GetCastItem()); } void Register() { OnEffectHitTarget += SpellEffectFn(grounded_plasma_shield_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } }; SpellScript* GetSpellScript() const { return new grounded_plasma_shield_SpellScript(); } }; // 71610, 71641 - Echoes of Light (Althor's Abacus) class spell_item_echoes_of_light : public SpellScriptLoader { public: spell_item_echoes_of_light() : SpellScriptLoader("spell_item_echoes_of_light") { } class spell_item_echoes_of_light_SpellScript : public SpellScript { PrepareSpellScript(spell_item_echoes_of_light_SpellScript); void FilterTargets(std::list<WorldObject*>& targets) { if (targets.size() < 2) return; targets.sort(Trinity::HealthPctOrderPred()); WorldObject* target = targets.front(); targets.clear(); targets.push_back(target); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_item_echoes_of_light_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_DEST_AREA_ALLY); } }; SpellScript* GetSpellScript() const { return new spell_item_echoes_of_light_SpellScript(); } }; void AddSC_item_spell_scripts() { // 23074 Arcanite Dragonling new spell_item_trigger_spell("spell_item_arcanite_dragonling", SPELL_ARCANITE_DRAGONLING); // 23133 Gnomish Battle Chicken new spell_item_trigger_spell("spell_item_gnomish_battle_chicken", SPELL_BATTLE_CHICKEN); // 23076 Mechanical Dragonling new spell_item_trigger_spell("spell_item_mechanical_dragonling", SPELL_MECHANICAL_DRAGONLING); // 23075 Mithril Mechanical Dragonling new spell_item_trigger_spell("spell_item_mithril_mechanical_dragonling", SPELL_MITHRIL_MECHANICAL_DRAGONLING); new spell_item_aegis_of_preservation(); new spell_item_arcane_shroud(); new spell_item_blessing_of_ancient_kings(); new spell_item_defibrillate("spell_item_goblin_jumper_cables", 67, SPELL_GOBLIN_JUMPER_CABLES_FAIL); new spell_item_defibrillate("spell_item_goblin_jumper_cables_xl", 50, SPELL_GOBLIN_JUMPER_CABLES_XL_FAIL); new spell_item_defibrillate("spell_item_gnomish_army_knife", 33); new spell_item_deviate_fish(); new spell_item_desperate_defense(); new spell_item_flask_of_the_north(); new spell_item_gnomish_death_ray(); new spell_item_make_a_wish(); new spell_item_mingos_fortune_generator(); new spell_item_necrotic_touch(); new spell_item_net_o_matic(); new spell_item_noggenfogger_elixir(); new spell_item_piccolo_of_the_flaming_fire(); new spell_item_savory_deviate_delight(); new spell_item_scroll_of_recall(); new spell_item_shadows_fate(); new spell_item_shadowmourne(); new spell_item_shadowmourne_soul_fragment(); new spell_item_six_demon_bag(); new spell_item_the_eye_of_diminution(); new spell_item_underbelly_elixir(); new spell_item_red_rider_air_rifle(); new spell_item_create_heart_candy(); new spell_item_book_of_glyph_mastery(); new spell_item_gift_of_the_harvester(); new spell_item_map_of_the_geyser_fields(); new spell_item_vanquished_clutches(); new spell_item_ashbringer(); new spell_magic_eater_food(); new spell_item_refocus(); new spell_item_shimmering_vessel(); new spell_item_purify_helboar_meat(); new spell_item_crystal_prison_dummy_dnd(); new spell_item_reindeer_transformation(); new spell_item_nigh_invulnerability(); new spell_item_poultryizer(); new spell_item_socrethars_stone(); new spell_item_demon_broiled_surprise(); new spell_item_complete_raptor_capture(); new spell_item_impale_leviroth(); new spell_item_brewfest_mount_transformation(); new spell_item_nitro_boots(); new spell_item_teach_language(); new spell_item_rocket_boots(); new spell_item_pygmy_oil(); new spell_item_unusual_compass(); new spell_item_chicken_cover(); new spell_item_muisek_vessel(); new spell_item_greatmothers_soulcatcher(); new spell_item_healthstone(); new spell_item_flask_of_enhancement(); // Spell - 79637 new spell_item_synapse_springs(); // Spell - 82174 new grounded_plasma_shield(); // Spell - 82626 new spell_item_echoes_of_light(); }
LordPsyan/WoWSource434_V10
src/server/scripts/Spells/spell_item.cpp
C++
gpl-2.0
102,670
( function( $ ) { $( 'time.entry-published' ).on( "click", function() { var old_date = $(this).html().trim(); $(this).html( $(this).attr( 'data-display-toggle' ) ); $(this).attr( 'data-display-toggle', old_date ); } ); } )( jQuery );
aprea/adoration
js/adoration.js
JavaScript
gpl-2.0
244
<?php /* * gwolle_gb_get_entry_count * Get the number of entries. * * Parameter $args is an Array: * - checked string: 'checked' or 'unchecked', List the entries that are checked or not checked * - trash string: 'trash' or 'notrash', List the entries that are deleted or not deleted * - spam string: 'spam' or 'nospam', List the entries marked as spam or as no spam * - all string: 'all', List all entries * * Return: * - int with the count of the entries * - false if there's an error. */ function gwolle_gb_get_entry_count($args) { global $wpdb; $where = " 1 = %d"; $values = Array(1); if ( !is_array($args) ) { return false; } if ( isset($args['checked']) ) { if ( $args['checked'] == 'checked' || $args['checked'] == 'unchecked' ) { $where .= " AND ischecked = %d"; if ( $args['checked'] == 'checked' ) { $values[] = 1; } else if ( $args['checked'] == 'unchecked' ) { $values[] = 0; } } } if ( isset($args['spam']) ) { if ( $args['spam'] == 'spam' || $args['spam'] == 'nospam' ) { $where .= " AND isspam = %d"; if ( $args['spam'] == 'spam' ) { $values[] = 1; } else if ( $args['spam'] == 'nospam' ) { $values[] = 0; } } } if ( isset($args['trash']) ) { if ( $args['trash'] == 'trash' || $args['trash'] == 'notrash' ) { $where .= " AND istrash = %d"; if ( $args['trash'] == 'trash' ) { $values[] = 1; } else if ( $args['trash'] == 'notrash' ) { $values[] = 0; } } } $tablename = $wpdb->prefix . "gwolle_gb_entries"; $sql = " SELECT COUNT(id) AS count FROM " . $tablename . " WHERE " . $where . " ;"; // If All is set, do not use $wpdb->prepare() if ( isset($args['all']) ) { if ( $args['all'] == 'all' ) { $sql = " SELECT COUNT(id) AS count FROM " . $tablename . ";"; } } else { $sql = $wpdb->prepare( $sql, $values ); } $data = $wpdb->get_results( $sql, ARRAY_A ); return (int) $data[0]['count']; }
TheNexusMan/Rest-a-Dom
wp-content/plugins/gwolle-gb/functions/function.get_entry_count.php
PHP
gpl-2.0
2,010
/** * @file * @brief Miscellaneous debugging functions. **/ #include "AppHdr.h" #include "dbg-util.h" #include "artefact.h" #include "cio.h" #include "coord.h" #include "dungeon.h" #include "env.h" #include "libutil.h" #include "message.h" #include "mon-stuff.h" #include "mon-util.h" #include "religion.h" #include "shopping.h" #include "skills2.h" #include "spl-util.h" monster_type debug_prompt_for_monster(void) { char specs[80]; mpr("Which monster by name? ", MSGCH_PROMPT); if (!cancelable_get_line_autohist(specs, sizeof specs)) { if (specs[0] == '\0') return (MONS_NO_MONSTER); return (get_monster_by_name(specs)); } return (MONS_NO_MONSTER); } static void _dump_vault_table(const CrawlHashTable &table) { if (!table.empty()) { CrawlHashTable::const_iterator i = table.begin(); for (; i != table.end(); ++i) mprf(" %s: %s", i->first.c_str(), i->second.get_string().c_str()); } } void debug_dump_levgen() { if (crawl_state.game_is_arena()) return; CrawlHashTable &props = env.properties; std::string method; std::string type; if (Generating_Level) { mpr("Currently generating level."); method = env.level_build_method; type = comma_separated_line(env.level_layout_types.begin(), env.level_layout_types.end(), ", "); } else { if (!props.exists(BUILD_METHOD_KEY)) method = "ABSENT"; else method = props[BUILD_METHOD_KEY].get_string(); if (!props.exists(LAYOUT_TYPE_KEY)) type = "ABSENT"; else type = props[LAYOUT_TYPE_KEY].get_string(); } mprf("level build method = %s", method.c_str()); mprf("level layout type = %s", type.c_str()); if (props.exists(LEVEL_EXTRAS_KEY)) { mpr("Level extras:"); const CrawlHashTable &extras = props[LEVEL_EXTRAS_KEY].get_table(); _dump_vault_table(extras); } if (props.exists(LEVEL_VAULTS_KEY)) { mpr("Level vaults:"); const CrawlHashTable &vaults = props[LEVEL_VAULTS_KEY].get_table(); _dump_vault_table(vaults); } mpr(""); } void error_message_to_player(void) { mpr("Oh dear. There appears to be a bug in the program."); mpr("I suggest you leave this level then save as soon as possible."); } std::string debug_coord_str(const coord_def &pos) { return make_stringf("(%d, %d)%s", pos.x, pos.y, !in_bounds(pos) ? " <OoB>" : ""); } std::string debug_mon_str(const monster* mon) { const int midx = mon->mindex(); if (invalid_monster_index(midx)) return make_stringf("Invalid monster index %d", midx); std::string out = "Monster '" + mon->full_name(DESC_PLAIN, true) + "' "; out += make_stringf("%s [midx = %d]", debug_coord_str(mon->pos()).c_str(), midx); return (out); } void debug_dump_mon(const monster* mon, bool recurse) { const int midx = mon->mindex(); if (invalid_monster_index(midx) || invalid_monster_type(mon->type)) return; fprintf(stderr, "<<<<<<<<<\n"); fprintf(stderr, "Name: %s\n", mon->name(DESC_PLAIN, true).c_str()); fprintf(stderr, "Base name: %s\n", mon->base_name(DESC_PLAIN, true).c_str()); fprintf(stderr, "Full name: %s\n\n", mon->full_name(DESC_PLAIN, true).c_str()); if (in_bounds(mon->pos())) { std::string feat = raw_feature_description(grd(mon->pos()), NUM_TRAPS, true); fprintf(stderr, "On/in/over feature: %s\n\n", feat.c_str()); } fprintf(stderr, "Foe: "); if (mon->foe == MHITNOT) fprintf(stderr, "none"); else if (mon->foe == MHITYOU) fprintf(stderr, "player"); else if (invalid_monster_index(mon->foe)) fprintf(stderr, "invalid monster index %d", mon->foe); else if (mon->foe == midx) fprintf(stderr, "self"); else fprintf(stderr, "%s", debug_mon_str(&menv[mon->foe]).c_str()); fprintf(stderr, "\n"); fprintf(stderr, "Target: "); if (mon->target.origin()) fprintf(stderr, "none\n"); else fprintf(stderr, "%s\n", debug_coord_str(mon->target).c_str()); int target = MHITNOT; fprintf(stderr, "At target: "); if (mon->target.origin()) fprintf(stderr, "N/A"); else if (mon->target == you.pos()) { fprintf(stderr, "player"); target = MHITYOU; } else if (mon->target == mon->pos()) { fprintf(stderr, "self"); target = midx; } else if (in_bounds(mon->target)) { target = mgrd(mon->target); if (target == NON_MONSTER) fprintf(stderr, "nothing"); else if (target == midx) fprintf(stderr, "improperly linked self"); else if (target == mon->foe) fprintf(stderr, "same as foe"); else if (invalid_monster_index(target)) fprintf(stderr, "invalid monster index %d", target); else fprintf(stderr, "%s", debug_mon_str(&menv[target]).c_str()); } else fprintf(stderr, "<OoB>"); fprintf(stderr, "\n"); if (mon->is_patrolling()) { fprintf(stderr, "Patrolling: %s\n\n", debug_coord_str(mon->patrol_point).c_str()); } if (mon->travel_target != MTRAV_NONE) { fprintf(stderr, "\nTravelling:\n"); fprintf(stderr, " travel_target = %d\n", mon->travel_target); fprintf(stderr, " travel_path.size() = %u\n", (unsigned int)mon->travel_path.size()); if (mon->travel_path.size() > 0) { fprintf(stderr, " next travel step: %s\n", debug_coord_str(mon->travel_path.back()).c_str()); fprintf(stderr, " last travel step: %s\n", debug_coord_str(mon->travel_path.front()).c_str()); } } fprintf(stderr, "\n"); fprintf(stderr, "Inventory:\n"); for (int i = 0; i < NUM_MONSTER_SLOTS; ++i) { const int idx = mon->inv[i]; if (idx == NON_ITEM) continue; fprintf(stderr, " slot #%d: ", i); if (idx < 0 || idx > MAX_ITEMS) { fprintf(stderr, "invalid item index %d\n", idx); continue; } const item_def &item(mitm[idx]); if (!item.defined()) { fprintf(stderr, "invalid item\n"); continue; } fprintf(stderr, "%s", item.name(DESC_PLAIN, false, true).c_str()); if (!item.held_by_monster()) { fprintf(stderr, " [not held by monster, pos = %s]", debug_coord_str(item.pos).c_str()); } else if (item.holding_monster() != mon) { fprintf(stderr, " [held by other monster: %s]", debug_mon_str(item.holding_monster()).c_str()); } fprintf(stderr, "\n"); } fprintf(stderr, "\n"); if (mon->can_use_spells()) { fprintf(stderr, "Spells:\n"); for (int i = 0; i < NUM_MONSTER_SPELL_SLOTS; ++i) { spell_type spell = mon->spells[i]; if (spell == SPELL_NO_SPELL) continue; fprintf(stderr, " slot #%d: ", i); if (!is_valid_spell(spell)) fprintf(stderr, "Invalid spell #%d\n", (int) spell); else fprintf(stderr, "%s\n", spell_title(spell)); } fprintf(stderr, "\n"); } fprintf(stderr, "attitude: %d, behaviour: %d, number: %d, flags: 0x%"PRIx64"\n", mon->attitude, mon->behaviour, mon->number, mon->flags); fprintf(stderr, "colour: %d, foe_memory: %d, shield_blocks:%d, " "experience: %u\n", mon->colour, mon->foe_memory, mon->shield_blocks, mon->experience); fprintf(stderr, "god: %s, seen_context: %s\n", god_name(mon->god).c_str(), mon->seen_context.c_str()); fprintf(stderr, ">>>>>>>>>\n\n"); if (!recurse) return; if (!invalid_monster_index(mon->foe) && mon->foe != midx && !invalid_monster_type(menv[mon->foe].type)) { fprintf(stderr, "Foe:\n"); debug_dump_mon(&menv[mon->foe], false); } if (!invalid_monster_index(target) && target != midx && target != mon->foe && !invalid_monster_type(menv[target].type)) { fprintf(stderr, "Target:\n"); debug_dump_mon(&menv[target], false); } } //--------------------------------------------------------------- // // debug_prompt_for_skill // //--------------------------------------------------------------- skill_type debug_prompt_for_skill(const char *prompt) { char specs[80]; msgwin_get_line_autohist(prompt, specs, sizeof(specs)); if (specs[0] == '\0') return (SK_NONE); skill_type skill = SK_NONE; for (int i = SK_FIRST_SKILL; i < NUM_SKILLS; ++i) { skill_type sk = static_cast<skill_type>(i); // Avoid the bad values. if (is_invalid_skill(sk)) continue; char sk_name[80]; strncpy(sk_name, skill_name(sk), sizeof(sk_name)); char *ptr = strstr(strlwr(sk_name), strlwr(specs)); if (ptr != NULL) { if (ptr == sk_name && strlen(specs) > 0) { // We prefer prefixes over partial matches. skill = sk; break; } else skill = sk; } } return (skill); } std::string debug_art_val_str(const item_def& item) { ASSERT(is_artefact(item)); return make_stringf("art val: %d, item val: %d", artefact_value(item), item_value(item, true)); } int debug_cap_stat(int stat) { return (stat < 1 ? 1 : stat > 127 ? 127 : stat); } #ifdef DEBUG static FILE *debugf = 0; void debuglog(const char *format, ...) { va_list args; if (!debugf) { debugf = fopen("debuglog.txt", "w"); ASSERT(debugf); } va_start(args, format); vfprintf(debugf, format, args); va_end(args); fflush(debugf); } #endif
dtsund/dtsund-crawl-mod
source/dbg-util.cc
C++
gpl-2.0
10,334
"use strict"; function Bola(context) { this.context = context; this.x = 0; this.y = 0; this.velocidadeX = 0; this.velocidadeY = 0; this.cor = 'black'; this.raio = 10; } Bola.prototype = { // - Interface utilizada em animacao.js atualizar : function() { var ctx = this.context; if (this.x < this.raio || this.x > ctx.canvas.width - this.raio) this.velocidadeX *= -1; if (this.y < this.raio || this.y > ctx.canvas.height - this.raio) this.velocidadeY *= -1; this.x += this.velocidadeX; this.y += this.velocidadeY; }, desenhar: function() { var ctx = this.context; ctx.save(); ctx.fillStyle = this.cor; ctx.beginPath(); ctx.arc(this.x, this.y, this.raio, 0, 2 * Math.PI, false); ctx.fill(); ctx.restore(); }, // - Interface utilizada em colisor.js retangulosColisao: function() { return [{ x: this.x - this.raio, y: this.y - this.raio, largura: this.raio * 2, altura: this.raio * 2 }]; }, colidiuCom: function(sprite) { if (this.x < sprite.x) this.velocidadeX = -Math.abs(this.velocidadeX); else this.velocidadeX = Math.abs(this.velocidadeX); if (this.y < sprite.y) this.velocidadeY = -Math.abs(this.velocidadeY); else this.velocidadeY = Math.abs(this.velocidadeY); } }
edgarberlinck/edgarberlinck.github.io
canvas/10-colisoes/bola.js
JavaScript
gpl-2.0
1,324
<?php /* Remove Unwanted Header Links */ remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'start_post_rel_link', 10, 0); remove_action('wp_head', 'parent_post_rel_link', 10, 0); remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); /* remove WP default inline CSS for ".recentcomments a" from header */ add_action('widgets_init', 'my_remove_recent_comments_style'); function my_remove_recent_comments_style() { global $wp_widget_factory; remove_action('wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style')); } /* remove unwanted Tags */ function remove_invalid_tags($str, $tags) { foreach($tags as $tag) { $str = preg_replace('#^<\/'.$tag.'>|<'.$tag.'>$#', '', $str); } return $str; } ?>
matt-tyas/matthewtyas.com
lab/gmfootballcentre/wp-content/themes/tisa-wp/inc/remove.php
PHP
gpl-2.0
1,004
#include "Input.hpp" Input::Input(){ _keybinds.insert({ { "up", SDL_SCANCODE_UP }, { "down", SDL_SCANCODE_DOWN }, { "left", SDL_SCANCODE_LEFT }, { "right", SDL_SCANCODE_RIGHT }, { "w", SDL_SCANCODE_W }, { "s", SDL_SCANCODE_S }, { "a", SDL_SCANCODE_A }, { "d", SDL_SCANCODE_D }, { "z", SDL_SCANCODE_Z }, { "x", SDL_SCANCODE_X }, { "q", SDL_SCANCODE_Q }, { "e", SDL_SCANCODE_E }, { "ctrl", SDL_SCANCODE_LCTRL }, { "space", SDL_SCANCODE_SPACE }, { "shift", SDL_SCANCODE_LSHIFT } }); } void Input::update(double dt){ const Uint8* keysDown = SDL_GetKeyboardState(0); for (KeyMap::iterator i = _keybinds.begin(); i != _keybinds.end(); i++){ StringSet::iterator keyString = _down.find(i->first); if (keysDown[i->second]){ if (keyString == _down.end()) _down.insert(i->first); } else{ if (keyString != _down.end()) _down.erase(i->first); } } } bool Input::isDown(const std::string& key){ StringSet::iterator keyString = _down.find(key); if (keyString == _down.end()) return false; return true; }
Stormatree/Component-Engine
engine/Component/Input.cpp
C++
gpl-2.0
1,058
<?php /** * Template Name: Posty uลผytkownika * */ get_header(); ?> <div class="row"> <div class="col-md-9 col-sm-6 col-xs-12"> <?php $query = new WP_Query(array( 'author' => $_GET['id'] )); ?> <?php if ($query->have_posts()): ?> <div class="container-fluid"> <?php while ($query->have_posts()) : $query->the_post(); ?> <div class="post"> <div class="row header "> <div class="title col-md-6"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </div> <div class="col-md-6 text-right small"> Ocena: <?php $data = get_post_meta(get_the_ID(), 'rating'); echo $data[0]; ?> | <?php the_modified_date(); ?> <?php the_modified_time(); ?> </div> </div> </div> <?php endwhile; ?> </div> <?php endif; ?> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <?php get_sidebar(); ?> </div> </div> <!--div.row--> <?php get_footer(); ?>
damian-kociuba/wordpressSimplePage
wp-content/themes/testtheme/page_posts.php
PHP
gpl-2.0
1,535
package net.demilich.metastone.game.spells.custom; import java.util.Map; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.entities.Actor; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.spells.Spell; import net.demilich.metastone.game.spells.desc.SpellArg; import net.demilich.metastone.game.spells.desc.SpellDesc; public class BetrayalSpell extends Spell { public static SpellDesc create() { Map<SpellArg, Object> arguments = SpellDesc.build(BetrayalSpell.class); return new SpellDesc(arguments); } @Override protected void onCast(GameContext context, Player player, SpellDesc desc, Entity source, Entity target) { Actor attacker = (Actor) target; for (Actor adjacentMinion : context.getAdjacentMinions(player, target.getReference())) { context.getLogic().damage(player, adjacentMinion, attacker.getAttack(), attacker); } } }
rafaelkalan/metastone
src/main/java/net/demilich/metastone/game/spells/custom/BetrayalSpell.java
Java
gpl-2.0
967
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package storefront */ ?> </div><!-- .col-full --> </div><!-- #content --> <?php do_action( 'storefront_before_footer' ); ?> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="col-full"> <?php /** * @hooked storefront_footer_widgets - 10 * @hooked storefront_credit - 20 */ do_action( 'storefront_footer' ); ?> </div><!-- .col-full --> </footer><!-- #colophon --> <?php do_action( 'storefront_after_footer' ); ?> </div><!-- #page --> <?php wp_footer(); ?> <script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/themes/groworganiclocal/js/bootstrap.min.js"></script> </body> </html>
DogburnDesign/groworganiclocal
wp-content/themes/groworganiclocal/footer.php
PHP
gpl-2.0
793
#!/usr/bin/env php <?php /** * File containing the ezexec.php script. * * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2011.12 * @package kernel */ require 'autoload.php'; $cli = eZCLI::instance(); $script = eZScript::instance( array( 'description' => ( "eZ Publish Script Executor\n\n" . "Allows execution of simple PHP scripts which uses eZ Publish functionality,\n" . "when the script is called all necessary initialization is done\n" . "\n" . "ezexec.php myscript.php" ), 'use-session' => false, 'use-modules' => true, 'use-extensions' => true ) ); $script->startup(); $options = $script->getOptions( "", "[scriptfile]", array() ); $script->initialize(); if ( count( $options['arguments'] ) < 1 ) { $script->shutdown( 1, "Missing script file" ); } $scriptFile = $options['arguments'][0]; if ( !file_exists( $scriptFile ) ) $script->shutdown( 1, "Could execute the script '$scriptFile', file was not found" ); $retCode = include( $scriptFile ); if ( $retCode != 1 ) $script->setExitCode( 1 ); $script->shutdown(); ?>
ETSGlobal/ezpublish_built
bin/php/ezexec.php
PHP
gpl-2.0
1,568
/** * Title: StanfordMaxEnt<p> * Description: A Maximum Entropy Toolkit<p> * Copyright: Copyright (c) Kristina Toutanova<p> * Company: Stanford University<p> * @author Kristina Toutanova * @version 1.0 */ package com.infoecos.util.io; import java.io.*; //: com:bruceeckel:tools:OutFile.java // Shorthand class for opening an output file // for data storage. public class OutDataStreamFile extends DataOutputStream { public OutDataStreamFile(String filename) throws IOException { this(new File(filename)); } public OutDataStreamFile(File file) throws IOException { super(new BufferedOutputStream(new FileOutputStream(file))); } } ///:~
javajoker/infoecos
src/com/infoecos/util/io/OutDataStreamFile.java
Java
gpl-2.0
680
#!/usr/bin/env python3 """ # TOP2049 Open Source programming suite # # Commandline utility # # Copyright (c) 2014 Pavel Stemberk <stemberk@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ import re import sys import os def substitute(input, oldSocket, newSocket): input = re.sub('(^\s*packages).*', lambda m:'{} = (("DIP10", ""), ),'.format(m.group(1)), input) input = re.sub('(^\s*chipPackage).*', lambda m:'{} = "DIP10",'.format(m.group(1)), input) input = re.sub('(^\s*chipPinVCC).*', lambda m:'{} = 9,'.format(m.group(1)), input) input = re.sub('(^\s*chipPinsVPP).*', lambda m:'{} = 10,'.format(m.group(1)), input) input = re.sub('(^\s*chipPinGND).*', lambda m:'{} = 8,'.format(m.group(1)), input) input = re.sub('(^\s*runtimeID).*', lambda m:'{} = (0xDF05, 0x01),'.format(m.group(1)), input) input = re.sub('(^\s*description).+"(.*)".*', lambda m:'{} = "{} - ICD",'.format(m.group(1), m.group(2)), input) input = re.sub('(^\s*bitfile).*', lambda m:'{} = "microchip16sip6",'.format(m.group(1)), input) input = re.sub("{}".format(oldSocket), "{}".format(newSocket), input) input = re.sub("{}".format(oldSocket.upper()), "{}".format(newSocket.upper()), input) return input def makeSip(): inputFileName = '__init__.py' fin = open(inputFileName) dMCU = {} for line in fin: matchObj = re.match('.*(pic[0-9]+l?f\w+)(sip[0-9a]+).*', line) if matchObj: continue matchObj = re.match('.*(pic[0-9]+l?f\w+)(dip[0-9a]+).*', line) if not matchObj: print("{} did not match".format(line)) continue # print('matched {} - {}'.format(matchObj.group(1), matchObj.group(2))) dMCU.setdefault(matchObj.group(1), matchObj.group(2)) fin.close() for item in dMCU.items(): fin = open("{}{}.py".format(item[0], item[1])) fout = open("{}sip6.py".format(item[0]), 'w') fout.write("#\n") fout.write("# THIS FILE WAS AUTOGENERATED BY makeSip6.py\n") fout.write("# Do not edit this file manually. All changes will be lost.\n") fout.write("#\n\n") for line in fin: fout.write(substitute(line, "{}".format(item[1]), "sip6")) fout.close() fin.close() def main(argv): makeSip() if __name__ == "__main__": exit(main(sys.argv))
mbuesch/toprammer
libtoprammer/chips/microchip16/makeSip6.py
Python
gpl-2.0
2,873
#include "Transform2D.h" Transform2D::Transform2D(glm::vec2 p_pos, float p_rot, glm::vec2 p_scale) { m_pos = p_pos; m_rot = p_rot; m_scale = p_scale; m_z = 0; } Transform2D::~Transform2D() { } glm::mat4 const & Transform2D::getModel() { glm::mat4 posMatrix = glm::translate(glm::vec3(m_pos, m_z)); glm::mat4 rotZMatrix = glm::rotate(m_rot, glm::vec3(0.0, 0.0, 1.0)); glm::mat4 scaleMatrix = glm::scale(glm::vec3(m_scale, 1.0)); m_model = posMatrix * rotZMatrix * scaleMatrix; return m_model; } glm::vec2 const & Transform2D::getPos() const { return m_pos; } glm::vec2 & Transform2D::getPos() { return m_pos; } float const & Transform2D::getRot() const { return m_rot; } float & Transform2D::getRot() { return m_rot; } glm::vec2 const & Transform2D::getScale() const { return m_scale; } glm::vec2 & Transform2D::getScale() { return m_scale; }
baadfood/myCode
Project3/Transform2D.cpp
C++
gpl-2.0
883
/** * Created with JetBrains WebStorm. * User: eder * Date: 14-7-14 * Time: ไธŠๅˆ11:36 * To change this template use File | Settings | File Templates. */ var gameConst = require('../../tools/constValue'); var pomelo = require('pomelo'); var logger = require('pomelo/node_modules/pomelo-logger').getLogger(pomelo.app.getServerId(), __filename); var templateManager = require('../../tools/templateManager'); var templateConst = require('../../../template/templateConst'); var eVipInfo = gameConst.eVipInfo; var config = require('../../tools/config'); var ePlayerInfo = gameConst.ePlayerInfo; module.exports = function (owner) { return new Handler(owner); }; var Handler = function (owner) { this.owner = owner; this.roleID = 0; this.buyPvpNum = 0; this.freeSweepNum = 0; this.physicalNum = 0; this.freeReliveNum = 0; this.mineSweepNum = 0; /** * ้ขๅค–่ดตๆ—็‚นๆ•ฐ๏ผŒ่ฟ่ฅๅ•†้€š่ฟ‡idip่ฐƒๆ•ด็š„๏ผŒๅชๅœจidipไธญๆ‰ไผš็”จๅˆฐ่ฟ™ไธช * ๆญฃๅธธ่ดตๆ—็‚นๆ•ฐๆ˜ฏไปฅ็ฑณๅคงๅธˆไธบๅ‡†็š„๏ผŒไฝ†ๅฆ‚ๆžœ่ฟ่ฅ้œ€่ฆ่ฐƒๆ•ด๏ผŒๅˆ™ๆ€ป่ดตๆ—็‚นๆ•ฐไธบ * ็ฑณๅคงๅธˆ่ฟ”ๅ›ž็š„ๅ€ผๅŠ ไธŠๅบ•ไธ‹่ฟ™ไธชๅ€ผ๏ผŒ่ฟ™ไธชๅ€ผไนŸๅฏ่ƒฝๆ˜ฏ่ดŸๅ€ผ * */ this.extraVipPoint = 0; }; var handler = Handler.prototype; handler.LoadDataByDB = function (dataList) { var self = this; if (null != dataList && dataList.length > 0) { self.roleID = dataList[eVipInfo.RoleID]; self.buyPvpNum = dataList[eVipInfo.BuyPVPNum]; self.freeSweepNum = dataList[eVipInfo.FreeSweepNum]; self.physicalNum = dataList[eVipInfo.PhysicalNum]; self.freeReliveNum = dataList[eVipInfo.FreeReliveNum]; self.mineSweepNum = dataList[eVipInfo.MineSweepNum]; } }; /** * idip่ฐƒๆ•ดvip็‚นๆ•ฐ็”จๅˆฐ๏ผŒไธŠ็บฟๆ—ถไปŽๅบ“ไธญๅ–่ฟ™ไธชๅ€ผๅ†ๅ’Œ็ฑณๅคงๅธˆ่ฟ”ๅ›ž็š„ๅ€ผๆฑ‚ๅˆ * */ handler.LoadExtraVipPoint = function(data) { var GameSvrId = this.owner.playerInfo[ePlayerInfo.serverUid]; var point = null; for(var index in data) { if(data[index]['serverUid'] == GameSvrId) { point = data[index]['point'] || 0; break; } } point = point == null ? 0 : point; this.extraVipPoint = point; }; handler.GetExtraVipPoint = function() { return this.extraVipPoint || 0; }; handler.GetSqlStr = function (roleID) { var info = ''; info += '('; info += roleID + ',' + this.buyPvpNum + ',' + this.freeSweepNum + ',' + this.physicalNum + ',' + this.freeReliveNum + ',' + this.mineSweepNum ; info += ')'; return info; }; handler.UpdateVip12Info = function () { this.buyPvpNum = 0; this.freeSweepNum = 0; this.physicalNum = 0; this.freeReliveNum = 0; this.mineSweepNum = 0; }; handler.InitNumByType = function (roleID, type, num) { var self = this; if (this.roleID == 0) { this.roleID = roleID; } switch (type) { case eVipInfo.BuyPVPNum: self.buyPvpNum = num; break; case eVipInfo.FreeSweepNum: self.freeSweepNum = num; break; case eVipInfo.PhysicalNum: self.physicalNum = num; break; case eVipInfo.FreeReliveNum: self.freeReliveNum = num; break; case eVipInfo.MineSweepNum: self.mineSweepNum = num; break; default : logger.error("้‡็ฝฎvipๆฌกๆ•ฐๆœ‰้”™่ฏฏ็ฑปๅž‹"); } }; //ๅŠ ไธŠ็”จ่ฟ‡็š„ๆฌกๆ•ฐ handler.setNumByType = function (roleID, type, num) { var self = this; if (this.roleID == 0) { this.roleID = roleID; } switch (type) { case eVipInfo.BuyPVPNum: self.buyPvpNum += num; break; case eVipInfo.FreeSweepNum: self.freeSweepNum += num; break; case eVipInfo.PhysicalNum: self.physicalNum += num; break; case eVipInfo.FreeReliveNum: self.freeReliveNum += num; break; case eVipInfo.MineSweepNum: self.mineSweepNum += num; break; default : logger.error("ๆ›ดๆ–ฐvipๆฌกๆ•ฐๆœ‰้”™่ฏฏ็ฑปๅž‹"); } }; handler.getNumByType = function (type) { switch (type) { case eVipInfo.BuyPVPNum: return this.buyPvpNum; break; case eVipInfo.FreeSweepNum: return this.freeSweepNum; break; case eVipInfo.PhysicalNum: return this.physicalNum; break; case eVipInfo.FreeReliveNum: return this.freeReliveNum; break; case eVipInfo.MineSweepNum: return this.mineSweepNum; break; default : logger.error("get vipๆฌกๆ•ฐๆœ‰้”™่ฏฏ็ฑปๅž‹"); } }; handler.SendFreeSweepNum = function () { var self = this; var player = self.owner; var vipLevel = player.GetPlayerInfo(gameConst.ePlayerInfo.VipLevel); var vipTemplate = null; if (null == vipLevel || vipLevel == 0) { vipTemplate = templateManager.GetTemplateByID('VipTemplate', 1); } else { vipTemplate = templateManager.GetTemplateByID('VipTemplate', vipLevel + 1); } var route = "ServerSendFreeWeeepNum"; var msg = {num: 0}; if (null !== vipTemplate) { msg.num = vipTemplate[templateConst.tVipTemp.freeSweep] - self.freeSweepNum; } // logger.warn('SendFreeSweepNum, roleID: %j', this.owner.GetPlayerInfo(gameConst.ePlayerInfo.ROLEID)); player.SendMessage(route, msg); }; //VIP็ญ‰็บงๅ‡็บงๆ—ถ้‡็ฝฎvipๆ‰ซ่กๆฌกๆ•ฐ handler.SetVipInfoNum = function ( vipLevel) { var self = this; var vipTemplate = templateManager.GetTemplateByID('VipTemplate', vipLevel + 1); if (null == vipTemplate) { return; } var sweepNum = self.getNumByType(gameConst.eVipInfo.FreeSweepNum); var vipNum = vipTemplate[templateConst.tVipTemp.freeSweep]; if (vipNum <= 0) { return; } self.InitNumByType(self.owner.GetPlayerInfo(gameConst.ePlayerInfo.ROLEID), gameConst.eVipInfo.FreeSweepNum, sweepNum); self.SendFreeSweepNum(); }; handler.GetVipTemplate = function () { var ownerVipLevel = this.owner.GetPlayerInfo(gameConst.ePlayerInfo.VipLevel); var vipTemplate = null; if (null == ownerVipLevel || ownerVipLevel == 0) { vipTemplate = templateManager.GetTemplateByID('VipTemplate', 1); } else { vipTemplate = templateManager.GetTemplateByID('VipTemplate', ownerVipLevel + 1); } return vipTemplate; };
huojiecs/game1
game-server/app/cs/vipInfo/vipInfoManager.js
JavaScript
gpl-2.0
6,562
package tv.emby.embyatv.ui; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.FrameLayout; import tv.emby.embyatv.R; /** * Created by Eric on 11/22/2015. */ public class DetailRowView extends FrameLayout { public DetailRowView(Context context) { super(context); inflateView(context); } public DetailRowView(Context context, AttributeSet attrs) { super(context, attrs); inflateView(context); } private void inflateView(Context context) { LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.details_overview_row, this); } }
letroll/Emby.AndroidTv
EmbyAndroidTv/app/src/main/java/tv/emby/embyatv/ui/DetailRowView.java
Java
gpl-2.0
708
<?php /*------------------------------------------------------------------------ # com_xcideveloper - Seamless merging of CI Development Style with Joomla CMS # ------------------------------------------------------------------------ # author Xavoc International / Gowrav Vishwakarma # copyright Copyright (C) 2011 xavoc.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.xavoc.com # Technical Support: Forum - http://xavoc.com/index.php?option=com_discussions&view=index&Itemid=157 -------------------------------------------------------------------------*/ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * CodeIgniter Security Helpers * * @package CodeIgniter * @subpackage Helpers * @category Helpers * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/helpers/security_helper.html */ // ------------------------------------------------------------------------ /** * XSS Filtering * * @access public * @param string * @param bool whether or not the content is an image file * @return string */ if ( ! function_exists('xss_clean')) { function xss_clean($str, $is_image = FALSE) { $CI =& get_instance(); return $CI->security->xss_clean($str, $is_image); } } // ------------------------------------------------------------------------ /** * Sanitize Filename * * @access public * @param string * @return string */ if ( ! function_exists('sanitize_filename')) { function sanitize_filename($filename) { $CI =& get_instance(); return $CI->security->sanitize_filename($filename); } } // -------------------------------------------------------------------- /** * Hash encode a string * * This is simply an alias for do_hash() * dohash() is now deprecated */ if ( ! function_exists('dohash')) { function dohash($str, $type = 'sha1') { return do_hash($str, $type); } } // -------------------------------------------------------------------- /** * Hash encode a string * * @access public * @param string * @return string */ if ( ! function_exists('do_hash')) { function do_hash($str, $type = 'sha1') { if ($type == 'sha1') { if ( ! function_exists('sha1')) { if ( ! function_exists('mhash')) { require_once(BASEPATH.'libraries/Sha1'.EXT); $SH = new CI_SHA; return $SH->generate($str); } else { return bin2hex(mhash(MHASH_SHA1, $str)); } } else { return sha1($str); } } else { return md5($str); } } } // ------------------------------------------------------------------------ /** * Strip Image Tags * * @access public * @param string * @return string */ if ( ! function_exists('strip_image_tags')) { function strip_image_tags($str) { $str = preg_replace("#<img\s+.*?src\s*=\s*[\"'](.+?)[\"'].*?\>#", "\\1", $str); $str = preg_replace("#<img\s+.*?src\s*=\s*(.+?).*?\>#", "\\1", $str); return $str; } } // ------------------------------------------------------------------------ /** * Convert PHP tags to entities * * @access public * @param string * @return string */ if ( ! function_exists('encode_php_tags')) { function encode_php_tags($str) { return str_replace(array('<?php', '<?php', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str); } } /* End of file security_helper.php */ /* Location: ./system/helpers/security_helper.php */
gowrav-vishwakarma/ffm
administrator/components/com_mlm/system/helpers/security_helper.php
PHP
gpl-2.0
3,951
<?php /** * Element: Header * Displays a title with a bunch of extras, like: description, image, versioncheck * * @package NoNumber Framework * @version 12.4.4 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright ยฉ 2012 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ // No direct access defined('_JEXEC') or die; // Load common functions require_once JPATH_PLUGINS.'/system/nnframework/helpers/functions.php'; /** * Header Element * * Available extra parameters: * title The title * description The description * xml The xml file for grabbing data * language_file Main name part of the language php file * image Image (and path) to show on the right * image_w Image width * image_h Image height * url The main url * help_url The url of the help page */ class nnFieldHeader { var $_version = '12.4.4'; function getInput($name, $id, $value, $params, $children, $j15 = 0) { $this->params = $params; $document = JFactory::getDocument(); $document->addStyleSheet(JURI::root(true).'/plugins/system/nnframework/css/style.css?v='.$this->_version); $title = $this->def('label'); $description = $this->def('description'); $xml = $this->def('xml'); $lang_file = $this->def('language_file'); $image = $this->def('image'); $image_w = $this->def('image_w'); $image_h = $this->def('image_h'); $url = $this->def('url'); $help_url = $this->def('help_url'); if ($description) { // variables $v1 = $this->def('var1'); $v2 = $this->def('var2'); $v3 = $this->def('var3'); $v4 = $this->def('var4'); $v5 = $this->def('var5'); $description = NNFrameworkFunctions::html_entity_decoder(trim(JText::sprintf($description, $v1, $v2, $v3, $v4, $v5))); } if ($lang_file) { jimport('joomla.filesystem.file'); // Include extra language file $language = JFactory::getLanguage(); $lang = str_replace('_', '-', $language->getTag()); $inc = ''; $lang_path = 'language/'.$lang.'/'.$lang.'.'.$lang_file.'.inc.php'; if (JFile::exists(JPATH_ADMINISTRATOR.'/'.$lang_path)) { $inc = JPATH_ADMINISTRATOR.'/'.$lang_path; } else if (JFile::exists(JPATH_SITE.'/'.$lang_path)) { $inc = JPATH_SITE.'/'.$lang_path; } if (!$inc && $lang != 'en-GB') { $lang = 'en-GB'; $lang_path = 'language/'.$lang.'/'.$lang.'.'.$lang_file.'.inc.php'; if (JFile::exists(JPATH_ADMINISTRATOR.'/'.$lang_path)) { $inc = JPATH_ADMINISTRATOR.'/'.$lang_path; } else if (JFile::exists(JPATH_SITE.'/'.$lang_path)) { $inc = JPATH_SITE.'/'.$lang_path; } } if ($inc) { include $inc; } } if ($title) { $title = JText::_($title); } if ($description) { $description = str_replace('span style="font-family:monospace;"', 'span class="nn_code"', $description); if ($description['0'] != '<') { $description = '<p>'.$description.'</p>'; } } if ($xml) { $xml = JApplicationHelper::parseXMLInstallFile(JPATH_SITE.'/'.$xml); $version = 0; if ($xml && isset($xml['version'])) { $version = $xml['version']; } if ($version) { if (!(strpos($version, 'PRO') === false)) { $version = str_replace('PRO', '', $version); $version .= ' <small style="color:green">[PRO]</small>'; } else if (!(strpos($version, 'FREE') === false)) { $version = str_replace('FREE', '', $version); $version .= ' <small style="color:green">[FREE]</small>'; } if ($title) { $title .= ' v'; } else { $title = JText::_('Version').' '; } $title .= $version; } } if ($url) { $url = '<a href="'.$url.'" target="_blank" title="'.preg_replace('#<[^>]*>#', '', $title).'">'; } $html = array(); $html[] = '<div class="panel nn_panel'.($j15 ? ' nn_panel_15' : '').'"><div class="nn_block nn_title">'; if ($image) { $image = str_replace('/', "\n", str_replace('\\', '/', $image)); $image = explode("\n", trim($image)); if ($image['0'] == 'administrator') { $image['0'] = JURI::base(true); } else { $image['0'] = JURI::root(true).'/'.$image['0']; } $image = '<img src="'.implode('/', $image).'" border="0" style="float:right;margin-left:10px" alt=""'; if ($image_w) { $image .= ' width="'.$image_w.'"'; } if ($image_h) { $image .= ' height="'.$image_h.'"'; } $image .= ' />'; if ($url) { $image = $url.$image.'</a>'; } $html[] = $image; } if ($title) { if ($url) { $title = $url.$title.'</a>'; } $html[] = '<h4 style="margin: 0px;">'.NNFrameworkFunctions::html_entity_decoder($title).'</h4>'; } if ($description) { $html[] = $description; } if ($help_url) { $html[] = '<p><a href="'.$help_url.'" target="_blank" title="'.JText::_('NN_MORE_INFO').'">'.JText::_('NN_MORE_INFO').'...</a></p>'; } $html[] = '<div style="clear: both;"></div>'; $html[] = '</div></div>'; return implode('', $html); } private function def($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } } if (version_compare(JVERSION, '1.6.0', 'l')) { // For Joomla 1.5 class JElementNN_Header extends JElement { /** * Element name * * @access protected * @var string */ var $_name = 'Header'; function fetchTooltip($label, $description, &$node, $control_name, $name) { $this->_nnfield = new nnFieldHeader(); return; } function fetchElement($name, $value, &$node, $control_name) { return $this->_nnfield->getInput($control_name.'['.$name.']', $control_name.$name, $value, $node->attributes(), $node->children(), 1); } } } else { // For Joomla 1.6 class JFormFieldNN_Header extends JFormField { /** * The form field type * * @var string */ public $type = 'Header'; protected function getLabel() { $this->_nnfield = new nnFieldHeader(); return; } protected function getInput() { return $this->_nnfield->getInput($this->name, $this->id, $this->value, $this->element->attributes(), $this->element->children()); } } }
MA-Ponyvriedjes/ponyvriendjes
plugins/system/nnframework/fields/header.php
PHP
gpl-2.0
6,158
<?php /** * @Project NUKEVIET 3.x * @Author VINADES.,JSC (contact@vinades.vn) * @Copyright (C) 2012 VINADES.,JSC. All rights reserved * @Createdate 28/10/2012, 14:51 */ // Xรกc ฤ‘แป‹nh root site define( 'NV_ROOTDIR', pathinfo( str_replace( DIRECTORY_SEPARATOR, '/', __file__ ), PATHINFO_DIRNAME ) ); class Token { public $type; public $contents; public function __construct( $rawToken ) { if( is_array( $rawToken ) ) { $this->type = $rawToken[0]; $this->contents = $rawToken[1]; } else { $this->type = - 1; $this->contents = $rawToken; } } } function nv_fomat_dir( $dirname, $all = false ) { $dh = opendir( NV_ROOTDIR . '/' . $dirname ); if( $dh ) { while( ($file = readdir( $dh )) !== false ) { if( preg_match( '/^([a-zA-Z0-9\-\_\/\.]+)\.php$/', $file ) ) { if( ! nv_fomat_file_php( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $dirname . '/' . $file . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.js$/", $file ) ) { if( ! nv_fomat_file_js( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $file . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.tpl$/", $file ) ) { if( ! nv_fomat_file_tpl( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { echo $dirname . '/' . $file . ' ---------------------- no change ----------------------<br>'; } else { echo $dirname . '/' . $file . '<br>'; } } elseif( $all and preg_match( "/^([a-zA-Z0-9\-\_\/]+)$/", $file ) and is_dir( NV_ROOTDIR . '/' . $dirname . '/' . $file ) ) { nv_fomat_dir( $dirname . '/' . $file, $all ); } } } } /** * @param strimg $filename * @return number */ function nv_fomat_file_php( $filename ) { // ap dung cho Aptana Studio 3 $array_file_not_fomat = array( ); $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/idna_convert.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/openid.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/pclzip.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/SimpleCaptcha.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/class/xtemplate.class.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.phpmailer.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.pop3.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/includes/phpmailer/class.smtp.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/api.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/cas.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/ConfigurationUpdater.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/createcasimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/createimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/getconfig.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/getmathml.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/libwiris.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/service.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/showcasimage.php'; $array_file_not_fomat[] = NV_ROOTDIR . '/editors/ckeditor/plugins/ckeditor_wiris/integration/showimage.php'; if( ! in_array( $filename, $array_file_not_fomat ) ) { $contents = file_get_contents( $filename ); // Thรชm dรฒng trแบฏng ฤ‘แบงu file $output_data = preg_replace( '/^\<\?php/', "<?php\n", trim( $contents ) ); // Thรชm dรฒng trแบฏng แปŸ cuแป‘i file $output_data = preg_replace( '/\?\>$/', "\n?>", $output_data ); //Xรณa cรกc dรฒng trแป‘ng cรณ tab, hoแบทc cรณ nhiแปu hฦกn 1 dรฒng trแป‘ng $output_data = trim( preg_replace( '/\n([\t\n]+)\n/', "\n\n", $output_data ) ); $output_data = preg_replace( '/\,\s\-\s/', ', -', $output_data ); //Khรดng xuแป‘ng dรฒng nแบฟu if cรณ 1 lแป‡nh $output_data = preg_replace( '/if\((.*)\)\n([\t\s]+)([^\{\s]{1}+)/', "if(\\1) \\3", $output_data ); //Thรชm khoแบฃng cรกch vร o sau vร  trฦฐแป›c dแบฅu mแปŸ ngoแบทc ฤ‘ฦกn $raw_tokens = token_get_all( $output_data ); $array_tokend = array( ); foreach( $raw_tokens as $rawToken ) { $array_tokend[] = new Token( $rawToken ); } foreach( $array_tokend as $key => $tokend ) { if( $tokend->contents == '(' ) { if( $array_tokend[$key + 1]->type != T_WHITESPACE ) { $array_tokend[$key]->contents = '( '; } } elseif( $tokend->contents == ')' ) { if( $array_tokend[$key - 1]->type != T_WHITESPACE ) { $array_tokend[$key]->contents = ' )'; } } } $output_data = ''; foreach( $array_tokend as $key => $tokend ) { $output_data .= $tokend->contents; } //Xแปญ lรฝ mแบฃng $raw_tokens = token_get_all( $output_data ); $array_tokend = array( ); foreach( $raw_tokens as $rawToken ) { $array_tokend[] = new Token( $rawToken ); } $output_data = ''; $this_line_tab = ''; // Thut dau dong dong hien tai $is_in_array = 0; // Trong array - array cap thu bao nhieu $num_open_parentheses = array( ); // Dem so dau ( $num_close_parentheses = array( ); // Dem so dau ) $is_double_arrow = array( ); // Array co xuong hang hay khong $total_tokend = sizeof( $array_tokend ); foreach( $array_tokend as $key => $tokend ) { // Xac dinh so tab if( $tokend->type == T_WHITESPACE and preg_match( "/\n/", $tokend->contents ) and $is_in_array <= 0 ) { $tab = array_filter( explode( "\n", $tokend->contents ) ); $tab = end( $tab ); $this_line_tab = $tab; } elseif( $tokend->type == T_CATCH and $array_tokend[$key + 1]->type == T_WHITESPACE ) { $array_tokend[$key + 1]->contents = ''; } // Danh dau array bat dau if( $tokend->type == T_ARRAY ) { $is_in_array++; $is_double_arrow[$is_in_array] = 0; // Mac dinh khong co mui ten hoac array con $key_close_array = $key; // Tim trong array nay co mui ten => hay la array con hay khong $j = $key; $_num_open_parentheses = 0; $_num_close_parentheses = 0; while( $j < $total_tokend ) { $j++; if( $array_tokend[$j]->contents == "(" ) $_num_open_parentheses++; if( $array_tokend[$j]->contents == ")" ) $_num_close_parentheses++; if( $array_tokend[$j]->type == T_DOUBLE_ARROW or $array_tokend[$j]->type == T_ARRAY or ($array_tokend[$j]->type == T_COMMENT and $array_tokend[$j - 2]->contents == ",") ) { $is_double_arrow[$is_in_array]++; } if( $_num_open_parentheses > 0 and $_num_open_parentheses == $_num_close_parentheses ) { $key_close_array = $j; break; } } $is_double_arrow[$is_in_array] = $is_double_arrow[$is_in_array] > 2 ? true : false; $num_open_parentheses[$is_in_array] = 0; $num_close_parentheses[$is_in_array] = 0; } if( $is_in_array > 0 ) { if( empty( $is_double_arrow[$is_in_array] ) and $tokend->type == T_WHITESPACE ) { $tokend->contents = str_replace( array( "\n", "\t" ), array( " ", "" ), $tokend->contents ); } // Xoa dau , cuoi cung cua array if( $key == ($key_close_array - 2) and $tokend->contents == "," and $tokend->type == - 1 ) { $tokend->contents = ''; } elseif( $tokend->type == T_WHITESPACE and preg_match( "/\n/", $tokend->contents ) and ! empty( $is_double_arrow[$is_in_array] ) ) { $tokend->contents = "\n" . $this_line_tab; for( $i = 0; $i < $is_in_array; ++$i ) { $tokend->contents .= "\t"; } } // Dong mo array if( $tokend->contents == "(" ) $num_open_parentheses[$is_in_array]++; if( $tokend->contents == ")" ) $num_close_parentheses[$is_in_array]++; if( $num_open_parentheses[$is_in_array] > 0 and $num_open_parentheses[$is_in_array] == $num_close_parentheses[$is_in_array] ) { if( ! empty( $is_double_arrow[$is_in_array] ) ) { $output_data = trim( $output_data ) . "\n" . $this_line_tab; for( $i = 1; $i < $is_in_array; ++$i ) { $output_data .= "\t"; } } $output_data .= ")"; $is_in_array--; } else { $output_data .= $tokend->contents; } } else { $output_data .= $tokend->contents; } } // Loแบกi bแป khoแบฃng trแบฏng ( ) $output_data = preg_replace( '/\([\s]+\)/', '()', $output_data ); $output_data = preg_replace( "/[ ]+/", " ", $output_data ); if( $output_data != $contents ) { return file_put_contents( $filename, trim( $output_data ), LOCK_EX ); } } return 0; } function nv_fomat_file_js( $filename ) { // ap dung cho Zend Studio 9.0.4 $contents = file_get_contents( $filename ); $output_data = preg_replace( '/\n([\t\n]+)\n/', "\n\n", $contents ); //Xรณa cรกc dรฒng trแป‘ng cรณ tab, hoแบทc cรณ nhiแปu hฦกn 1 dรฒng trแป‘ng $output_data = str_replace( '( var ', '(var ', $output_data ); if( $output_data != $contents ) { return file_put_contents( $filename, trim( $output_data ), LOCK_EX ); } return 0; } function nv_fomat_file_tpl( $filename ) { $contents = file_get_contents( $filename ); // Xรณa dรฒng trแป‘ng แปŸ cuแป‘i vร  sแปญa khoแบฃng trแป‘ng <textarea $contentssave = trim( preg_replace( '/\>\s*\<textarea\s*/', '><textarea ', $contents ) ); $contentssave = str_replace( '<td></td>', '<td>&nbsp;</td>', $contentssave ); $contentssave = str_replace( '<tbody{', '<tbody {', $contentssave ); $contentssave = str_replace( '<li{', '<li {', $contentssave ); $contentssave = str_replace( '<blockquote{CLASS}>', '<blockquote {CLASS}>', $contentssave ); $dom = new DOMDocument( ); $dom->loadHTML( $contentssave ); $dom->preserveWhiteSpace = false; $Tagname = $dom->getElementsByTagname( 'script' ); foreach( $Tagname as $child ) { $tmp_dom = new DOMDocument( ); $tmp_dom->appendChild( $tmp_dom->importNode( $child, true ) ); $html = trim( $tmp_dom->saveHTML( ) ); if( preg_match( '/\<\!\-\-\s*BEGIN:\s*([a-zA-Z0-9\-\_]+)\s*\-\-\>/', $html, $m ) ) { print_r( "Xtemplate: " . $m[1] . " trong JS file: " . $filename ); return 0; } elseif( preg_match_all( '/\{\s*\n*\t*([a-zA-Z0-9\-\_\.]+)\s*\n*\t*\}/i', $html, $m ) ) { $s = sizeof( $m[0] ); for( $i = 0; $i <= $s; $i++ ) { $contentssave = ( string )str_replace( $m[0][$i], '{' . trim( $m[1][$i] ) . '}', $contentssave ); } } } //Xรณa cรกc dรฒng trแป‘ng cรณ tab, hoแบทc cรณ nhiแปu hฦกn 1 dรฒng trแป‘ng $contentssave = trim( preg_replace( '/\n([\t\n]+)\n/', "\n\n", $contentssave ) ); if( $contentssave != $contents ) { return file_put_contents( $filename, $contentssave, LOCK_EX ); } return 0; } $filename = isset( $_GET['f'] ) ? trim( $_GET['f'] ) : ''; $filename = str_replace( '..', '', $filename ); if( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.php$/", $filename ) ) { if( ! nv_fomat_file_php( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.tpl$/", $filename ) ) { if( ! nv_fomat_file_tpl( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( preg_match( "/^([a-zA-Z0-9\-\_\/\.]+)\.js$/", $filename ) ) { if( ! nv_fomat_file_js( NV_ROOTDIR . '/' . $filename ) ) { echo $filename . ' ---------------------- no change ----------------------<br>'; } else { echo $filename . '<br>'; } } elseif( (preg_match( "/^([a-zA-Z0-9\-\_\/]+)$/", $filename ) or $filename == '') and is_dir( NV_ROOTDIR . '/' . $filename ) ) { $all = isset( $_GET['all'] ) ? intval( $_GET['all'] ) : 0; nv_fomat_dir( $filename, $all ); } else { die( $filename ); } ?>
teammhst13-27/mhst13-27
fa.php
PHP
gpl-2.0
12,410
<?php require_once(drupal_get_path('theme','heshel').'/tpl/header.tpl.php'); global $base_url; drupal_set_title(''); ?> <?php if (!empty($tabs['#primary']) || !empty($tabs['#secondary'])): print render($tabs); endif; print $messages; unset($page['content']['system_main']['default_message']); ?> <div class="wrapper"> <div class="container"> <div class="content_block row no-sidebar"> <div class="page_title"> <h1><?php print drupal_get_title(); ?></h1> </div> <div class="fl-container"> <div class="posts-block"> <div class="contentarea"> <div class="rounded-corners" style="max-width:976px; margin-left:auto; margin-right:auto; background-color:#EEEEEE; padding:10px;"> <?php if($page['content']):?> <?php print render($page['content']); ?> <?php endif; ?> <?php if($page['section_content']):?> <?php print render($page['section_content']); ?> <?php endif; ?> </div> </div> </div> </div> </div> </div> <br /> <br /> <?php require_once(drupal_get_path('theme','heshel').'/tpl/footer.tpl.php'); ?>
agroknow/agreri
sites/all/themes/heshel/tpl/page--project.tpl.php
PHP
gpl-2.0
1,723
/* * Copyright (C) 2015 TinyCore <http://www.tinycore.net/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: The_Eye SD%Complete: 100 SDComment: SDCategory: Tempest Keep, The Eye EndScriptData */ /* ContentData npc_crystalcore_devastator EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_eye.h" enum Spells { SPELL_COUNTERCHARGE = 35035, SPELL_KNOCKAWAY = 22893, }; class npc_crystalcore_devastator : public CreatureScript { public: npc_crystalcore_devastator() : CreatureScript("npc_crystalcore_devastator") { } struct npc_crystalcore_devastatorAI : public ScriptedAI { npc_crystalcore_devastatorAI(Creature* creature) : ScriptedAI(creature) { Initialize(); } void Initialize() { Countercharge_Timer = 9000; Knockaway_Timer = 25000; } uint32 Knockaway_Timer; uint32 Countercharge_Timer; void Reset() override { Initialize(); } void EnterCombat(Unit* /*who*/) override { } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; //Check if we have a current target //Knockaway_Timer if (Knockaway_Timer <= diff) { DoCastVictim(SPELL_KNOCKAWAY, true); // current aggro target is knocked away pick new target Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0); if (!target || target == me->GetVictim()) target = SelectTarget(SELECT_TARGET_TOPAGGRO, 1); if (target) me->TauntApply(target); Knockaway_Timer = 23000; } else Knockaway_Timer -= diff; //Countercharge_Timer if (Countercharge_Timer <= diff) { DoCast(me, SPELL_COUNTERCHARGE); Countercharge_Timer = 45000; } else Countercharge_Timer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_crystalcore_devastatorAI(creature); } }; void AddSC_the_eye() { new npc_crystalcore_devastator(); }
AwkwardDev/TinyCore
src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp
C++
gpl-2.0
3,339
<?php /** * The themes Header file. * * Displays all of the <head> section and everything up till <div id="main-wrap"> * * @package Moka * @since Moka 1.0 */ ?><!DOCTYPE html> <html id="doc" <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="shortcut icon" href="http://blog.kochabo.at/wp-content/uploads/2014/02/kochabo-at-favicon.png" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link href='http://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'> <?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script> <![endif]--> <?php wp_head(); ?> <?php if(get_site_url()=="http://blog.kochabo.at") : ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-29618342-1']); _gaq.push(['_setDomainName', 'blog.kochabo.at']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> function saveEmailLead(){ var email = document.getElementById('lead-signup-email').value; jQuery.ajax({ url: 'http://www.kochabo.at/kochabo/ajax/saveFacebookLead', data: ({email:email, source: 'blog-sidebar'}), success: function() { } }); document.getElementById('signupsuccess').style.display = 'block'; } </script> <?php elseif(get_site_url()=="http://blog.kochpost.ch") : ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-26604164-1']); _gaq.push(['_setDomainName', 'blog.kochpost.ch']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> function saveEmailLead(){ var email = document.getElementById('lead-signup-email').value; jQuery.ajax({ url: 'http://www.kochpost.ch/kochabo/ajax/saveFacebookLead', data: ({email:email, source: 'blog-sidebar'}), success: function() { } }); document.getElementById('signupsuccess').style.display = 'block'; } </script> <?php endif; ?> <script type="text/javascript"> jQuery(function() { jQuery('body').hide().show(); }); </script> </head> <body <?php body_class(); ?>> <div id="container"> <div class="search-overlay"> <div class="search-wrap"> <?php get_template_part( 'search-main' ); ?> <div class="search-close"><?php _e('Close Search', 'moka') ?></div> <p class="search-info"><?php _e('Type your search terms above and press return to see the search results.', 'moka') ?></p> </div><!-- end .search-wrap --> </div><!-- end .search-overlay --> <div id="sidebar-wrap"> <div id="sidebar"> <header id="masthead" class="clearfix" role="banner"> <div id="site-title"> <h1><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1> <?php if ( '' != get_bloginfo('description') ) : ?> <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2> <?php endif; ?> </div><!-- end #site-title --> </header><!-- end #masthead --> <a href="#nav-mobile" id="mobile-menu-btn"><span><?php _e('Menu', 'moka') ?></span></a> <nav id="site-nav" class="clearfix"> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container' => 'false') ); ?> <div style="margin-top:25px;"> <?php if(get_site_url()=="http://blog.kochabo.at") : ?> <a href="http://www.facebook.com/kochabo" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/facebook-icon.png" width="40" alt="KochAbo.at Facebook" /></a>&nbsp; <a href="http://www.twitter.com/kochabo_at" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/twitter-icon.png" width="40" alt="KochAbo.at Twitter" /></a>&nbsp; <a href="http://www.youtube.com/KochAboAT" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/youtube-icon.png" width="40" alt="KochAbo.at Youtube" /></a> <?php elseif(get_site_url()=="http://blog.kochpost.ch") : ?> <a href="http://www.facebook.com/kochpost" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/facebook-icon.png" width="40" alt="KochAbo.at Facebook" /></a>&nbsp; <a href="http://www.youtube.com/kochpost" target="_BLANK"><img src="http://blog.kochabo.at/wp-content/uploads/2014/03/youtube-icon.png" width="40" alt="KochAbo.at Youtube" /></a> <?php endif; ?> <div style="margin-top:20px; font-size:14px;"> Woche fรผr Woche kรถstliche Rezepte per E-Mail. Jetzt anmelden! <div id="signupsuccess" style="display:none; color:green;">Danke fรผr deine Anmeldung!</div> </div> <div style="margin-top:10px;"> <form action='javascript:saveEmailLead()' id='signup' name='signup' method='GET'> <input id='lead-signup-email' placeholder='Deine E-Mail Adresse' size='28' type='text'> <a style="margin-top:5px;" class="standard-btn red-btn xsmall-btn" href="javascript:document.signup.submit()"> <span>Eintragen</span> </a> </form> </div> </div> <div id="search-btn"><?php _e('Suche', 'moka') ?></div> </nav><!-- end #site-nav --> </div><!-- end #sidebar --> </div><!-- end #sidebar-wrap --> <div id="main-wrap">
Designer023/wp-at-blog
wp-content/themes/moka/header.php
PHP
gpl-2.0
6,225
angular.module('starter.controllers') .controller('ChartsCtrl', function($scope,ChartData, $ionicLoading){ $scope.labels = []; $scope.series = ['']; $scope.chartOptions = { datasetFill:false, animation:false, showScale:true, scaleShowGridLines: true, pointDot:false, bezierCurve:false }; $scope.startDate = moment().subtract(30, 'days').toDate(); $scope.endDate = new Date(); var showMonthXLabels = false; $scope.getChart = function(shareIndex, startDate, endDate,report) { $ionicLoading.show({template: "loading..."}); ChartData.chartData(shareIndex, startDate, endDate, report) .error(function(){ alert('Ugh, something went wrong with loading the chart. Please try again or contact us for support.'); $ionicLoading.hide(); }) .success(function(data){ $ionicLoading.hide(); var results = []; for (var i = 0; i < data.Rows.length; i++){ results.push(data.Rows[i]); } //TODO: Eish, figure out a way to do this better!!! if (results.length > 20) { showMonthXLabels = true; } else{ showMonthXLabels = false; } var fillColor = "rgba(252,7,31,0)"; var datasets = []; if (report == "MyPortfolioReport"){ var portfolioOverallValues = results.map(function(row){return row.portfolioOverallValue/100;}) var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); $scope.labels = labels; $scope.series = ['Portfolio Value']; $scope.data = [portfolioOverallValues]; } if (report == "RsiReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); var rsi = results.map(function(row){ return parseInt(row.rsi);}); $scope.labels = labels; $scope.series = ['Relative Strength']; $scope.data = [rsi]; } if (report == "SingleStockMacdReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.date)); } else return toJSONLocal(new Date(row.date)); }); macd = results.map(function(row){ return parseInt(row.macd_line);}); histogram = results.map(function(row){ return parseInt(row.histogram);}); divergence = results.map(function(row){ return parseInt(row.signal_line);}); $scope.labels = labels; $scope.series = ['Macd','Divergence']; $scope.data = [macd,divergence]; } if (report == "DailyCloseStockPriceReport"){ var labels = results.map(function(row){ if (showMonthXLabels){ return showFirstDateOfMonthOrNothing(new Date(row.dateOfPrice)); } else return toJSONLocal(new Date(row.dateOfPrice)); }); close_prices = results.map(function(row){return row.closePrice / 100;}) $scope.labels = labels; $scope.data = [close_prices] $scope.series = ['Close Prices'] } }); }; }); var lastDate = undefined; var dateCount = 0; function showFirstDateOfMonthOrNothing(date){ var returnValue = ""; if (dateCount == 0){ returnValue = toJSONLocal(date); } else if (dateCount % 10 == 0){ returnValue = toJSONLocal(date); } dateCount ++; return returnValue; }
tbohnen/EquityTrader
StockRetriever.Ui.Mobile/www/js/chartsController.js
JavaScript
gpl-2.0
3,667
/* FatRat download manager http://fatrat.dolezel.info Copyright (C) 2006-2011 Lubos Dolezel <lubos a dolezel.info> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package info.dolezel.fatrat.plugins.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author lubos */ public class XmlUtils { static final XPathFactory factory = XPathFactory.newInstance(); static final DocumentBuilderFactory dbf; static { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(false); dbf.setValidating(false); } public static XPathExpression expr(String xpathStr) throws XPathExpressionException { XPath xpath = factory.newXPath(); return xpath.compile(xpathStr); } public static String xpathString(Node node, String xpath) throws XPathExpressionException { return (String) expr(xpath).evaluate(node, XPathConstants.STRING); } public static Node xpathNode(Node node, String xpath) throws XPathExpressionException { return (Node) expr(xpath).evaluate(node, XPathConstants.NODE); } public static NodeList xpathNodeList(Node node, String xpath) throws XPathExpressionException { return (NodeList) expr(xpath).evaluate(node, XPathConstants.NODESET); } public static Document loadDocument(ByteBuffer buf) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = dbf.newDocumentBuilder(); //byte[] b = Charset.forName("UTF-8").decode(buf).toString().getBytes("UTF-8"); //System.out.println("New byte[] len: "+b.length); //return builder.parse(new ByteArrayInputStream(b)); return builder.parse(new ByteBufferInputStream(buf)); } }
LubosD/fatrat-jplugins
core/src/main/java/info/dolezel/fatrat/plugins/util/XmlUtils.java
Java
gpl-2.0
2,849
<?php /** * @file * Contains the SearchApiAutocompleteSearch class. */ /** * Class describing the settings for a certain search for which autocompletion * is available. */ class SearchApiAutocompleteSearch extends Entity { // Entity properties, loaded from the database: /** * @var integer */ public $id; /** * @var string */ public $machine_name; /** * @var string */ public $name; /** * @var integer */ public $index_id; /** * @var string */ public $type; /** * @var boolean */ public $enabled; /** * An array of options for this search, containing any of the following: * - results: Boolean indicating whether to also list the estimated number of * results for each suggestion (if possible). * - custom: An array of type-specific settings. * * @var array */ public $options = array(); // Inferred properties, for caching: /** * @var SearchApiIndex */ protected $index; /** * @var SearchApiServer */ protected $server; /** * Constructor. * * @param array $values * The entity properties. */ public function __construct(array $values = array()) { parent::__construct($values, 'search_api_autocomplete_search'); } /** * @return SearchApiIndex * The index this search belongs to. */ public function index() { if (!isset($this->index)) { $this->index = search_api_index_load($this->index_id); if (!$this->index) { $this->index = FALSE; } } return $this->index; } /** * @return SearchApiServer * The server this search would at the moment be executed on. */ public function server() { if (!isset($this->server)) { if (!$this->index() || !$this->index()->server) { $this->server = FALSE; } else { $this->server = $this->index()->server(); if (!$this->server) { $this->server = FALSE; } } } return $this->server; } /** * @return boolean * TRUE if the server this search is currently associated with supports the * autocompletion feature; FALSE otherwise. */ public function supportsAutocompletion() { return $this->server() && $this->server()->supportsFeature('search_api_autocomplete'); } /** * Helper method for altering a textfield form element to use autocompletion. */ public function alterElement(array &$element) { if (user_access('use search_api_autocomplete') && $this->supportsAutocompletion()) { $element['#attached']['css'][] = drupal_get_path('module', 'search_api_autocomplete') . '/search_api_autocomplete.css'; $element['#autocomplete_path'] = 'search_api_autocomplete/' . $this->machine_name; } } /** * Split a string with search keywords into two parts. * * The first part consists of all words the user has typed completely, the * second one contains the beginning of the last, possibly incomplete word. * * @return array * An array with $keys split into exactly two parts, both of which may be * empty. */ public function splitKeys($keys) { $keys = ltrim($keys); // If there is whitespace or a quote on the right, all words have been // completed. if (rtrim($keys, " \t\n\r\0\x0B\"") != $keys) { return array(rtrim($keys), ''); } if (preg_match('/^(.*?)\s*"?([\S]*)$/', $keys, $m)) { return array($m[1], $m[2]); } return array('', $keys); } /** * Create the query that would be issued for this search for the complete keys. * * @param $complete * A string containing the complete search keys. * @param $incomplete * A string containing the incomplete last search key. * * @return SearchApiQueryInterface * The query that would normally be executed when only $complete was entered * as the search keys for this search. */ public function getQuery($complete, $incomplete) { $info = search_api_autocomplete_get_types($this->type); if (empty($info['create query'])) { return NULL; } $query = $info['create query']($this, $complete, $incomplete); if ($complete && !$query->getKeys()) { $query->keys($complete); } return $query; } }
switch13/tonys-rest
sites/all/modules/search_api_autocomplete/search_api_autocomplete.entity.php
PHP
gpl-2.0
4,284
# -*- coding: utf-8 -*- __author__ = 'shreejoy' import unittest from article_text_mining.rep_html_table_struct import rep_html_table_struct class RepTableStructureTest(unittest.TestCase): @property def load_html_table_simple(self): # creates data table object 16055 with some dummy data with open('tests/test_html_data_tables/example_html_table_simple.html', mode='rb') as f: simple_table_text = f.read() return simple_table_text @property def load_html_table_complex(self): with open('tests/test_html_data_tables/example_html_table_complex.html', mode='rb') as f: complex_table_text = f.read() return complex_table_text def test_rep_html_table_struct_simple(self): expected_table_output = [['th-1', 'th-2', 'th-3', 'th-4', 'th-5', 'th-6'], ['td-1', 'td-1', 'td-1', 'td-1', 'td-1', 'td-1'], ['td-2', 'td-3', 'td-4', 'td-5', 'td-6', 'td-7'], ['td-8', 'td-9', 'td-10', 'td-11', 'td-12', 'td-13'], ['td-14', 'td-15', 'td-16', 'td-17', 'td-18', 'td-19'], ['td-20', 'td-21', 'td-22', 'td-23', 'td-24', 'td-25'], ['td-26', 'td-27', 'td-28', 'td-29', 'td-30', 'td-31'], ['td-32', 'td-33', 'td-34', 'td-35', 'td-36', 'td-37'], ['td-38', 'td-39', 'td-40', 'td-41', 'td-42', 'td-43'], ['td-44', 'td-45', 'td-46', 'td-47', 'td-48', 'td-49'], ['td-50', 'td-51', 'td-52', 'td-53', 'td-54', 'td-55'], ['td-56', 'td-57', 'td-58', 'td-59', 'td-60', 'td-61'], ['td-62', 'td-63', 'td-64', 'td-65', 'td-66', 'td-67'], ['td-68', 'td-69', 'td-70', 'td-71', 'td-72', 'td-73'], ['td-74', 'td-75', 'td-76', 'td-77', 'td-78', 'td-79'], ['td-80', 'td-81', 'td-82', 'td-83', 'td-84', 'td-85'], ['td-86', 'td-87', 'td-88', 'td-89', 'td-90', 'td-91'], ['td-92', 'td-93', 'td-94', 'td-95', 'td-96', 'td-97'], ['td-98', 'td-99', 'td-100', 'td-101', 'td-102', 'td-103'], ['td-104', 'td-105', 'td-106', 'td-107', 'td-108', 'td-109']] html_table_text = self.load_html_table_simple a, b, html_id_table = rep_html_table_struct(html_table_text) self.assertEqual(html_id_table, expected_table_output) def test_rep_html_table_struct_complex(self): expected_table_output = [['td-1', 0, 0, 0, 0, 0, 0, 0, 0, 0], ['td-2', 'td-2', 'td-2', 'td-2', 'td-2', 'td-2', 'td-2', 'td-2', 'td-2', 'td-2'], ['td-3', 'td-4', 'td-4', 'td-5', 'td-5', 'td-6', 'td-6', 0, 0, 0], ['td-3', 'td-7', 'td-8', 'td-9', 'td-10', 'td-11', 'td-12', 0, 0, 0], ['td-13', 'td-13', 'td-13', 'td-13', 'td-13', 'td-13', 'td-13', 'td-13', 'td-13', 'td-13'], ['td-14', 'td-15', 'td-16', 'td-17', 'td-18', 'td-19', 'td-20', 0, 0, 0], ['td-21', 'td-22', 'td-23', 'td-24', 'td-25', 'td-26', 'td-27', 0, 0, 0], ['td-28', 'td-29', 'td-30', 'td-31', 'td-32', 'td-33', 'td-34', 0, 0, 0], ['td-35', 'td-36', 'td-37', 'td-38', 'td-39', 'td-40', 'td-41', 0, 0, 0], ['td-42', 'td-43', 'td-44', 'td-45', 'td-46', 'td-47', 'td-48', 0, 0, 0], ['td-49', 'td-50', 'td-51', 'td-52', 'td-53', 'td-54', 'td-55', 0, 0, 0], ['td-56', 'td-57', 'td-58', 'td-59', 'td-60', 'td-61', 'td-62', 0, 0, 0], ['td-63', 'td-64', 'td-65', 'td-66', 'td-67', 'td-68', 'td-69', 0, 0, 0], ['td-70', 'td-71', 'td-72', 'td-73', 'td-74', 'td-75', 'td-76', 0, 0, 0], ['td-77', 'td-78', 'td-79', 'td-80', 'td-81', 'td-82', 'td-83', 0, 0, 0]] html_table_text = self.load_html_table_complex a, b, html_id_table = rep_html_table_struct(html_table_text) self.assertEqual(html_id_table, expected_table_output) if __name__ == '__main__': unittest.main()
neuroelectro/neuroelectro_org
tests/test_rep_html_table_struct.py
Python
gpl-2.0
4,596
/**************************************************************************** * MeshLab o o * * An extendible mesh processor o o * * _ O _ * * Copyright(C) 2005, 2009 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * 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 (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /* A class implementing Meshlab's Edit interface that is for picking points in 3D * * * @author Oscar Barney */ #include <QtGui> #include <GL/glew.h> #include "editpickpoints.h" #include <meshlab/mainwindow.h> #include <wrap/gl/picking.h> #include <wrap/gl/pick.h> #include <wrap/qt/gl_label.h> #include <math.h> using namespace vcg; #define PI 3.14159265 EditPickPointsPlugin::EditPickPointsPlugin() { //initialize to false so we dont end up collection some weird point in the beginning registerPoint = false; moveSelectPoint = false; pickPointsDialog = 0; currentModel = 0; overrideCursorShape = 0; } //Constants const QString EditPickPointsPlugin::Info() { return tr("Pick and save 3D points on the mesh"); } //called void EditPickPointsPlugin::Decorate(MeshModel &mm, GLArea *gla, QPainter *painter) { //qDebug() << "Decorate " << mm.fileName.c_str() << " ..." << mm.cm.fn; if(gla != glArea || mm.cm.fn < 1) { //qDebug() << "GLarea is different or no faces!!! "; return; } //make sure we picking points on the right meshes! if(&mm != currentModel){ //now that were are ending tell the dialog to save any points it has to metadata pickPointsDialog->savePointsToMetaData(); //set the new mesh model pickPointsDialog->setCurrentMeshModel(&mm, gla); currentModel = &mm; } //We have to calculate the position here because it doesnt work in the mouseEvent functions for some reason Point3f pickedPoint; if (moveSelectPoint && Pick<Point3f>(currentMousePosition.x(),gla->height()-currentMousePosition.y(),pickedPoint)){ /* qDebug("Found point for move %i %i -> %f %f %f", currentMousePosition.x(), currentMousePosition.y(), pickedPoint[0], pickedPoint[1], pickedPoint[2]); */ //let the dialog know that this was the pointed picked incase it wants the information pickPointsDialog->selectOrMoveThisPoint(pickedPoint); moveSelectPoint = false; } else if(registerPoint && Pick<Point3f>(currentMousePosition.x(),gla->height()-currentMousePosition.y(),pickedPoint)) { /* qDebug("Found point for add %i %i -> %f %f %f", currentMousePosition.x(), currentMousePosition.y(), pickedPoint[0], pickedPoint[1], pickedPoint[2]); */ //find the normal of the face we just clicked CFaceO *face; bool result = GLPickTri<CMeshO>::PickNearestFace(currentMousePosition.x(),gla->height()-currentMousePosition.y(), mm.cm, face); if(!result){ qDebug() << "find nearest face failed!"; } else { CFaceO::NormalType faceNormal = face->N(); //qDebug() << "found face normal: " << faceNormal[0] << faceNormal[1] << faceNormal[2]; //if we didnt find a face then dont add the point because the user was probably //clicking on another mesh opened inside the glarea pickPointsDialog->addMoveSelectPoint(pickedPoint, faceNormal); } registerPoint = false; } drawPickedPoints(pickPointsDialog->getPickedPointTreeWidgetItemVector(), mm.cm.bbox, painter); } bool EditPickPointsPlugin::StartEdit(MeshModel &mm, GLArea *gla ) { //qDebug() << "StartEdit Pick Points: " << mm.fileName.c_str() << " ..." << mm.cm.fn; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) { if(NULL != pickPointsDialog) { pickPointsDialog->hide(); } //show message QMessageBox::warning(gla->window(), "Edit Pick Points", "Sorry, this mesh has no faces on which picked points can sit.", QMessageBox::Ok, QMessageBox::Ok); return false; } //get the cursor QCursor *cursor = QApplication::overrideCursor(); if(cursor) overrideCursorShape = cursor->shape(); else overrideCursorShape = Qt::ArrowCursor; //set this so redraw can use it glArea = gla; //Create GUI window if we dont already have one if(pickPointsDialog == 0) { pickPointsDialog = new PickPointsDialog(this, gla->window()); } currentModel = &mm; //set the current mesh pickPointsDialog->setCurrentMeshModel(&mm, gla); //show the dialog pickPointsDialog->show(); return true; } void EditPickPointsPlugin::EndEdit(MeshModel &mm, GLArea *gla) { //qDebug() << "EndEdit Pick Points: " << mm.fileName.c_str() << " ..." << mm.cm.fn; // some cleaning at the end. if(mm.cm.fn > 0) { assert(pickPointsDialog); //now that were are ending tell the dialog to save any points it has to metadata pickPointsDialog->savePointsToMetaData(); //remove the dialog from the screen pickPointsDialog->hide(); QApplication::setOverrideCursor( QCursor((Qt::CursorShape)overrideCursorShape) ); this->glArea = 0; } } void EditPickPointsPlugin::mousePressEvent(QMouseEvent *event, MeshModel &mm, GLArea *gla ) { //qDebug() << "mouse press Pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } if(Qt::RightButton == event->button() && pickPointsDialog->getMode() != PickPointsDialog::ADD_POINT){ currentMousePosition = event->pos(); pickPointsDialog->recordNextPointForUndo(); //set flag that we need to add a new point moveSelectPoint = true; } } void EditPickPointsPlugin::mouseMoveEvent(QMouseEvent *event, MeshModel &mm, GLArea *gla ) { //qDebug() << "mousemove pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } if(Qt::RightButton & event->buttons() && pickPointsDialog->getMode() != PickPointsDialog::ADD_POINT){ //qDebug() << "mouse move left button and move mode: "; currentMousePosition = event->pos(); //set flag that we need to add a new point registerPoint = true; } } void EditPickPointsPlugin::mouseReleaseEvent(QMouseEvent *event, MeshModel &mm, GLArea * gla) { //qDebug() << "mouseRelease Pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } //only add points for the left button if(Qt::RightButton == event->button()){ currentMousePosition = event->pos(); //set flag that we need to add a new point registerPoint = true; } } void EditPickPointsPlugin::drawPickedPoints( std::vector<PickedPointTreeWidgetItem*> &pointVector, vcg::Box3f &boundingBox, QPainter *painter) { assert(glArea); vcg::Point3f size = boundingBox.Dim(); //how we scale the object indicating the normal at each selected point float scaleFactor = (size[0]+size[1]+size[2])/90.0; //qDebug() << "scaleFactor: " << scaleFactor; glPushAttrib(GL_ALL_ATTRIB_BITS); // enable color tracking glEnable(GL_COLOR_MATERIAL); //draw the things that we always want to show, like the names glDepthFunc(GL_ALWAYS); glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); //set point attributes glPointSize(4.5); bool showNormal = pickPointsDialog->showNormal(); bool showPin = pickPointsDialog->drawNormalAsPin(); for(int i = 0; i < pointVector.size(); ++i) { PickedPointTreeWidgetItem * item = pointVector[i]; //if the point has been set (it may not be if a template has been loaded) if(item->isActive()){ Point3f point = item->getPoint(); glColor(Color4b::Blue); glLabel::render(painter,point, QString(item->getName())); //draw the dot if we arnt showing the normal or showing the normal as a line if(!showNormal || !showPin) { if(item->isSelected() ) glColor(Color4b::Green); glBegin(GL_POINTS); glVertex(point); glEnd(); } } } //now draw the things that we want drawn if they are not ocluded //we can see in bright red glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_MODELVIEW); Point3f yaxis; yaxis[0] = 0; yaxis[1] = 1; yaxis[2] = 0; for(int i = 0; i < pointVector.size(); ++i) { PickedPointTreeWidgetItem * item = pointVector[i]; //if the point has been set (it may not be if a template has been loaded) if(item->isActive()){ Point3f point = item->getPoint(); if(showNormal) { Point3f normal = item->getNormal(); if(showPin) { //dot product float angle = (Angle(normal,yaxis) * 180.0 / PI); //cross product Point3f axis = yaxis^normal; //qDebug() << "angle: " << angle << " x" << axis[0] << " y" << axis[1] << " z" << axis[2]; //bluegreen and a little clear glColor4f(0.0f, 1.0f, 0.0f, 0.7f); //glColor(Color4b::Green); glPushMatrix(); //move the pin to where it needs to be glTranslatef(point[0], point[1], point[2]); glRotatef(angle, axis[0], axis[1], axis[2]); glScalef(0.2*scaleFactor, 1.5*scaleFactor, 0.2*scaleFactor); glBegin(GL_TRIANGLES); //front glNormal3f(0, -1, 1); glVertex3f(0,0,0); glVertex3f(1,1,1); glVertex3f(-1,1,1); //right glNormal3f(1, -1, 0); glVertex3f(0,0,0); glVertex3f(1,1,-1); glVertex3f(1,1,1); //left glNormal3f(-1, -1, 0); glVertex3f(0,0,0); glVertex3f(-1,1,1); glVertex3f(-1,1,-1); //back glNormal3f(0, -1, -1); glVertex3f(0,0,0); glVertex3f(-1,1,-1); glVertex3f(1,1,-1); //top //if it is selected color it green if(item->isSelected() ) glColor4f(0.0f, 0.0f, 1.0f, 0.7f); glNormal3f(0, 1, 0); glVertex3f(1,1,1); glVertex3f(1,1,-1); glVertex3f(-1,1,-1); glNormal3f(0, 1, 0); glVertex3f(1,1,1); glVertex3f(-1,1,-1); glVertex3f(-1,1,1); //change back if(item->isSelected() ) glColor4f(0.0f, 1.0f, 0.0f, 0.7f); glEnd(); glPopMatrix(); } else { glColor(Color4b::Green); glBegin(GL_LINES); glVertex(point); glVertex(point+(normal*scaleFactor)); glEnd(); } } glColor(Color4b::Red); glArea->renderText(point[0], point[1], point[2], QString(item->getName()) ); } } glDisable(GL_BLEND); glDisable(GL_COLOR_MATERIAL); glDisable(GL_DEPTH_TEST); glPopAttrib(); }
guerrerocarlos/meshlab
src/plugins/edit_pickpoints/editpickpoints.cpp
C++
gpl-2.0
12,813
""" AUTHOR: Dr. Andrew David Burbanks, 2005. This software is Copyright (C) 2004-2008 Bristol University and is released under the GNU General Public License version 2. MODULE: SystemBath PURPOSE: Used to generate System Bath Hamiltonian, given number of bath modes. NOTES: The system defined by the Hamiltonian is (2n+2)-dimensional, and is ordered (s, p_s, x, p_x, y, p_y, ...). There is no need for Taylor expansion, as we have the Hamiltonian in explicit polynomial form. """ from math import * from random import * from Polynomial import * from LieAlgebra import LieAlgebra class SystemBath: """ The original (_not_ mass-weighted) system bath. The system-bath model represents a 'system' part: a symmetric quartic double-well potential, coupled to a number of 'bath modes': harmonic oscillators. The coupling is achieved via a bilinear coupling between the configuration space coordinate of the system and the conjugate momenta of each of the bath modes. The resulting Hamiltonian is a polynomial of degree 4 in the phase space coordinates. With this version, the client must specify all of the following:- @param n_bath_modes: (non-negative int). @param system_mass: (positive real). @param imag_harmonic_frequency_at_barrier: (real; imag part of pure imag). @param reciprocal_barrier_height_above_well_bottom: (positive real). @param bath_masses: (seq of n_bath_modes positive reals). @param bath_frequencies: (seq of n_bath_modes reals). @param bath_coupling_constants: (seq of n_bath_modes reals). """ def __init__(self, n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, bath_masses, bath_frequencies, bath_coupling_constants): assert n_bath_modes>=0 assert system_mass >= 0.0 assert abs(imag_harmonic_frequency_at_barrier) > 0.0 assert reciprocal_barrier_height_above_well_bottom >= 0.0 assert len(bath_masses) == n_bath_modes assert len(bath_frequencies) == n_bath_modes assert len(bath_coupling_constants) == n_bath_modes for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g self._m_s = system_mass #system mass self._omega_b = imag_harmonic_frequency_at_barrier self._v_0_sh = reciprocal_barrier_height_above_well_bottom self._n = n_bath_modes self._c = bath_coupling_constants #to the system s coordinate. self._w = bath_frequencies self._m = bath_masses self._lie = LieAlgebra(n_bath_modes+1) #$a = (-1/2)m_s\omega_b^2.$ self._a = -0.5*self._m_s*(self._omega_b**2) #$b = \frac{m_s^2\omega_b^4}{16V_0}.$ self._b = ((self._m_s**2) * (self._omega_b**4))/(16.0*self._v_0_sh) def lie_algebra(self): """ Return the Lie algebra on which the polynomials will be constructed. For N bath modes, this has (N+1)-dof. """ return self._lie def hamiltonian_real(self): """ Calculate the real Hamiltonian for the system-bath model. """ #Establish some convenient notation: n = self._n a = self._a b = self._b m_s = self._m_s c = self._c w = self._w m = self._m q_s = self._lie.q(0) p_s = self._lie.p(0) #Compute some constants: coeff_q_s = a for i in xrange(0, len(c)): coeff_q_s += (c[i]**2.0)/(2.0 * m[i] * (w[i]**2.0)) coeff_p_s = 1.0/(2.0 * m_s) coeff_q_bath = [] coeff_p_bath = [] for i in xrange(0, len(c)): coeff_q_bath.append(0.5 * m[i] * (w[i]**2.0)) coeff_p_bath.append(1.0/(2.0 * m[i])) #Sanity checks: assert n >= 0, 'Need zero or more bath modes.' assert len(c) == n, 'Need a coupling constant for each bath mode.' assert len(coeff_q_bath) == n, 'Need constant for each bath config.' assert len(coeff_p_bath) == n, 'Need constant for each bath momentum.' #System part: h_system = coeff_p_s * (p_s**2) h_system += coeff_q_s * (q_s**2) h_system += b * (q_s**4) #Bath part: h_bath = self._lie.zero() for i in xrange(len(c)): bath_dof = i+1 h_bath += coeff_q_bath[i] * (self._lie.q(bath_dof)**2) h_bath += coeff_p_bath[i] * (self._lie.p(bath_dof)**2) #Coupling part: h_coupling = self._lie.zero() for i, c_i in enumerate(c): bath_dof = i+1 h_coupling += -c_i * (self._lie.q(bath_dof) * q_s) #Complete Hamiltonian: h = h_system + h_bath + h_coupling #Sanity checks: assert h.degree() == 4 assert h.n_vars() == 2*n+2 assert len(h) == (3) + (2*n) + (n) #system+bath+coupling return h class MassWeightedSystemBath: """ The system-bath model represents a 'system' part (a symmetric quartic double-well potential) coupled to a number of 'bath modes' (harmonic oscillators). The coupling is achieved via a bilinear coupling between the configuration space coordinate of the system and the conjugate momenta of each of the bath modes. The resulting Hamiltonian is a polynomial of degree 4 in the phase space coordinates. """ def __init__(self, n_bath_modes, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, damping_strength, bath_cutoff_frequency, bath_masses, bath_frequencies, bath_compound_coupling_constants): """ Construct a mass-weighted system bath given the values of the parameters and the compound coupling constants. @param n_bath_modes: (non-negative int). @param imag_harmonic_frequency_at_barrier: (real; im part of pure im). @param reciprocal_barrier_height_above_well_bottom: (positive real). @param damping_strength: (real). @param bath_cutoff_frequency: (real, <<bath_frequencies[-1]). @param bath_masses: (seq of n_bath_modes positive reals). @param bath_frequencies: (increasing seq of n_bath_modes reals). @param bath_compound_coupling_constants: (seq of n_bath_modes reals). """ #check inputs assert n_bath_modes>=0 assert abs(imag_harmonic_frequency_at_barrier) > 0.0 assert reciprocal_barrier_height_above_well_bottom >= 0.0 assert len(bath_masses) == n_bath_modes assert len(bath_frequencies) == n_bath_modes assert len(bath_compound_coupling_constants) == n_bath_modes #ensure that the bath frequencies are increasing for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g #store member variables self._n = n_bath_modes self._omega_b = imag_harmonic_frequency_at_barrier self._v_0_sh = reciprocal_barrier_height_above_well_bottom self._eta = damping_strength self._omega_c = bath_cutoff_frequency self._c_star = bath_compound_coupling_constants #to system coord self._w = bath_omegas self._lie = LieAlgebra(n_bath_modes+1) def compute_compound_constants(n_bath_modes, damping_strength, bath_cutoff_frequency, bath_frequencies): """ Compute the compound coupling constants. @param n_bath_modes: (non-negative int). @param damping_strength: (real). @param bath_cutoff_frequency: (real, <<bath_frequencies[-1]). @param bath_frequencies: (seq of n_bath_modes reals increasing). @return: bath_compound_coupling_constants (seq of n_bath_modes reals). """ #check inputs assert n_bath_modes>=0 assert len(bath_frequencies) == n_bath_modes for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g assert bath_frequencies[-1] > bath_cutoff_frequency #accumulate compound frequencies c_star = [] omega_c = bath_cutoff_frequency eta = damping_strength for jm1, omega_j in enumerate(bath_frequencies): c = (-2.0/(pi*(jm1+1.0)))*eta*omega_c d = ((omega_j+omega_c)*exp(-omega_j/omega_c) - omega_c) c_star.append(c*d) return c_star compute_compound_constants = staticmethod(compute_compound_constants) def bath_spectral_density_function(self, omega): """ The bath is defined in terms of a continuous spectral density function, which has the Ohmic form with an exponential cutoff. For infinite bath cutoff frequency, $\omega_c$, the bath is strictly Ohmic, i.e., the friction kernel becomes a delta function in the time domain, and the classical dynamics of the system coordinate are described by the ordinary Langevin equation. In that case, $eta$ (the damping strength) is the classically measurable friction coefficient. However, for finite values of the bath cutoff frequency, the friction kernel is nonlocal, which introduces memory effects into the Generalized Langevin Equation (GLE). """ return self.eta * omega * exp(-omega/self._omega_c) def hamiltonian_real(self): """ Calculate the real Hamiltonian for the system-bath model. """ #establish some convenient notation: n = self._n w = self._w c_star = self._c_star #sanity checks: assert n >= 0, 'Need zero or more bath modes.' assert len(c_star) == n, 'Need a coupling constant for each bath mode.' #system coefficients: a = -0.5*(self._omega_b**2) b = (self._omega_b**4)/(16.0*self._v_0_sh) coeff_q_s = a for i in xrange(0, len(c_star)): coeff_q_s += c_star[i]/(2.0 * (w[i])) coeff_p_s = 1.0/2.0 #system part: q_s = self._lie.q(0) p_s = self._lie.p(0) h_system = coeff_p_s * (p_s**2) h_system += coeff_q_s * (q_s**2) h_system += b * (q_s**4) #bath coefficients: coeff_q_bath = [] coeff_p_bath = [] for i in xrange(0, len(c_star)): coeff_q_bath.append(0.5 * (w[i]**2.0)) coeff_p_bath.append(1.0/2.0) #sanity checks: assert len(coeff_q_bath) == n, 'Need constant for each bath config.' assert len(coeff_p_bath) == n, 'Need constant for each bath momentum.' #bath part: h_bath = self._lie.zero() for i in xrange(len(c_star)): bath_dof = i+1 h_bath += coeff_q_bath[i] * (self._lie.q(bath_dof)**2) h_bath += coeff_p_bath[i] * (self._lie.p(bath_dof)**2) #coupling part: h_coupling = self._lie.zero() for i, c_i in enumerate(c_star): bath_dof = i+1 h_coupling += -sqrt(c_i*w[i]) * (self._lie.q(bath_dof)*q_s) #complete Hamiltonian: h = h_system + h_bath + h_coupling #sanity checks: assert h.degree() == 4 assert h.n_vars() == 2*n+2 assert len(h) == (3) + (2*n) + (n) #system+bath+coupling return h def new_random_system_bath(n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, random_seed): #check inputs assert n_bath_modes >= 0 assert system_mass >= 0.0 #unitialize random number generator seed(random_seed) #generate parameters bath_masses = [] bath_omegas = [] bath_coupling_constants = [] for i in xrange(0, n_bath_modes): bath_coupling_constants.append(uniform(0.001, 0.5)) bath_masses.append(uniform(0.5, 3.6)) bath_omegas.append(gauss(0.0, 2.0)) #sort frequencies into increasing order bath_omegas.sort() #instantiate the system bath sb = SystemBath(n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, bath_masses, bath_omegas, bath_coupling_constants) return sb
Peter-Collins/NormalForm
src/py/SystemBath.py
Python
gpl-2.0
12,748
package by.falc0n.util; /** * Contains a set of extension methods and constants to operate with arrays * (primitive and object). * * @author falc0n * @version 1.0 * */ public final class ArrayExt { /** * An empty {@code byte} array. * * @since 1.0 */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * An empty {@code short} array. * * @since 1.0 */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** * An empty {@code int} array. * * @since 1.0 */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** * An empty {@code long} array. * * @since 1.0 */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * An empty {@code float} array. * * @since 1.0 */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** * An empty {@code double} array. * * @since 1.0 */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** * An empty {@code char} array. * * @since 1.0 */ public static final char[] EMPTY_CHAR_ARRAY = new char[0]; /** * An empty {@code boolean} array. * * @since 1.0 */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * An empty {@link Byte} array. * * @since 1.0 */ public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0]; /** * An empty {@link Short} array. * * @since 1.0 */ public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0]; /** * An empty {@link Integer} array. * * @since 1.0 */ public static final Integer[] EMPTY_INT_OBJECT_ARRAY = new Integer[0]; /** * An empty {@link Long} array. * * @since 1.0 */ public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; /** * An empty {@link Float} array. * * @since 1.0 */ public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0]; /** * An empty {@link Double} array. * * @since 1.0 */ public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0]; /** * An empty {@link Character} array. * * @since 1.0 */ public static final Character[] EMPTY_CHAR_OBJECT_ARRAY = new Character[0]; /** * An empty {@link Boolean} array. * * @since 1.0 */ public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0]; /** * An empty object array. * * @since 1.0 */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * Checks whether the {@code byte} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(byte[] array, byte value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code short} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(short[] array, short value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code int} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(int[] array, int value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code long} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(long[] array, long value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code float} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(float[] array, float value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code double} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(double[] array, double value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code char} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(char[] array, char value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code boolean} array contains the specified value. * The array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(boolean[] array, boolean value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the object array contains the specified value. "Contains" * means that the array has an element which equals (see * {@link #equals(Object)} ) to the value or they're both {@code null}. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(Object[] array, Object value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (ObjectExt.equalOrNull(array[i], value)) { result = true; break; } } return result; } /** * Converts the {@code byte} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Byte[] toObjectArray(byte[] array) { Byte[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Byte[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_BYTE_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code short} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Short[] toObjectArray(short[] array) { Short[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Short[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_SHORT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code int} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Integer[] toObjectArray(int[] array) { Integer[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Integer[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_INT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code long} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Long[] toObjectArray(long[] array) { Long[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Long[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_LONG_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code float} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Float[] toObjectArray(float[] array) { Float[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Float[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_FLOAT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code double} array to an array of corresponding objects. * If the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Double[] toObjectArray(double[] array) { Double[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Double[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_DOUBLE_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code char} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Character[] toObjectArray(char[] array) { Character[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Character[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_CHAR_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code boolean} array to an array of corresponding objects. * If the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Boolean[] toObjectArray(boolean[] array) { Boolean[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_BOOLEAN_OBJECT_ARRAY; } } return objArray; } public static final byte[] toPrimitiveArray(Byte[] array) { byte[] primArray = null; if (array != null) { if (array.length > 0) { primArray = new byte[array.length]; for (int i = 0; i < array.length; i++) { primArray[i] = array[i]; } } else { primArray = EMPTY_BYTE_ARRAY; } } return primArray; } public static final byte[] toPrimitiveArray(Byte[] array, byte nullValue) { byte[] primArray = null; if (array != null) { if (array.length > 0) { primArray = new byte[array.length]; for (int i = 0; i < array.length; i++) { primArray[i] = (array[i] != null) ? array[i] : nullValue; } } else { primArray = EMPTY_BYTE_ARRAY; } } return primArray; } private ArrayExt() { super(); } }
fa1con/falc0n-utils
src/main/java/by/falc0n/util/ArrayExt.java
Java
gpl-2.0
13,659
<?php /** * @package CrowdfundingPartners * @subpackage Files * @author Todor Iliev * @copyright Copyright (C) 2015 Todor Iliev <todor@itprism.com>. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL */ namespace CrowdfundingPartners; use Prism\Database\ArrayObject; use Joomla\Utilities\ArrayHelper; defined('JPATH_PLATFORM') or die; /** * This class provides functionality that manage partners. * * @package CrowdfundingPartners * @subpackage Parnters */ class Partners extends ArrayObject { /** * Load partners data by ID from database. * * <code> * $ids = array(1,2,3,4,5); * * $partners = new CrowdfundingPartners\Partners(JFactory::getDbo()); * $partners->load($ids); * * foreach($partners as $partner) { * echo $partners["name"]; * echo $partners["partner_id"]; * } * </code> * * @param int $projectId * @param array $ids */ public function load($projectId = 0, $ids = array()) { // Load project data $query = $this->db->getQuery(true); $query ->select("a.id, a.name, a.project_id, a.partner_id") ->from($this->db->quoteName("#__cfpartners_partners", "a")); if (!empty($ids)) { ArrayHelper::toInteger($ids); $query->where("a.id IN ( " . implode(",", $ids) . " )"); } if (!empty($projectId)) { $query->where("a.project_id = " . (int)$projectId); } $this->db->setQuery($query); $results = $this->db->loadAssocList(); if (!$results) { $results = array(); } $this->items = $results; } /** * Add a new value to the array. * * <code> * $partner = array( * "name" => "John Dow", * "project_id" => 1, * "partner_id" => 2 * ); * * $partners = new CrowdfundingPartners\Partners(); * $partners->add($partner); * </code> * * @param array $value * @param null|int $index * * @return $this */ public function add($value, $index = null) { if (!is_null($index)) { $this->items[$index] = $value; } else { $this->items[] = $value; } return $this; } }
Creativetech-Solutions/joomla-easysocial-network
libraries/CrowdfundingPartners/Partners.php
PHP
gpl-2.0
2,368
<?php get_header(); ?> <div id="content" class="clearfix row"> <div class="row centered"> <div class="brandhead"> <h1 class="">News and Articles</h1> <p class="lead">A partnership to deliver high quality, efficient patient care for South Yorkshire, Mid Yorkshire and North Derbyshire</p> </div> </div> <div id="main" class="col-sm-8 clearfix" role="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article"> <header> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'wpbs-featured' ); ?></a> <div class="article-header"><h1 class="h2"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1></div> <p class="meta"><?php _e("Posted", "wpbootstrap"); ?> <time datetime="<?php echo the_time('Y-m-j'); ?>" pubdate><?php the_time(); ?></time> <?php _e("by", "wpbootstrap"); ?> <?php the_author_posts_link(); ?> <span class="amp">&</span> <?php _e("filed under", "wpbootstrap"); ?> <?php the_category(', '); ?>.</p> </header> <!-- end article header --> <section class="post_content clearfix"> <?php the_content( __("Read more &raquo;","wpbootstrap") ); ?> </section> <!-- end article section --> <footer> <p class="tags"><?php the_tags('<span class="tags-title">' . __("Tags","wpbootstrap") . ':</span> ', ' ', ''); ?></p> </footer> <!-- end article footer --> </article> <!-- end article --> <?php endwhile; ?> <?php if (function_exists('page_navi')) { // if expirimental feature is active ?> <?php page_navi(); // use the page navi function ?> <?php } else { // if it is disabled, display regular wp prev & next links ?> <nav class="wp-prev-next"> <ul class="pager"> <li class="previous"><?php next_posts_link(_e('&laquo; Older Entries', "wpbootstrap")) ?></li> <li class="next"><?php previous_posts_link(_e('Newer Entries &raquo;', "wpbootstrap")) ?></li> </ul> </nav> <?php } ?> <?php else : ?> <article id="post-not-found"> <header> <h1><?php _e("Not Found", "wpbootstrap"); ?></h1> </header> <section class="post_content"> <p><?php _e("Sorry, but the requested resource was not found on this site.", "wpbootstrap"); ?></p> </section> <footer> </footer> </article> <?php endif; ?> </div> <!-- end #main --> <?php get_sidebar(); // sidebar 1 ?> </div> <!-- end #content --> <?php get_footer(); ?>
gitpress/together
wp-content/themes/wordpress-bootstrap-master/index.php
PHP
gpl-2.0
2,891
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\IFD0; use PHPExiftool\Driver\AbstractTag; class Copyright extends AbstractTag { protected $Id = 33432; protected $Name = 'Copyright'; protected $FullName = 'Exif::Main'; protected $GroupName = 'IFD0'; protected $g0 = 'EXIF'; protected $g1 = 'IFD0'; protected $g2 = 'Image'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Copyright'; protected $local_g2 = 'Author'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/IFD0/Copyright.php
PHP
gpl-2.0
724
<?php /** * The template for displaying search results pages. * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result * * @package Brushy Hill Cottage */ get_header(); ?> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'brushy-hill-cottage' ), '<span>' . get_search_query() . '</span>' ); ?></h1> </header><!-- .page-header --> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /** * Run the loop for the search to output the results. * If you want to overload this in a child theme then include a file * called content-search.php and that will be used instead. */ get_template_part( 'template-parts/content', 'search' ); ?> <?php endwhile; ?> <?php the_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'template-parts/content', 'none' ); ?> <?php endif; ?> </main><!-- #main --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
bpriddy/brushyhillcottage
wp-content/themes/brushy-hill-cottage/search.php
PHP
gpl-2.0
1,206
package com.badday.ss.blocks; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; import com.badday.ss.SS; import com.badday.ss.SSConfig; import com.badday.ss.api.IGasNetwork; import com.badday.ss.api.IGasNetworkElement; import com.badday.ss.api.IGasNetworkVent; import com.badday.ss.core.atmos.GasUtils; import com.badday.ss.core.utils.BlockVec3; import com.badday.ss.events.RebuildNetworkPoint; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * * @author KolesnikovAK * * Seal gases on bay * */ public class SSBlockAirVent extends BlockContainer implements IGasNetworkElement { private IIcon[] iconBuffer; //private int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_SIDE_ACTIVATED = 2; private int ICON_SIDE = 0, ICON_SIDE_FRONT = 1, ICON_SIDE_BACK = 2, ICON_SIDE_FRONTON=3; public SSBlockAirVent(String assetName) { super(Material.rock); this.setResistance(1000.0F); this.setHardness(330.0F); this.setBlockTextureName(SS.ASSET_PREFIX + assetName); this.setBlockName(assetName); this.setBlockUnbreakable(); this.setStepSound(soundTypeMetal); this.setCreativeTab(SS.ssTab); disableStats(); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister) { iconBuffer = new IIcon[4]; //iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("ss:airgenSideInactive"); //iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("ss:contBottom"); //iconBuffer[ICON_SIDE_ACTIVATED] = par1IconRegister.registerIcon("ss:airgenSideActive"); iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("ss:blockGasVentSide"); iconBuffer[ICON_SIDE_FRONT] = par1IconRegister.registerIcon("ss:blockGasVentFront"); iconBuffer[ICON_SIDE_BACK] = par1IconRegister.registerIcon("ss:blockGasVentBack"); iconBuffer[ICON_SIDE_FRONTON] = par1IconRegister.registerIcon("ss:blockGasVentFrontOn"); } @SideOnly(Side.CLIENT) @Override public IIcon getIcon(int side, int metadata) { if (side == 1) { if (metadata == 0) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 1) { return iconBuffer[ICON_SIDE_FRONT]; } else if (metadata == 2) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 3) { return iconBuffer[ICON_SIDE_FRONTON]; } } if (side == 0) { if (metadata == 0) { return iconBuffer[ICON_SIDE_FRONT]; } else if (metadata == 1) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 2) { return iconBuffer[ICON_SIDE_FRONTON]; } else if (metadata == 3) { return iconBuffer[ICON_SIDE_BACK]; } } return iconBuffer[ICON_SIDE]; } /** * Overridden by {@link #createTileEntity(World, int)} */ @Override public TileEntity createNewTileEntity(World w, int i) { return null; } @Override public TileEntity createTileEntity(World world, int meta) { return new SSTileEntityAirVent(); } /** * Returns the quantity of items to drop on block destruction. */ @Override public int quantityDropped(Random par1Random) { return 0; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int side, float a, float b, float c) { if (world.isRemote) return true; if (entityplayer.getCurrentEquippedItem() != null) { String itemName = entityplayer.getCurrentEquippedItem().getUnlocalizedName(); if (itemName.equals("item.ss.multitool")) { TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof SSTileEntityAirVent) { IGasNetwork net = ((SSTileEntityAirVent) tileEntity).getGasNetwork(); if (SS.Debug) { ((SSTileEntityAirVent) tileEntity).printDebugInfo(); } } } else if (itemName.equals("ic2.itemToolWrenchElectric") || itemName.equals("item.thermalexpansion.tool.wrench")) { // Rotate AirVent int oldMeta = world.getBlockMetadata(x, y, z); int oldSide = oldMeta & 1; if (side != oldSide && side >= 0 && side < 2) { if (side == 0 && side != oldSide) { world.setBlockMetadataWithNotify(x, y, z, oldMeta & 2, 3); // old meta 1 or 3 -> 0 or 2 entityplayer.getCurrentEquippedItem().damageItem(1, entityplayer); TileEntity tileEntity = world.getTileEntity(x, y, z); ((IGasNetworkVent) tileEntity).getGasNetwork().removeVent((IGasNetworkVent) tileEntity); // Rebuild new network on UP from Vent if (SS.Debug) System.out.println("Try to rebild on UP"); if (world.getBlock(x, y+1, z) == SSConfig.ssBlockGasPipe || world.getBlock(x, y+1, z) == SSConfig.ssBlockGasPipeCasing) { GasUtils.registeredEventRebuildGasNetwork(new RebuildNetworkPoint(world,new BlockVec3(x,y+1,z))); } } else if (side == 1 && side != oldSide) { world.setBlockMetadataWithNotify(x, y, z, oldMeta | 1, 3); // old meta 0 or 2 -> 1 or 3 entityplayer.getCurrentEquippedItem().damageItem(1, entityplayer); TileEntity tileEntity = world.getTileEntity(x, y, z); ((IGasNetworkVent) tileEntity).getGasNetwork().removeVent((IGasNetworkVent) tileEntity); // Rebuild new network on DOWN from Vent if (SS.Debug) System.out.println("Try to rebild on DOWN"); if (world.getBlock(x, y-1, z) == SSConfig.ssBlockGasPipe || world.getBlock(x, y-1, z) == SSConfig.ssBlockGasPipeCasing) { GasUtils.registeredEventRebuildGasNetwork(new RebuildNetworkPoint(world,new BlockVec3(x,y-1,z))); } } } } } return true; } @Override public void breakBlock(World par1World, int par2, int par3, int par4, Block par5, int par6) { TileEntity te = par1World.getTileEntity(par2, par3, par4); if (te != null) { te.invalidate(); } super.breakBlock(par1World, par2, par3, par4, par5, par6); } }
Tankistodor/SSAraminta
src/main/java/com/badday/ss/blocks/SSBlockAirVent.java
Java
gpl-2.0
6,252
Almadeladanza::Application.routes.draw do devise_for :users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) mount ActiveAdmin::Tinymce::Engine => '/', as: 'admin_editor' root to: "news#index" resources :dance_styles, only: [:index, :show] resources :lessons, only: [:index, :show] resources :interior_images, only: [:index] resources :news, only: [:index, :show] resources :gallery_events, only: [:index] resources :about, only: [:index] resources :contacts, only: [:index] resources :feedback, only: [:index] resources :coaches, only: [:index, :show] resources :posts, only: [:index, :show] resources :clients, only: [:create] # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
KernelCorp/almadeladanza
config/routes.rb
Ruby
gpl-2.0
2,432
using System; using System.Collections.Generic; using System.Linq; using Server.Engines.PartySystem; using Server.Items; using Server.Spells.Fourth; using Server.Spells.Necromancy; using Server.Targeting; namespace Server.Spells.Mysticism { public class CleansingWindsSpell : MysticSpell { public override SpellCircle Circle { get { return SpellCircle.Sixth; } } private static SpellInfo m_Info = new SpellInfo( "Cleansing Winds", "In Vas Mani Hur", 230, 9022, Reagent.Garlic, Reagent.Ginseng, Reagent.MandrakeRoot, Reagent.DragonBlood ); public CleansingWindsSpell(Mobile caster, Item scroll) : base(caster, scroll, m_Info) { } public override void OnCast() { Caster.Target = new MysticSpellTarget(this, TargetFlags.Beneficial); } public override void OnTarget(object o) { var targeted = o as Mobile; if (targeted == null) return; if (CheckBSequence(targeted)) { /* Soothing winds attempt to neutralize poisons, lift curses, and heal a valid * Target. The Caster's Mysticism and either Focus or Imbuing (whichever is * greater) skills determine the effectiveness of the Cleansing Winds. */ Caster.PlaySound(0x64C); var targets = new List<Mobile> {targeted}; targets.AddRange(FindAdditionalTargets(targeted).Take(3)); // This effect can hit up to 3 additional players beyond the primary target. double primarySkill = Caster.Skills[CastSkill].Value; double secondarySkill = Caster.Skills[DamageSkill].Value; var toHeal = (int)((primarySkill + secondarySkill) / 4.0) + Utility.RandomMinMax(-3, 3); toHeal /= targets.Count; // The effectiveness of the spell is reduced by the number of targets affected. foreach (var target in targets) { // WARNING: This spell will flag the caster as a criminal if a criminal or murderer party member is close enough // to the target to receive the benefits from the area of effect. Caster.DoBeneficial(target); PlayEffect(target); int toHealMod = toHeal; if (target.Poisoned) { int poisonLevel = target.Poison.RealLevel + 1; int chanceToCure = (10000 + (int)((primarySkill + secondarySkill) / 2 * 75) - (poisonLevel * 1750)) / 100; if (chanceToCure > Utility.Random(100) && target.CurePoison(Caster)) { // Poison reduces healing factor by 15% per level of poison. toHealMod -= (int)(toHeal * poisonLevel * 0.15); } else { // If the cure fails, the target will not be healed. toHealMod = 0; } } // Cleansing Winds will not heal the target after removing mortal wound. if (MortalStrike.IsWounded(target)) { MortalStrike.EndWound(target); toHealMod = 0; } var curseLevel = RemoveCurses(target); if (toHealMod > 0 && curseLevel > 0) { // Each Curse reduces healing by 3 points + 1% per curse level. int toHealMod1 = toHealMod - (curseLevel * 3); int toHealMod2 = toHealMod - (int)(toHealMod * (curseLevel / 100.0)); toHealMod -= toHealMod1 + toHealMod2; } if (toHealMod > 0) SpellHelper.Heal(toHealMod, target, Caster); } } FinishSequence(); } private static void PlayEffect(Mobile m) { m.FixedParticles(0x3709, 1, 30, 9963, 13, 3, EffectLayer.Head); var from = new Entity(Serial.Zero, new Point3D(m.X, m.Y, m.Z - 10), m.Map); var to = new Entity(Serial.Zero, new Point3D(m.X, m.Y, m.Z + 50), m.Map); Effects.SendMovingParticles(from, to, 0x2255, 1, 0, false, false, 13, 3, 9501, 1, 0, EffectLayer.Head, 0x100); } private IEnumerable<Mobile> FindAdditionalTargets(Mobile targeted) { var casterParty = Party.Get(Caster); if (casterParty == null) yield break; foreach (var m in Caster.Map.GetMobilesInRange(new Point3D(targeted), 2)) { if (m == null || m == targeted) continue; // Players in the area must be in the casters party in order to receive the beneficial effects of the spell. if (Caster.CanBeBeneficial(m, false) && casterParty.Contains(m)) yield return m; } } private static int RemoveCurses(Mobile m) { int curseLevel = 0; if (SleepSpell.IsUnderSleepEffects(m)) { SleepSpell.EndSleep(m); curseLevel += 2; } if (EvilOmenSpell.TryEndEffect(m)) { curseLevel += 1; } if (StrangleSpell.RemoveCurse(m)) { curseLevel += 2; } if (CorpseSkinSpell.RemoveCurse(m)) { curseLevel += 3; } if (CurseSpell.UnderEffect(m)) { CurseSpell.RemoveEffect(m); curseLevel += 4; } if (BloodOathSpell.RemoveCurse(m)) { curseLevel += 3; } if (MindRotSpell.HasMindRotScalar(m)) { MindRotSpell.ClearMindRotScalar(m); curseLevel += 2; } if (SpellPlagueSpell.HasSpellPlague(m)) { SpellPlagueSpell.RemoveFromList(m); curseLevel += 4; } if (m.GetStatMod("[Magic] Str Curse") != null) { m.RemoveStatMod("[Magic] Str Curse"); curseLevel += 1; } if (m.GetStatMod("[Magic] Dex Curse") != null) { m.RemoveStatMod("[Magic] Dex Curse"); curseLevel += 1; } if (m.GetStatMod("[Magic] Int Curse") != null) { m.RemoveStatMod("[Magic] Int Curse"); curseLevel += 1; } BuffInfo.RemoveBuff(m, BuffIcon.Clumsy); BuffInfo.RemoveBuff(m, BuffIcon.FeebleMind); BuffInfo.RemoveBuff(m, BuffIcon.Weaken); BuffInfo.RemoveBuff(m, BuffIcon.Curse); BuffInfo.RemoveBuff(m, BuffIcon.MassCurse); BuffInfo.RemoveBuff(m, BuffIcon.MortalStrike); BuffInfo.RemoveBuff(m, BuffIcon.Mindrot); BuffInfo.RemoveBuff(m, BuffIcon.CorpseSkin); BuffInfo.RemoveBuff(m, BuffIcon.Strangle); BuffInfo.RemoveBuff(m, BuffIcon.EvilOmen); return curseLevel; } } }
SirGrizzlyBear/ServUOGrizzly
Scripts/Spells/Mysticism/SpellDefinitions/CleansingWindsSpell.cs
C#
gpl-2.0
7,614
/* * Copyright (c) 2011, Intel Corporation. * * 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. */ #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include "kernelAPI.h" #include "globals.h" #define FILENAME_FLAGS (O_RDWR | O_TRUNC | O_CREAT) #define FILENAME_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH) KernelAPI::KernelAPI() { } KernelAPI::~KernelAPI() { } uint8_t * KernelAPI::mmap(size_t bufLength, uint16_t bufID, MmapRegion region) { int prot = PROT_READ; if (region >= MMAPREGION_FENCE) throw FrmwkEx(HERE, "Detected illegal region = %d", region); if (region == MMR_META) prot |= PROT_WRITE; off_t encodeOffset = bufID; encodeOffset |= ((off_t)region << METADATA_UNIQUE_ID_BITS); encodeOffset *= sysconf(_SC_PAGESIZE); return (uint8_t *)::mmap(0, bufLength, prot, MAP_SHARED, gDutFd, encodeOffset); } void KernelAPI::munmap(uint8_t *memPtr, size_t bufLength) { ::munmap(memPtr, bufLength); } void KernelAPI::DumpKernelMetrics(DumpFilename filename) { int rc; struct nvme_file dumpMe = { (short unsigned int)filename.length(), filename.c_str() }; LOG_NRM("Dump dnvme metrics to filename: %s", filename.c_str()); if ((rc = ioctl(gDutFd, NVME_IOCTL_DUMP_METRICS, &dumpMe)) < 0) throw FrmwkEx(HERE, "Unable to dump dnvme metrics, err code = %d", rc); } void KernelAPI::DumpCtrlrSpaceRegs(DumpFilename filename, bool verbose) { int fd; string work; uint64_t value = 0; string outFile; const CtlSpcType *ctlMetrics = gRegisters->GetCtlMetrics(); LOG_NRM("Dump ctrlr regs to filename: %s", filename.c_str()); if ((fd = open(filename.c_str(), FILENAME_FLAGS, FILENAME_MODE)) == -1) throw FrmwkEx(HERE, "file=%s: %s", filename.c_str(), strerror(errno)); // Read all registers in ctrlr space for (int i = 0; i < CTLSPC_FENCE; i++) { if (!gRegisters->ValidSpecRev(ctlMetrics[i].specRev)) continue; if (ctlMetrics[i].size > MAX_SUPPORTED_REG_SIZE) { uint8_t *buffer; buffer = new uint8_t[ctlMetrics[i].size]; if (gRegisters->Read(NVMEIO_BAR01, ctlMetrics[i].size, ctlMetrics[i].offset, buffer, verbose) == false) { goto ERROR_OUT; } else { string work = " "; work += gRegisters->FormatRegister(NVMEIO_BAR01, ctlMetrics[i].size, ctlMetrics[i].offset, buffer); work += "\n"; write(fd, work.c_str(), work.size()); } delete [] buffer; } else if (gRegisters->Read((CtlSpc)i, value, verbose) == false) { break; } else { work = " "; // indent reg values within each capability work += gRegisters->FormatRegister(ctlMetrics[i].size, ctlMetrics[i].desc, value); work += "\n"; write(fd, work.c_str(), work.size()); } } close(fd); return; ERROR_OUT: close(fd); throw FrmwkEx(HERE); } void KernelAPI::DumpPciSpaceRegs(DumpFilename filename, bool verbose) { int fd; string work; uint64_t value; const PciSpcType *pciMetrics = gRegisters->GetPciMetrics(); const vector<PciCapabilities> *pciCap = gRegisters->GetPciCapabilities(); LOG_NRM("Dump PCI regs to filename: %s", filename.c_str()); if ((fd = open(filename.c_str(), FILENAME_FLAGS, FILENAME_MODE)) == -1) throw FrmwkEx(HERE, "file=%s: %s", filename.c_str(), strerror(errno)); // Traverse the PCI header registers work = "PCI header registers\n"; write(fd, work.c_str(), work.size()); for (int j = 0; j < PCISPC_FENCE; j++) { if (!gRegisters->ValidSpecRev(pciMetrics[j].specRev)) continue; // All PCI hdr regs don't have an associated capability if (pciMetrics[j].cap == PCICAP_FENCE) { if (gRegisters->Read((PciSpc)j, value, verbose) == false) goto ERROR_OUT; RegToFile(fd, pciMetrics[j], value); } } // Traverse all discovered capabilities for (size_t i = 0; i < pciCap->size(); i++) { switch (pciCap->at(i)) { case PCICAP_PMCAP: work = "Capabilities: PMCAP: PCI power management\n"; break; case PCICAP_MSICAP: work = "Capabilities: MSICAP: Message signaled interrupt\n"; break; case PCICAP_MSIXCAP: work = "Capabilities: MSIXCAP: Message signaled interrupt ext'd\n"; break; case PCICAP_PXCAP: work = "Capabilities: PXCAP: Message signaled interrupt\n"; break; case PCICAP_AERCAP: work = "Capabilities: AERCAP: Advanced Error Reporting\n"; break; default: LOG_ERR("PCI space reporting an unknown capability: %d\n", pciCap->at(i)); goto ERROR_OUT; } write(fd, work.c_str(), work.size()); // Read all registers assoc with the discovered capability for (int j = 0; j < PCISPC_FENCE; j++) { if (!gRegisters->ValidSpecRev(pciMetrics[j].specRev)) continue; if (pciCap->at(i) == pciMetrics[j].cap) { if (pciMetrics[j].size > MAX_SUPPORTED_REG_SIZE) { bool err = false; uint8_t *buffer; buffer = new uint8_t[pciMetrics[j].size]; if (gRegisters->Read(NVMEIO_PCI_HDR, pciMetrics[j].size, pciMetrics[j].offset, buffer, verbose) == false) { err = true; } else { string work = " "; work += gRegisters->FormatRegister(NVMEIO_PCI_HDR, pciMetrics[j].size, pciMetrics[j].offset, buffer); work += "\n"; write(fd, work.c_str(), work.size()); } delete [] buffer; if (err) goto ERROR_OUT; } else if (gRegisters->Read((PciSpc)j, value, verbose) == false) { goto ERROR_OUT; } else { RegToFile(fd, pciMetrics[j], value); } } } } close(fd); return; ERROR_OUT: close(fd); throw FrmwkEx(HERE); } void KernelAPI::RegToFile(int fd, const PciSpcType regMetrics, uint64_t value) { string work = " "; // indent reg values within each capability work += gRegisters->FormatRegister(regMetrics.size, regMetrics.desc, value); work += "\n"; write(fd, work.c_str(), work.size()); } void KernelAPI::LogCQMetrics(struct nvme_gen_cq &cqMetrics) { LOG_NRM("CQMetrics.q_id = 0x%04X", cqMetrics.q_id); LOG_NRM("CQMetrics.tail_ptr = 0x%04X", cqMetrics.tail_ptr); LOG_NRM("CQMetrics.head_ptr = 0x%04X", cqMetrics.head_ptr); LOG_NRM("CQMetrics.elements = 0x%04X", cqMetrics.elements); LOG_NRM("CQMetrics.irq_enabled = %s", cqMetrics.irq_enabled ? "T" : "F"); LOG_NRM("CQMetrics.irq_no = %d", cqMetrics.irq_no); LOG_NRM("CQMetrics.pbit_new_entry = %d", cqMetrics.pbit_new_entry); } void KernelAPI::LogSQMetrics(struct nvme_gen_sq &sqMetrics) { LOG_NRM("SQMetrics.sq_id = 0x%04X", sqMetrics.sq_id); LOG_NRM("SQMetrics.cq_id = 0x%04X", sqMetrics.cq_id); LOG_NRM("SQMetrics.tail_ptr = 0x%04X", sqMetrics.tail_ptr); LOG_NRM("SQMetrics.tail_ptr_virt = 0x%04X", sqMetrics.tail_ptr_virt); LOG_NRM("SQMetrics.head_ptr = 0x%04X", sqMetrics.head_ptr); LOG_NRM("SQMetrics.elements = 0x%04X", sqMetrics.elements); } void KernelAPI::WriteToDnvmeLog(string log) { int rc; struct nvme_logstr logMe = { (short unsigned int)log.length(), log.c_str() }; LOG_NRM("Write custom string to dnvme's log output: \"%s\"", log.c_str()); if ((rc = ioctl(gDutFd, NVME_IOCTL_MARK_SYSLOG, &logMe)) < 0) { throw FrmwkEx(HERE, "Unable to log custom string to dnvme, err = %d", rc); } }
junqiang521/Test
dnvme/tnvme-master/Utils/kernelAPI.cpp
C++
gpl-2.0
8,831
import csv import logging from fa.miner import yahoo from fa.piping import csv_string_to_records from fa.util import partition from fa.database.query import get_outdated_symbols, update_fundamentals import initialize from settings import * """ Download data from internet to database """ initialize.init() logger = logging.getLogger(__name__) logger.info("Will update historical prices of all symbols not up to date on {0}.".format(end_date)) all_symbols = [s.symbol for s in get_outdated_symbols("price", end_date)] # do the download in chunks of size 8 to prevent overloading servers for symbols in partition(all_symbols, 8): data = yahoo.get_historical_data(symbols, start_date, end_date) for symbol, csv_string in data.items(): if csv_string: try: records = csv_string_to_records(symbol, csv_string, strict=True) update_fundamentals("price", symbol, records, end_date, delete_old=True) except csv.Error as e: logger.exception(e) logger.error("csv of {0} is malformed.".format(symbol)) else: logger.warning("Could not find updated historical prices of {0}. Skip.".format(symbol)) logger.info("Finished updating historical prices.")
kakarukeys/algo-fa
examples/update_price_data.py
Python
gpl-2.0
1,268
<?php /** * @version $Id: frontpage.class.php,v 1.1 2005/07/22 01:54:45 eddieajau Exp $ * @package Mambo * @subpackage Content * @copyright (C) 2000 - 2005 Miro International Pty Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * Mambo is Free Software */ /** ensure this file is being included by a parent file */ defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * @package Mambo * @subpackage Content */ class mosFrontPage extends mosDBTable { /** @var int Primary key */ var $content_id=null; /** @var int */ var $ordering=null; /** * @param database A database connector object */ function mosFrontPage( &$db ) { $this->mosDBTable( '#__content_frontpage', 'content_id', $db ); } } ?>
wuts/earthquake
components/com_frontpage/frontpage.class.php
PHP
gpl-2.0
752
/* * Copyright (c) 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. */ /** * JDK-8050964: OptimisticTypesPersistence.java should use java.util.Date instead of java.sql.Date * * Make sure that nashorn.jar has only 'compact1' dependency. * * @test * @option -scripting * @run */ // assume that this script is run with "nashorn.jar" System // property set to relative path of nashorn.jar from the current // directory of test execution. if (typeof fail != 'function') { fail = print; } var System = java.lang.System; var File = java.io.File; var nashornJar = new File(System.getProperty("nashorn.jar")); if (! nashornJar.isAbsolute()) { nashornJar = new File(".", nashornJar); } var javahome = System.getProperty("java.home"); var jdepsPath = javahome + "/../bin/jdeps".replaceAll(/\//g, File.separater); // run jdep on nashorn.jar - only summary but print profile info `${jdepsPath} -s -P ${nashornJar.absolutePath}` // check for "(compact1)" in output from jdep tool if (! /(compact1)/.test($OUT)) { fail("non-compact1 dependency: " + $OUT); }
koutheir/incinerator-hotspot
nashorn/test/script/nosecurity/JDK-8050964.js
JavaScript
gpl-2.0
2,050
from infoshopkeeper_config import configuration cfg = configuration() dbtype = cfg.get("dbtype") dbname = cfg.get("dbname") dbhost = cfg.get("dbhost") dbuser = cfg.get("dbuser") dbpass = cfg.get("dbpass") from sqlobject import * if dbtype in ('mysql', 'postgres'): if dbtype is 'mysql': import MySQLdb as dbmodule elif dbtype is 'postgres': import psycopg as dbmodule #deprecate def connect(): return dbmodule.connect (host=dbhost,db=dbname,user=dbuser,passwd=dbpass) def conn(): return '%s://%s:%s@%s/%s?charset=utf8&sqlobject_encoding=utf8' % (dbtype,dbuser,dbpass,dbhost,dbname) elif dbtype is 'sqlite': import os, time, re from pysqlite2 import dbapi2 as sqlite db_file_ext = '.' + dbtype if not dbname.endswith(db_file_ext): dbname+=db_file_ext dbpath = os.path.join(dbhost, dbname) def now(): return time.strftime('%Y-%m-%d %H:%M:%S') def regexp(regex, val): print regex, val, bool(re.search(regex, val, re.I)) return bool(re.search(regex, val, re.I)) class SQLiteCustomConnection(sqlite.Connection): def __init__(self, *args, **kwargs): print '@@@ SQLiteCustomConnection: registering functions' sqlite.Connection.__init__(self, *args, **kwargs) SQLiteCustomConnection.registerFunctions(self) def registerFunctions(self): self.create_function("NOW", 0, now) self.create_function("REGEXP", 2, regexp) self.create_function("regexp", 2, regexp) #~ self.execute("SELECT * FROM title WHERE title.booktitle REGEXP 'mar'") registerFunctions=staticmethod(registerFunctions) #deprecate _conn=None def connect(): import sqlobject #~ return sqlite.connect (database=dbpath) global _conn if not _conn: #~ _conn = sqlite.connect (database=dbpath) from objects.title import Title # can't use factory in URI because sqliteconnection doesn't share globals with us Title._connection._connOptions['factory'] = SQLiteCustomConnection # get the connection instance that sqlobject is going to use, so we only have one _conn = Title._connection.getConnection() # since a connection is made before we can set the factory, we have to register # the functions here also SQLiteCustomConnection.registerFunctions(_conn) return _conn def conn(): return '%s://%s?debug=t' % (dbtype,dbpath) #~ return '%s://%s?debug=t&factory=SQLiteCustomConnection' % (dbtype,dbpath)
johm/infoshopkeeper
components/db.py
Python
gpl-2.0
2,693
package co.deepthought; import co.deepthought.imagine.image.Fingerprinter; import co.deepthought.imagine.store.Size; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashSet; public class Tester { public static void main(String[] args) throws IOException { final String[] imageFiles = { "fireboat-300x200-100.jpg", "fireboat-1200x800-60.jpg", "liberty+autocolor-900x600-60.jpg", "liberty-600x400-40.jpg", "liberty-1200x800-80.jpg", "pathological-cropped-1.jpeg", "pathological-cropped-2.jpeg", "pathological-skyline-1.jpeg", "pathological-skyline-2.jpeg", "hat-small.jpeg", "hat-large.jpeg" }; final String[] fingerprints = new String[imageFiles.length]; for(int i = 0; i < imageFiles.length; i++) { final BufferedImage image = ImageIO.read( new File("/Users/kevindolan/rentenna/imagine/resources/test/"+imageFiles[i])); final Fingerprinter fingerprinter = new Fingerprinter(image); fingerprints[i] = fingerprinter.getFingerprint(new Size(36, 24)); } final HashSet<String> seen = new HashSet<>(); for(int i = 0; i < imageFiles.length; i++) { if(!seen.contains(imageFiles[i])) { seen.add(imageFiles[i]); System.out.println(imageFiles[i]); for(int j = 0; j < imageFiles.length; j++) { if(!seen.contains(imageFiles[j])) { final int difference = Fingerprinter.difference(fingerprints[i], fingerprints[j]); System.out.println(difference); if(difference < 256) { System.out.println("\t" + imageFiles[j]); seen.add(imageFiles[j]); } } } } } } }
metric-collective/imagine
src/main/java/co/deepthought/Tester.java
Java
gpl-2.0
2,065
package net.demilich.metastone.game.spells; import net.demilich.metastone.game.Attribute; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.cards.Card; import net.demilich.metastone.game.cards.CardCatalogue; import net.demilich.metastone.game.cards.CardList; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.spells.desc.SpellArg; import net.demilich.metastone.game.spells.desc.SpellDesc; import net.demilich.metastone.game.spells.desc.filter.EntityFilter; import net.demilich.metastone.game.targeting.CardLocation; public class ReceiveCardAndDoSomethingSpell extends Spell { private void castSomethingSpell(GameContext context, Player player, SpellDesc spell, Entity source, Card card) { context.getLogic().receiveCard(player.getId(), card); // card may be null (i.e. try to draw from deck, but already in // fatigue) if (card == null || card.getLocation() == CardLocation.GRAVEYARD) { return; } context.setEventCard(card); SpellUtils.castChildSpell(context, player, spell, source, card); context.setEventCard(null); } @Override protected void onCast(GameContext context, Player player, SpellDesc desc, Entity source, Entity target) { EntityFilter cardFilter = (EntityFilter) desc.get(SpellArg.CARD_FILTER); SpellDesc cardEffectSpell = (SpellDesc) desc.get(SpellArg.SPELL); int count = desc.getValue(SpellArg.VALUE, context, player, target, source, 1); if (cardFilter != null) { CardList cards = CardCatalogue.query(context.getDeckFormat()); CardList result = new CardList(); String replacementCard = (String) desc.get(SpellArg.CARD); for (Card card : cards) { if (cardFilter.matches(context, player, card)) { result.add(card); } } for (int i = 0; i < count; i++) { Card card = null; if (!result.isEmpty()) { card = result.getRandom(); } else if (replacementCard != null) { card = CardCatalogue.getCardById(replacementCard); } if (card != null) { Card clone = card.clone(); castSomethingSpell(context, player, cardEffectSpell, source, clone); } } } else { for (Card card : SpellUtils.getCards(context, desc, player)) { for (int i = 0; i < count; i++) { castSomethingSpell(context, player, cardEffectSpell, source, card); } } } } }
doombubbles/metastonething
game/src/main/java/net/demilich/metastone/game/spells/ReceiveCardAndDoSomethingSpell.java
Java
gpl-2.0
2,386
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2017 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** @file * @brief */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access this file directly"); } /** * Relation between item and devices **/ class Item_DevicePowerSupply extends Item_Devices { static public $itemtype_2 = 'DevicePowerSupply'; static public $items_id_2 = 'devicepowersupplies_id'; static protected $notable = false; /** * @since version 0.85 **/ static function getSpecificities($specif='') { return array('serial' => parent::getSpecificities('serial'), 'otherserial' => parent::getSpecificities('otherserial'), 'locations_id' => parent::getSpecificities('locations_id'), 'states_id' => parent::getSpecificities('states_id') ); } }
eltharin/glpi
inc/item_devicepowersupply.class.php
PHP
gpl-2.0
1,935
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson * * $Id: DocumentEcmaWrap.java,v 1.2 2004/09/29 00:13:10 cvs Exp $ */ package com.caucho.eswrap.org.w3c.dom; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; public class DocumentEcmaWrap { public static Attr createAttribute(Document doc, String name, String value) throws DOMException { Attr attr = doc.createAttribute(name); attr.setValue(value); return attr; } }
christianchristensen/resin
modules/ecmascript/src/com/caucho/eswrap/org/w3c/dom/DocumentEcmaWrap.java
Java
gpl-2.0
1,457
#include <QImage> #include <QFile> #include "SpriteBundle.h" SpriteBundle::SpriteBundle() { m_index = 0; } void SpriteBundle::update(const int delta) { Sprite &image = m_sprites[m_index]; image.update(delta); } void SpriteBundle::setImageIndex(const int index) { m_index = index; } QSGTexture *SpriteBundle::currentImage(Scene *scene, bool flipped) { Sprite &image = m_sprites[m_index]; QSGTexture *frame = image.currentFrame(scene, flipped); return frame; } int SpriteBundle::spriteCount() const { return m_sprites.count(); } int SpriteBundle::imageIndex() const { return m_index; } QDataStream &operator >>(QDataStream &stream, SpriteBundle &bundle) { stream >> bundle.m_sprites; return stream; }
MemoryLeek/ld27
SpriteBundle.cpp
C++
gpl-2.0
720
/************************************************************************* * Clus - Software for Predictive Clustering * * Copyright (C) 2007 * * Katholieke Universiteit Leuven, Leuven, Belgium * * Jozef Stefan Institute, Ljubljana, Slovenia * * * * 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/>. * * * * Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. * *************************************************************************/ /* * Created on Jul 28, 2005 * */ package clus.ext.beamsearch; import clus.algo.tdidt.ClusNode; import clus.main.Settings; import clus.statistic.ClusStatistic; import clus.statistic.RegressionStat; public class ClusBeamHeuristicMorishita extends ClusBeamHeuristic { public ClusBeamHeuristicMorishita(ClusStatistic stat) { super(stat); } public double computeMorishitaStat(ClusStatistic stat, ClusStatistic tstat) { RegressionStat stat_set = (RegressionStat)stat; RegressionStat stat_all = (RegressionStat)tstat; // Compute half of formula from Definition 2 of Morishita paper double result = 0.0; for (int i = 0; i < stat_set.getNbAttributes(); i++) { double term_i = stat_set.getMean(i) - stat_all.getMean(i); result += term_i * term_i; } return result * stat_set.getTotalWeight(); } public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_tot = c_tstat.m_SumWeight; double n_pos = c_pstat.m_SumWeight; double n_neg = n_tot - n_pos; // Acceptable? if (n_pos < Settings.MINIMAL_WEIGHT || n_neg < Settings.MINIMAL_WEIGHT) { return Double.NEGATIVE_INFINITY; } m_Neg.copy(c_tstat); m_Neg.subtractFromThis(c_pstat); // Does not take into account missing values! return computeMorishitaStat(c_pstat, c_tstat) + computeMorishitaStat(m_Neg, c_tstat); } public double estimateBeamMeasure(ClusNode tree, ClusNode parent) { if (tree.atBottomLevel()) { return computeMorishitaStat(tree.getClusteringStat(), parent.getClusteringStat()); } else { double result = 0.0; for (int i = 0; i < tree.getNbChildren(); i++) { ClusNode child = (ClusNode)tree.getChild(i); result += estimateBeamMeasure(child); } return result; } } public double estimateBeamMeasure(ClusNode tree) { if (tree.atBottomLevel()) { return 0; } else { double result = 0.0; for (int i = 0; i < tree.getNbChildren(); i++) { ClusNode child = (ClusNode)tree.getChild(i); result += estimateBeamMeasure(child, tree); } return result; } } public double computeLeafAdd(ClusNode leaf) { return 0.0; } public String getName() { return "Beam Heuristic (Morishita)"; } public void setRootStatistic(ClusStatistic stat) { super.setRootStatistic(stat); } }
active-learning/active-learning-scala
src/main/java/clus/ext/beamsearch/ClusBeamHeuristicMorishita.java
Java
gpl-2.0
3,865
// Implementing the functionality for system calls (keystrokes etc.) and // exercising different functions available from other classes/files // // Author: Archit Gupta, Nehal Bhandari // Date: December 24, 2015 #include "process.h" char valid_keystroke(DisplayHandler* display, char input) { if ((input <= 'z' && input >= 'a') || (input <= 'Z' && input >= 'A')) { return 0; } return input; } // Function definitions for PreviewManager class PreviewManager::PreviewManager() { win = NULL; m_mode = VISUAL; m_exit_signal = false; m_cursor_y = Y_OFFSET; m_cursor_x = X_OFFSET; } // Function definitions specific to ListPreviewManager ListPreviewManager::ListPreviewManager() { ListPreviewManager(NULL, NULL); } ListPreviewManager::ListPreviewManager(WINDOW *_win, ToDoList *td) { win = _win; td_list = td; if (td_list != NULL) { entry_under_cursor = td->get_list_top(); } m_mode = VISUAL; m_exit_signal = false; m_cursor_y = Y_OFFSET; m_cursor_x = X_OFFSET; } void ListPreviewManager::printToDoList(ToDoListEntry* first_entry_to_print) { int y_cursor = m_cursor_y; // TODO: Add functionality to print the todo-list title here (and have a // title for the todo list in the first place ToDoListEntry* entry_to_print = first_entry_to_print; while(entry_to_print != NULL) { printToDoEntry(entry_to_print, y_cursor); y_cursor += entry_to_print->get_message_block_length(); entry_to_print = entry_to_print->get_next_todo_entry(); } box(win, 0, 0); wrefresh(win); } void ListPreviewManager::printToDoEntry(ToDoListEntry* entry_to_print, int y_cursor) { entry_to_print->print(win, y_cursor, entry_to_print == entry_under_cursor); #ifdef __DEBUG__ //getch(); //box(win, 0, 0); wrefresh(win); #endif } void ListPreviewManager::insert_text(char input) { entry_under_cursor->insert_text(win, m_cursor_y, m_cursor_x, input); if ((input >= (char) FIRST_WRITABLE_ASCII_CHAR) && (input <= (char) LAST_WRITEABLE_ASCII_CHAR)) { move_cursor_right(); } else if (input == (char) M_KEY_BACKSPACE) { move_cursor_left(); } wrefresh(win); } void ListPreviewManager::process(char input) { switch (input) { #define F_DEF(INPUT, FUNCTION, NON_FUNC_MODE)\ case INPUT:\ if (m_mode == NON_FUNC_MODE)\ {\ insert_text(INPUT);\ } else {\ FUNCTION(); \ } break; #include "keystrokes.def" #undef F_DEF default: if (m_mode == INSERT) { insert_text(input); } else { return; } break; } } // Key stroke related functions have been described here void ListPreviewManager::move_cursor_left(){ if (m_mode == EDIT || m_mode == INSERT) { if (m_cursor_x > X_OFFSET) { wmove(win, m_cursor_y, --m_cursor_x); wrefresh(win); } else{ int old_cursor_y = m_cursor_y; move_cursor_up(); if (old_cursor_y != m_cursor_y) { // Change the x cursor value only if the y cursor has changed // (i.e. the line under cursor has been switched) m_cursor_x = WRITABLE_X; wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } } } } void ListPreviewManager::move_cursor_right(){ if (m_mode == EDIT || m_mode == INSERT) { if (m_cursor_x < entry_under_cursor->x_limit()) { wmove(win, m_cursor_y, ++m_cursor_x); wrefresh(win); } else{ int old_cursor_y = m_cursor_y; move_cursor_down(); if (old_cursor_y != m_cursor_y) { // Change the x cursor value only if the y cursor has changed // (i.e. the line under cursor has been switched) m_cursor_x = X_OFFSET; wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } } } } void ListPreviewManager::move_cursor_up(){ if (m_mode == VISUAL) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor->refresh(win, m_cursor_y, false); entry_under_cursor = entry_under_cursor->get_prev_todo_entry(); m_cursor_y -= entry_under_cursor->get_message_block_length(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); box(win, 0, 0); } } else { bool jump_todo_entry = entry_under_cursor->check_end_point(true); if (jump_todo_entry) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor = entry_under_cursor->get_prev_todo_entry(); entry_under_cursor->set_cursor_bottom(); m_cursor_x = entry_under_cursor->x_limit(); wmove(win, --m_cursor_y, m_cursor_x); } } else { entry_under_cursor->update_cursor_position(win, m_cursor_y, m_cursor_x, true); } wrefresh(win); } } void ListPreviewManager::move_cursor_down(){ if (m_mode == VISUAL) { if(entry_under_cursor->get_next_todo_entry() != NULL) { entry_under_cursor->refresh(win, m_cursor_y, false); m_cursor_y += entry_under_cursor->get_message_block_length(); entry_under_cursor = entry_under_cursor->get_next_todo_entry(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); box(win, 0, 0); } } else { bool jump_todo_entry = entry_under_cursor->check_end_point(false); if (jump_todo_entry) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor = entry_under_cursor->get_next_todo_entry(); entry_under_cursor->set_cursor_top(); m_cursor_x = X_OFFSET; wmove(win, ++m_cursor_y, m_cursor_x); } } else { entry_under_cursor->update_cursor_position(win, m_cursor_y, m_cursor_x, false); } wrefresh(win); } } // Switching between various modes void ListPreviewManager::switch_to_edit_mode(){ PreviewMode last_mode = m_mode; m_mode = EDIT; curs_set(m_mode); if (last_mode == VISUAL) { entry_under_cursor->refresh(win, m_cursor_y, false); wmove(win, m_cursor_y, X_OFFSET); wrefresh(win); } } void ListPreviewManager::switch_to_visual_mode(){ if (m_mode == EDIT) { m_mode = VISUAL; curs_set(m_mode); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); } } void ListPreviewManager::switch_to_insert_mode(){ m_mode = INSERT; curs_set(EDIT); // Using curs_set(INSERT) makes the cursor invisible -___- entry_under_cursor->refresh(win, m_cursor_y, false); wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } void ListPreviewManager::step_modes_back(){ switch (m_mode) { case EDIT: switch_to_visual_mode(); break; case INSERT: switch_to_edit_mode(); break; default: switch_to_visual_mode(); break; } } // Adding and deleting ToDo Entries void ListPreviewManager::add_todo_entry(){ entry_under_cursor = td_list->new_todo_entry(entry_under_cursor); printToDoList(entry_under_cursor); } void ListPreviewManager::two_tap_delete(){ char repeat = getch(); if (repeat == 'd') { ToDoListEntry* next_todo_entry = entry_under_cursor->get_next_todo_entry(); td_list->remove_todo_entry(entry_under_cursor); entry_under_cursor = next_todo_entry; printToDoList(entry_under_cursor); } } void ListPreviewManager::two_tap_quit(){ char repeat = getch(); if (repeat == 'q') { m_exit_signal = true; } } void ListPreviewManager::toggle_mark_unmark(){ entry_under_cursor->toggle_mark_unmark(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); }
architgupta93/todo-app
2_Code/process.cpp
C++
gpl-2.0
8,567
function Drag(id,init) { var _this=this; this.disX=0; this.disY=0; this.oDiv=document.getElementById(id); if(init) { _this.fnDown(); } this.oDiv.onmousedown=function (ev) { _this.fnDown(ev); return false; }; } Drag.prototype.fnDown=function (ev) { var _this=this; var oEvent=ev||event; this.disX=oEvent.clientX-this.oDiv.offsetLeft; this.disY=oEvent.clientY-this.oDiv.offsetTop; document.onmousemove=function (ev) { _this.fnMove(ev); }; document.onmouseup=function () { _this.fnUp(); }; }; Drag.prototype.fnMove=function (ev) { var oEvent=ev||event; this.oDiv.style.left=oEvent.clientX-this.disX+'px'; this.oDiv.style.top=oEvent.clientY-this.disY+'px'; }; Drag.prototype.fnUp=function () { document.onmousemove=null; document.onmouseup=null; }; function LimitDrag(id) { Drag.call(this, id); } //LimitDrag.prototype=Drag.prototype; for(var i in Drag.prototype) { LimitDrag.prototype[i]=Drag.prototype[i]; } LimitDrag.prototype.fnMove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-this.disX; var t=oEvent.clientY-this.disY; if(l<0) { l=0; } else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth) { l=document.documentElement.clientWidth-this.oDiv.offsetWidth; } if(t<0) { t=0; } else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight) { t=document.documentElement.clientHeight-this.oDiv.offsetHeight; } this.oDiv.style.left=l+'px'; this.oDiv.style.top=t+'px'; };
Jackmeng1985/drupal7
sites/all/modules/beauty_crm/js/drag.js
JavaScript
gpl-2.0
1,492
#!/usr/bin/env python background_image_filename = 'sushiplate.jpg' import pygame from pygame.locals import * from sys import exit SCREEN_SIZE = (640, 480) pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, NOFRAME, 32) background = pygame.image.load(background_image_filename).convert() while True: event = pygame.event.wait() if event.type == QUIT: exit() if event.type == VIDEORESIZE: SCREEN_SIZE = event.size screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32) pygame.display.set_caption('Window resized to ' + str(event.size)) # screen.fill((0, 0, 0)) screen.blit(background, (0, 0)) # screen_width, screen_height = SCREEN_SIZE # for y in range(0, screen_height, background.get_height()): # for x in range(0, screen_width, background.get_width()): # screen.blit(background, (x, y)) pygame.display.update()
opensvn/python
pygame/resize.py
Python
gpl-2.0
919
/* * _ __ _ * | |/ /__ __ __ _ _ __ | |_ _ _ _ __ ___ * | ' / \ \ / // _` || '_ \ | __|| | | || '_ ` _ \ * | . \ \ V /| (_| || | | || |_ | |_| || | | | | | * |_|\_\ \_/ \__,_||_| |_| \__| \__,_||_| |_| |_| * * Copyright (C) 2019 Alexander Sรถderberg * * 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 xyz.kvantum.server.api.util; public interface ApplicationStructureFactory<A extends ApplicationStructure> { A create(ApplicationContext applicationContext); }
IntellectualSites/IntellectualServer
ServerAPI/src/main/java/xyz/kvantum/server/api/util/ApplicationStructureFactory.java
Java
gpl-2.0
1,042
<? echo "<div class='information'>\n"; require("../updatePubliDocs.php"); $chemin="$_SERVER[DOCUMENT_ROOT]$public_path/$publi[year]/$publi[bibTex]/" ; intranetSqlConnect(); if (!empty($_POST["group"])) $group=$_POST["group"]; $res_upd = sqlQuery("SELECT * from docs WHERE id=$id_doc"); $docs = mysql_fetch_array($res_upd); switch ($group) { case "public": rename($chemin."$protected/$docs[source]", $chemin.$docs['source']); break; case "private": if (!is_dir($chemin."$protected/")) { mkdir($chemin."$protected/", 0755); } if (!is_file($chemin."$protected/.htaccess")) { // Creation of .htaccess file $file = $chemin."$protected/.htaccess"; echo "Creating .htaccess file in $chemin$protected/<br />\n"; copy("$_SERVER[DOCUMENT_ROOT]$intra_path/htaccess_private", $file); if (!is_file("$file")) error("File .htaccess could not be created"); } rename($chemin.$docs['source'], $chemin."$protected/$docs[source]"); break; } updatePubliDocs($id); echo "</div>\n"; ?>
truijllo/basilic
Sources/Intranet/Publications/mod_upd.php
PHP
gpl-2.0
1,036
<?php /** *------------------------------------------------------------------------------ * iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x *------------------------------------------------------------------------------ * @package com_icagenda * @copyright Copyright (c)2012-2014 Cyril RezยŽ, Jooml!C - All rights reserved * * @license GNU General Public License version 3 or later; see LICENSE.txt * @author Cyril RezยŽ (Lyr!C) * @link http://www.joomlic.com * * @version 3.3.3 2014-04-02 * @since 3.3.3 *------------------------------------------------------------------------------ */ // No direct access to this file defined('_JEXEC') or die(); /** * category Table class */ class iCagendaTableregistration extends JTable { /** * Constructor * * @param JDatabase A database connector object */ public function __construct(&$_db) { parent::__construct('#__icagenda_registration', 'id', $_db); } /** * Overloaded bind function to pre-process the params. * * @param array Named array * @return null|string null is operation was satisfactory, otherwise returns an error * @see JTable:bind * @since 1.5 */ public function bind($array, $ignore = '') { if (isset($array['params']) && is_array($array['params'])) { $registry = new JRegistry(); $registry->loadArray($array['params']); $array['params'] = (string)$registry; } if (isset($array['metadata']) && is_array($array['metadata'])) { $registry = new JRegistry(); $registry->loadArray($array['metadata']); $array['metadata'] = (string)$registry; } return parent::bind($array, $ignore); } /** * Overloaded check function */ public function check() { //If there is an ordering column and this is a new row then get the next ordering value if (property_exists($this, 'ordering') && $this->id == 0) { $this->ordering = self::getNextOrder(); } // URL jimport( 'joomla.filter.output' ); // if(empty($this->alias)) { // $this->alias = $this->title; // } // $this->alias = JFilterOutput::stringURLSafe($this->alias); return parent::check(); } /** * Method to set the publishing state for a row or list of rows in the database * table. The method respects checked out rows by other users and will attempt * to checkin rows that it can after adjustments are made. * * @param mixed An optional array of primary key values to update. If not * set the instance property value is used. * @param integer The publishing state. eg. [0 = unpublished, 1 = published] * @param integer The user id of the user performing the operation. * @return boolean True on success. * @since 1.0.4 */ public function publish($pks = null, $state = 1, $userId = 0) { // Initialise variables. $k = $this->_tbl_key; // Sanitize input. JArrayHelper::toInteger($pks); $userId = (int) $userId; $state = (int) $state; // If there are no primary keys set check to see if the instance key is set. if (empty($pks)) { if ($this->$k) { $pks = array($this->$k); } // Nothing to set publishing state on, return false. else { $this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); return false; } } // Build the WHERE clause for the primary keys. $where = $k.'='.implode(' OR '.$k.'=', $pks); // Determine if there is checkin support for the table. if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) { $checkin = ''; } else { $checkin = ' AND (checked_out = 0 OR checked_out = '.(int) $userId.')'; } // Update the publishing state for rows with the given primary keys. $this->_db->setQuery( 'UPDATE `'.$this->_tbl.'`' . ' SET `state` = '.(int) $state . ' WHERE ('.$where.')' . $checkin ); $this->_db->query(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } // If checkin is supported and all rows were adjusted, check them in. if ($checkin && (count($pks) == $this->_db->getAffectedRows())) { // Checkin the rows. foreach($pks as $pk) { $this->checkin($pk); } } // If the JTable instance value is in the list of primary keys that were set, set the instance. if (in_array($this->$k, $pks)) { $this->state = $state; } $this->setError(''); return true; } }
C3Style/appuihec
administrator/components/com_icagenda/tables/registration.php
PHP
gpl-2.0
4,975
/** * stencil_maskType.java * * This file was generated by XMLSpy 2007sp2 Enterprise Edition. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the XMLSpy Documentation for further details. * http://www.altova.com/xmlspy */ package com.jmex.model.collada.schema; import com.jmex.xml.types.SchemaNCName; public class stencil_maskType extends com.jmex.xml.xml.Node { public stencil_maskType(stencil_maskType node) { super(node); } public stencil_maskType(org.w3c.dom.Node node) { super(node); } public stencil_maskType(org.w3c.dom.Document doc) { super(doc); } public stencil_maskType(com.jmex.xml.xml.Document doc, String namespaceURI, String prefix, String name) { super(doc, namespaceURI, prefix, name); } public void adjustPrefix() { for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "value" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "value", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "param" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "param", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } } public void setXsiType() { org.w3c.dom.Element el = (org.w3c.dom.Element) domNode; el.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "stencil_mask"); } public static int getvalue2MinCount() { return 0; } public static int getvalue2MaxCount() { return 1; } public int getvalue2Count() { return getDomChildCount(Attribute, null, "value"); } public boolean hasvalue2() { return hasDomChild(Attribute, null, "value"); } public int2 newvalue2() { return new int2(); } public int2 getvalue2At(int index) throws Exception { return new int2(getDomNodeValue(getDomChildAt(Attribute, null, "value", index))); } public org.w3c.dom.Node getStartingvalue2Cursor() throws Exception { return getDomFirstChild(Attribute, null, "value" ); } public org.w3c.dom.Node getAdvancedvalue2Cursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "value", curNode ); } public int2 getvalue2ValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new int2(getDomNodeValue(curNode)); } public int2 getvalue2() throws Exception { return getvalue2At(0); } public void removevalue2At(int index) { removeDomChildAt(Attribute, null, "value", index); } public void removevalue2() { removevalue2At(0); } public org.w3c.dom.Node addvalue2(int2 value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "value", value.toString()); } public org.w3c.dom.Node addvalue2(String value) throws Exception { return addvalue2(new int2(value)); } public void insertvalue2At(int2 value, int index) { insertDomChildAt(Attribute, null, "value", index, value.toString()); } public void insertvalue2At(String value, int index) throws Exception { insertvalue2At(new int2(value), index); } public void replacevalue2At(int2 value, int index) { replaceDomChildAt(Attribute, null, "value", index, value.toString()); } public void replacevalue2At(String value, int index) throws Exception { replacevalue2At(new int2(value), index); } public static int getparamMinCount() { return 0; } public static int getparamMaxCount() { return 1; } public int getparamCount() { return getDomChildCount(Attribute, null, "param"); } public boolean hasparam() { return hasDomChild(Attribute, null, "param"); } public SchemaNCName newparam() { return new SchemaNCName(); } public SchemaNCName getparamAt(int index) throws Exception { return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "param", index))); } public org.w3c.dom.Node getStartingparamCursor() throws Exception { return getDomFirstChild(Attribute, null, "param" ); } public org.w3c.dom.Node getAdvancedparamCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "param", curNode ); } public SchemaNCName getparamValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new SchemaNCName(getDomNodeValue(curNode)); } public SchemaNCName getparam() throws Exception { return getparamAt(0); } public void removeparamAt(int index) { removeDomChildAt(Attribute, null, "param", index); } public void removeparam() { removeparamAt(0); } public org.w3c.dom.Node addparam(SchemaNCName value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "param", value.toString()); } public org.w3c.dom.Node addparam(String value) throws Exception { return addparam(new SchemaNCName(value)); } public void insertparamAt(SchemaNCName value, int index) { insertDomChildAt(Attribute, null, "param", index, value.toString()); } public void insertparamAt(String value, int index) throws Exception { insertparamAt(new SchemaNCName(value), index); } public void replaceparamAt(SchemaNCName value, int index) { replaceDomChildAt(Attribute, null, "param", index, value.toString()); } public void replaceparamAt(String value, int index) throws Exception { replaceparamAt(new SchemaNCName(value), index); } }
tectronics/xenogeddon
src/com/jmex/model/collada/schema/stencil_maskType.java
Java
gpl-2.0
5,745
#include "document.h" #include "effect.h" #include "newdialog.h" #include <QtCore/QFile> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtGui/QMessageBox> #include <QtGui/QFileDialog> namespace { static QString strippedName(const QString & fileName) { return QFileInfo(fileName).fileName(); } static QString strippedName(const QFile & file) { return QFileInfo(file).fileName(); } } // static QString Document::lastEffect() { return s_lastEffect; } // static void Document::setLastEffect(const QString & effectPath) { s_lastEffect = effectPath; } // static QString Document::s_lastEffect; Document::Document(QGLWidget * glWidget, QWidget * parent/*= 0*/) : QObject(parent) { Q_ASSERT(glWidget != NULL); m_glWidget = glWidget; m_owner = parent; m_effectFactory = NULL; m_file = NULL; m_effect = NULL; m_modified = false; } Document::~Document() { closeEffect(); } bool Document::isModified() const { return m_modified; } void Document::setModified(bool m) { // If file not saved, modified is always true. //if (m_modified != m) // Sometimes want to force an update by invoking the signal. { m_modified = m; emit modifiedChanged(m_modified); } } /// Return the current document file name. QString Document::fileName() const { QString fileName; if (m_file != NULL) { fileName = strippedName(*m_file); } else { QString fileExtension = m_effectFactory->extension(); fileName = tr("untitled") + "." + fileExtension; } return fileName; } /// Return document's title. QString Document::title() const { QString title; if (m_file == NULL) { title = tr("Untitled"); } else { title = strippedName(*m_file); } if (m_modified) { title.append(" "); title.append(tr("[modified]")); } return title; } bool Document::canLoadFile(const QString & fileName) const { int idx = fileName.lastIndexOf('.'); QString fileExtension = fileName.mid(idx+1); const EffectFactory * effectFactory = EffectFactory::factoryForExtension(fileExtension); return (effectFactory != NULL) && m_effectFactory->isSupported(); } /*************************Peter Komar code, august 2009 ************************************/ void Document::slot_load_from_library_shader(const QString& name_lib) { if (!close()) { // User cancelled the operation. return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QFile *filelib = new QFile(name_lib); if (!filelib->open(QIODevice::ReadOnly)) { QMessageBox::critical(m_owner, tr("Error"), tr("Can't open library.")); return; } int idx = name_lib.lastIndexOf('.'); QString Ext = name_lib.mid(idx+1); m_effectFactory = EffectFactory::factoryForExtension(Ext); if (m_effectFactory != NULL) { Q_ASSERT(m_effectFactory->isSupported()); m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_effect->load(filelib); emit effectCreated(); build(false); } emit titleChanged(name_lib.mid(name_lib.lastIndexOf("/")+1,idx)); filelib->close(); delete filelib; QApplication::restoreOverrideCursor(); } /**************************************************************************/ bool Document::loadFile(const QString & fileName) { if (!close()) { // User cancelled the operation. return false; } delete m_file; m_file = new QFile(fileName); if (!m_file->open(QIODevice::ReadOnly)) { delete m_file; m_file = NULL; return false; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); m_modified = false; int idx = fileName.lastIndexOf('.'); QString fileExtension = fileName.mid(idx+1); m_effectFactory = EffectFactory::factoryForExtension(fileExtension); if (m_effectFactory != NULL) { Q_ASSERT(m_effectFactory->isSupported()); m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_effect->load(m_file); emit effectCreated(); build(false); } else { // @@ Can this happen? } m_file->close(); emit titleChanged(title()); s_lastEffect = fileName; // @@ Move this somewhere else! emit fileNameChanged(fileName); QApplication::restoreOverrideCursor(); return true; } void Document::reset(bool startup) { // Count effect file types. const QList<const EffectFactory *> & effectFactoryList = EffectFactory::factoryList(); int count = 0; foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported()) { ++count; } } const EffectFactory * effectFactory = NULL; if (count == 0) { // Display error. QMessageBox::critical(m_owner, tr("Error"), tr("No effect files supported"), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } else if(count == 1) { // Use the first supported effect type. foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported()) { effectFactory = ef; break; } } } else { // Let the user choose the effect type. NewDialog newDialog(m_owner, startup); int result = newDialog.exec(); if (result == QDialog::Accepted) { QString selection = newDialog.shaderType(); foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported() && ef->name() == selection) { effectFactory = ef; break; } } } else if (result == NewDialog::OpenEffect) { open(); return; } } if (effectFactory != NULL) { newEffect(effectFactory); } } void Document::open() { // Find supported effect types. QStringList effectTypes; QStringList effectExtensions; foreach (const EffectFactory * factory, EffectFactory::factoryList()) { if (factory->isSupported()) { QString effectType = QString("%1 (*.%2)").arg(factory->namePlural()).arg(factory->extension()); effectTypes.append(effectType); QString effectExtension = factory->extension(); effectExtensions.append("*." + effectExtension); } } if (effectTypes.isEmpty()) { QMessageBox::critical(m_owner, tr("Error"), tr("No effect files supported"), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); return; } //QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), tr("."), effectTypes.join(";")); QString fileName = QFileDialog::getOpenFileName(m_owner, tr("Open File"), s_lastEffect, QString(tr("Effect Files (%1)")).arg(effectExtensions.join(" "))); if (!fileName.isEmpty()) { loadFile(fileName); } } bool Document::save() { if (m_file == NULL) { // Choose file dialog. QString fileExtension = m_effectFactory->extension(); QString effectType = QString("%1 (*.%2)").arg(m_effectFactory->namePlural()).arg(fileExtension); QString fileName = QFileDialog::getSaveFileName(m_owner, tr("Save File"), tr("untitled") + "." + fileExtension, effectType); if( fileName.isEmpty() ) { return false; } m_file = new QFile(fileName); } // @@ Check for errors. return saveEffect(); } void Document::saveAs() { Q_ASSERT(m_effectFactory != NULL); QString fileExtension = m_effectFactory->extension(); QString effectType = QString("%1 (*.%2)").arg(m_effectFactory->namePlural()).arg(fileExtension); // Choose file dialog. QString fileName = QFileDialog::getSaveFileName(m_owner, tr("Save File"), this->fileName(), effectType); if( fileName.isEmpty() ) { return; } delete m_file; m_file = new QFile(fileName); // @@ Check for errors. saveEffect(); // @@ Emit only when file name actually changed. emit fileNameChanged(fileName); } bool Document::close() { if (m_effect == NULL) { Q_ASSERT(m_file == NULL); // No effect open. return true; } if (m_effectFactory != NULL && isModified()) { QString fileName; if (m_file != NULL) { fileName = strippedName(*m_file); } else { QString extension = m_effectFactory->extension(); fileName = tr("untitled") + "." + extension; } while (true) { int answer = QMessageBox::question(m_owner, tr("Save modified files"), tr("Do you want to save '%1' before closing?").arg(fileName), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (answer == QMessageBox::Yes) { if( save() ) { break; } } else if (answer == QMessageBox::Cancel) { return false; } else { break; } } } emit effectDeleted(); closeEffect(); return true; } void Document::build(bool threaded /*= true*/) { Q_ASSERT(m_effect != NULL); emit synchronizeEditors(); emit effectBuilding(); m_effect->build(threaded); } void Document::onParameterChanged() { Q_ASSERT(m_effectFactory != NULL); if (m_effectFactory->savesParameters() && !isModified()) { setModified(true); } } void Document::newEffect(const EffectFactory * effectFactory) { Q_ASSERT(effectFactory != NULL); if (!close()) { // User cancelled the operation. return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); m_effectFactory = effectFactory; m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_modified = false; emit effectCreated(); emit titleChanged(title()); build(false); QApplication::restoreOverrideCursor(); } bool Document::saveEffect() { m_file->open(QIODevice::WriteOnly); // Synchronize before save. emit synchronizeEditors(); m_effect->save(m_file); m_file->close(); setModified(false); emit titleChanged(title()); //updateActions(); // qshaderedit listens to modifiedChanged return true; } void Document::closeEffect() { // Delete effect. delete m_effect; m_effect = NULL; delete m_file; m_file = NULL; }
peterkomar/qshaderedit
src/document.cpp
C++
gpl-2.0
10,048
<?php /* Plugin Name: Email Subscribers Plugin URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ Description: Email subscribers plugin has options to send newsletters to subscribers. It has a separate page with HTML editor to create a HTML newsletter. Also have options to send notification email to subscribers when new posts are published to your blog. Separate page available to include and exclude categories to send notifications. Version: 2.7 Author: Gopi Ramasamy Donate link: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ Author URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html */ /* Copyright 2014 Email subscribers (http://www.gopiplus.com) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); } require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'base'.DIRECTORY_SEPARATOR.'es-defined.php'); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-stater.php'); add_action('admin_menu', array( 'es_cls_registerhook', 'es_adminmenu' )); register_activation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_activation' )); register_deactivation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_deactivation' )); add_action( 'widgets_init', array( 'es_cls_registerhook', 'es_widget_loading' )); add_shortcode( 'email-subscribers', 'es_shortcode' ); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-directly.php'); function es_textdomain() { load_plugin_textdomain( 'email-subscribers' , false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); } add_action('plugins_loaded', 'es_textdomain'); add_action( 'transition_post_status', array( 'es_cls_sendmail', 'es_prepare_notification' ), 10, 3 ); ?>
CosmicPi/cosmicpi.org
wp-content/plugins/email-subscribers/email-subscribers.php
PHP
gpl-2.0
2,553
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectPackageTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_package', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('repository'); $table->string('deploy_branch'); $table->string('deploy_location'); $table->integer('order'); $table->integer('project_id')->unsigned(); }); Schema::table('project_package', function($table) { $table->foreign('project_id') ->references('id')->on('project') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('project_package'); } }
ImbalanceGaming/imbalance-gaming-laravel
database/migrations/2016_04_14_100207_create_project_package_table.php
PHP
gpl-2.0
1,001
package com.example.seventeen.blissappid; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.CountDownTimer; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; /** * Hofundur: Egill Orn Sigthorsson * Dagsetning: 1.10.2014 * Lysing: Vidmot fyrir nothafa, tar sem hann getur tjad ja og nei * a audskiljanlegan hatt og opnad fulla blisstaknatoflu */ public class nothafi1 extends Activity { /** * Gerum sitthvoran onclicklistner fyrir ja og nei * @param savedInstanceState save instance */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nothafi1); makeOnclickListeners(); } /** * bua til on click listnera fyrir takka i netenda vidmoti */ public void makeOnclickListeners(){ ImageButton jabutt; jabutt = (ImageButton) findViewById(R.id.ja); jabutt.setOnClickListener(gotoClickListener); ImageButton neibutt; neibutt = (ImageButton) findViewById(R.id.nei); neibutt.setOnClickListener(gotoneiClickListener); ImageButton bio; bio = (ImageButton) findViewById(R.id.bio); bio.setOnClickListener(gotoBioClickListener); ImageButton ftafla; ftafla = (ImageButton) findViewById(R.id.ftafla); ftafla.setOnClickListener(gotoftaflaClickListener); } /** * Ef smellt er a ja takkan */ View.OnClickListener gotoClickListener = new View.OnClickListener() { /** * tegar smellt er a ja takkan gloir hann i 3 sekundur * * @param v er view */ @Override public void onClick(View v) { final ImageButton jabutt; jabutt = (ImageButton) findViewById(R.id.ja); new CountDownTimer(3000,1000){ /** * breytum bakgrunni a takkanum a medan vid teljum nidur * @param millisUntilFinished timi eftir */ @Override public void onTick(long millisUntilFinished){ jabutt.setBackgroundResource(R.drawable.jafoc); } /** * breytum bakgrunni a takkanum i upprunalegt astandi tegar 3 sekundur eru lidnar */ @Override public void onFinish(){ //set the new Content of your activity jabutt.setBackgroundResource(R.drawable.ja); } }.start(); } }; /** * Ef smellt er a nei takkan */ View.OnClickListener gotoneiClickListener = new View.OnClickListener() { /** * รžegar smellt er รก nei takkan glรณir hann i 3 sekundur * @param v er view */ @Override public void onClick(View v) { final ImageButton neibutt; neibutt = (ImageButton) findViewById(R.id.nei); new CountDownTimer(3000,1000){ /** * breytum bakgrunni รก takkanum a medan viรฐ teljum nidur * @param millisUntilFinished timi eftir */ @Override public void onTick(long millisUntilFinished){ neibutt.setBackgroundResource(R.drawable.neifoc); } /** * breytum bakgrunni รก takkanum รญ upprunalegt astandi tegar 3 sekundur eru lidnar */ @Override public void onFinish(){ //set the new Content of your activity neibutt.setBackgroundResource(R.drawable.nei); } }.start(); } }; /** * Ef smellt er a bio takkan */ View.OnClickListener gotoBioClickListener = new View.OnClickListener() { /** * ef smellt er a bio takkan er kallad a fallid bio() * @param v view */ @Override public void onClick(View v) { bio(); } }; /** * opnar nyja gluggan bio */ private void bio(){ startActivity(new Intent(this, bio.class)); } /** * Ef smellt er a bio takkan */ View.OnClickListener gotoftaflaClickListener = new View.OnClickListener() { /** * ef smellt er a bio takkan er kallad a fallid bio() * @param v view */ @Override public void onClick(View v) { ftafla(); } }; /** * opnar nyja gluggan ftafla */ private void ftafla(){ startActivity(new Intent(this, full_blisstafla.class)); } /** * Inflate the menu; this adds items to the action bar if it is present. * @param menu Menu * @return true */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.nothafi1, menu); return true; } /** * Handle action bar item clicks here. The action bar will * automatically handle clicks on the Home/Up button, so long * as you specify a parent activity in AndroidManifest.xml. * @param item MenuItem * @return super.onOptionsItemSelected(item); */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
sbleika/Blissid
BlissAppid_git/BlissAppid/app/src/main/java/com/example/seventeen/blissappid/nothafi1.java
Java
gpl-2.0
5,549
/** * */ package com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes; import java.util.List; import com.ankamagames.dofus.harvey.engine.common.sets.classes.AbstractIntervalBridge; import com.ankamagames.dofus.harvey.engine.common.sets.classes.SplitOnRangeBridge; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteBoundComparisonToolbox; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteEqualityToolbox; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteIntervalCreationToolbox; import com.ankamagames.dofus.harvey.numeric.bytes.sets.classes.ByteInterval; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteBound; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteInterval; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IElementaryByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IEmptyByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.ISimpleByteSet; import org.eclipse.jdt.annotation.NonNullByDefault; /** * @author sgros * */ @NonNullByDefault public class ByteIntervalBridge<Bridged extends ByteInterval> extends AbstractIntervalBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> { protected ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> _boundToolbox; protected ByteIntervalCreationToolbox<Bridged> _creationToolbox; protected ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> _equalityToolbox; protected SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> _splitBridge; public ByteIntervalBridge(final Bridged bridged) { super(bridged); _boundToolbox = new ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged>(_bridged); _creationToolbox = new ByteIntervalCreationToolbox<Bridged>(_bridged); _equalityToolbox = new ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged>(_bridged); _splitBridge = new SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged>(_bridged, _creationToolbox); } @Override protected SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> getSplitBridge() { return _splitBridge; } @Override protected ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> getBoundComparisonToolbox() { return _boundToolbox; } @Override protected ByteIntervalCreationToolbox<Bridged> getSetCreationToolbox() { return _creationToolbox; } @Override protected ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> getEqualityToolbox() { return _equalityToolbox; } public List<? extends IByteSet> split(final byte[] values, final boolean[] isIntervalStart) { return getSetCreationToolbox().split(values, isIntervalStart); } @Override public boolean isEmpty() { final IByteBound lowerBound = _bridged.getLowerBound(); final IByteBound upperBound = _bridged.getUpperBound(); if(lowerBound == null || upperBound == null) return true; return (lowerBound.getValue() - upperBound.getValue())>0; } @Override public IByteSet unite(final IByteSet set) { return super.unite(set).getAsSet(); } @Override public IByteSet intersect(final IByteSet set) { return super.intersect(set).getAsSet(); } }
Ankama/harvey
src/com/ankamagames/dofus/harvey/engine/numeric/bytes/sets/classes/ByteIntervalBridge.java
Java
gpl-2.0
3,714
package com.frm.bdTask.controls; /** * @author: Larry Pham. * @since: 3/24/2014. * @version: 2014.03.24. */ public class ListTodosActivityControl { }
PhamPhi/birdy_task
src/com/frm/bdTask/controls/ListTodosActivityControl.java
Java
gpl-2.0
155
<?php prado::using ('Application.pages.s.report.MainPageReports'); class ReportDT1 extends MainPageReports { public function onLoad ($param) { parent::onLoad ($param); $this->showLokasi=true; $this->showDT1=true; $this->createObjFinance(); $this->createObjKegiatan(); if (!$this->IsPostBack&&!$this->IsCallBack) { $this->toolbarOptionsBulanRealisasi->Enabled=false; $this->toolbarOptionsTahunAnggaran->DataSource=$this->TGL->getYear(); $this->toolbarOptionsTahunAnggaran->Text=$this->session['ta']; $this->toolbarOptionsTahunAnggaran->dataBind(); if (isset($_SESSION['currentPageReportDT1']['datakegiatan']['iddt1'])) { $this->detailProcess(); }else { if (!isset($_SESSION['currentPageReportDT1'])||$_SESSION['currentPageReportDT1']['page_name']!='s.report.ReportDT1') { $_SESSION['currentPageReportDT1']=array('page_name'=>'s.report.ReportDT1','page_num'=>0,'datakegiatan'=>array()); } $this->literalHeader->Text='Laporan Kegiatan Berdasarkan Daerah Tingkat I '; $this->populateData (); } } } public function changeTahunAnggaran ($sender,$param) { if (isset($_SESSION['currentPageReportDT1']['datakegiatan']['iddt1'])) { $this->idProcess='view'; $_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text; $this->contentReport->Text=$this->printContent(); }else { $_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text; $this->populateData(); } } protected function populateData () { $ta=$this->session['ta']; $str = 'SELECT iddt1,nama_dt1 FROM dt1 ORDER BY dt1.iddt1 ASC'; $this->DB->setFieldTable(array('iddt1','nama_dt1')); $r=$this->DB->getRecord($str); $result=array(); $str = "SELECT idlok,COUNT(idproyek) AS jumlah_proyek,SUM(nilai_pagu) AS nilai_pagu FROM proyek WHERE ket_lok='dt1' AND tahun_anggaran=$ta GROUP BY idlok ORDER BY idlok ASC"; $this->DB->setFieldTable(array('idlok','jumlah_proyek','nilai_pagu')); $kegiatan=$this->DB->getRecord($str); while (list($k,$v)=each($r)) { $jumlah_kegiatan=0; $nilai_pagu=0; foreach ($kegiatan as $lokasi) { if ($lokasi['idlok']==$v['iddt1']) { $jumlah_kegiatan=$lokasi['jumlah_proyek']; $nilai_pagu=$this->finance->toRupiah($lokasi['nilai_pagu']); break; } } $v['jumlah_kegiatan']=$jumlah_kegiatan; $v['nilai_pagu']=$nilai_pagu; $result[$k]=$v; } $this->RepeaterS->DataSource=$result; $this->RepeaterS->dataBind(); } public function viewRecord($sender,$param) { $iddt1=$this->getDataKeyField($sender, $this->RepeaterS); $str = "SELECT iddt1,nama_dt1 FROM dt1 WHERE iddt1=$iddt1"; $this->DB->setFieldTable(array('iddt1','nama_dt1')); $r=$this->DB->getRecord($str); $_SESSION['currentPageReportDT1']['datakegiatan']=$r[1]; $this->redirect('s.report.ReportDT1'); } public function detailProcess () { $this->idProcess='view'; $datalokasi=$_SESSION['currentPageReportDT1']['datakegiatan']; $this->literalHeader->Text="Daftar Kegiatan di {$datalokasi['nama_dt1']} "; $this->contentReport->Text=$this->printContent(); } /** * digunakan untuk mendapatkan nilai total pagu untuk satu unit * */ private function getTotalNilaiPaguUnit ($idunit,$ta) { $iddt1=$_SESSION['currentPageReportDT1']['datakegiatan']['iddt1']; $str = "SELECT SUM(p.nilai_pagu) AS total FROM proyek p,program pr WHERE p.idprogram=pr.idprogram AND pr.idunit='$idunit' AND pr.tahun='$ta' AND ket_lok='dt1' AND idlok=$iddt1"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } /** * * total fisik satu proyek, tahun, bulan penggunaan */ private function getTotalFisik ($idproyek,$tahun) { $str = "SELECT SUM(fisik) AS total FROM v_laporan_a WHERE tahun_penggunaan='$tahun' AND idproyek='$idproyek'"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } /** * * jumlah realisasi satu proyek, tahun, bulan penggunaan */ private function getJumlahFisik ($idproyek,$tahun) { $str = "SELECT COUNT(realisasi) AS total FROM v_laporan_a WHERE tahun_penggunaan='$tahun' AND idproyek='$idproyek'"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } public function printContent () { $datalokasi=$_SESSION['currentPageReportDT1']['datakegiatan']; $idunit=$this->idunit; $ta=$this->session['ta']; $this->DB->setFieldTable (array('idprogram','kode_program','nama_program')); $str = "SELECT idprogram,kode_program,nama_program FROM program WHERE idunit='$idunit' AND tahun='$ta'"; //daftar program pada unit $daftar_program=$this->DB->getRecord($str); $content="<p class=\"msg info\"> Belum ada program pada tahun anggaran $ta.</p>"; if (isset($daftar_program[1])) { //total pagu satu unit $totalPaguUnit = $this->getTotalNilaiPaguUnit ($idunit,$ta); if ($totalPaguUnit > 0) { $content= '<table class="list" style="font-size:9px"> <thead> <tr> <th rowspan="4" class="center">NO</th> <th rowspan="4" width="350" class="center">PROGRAM/KEGIATAN</th> <th rowspan="4" class="center">SUMBER<br />DANA</th> <th rowspan="4" class="center">PAGU DANA</th> <th rowspan="4" class="center">BOBOT</th> <th colspan="5" class="center">REALISASI</th> <th rowspan="2" colspan="2" class="center">SISA ANGGARAN</th> </tr> <tr> <th colspan="2" class="center">FISIK</th> <th colspan="3" class="center">KEUANGAN</th> </tr> <tr> <th class="center">% per</th> <th class="center">% per</th> <th rowspan="2" class="center">(Rp)</th> <th class="center">% per</th> <th class="center">% per</th> <th rowspan="2" class="center">(Rp)</th> <th rowspan="2" class="center">(%)</th> </tr> <tr> <th class="center">kegiatan</th> <th class="center">SPPD</th> <th class="center">kegiatan</th> <th class="center">SPPD</th> </tr> <tr> <th class="center">1</th> <th class="center">2</th> <th class="center">3</th> <th class="center">4</th> <th class="center">5</th> <th class="center">6</th> <th class="center">7</th> <th class="center">8</th> <th class="center">9</th> <th class="center">10</th> <th class="center">11</th> <th class="center">12</th> </tr> </thead><tbody>'; $no_huruf=ord('a'); $totalRealisasiKeseluruhan=0; $totalPersenRealisasiPerSPPD='0.00'; $totalSisaAnggaran=0; $jumlah_kegiatan=0; while (list($k,$v)=each($daftar_program)) { $idprogram=$v['idprogram']; $this->DB->setFieldTable(array('idproyek','nama_proyek','nilai_pagu','sumber_anggaran','idlok','ket_lok')); $str = "SELECT p.idproyek,p.nama_proyek,p.nilai_pagu,p.sumber_anggaran,idlok,ket_lok FROM proyek p WHERE idprogram='$idprogram' AND ket_lok='dt1' AND idlok='{$datalokasi['iddt1']}'"; $daftar_kegiatan = $this->DB->getRecord($str); if (isset($daftar_kegiatan[1])) { $totalpagueachprogram=0; foreach ($daftar_kegiatan as $eachprogram) { $totalpagueachprogram+=$eachprogram['nilai_pagu']; } $totalpagueachprogram=$this->finance->toRupiah($totalpagueachprogram,'tanpa_rp'); $content.= '<tr> <td class="center"><strong>'.chr($no_huruf).'</strong></td> <td class="left"><strong>'.$v['nama_program'].'</strong></td> <td class="left">&nbsp;</td> <td class="right"><strong>'.$totalpagueachprogram.'</strong></td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> </tr>'; $no=1; while (list($m,$n)=each($daftar_kegiatan)) { $idproyek=$n['idproyek']; $content.= '<tr>'; $content.= '<td class="center">'.$n['no'].'</td>'; $content.= '<td class="left">'.$n['nama_proyek'].'</td>'; $content.= '<td class="center">'.$n['sumber_anggaran'].'</td>'; $nilai_pagu_proyek=$n['nilai_pagu']; $rp_nilai_pagu_proyek=$this->finance->toRupiah($nilai_pagu_proyek,'tanpa_rp'); $content.= "<td class=\"right\">$rp_nilai_pagu_proyek</td>"; $persen_bobot=number_format(($nilai_pagu_proyek/$totalPaguUnit)*100,2); $totalPersenBobot+=$persen_bobot; $content.= "<td class=\"center\">$persen_bobot</td>"; $str = "SELECT SUM(realisasi) AS total FROM v_laporan_a WHERE idproyek=$idproyek AND tahun_penggunaan='$ta'"; $this->DB->setFieldTable(array('total')); $realisasi=$this->DB->getRecord($str); $persen_fisik='0.00'; $persenFisikPerSPPD='0.00'; $totalrealisasi=0; $persen_realisasi='0.00'; $persenRealisasiPerSPPD='0.00'; $sisa_anggaran=0; $persen_sisa_anggaran='0.00'; if ($realisasi[1]['total'] > 0 ){ //fisik $totalFisikSatuProyek=$this->getTotalFisik($idproyek,$ta); $jumlahRealisasiFisikSatuProyek=$this->getJumlahFisik ($idproyek,$ta); $persen_fisik=number_format(($totalFisikSatuProyek/$jumlahRealisasiFisikSatuProyek),2); $totalPersenFisik+=$persen_fisik; $persenFisikPerSPPD=number_format(($persen_fisik/100)*$persen_bobot,2); $totalPersenFisikPerSPPD+=$persenFisikPerSPPD; $totalrealisasi=$realisasi[1]['total']; $totalRealisasiKeseluruhan+=$totalrealisasi; $persen_realisasi=number_format(($totalrealisasi/$nilai_pagu_proyek)*100,2); $totalPersenRealisasi+=$persen_realisasi; $persenRealisasiPerSPPD=number_format(($persen_realisasi/100)*$persen_bobot,2); $totalPersenRealisasiPerSPPD+=$persenRealisasiPerSPPD; $sisa_anggaran=$nilai_pagu_proyek- $totalrealisasi; $persen_sisa_anggaran=number_format(($sisa_anggaran/$totalPaguUnit)*100,2); $totalPersenSisaAnggaran+=$persen_sisa_anggaran; $totalSisaAnggaran+=$sisa_anggaran; } $content.= '<td class="center">'.$persen_fisik.'</td>'; $content.= '<td class="center">'.$persenFisikPerSPPD.'</td>'; $content.= '<td class="right">'.$this->finance->toRupiah($totalrealisasi,'tanpa_rp').'</td>'; $content.= '<td class="center">'.$persen_realisasi.'</td>'; $content.= '<td class="center">'.$persenRealisasiPerSPPD.'</td>'; $content.= '<td class="right">'.$this->finance->toRupiah($sisa_anggaran,'tanpa_rp').'</td>'; $content.= '<td class="center">'.$persen_sisa_anggaran.'</td>'; $content.='</tr>'; $no++; $jumlah_kegiatan++; } $no_huruf++; } } $rp_total_pagu_unit=$this->finance->toRupiah($totalPaguUnit,'tanpa_rp'); $totalPersenBobot=number_format($totalPersenBobot); $rp_total_realisasi_keseluruhan=$this->finance->toRupiah($totalRealisasiKeseluruhan,'tanpa_rp'); if ($totalPersenRealisasi > 0) $totalPersenRealisasi=number_format(($totalPersenRealisasi/$jumlah_kegiatan),2); if ($totalPersenSisaAnggaran > 0) $totalPersenSisaAnggaran=number_format(($totalPersenSisaAnggaran/$jumlah_kegiatan),2); $totalPersenFisik=number_format($totalPersenFisik/$jumlah_kegiatan,2); $totalPersenRealisasiPerSPPD=number_format($totalPersenRealisasiPerSPPD,2); $totalPersenFisikPerSPPD=number_format($totalPersenFisikPerSPPD,2); $rp_total_sisa_anggaran=$this->finance->toRupiah($totalSisaAnggaran,'tanpa_rp'); $content.= '<tr> <td colspan="2" class="right"><strong>Jumlah</strong></td> <td class="left"></td> <td class="right">'.$rp_total_pagu_unit.'</td> <td class="center">'.$totalPersenBobot.'</td> <td class="center">'.$totalPersenFisik.'</td> <td class="center">'.$totalPersenFisikPerSPPD.'</td> <td class="right">'.$rp_total_realisasi_keseluruhan.'</td> <td class="center">'.$totalPersenRealisasi.'</td> <td class="center">'.$totalPersenRealisasiPerSPPD.'</td> <td class="right">'.$rp_total_sisa_anggaran.'</td> <td class="center">'.$totalPersenSisaAnggaran.'</td> </tr>'; $content.='</tbody></table>'; } } return $content; } public function printOut ($sender,$param) { $this->idProcess='view'; $this->createObjReport(); $this->report->dataKegiatan=$_SESSION['currentPageReportDT1']['datakegiatan']; $this->report->dataKegiatan['idunit']=$this->idunit; $this->report->dataKegiatan['tahun']=$_SESSION['ta']; $this->report->dataKegiatan['userid']=$this->userid; $this->report->dataKegiatan['tipe_lokasi']='dt1'; $filetype=$this->cmbTipePrintOut->Text; switch($filetype) { case 'excel2003' : $this->report->setMode('excel2003'); $this->report->printLokasi($this->linkOutput); break; case 'excel2007' : $this->report->setMode('excel2007'); $this->report->printLokasi($this->linkOutput); break; } } public function close($sender,$param) { unset($_SESSION['currentPageReportDT1']); $this->redirect('s.report.ReportDT1'); } } ?>
ibnoe/simonev
protected/pages/s/report/ReportDT1.php
PHP
gpl-2.0
18,291
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package datagen.engine; import java.util.ArrayList; /** * * @author juan.garson */ public class Table { private final ArrayList<Column> columns; private final String name; private int count; private final ArrayList<String> reference; public Table(String name){ this.name = name; columns = new ArrayList<>(); reference = new ArrayList<>(); } public Column getColumn(String name){ Column response; try{ response = null; for(Column column: columns){ if(column.field.equals(name)){ response = column; break; } } }catch(Exception e){ response = null; } return response; } public String[] getRow(int position){ String[] response; try{ response = new String[columns.size()]; for(int i=0;i<columns.size();i++){ response[i] = columns.get(i).gen[position]; } }catch(Exception e){ System.err.println(e.getMessage()); response = null; } return response; } public boolean hasReferences(){ return reference.size() > 0; } public ArrayList<String> getReferences(){ return reference; } public void addColumn(Column column){ columns.add(column); } public String getName(){ return name; } public void setCount(int count){ this.count = count; } public int getCount(){ return count; } public ArrayList<Column> getColumns(){ return columns; } /*@Override public String toString() { StringBuilder builder; builder = new StringBuilder(); builder.append("Table : "); builder.append(name); builder.append("\n"); for(Column col : columns){ builder.append(col.toString()); builder.append("\n"); } return builder.toString(); }*/ @Override public String toString() { return name; } }
lanstat/DataGen
src/datagen/engine/Table.java
Java
gpl-2.0
2,373
############################################################# # Signal.rb # # Copyright (c) 2002 Phil Tomson # released under the GNU General Public License (GPL) # ################################################## ####################################################### # add a bin method to the built-in String class # converts a String composed of '1's and '0's to binary # (note: won't be needed in Ruby 1.7/1.8 # ##################################################### class String def bin val = self.strip pattern = /^([+-]?)(0b)?([01]+)(.*)$/ parts = pattern.match(val) return 0 if not parts sign = parts[1] num = parts[3] eval(sign+"0b"+num) end end ##################################################### # add a 'inv' method to the built-in Fixnum class # ##################################################### class Fixnum def inv binary = sprintf("%b",self) #get a binary representation of 'self' ones = '1'*binary.length #create a string of '1's the length of binary self ^ ones.bin #invert by XOR'ing with ones end end module RHDL ############################################################### # Signal - ############################################################### class Signal @@signalList = []#everytime we create a new signal we add it to this list @@deltaEvents = true attr_reader :valObj, :next_value, :event attr_writer :event def Signal.update_all @@signalList.each {|signal| signal.update } end def Signal.deltaEvents? @@deltaEvents end def Signal.clear_deltaEvents @@deltaEvents = false end def Signal.set_deltaEvents @@deltaEvents = true end def inspect @valObj.inspect end def value #was: #self.inspect #TODO: should it just be: @valObj @valObj end def value=(n) @valObj.assign(n) end #TODO: do we need Signal.clear_events ? def Signal.clear_events @@signalList.each { |signal| signal.event = false } end def type @valObj.class end def rising_edge event && value == '1' end def falling_edge event && value == '0' end #signals have history def initialize(valObj,width = 1) @valObj = valObj @@signalList << self @eventQueue = [] @event = false @next_value = nil end ####The old assign_at and assign methods:############## # define a driver function for this signal: #def assign_at (relTime=0,function=nil) # #schedule an event # nextValue = case function # when nil # Proc.new.call # when Proc # function.call # when Signal # proc{function.to_s}.call # else # function # end # @eventQueue[relTime] = nextValue # nextValInQueue = @eventQueue.shift # @next_value = nextValInQueue if nextValInQueue #end # #def assign(function=nil) # if function # assign_at(0,function) # else # assign_at(0,Proc.new) # end #end ####################################################### def call proc{self.to_s}.call end #.... def assign_at (relTime=0,nextValue=Proc.new) nextValue = nextValue.call if nextValue.respond_to? :call ###Experimental#### if(relTime < @eventQueue.length) @eventQueue.clear @eventQueue[0] = nextValue else @eventQueue[relTime] = nextValue end #@eventQueue[relTime] = nextValue if @@deltaEvents nextValInQueue = @eventQueue[0] #nextValInQueue = @eventQueue.shift else nextValInQueue = @eventQueue.shift end ###\Experimental#### puts "nextValInQueue: #{nextValInQueue}" if $DEBUG puts "@eventQueue:" if $DEBUG puts @eventQueue if $DEBUG @next_value = nextValInQueue if nextValInQueue != nil end def assign(nextValue=Proc.new) puts "assign #{nextValue}" if $DEBUG assign_at(0,nextValue) end #deprecated: #def <<(nextValue=Proc.new) # self.assign(nextValue) #end ########################################### # <= means assignment, not les-than-or-equal ########################################### def <=(nextValue=Proc.new) self.assign(nextValue) end ########################################### # less-than-or-equal (since we can't use <= anymore ) # ######################################### def lte(other) if other.class == Signal @valObj <= other.value else @valObj <= other end end ########################################## # greater-than-or-equal # ######################################## def gte(other) if other.class == Signal @valObj >= other.value else @valObj >= other end end #was commented: def method_missing(methID,*args) puts "methID is: #{methID}, args are: #{args}" if $DEBUG case methID when :+,:-,:*,:==,:===,:<=>,:>,:<,:or,:and,:^,:&,:|,:xor other = args[0] if other.class == Signal @valObj.send(methID,other.value) else @valObj.send(methID,other) end else @valObj.send(methID,*args) end end def to_s @valObj.to_s end def update puts "update: next_value = #@next_value current value = #{@valObj.inspect}" if $DEBUG puts "update: next_value = #@next_value current value = #{@valObj}" if $DEBUG puts "update: next_value.class = #{@next_value.class} current value.class = #{@valObj.class}" if $DEBUG #TODO: what about using 'inspect' to determine values for events? #was:if @next_value && @next_value.to_s != @valObj.inspect.to_s #if changed if @next_value && @valObj != @next_value #if changed puts "update: #{@next_value.to_s} #{valObj.inspect.to_s}" if $DEBUG puts "update: #{@next_value} #{valObj}" if $DEBUG puts "update: class:#{@next_value.class}!= #{@valObj.class}" if @next_value.class != @valObj.class if $DEBUG @event = true @@deltaEvents = true else @event = false end if @next_value if @valObj.respond_to?(:assign) @valObj.assign(@next_value) else @valObj = @next_value end end puts "update value is now: #@valObj" if $DEBUG end def coerce(other) puts "coersion called! other is: #{other}, other.class is: #{other.class}" case other when Fixnum #return [ Signal.new(other), self.value.to_i] return [ other, self.value.to_i] when String puts "Coerce String!!!!!!" return [ Signal(BitVector(other)), self] end end #the '==' that comes with all objects must be overridden def ==(other) if other.class == Signal @valObj == other.value else @valObj == other end end #NOTE: commented to try coerce #def ===(other) # puts "Signal::===" if $DEBUG # @valObj === other #end end def Signal(val,width=1) Signal.new(val,width) end end #RHDL if $0 == __FILE__ require 'Bit' include RHDL require "test/unit" puts "Test Signal" class Testing_Signal < Test::Unit::TestCase def setup @a_bit = Signal(Bit('1')) @b_bit = Signal(Bit('1')) @c_bit = Signal(Bit()) @counter = Signal(0) @a_bv = Signal(BitVector('1010')) @b_bv = Signal(BitVector('0101')) @c_bv = Signal(BitVector('XXXX')) end def test_add_bit @c_bit <= @a_bit + @b_bit @c_bit.update assert_equal(1, @c_bit) end def test_inv_bit @a_bit <= @a_bit.inv @a_bit.update assert_equal(0, @a_bit) end def test_compare_bv assert_not_equal(@a_bv, @b_bv) assert( @a_bv > @b_bv ) #compare with a string literal: assert( @a_bv > '0000') #compare with an integer: assert( @a_bv < 22 ) assert( @a_bv == 0b1010 ) assert( @a_bv.lte(0b1010) ) assert( @a_bv.gte(@b_bv )) end def test_add_bv @c_bv <= (@a_bv + @b_bv) @c_bv.update puts "@c_bv.value.class is: #{@c_bv.value.class}" #assert_equal( @c_bv, '1111') assert_equal( '1111', @c_bv.value.to_s) #try adding a literal to a Signal: @c_bv <= ( @c_bv + '0001' ) @c_bv.update assert_equal( '0000', @c_bv.value.to_s ) #try adding a BitVector to a BitVector Signal: @c_bv <= ( @c_bv + BitVector.new('1000')) @c_bv.update assert_equal( '1000', @c_bv.value.to_s ) #try adding an integer to a BitVector Signal: @c_bv <= ( @c_bv + 1 ) @c_bv.update assert_equal( '1001', @c_bv.value.to_s ) #try adding a Signal(BitVector) to an integer: @c_bv <= ( 1 + @c_bv ) @c_bv.update assert_equal( '1010', @c_bv.value.to_s ) #try adding a Bitvector to a Signal: @c_bv <= (@c_bv + BitVector('0011') ) @c_bv.update assert_equal( '1101', @c_bv.value.to_s ) #NOTE: the following doesn't work and probably won't ever #try adding Signal to string literal (which represents BitVector): #@c_bv <= ('0010' + @c_bv) #@c_bv.update #assert_equal( '1111', @c_bv.value.to_s ) end def test_reassignment_options @a_bit <= 0 @a_bit.update assert_equal(0, @a_bit) @a_bit <= '1' @a_bit.update assert_equal(1, @a_bit) @c_bv <= '0000' @c_bv.update assert_equal(RHDL::Signal, @c_bv.class) assert_equal(BitVector, @c_bv.value.class ) assert_equal('0000', @c_bv.value.to_s) end def test_integer_signal @counter <= @counter + 1 @counter.update assert_equal(1, @counter) #try adding two signals: val = Signal( 1 ) @counter <= @counter + val @counter.update assert_equal(2, @counter) end end if false c0 = 0 #Integer a = Signal(Bit('1')) b = Signal(Bit('1')) c = Signal(Bit()) c <= (a + b) c.update if c == '1' puts "yes" end counter = Signal(c0) counter.<<(counter + 1) counter.update puts counter.inspect puts c counter.assign(counter + 8) counter.update puts counter.inspect counter.assign(counter & 5) counter.update puts counter.inspect counter.assign(counter * 0b0101) counter.update puts counter.inspect counter.assign(counter ^ 0xF) counter.update puts counter.inspect if c == '1' puts "yes" end end end
philtomson/RHDL
lib/hardware/RHDL/Signal.rb
Ruby
gpl-2.0
10,266
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | # | | |___| | | | __/ (__| < | | | | . \ | # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | # | | # | Copyright Mathias Kettner 2014 mk@mathias-kettner.de | # +------------------------------------------------------------------+ # # This file is part of Check_MK. # The official homepage is at http://mathias-kettner.de/check_mk. # # check_mk 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 in version 2. check_mk is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more de- # tails. You should have received a copy of the GNU General Public # License along with GNU Make; see the file COPYING. If not, write # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA. import utils import config, time, os, re, pprint import hashlib import weblib, traceback, forms, valuespec, inventory, visuals, metrics import sites import bi import inspect import livestatus from log import logger from gui_exceptions import MKGeneralException, MKUserError, MKInternalError import cmk.paths # Datastructures and functions needed before plugins can be loaded loaded_with_language = False display_options = None # Load all view plugins def load_plugins(force): global loaded_with_language if loaded_with_language == current_language and not force: # always reload the hosttag painters, because new hosttags might have been # added during runtime load_host_tag_painters() clear_alarm_sound_states() return global multisite_datasources ; multisite_datasources = {} global multisite_layouts ; multisite_layouts = {} global multisite_painters ; multisite_painters = {} global multisite_sorters ; multisite_sorters = {} global multisite_builtin_views ; multisite_builtin_views = {} global multisite_painter_options ; multisite_painter_options = {} global multisite_commands ; multisite_commands = [] global multisite_command_groups ; multisite_command_groups = {} global view_hooks ; view_hooks = {} global inventory_displayhints ; inventory_displayhints = {} config.declare_permission_section("action", _("Commands on host and services"), do_sort = True) utils.load_web_plugins("views", globals()) load_host_tag_painters() clear_alarm_sound_states() # This must be set after plugin loading to make broken plugins raise # exceptions all the time and not only the first time (when the plugins # are loaded). loaded_with_language = current_language # Declare permissions for builtin views config.declare_permission_section("view", _("Multisite Views"), do_sort = True) for name, view in multisite_builtin_views.items(): config.declare_permission("view.%s" % name, format_view_title(view), "%s - %s" % (name, _u(view["description"])), config.builtin_role_ids) # Make sure that custom views also have permissions config.declare_dynamic_permissions(lambda: visuals.declare_custom_permissions('views')) declare_inventory_columns() # Load all views - users or builtins def load_views(): global multisite_views, available_views # Skip views which do not belong to known datasources multisite_views = visuals.load('views', multisite_builtin_views, skip_func = lambda v: v['datasource'] not in multisite_datasources) available_views = visuals.available('views', multisite_views) transform_old_views() def permitted_views(): try: return available_views except: # In some cases, for example when handling AJAX calls the views might # have not been loaded yet load_views() return available_views def all_views(): return multisite_views # Convert views that are saved in the pre 1.2.6-style # FIXME: Can be removed one day. Mark as incompatible change or similar. def transform_old_views(): for view in multisite_views.values(): ds_name = view['datasource'] datasource = multisite_datasources[ds_name] if "context" not in view: # legacy views did not have this explicitly view.setdefault("user_sortable", True) if 'context_type' in view: # This code transforms views from user_views.mk which have been migrated with # daily snapshots from 2014-08 till beginning 2014-10. visuals.transform_old_visual(view) elif 'single_infos' not in view: # This tries to map the datasource and additional settings of the # views to get the correct view context # # This code transforms views from views.mk (legacy format) to the current format try: hide_filters = view.get('hide_filters') if 'service' in hide_filters and 'host' in hide_filters: view['single_infos'] = ['service', 'host'] elif 'service' in hide_filters and 'host' not in hide_filters: view['single_infos'] = ['service'] elif 'host' in hide_filters: view['single_infos'] = ['host'] elif 'hostgroup' in hide_filters: view['single_infos'] = ['hostgroup'] elif 'servicegroup' in hide_filters: view['single_infos'] = ['servicegroup'] elif 'aggr_service' in hide_filters: view['single_infos'] = ['service'] elif 'aggr_name' in hide_filters: view['single_infos'] = ['aggr'] elif 'aggr_group' in hide_filters: view['single_infos'] = ['aggr_group'] elif 'log_contact_name' in hide_filters: view['single_infos'] = ['contact'] elif 'event_host' in hide_filters: view['single_infos'] = ['host'] elif hide_filters == ['event_id', 'history_line']: view['single_infos'] = ['history'] elif 'event_id' in hide_filters: view['single_infos'] = ['event'] elif 'aggr_hosts' in hide_filters: view['single_infos'] = ['host'] else: # For all other context types assume the view is showing multiple objects # and the datasource can simply be gathered from the datasource view['single_infos'] = [] except: # Exceptions can happen for views saved with certain GIT versions if config.debug: raise # Convert from show_filters, hide_filters, hard_filters and hard_filtervars # to context construct if 'context' not in view: view['show_filters'] = view['hide_filters'] + view['hard_filters'] + view['show_filters'] single_keys = visuals.get_single_info_keys(view) # First get vars for the classic filters context = {} filtervars = dict(view['hard_filtervars']) all_vars = {} for filter_name in view['show_filters']: if filter_name in single_keys: continue # skip conflictings vars / filters context.setdefault(filter_name, {}) try: f = visuals.get_filter(filter_name) except: # The exact match filters have been removed. They where used only as # link filters anyway - at least by the builtin views. continue for var in f.htmlvars: # Check whether or not the filter is supported by the datasource, # then either skip or use the filter vars if var in filtervars and f.info in datasource['infos']: value = filtervars[var] all_vars[var] = value context[filter_name][var] = value # We changed different filters since the visuals-rewrite. This must be treated here, since # we need to transform views which have been created with the old filter var names. # Changes which have been made so far: changed_filter_vars = { 'serviceregex': { # Name of the filter # old var name: new var name 'service': 'service_regex', }, 'hostregex': { 'host': 'host_regex', }, 'hostgroupnameregex': { 'hostgroup_name': 'hostgroup_regex', }, 'servicegroupnameregex': { 'servicegroup_name': 'servicegroup_regex', }, 'opthostgroup': { 'opthostgroup': 'opthost_group', 'neg_opthostgroup': 'neg_opthost_group', }, 'optservicegroup': { 'optservicegroup': 'optservice_group', 'neg_optservicegroup': 'neg_optservice_group', }, 'hostgroup': { 'hostgroup': 'host_group', 'neg_hostgroup': 'neg_host_group', }, 'servicegroup': { 'servicegroup': 'service_group', 'neg_servicegroup': 'neg_service_group', }, 'host_contactgroup': { 'host_contactgroup': 'host_contact_group', 'neg_host_contactgroup': 'neg_host_contact_group', }, 'service_contactgroup': { 'service_contactgroup': 'service_contact_group', 'neg_service_contactgroup': 'neg_service_contact_group', }, } if filter_name in changed_filter_vars and f.info in datasource['infos']: for old_var, new_var in changed_filter_vars[filter_name].items(): if old_var in filtervars: value = filtervars[old_var] all_vars[new_var] = value context[filter_name][new_var] = value # Now, when there are single object infos specified, add these keys to the # context for single_key in single_keys: if single_key in all_vars: context[single_key] = all_vars[single_key] view['context'] = context # Cleanup unused attributes for k in [ 'hide_filters', 'hard_filters', 'show_filters', 'hard_filtervars' ]: try: del view[k] except KeyError: pass def save_views(us): visuals.save('views', multisite_views) # For each view a function can be registered that has to return either True # or False to show a view as context link view_is_enabled = {} def is_enabled_for(linking_view, view, context_vars): if view["name"] not in view_is_enabled: return True # Not registered are always visible! return view_is_enabled[view["name"]](linking_view, view, context_vars) #. # .--PainterOptions------------------------------------------------------. # | ____ _ _ ___ _ _ | # | | _ \ __ _(_)_ __ | |_ ___ _ __ / _ \ _ __ | |_(_) ___ _ __ ___ | # | | |_) / _` | | '_ \| __/ _ \ '__| | | | '_ \| __| |/ _ \| '_ \/ __| | # | | __/ (_| | | | | | || __/ | | |_| | |_) | |_| | (_) | | | \__ \ | # | |_| \__,_|_|_| |_|\__\___|_| \___/| .__/ \__|_|\___/|_| |_|___/ | # | |_| | # +----------------------------------------------------------------------+ # | Painter options are settings that can be changed per user per view. | # | These options are controlled throught the painter options form which | # | is accessible through the small monitor icon on the top left of the | # | views. | # '----------------------------------------------------------------------' # TODO: Better name it PainterOptions or DisplayOptions? There are options which only affect # painters, but some which affect generic behaviour of the views, so DisplayOptions might # be better. class PainterOptions(object): def __init__(self, view_name=None): self._view_name = view_name # The names of the painter options used by the current view self._used_option_names = None # The effective options for this view self._options = {} def load(self): self._load_from_config() # Load the options to be used for this view def _load_used_options(self, view): if self._used_option_names != None: return # only load once per request options = set([]) for cell in get_group_cells(view) + get_cells(view): options.update(cell.painter_options()) # Also layouts can register painter options layout_name = view.get("layout") if layout_name != None: options.update(multisite_layouts[layout_name].get("options", [])) # TODO: Improve sorting. Add a sort index? self._used_option_names = sorted(options) def _load_from_config(self): if self._is_anonymous_view(): return # never has options if not self.painter_options_permitted(): return # Options are stored per view. Get all options for all views vo = config.user.load_file("viewoptions", {}) self._options = vo.get(self._view_name, {}) def save_to_config(self): vo = config.user.load_file("viewoptions", {}, lock=True) vo[self._view_name] = self._options config.user.save_file("viewoptions", vo) def update_from_url(self, view): self._load_used_options(view) if not self.painter_option_form_enabled(): return if html.has_var("_reset_painter_options"): self._clear_painter_options() return elif html.has_var("_update_painter_options"): self._set_from_submitted_form() def _set_from_submitted_form(self): # TODO: Remove all keys that are in multisite_painter_options # but not in self._used_option_names modified = False for option_name in self._used_option_names: # Get new value for the option from the value spec vs = self.get_valuespec_of(option_name) value = vs.from_html_vars("po_%s" % option_name) if not self._is_set(option_name) or self.get(option_name) != value: modified = True self.set(option_name, value) if modified: self.save_to_config() def _clear_painter_options(self): # TODO: This never removes options that are not existant anymore modified = False for name in multisite_painter_options.keys(): try: del self._options[name] modified = True except KeyError: pass if modified: self.save_to_config() # Also remove the options from current html vars. Otherwise the # painter option form will display the just removed options as # defaults of the painter option form. for varname in html.all_varnames_with_prefix("po_"): html.del_var(varname) def get_valuespec_of(self, name): opt = multisite_painter_options[name] if type(lambda: None) == type(opt["valuespec"]): return opt["valuespec"]() else: return opt["valuespec"] def _is_set(self, name): return name in self._options # Sets a painter option value (only for this request). Is not persisted! def set(self, name, value): self._options[name] = value # Returns either the set value, the provided default value or if none # provided, it returns the default value of the valuespec. def get(self, name, dflt=None): if dflt == None: try: dflt = self.get_valuespec_of(name).default_value() except KeyError: # Some view options (that are not declared as display options) # like "refresh" don't have a valuespec. So they need to default # to None. # TODO: Find all occurences and simply declare them as "invisible" # painter options. pass return self._options.get(name, dflt) # Not falling back to a default value, simply returning None in case # the option is not set. def get_without_default(self, name): return self._options.get(name) def get_all(self): return self._options def _is_anonymous_view(self): return self._view_name == None def painter_options_permitted(self): return config.user.may("general.painter_options") def painter_option_form_enabled(self): return self._used_option_names and self.painter_options_permitted() def show_form(self, view): self._load_used_options(view) if not display_options.enabled(display_options.D) or not self.painter_option_form_enabled(): return html.open_div(id_="painteroptions", class_=["view_form"], style="display: none;") html.begin_form("painteroptions") forms.header(_("Display Options")) for name in self._used_option_names: vs = self.get_valuespec_of(name) forms.section(vs.title()) # TODO: Possible improvement for vars which default is specified # by the view: Don't just default to the valuespecs default. Better # use the view default value here to get the user the current view # settings reflected. vs.render_input("po_%s" % name, self.get(name)) forms.end() html.button("_update_painter_options", _("Submit"), "submit") html.button("_reset_painter_options", _("Reset"), "submit") html.hidden_fields() html.end_form() html.close_div() def prepare_painter_options(view_name=None): global painter_options painter_options = PainterOptions(view_name) painter_options.load() #. # .--Cells---------------------------------------------------------------. # | ____ _ _ | # | / ___|___| | |___ | # | | | / _ \ | / __| | # | | |__| __/ | \__ \ | # | \____\___|_|_|___/ | # | | # +----------------------------------------------------------------------+ # | View cell handling classes. Each cell instanciates a multisite | # | painter to render a table cell. | # '----------------------------------------------------------------------' # A cell is an instance of a painter in a view (-> a cell or a grouping cell) class Cell(object): # Wanted to have the "parse painter spec logic" in one place (The Cell() class) # but this should be cleaned up more. TODO: Move this to another place @staticmethod def painter_exists(painter_spec): if type(painter_spec[0]) == tuple: painter_name = painter_spec[0][0] else: painter_name = painter_spec[0] return painter_name in multisite_painters # Wanted to have the "parse painter spec logic" in one place (The Cell() class) # but this should be cleaned up more. TODO: Move this to another place @staticmethod def is_join_cell(painter_spec): return len(painter_spec) >= 4 def __init__(self, view, painter_spec=None): self._view = view self._painter_name = None self._painter_params = None self._link_view_name = None self._tooltip_painter_name = None if painter_spec: self._from_view(painter_spec) # In views the painters are saved as tuples of the following formats: # # Painter name, Link view name # ('service_discovery_service', None), # # Painter name, Link view name, Hover painter name # ('host_plugin_output', None, None), # # Join column: Painter name, Link view name, hover painter name, Join service description # ('service_description', None, None, u'CPU load') # # Join column: Painter name, Link view name, hover painter name, Join service description, custom title # ('service_description', None, None, u'CPU load') # # Parameterized painters: # Same as above but instead of the "Painter name" a two element tuple with the painter name as # first element and a dictionary of parameters as second element is set. def _from_view(self, painter_spec): if type(painter_spec[0]) == tuple: self._painter_name, self._painter_params = painter_spec[0] else: self._painter_name = painter_spec[0] if painter_spec[1] != None: self._link_view_name = painter_spec[1] # Clean this call to Cell.painter_exists() up! if len(painter_spec) >= 3 and Cell.painter_exists((painter_spec[2], None)): self._tooltip_painter_name = painter_spec[2] # Get a list of columns we need to fetch in order to render this cell def needed_columns(self): columns = set(get_painter_columns(self.painter())) if self._link_view_name: # Make sure that the information about the available views is present. If # called via the reporting, then this might not be the case # TODO: Move this to some better place. views = permitted_views() if self._has_link(): link_view = self._link_view() if link_view: # TODO: Clean this up here for filt in [ visuals.get_filter(fn) for fn in visuals.get_single_info_keys(link_view) ]: columns.update(filt.link_columns) if self.has_tooltip(): columns.update(get_painter_columns(self.tooltip_painter())) return columns def is_joined(self): return False def join_service(self): return None def _has_link(self): return self._link_view_name != None def _link_view(self): try: return get_view_by_name(self._link_view_name) except KeyError: return None def painter(self): return multisite_painters[self._painter_name] def painter_name(self): return self._painter_name def export_title(self): return self._painter_name def painter_options(self): return self.painter().get("options", []) # The parameters configured in the view for this painter. In case the # painter has params, it defaults to the valuespec default value and # in case the painter has no params, it returns None. def painter_parameters(self): vs_painter_params = get_painter_params_valuespec(self.painter()) if not vs_painter_params: return if vs_painter_params and self._painter_params == None: return vs_painter_params.default_value() else: return self._painter_params def title(self, use_short=True): painter = self.painter() if use_short: return painter.get("short", painter["title"]) else: return painter["title"] # Can either be: # True : Is printable in PDF # False : Is not printable at all # "<string>" : ID of a painter_printer (Reporting module) def printable(self): return self.painter().get("printable", True) def has_tooltip(self): return self._tooltip_painter_name != None def tooltip_painter_name(self): return self._tooltip_painter_name def tooltip_painter(self): return multisite_painters[self._tooltip_painter_name] def paint_as_header(self, is_last_column_header=False): # Optional: Sort link in title cell # Use explicit defined sorter or implicit the sorter with the painter name # Important for links: # - Add the display options (Keeping the same display options as current) # - Link to _self (Always link to the current frame) classes = [] onclick = '' title = '' if display_options.enabled(display_options.L) \ and self._view.get('user_sortable', False) \ and get_sorter_name_of_painter(self.painter_name()) is not None: params = [ ('sort', self._sort_url()), ] if display_options.title_options: params.append(('display_options', display_options.title_options)) classes += [ "sort", get_primary_sorter_order(self._view, self.painter_name()) ] onclick = "location.href=\'%s\'" % html.makeuri(params, 'sort') title = _('Sort by %s') % self.title() if is_last_column_header: classes.append("last_col") html.open_th(class_=classes, onclick=onclick, title=title) html.write(self.title()) html.close_th() #html.guitest_record_output("view", ("header", title)) def _sort_url(self): """ The following sorters need to be handled in this order: 1. group by sorter (needed in grouped views) 2. user defined sorters (url sorter) 3. configured view sorters """ sorter = [] group_sort, user_sort, view_sort = get_separated_sorters(self._view) sorter = group_sort + user_sort + view_sort # Now apply the sorter of the current column: # - Negate/Disable when at first position # - Move to the first position when already in sorters # - Add in the front of the user sorters when not set sorter_name = get_sorter_name_of_painter(self.painter_name()) if self.is_joined(): # TODO: Clean this up and then remove Cell.join_service() this_asc_sorter = (sorter_name, False, self.join_service()) this_desc_sorter = (sorter_name, True, self.join_service()) else: this_asc_sorter = (sorter_name, False) this_desc_sorter = (sorter_name, True) if user_sort and this_asc_sorter == user_sort[0]: # Second click: Change from asc to desc order sorter[sorter.index(this_asc_sorter)] = this_desc_sorter elif user_sort and this_desc_sorter == user_sort[0]: # Third click: Remove this sorter sorter.remove(this_desc_sorter) else: # First click: add this sorter as primary user sorter # Maybe the sorter is already in the user sorters or view sorters, remove it for s in [ user_sort, view_sort ]: if this_asc_sorter in s: s.remove(this_asc_sorter) if this_desc_sorter in s: s.remove(this_desc_sorter) # Now add the sorter as primary user sorter sorter = group_sort + [this_asc_sorter] + user_sort + view_sort p = [] for s in sorter: if len(s) == 2: p.append((s[1] and '-' or '') + s[0]) else: p.append((s[1] and '-' or '') + s[0] + '~' + s[2]) return ','.join(p) def render(self, row): row = join_row(row, self) try: tdclass, content = self.render_content(row) except: logger.exception("Failed to render painter '%s' (Row: %r)" % (self._painter_name, row)) raise if tdclass == None: tdclass = "" if tdclass == "" and content == "": return "", "" # Add the optional link to another view if content and self._has_link(): content = link_to_view(content, row, self._link_view_name) # Add the optional mouseover tooltip if content and self.has_tooltip(): tooltip_cell = Cell(self._view, (self.tooltip_painter_name(), None)) tooltip_tdclass, tooltip_content = tooltip_cell.render_content(row) tooltip_text = html.strip_tags(tooltip_content) content = '<span title="%s">%s</span>' % (tooltip_text, content) return tdclass, content # Same as self.render() for HTML output: Gets a painter and a data # row and creates the text for being painted. def render_for_pdf(self, row, time_range): # TODO: Move this somewhere else! def find_htdocs_image_path(filename): dirs = [ cmk.paths.local_web_dir + "/htdocs/", cmk.paths.web_dir + "/htdocs/", ] for d in dirs: if os.path.exists(d + filename): return d + filename try: row = join_row(row, self) css_classes, txt = self.render_content(row) if txt is None: return css_classes, "" txt = txt.strip() # Handle <img...>. Our PDF writer cannot draw arbitrary # images, but all that we need for showing simple icons. # Current limitation: *one* image if txt.lower().startswith("<img"): img_filename = re.sub('.*src=["\']([^\'"]*)["\'].*', "\\1", str(txt)) img_path = find_htdocs_image_path(img_filename) if img_path: txt = ("icon", img_path) else: txt = img_filename if isinstance(txt, HTML): txt = "%s" % txt elif not isinstance(txt, tuple): txt = html.escaper.unescape_attributes(txt) txt = html.strip_tags(txt) return css_classes, txt except Exception: raise MKGeneralException('Failed to paint "%s": %s' % (self.painter_name(), traceback.format_exc())) def render_content(self, row): if not row: return "", "" # nothing to paint painter = self.painter() paint_func = painter["paint"] # Painters can request to get the cell object handed over. # Detect that and give the painter this argument. arg_names = inspect.getargspec(paint_func)[0] painter_args = [] for arg_name in arg_names: if arg_name == "row": painter_args.append(row) elif arg_name == "cell": painter_args.append(self) # Add optional painter arguments from painter specification if "args" in painter: painter_args += painter["args"] return painter["paint"](*painter_args) def paint(self, row, tdattrs="", is_last_cell=False): tdclass, content = self.render(row) has_content = content != "" if is_last_cell: if tdclass == None: tdclass = "last_col" else: tdclass += " last_col" if tdclass: html.write("<td %s class=\"%s\">" % (tdattrs, tdclass)) html.write(content) html.close_td() else: html.write("<td %s>" % (tdattrs)) html.write(content) html.close_td() #html.guitest_record_output("view", ("cell", content)) return has_content class JoinCell(Cell): def __init__(self, view, painter_spec): self._join_service_descr = None self._custom_title = None super(JoinCell, self).__init__(view, painter_spec) def _from_view(self, painter_spec): super(JoinCell, self)._from_view(painter_spec) if len(painter_spec) >= 4: self._join_service_descr = painter_spec[3] if len(painter_spec) == 5: self._custom_title = painter_spec[4] def is_joined(self): return True def join_service(self): return self._join_service_descr def livestatus_filter(self, join_column_name): return "Filter: %s = %s" % \ (livestatus.lqencode(join_column_name), livestatus.lqencode(self._join_service_descr)) def title(self, use_short=True): if self._custom_title: return self._custom_title else: return self._join_service_descr def export_title(self): return "%s.%s" % (self._painter_name, self.join_service()) class EmptyCell(Cell): def __init__(self, view): super(EmptyCell, self).__init__(view) def render(self, row): return "", "" def paint(self, row): return False #. # .--Table of views------------------------------------------------------. # | _____ _ _ __ _ | # | |_ _|_ _| |__ | | ___ ___ / _| __ _(_) _____ _____ | # | | |/ _` | '_ \| |/ _ \ / _ \| |_ \ \ / / |/ _ \ \ /\ / / __| | # | | | (_| | |_) | | __/ | (_) | _| \ V /| | __/\ V V /\__ \ | # | |_|\__,_|_.__/|_|\___| \___/|_| \_/ |_|\___| \_/\_/ |___/ | # | | # +----------------------------------------------------------------------+ # | Show list of all views with buttons for editing | # '----------------------------------------------------------------------' def page_edit_views(): load_views() cols = [ (_('Datasource'), lambda v: multisite_datasources[v["datasource"]]['title']) ] visuals.page_list('views', _("Edit Views"), multisite_views, cols) #. # .--Create View---------------------------------------------------------. # | ____ _ __ ___ | # | / ___|_ __ ___ __ _| |_ ___ \ \ / (_) _____ __ | # | | | | '__/ _ \/ _` | __/ _ \ \ \ / /| |/ _ \ \ /\ / / | # | | |___| | | __/ (_| | || __/ \ V / | | __/\ V V / | # | \____|_| \___|\__,_|\__\___| \_/ |_|\___| \_/\_/ | # | | # +----------------------------------------------------------------------+ # | Select the view type of the new view | # '----------------------------------------------------------------------' # First step: Select the data source # Create datasource selection valuespec, also for other modules # FIXME: Sort the datasources by (assumed) common usage def DatasourceSelection(): # FIXME: Sort the datasources by (assumed) common usage datasources = [] for ds_name, ds in multisite_datasources.items(): datasources.append((ds_name, ds['title'])) return DropdownChoice( title = _('Datasource'), help = _('The datasources define which type of objects should be displayed with this view.'), choices = datasources, sorted = True, columns = 1, default_value = 'services', ) def page_create_view(next_url = None): vs_ds = DatasourceSelection() ds = 'services' # Default selection html.header(_('Create View'), stylesheets=["pages"]) html.begin_context_buttons() back_url = html.var("back", "") html.context_button(_("Back"), back_url or "edit_views.py", "back") html.end_context_buttons() if html.var('save') and html.check_transaction(): try: ds = vs_ds.from_html_vars('ds') vs_ds.validate_value(ds, 'ds') if not next_url: next_url = html.makeuri([('datasource', ds)], filename = "create_view_infos.py") else: next_url = next_url + '&datasource=%s' % ds html.http_redirect(next_url) return except MKUserError, e: html.div(e, class_=["error"]) html.add_user_error(e.varname, e) html.begin_form('create_view') html.hidden_field('mode', 'create') forms.header(_('Select Datasource')) forms.section(vs_ds.title()) vs_ds.render_input('ds', ds) html.help(vs_ds.help()) forms.end() html.button('save', _('Continue'), 'submit') html.hidden_fields() html.end_form() html.footer() def page_create_view_infos(): ds_name = html.var('datasource') if ds_name not in multisite_datasources: raise MKGeneralException(_('The given datasource is not supported')) visuals.page_create_visual('views', multisite_datasources[ds_name]['infos'], next_url = 'edit_view.py?mode=create&datasource=%s&single_infos=%%s' % ds_name) #. # .--Edit View-----------------------------------------------------------. # | _____ _ _ _ __ ___ | # | | ____|__| (_) |_ \ \ / (_) _____ __ | # | | _| / _` | | __| \ \ / /| |/ _ \ \ /\ / / | # | | |__| (_| | | |_ \ V / | | __/\ V V / | # | |_____\__,_|_|\__| \_/ |_|\___| \_/\_/ | # | | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' # Return list of available datasources (used to render filters) def get_view_infos(view): ds_name = view.get('datasource', html.var('datasource')) return multisite_datasources[ds_name]['infos'] def page_edit_view(): load_views() visuals.page_edit_visual('views', multisite_views, custom_field_handler = render_view_config, load_handler = transform_view_to_valuespec_value, create_handler = create_view_from_valuespec, info_handler = get_view_infos, ) def view_choices(only_with_hidden = False): choices = [("", "")] for name, view in available_views.items(): if not only_with_hidden or view['single_infos']: title = format_view_title(view) choices.append(("%s" % name, title)) return choices def format_view_title(view): if view.get('mobile', False): return _('Mobile: ') + _u(view["title"]) else: return _u(view["title"]) def view_editor_options(): return [ ('mobile', _('Show this view in the Mobile GUI')), ('mustsearch', _('Show data only on search')), ('force_checkboxes', _('Always show the checkboxes')), ('user_sortable', _('Make view sortable by user')), ('play_sounds', _('Play alarm sounds')), ] def view_editor_specs(ds_name, general_properties=True): load_views() # make sure that available_views is present specs = [] if general_properties: specs.append( ('view', Dictionary( title = _('View Properties'), render = 'form', optional_keys = None, elements = [ ('datasource', FixedValue(ds_name, title = _('Datasource'), totext = multisite_datasources[ds_name]['title'], help = _('The datasource of a view cannot be changed.'), )), ('options', ListChoice( title = _('Options'), choices = view_editor_options(), default_value = ['user_sortable'], )), ('browser_reload', Integer( title = _('Automatic page reload'), unit = _('seconds'), minvalue = 0, help = _('Leave this empty or at 0 for no automatic reload.'), )), ('layout', DropdownChoice( title = _('Basic Layout'), choices = [ (k, v["title"]) for k,v in multisite_layouts.items() if not v.get("hide")], default_value = 'table', sorted = True, )), ('num_columns', Integer( title = _('Number of Columns'), default_value = 1, minvalue = 1, maxvalue = 50, )), ('column_headers', DropdownChoice( title = _('Column Headers'), choices = [ ("off", _("off")), ("pergroup", _("once per group")), ("repeat", _("repeat every 20'th row")), ], default_value = 'pergroup', )), ], )) ) def column_spec(ident, title, ds_name): painters = painters_of_datasource(ds_name) allow_empty = True empty_text = None if ident == 'columns': allow_empty = False empty_text = _("Please add at least one column to your view.") vs_column = Tuple( title = _('Column'), elements = [ CascadingDropdown( title = _('Column'), choices = painter_choices_with_params(painters), no_preselect = True, ), DropdownChoice( title = _('Link'), choices = view_choices, sorted = True, ), DropdownChoice( title = _('Tooltip'), choices = [(None, "")] + painter_choices(painters), ), ], ) join_painters = join_painters_of_datasource(ds_name) if ident == 'columns' and join_painters: join_painters = join_painters_of_datasource(ds_name) vs_column = Alternative( elements = [ vs_column, Tuple( title = _('Joined column'), help = _("A joined column can display information about specific services for " "host objects in a view showing host objects. You need to specify the " "service description of the service you like to show the data for."), elements = [ CascadingDropdown( title = _('Column'), choices = painter_choices_with_params(join_painters), no_preselect = True, ), TextUnicode( title = _('of Service'), allow_empty = False, ), DropdownChoice( title = _('Link'), choices = view_choices, sorted = True, ), DropdownChoice( title = _('Tooltip'), choices = [(None, "")] + painter_choices(join_painters), ), TextUnicode( title = _('Title'), ), ], ), ], style = 'dropdown', match = lambda x: 1 * (x is not None and len(x) == 5), ) return (ident, Dictionary( title = title, render = 'form', optional_keys = None, elements = [ (ident, ListOf(vs_column, title = title, add_label = _('Add column'), allow_empty = allow_empty, empty_text = empty_text, )), ], )) specs.append(column_spec('columns', _('Columns'), ds_name)) specs.append( ('sorting', Dictionary( title = _('Sorting'), render = 'form', optional_keys = None, elements = [ ('sorters', ListOf( Tuple( elements = [ DropdownChoice( title = _('Column'), choices = [ (name, get_painter_title_for_choices(p)) for name, p in sorters_of_datasource(ds_name).items() ], sorted = True, no_preselect = True, ), DropdownChoice( title = _('Order'), choices = [(False, _("Ascending")), (True, _("Descending"))], ), ], orientation = 'horizontal', ), title = _('Sorting'), add_label = _('Add sorter'), )), ], )), ) specs.append(column_spec('grouping', _('Grouping'), ds_name)) return specs def render_view_config(view, general_properties=True): ds_name = view.get("datasource", html.var("datasource")) if not ds_name: raise MKInternalError(_("No datasource defined.")) if ds_name not in multisite_datasources: raise MKInternalError(_('The given datasource is not supported.')) view['datasource'] = ds_name for ident, vs in view_editor_specs(ds_name, general_properties): vs.render_input(ident, view.get(ident)) # Is used to change the view structure to be compatible to # the valuespec This needs to perform the inverted steps of the # transform_valuespec_value_to_view() function. FIXME: One day we should # rewrite this to make no transform needed anymore def transform_view_to_valuespec_value(view): view["view"] = {} # Several global variables are put into a sub-dict # Only copy our known keys. Reporting element, etc. might have their own keys as well for key in [ "datasource", "browser_reload", "layout", "num_columns", "column_headers" ]: if key in view: view["view"][key] = view[key] view["view"]['options'] = [] for key, title in view_editor_options(): if view.get(key): view['view']['options'].append(key) view['visibility'] = {} for key in [ 'hidden', 'hidebutton', 'public' ]: if view.get(key): view['visibility'][key] = view[key] view['grouping'] = { "grouping" : view.get('group_painters', []) } view['sorting'] = { "sorters" : view.get('sorters', {}) } columns = [] view['columns'] = { "columns" : columns } for entry in view.get('painters', []): if len(entry) == 5: pname, viewname, tooltip, join_index, col_title = entry columns.append((pname, join_index, viewname, tooltip or None, col_title)) elif len(entry) == 4: pname, viewname, tooltip, join_index = entry columns.append((pname, join_index, viewname, tooltip or None, '')) elif len(entry) == 3: pname, viewname, tooltip = entry columns.append((pname, viewname, tooltip or None)) else: pname, viewname = entry columns.append((pname, viewname, None)) def transform_valuespec_value_to_view(view): for ident, attrs in view.items(): # Transform some valuespec specific options to legacy view # format. We do not want to change the view data structure # at the moment. if ident == 'view': if "options" in attrs: # First set all options to false for option in dict(view_editor_options()).keys(): view[option] = False # Then set the selected single options for option in attrs['options']: view[option] = True # And cleanup del attrs['options'] view.update(attrs) del view["view"] elif ident == 'sorting': view.update(attrs) del view["sorting"] elif ident == 'grouping': view['group_painters'] = attrs['grouping'] del view["grouping"] elif ident == 'columns': painters = [] for column in attrs['columns']: if len(column) == 5: pname, join_index, viewname, tooltip, col_title = column else: pname, viewname, tooltip = column join_index, col_title = None, None viewname = viewname if viewname else None if join_index and col_title: painters.append((pname, viewname, tooltip, join_index, col_title)) elif join_index: painters.append((pname, viewname, tooltip, join_index)) else: painters.append((pname, viewname, tooltip)) view['painters'] = painters del view["columns"] # Extract properties of view from HTML variables and construct # view object, to be used for saving or displaying # # old_view is the old view dict which might be loaded from storage. # view is the new dict object to be updated. def create_view_from_valuespec(old_view, view): ds_name = old_view.get('datasource', html.var('datasource')) view['datasource'] = ds_name vs_value = {} for ident, vs in view_editor_specs(ds_name): attrs = vs.from_html_vars(ident) vs.validate_value(attrs, ident) vs_value[ident] = attrs transform_valuespec_value_to_view(vs_value) view.update(vs_value) return view #. # .--Display View--------------------------------------------------------. # | ____ _ _ __ ___ | # | | _ \(_)___ _ __ | | __ _ _ _ \ \ / (_) _____ __ | # | | | | | / __| '_ \| |/ _` | | | | \ \ / /| |/ _ \ \ /\ / / | # | | |_| | \__ \ |_) | | (_| | |_| | \ V / | | __/\ V V / | # | |____/|_|___/ .__/|_|\__,_|\__, | \_/ |_|\___| \_/\_/ | # | |_| |___/ | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' def show_filter(f): if not f.visible(): html.open_div(style="display:none;") f.display() html.close_div() else: visuals.show_filter(f) def show_filter_form(is_open, filters): # Table muss einen anderen Namen, als das Formular html.open_div(id_="filters", class_=["view_form"], style="display: none;" if not is_open else None) html.begin_form("filter") html.open_table(class_=["filterform"], cellpadding="0", cellspacing="0", border="0") html.open_tr() html.open_td() # sort filters according to title s = [(f.sort_index, f.title, f) for f in filters if f.available()] s.sort() # First show filters with double height (due to better floating # layout) for sort_index, title, f in s: if f.double_height(): show_filter(f) # Now single height filters for sort_index, title, f in s: if not f.double_height(): show_filter(f) html.close_td() html.close_tr() html.open_tr() html.open_td() html.button("search", _("Search"), "submit") html.close_td() html.close_tr() html.close_table() html.hidden_fields() html.end_form() html.close_div() def page_view(): bi.reset_cache_status() # needed for status icon load_views() view_name = html.var("view_name") if view_name == None: raise MKGeneralException(_("Missing the variable view_name in the URL.")) view = available_views.get(view_name) if not view: raise MKGeneralException(_("No view defined with the name '%s'.") % html.attrencode(view_name)) # Gather the page context which is needed for the "add to visual" popup menu # to add e.g. views to dashboards or reports datasource = multisite_datasources[view['datasource']] context = visuals.get_context_from_uri_vars(datasource['infos']) context.update(visuals.get_singlecontext_html_vars(view)) html.set_page_context(context) prepare_painter_options(view_name) painter_options.update_from_url(view) show_view(view, True, True, True) def get_painter_columns(painter): if type(lambda: None) == type(painter["columns"]): return painter["columns"]() else: return painter["columns"] # Display view with real data. This is *the* function everying # is about. def show_view(view, show_heading = False, show_buttons = True, show_footer = True, render_function = None, only_count=False, all_filters_active=False, limit=None): weblib.prepare_display_options(globals()) # Load from hard painter options > view > hard coded default num_columns = painter_options.get("num_columns", view.get("num_columns", 1)) browser_reload = painter_options.get("refresh", view.get("browser_reload", None)) force_checkboxes = view.get("force_checkboxes", False) show_checkboxes = force_checkboxes or html.var('show_checkboxes', '0') == '1' # Get the datasource (i.e. the logical table) try: datasource = multisite_datasources[view["datasource"]] except KeyError: if view["datasource"].startswith("mkeventd_"): raise MKUserError(None, _("The Event Console view '%s' can not be rendered. The Event Console is possibly " "disabled.") % view["name"]) else: raise MKUserError(None, _("The view '%s' using the datasource '%s' can not be rendered " "because the datasource does not exist.") % (view["name"], view["datasource"])) tablename = datasource["table"] # Filters to use in the view # In case of single object views, the needed filters are fixed, but not always present # in context. In this case, take them from the context type definition. use_filters = visuals.filters_of_visual(view, datasource['infos'], all_filters_active, datasource.get('link_filters', {})) # Not all filters are really shown later in show_filter_form(), because filters which # have a hardcoded value are not changeable by the user show_filters = visuals.visible_filters_of_visual(view, use_filters) # FIXME TODO HACK to make grouping single contextes possible on host/service infos # Is hopefully cleaned up soon. if view['datasource'] in ['hosts', 'services']: if html.has_var('hostgroup') and not html.has_var("opthost_group"): html.set_var("opthost_group", html.var("hostgroup")) if html.has_var('servicegroup') and not html.has_var("optservice_group"): html.set_var("optservice_group", html.var("servicegroup")) # TODO: Another hack :( Just like the above one: When opening the view "ec_events_of_host", # which is of single context "host" using a host name of a unrelated event, the list of # events is always empty since the single context filter "host" is sending a "host_name = ..." # filter to livestatus which is not matching a "unrelated event". Instead the filter event_host # needs to be used. # But this may only be done for the unrelated events view. The "ec_events_of_monhost" view still # needs the filter. :-/ # Another idea: We could change these views to non single context views, but then we would not # be able to show the buttons to other host related views, which is also bad. So better stick # with the current mode. if view["datasource"] in [ "mkeventd_events", "mkeventd_history" ] \ and "host" in view["single_infos"] and view["name"] != "ec_events_of_monhost": # Remove the original host name filter use_filters = [ f for f in use_filters if f.name != "host" ] # Set the value for the event host filter if not html.has_var("event_host"): html.set_var("event_host", html.var("host")) # Now populate the HTML vars with context vars from the view definition. Hard # coded default values are treated differently: # # a) single context vars of the view are enforced # b) multi context vars can be overwritten by existing HTML vars visuals.add_context_to_uri_vars(view, datasource["infos"], only_count) # Check that all needed information for configured single contexts are available visuals.verify_single_contexts('views', view, datasource.get('link_filters', {})) # Prepare Filter headers for Livestatus # TODO: When this is used by the reporting then *all* filters are # active. That way the inventory data will always be loaded. When # we convert this to the visuals principle the we need to optimize # this. filterheaders = "" all_active_filters = [ f for f in use_filters if f.available() ] for filt in all_active_filters: header = filt.filter(tablename) filterheaders += header # Apply the site hint / filter if html.var("site"): only_sites = [html.var("site")] else: only_sites = None # Prepare limit: # We had a problem with stats queries on the logtable where # the limit was not applied on the resulting rows but on the # lines of the log processed. This resulted in wrong stats. # For these datasources we ignore the query limits. if limit == None: # Otherwise: specified as argument if not datasource.get('ignore_limit', False): limit = get_limit() # Fork to availability view. We just need the filter headers, since we do not query the normal # hosts and service table, but "statehist". This is *not* true for BI availability, though (see later) if html.var("mode") == "availability" and ( "aggr" not in datasource["infos"] or html.var("timeline_aggr")): context = visuals.get_context_from_uri_vars(datasource['infos']) context.update(visuals.get_singlecontext_html_vars(view)) return render_availability_page(view, datasource, context, filterheaders, only_sites, limit) query = filterheaders + view.get("add_headers", "") # Sorting - use view sorters and URL supplied sorters if not only_count: user_sorters = parse_url_sorters(html.var("sort")) if user_sorters: sorter_list = user_sorters else: sorter_list = view["sorters"] sorters = [ (multisite_sorters[s[0]],) + s[1:] for s in sorter_list if s[0] in multisite_sorters ] else: sorters = [] # Prepare cells of the view # Group cells: Are displayed as titles of grouped rows # Regular cells: Are displaying information about the rows of the type the view is about # Join cells: Are displaying information of a joined source (e.g.service data on host views) group_cells = get_group_cells(view) cells = get_cells(view) regular_cells = get_regular_cells(cells) join_cells = get_join_cells(cells) # Now compute the list of all columns we need to query via Livestatus. # Those are: (1) columns used by the sorters in use, (2) columns use by # column- and group-painters in use and - note - (3) columns used to # satisfy external references (filters) of views we link to. The last bit # is the trickiest. Also compute this list of view options use by the # painters columns = get_needed_regular_columns(group_cells + cells, sorters, datasource) join_columns = get_needed_join_columns(join_cells, sorters, datasource) # Fetch data. Some views show data only after pressing [Search] if (only_count or (not view.get("mustsearch")) or html.var("filled_in") in ["filter", 'actions', 'confirm', 'painteroptions']): # names for additional columns (through Stats: headers) add_columns = datasource.get("add_columns", []) # tablename may be a function instead of a livestatus tablename # In that case that function is used to compute the result. # It may also be a tuple. In this case the first element is a function and the second element # is a list of argument to hand over to the function together with all other arguments that # are passed to query_data(). if type(tablename) == type(lambda x:None): rows = tablename(columns, query, only_sites, limit, all_active_filters) elif type(tablename) == tuple: func, args = tablename rows = func(datasource, columns, add_columns, query, only_sites, limit, *args) else: rows = query_data(datasource, columns, add_columns, query, only_sites, limit) # Now add join information, if there are join columns if join_cells: do_table_join(datasource, rows, filterheaders, join_cells, join_columns, only_sites) # If any painter, sorter or filter needs the information about the host's # inventory, then we load it and attach it as column "host_inventory" if is_inventory_data_needed(group_cells, cells, sorters, all_active_filters): for row in rows: if "host_name" in row: row["host_inventory"] = inventory.load_tree(row["host_name"]) sort_data(rows, sorters) else: rows = [] # Apply non-Livestatus filters for filter in all_active_filters: rows = filter.filter_table(rows) if html.var("mode") == "availability": render_bi_availability(view_title(view), rows) return # TODO: Use livestatus Stats: instead of fetching rows! if only_count: for fname, filter_vars in view["context"].items(): for varname, value in filter_vars.items(): html.del_var(varname) return len(rows) # The layout of the view: it can be overridden by several specifying # an output format (like json or python). Note: the layout is not # always needed. In case of an embedded view in the reporting this # field is simply missing, because the rendering is done by the # report itself. # TODO: CSV export should be handled by the layouts. It cannot # be done generic in most cases if html.output_format == "html": if "layout" in view: layout = multisite_layouts[view["layout"]] else: layout = None else: if "layout" in view and "csv_export" in multisite_layouts[view["layout"]]: multisite_layouts[view["layout"]]["csv_export"](rows, view, group_cells, cells) return else: # Generic layout of export layout = multisite_layouts.get(html.output_format) if not layout: layout = multisite_layouts["json"] # Set browser reload if browser_reload and display_options.enabled(display_options.R) and not only_count: html.set_browser_reload(browser_reload) # Until now no single byte of HTML code has been output. # Now let's render the view. The render_function will be # replaced by the mobile interface for an own version. if not render_function: render_function = render_view render_function(view, rows, datasource, group_cells, cells, show_heading, show_buttons, show_checkboxes, layout, num_columns, show_filters, show_footer, browser_reload) def get_group_cells(view): return [ Cell(view, e) for e in view["group_painters"] if Cell.painter_exists(e) ] def get_cells(view): cells = [] for e in view["painters"]: if not Cell.painter_exists(e): continue if Cell.is_join_cell(e): cells.append(JoinCell(view, e)) else: cells.append(Cell(view, e)) return cells def get_join_cells(cell_list): return filter(lambda x: type(x) == JoinCell, cell_list) def get_regular_cells(cell_list): return filter(lambda x: type(x) == Cell, cell_list) def get_needed_regular_columns(cells, sorters, datasource): # BI availability needs aggr_tree # TODO: wtf? a full reset of the list? Move this far away to a special place! if html.var("mode") == "availability" and "aggr" in datasource["infos"]: return [ "aggr_tree", "aggr_name", "aggr_group" ] columns = columns_of_cells(cells) # Columns needed for sorters # TODO: Move sorter parsing and logic to something like Cells() for s in sorters: if len(s) == 2: columns.update(s[0]["columns"]) # Add key columns, needed for executing commands columns.update(datasource["keys"]) # Add idkey columns, needed for identifying the row columns.update(datasource["idkeys"]) # Remove (implicit) site column try: columns.remove("site") except KeyError: pass return list(columns) def get_needed_join_columns(join_cells, sorters, datasource): join_columns = columns_of_cells(join_cells) # Columns needed for sorters # TODO: Move sorter parsing and logic to something like Cells() for s in sorters: if len(s) != 2: join_columns.update(s[0]["columns"]) return list(join_columns) def is_inventory_data_needed(group_cells, cells, sorters, all_active_filters): for cell in cells: if cell.has_tooltip(): if cell.tooltip_painter_name().startswith("inv_"): return True for s in sorters: if s[0].get("load_inv"): return True for cell in group_cells + cells: if cell.painter().get("load_inv"): return True for filt in all_active_filters: if filt.need_inventory(): return True return False def columns_of_cells(cells): columns = set([]) for cell in cells: columns.update(cell.needed_columns()) return columns # Output HTML code of a view. If you add or remove paramters here, # then please also do this in htdocs/mobile.py! def render_view(view, rows, datasource, group_painters, painters, show_heading, show_buttons, show_checkboxes, layout, num_columns, show_filters, show_footer, browser_reload): if html.transaction_valid() and html.do_actions(): html.set_browser_reload(0) # Show heading (change between "preview" mode and full page mode) if show_heading: # Show/Hide the header with page title, MK logo, etc. if display_options.enabled(display_options.H): # FIXME: view/layout/module related stylesheets/javascripts e.g. in case of BI? html.body_start(view_title(view), stylesheets=["pages","views","status","bi"]) if display_options.enabled(display_options.T): html.top_heading(view_title(view)) has_done_actions = False row_count = len(rows) # This is a general flag which makes the command form render when the current # view might be able to handle commands. When no commands are possible due missing # permissions or datasources without commands, the form is not rendered command_form = should_show_command_form(datasource) if command_form: weblib.init_selection() # Is the layout able to display checkboxes? can_display_checkboxes = layout.get('checkboxes', False) if show_buttons: show_combined_graphs_button = \ ("host" in datasource["infos"] or "service" in datasource["infos"]) and \ (type(datasource["table"]) == str) and \ ("host" in datasource["table"] or "service" in datasource["table"]) show_context_links(view, datasource, show_filters, # Take into account: permissions, display_options row_count > 0 and command_form, # Take into account: layout capabilities can_display_checkboxes and not view.get("force_checkboxes"), show_checkboxes, # Show link to availability datasource["table"] in [ "hosts", "services" ] or "aggr" in datasource["infos"], # Show link to combined graphs show_combined_graphs_button,) # User errors in filters html.show_user_errors() # Filter form filter_isopen = view.get("mustsearch") and not html.var("filled_in") if display_options.enabled(display_options.F) and len(show_filters) > 0: show_filter_form(filter_isopen, show_filters) # Actions if command_form: # If we are currently within an action (confirming or executing), then # we display only the selected rows (if checkbox mode is active) if show_checkboxes and html.do_actions(): rows = filter_selected_rows(view, rows, weblib.get_rowselection('view-' + view['name'])) # There are one shot actions which only want to affect one row, filter the rows # by this id during actions if html.has_var("_row_id") and html.do_actions(): rows = filter_by_row_id(view, rows) if html.do_actions() and html.transaction_valid(): # submit button pressed, no reload try: # Create URI with all actions variables removed backurl = html.makeuri([], delvars=['filled_in', 'actions']) has_done_actions = do_actions(view, datasource["infos"][0], rows, backurl) except MKUserError, e: html.show_error(e) html.add_user_error(e.varname, e) if display_options.enabled(display_options.C): show_command_form(True, datasource) elif display_options.enabled(display_options.C): # (*not* display open, if checkboxes are currently shown) show_command_form(False, datasource) # Also execute commands in cases without command form (needed for Python- # web service e.g. for NagStaMon) elif row_count > 0 and config.user.may("general.act") \ and html.do_actions() and html.transaction_valid(): # There are one shot actions which only want to affect one row, filter the rows # by this id during actions if html.has_var("_row_id") and html.do_actions(): rows = filter_by_row_id(view, rows) try: do_actions(view, datasource["infos"][0], rows, '') except: pass # currently no feed back on webservice painter_options.show_form(view) # The refreshing content container if display_options.enabled(display_options.R): html.open_div(id_="data_container") if not has_done_actions: # Limit exceeded? Show warning if display_options.enabled(display_options.W): check_limit(rows, get_limit()) layout["render"](rows, view, group_painters, painters, num_columns, show_checkboxes and not html.do_actions()) headinfo = "%d %s" % (row_count, _("row") if row_count == 1 else _("rows")) if show_checkboxes: selected = filter_selected_rows(view, rows, weblib.get_rowselection('view-' + view['name'])) headinfo = "%d/%s" % (len(selected), headinfo) if html.output_format == "html": html.javascript("update_headinfo('%s');" % headinfo) # The number of rows might have changed to enable/disable actions and checkboxes if show_buttons: update_context_links( # don't take display_options into account here ('c' is set during reload) row_count > 0 and should_show_command_form(datasource, ignore_display_option=True), # and not html.do_actions(), can_display_checkboxes ) # Play alarm sounds, if critical events have been displayed if display_options.enabled(display_options.S) and view.get("play_sounds"): play_alarm_sounds() else: # Always hide action related context links in this situation update_context_links(False, False) # In multi site setups error messages of single sites do not block the # output and raise now exception. We simply print error messages here. # In case of the web service we show errors only on single site installations. if config.show_livestatus_errors \ and display_options.enabled(display_options.W) \ and html.output_format == "html": for sitename, info in sites.live().dead_sites().items(): html.show_error("<b>%s - %s</b><br>%s" % (info["site"]["alias"], _('Livestatus error'), info["exception"])) # FIXME: Sauberer waere noch die Status Icons hier mit aufzunehmen if display_options.enabled(display_options.R): html.close_div() if show_footer: pid = os.getpid() if sites.live().successfully_persisted(): html.add_status_icon("persist", _("Reused persistent livestatus connection from earlier request (PID %d)") % pid) if bi.reused_compilation(): html.add_status_icon("aggrcomp", _("Reused cached compiled BI aggregations (PID %d)") % pid) html.bottom_focuscode() if display_options.enabled(display_options.Z): html.bottom_footer() if display_options.enabled(display_options.H): html.body_end() def check_limit(rows, limit): count = len(rows) if limit != None and count >= limit + 1: text = _("Your query produced more than %d results. ") % limit if html.var("limit", "soft") == "soft" and config.user.may("general.ignore_soft_limit"): text += html.render_a(_('Repeat query and allow more results.'), target="_self", href=html.makeuri([("limit", "hard")])) elif html.var("limit") == "hard" and config.user.may("general.ignore_hard_limit"): text += html.render_a(_('Repeat query without limit.'), target="_self", href=html.makeuri([("limit", "none")])) text += " " + _("<b>Note:</b> the shown results are incomplete and do not reflect the sort order.") html.show_warning(text) del rows[limit:] return False return True def do_table_join(master_ds, master_rows, master_filters, join_cells, join_columns, only_sites): join_table, join_master_column = master_ds["join"] slave_ds = multisite_datasources[join_table] join_slave_column = slave_ds["joinkey"] # Create additional filters join_filters = [] for cell in join_cells: join_filters.append(cell.livestatus_filter(join_slave_column)) join_filters.append("Or: %d" % len(join_filters)) query = "%s%s\n" % (master_filters, "\n".join(join_filters)) rows = query_data(slave_ds, [join_master_column, join_slave_column] + join_columns, [], query, only_sites, None) per_master_entry = {} current_key = None current_entry = None for row in rows: master_key = (row["site"], row[join_master_column]) if master_key != current_key: current_key = master_key current_entry = {} per_master_entry[current_key] = current_entry current_entry[row[join_slave_column]] = row # Add this information into master table in artificial column "JOIN" for row in master_rows: key = (row["site"], row[join_master_column]) joininfo = per_master_entry.get(key, {}) row["JOIN"] = joininfo g_alarm_sound_states = set([]) def clear_alarm_sound_states(): g_alarm_sound_states.clear() def save_state_for_playing_alarm_sounds(row): if not config.enable_sounds or not config.sounds: return # TODO: Move this to a generic place. What about -1? host_state_map = { 0: "up", 1: "down", 2: "unreachable"} service_state_map = { 0: "up", 1: "warning", 2: "critical", 3: "unknown"} for state_map, state in [ (host_state_map, row.get("host_hard_state", row.get("host_state"))), (service_state_map, row.get("service_last_hard_state", row.get("service_state"))) ]: if state is None: continue try: state_name = state_map[int(state)] except KeyError: continue g_alarm_sound_states.add(state_name) def play_alarm_sounds(): if not config.enable_sounds or not config.sounds: return url = config.sound_url if not url.endswith("/"): url += "/" for state_name, wav in config.sounds: if not state_name or state_name in g_alarm_sound_states: html.play_sound(url + wav) break # only one sound at one time # How many data rows may the user query? def get_limit(): limitvar = html.var("limit", "soft") if limitvar == "hard" and config.user.may("general.ignore_soft_limit"): return config.hard_query_limit elif limitvar == "none" and config.user.may("general.ignore_hard_limit"): return None else: return config.soft_query_limit def view_title(view): return visuals.visual_title('view', view) def view_optiondial(view, option, choices, help): # Darn: The option "refresh" has the name "browser_reload" in the # view definition if option == "refresh": name = "browser_reload" else: name = option # Take either the first option of the choices, the view value or the # configured painter option. value = painter_options.get(option, dflt=view.get(name, choices[0][0])) title = dict(choices).get(value, value) html.begin_context_buttons() # just to be sure # Remove unicode strings choices = [ [c[0], str(c[1])] for c in choices ] html.open_div(id_="optiondial_%s" % option, class_=["optiondial", option, "val_%s" % value], title=help, onclick="view_dial_option(this, \'%s\', \'%s\', %r)" % (view["name"], option, choices)) html.div(title) html.close_div() html.final_javascript("init_optiondial('optiondial_%s');" % option) def view_optiondial_off(option): html.div('', class_=["optiondial", "off", option]) # FIXME: Consolidate with html.toggle_button() rendering functions def toggler(id, icon, help, onclick, value, hidden = False): html.begin_context_buttons() # just to be sure hide = ' style="display:none"' if hidden else '' html.write('<div id="%s_on" title="%s" class="togglebutton %s %s" %s>' '<a href="javascript:void(0)" onclick="%s"><img src="images/icon_%s.png"></a></div>' % ( id, help, icon, value and "down" or "up", hide, onclick, icon)) # Will be called when the user presses the upper button, in order # to persist the new setting - and to make it active before the # browser reload of the DIV containing the actual status data is done. def ajax_set_viewoption(): view_name = html.var("view_name") option = html.var("option") value = html.var("value") value = { 'true' : True, 'false' : False }.get(value, value) if type(value) == str and value[0].isdigit(): try: value = int(value) except: pass po = PainterOptions(view_name) po.load() po.set(option, value) po.save_to_config() def show_context_links(thisview, datasource, show_filters, enable_commands, enable_checkboxes, show_checkboxes, show_availability, show_combined_graphs): # html.begin_context_buttons() called automatically by html.context_button() # That way if no button is painted we avoid the empty container if display_options.enabled(display_options.B): execute_hooks('buttons-begin') filter_isopen = html.var("filled_in") != "filter" and thisview.get("mustsearch") if display_options.enabled(display_options.F): if html.var("filled_in") == "filter": icon = "filters_set" help = _("The current data is being filtered") else: icon = "filters" help = _("Set a filter for refining the shown data") html.toggle_button("filters", filter_isopen, icon, help, disabled=not show_filters) if display_options.enabled(display_options.D): html.toggle_button("painteroptions", False, "painteroptions", _("Modify display options"), disabled=not painter_options.painter_option_form_enabled()) if display_options.enabled(display_options.C): html.toggle_button("commands", False, "commands", _("Execute commands on hosts, services and other objects"), hidden = not enable_commands) html.toggle_button("commands", False, "commands", "", hidden=enable_commands, disabled=True) selection_enabled = (enable_commands and enable_checkboxes) or thisview.get("force_checkboxes") if not thisview.get("force_checkboxes"): toggler("checkbox", "checkbox", _("Enable/Disable checkboxes for selecting rows for commands"), "location.href='%s';" % html.makeuri([('show_checkboxes', show_checkboxes and '0' or '1')]), show_checkboxes, hidden = True) # not selection_enabled) html.toggle_button("checkbox", False, "checkbox", "", hidden=not thisview.get("force_checkboxes"), disabled=True) html.javascript('g_selection_enabled = %s;' % ('true' if selection_enabled else 'false')) if display_options.enabled(display_options.O): if config.user.may("general.view_option_columns"): choices = [ [x, "%s" % x] for x in config.view_option_columns ] view_optiondial(thisview, "num_columns", choices, _("Change the number of display columns")) else: view_optiondial_off("num_columns") if display_options.enabled(display_options.R) and config.user.may("general.view_option_refresh"): choices = [ [x, {0:_("off")}.get(x, str(x) + "s") ] for x in config.view_option_refreshes ] view_optiondial(thisview, "refresh", choices, _("Change the refresh rate")) else: view_optiondial_off("refresh") if display_options.enabled(display_options.B): # WATO: If we have a host context, then show button to WATO, if permissions allow this if html.has_var("host") \ and config.wato_enabled \ and config.user.may("wato.use") \ and (config.user.may("wato.hosts") or config.user.may("wato.seeall")): host = html.var("host") if host: url = wato.link_to_host_by_name(host) else: url = wato.link_to_folder_by_path(html.var("wato_folder", "")) html.context_button(_("WATO"), url, "wato", id="wato", bestof = config.context_buttons_to_show) # Button for creating an instant report (if reporting is available) if config.reporting_available() and config.user.may("general.reporting"): html.context_button(_("Export as PDF"), html.makeuri([], filename="report_instant.py"), "report", class_="context_pdf_export") # Buttons to other views, dashboards, etc. links = visuals.collect_context_links(thisview) for linktitle, uri, icon, buttonid in links: html.context_button(linktitle, url=uri, icon=icon, id=buttonid, bestof=config.context_buttons_to_show) # Customize/Edit view button if display_options.enabled(display_options.E) and config.user.may("general.edit_views"): url_vars = [ ("back", html.requested_url()), ("load_name", thisview["name"]), ] if thisview["owner"] != config.user.id: url_vars.append(("load_user", thisview["owner"])) url = html.makeuri_contextless(url_vars, filename="edit_view.py") html.context_button(_("Edit View"), url, "edit", id="edit", bestof=config.context_buttons_to_show) if display_options.enabled(display_options.E): if show_availability: html.context_button(_("Availability"), html.makeuri([("mode", "availability")]), "availability") if show_combined_graphs and config.combined_graphs_available(): html.context_button(_("Combined graphs"), html.makeuri([ ("single_infos", ",".join(thisview["single_infos"])), ("datasource", thisview["datasource"]), ("view_title", view_title(thisview)), ], filename="combined_graphs.py"), "pnp") if display_options.enabled(display_options.B): execute_hooks('buttons-end') html.end_context_buttons() def update_context_links(enable_command_toggle, enable_checkbox_toggle): html.javascript("update_togglebutton('commands', %d);" % (enable_command_toggle and 1 or 0)) html.javascript("update_togglebutton('checkbox', %d);" % (enable_command_toggle and enable_checkbox_toggle and 1 or 0, )) def ajax_count_button(): id = html.var("id") counts = config.user.load_file("buttoncounts", {}) for i in counts: counts[i] *= 0.95 counts.setdefault(id, 0) counts[id] += 1 config.user.save_file("buttoncounts", counts) # Retrieve data via livestatus, convert into list of dicts, # prepare row-function needed for painters # datasource: the datasource object as defined in plugins/views/datasources.py # columns: the list of livestatus columns to query # add_columns: list of columns the datasource is known to add itself # (couldn't we get rid of this parameter by looking that up ourselves?) # add_headers: additional livestatus headers to add # only_sites: list of sites the query is limited to # limit: maximum number of data rows to query def query_data(datasource, columns, add_columns, add_headers, only_sites = None, limit = None, tablename=None): if only_sites is None: only_sites = [] if tablename == None: tablename = datasource["table"] add_headers += datasource.get("add_headers", "") merge_column = datasource.get("merge_by") if merge_column: columns = [merge_column] + columns # Most layouts need current state of object in order to # choose background color - even if no painter for state # is selected. Make sure those columns are fetched. This # must not be done for the table 'log' as it cannot correctly # distinguish between service_state and host_state if "log" not in datasource["infos"]: state_columns = [] if "service" in datasource["infos"]: state_columns += [ "service_has_been_checked", "service_state" ] if "host" in datasource["infos"]: state_columns += [ "host_has_been_checked", "host_state" ] for c in state_columns: if c not in columns: columns.append(c) auth_domain = datasource.get("auth_domain", "read") # Remove columns which are implicitely added by the datasource columns = [ c for c in columns if c not in add_columns ] query = "GET %s\n" % tablename rows = do_query_data(query, columns, add_columns, merge_column, add_headers, only_sites, limit, auth_domain) # Datasource may have optional post processing function to filter out rows post_process_func = datasource.get("post_process") if post_process_func: return post_process_func(rows) else: return rows def do_query_data(query, columns, add_columns, merge_column, add_headers, only_sites, limit, auth_domain): query += "Columns: %s\n" % " ".join(columns) query += add_headers sites.live().set_prepend_site(True) if limit != None: sites.live().set_limit(limit + 1) # + 1: We need to know, if limit is exceeded else: sites.live().set_limit(None) if config.debug_livestatus_queries \ and html.output_format == "html" and display_options.enabled(display_options.W): html.open_div(class_=["livestatus", "message"]) html.tt(query.replace('\n', '<br>\n')) html.close_div() if only_sites: sites.live().set_only_sites(only_sites) sites.live().set_auth_domain(auth_domain) data = sites.live().query(query) sites.live().set_auth_domain("read") sites.live().set_only_sites(None) sites.live().set_prepend_site(False) sites.live().set_limit() # removes limit if merge_column: data = merge_data(data, columns) # convert lists-rows into dictionaries. # performance, but makes live much easier later. columns = ["site"] + columns + add_columns rows = [ dict(zip(columns, row)) for row in data ] return rows # Merge all data rows with different sites but the same value # in merge_column. We require that all column names are prefixed # with the tablename. The column with the merge key is required # to be the *second* column (right after the site column) def merge_data(data, columns): merged = {} mergefuncs = [lambda a,b: ""] # site column is not merged def worst_service_state(a, b): if a == 2 or b == 2: return 2 else: return max(a, b) def worst_host_state(a, b): if a == 1 or b == 1: return 1 else: return max(a, b) for c in columns: tablename, col = c.split("_", 1) if col.startswith("num_") or col.startswith("members"): mergefunc = lambda a,b: a+b elif col.startswith("worst_service"): return worst_service_state elif col.startswith("worst_host"): return worst_host_state else: mergefunc = lambda a,b: a mergefuncs.append(mergefunc) for row in data: mergekey = row[1] if mergekey in merged: oldrow = merged[mergekey] merged[mergekey] = [ f(a,b) for f,a,b in zip(mergefuncs, oldrow, row) ] else: merged[mergekey] = row # return all rows sorted according to merge key mergekeys = merged.keys() mergekeys.sort() return [ merged[k] for k in mergekeys ] # Sort data according to list of sorters. The tablename # is needed in order to handle different column names # for same objects (e.g. host_name in table services and # simply name in table hosts) def sort_data(data, sorters): if len(sorters) == 0: return # Handle case where join columns are not present for all rows def save_compare(compfunc, row1, row2, args): if row1 == None and row2 == None: return 0 elif row1 == None: return -1 elif row2 == None: return 1 else: if args: return compfunc(row1, row2, *args) else: return compfunc(row1, row2) sort_cmps = [] for s in sorters: cmpfunc = s[0]["cmp"] negate = -1 if s[1] else 1 if len(s) > 2: joinkey = s[2] # e.g. service description else: joinkey = None sort_cmps.append((cmpfunc, negate, joinkey, s[0].get('args'))) def multisort(e1, e2): for func, neg, joinkey, args in sort_cmps: if joinkey: # Sorter for join column, use JOIN info c = neg * save_compare(func, e1["JOIN"].get(joinkey), e2["JOIN"].get(joinkey), args) else: if args: c = neg * func(e1, e2, *args) else: c = neg * func(e1, e2) if c != 0: return c return 0 # equal data.sort(multisort) def sorters_of_datasource(ds_name): return allowed_for_datasource(multisite_sorters, ds_name) def painters_of_datasource(ds_name): return allowed_for_datasource(multisite_painters, ds_name) def join_painters_of_datasource(ds_name): ds = multisite_datasources[ds_name] if "join" not in ds: return {} # no joining with this datasource # Get the painters allowed for the join "source" and "target" painters = painters_of_datasource(ds_name) join_painters_unfiltered = allowed_for_datasource(multisite_painters, ds['join'][0]) # Filter out painters associated with the "join source" datasource join_painters = {} for key, val in join_painters_unfiltered.items(): if key not in painters: join_painters[key] = val return join_painters # Filters a list of sorters or painters and decides which of # those are available for a certain data source def allowed_for_datasource(collection, datasourcename): datasource = multisite_datasources[datasourcename] infos_available = set(datasource["infos"]) add_columns = datasource.get("add_columns", []) allowed = {} for name, item in collection.items(): infos_needed = infos_needed_by_painter(item, add_columns) if len(infos_needed.difference(infos_available)) == 0: allowed[name] = item return allowed def infos_needed_by_painter(painter, add_columns=None): if add_columns is None: add_columns = [] columns = get_painter_columns(painter) return set([ c.split("_", 1)[0] for c in columns if c != "site" and c not in add_columns]) # Returns either the valuespec of the painter parameters or None def get_painter_params_valuespec(painter): if "params" not in painter: return if type(lambda: None) == type(painter["params"]): return painter["params"]() else: return painter["params"] def painter_choices(painters, add_params=False): choices = [] for name, painter in painters.items(): title = get_painter_title_for_choices(painter) # Add the optional valuespec for painter parameters if add_params and "params" in painter: vs_params = get_painter_params_valuespec(painter) choices.append((name, title, vs_params)) else: choices.append((name, title)) return sorted(choices, key=lambda x: x[1]) def get_painter_title_for_choices(painter): info_title = "/".join([ visuals.infos[info_name]["title_plural"] for info_name in sorted(infos_needed_by_painter(painter)) ]) # TODO: Cleanup the special case for sites. How? Add an info for it? if painter["columns"] == ["site"]: info_title = _("Site") return "%s: %s" % (info_title, painter["title"]) def painter_choices_with_params(painters): return painter_choices(painters, add_params=True) #. # .--Commands------------------------------------------------------------. # | ____ _ | # | / ___|___ _ __ ___ _ __ ___ __ _ _ __ __| |___ | # | | | / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` / __| | # | | |__| (_) | | | | | | | | | | | (_| | | | | (_| \__ \ | # | \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_|___/ | # | | # +----------------------------------------------------------------------+ # | Functions dealing with external commands send to the monitoring | # | core. The commands themselves are defined as a plugin. Shipped | # | command definitions are in plugins/views/commands.py. | # | We apologize for the fact that we one time speak of "commands" and | # | the other time of "action". Both is the same here... | # '----------------------------------------------------------------------' # Checks whether or not this view handles commands for the current user # When it does not handle commands the command tab, command form, row # selection and processing commands is disabled. def should_show_command_form(datasource, ignore_display_option=False): if not ignore_display_option and display_options.disabled(display_options.C): return False if not config.user.may("general.act"): return False # What commands are available depends on the Livestatus table we # deal with. If a data source provides information about more # than one table, (like services datasource also provide host # information) then the first info is the primary table. So 'what' # will be one of "host", "service", "command" or "downtime". what = datasource["infos"][0] for command in multisite_commands: if what in command["tables"] and config.user.may(command["permission"]): return True return False def show_command_form(is_open, datasource): # What commands are available depends on the Livestatus table we # deal with. If a data source provides information about more # than one table, (like services datasource also provide host # information) then the first info is the primary table. So 'what' # will be one of "host", "service", "command" or "downtime". what = datasource["infos"][0] html.open_div(id_="commands", class_=["view_form"], style="display:none;" if not is_open else None) html.begin_form("actions") html.hidden_field("_do_actions", "yes") html.hidden_field("actions", "yes") html.hidden_fields() # set all current variables, exception action vars # Show command forms, grouped by (optional) command group by_group = {} for command in multisite_commands: if what in command["tables"] and config.user.may(command["permission"]): # Some special commands can be shown on special views using this option. # It is currently only used in custom views, not shipped with check_mk. if command.get('only_view') and html.var('view_name') != command['only_view']: continue group = command.get("group", "various") by_group.setdefault(group, []).append(command) for group_ident, group_commands in sorted(by_group.items(), key=lambda x: multisite_command_groups[x[0]]["sort_index"]): forms.header(multisite_command_groups[group_ident]["title"], narrow=True) for command in group_commands: forms.section(command["title"]) command["render"]() forms.end() html.end_form() html.close_div() # Examine the current HTML variables in order determine, which # command the user has selected. The fetch ids from a data row # (host name, service description, downtime/commands id) and # construct one or several core command lines and a descriptive # title. def core_command(what, row, row_nr, total_rows): host = row.get("host_name") descr = row.get("service_description") if what == "host": spec = host cmdtag = "HOST" elif what == "service": spec = "%s;%s" % (host, descr) cmdtag = "SVC" else: spec = row.get(what + "_id") if descr: cmdtag = "SVC" else: cmdtag = "HOST" commands = None title = None # Call all command actions. The first one that detects # itself to be executed (by examining the HTML variables) # will return a command to execute and a title for the # confirmation dialog. for cmd in multisite_commands: if config.user.may(cmd["permission"]): # Does the command need information about the total number of rows # and the number of the current row? Then specify that if cmd.get("row_stats"): result = cmd["action"](cmdtag, spec, row, row_nr, total_rows) else: result = cmd["action"](cmdtag, spec, row) if result: executor = cmd.get("executor", command_executor_livestatus) commands, title = result break # Use the title attribute to determine if a command exists, since the list # of commands might be empty (e.g. in case of "remove all downtimes" where) # no downtime exists in a selection of rows. if not title: raise MKUserError(None, _("Sorry. This command is not implemented.")) # Some commands return lists of commands, others # just return one basic command. Convert those if type(commands) != list: commands = [commands] return commands, title, executor def command_executor_livestatus(command, site): sites.live().command("[%d] %s" % (int(time.time()), command), site) # make gettext localize some magic texts _("services") _("hosts") _("commands") _("downtimes") _("aggregations") # Returns: # True -> Actions have been done # False -> No actions done because now rows selected # [...] new rows -> Rows actions (shall/have) be performed on def do_actions(view, what, action_rows, backurl): if not config.user.may("general.act"): html.show_error(_("You are not allowed to perform actions. " "If you think this is an error, please ask " "your administrator grant you the permission to do so.")) return False # no actions done if not action_rows: message = _("No rows selected to perform actions for.") if html.output_format == "html": # sorry for this hack message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view')) html.show_error(message) return False # no actions done command = None title, executor = core_command(what, action_rows[0], 0, len(action_rows))[1:3] # just get the title and executor if not html.confirm(_("Do you really want to %(title)s the following %(count)d %(what)s?") % { "title" : title, "count" : len(action_rows), "what" : visuals.infos[what]["title_plural"], }, method = 'GET'): return False count = 0 already_executed = set([]) for nr, row in enumerate(action_rows): core_commands, title, executor = core_command(what, row, nr, len(action_rows)) for command_entry in core_commands: site = row.get("site") # site is missing for BI rows (aggregations can spawn several sites) if (site, command_entry) not in already_executed: # Some command functions return the information about the site per-command (e.g. for BI) if type(command_entry) == tuple: site, command = command_entry else: command = command_entry if type(command) == unicode: command = command.encode("utf-8") executor(command, site) already_executed.add((site, command_entry)) count += 1 message = None if command: message = _("Successfully sent %d commands.") % count if config.debug: message += _("The last one was: <pre>%s</pre>") % command elif count == 0: message = _("No matching data row. No command sent.") if message: if html.output_format == "html": # sorry for this hack message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view')) if html.var("show_checkboxes") == "1": html.del_var("selection") weblib.selection_id() backurl += "&selection=" + html.var("selection") message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view with checkboxes reset')) if html.var("_show_result") == "0": html.immediate_browser_redirect(0.5, backurl) html.message(message) return True def filter_by_row_id(view, rows): wanted_row_id = html.var("_row_id") for row in rows: if row_id(view, row) == wanted_row_id: return [row] return [] def filter_selected_rows(view, rows, selected_ids): action_rows = [] for row in rows: if row_id(view, row) in selected_ids: action_rows.append(row) return action_rows def get_context_link(user, viewname): if viewname in available_views: return "view.py?view_name=%s" % viewname else: return None def ajax_export(): load_views() for name, view in available_views.items(): view["owner"] = '' view["public"] = True html.write(pprint.pformat(available_views)) def get_view_by_name(view_name): load_views() return available_views[view_name] #. # .--Plugin Helpers------------------------------------------------------. # | ____ _ _ _ _ _ | # | | _ \| |_ _ __ _(_)_ __ | | | | ___| |_ __ ___ _ __ ___ | # | | |_) | | | | |/ _` | | '_ \ | |_| |/ _ \ | '_ \ / _ \ '__/ __| | # | | __/| | |_| | (_| | | | | | | _ | __/ | |_) | __/ | \__ \ | # | |_| |_|\__,_|\__, |_|_| |_| |_| |_|\___|_| .__/ \___|_| |___/ | # | |___/ |_| | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' def register_command_group(ident, title, sort_index): multisite_command_groups[ident] = { "title" : title, "sort_index" : sort_index, } def register_hook(hook, func): if not hook in view_hooks: view_hooks[hook] = [] if func not in view_hooks[hook]: view_hooks[hook].append(func) def execute_hooks(hook): for hook_func in view_hooks.get(hook, []): try: hook_func() except: if config.debug: raise MKGeneralException(_('Problem while executing hook function %s in hook %s: %s') % (hook_func.__name__, hook, traceback.format_exc())) else: pass def join_row(row, cell): if type(cell) == JoinCell: return row.get("JOIN", {}).get(cell.join_service()) else: return row def url_to_view(row, view_name): if display_options.disabled(display_options.I): return None view = permitted_views().get(view_name) if view: # Get the context type of the view to link to, then get the parameters of this # context type and try to construct the context from the data of the row url_vars = [] datasource = multisite_datasources[view['datasource']] for info_key in datasource['infos']: if info_key in view['single_infos']: # Determine which filters (their names) need to be set # for specifying in order to select correct context for the # target view. for filter_name in visuals.info_params(info_key): filter_object = visuals.get_filter(filter_name) # Get the list of URI vars to be set for that filter new_vars = filter_object.variable_settings(row) url_vars += new_vars # See get_link_filter_names() comment for details for src_key, dst_key in visuals.get_link_filter_names(view, datasource['infos'], datasource.get('link_filters', {})): try: url_vars += visuals.get_filter(src_key).variable_settings(row) except KeyError: pass try: url_vars += visuals.get_filter(dst_key).variable_settings(row) except KeyError: pass # Some special handling for the site filter which is meant as optional hint # Always add the site filter var when some useful information is available add_site_hint = True for filter_key in datasource.get('multiple_site_filters', []): if filter_key in dict(url_vars): add_site_hint = False # Hack for servicedesc view which is meant to show all services with the given # description: Don't add the site filter for this view. if view_name == "servicedesc": add_site_hint = False if add_site_hint and row.get('site'): url_vars.append(('site', row['site'])) do = html.var("display_options") if do: url_vars.append(("display_options", do)) filename = "mobile_view.py" if html.mobile else "view.py" return filename + "?" + html.urlencode_vars([("view_name", view_name)] + url_vars) def link_to_view(content, row, view_name): if display_options.disabled(display_options.I): return content url = url_to_view(row, view_name) if url: return "<a href=\"%s\">%s</a>" % (url, content) else: return content def docu_link(topic, text): return '<a href="%s" target="_blank">%s</a>' % (config.doculink_urlformat % topic, text) # Calculates a uniq id for each data row which identifies the current # row accross different page loadings. def row_id(view, row): key = u'' for col in multisite_datasources[view['datasource']]['idkeys']: key += u'~%s' % row[col] return hashlib.sha256(key.encode('utf-8')).hexdigest() def paint_stalified(row, text): if is_stale(row): return "stale", text else: return "", text def substract_sorters(base, remove): for s in remove: if s in base: base.remove(s) elif (s[0], not s[1]) in base: base.remove((s[0], not s[1])) def parse_url_sorters(sort): sorters = [] if not sort: return sorters for s in sort.split(','): if not '~' in s: sorters.append((s.replace('-', ''), s.startswith('-'))) else: sorter, join_index = s.split('~', 1) sorters.append((sorter.replace('-', ''), sorter.startswith('-'), join_index)) return sorters def get_sorter_name_of_painter(painter_name): painter = multisite_painters[painter_name] if 'sorter' in painter: return painter['sorter'] elif painter_name in multisite_sorters: return painter_name def get_primary_sorter_order(view, painter_name): sorter_name = get_sorter_name_of_painter(painter_name) this_asc_sorter = (sorter_name, False) this_desc_sorter = (sorter_name, True) group_sort, user_sort, view_sort = get_separated_sorters(view) if user_sort and this_asc_sorter == user_sort[0]: return 'asc' elif user_sort and this_desc_sorter == user_sort[0]: return 'desc' else: return '' def get_separated_sorters(view): group_sort = [ (get_sorter_name_of_painter(p[0]), False) for p in view['group_painters'] if p[0] in multisite_painters and get_sorter_name_of_painter(p[0]) is not None ] view_sort = [ s for s in view['sorters'] if not s[0] in group_sort ] # Get current url individual sorters. Parse the "sort" url parameter, # then remove the group sorters. The left sorters must be the user # individual sorters for this view. # Then remove the user sorters from the view sorters user_sort = parse_url_sorters(html.var('sort')) substract_sorters(user_sort, group_sort) substract_sorters(view_sort, user_sort) return group_sort, user_sort, view_sort # The Group-value of a row is used for deciding whether # two rows are in the same group or not def group_value(row, group_cells): group = [] for cell in group_cells: painter = cell.painter() groupvalfunc = painter.get("groupby") if groupvalfunc: if "args" in painter: group.append(groupvalfunc(row, *painter["args"])) else: group.append(groupvalfunc(row)) else: for c in get_painter_columns(painter): if c in row: group.append(row[c]) return create_dict_key(group) def create_dict_key(value): if type(value) in (list, tuple): return tuple(map(create_dict_key, value)) elif type(value) == dict: return tuple([ (k, create_dict_key(v)) for (k, v) in sorted(value.items()) ]) else: return value def get_host_tags(row): if type(row.get("host_custom_variables")) == dict: return row["host_custom_variables"].get("TAGS", "") if type(row.get("host_custom_variable_names")) != list: return "" for name, val in zip(row["host_custom_variable_names"], row["host_custom_variable_values"]): if name == "TAGS": return val return "" # Get the definition of a tag group g_taggroups_by_id = {} def get_tag_group(tgid): # Build a cache if not g_taggroups_by_id: for entry in config.host_tag_groups(): g_taggroups_by_id[entry[0]] = (entry[1], entry[2]) return g_taggroups_by_id.get(tgid, (_("N/A"), [])) def get_custom_var(row, key): for name, val in zip(row["custom_variable_names"], row["custom_variable_values"]): if name == key: return val return "" def is_stale(row): return row.get('service_staleness', row.get('host_staleness', 0)) >= config.staleness_threshold def cmp_insensitive_string(v1, v2): c = cmp(v1.lower(), v2.lower()) # force a strict order in case of equal spelling but different # case! if c == 0: return cmp(v1, v2) else: return c # Sorting def cmp_ip_address(column, r1, r2): def split_ip(ip): try: return tuple(int(part) for part in ip.split('.')) except: return ip v1, v2 = split_ip(r1.get(column, '')), split_ip(r2.get(column, '')) return cmp(v1, v2) def cmp_simple_string(column, r1, r2): v1, v2 = r1.get(column, ''), r2.get(column, '') return cmp_insensitive_string(v1, v2) def cmp_num_split(column, r1, r2): return utils.cmp_num_split(r1[column].lower(), r2[column].lower()) def cmp_string_list(column, r1, r2): v1 = ''.join(r1.get(column, [])) v2 = ''.join(r2.get(column, [])) return cmp_insensitive_string(v1, v2) def cmp_simple_number(column, r1, r2): return cmp(r1.get(column), r2.get(column)) def cmp_custom_variable(r1, r2, key, cmp_func): return cmp(get_custom_var(r1, key), get_custom_var(r2, key)) def cmp_service_name_equiv(r): if r == "Check_MK": return -6 elif r == "Check_MK Agent": return -5 elif r == "Check_MK Discovery": return -4 elif r == "Check_MK inventory": return -3 # FIXME: Remove old name one day elif r == "Check_MK HW/SW Inventory": return -2 else: return 0 def declare_simple_sorter(name, title, column, func): multisite_sorters[name] = { "title" : title, "columns" : [ column ], "cmp" : lambda r1, r2: func(column, r1, r2) } def declare_1to1_sorter(painter_name, func, col_num = 0, reverse = False): multisite_sorters[painter_name] = { "title" : multisite_painters[painter_name]['title'], "columns" : multisite_painters[painter_name]['columns'], } if not reverse: multisite_sorters[painter_name]["cmp"] = \ lambda r1, r2: func(multisite_painters[painter_name]['columns'][col_num], r1, r2) else: multisite_sorters[painter_name]["cmp"] = \ lambda r1, r2: func(multisite_painters[painter_name]['columns'][col_num], r2, r1) return painter_name # Ajax call for fetching parts of the tree def ajax_inv_render_tree(): hostname = html.var("host") invpath = html.var("path") tree_id = html.var("treeid", "") if html.var("show_internal_tree_paths"): show_internal_tree_paths = True else: show_internal_tree_paths = False if tree_id: struct_tree = inventory.load_delta_tree(hostname, int(tree_id[1:])) tree_renderer = DeltaNodeRenderer(hostname, tree_id, invpath) else: struct_tree = inventory.load_tree(hostname) tree_renderer = AttributeRenderer(hostname, "", invpath, show_internal_tree_paths=show_internal_tree_paths) if struct_tree is None: html.show_error(_("No such inventory tree.")) struct_tree = struct_tree.get_filtered_tree(inventory.get_permitted_inventory_paths()) parsed_path, attributes_key = inventory.parse_tree_path(invpath) if parsed_path: children = struct_tree.get_sub_children(parsed_path) else: children = [struct_tree.get_root_container()] if children is None: html.show_error(_("Invalid path in inventory tree: '%s' >> %s") % (invpath, repr(parsed_path))) else: for child in inventory.sort_children(children): child.show(tree_renderer, path=invpath) def output_csv_headers(view): filename = '%s-%s.csv' % (view['name'], time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time()))) if type(filename) == unicode: filename = filename.encode("utf-8") html.req.headers_out['Content-Disposition'] = 'Attachment; filename="%s"' % filename def paint_host_list(site, hosts): entries = [] for host in hosts: args = [ ("view_name", "hoststatus"), ("site", site), ("host", host), ] if html.var("display_options"): args.append(("display_options", html.var("display_options"))) url = html.makeuri_contextless(args, filename="view.py") entries.append(html.render_a(host, href=url)) return "", HTML(", ").join(entries) # There is common code with modules/events.py:format_plugin_output(). Please check # whether or not that function needs to be changed too # TODO(lm): Find a common place to unify this functionality. def format_plugin_output(output, row = None): ok_marker = '<b class="stmark state0">OK</b>' warn_marker = '<b class="stmark state1">WARN</b>' crit_marker = '<b class="stmark state2">CRIT</b>' unknown_marker = '<b class="stmark state3">UNKN</b>' shall_escape = config.escape_plugin_output # In case we have a host or service row use the optional custom attribute # ESCAPE_PLUGIN_OUTPUT (set by host / service ruleset) to override the global # setting. if row: custom_vars = row.get("service_custom_variables", row.get("host_custom_variables", {})) if "ESCAPE_PLUGIN_OUTPUT" in custom_vars: shall_escape = custom_vars["ESCAPE_PLUGIN_OUTPUT"] == "1" if shall_escape: output = html.attrencode(output) output = output.replace("(!)", warn_marker) \ .replace("(!!)", crit_marker) \ .replace("(?)", unknown_marker) \ .replace("(.)", ok_marker) if row and "[running on" in output: a = output.index("[running on") e = output.index("]", a) hosts = output[a+12:e].replace(" ","").split(",") css, h = paint_host_list(row["site"], hosts) output = output[:a] + "running on " + h + output[e+1:] if shall_escape: # (?:&lt;A HREF=&quot;), (?: target=&quot;_blank&quot;&gt;)? and endswith(" </A>") is a special # handling for the HTML code produced by check_http when "clickable URL" option is active. output = re.sub("(?:&lt;A HREF=&quot;)?(http[s]?://[^\"'>\t\s\n,]+)(?: target=&quot;_blank&quot;&gt;)?", lambda p: '<a href="%s"><img class=pluginurl align=absmiddle title="%s" src="images/pluginurl.png"></a>' % (p.group(1).replace('&quot;', ''), p.group(1).replace('&quot;', '')), output) if output.endswith(" &lt;/A&gt;"): output = output[:-11] return output #. # .--Icon Selector-------------------------------------------------------. # | ___ ____ _ _ | # | |_ _|___ ___ _ __ / ___| ___| | ___ ___| |_ ___ _ __ | # | | |/ __/ _ \| '_ \ \___ \ / _ \ |/ _ \/ __| __/ _ \| '__| | # | | | (_| (_) | | | | ___) | __/ | __/ (__| || (_) | | | # | |___\___\___/|_| |_| |____/ \___|_|\___|\___|\__\___/|_| | # | | # +----------------------------------------------------------------------+ # | AJAX API call for rendering the icon selector | # '----------------------------------------------------------------------' def ajax_popup_icon_selector(): varprefix = html.var('varprefix') value = html.var('value') allow_empty = html.var('allow_empty') == '1' vs = IconSelector(allow_empty=allow_empty) vs.render_popup_input(varprefix, value) #. # .--Action Menu---------------------------------------------------------. # | _ _ _ __ __ | # | / \ ___| |_(_) ___ _ __ | \/ | ___ _ __ _ _ | # | / _ \ / __| __| |/ _ \| '_ \ | |\/| |/ _ \ '_ \| | | | | # | / ___ \ (__| |_| | (_) | | | | | | | | __/ | | | |_| | | # | /_/ \_\___|\__|_|\___/|_| |_| |_| |_|\___|_| |_|\__,_| | # | | # +----------------------------------------------------------------------+ # | Realizes the popup action menu for hosts/services in views | # '----------------------------------------------------------------------' def query_action_data(what, host, site, svcdesc): # Now fetch the needed data from livestatus columns = list(iconpainter_columns(what, toplevel=False)) try: columns.remove('site') except KeyError: pass if site: sites.live().set_only_sites([site]) sites.live().set_prepend_site(True) query = 'GET %ss\n' \ 'Columns: %s\n' \ 'Filter: host_name = %s\n' \ % (what, ' '.join(columns), host) if what == 'service': query += 'Filter: service_description = %s\n' % svcdesc row = sites.live().query_row(query) sites.live().set_prepend_site(False) sites.live().set_only_sites(None) return dict(zip(['site'] + columns, row)) def ajax_popup_action_menu(): site = html.var('site') host = html.var('host') svcdesc = html.var('service') what = 'service' if svcdesc else 'host' weblib.prepare_display_options(globals()) row = query_action_data(what, host, site, svcdesc) icons = get_icons(what, row, toplevel=False) html.open_ul() for icon in icons: if len(icon) != 4: html.open_li() html.write(icon[1]) html.close_li() else: html.open_li() icon_name, title, url_spec = icon[1:] if url_spec: url, target_frame = sanitize_action_url(url_spec) url = replace_action_url_macros(url, what, row) onclick = None if url.startswith('onclick:'): onclick = url[8:] url = 'javascript:void(0);' target = None if target_frame and target_frame != "_self": target = target_frame html.open_a(href=url, target=target, onclick=onclick) html.icon('', icon_name) if title: html.write(title) else: html.write_text(_("No title")) if url_spec: html.close_a() html.close_li() html.close_ul() def sanitize_action_url(url_spec): if type(url_spec) == tuple: return url_spec else: return (url_spec, None) #. # .--Reschedule----------------------------------------------------------. # | ____ _ _ _ | # | | _ \ ___ ___ ___| |__ ___ __| |_ _| | ___ | # | | |_) / _ \/ __|/ __| '_ \ / _ \/ _` | | | | |/ _ \ | # | | _ < __/\__ \ (__| | | | __/ (_| | |_| | | __/ | # | |_| \_\___||___/\___|_| |_|\___|\__,_|\__,_|_|\___| | # | | # +----------------------------------------------------------------------+ # | Ajax webservice for reschedulung host- and service checks | # '----------------------------------------------------------------------' def ajax_reschedule(): try: do_reschedule() except Exception, e: html.write("['ERROR', '%s']\n" % e) def do_reschedule(): if not config.user.may("action.reschedule"): raise MKGeneralException("You are not allowed to reschedule checks.") site = html.var("site") host = html.var("host", "") if not host: raise MKGeneralException("Action reschedule: missing host name") service = html.get_unicode_input("service", "") wait_svc = html.get_unicode_input("wait_svc", "") if service: cmd = "SVC" what = "service" spec = "%s;%s" % (host, service.encode("utf-8")) if wait_svc: wait_spec = u'%s;%s' % (host, wait_svc) add_filter = "Filter: service_description = %s\n" % livestatus.lqencode(wait_svc) else: wait_spec = spec add_filter = "Filter: service_description = %s\n" % livestatus.lqencode(service) else: cmd = "HOST" what = "host" spec = host wait_spec = spec add_filter = "" try: now = int(time.time()) sites.live().command("[%d] SCHEDULE_FORCED_%s_CHECK;%s;%d" % (now, cmd, livestatus.lqencode(spec), now), site) sites.live().set_only_sites([site]) query = u"GET %ss\n" \ "WaitObject: %s\n" \ "WaitCondition: last_check >= %d\n" \ "WaitTimeout: %d\n" \ "WaitTrigger: check\n" \ "Columns: last_check state plugin_output\n" \ "Filter: host_name = %s\n%s" \ % (what, livestatus.lqencode(wait_spec), now, config.reschedule_timeout * 1000, livestatus.lqencode(host), add_filter) row = sites.live().query_row(query) sites.live().set_only_sites() last_check = row[0] if last_check < now: html.write("['TIMEOUT', 'Check not executed within %d seconds']\n" % (config.reschedule_timeout)) else: if service == "Check_MK": # Passive services triggered by Check_MK often are updated # a few ms later. We introduce a small wait time in order # to increase the chance for the passive services already # updated also when we return. time.sleep(0.7); html.write("['OK', %d, %d, %r]\n" % (row[0], row[1], row[2].encode("utf-8"))) except Exception, e: sites.live().set_only_sites() raise MKGeneralException(_("Cannot reschedule check: %s") % e)
huiyiqun/check_mk
web/htdocs/views.py
Python
gpl-2.0
129,902
<?php namespace Drupal\message_subscribe; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Session\AccountInterface; use Drupal\message\MessageInterface; /** * Subscribers service. */ interface SubscribersInterface { /** * Process a message and send to subscribed users. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object to process subscriptions and send notifications for. * @param \Drupal\message\MessageInterface $message * The message object. * @param array $notify_options * (optional) An array of options to be passed to the message notifier * service. See `\Drupal\message_notify\MessageNotifier::send()`. * @param array $subscribe_options * (optional) Array with the following optional values: * - 'save message' (defaults to TRUE) Determine if the Message should be * saved. * - 'skip context' (defaults to FALSE) determine if extracting basic * context should be skipped in `self::getSubscribers()`. * - 'last uid' (defaults to 0) Only query UIDs greater than this UID. * - 'uids': Array of user IDs to be processed. Setting this, will cause * skipping `self::getSubscribers()` to get the subscribed * users. * - 'range': (defaults to FALSE) limit the number of items to fetch in the * subscribers query. * - 'end time': The timestamp of the time limit for the function to * execute. Defaults to FALSE, meaning there is no time limitation. * - 'use queue': Determine if queue API should be used to * - 'queue': Set to TRUE to indicate the processing is done via a queue * worker. * - 'entity access: (defaults to TRUE) determine if access to view the * entity should be applied when getting the list of subscribed users. * - 'notify blocked users' (defaults to the global setting in * `message_subscribe.settings`) determine whether blocked users * should be notified. Typically this should be used in conjunction with * 'entity access' to ensure that blocked users don't receive * notifications about entities which they used to have access to * before they were blocked. * - 'notify message owner' (defaults to the global setting in * `message_subscribe.settings`) determines if the user that created the * entity gets notified of their own action. If TRUE the author will get * notified. * @param array $context * (optional) array keyed with the entity type and array of entity IDs as * the value. For example, if the event is related to a node * entity, the implementing module might pass along with the node * itself, the node author and related taxonomy terms. * * Example usage. * * @code * $subscribe_options['uids'] = array( * 1 => array( * 'notifiers' => array('email'), * ), * ); * $context = array( * 'node' => array(1), * // The node author. * 'user' => array(10), * // Related taxonomy terms. * 'taxonomy_term' => array(100, 200, 300) * ); * @endcode */ public function sendMessage(EntityInterface $entity, MessageInterface $message, array $notify_options = [], array $subscribe_options = [], array $context = []); /** * Retrieve a list of subscribers for a given entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to retrieve subscribers for. * @param \Drupal\message\MessageInterface $message * The message entity. * @param array $options * (optional) An array of options with the same elements as the * `$subscribe_options` array for `self::sendMessage()`. * @param array $context * (optional) The context array, passed by reference. This has the same * elements as the `$context` paramater for `self::sendMessage()`. * * @return \Drupal\message_subscribe\Subscribers\DeliveryCandidateInterface[] * Array of delivery candidate objects keyed with the user IDs to send * notifications to. */ public function getSubscribers(EntityInterface $entity, MessageInterface $message, array $options = [], array &$context = []); /** * Get context from a given entity type. * * This is a naive implementation, which extracts context from an entity. * For example, given a node we extract the node author and related * taxonomy terms. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object. * @param bool $skip_detailed_context * (optional) Skip detailed context detection and just use entity ID/type. * Defaults to FALSE. * @param array $context * (optional) The starting context array to modify. * * @return array * Array keyed with the entity type and array of entity IDs as the value. */ public function getBasicContext(EntityInterface $entity, $skip_detailed_context = FALSE, array $context = []); /** * Get Message subscribe related flags. * * Return Flags related to message subscribe using a name convention -- * the flag name should start with "subscribe_". * * @param string $entity_type * (optional) The entity type for which to load the flags. * @param string $bundle * (optional) The bundle for which to load the flags. * @param \Drupal\Core\Session\AccountInterface $account * (optional) The user account to filter available flags. If not set, all * flags for the given entity and bundle will be returned. * * @return \Drupal\flag\FlagInterface[] * An array of the structure [fid] = flag_object. * * @see \Drupal\flag\FlagServiceInterface::getAllFlags() */ public function getFlags($entity_type = NULL, $bundle = NULL, AccountInterface $account = NULL); }
rahulrasgon/Music-Store-Theme
modules/message_subscribe/src/SubscribersInterface.php
PHP
gpl-2.0
5,817
<?php /** * Table Definition for Items_Translations * * PHP version 5 * * Copyright (C) Demian Katz 2012. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category GeebyDeeby * @package Db_Table * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ namespace GeebyDeeby\Db\Table; use Laminas\Db\Adapter\Adapter; use Laminas\Db\RowGateway\RowGateway; use Laminas\Db\Sql\Expression; use Laminas\Db\Sql\Select; /** * Table Definition for Items_Translations * * @category GeebyDeeby * @package Db_Table * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ class ItemsTranslations extends Gateway { /** * Constructor * * @param Adapter $adapter Database adapter * @param PluginManager $tm Table manager * @param RowGateway $rowObj Row prototype object (null for default) */ public function __construct(Adapter $adapter, PluginManager $tm, RowGateway $rowObj = null ) { parent::__construct($adapter, $tm, $rowObj, 'Items_Translations'); } /** * Support method to add language information to a query. * * @param \Laminas\Db\Sql\Select $select Query to modify * * @return void */ public static function addLanguageToSelect($select) { $select->join( ['eds' => 'Editions'], 'eds.Item_ID = i.Item_ID', [], Select::JOIN_LEFT ); $select->join( ['s' => 'Series'], 's.Series_ID = eds.Series_ID', [], Select::JOIN_LEFT ); $select->join( ['l' => 'Languages'], 'l.Language_ID = s.Language_ID', [ 'Language_Name' => new Expression( 'min(?)', ['Language_Name'], [Expression::TYPE_IDENTIFIER] ) ], Select::JOIN_LEFT ); $select->group('i.Item_ID'); } /** * Get a list of items translated from the specified item. * * @param int $itemID Item ID * @param bool $includeLang Should we also load language information? * * @return mixed */ public function getTranslatedFrom($itemID, $includeLang = false) { $callback = function ($select) use ($itemID, $includeLang) { $select->join( ['i' => 'Items'], 'Items_Translations.Trans_Item_ID = i.Item_ID' ); $select->where->equalTo('Source_Item_ID', $itemID); $select->order('i.Item_Name'); if ($includeLang) { ItemsTranslations::addLanguageToSelect($select); } }; return $this->select($callback); } /** * Get a list of items translated into the specified item. * * @param int $itemID Item ID * @param bool $includeLang Should we also load language information? * * @return mixed */ public function getTranslatedInto($itemID, $includeLang = false) { $callback = function ($select) use ($itemID, $includeLang) { $select->join( ['i' => 'Items'], 'Items_Translations.Source_Item_ID = i.Item_ID' ); $select->where->equalTo('Trans_Item_ID', $itemID); $select->order('i.Item_Name'); if ($includeLang) { ItemsTranslations::addLanguageToSelect($select); } }; return $this->select($callback); } }
demiankatz/Geeby-Deeby
module/GeebyDeeby/src/GeebyDeeby/Db/Table/ItemsTranslations.php
PHP
gpl-2.0
4,351
/* * irctabitem.cpp * * Copyright 2008 David Vachulka <david@konstrukce-cad.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shellapi.h> #endif #include "irctabitem.h" #include "tetristabitem.h" #include "icons.h" #include "config.h" #include "i18n.h" FXDEFMAP(DccSendDialog) DccSendDialogMap[] = { FXMAPFUNC(SEL_COMMAND, DccSendDialog_FILE, DccSendDialog::onFile), FXMAPFUNC(SEL_COMMAND, DccSendDialog_SEND, DccSendDialog::onSend), FXMAPFUNC(SEL_COMMAND, DccSendDialog_CANCEL, DccSendDialog::onCancel), FXMAPFUNC(SEL_CLOSE, 0, DccSendDialog::onCancel), FXMAPFUNC(SEL_KEYPRESS, 0, DccSendDialog::onKeyPress) }; FXIMPLEMENT(DccSendDialog, FXDialogBox, DccSendDialogMap, ARRAYNUMBER(DccSendDialogMap)) DccSendDialog::DccSendDialog(FXMainWindow* owner, FXString nick) : FXDialogBox(owner, FXStringFormat(_("Send file to %s"), nick.text()), DECOR_RESIZE|DECOR_TITLE|DECOR_BORDER, 0,0,0,0, 0,0,0,0, 0,0) { m_mainFrame = new FXVerticalFrame(this, LAYOUT_FILL_X|LAYOUT_FILL_Y); m_fileFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X); new FXLabel(m_fileFrame, _("File:")); m_fileText = new FXTextField(m_fileFrame, 25, NULL, 0, TEXTFIELD_READONLY|FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_X); m_buttonFile = new dxEXButton(m_fileFrame, "...", NULL, this, DccSendDialog_FILE, FRAME_RAISED|FRAME_THICK|LAYOUT_CENTER_X, 0,0,0,0, 10,10,2,2); m_passiveFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X); m_checkPassive = new FXCheckButton(m_passiveFrame, _("Send passive"), NULL, 0); m_buttonFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X|PACK_UNIFORM_WIDTH); m_buttonCancel = new dxEXButton(m_buttonFrame, _("&Cancel"), NULL, this, DccSendDialog_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); m_buttonSend = new dxEXButton(m_buttonFrame, _("&Send file"), NULL, this, DccSendDialog_SEND, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); } DccSendDialog::~DccSendDialog() { } FXuint DccSendDialog::execute(FXuint placement) { create(); show(placement); getApp()->refresh(); dxEXFileDialog dialog(this, _("Select file")); if(dialog.execute()) { m_fileText->setText(dialog.getFilename()); } return getApp()->runModalFor(this); } long DccSendDialog::onFile(FXObject*, FXSelector, void*) { dxEXFileDialog dialog(this, _("Select file")); if(dialog.execute()) { m_fileText->setText(dialog.getFilename()); } return 1; } long DccSendDialog::onSend(FXObject*, FXSelector, void*) { getApp()->stopModal(this,TRUE); hide(); return 1; } long DccSendDialog::onCancel(FXObject*, FXSelector, void*) { getApp()->stopModal(this,FALSE); hide(); return 1; } long DccSendDialog::onKeyPress(FXObject *sender, FXSelector sel, void *ptr) { if(FXTopWindow::onKeyPress(sender,sel,ptr)) return 1; if(((FXEvent*)ptr)->code == KEY_Escape) { handle(this,FXSEL(SEL_COMMAND,DccSendDialog_CANCEL),NULL); return 1; } return 0; } FXDEFMAP(NickList) NickListMap [] = { FXMAPFUNC(SEL_QUERY_TIP, 0, NickList::onQueryTip) }; FXIMPLEMENT(NickList, FXList, NickListMap, ARRAYNUMBER(NickListMap)) NickList::NickList(FXComposite* p, IrcTabItem* tgt, FXSelector sel, FXuint opts, FXint x, FXint y, FXint w, FXint h) : FXList(p, tgt, sel, opts, x, y, w, h), m_parent(tgt) { } long NickList::onQueryTip(FXObject *sender, FXSelector sel, void *ptr) { if(FXWindow::onQueryTip(sender, sel, ptr)) return 1; if((flags&FLAG_TIP) && !(options&LIST_AUTOSELECT) && (0<=cursor)) // No tip when autoselect! { FXString string = items[cursor]->getText(); string.append('\n'); NickInfo nick = m_parent->m_engine->getNickInfo(items[cursor]->getText()); string.append(FXStringFormat(_("User: %s@%s\n"), nick.user.text(), nick.host.text())); string.append(FXStringFormat(_("Realname: %s"), nick.real.text())); sender->handle(this, FXSEL(SEL_COMMAND,ID_SETSTRINGVALUE), (void*)&string); return 1; } return 0; } FXIMPLEMENT(NickListItem, FXListItem, NULL, 0) void NickListItem::setUserMode(UserMode mode) { m_mode = mode; FXbool away = m_tab->m_engine->getNickInfo(getText()).away; m_parent->recalc(); switch(m_mode){ case ADMIN: setIcon(away? ICO_IRCAWAYADMIN:ICO_IRCADMIN);break; case OWNER: setIcon(away? ICO_IRCAWAYOWNER:ICO_IRCOWNER);break; case OP: setIcon(away? ICO_IRCAWAYOP:ICO_IRCOP);break; case HALFOP: setIcon(away? ICO_IRCAWAYHALFOP:ICO_IRCHALFOP);break; case VOICE: setIcon(away? ICO_IRCAWAYVOICE:ICO_IRCVOICE);break; case NONE: setIcon(away? ICO_IRCAWAYNORMAL:ICO_IRCNORMAL);break; } } void NickListItem::changeAway(FXbool away) { m_parent->recalc(); switch(m_mode){ case ADMIN: setIcon(away? ICO_IRCAWAYADMIN:ICO_IRCADMIN);break; case OWNER: setIcon(away? ICO_IRCAWAYOWNER:ICO_IRCOWNER);break; case OP: setIcon(away? ICO_IRCAWAYOP:ICO_IRCOP);break; case HALFOP: setIcon(away? ICO_IRCAWAYHALFOP:ICO_IRCHALFOP);break; case VOICE: setIcon(away? ICO_IRCAWAYVOICE:ICO_IRCVOICE);break; case NONE: setIcon(away? ICO_IRCAWAYNORMAL:ICO_IRCNORMAL);break; } } FXDEFMAP(IrcTabItem) IrcTabItemMap[] = { FXMAPFUNC(SEL_COMMAND, IrcTabItem_COMMANDLINE, IrcTabItem::onCommandline), FXMAPFUNC(SEL_KEYPRESS, IrcTabItem_COMMANDLINE, IrcTabItem::onKeyPress), FXMAPFUNC(SEL_COMMAND, IrcEngine_SERVER, IrcTabItem::onIrcEvent), FXMAPFUNC(SEL_TIMEOUT, IrcTabItem_PTIME, IrcTabItem::onPipeTimeout), FXMAPFUNC(SEL_TIMEOUT, IrcTabItem_ETIME, IrcTabItem::onEggTimeout), FXMAPFUNC(SEL_TEXTLINK, IrcTabItem_TEXT, IrcTabItem::onTextLink), FXMAPFUNC(SEL_RIGHTBUTTONRELEASE, IrcTabItem_USERS, IrcTabItem::onRightMouse), FXMAPFUNC(SEL_DOUBLECLICKED, IrcTabItem_USERS, IrcTabItem::onDoubleclick), FXMAPFUNC(SEL_COMMAND, IrcTabItem_NEWQUERY, IrcTabItem::onNewQuery), FXMAPFUNC(SEL_COMMAND, IrcTabItem_WHOIS, IrcTabItem::onWhois), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DCCCHAT, IrcTabItem::onDccChat), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DCCSEND, IrcTabItem::onDccSend), FXMAPFUNC(SEL_COMMAND, IrcTabItem_OP, IrcTabItem::onOp), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEOP, IrcTabItem::onDeop), FXMAPFUNC(SEL_COMMAND, IrcTabItem_VOICE, IrcTabItem::onVoice), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEVOICE, IrcTabItem::onDevoice), FXMAPFUNC(SEL_COMMAND, IrcTabItem_KICK, IrcTabItem::onKick), FXMAPFUNC(SEL_COMMAND, IrcTabItem_BAN, IrcTabItem::onBan), FXMAPFUNC(SEL_COMMAND, IrcTabItem_KICKBAN, IrcTabItem::onKickban), FXMAPFUNC(SEL_COMMAND, IrcTabItem_IGNORE, IrcTabItem::onIgnore), FXMAPFUNC(SEL_COMMAND, IrcTabItem_TOPIC, IrcTabItem::onTopic), FXMAPFUNC(SEL_LINK, IrcTabItem_TOPIC, IrcTabItem::onTopicLink), FXMAPFUNC(SEL_COMMAND, dxPipe::ID_PIPE, IrcTabItem::onPipe), FXMAPFUNC(SEL_COMMAND, IrcTabItem_AWAY, IrcTabItem::onSetAway), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEAWAY, IrcTabItem::onRemoveAway), FXMAPFUNC(SEL_COMMAND, IrcTabItem_SPELL, IrcTabItem::onSpellLang) }; FXIMPLEMENT(IrcTabItem, dxTabItem, IrcTabItemMap, ARRAYNUMBER(IrcTabItemMap)) IrcTabItem::IrcTabItem(dxTabBook *tab, const FXString &tabtext, FXIcon *icon, FXuint opts, FXint id, TYPE type, IrcEngine *socket, FXbool ownServerWindow, FXbool usersShown, FXbool logging, FXString commandsList, FXString logPath, FXint maxAway, IrcColor colors, FXString nickChar, FXFont *font, FXbool sameCommand, FXbool sameList, FXbool coloredNick, FXbool stripColors, FXbool useSpell, FXbool showSpellCombo) : dxTabItem(tab, tabtext, icon, opts, id), m_engine(socket), m_parent(tab), m_type(type), m_usersShown(usersShown), m_logging(logging), m_ownServerWindow(ownServerWindow), m_sameCmd(sameCommand), m_sameList(sameList), m_coloredNick(coloredNick), m_stripColors(stripColors), m_useSpell(useSpell), m_showSpellCombo(showSpellCombo), m_colors(colors), m_commandsList(commandsList), m_logPath(logPath), m_maxAway(maxAway), m_nickCompletionChar(nickChar), m_logstream(NULL) { m_currentPosition = 0; m_historyMax = 25; m_numberUsers = 0; m_maxLen = 460; m_iamOp = FALSE; m_topic = _("No topic is set"); m_editableTopic = TRUE; m_pipe = NULL; m_sendPipe = FALSE; m_scriptHasAll = FALSE; m_scriptHasMyMsg = FALSE; m_unreadColor = FXRGB(0,0,255); m_highlightColor = FXRGB(255,0,0); if(m_type == CHANNEL && m_engine->getConnected()) { m_engine->sendMode(getText()); } m_mainframe = new FXVerticalFrame(m_parent, FRAME_RAISED|LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y); m_splitter = new FXSplitter(m_mainframe, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y|SPLITTER_REVERSED|SPLITTER_TRACKING); m_textframe = new FXVerticalFrame(m_splitter, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_X|LAYOUT_FILL_Y); m_topicline = new dxTextField(m_textframe, 50, this, IrcTabItem_TOPIC, FRAME_SUNKEN|TEXTFIELD_ENTER_ONLY|JUSTIFY_LEFT|LAYOUT_FILL_X); m_topicline->setFont(font); m_topicline->setLinkColor(m_colors.link); m_topicline->setText(m_topic); m_topicline->setUseLink(TRUE); m_topicline->setTopicline(TRUE); if(m_type != CHANNEL) { m_topicline->hide(); } m_text = new dxText(m_textframe, this, IrcTabItem_TEXT, FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y|TEXT_READONLY|TEXT_WORDWRAP|TEXT_SHOWACTIVE|TEXT_AUTOSCROLL); m_text->setFont(font); m_text->setSelTextColor(getApp()->getSelforeColor()); m_text->setSelBackColor(getApp()->getSelbackColor()); m_usersframe = new FXVerticalFrame(m_splitter, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_FIX_WIDTH); m_users = new NickList(m_usersframe, this, IrcTabItem_USERS, LAYOUT_FILL_X|LAYOUT_FILL_Y); m_users->setSortFunc(FXList::ascendingCase); m_users->setScrollStyle(HSCROLLING_OFF); if(m_sameList) m_users->setFont(font); if(m_type != CHANNEL || !m_usersShown) { m_usersframe->hide(); m_users->hide(); } m_commandframe = new FXHorizontalFrame(m_mainframe, LAYOUT_FILL_X, 0,0,0,0, 0,0,0,0); m_commandline = new dxTextField(m_commandframe, 25, this, IrcTabItem_COMMANDLINE, TEXTFIELD_ENTER_ONLY|FRAME_SUNKEN|JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_BOTTOM, 0, 0, 0, 0, 1, 1, 1, 1); if(m_sameCmd) m_commandline->setFont(font); m_spellLangs = new FXComboBox(m_commandframe, 6, this, IrcTabItem_SPELL, COMBOBOX_STATIC); m_spellLangs->setTipText(_("Spellchecking language list")); m_spellLangs->hide(); if(m_sameCmd) m_spellLangs->setFont(font); if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } dxHiliteStyle style = {m_colors.text,m_colors.back,getApp()->getSelforeColor(),getApp()->getSelbackColor(),0,FALSE}; for(int i=0; i<17; i++) { m_textStyleList.append(style); } //gray text - user commands m_textStyleList[0].normalForeColor = m_colors.user; //orange text - Actions m_textStyleList[1].normalForeColor = m_colors.action; //blue text - Notice m_textStyleList[2].normalForeColor = m_colors.notice; //red text - Errors m_textStyleList[3].normalForeColor = m_colors.error; //bold style m_textStyleList[4].style = FXText::STYLE_BOLD; //underline style m_textStyleList[5].style = FXText::STYLE_UNDERLINE; //bold & underline m_textStyleList[6].style = FXText::STYLE_UNDERLINE; m_textStyleList[6].style ^=FXText::STYLE_BOLD; //highlight text m_textStyleList[7].normalForeColor = m_colors.hilight; //link style m_textStyleList[8].normalForeColor = m_colors.link; m_textStyleList[8].link = TRUE; //next styles for colored nicks m_textStyleList[9].normalForeColor = FXRGB(196, 160, 0); m_textStyleList[10].normalForeColor = FXRGB(206, 92, 0); m_textStyleList[11].normalForeColor = FXRGB(143, 89, 2); m_textStyleList[12].normalForeColor = FXRGB(78, 154, 6); m_textStyleList[13].normalForeColor = FXRGB(32, 74, 135); m_textStyleList[14].normalForeColor = FXRGB(117, 80, 123); m_textStyleList[15].normalForeColor = FXRGB(164, 0, 0); m_textStyleList[16].normalForeColor = FXRGB(85, 87, 83); //text->setStyled(TRUE); m_text->setHiliteStyles(m_textStyleList.data()); m_text->setBackColor(m_colors.back); m_commandline->setBackColor(m_colors.back); m_topicline->setBackColor(m_colors.back); m_users->setBackColor(m_colors.back); m_text->setTextColor(m_colors.text); m_commandline->setTextColor(m_colors.text); m_commandline->setCursorColor(m_colors.text); m_topicline->setTextColor(m_colors.text); m_topicline->setCursorColor(m_colors.text); m_users->setTextColor(m_colors.text); m_spellLangs->setBackColor(m_colors.back); m_spellLangs->setTextColor(m_colors.text); this->setIconPosition(ICON_BEFORE_TEXT); } IrcTabItem::~IrcTabItem() { this->stopLogging(); if(m_pipe) m_pipe->stopCmd(); m_pipeStrings.clear(); getApp()->removeTimeout(this, IrcTabItem_PTIME); } void IrcTabItem::createGeom() { m_mainframe->create(); m_commandline->setFocus(); } void IrcTabItem::clearChat() { m_textStyleList.no(17); m_text->setHiliteStyles(m_textStyleList.data()); m_text->clearText(); } //usefull for set tab current void IrcTabItem::makeLastRowVisible() { m_text->makeLastRowVisible(TRUE); } FXString IrcTabItem::getSpellLang() { #ifdef HAVE_ENCHANT if(m_spellLangs->getNumItems()) return m_spellLangs->getItemText(m_spellLangs->getCurrentItem()); #endif return ""; } void IrcTabItem::reparentTab() { reparent(m_parent); m_mainframe->reparent(m_parent); } void IrcTabItem::hideUsers() { m_usersShown = !m_usersShown; if(m_type == CHANNEL) { m_usersframe->hide(); m_users->hide(); m_splitter->setSplit(1, 0); } } void IrcTabItem::showUsers() { m_usersShown = !m_usersShown; if(m_type == CHANNEL) { m_usersframe->show(); m_users->show(); m_splitter->recalc(); } } void IrcTabItem::setType(const TYPE &typ, const FXString &tabtext) { if(typ == CHANNEL) { if(m_usersShown) m_usersframe->show(); if(m_usersShown) m_users->show(); m_topicline->show(); m_topicline->setText(m_topic); m_splitter->recalc(); setText(tabtext); if(m_engine->getConnected()) m_engine->sendMode(getText()); m_type = typ; } else if(typ == SERVER || typ == QUERY) { m_usersframe->hide(); m_users->hide(); m_topicline->setText(""); m_topicline->hide(); m_topic = _("No topic is set"); setText(tabtext); m_splitter->setSplit(1, 0); if(m_type == CHANNEL) { m_users->clearItems(); m_numberUsers = 0; } m_type = typ; } this->stopLogging(); if(m_type == SERVER) this->setIcon(ICO_SERVER); else if(m_type == CHANNEL) this->setIcon(ICO_CHANNEL); else this->setIcon(ICO_QUERY); if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } else { m_commandline->setUseSpell(FALSE); m_commandline->setTipText(""); m_spellLangs->hide(); m_commandframe->recalc(); } } void IrcTabItem::setColor(IrcColor clrs) { m_colors = clrs; setTextForeColor(clrs.text); setTextBackColor(clrs.back); setUserColor(clrs.user); setActionsColor(clrs.action); setNoticeColor(clrs.notice); setErrorColor(clrs.error); setHilightColor(clrs.hilight); setLinkColor(m_colors.link); } void IrcTabItem::setTextBackColor(FXColor clr) { for(FXint i=0; i<m_textStyleList.no(); i++) { m_textStyleList[i].normalBackColor = clr; } m_text->setBackColor(clr); m_commandline->setBackColor(clr); m_topicline->setBackColor(clr); m_users->setBackColor(clr); m_spellLangs->setBackColor(clr); } void IrcTabItem::setTextForeColor(FXColor clr) { m_textStyleList[4].normalForeColor = clr; m_textStyleList[5].normalForeColor = clr; m_textStyleList[6].normalForeColor = clr; m_text->setTextColor(clr); m_commandline->setTextColor(clr); m_commandline->setCursorColor(clr); m_topicline->setTextColor(clr); m_topicline->setCursorColor(clr); m_users->setTextColor(clr); m_spellLangs->setTextColor(clr); } void IrcTabItem::setUserColor(FXColor clr) { m_textStyleList[0].normalForeColor = clr; } void IrcTabItem::setActionsColor(FXColor clr) { m_textStyleList[1].normalForeColor = clr; } void IrcTabItem::setNoticeColor(FXColor clr) { m_textStyleList[2].normalForeColor = clr; } void IrcTabItem::setErrorColor(FXColor clr) { m_textStyleList[3].normalForeColor = clr; } void IrcTabItem::setHilightColor(FXColor clr) { m_textStyleList[7].normalForeColor = clr; } void IrcTabItem::setLinkColor(FXColor clr) { m_textStyleList[8].normalForeColor = clr; m_topicline->setLinkColor(clr); } void IrcTabItem::setUnreadTabColor(FXColor clr) { if(m_unreadColor!=clr) { FXbool update = this->getTextColor()==m_unreadColor; m_unreadColor = clr; if(update) this->setTextColor(m_unreadColor); } } void IrcTabItem::setHighlightTabColor(FXColor clr) { if(m_highlightColor!=clr) { FXbool update = this->getTextColor()==m_highlightColor; m_highlightColor = clr; if(update) this->setTextColor(m_highlightColor); } } void IrcTabItem::setCommandsList(FXString clst) { m_commandsList = clst; } void IrcTabItem::setMaxAway(FXint maxa) { m_maxAway = maxa; } void IrcTabItem::setLogging(FXbool log) { m_logging = log; } void IrcTabItem::setLogPath(FXString pth) { m_logPath = pth; this->stopLogging(); } void IrcTabItem::setNickCompletionChar(FXString nichr) { m_nickCompletionChar = nichr; } void IrcTabItem::setIrcFont(FXFont *fnt) { if(m_text->getFont() != fnt) { m_text->setFont(fnt); m_text->recalc(); } if(m_topicline->getFont() != fnt) { m_topicline->setFont(fnt); m_topicline->recalc(); } if(m_sameCmd && m_commandline->getFont() != fnt) { m_commandline->setFont(fnt); m_commandline->recalc(); m_spellLangs->setFont(fnt); m_spellLangs->recalc(); } else { m_commandline->setFont(getApp()->getNormalFont()); m_commandline->recalc(); m_spellLangs->setFont(getApp()->getNormalFont()); m_spellLangs->recalc(); } if(m_sameList && m_users->getFont() != fnt) { m_users->setFont(fnt); m_users->recalc(); } else { m_users->setFont(getApp()->getNormalFont()); m_users->recalc(); } } void IrcTabItem::setSameCmd(FXbool scmd) { m_sameCmd = scmd; } void IrcTabItem::setSameList(FXbool slst) { m_sameList = slst; } void IrcTabItem::setColoredNick(FXbool cnick) { m_coloredNick = cnick; } void IrcTabItem::setStripColors(FXbool sclr) { m_stripColors = sclr; } void IrcTabItem::setSmileys(FXbool smiley, dxSmileyArray nsmileys) { m_text->setSmileys(smiley, nsmileys); } void IrcTabItem::setUseSpell(FXbool useSpell) { m_useSpell = useSpell; if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } else { m_commandline->setUseSpell(FALSE); m_commandline->setTipText(""); m_spellLangs->hide(); } m_commandframe->recalc(); } void IrcTabItem::setShowSpellCombo(FXbool showSpellCombo) { if(m_showSpellCombo!=showSpellCombo) { m_showSpellCombo = showSpellCombo; if(m_showSpellCombo) m_spellLangs->show(); else m_spellLangs->hide(); m_commandframe->recalc(); } } void IrcTabItem::removeSmileys() { m_text->removeSmileys(); } //if highlight==TRUE, highlight tab void IrcTabItem::appendText(FXString msg, FXbool highlight, FXbool logLine) { appendIrcText(msg, 0, FALSE, logLine); if(highlight && m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(msg.contains(getNickName())) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } } void IrcTabItem::appendIrcText(FXString msg, FXTime time, FXbool disableStrip, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); appendLinkText(m_stripColors && !disableStrip ? stripColors(msg, FALSE) : msg, 0); if(logLine) this->logLine(stripColors(msg, TRUE), time); } void IrcTabItem::appendIrcNickText(FXString nick, FXString msg, FXint style, FXTime time, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); m_text->appendStyledText(nick+": ", style); appendLinkText(m_stripColors ? stripColors(msg, FALSE) : msg, 0); if(logLine) this->logLine(stripColors("<"+nick+"> "+msg, TRUE), time); } /* if highlight==TRUE, highlight tab * disableStrip is for dxirc.Print */ void IrcTabItem::appendStyledText(FXString text, FXint style, FXbool highlight, FXbool disableStrip, FXbool logLine) { if(style) appendIrcStyledText(text, style, 0, disableStrip, logLine); else appendIrcText(text, 0, disableStrip, logLine); if(highlight && m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(m_type != OTHER && text.contains(getNickName())) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } } void IrcTabItem::appendIrcStyledText(FXString styled, FXint stylenum, FXTime time, FXbool disableStrip, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); appendLinkText(m_stripColors && !disableStrip ? stripColors(styled, TRUE) : styled, stylenum); if(logLine) this->logLine(stripColors(styled, TRUE), time); } static FXbool isBadchar(FXchar c) { switch(c) { case ' ': case ',': case '\0': case '\02': case '\03': case '\017': case '\021': case '\026': case '\035': case '\037': case '\n': case '\r': case '<': case '>': case '"': case '\'': return TRUE; default: return FALSE; } } // checks is char nick/word delimiter static FXbool isDelimiter(FXchar c) { switch(c) { case ' ': case '.': case ',': case '/': case '\\': case '`': case '\'': case '!': case '(': case ')': case '{': case '}': case '|': case '[': case ']': case '\"': case ':': case ';': case '<': case '>': case '?': return TRUE; default: return FALSE; } } void IrcTabItem::appendLinkText(const FXString &txt, FXint stylenum) { FXint i = 0; FXint linkLength = 0; FXbool bold = FALSE; FXbool under = FALSE; FXint lastStyle = stylenum; FXColor foreColor = stylenum && stylenum<=m_textStyleList.no() ? m_textStyleList[stylenum-1].normalForeColor : m_colors.text; FXColor backColor = stylenum && stylenum<=m_textStyleList.no() ? m_textStyleList[stylenum-1].normalBackColor : m_colors.back; FXString normalText = ""; FXint length = txt.length(); while(i<length) { if(txt[i]=='h' && !comparecase(txt.mid(i,7),"http://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>7 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='h' && !comparecase(txt.mid(i,8),"https://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>8 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='f' && !comparecase(txt.mid(i,6),"ftp://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>6 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='w' && !comparecase(txt.mid(i,4),"www.")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>4 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else { if(txt[i] == '\002') //bold { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } bold = !bold; FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\026') //reverse { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; FXColor tempColor = foreColor; foreColor = backColor; backColor = tempColor; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\037') //underline { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } under = !under; FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\021') //fixed { utils::instance().debugLine("Poslan fixed styl"); } else if(txt[i] == '\035') //italic { utils::instance().debugLine("Poslan italic styl"); } else if(txt[i] == '\003') //color { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } FXuint style=0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; FXbool isHexColor = FALSE; FXint colorLength = 0; foreColor = m_colors.text; backColor = m_colors.back; if(i+1<length) { if(txt[i+1] == '#') isHexColor = TRUE; } if(isHexColor) { if(FXRex("^\\h\\h\\h\\h\\h\\h+$").match(txt.mid(i+2,6))) { foreColor = FXRGB(FXIntVal(txt.mid(i+2,2),16),FXIntVal(txt.mid(i+4,2),16),FXIntVal(txt.mid(i+6,2),16)); colorLength +=7; } if(i+8 < length && txt[i+8] == ',' && FXRex("^\\h\\h\\h\\h\\h\\h+$").match(txt.mid(i+10,6))) { backColor = FXRGB(FXIntVal(txt.mid(i+10,2),16),FXIntVal(txt.mid(i+12,2),16),FXIntVal(txt.mid(i+14,2),16)); colorLength +=8; } } else { if(i+2<length) { FXint code = -1; if(isdigit(txt[i+1])) { if(isdigit(txt[i+2])) { code = (txt[i+1]-48)*10+txt[i+2]-48; colorLength +=2; } else { code = txt[i+1]-48; colorLength ++; } } if(code!=-1) foreColor = getIrcColor(code%16); } if(i+colorLength+1 < length && txt[i+colorLength+1] == ',') { FXint code = -1; if(isdigit(txt[i+colorLength+2])) { if(isdigit(txt[i+colorLength+3])) { code = (txt[i+colorLength+2]-48)*10+txt[i+colorLength+3]-48; colorLength +=3; } else { code = txt[i+colorLength+2]-48; colorLength +=2; } } if(code!=-1) backColor = getIrcColor(code%16); } } lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; }; i +=colorLength; } else if(txt[i] == '\017') //reset { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } bold = FALSE; under = FALSE; foreColor = m_colors.text; backColor = m_colors.back; lastStyle = stylenum; } else { normalText.append(txt[i]); } } i++; } if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); } m_text->appendText("\n"); } void IrcTabItem::startLogging() { if(m_logstream && FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()+PATHSEPSTRING+FXSystem::time("%Y-%m-%d", FXSystem::now()))) return; if(m_logging && m_type != SERVER) { if(!FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName())) FXDir::create(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()); if(!FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText())) FXDir::create(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()); m_logstream = new std::ofstream(FXString(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()+PATHSEPSTRING+FXSystem::time("%Y-%m-%d", FXSystem::now())).text(), std::ios::out|std::ios::app); } } void IrcTabItem::stopLogging() { if(m_logstream) { m_logstream->close(); delete m_logstream; m_logstream = NULL; } } void IrcTabItem::logLine(const FXString &line, const FXTime &time) { if(m_logging && m_type != SERVER) { this->startLogging(); *m_logstream << "[" << FXSystem::time("%H:%M:%S", time).text() << "] " << line.text() << std::endl; } } FXbool IrcTabItem::isChannel(const FXString &text) { if(text.length()) return m_engine->getChanTypes().contains(text[0]); return FALSE; } long IrcTabItem::onCommandline(FXObject *, FXSelector, void *) { FXString commandtext = m_commandline->getText(); if(commandtext.empty()) return 1; m_commandsHistory.append(commandtext); if (m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; m_commandline->setText(""); if(comparecase(commandtext.left(4),"/say") != 0) commandtext.substitute("^B", "\002").substitute("^C", "\003").substitute("^O", "\017").substitute("^V", "\026").substitute("^_", "\037"); for(FXint i=0; i<=commandtext.contains('\n'); i++) { FXString text = commandtext.section('\n', i).before('\r'); if(comparecase(text.after('/').before(' '), "quit") == 0 || comparecase(text.after('/').before(' '), "lua") == 0) { processLine(text); return 1; } #ifdef HAVE_LUA if(text[0] != '/') m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_MYMSG), &text); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_COMMAND), &text); if(text[0] == '/' && !m_scriptHasAll) processLine(text); else if(!m_scriptHasMyMsg && !m_scriptHasAll) processLine(text); #else processLine(text); #endif } return 1; } FXbool IrcTabItem::processLine(const FXString& commandtext) { FXString command = (commandtext[0] == '/' ? commandtext.before(' ') : ""); if(!utils::instance().getAlias(command).empty()) { FXString acommand = utils::instance().getAlias(command); if(acommand.contains("%s")) acommand.substitute("%s", commandtext.after(' ')); else acommand += commandtext.after(' '); FXint num = acommand.contains("&&"); if(num) { FXbool result = FALSE; for(FXint i=0; i<=acommand.contains('&'); i++) { if(!acommand.section('&',i).trim().empty()) result = processCommand(acommand.section('&',i).trim()); } return result; } else { return processCommand(acommand); } } return processCommand(commandtext); } FXbool IrcTabItem::processCommand(const FXString& commandtext) { FXString command = (commandtext[0] == '/' ? commandtext.after('/').before(' ').lower() : ""); if(m_type == OTHER) { if(utils::instance().isScriptCommand(command)) { LuaRequest lua; lua.type = LUA_COMMAND; lua.text = commandtext.after('/'); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; } if(command == "commands") { appendIrcStyledText(utils::instance().availableScriptsCommands(), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "egg") { m_text->clearText(); m_text->appendStyledText(FXString("ahoj sem pan Vajรญฤko.\n"), 3); getApp()->addTimeout(this, IrcTabItem_ETIME, 1000); m_pics = 0; return TRUE; } if(command == "help") { return showHelp(commandtext.after(' ').lower().trim()); } if(command == "tetris") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWTETRIS), NULL); return TRUE; } return TRUE; } if(commandtext[0] == '/') { if(utils::instance().isScriptCommand(command)) { LuaRequest lua; lua.type = LUA_COMMAND; lua.text = commandtext.after('/'); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; } if(command == "admin") { if(m_engine->getConnected()) return m_engine->sendAdmin(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "away") { if(m_engine->getConnected()) { if(commandtext.after(' ').length() > m_engine->getAwayLen()) { appendIrcStyledText(FXStringFormat(_("Warning: Away message is too long. Max. away message length is %d."), m_engine->getAwayLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendAway(commandtext.after(' ')); } else return m_engine->sendAway(commandtext.after(' ')); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "banlist") { if(m_engine->getConnected()) { FXString channel = commandtext.after(' '); if(channel.empty() && m_type == CHANNEL) return m_engine->sendBanlist(getText()); else if(!isChannel(channel) && m_type != CHANNEL) { appendIrcStyledText(_("/banlist <channel>, shows banlist for channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendBanlist(channel); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "connect") { if(commandtext.after(' ').empty()) { appendIrcStyledText(_("/connect <server> [port] [nick] [password] [realname] [channels], connects for given server."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { ServerInfo srv; srv.hostname = commandtext.after(' ').section(' ', 0); srv.port = commandtext.after(' ').section(' ', 1).empty() ? 6667 : FXIntVal(commandtext.after(' ').section(' ', 1)); srv.nick = commandtext.after(' ').section(' ', 2).empty() ? FXSystem::currentUserName() : commandtext.after(' ').section(' ', 2); srv.passwd = commandtext.after(' ').section(' ', 3).empty() ? "" : commandtext.after(' ').section(' ', 3); srv.realname = commandtext.after(' ').section(' ', 4).empty() ? FXSystem::currentUserName() : commandtext.after(' ').section(' ', 4); srv.channels = commandtext.after(' ').section(' ', 5).empty() ? "" : commandtext.after(' ').section(' ', 5); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CSERVER), &srv); return TRUE; } } if(command == "commands") { appendIrcStyledText(utils::instance().availableCommands(), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ctcp") { if(m_engine->getConnected()) { FXString to = commandtext.after(' ').before(' '); FXString msg = commandtext.after(' ', 2); if(to.empty() || msg.empty()) { appendIrcStyledText(_("/ctcp <nick> <message>, sends a CTCP message to a user."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(msg.length() > m_maxLen-12-to.length()) { appendIrcStyledText(FXStringFormat(_("Warning: ctcp message is too long. Max. ctcp message length is %d."), m_maxLen-12-to.length()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendCtcp(to, msg); } else return m_engine->sendCtcp(to, msg); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "cycle") { if(m_engine->getConnected()) { if(m_type == CHANNEL) { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); reason.empty() ? m_engine->sendPart(channel) : m_engine->sendPart(channel, reason); return m_engine->sendJoin(channel); } else { commandtext.after(' ').empty() ? m_engine->sendPart(getText()) : m_engine->sendPart(getText(), commandtext.after(' ')); return m_engine->sendJoin(getText()); } } else { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); reason.empty() ? m_engine->sendPart(channel) : m_engine->sendPart(channel, reason); return m_engine->sendJoin(channel); } else { appendIrcStyledText(_("/cycle <channel> [message], leaves and join channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "dcc") { if(m_engine->getConnected()) { FXString dccCommand = utils::instance().getParam(commandtext, 2, FALSE).lower(); if(dccCommand == "chat") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); if(!comparecase(nick, "chat")) { appendIrcStyledText(_("Nick for chat wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Chat with yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCSERVER; ev.param1 = nick; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else if(dccCommand == "send") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); FXString file = utils::instance().getParam(commandtext, 4, TRUE); if(!comparecase(nick, "send")) { appendIrcStyledText(_("Nick for sending file wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Sending to yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, file)) { appendIrcStyledText(_("Filename wasn't entered"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!FXStat::exists(file)) { appendIrcStyledText(FXStringFormat(_("File '%s' doesn't exist"), file.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCOUT; ev.param1 = nick; ev.param2 = file; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else if(dccCommand == "psend") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); FXString file = utils::instance().getParam(commandtext, 4, TRUE); if(!comparecase(nick, "psend")) { appendIrcStyledText(_("Nick for sending file wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Sending to yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, file)) { appendIrcStyledText(_("Filename wasn't entered"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!FXStat::exists(file)) { appendIrcStyledText(FXStringFormat(_("File '%s' doesn't exist"), file.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCPOUT; ev.param1 = nick; ev.param2 = file; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else { appendIrcStyledText(FXStringFormat(_("'%s' isn't dcc command <chat|send|psend>"), dccCommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "deop") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/deop <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/deop <channel> <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/deop <channel> <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "devoice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/devoice <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/devoice <channel> <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/devoice <channel> <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "disconnect") { if(m_engine->getConnected()) { if(commandtext.after(' ').empty()) m_engine->disconnect(); else m_engine->disconnect(commandtext.after(' ')); return TRUE; } else { m_engine->closeConnection(TRUE); return TRUE; } } if(command == "dxirc") { for(FXint i=0; i<5+rand()%5; i++) { appendIrcText("", FXSystem::now(), FALSE, FALSE); } appendIrcText(" __ __ _", FXSystem::now(), FALSE, FALSE); appendIrcText(" _/__//__/|_ | | _", FXSystem::now(), FALSE, FALSE); appendIrcText(" /_| |_| |/_/| __| |__ __|_| _ _ ___", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_ _ _|/ / _ |\\ \\/ /| || '_)/ __)", FXSystem::now(), FALSE, FALSE); appendIrcText(" /_| |_| |/_/| | (_| | | | | || | | (__", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_ _ _|/ \\____|/_/\\_\\|_||_| \\___)", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_|/|_|/ (c) 2008~ David Vachulka", FXSystem::now(), FALSE, FALSE); appendIrcText(" http://dxirc.org", FXSystem::now(), FALSE, FALSE); for(FXint i=0; i<5+rand()%5; i++) { appendIrcText("", FXSystem::now(), FALSE, FALSE); } return TRUE; } if(command == "egg") { m_text->clearText(); m_text->appendStyledText(FXString("ahoj sem pan Vajรญฤko.\n"), 3); getApp()->addTimeout(this, IrcTabItem_ETIME, 1000); m_pics = 0; return TRUE; } if(command == "exec") { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/exec [-o|-c] <command>, executes command, -o sends output to channel/query, -c closes running command."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if(!m_pipe) m_pipe = new dxPipe(getApp(), this); m_pipeStrings.clear(); if(params.before(' ').contains("-o")) { m_sendPipe = TRUE; m_pipe->execCmd(params.after(' ')); } else if(params.before(' ').contains("-c")) { m_sendPipe = FALSE; m_pipeStrings.clear(); m_pipe->stopCmd(); } else { m_sendPipe = FALSE; m_pipe->execCmd(params); } return TRUE; } } if(command == "help") { return showHelp(commandtext.after(' ').lower().trim()); } if(command == "ignore") { FXString ignorecommand = commandtext.after(' ').before(' '); FXString ignoretext = commandtext.after(' ').after(' '); if(ignorecommand.empty()) { appendIrcStyledText(_("/ignore <list|addcmd|rmcmd|addusr|rmusr> [command|user] [channel] [server]"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(comparecase(ignorecommand, "list")==0) { appendIrcStyledText(_("Ignored commands:"), 7, FXSystem::now(), FALSE, FALSE); if(m_commandsList.empty()) appendIrcText(_("No ignored commands"), FXSystem::now(), FALSE, FALSE); else appendIrcText(m_commandsList.rbefore(';'), FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Ignored users:"), 7, FXSystem::now(), FALSE, FALSE); dxIgnoreUserArray users = m_engine->getUsersList(); if(!users.no()) appendIrcText(_("No ignored users"), FXSystem::now(), FALSE, FALSE); else { for(FXint i=0; i<users.no(); i++) { appendIrcText(FXStringFormat(_("%s on channel(s): %s and network: %s"), users[i].nick.text(), users[i].channel.text(), users[i].network.text()), FXSystem::now(), FALSE, FALSE); } } return TRUE; } else if(comparecase(ignorecommand, "addcmd")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore addcmd <command>, adds command to ignored commands."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDICOMMAND), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "rmcmd")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore rmcmd <command>, removes command from ignored commands."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_RMICOMMAND), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "addusr")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore addusr <user> [channel] [server], adds user to ignored users."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDIUSER), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "rmusr")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore rmusr <user>, removes user from ignored users."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_RMIUSER), &ignoretext); return TRUE; } else { appendIrcStyledText(FXStringFormat(_("'%s' isn't <list|addcmd|rmcmd|addusr|rmusr>"), ignorecommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } if(command == "invite") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/invite <nick> <channel>, invites someone to a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/invite <nick> <channel>, invites someone to a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { FXString nick = params.before(' '); FXString channel = params.after(' '); return m_engine->sendInvite(nick, channel); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "join") { if(m_engine->getConnected()) { FXString channel = commandtext.after(' '); if(!isChannel(channel)) { appendIrcStyledText(_("/join <channel>, joins a channel."), 4, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(FXStringFormat(_("'%c' isn't valid char for channel."), channel[0]), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendJoin(channel); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "kick") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/kick <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/kick <channel> <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nick = params.after(' '); FXString reason = params.after(' ', 2); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } else { FXString channel = getText(); FXString nick = params.before(' '); FXString reason = params.after(' '); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nick = params.after(' '); FXString reason = params.after(' ', 2); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } else { appendIrcStyledText(_("/kick <channel> <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "kill") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString nick = params.before(' '); FXString reason = params.after(' '); if(params.empty()) { appendIrcStyledText(_("/kill <user> [reason], kills a user from the network."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(reason.length() > m_maxLen-7-nick.length()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kill is too long. Max. reason length is %d."), m_maxLen-7-nick.length()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKill(nick, reason); } else return m_engine->sendKill(nick, reason); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "list") { if(m_engine->getConnected()) return m_engine->sendList(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "lua") { #ifdef HAVE_LUA FXString luacommand = commandtext.after(' ').before(' '); FXString luatext = commandtext.after(' ').after(' '); LuaRequest lua; if(luacommand.empty()) { appendIrcStyledText(_("/lua <help|load|unload|list> [scriptpath|scriptname]"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(comparecase(luacommand, "help")==0) { appendIrcStyledText(FXStringFormat(_("For help about Lua scripting visit: %s"), LUA_HELP_PATH), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } else if(comparecase(luacommand, "load")==0) lua.type = LUA_LOAD; else if(comparecase(luacommand, "unload")==0) lua.type = LUA_UNLOAD; else if(comparecase(luacommand, "list")==0) lua.type = LUA_LIST; else { appendIrcStyledText(FXStringFormat(_("'%s' isn't <help|load|unload|list>"), luacommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } lua.text = luatext; m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; #else appendIrcStyledText(_("dxirc is compiled without support for Lua scripting"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; #endif } if(command == "me") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/me <message>, sends the action to the current channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString message = params.after(' '); if(channel == getText()) { appendIrcStyledText(getNickName()+" "+message, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = channel; ev.param3 = message; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } if(message.length() > m_maxLen-19-channel.length()) { dxStringArray messages = cutText(message, m_maxLen-19-channel.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(channel, messages[i]) &result; } return result; } else return m_engine->sendMe(channel, message); } else { appendIrcStyledText(getNickName()+" "+params, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = params; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(params.length() > m_maxLen-19-getText().length()) { dxStringArray messages = cutText(params, m_maxLen-19-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(getText(), messages[i]) &result; } return result; } else return m_engine->sendMe(getText(), params); } } else if(m_type == QUERY) { if(params.empty()) { appendIrcStyledText(_("/me <message>, sends the action to the current query."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { appendIrcStyledText(getNickName()+" "+params, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = params; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(params.length() > m_maxLen-19-getText().length()) { dxStringArray messages = cutText(params, m_maxLen-19-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(getText(), messages[i]) &result; } return result; } else return m_engine->sendMe(getText(), params); } } else { if(!params.after(' ').empty()) { FXString to = params.before(' '); FXString message = params.after(' '); if(message.length() > m_maxLen-19-to.length()) { dxStringArray messages = cutText(message, m_maxLen-19-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(to, messages[i]) &result; } return result; } else return m_engine->sendMe(to, message); } else { appendIrcStyledText(_("/me <to> <message>, sends the action."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "mode") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/mode <channel> <modes>, sets modes for a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendMode(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "msg") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString to = params.before(' '); FXString message = params.after(' '); if(!to.empty() && !message.empty()) { if(to == getText()) { if(m_coloredNick) appendIrcNickText(getNickName(), message, getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), message, 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = to; ev.param3 = message; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } if(message.length() > m_maxLen-10-to.length()) { dxStringArray messages = cutText(message, m_maxLen-10-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(to, messages[i]) &result; } return result; } else return m_engine->sendMsg(to, message); } else { appendIrcStyledText(_("/msg <nick/channel> <message>, sends a normal message."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "names") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) return m_engine->sendNames(getText()); else return m_engine->sendNames(params); } else { if(params.empty()) { appendIrcStyledText(_("/names <channel>, for nicks on a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendNames(params); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "nick") { if(m_engine->getConnected()) { FXString nick = commandtext.after(' '); if(nick.empty()) { appendIrcStyledText(_("/nick <nick>, changes nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(nick.length() > m_engine->getNickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: nick is too long. Max. nick length is %d."), m_engine->getNickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendNick(nick); } else { return m_engine->sendNick(nick); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "notice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString to = params.before(' '); FXString message = params.after(' '); if(!to.empty() && !message.empty()) { appendIrcStyledText(FXStringFormat(_("NOTICE to %s: %s"), to.text(), message.text()), 2, FXSystem::now()); if(message.length() > m_maxLen-9-to.length()) { dxStringArray messages = cutText(message, m_maxLen-9-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendNotice(to, messages[i]) &result; } return result; } return m_engine->sendNotice(to, message); } else { appendIrcStyledText(_("/notice <nick/channel> <message>, sends a notice."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "op") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/op <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/op <channel> <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/op <channel> <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "oper") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString login = params.before(' '); FXString password = params.after(' '); if(!login.empty() && !password.empty()) return m_engine->sendOper(login, password); else { appendIrcStyledText(_("/oper <login> <password>, oper up."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "part") { if(m_engine->getConnected()) { if(m_type == CHANNEL) { if(commandtext.after(' ').empty()) return m_engine->sendPart(getText()); else return m_engine->sendPart(getText(), commandtext.after(' ')); } else { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); if(reason.empty()) return m_engine->sendPart(channel); else return m_engine->sendPart(channel, reason); } else { appendIrcStyledText(_("/part <channel> [reason], leaves channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "query") { if(m_engine->getConnected()) { if(commandtext.after(' ').empty()) { appendIrcStyledText(_("/query <nick>, opens query with nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = commandtext.after(' ').before(' '); ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "quit") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CQUIT), NULL); return TRUE; } if(command == "quote") { if(m_engine->getConnected()) return m_engine->sendQuote(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "say") { if(m_engine->getConnected()) { if (m_type != SERVER && !commandtext.after(' ').empty()) { if(m_coloredNick) appendIrcNickText(getNickName(), commandtext.after(' '), getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), commandtext.after(' '), 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = commandtext.after(' '); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(commandtext.after(' ').length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(commandtext.after(' '), m_maxLen-10-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(getText(), messages[i]) &result; } return result; } else return m_engine->sendMsg(getText(), commandtext.after(' ')); } return FALSE; } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "stats") { if(m_engine->getConnected()) return m_engine->sendStats(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "tetris") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWTETRIS), NULL); return TRUE; } if(command == "time") { if(m_engine->getConnected()) return m_engine->sendQuote("TIME"); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "topic") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) return m_engine->sendTopic(getText()); else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString topic = params.after(' '); if(topic.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(channel, topic); } else return m_engine->sendTopic(channel, topic); } else { if(params.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(getText(), params); } else return m_engine->sendTopic(getText(), params); } } else { if(isChannel(params)) { FXString channel = params.before(' '); FXString topic = params.after(' '); if(topic.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(channel, params); } else return m_engine->sendTopic(channel, topic); } else { appendIrcStyledText(_("/topic <channel> [topic], views or changes channel topic."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "voice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/voice <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/voice <channel> <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/voice <channel> <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "wallops") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/wallops <message>, sends wallop message."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if(params.length() > m_maxLen-9) { dxStringArray messages = cutText(params, m_maxLen-9); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendWallops(messages[i]) &result; } return result; } else return m_engine->sendWallops(params); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "who") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/who <mask> [o], searchs for mask on network, if o is supplied, only search for opers."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWho(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whoami") { if(m_engine->getConnected()) return m_engine->sendWhoami(); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whois") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { if(m_type == QUERY) return m_engine->sendWhois(getText()); appendIrcStyledText(_("/whois <nick>, whois nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWhois(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whowas") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/whowas <nick>, whowas nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWhowas(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } appendIrcStyledText(FXStringFormat(_("Unknown command '%s', type /commands for available commands"), command.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if (command.empty() && m_type != SERVER && !commandtext.empty() && m_engine->getConnected()) { if(m_coloredNick) appendIrcNickText(getNickName(), commandtext, getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), commandtext, 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = commandtext; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(commandtext.length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(commandtext, m_maxLen-10-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(getText(), messages[i]) &result; } return result; } else return m_engine->sendMsg(getText(), commandtext); } if(!m_engine->getConnected()) { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } return FALSE; } return FALSE; } FXbool IrcTabItem::showHelp(FXString command) { if(utils::instance().isScriptCommand(command)) { appendIrcStyledText(utils::instance().getHelpText(command), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "admin") { appendIrcStyledText(_("ADMIN [server], finds information about administrator for current server or [server]."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "away") { appendIrcStyledText(_("AWAY [message], sets away status."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "banlist") { appendIrcStyledText(_("BANLIST <channel>, shows banlist for channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "commands") { appendIrcStyledText(_("COMMANDS, shows available commands"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "connect") { appendIrcStyledText(_("CONNECT <server> [port] [nick] [password] [realname] [channels], connects for given server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ctcp") { appendIrcStyledText(_("CTCP <nick> <message>, sends a CTCP message to a user."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "cycle") { appendIrcStyledText(_("CYCLE <channel> [message], leaves and join channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "dcc") { appendIrcStyledText(_("DCC chat <nick>, starts DCC chat."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("DCC send <nick> <filename>, sends file over DCC."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("DCC psend <nick> <filename>, sends file passive over DCC."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("More information about passive DCC on http://en.wikipedia.org/wiki/Direct_Client-to-Client#Passive_DCC"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "deop") { appendIrcStyledText(_("DEOP <channel> <nicks>, removes operator status from one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "devoice") { appendIrcStyledText(_("DEVOICE <channel> <nicks>, removes voice from one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "disconnect") { appendIrcStyledText(_("DISCONNECT [reason], leaves server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #ifndef WIN32 if(command == "exec") { appendIrcStyledText(_("EXEC [-o|-c] <command>, executes command, -o sends output to channel/query, -c closes running command."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #endif if(command == "help") { appendIrcStyledText(_("HELP <command>, shows help for command."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ignore") { appendIrcStyledText(_("IGNORE list, shows list ignored commands and users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE addcmd <command>, adds command to ignored commands."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE rmcmd <command>, removes command from ignored commands."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE addusr <user> [channel] [server], adds user to ignored users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE rmusr <user>, removes user from ignored users."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "invite") { appendIrcStyledText(_("INVITE <nick> <channel>, invites someone to a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "join") { appendIrcStyledText(_("JOIN <channel>, joins a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "kick") { appendIrcStyledText(_("KICK <channel> <nick>, kicks a user from a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "kill") { appendIrcStyledText(_("KILL <user> [reason], kills a user from the network."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "list") { appendIrcStyledText(_("LIST [channel], lists channels and their topics."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #ifdef HAVE_LUA if(command == "lua") { appendIrcStyledText(_("LUA help, shows help for lua scripting."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA load <path>, loads script."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Example: /lua load /home/dvx/test.lua"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA unload <name>, unloads script."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Example: /lua unload test"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA list, shows list of loaded scripts"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #else if(command == "lua") { appendIrcStyledText(_("dxirc is compiled without support for Lua scripting"), 4, FXSystem::now(), FALSE, FALSE); return TRUE; } #endif if(command == "me") { appendIrcStyledText(_("ME <to> <message>, sends the action."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "mode") { appendIrcStyledText(_("MODE <channel> <modes>, sets modes for a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "msg") { appendIrcStyledText(_("MSG <nick/channel> <message>, sends a normal message."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "names") { appendIrcStyledText(_("NAMES <channel>, for nicks on a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "nick") { appendIrcStyledText(_("NICK <nick>, changes nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "notice") { appendIrcStyledText(_("NOTICE <nick/channel> <message>, sends a notice."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "op") { appendIrcStyledText(_("OP <channel> <nicks>, gives operator status for one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "oper") { appendIrcStyledText(_("OPER <login> <password>, oper up."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "part") { appendIrcStyledText(_("PART <channel> [reason], leaves channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "query") { appendIrcStyledText(_("QUERY <nick>, opens query with nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "quit") { appendIrcStyledText(_("QUIT, closes application."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "quote") { appendIrcStyledText(_("QUOTE [text], sends text to server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "say") { appendIrcStyledText(_("SAY [text], sends text to current tab."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "stats") { appendIrcStyledText(_("STATS <type>, shows some irc server usage statistics. Available types vary slightly per server; some common ones are:"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("c - shows C and N lines for a given server. These are the names of the servers that are allowed to connect."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("h - shows H and L lines for a given server (Hubs and Leaves)."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("k - show K lines for a server. This shows who is not allowed to connect and possibly at what time they are not allowed to connect."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("i - shows I lines. This is who CAN connect to a server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("l - shows information about amount of information passed to servers and users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("m - shows a count for the number of times the various commands have been used since the server was booted."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("o - shows the list of authorized operators on the server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("p - shows online operators and their idle times."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("u - shows the uptime for a server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("y - shows Y lines, which lists the various connection classes for a given server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "tetris") { appendIrcStyledText(_("TETRIS, start small easteregg."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Keys for playing:"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("n .. new game"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("p .. pause game"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("i .. rotate piece"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("l .. move piece right"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("k .. drop piece"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("j .. move piece left"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "time") { appendIrcStyledText(_("TIME, displays the time of day, local to server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "topic") { appendIrcStyledText(_("TOPIC [topic], sets or shows topic."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "voice") { appendIrcStyledText(_("VOICE <channel> <nicks>, gives voice for one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "wallops") { appendIrcStyledText(_("WALLOPS <message>, sends wallop message."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "who") { appendIrcStyledText(_("WHO <mask> [o], searchs for mask on network, if o is supplied, only search for opers."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whoami") { appendIrcStyledText(_("WHOAMI, whois about you."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whois") { appendIrcStyledText(_("WHOIS <nick>, whois nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whowas") { appendIrcStyledText(_("WHOWAS <nick>, whowas nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(!utils::instance().getAlias(command[0] == '/' ? command:"/"+command).empty()) { appendIrcStyledText(FXStringFormat("%s: %s", command.upper().text(), utils::instance().getAlias(command[0] == '/' ? command:"/"+command).text()), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command.empty()) appendIrcStyledText(_("Command is empty, type /commands for available commands"), 4, FXSystem::now(), FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("Unknown command '%s', type /commands for available commands"), command.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } long IrcTabItem::onKeyPress(FXObject *, FXSelector, void *ptr) { if (m_commandline->hasFocus()) { FXEvent* event = (FXEvent*)ptr; FXString line = m_commandline->getText(); switch(event->code){ case KEY_Tab: if(event->state&CONTROLMASK) { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEXTTAB), NULL); return 1; } if(line[0] == '/' && line.after(' ').empty()) { for(FXint i = 0; i < utils::instance().commandsNo(); i++) { if(comparecase(line.after('/').before(' '), utils::instance().commandsAt(i)) == 0) { if((i+1) < utils::instance().commandsNo()) m_commandline->setText("/"+utils::instance().commandsAt(++i)+" "); else m_commandline->setText("/"+utils::instance().commandsAt(0)+" "); break; } else if(comparecase(line.after('/'), utils::instance().commandsAt(i).left(line.after('/').length())) == 0) { m_commandline->setText("/"+utils::instance().commandsAt(i)+" "); break; } } return 1; } if(line[0] != '/' && line.after(' ').empty()) { if(line.empty()) { m_commandline->setText(getNick(0)+m_nickCompletionChar+" "); return 1; } for(FXint j = 0; j < m_users->getNumItems() ; j++) { if(comparecase(line, getNick(j).left(line.length())) == 0) { m_commandline->setText(getNick(j)+m_nickCompletionChar+" "); break; } else if(comparecase(line.section(m_nickCompletionChar, 0, 1), getNick(j)) == 0) { if((j+1) < m_users->getNumItems()) m_commandline->setText(getNick(++j)+m_nickCompletionChar+" "); else m_commandline->setText(getNick(0)+m_nickCompletionChar+" "); break; } } return 1; } if(line.find(' ') != -1) { FXint curpos; line[m_commandline->getCursorPos()] == ' ' ? curpos = m_commandline->getCursorPos()-1 : curpos = m_commandline->getCursorPos(); FXint pos = line.rfind(' ', curpos)+1; FXint n = line.find(' ', curpos)>0 ? line.find(' ', curpos)-pos : line.length()-pos; FXString toCompletion = line.mid(pos, n); for(FXint j = 0; j < m_users->getNumItems(); j++) { if(comparecase(toCompletion, getNick(j)) == 0) { if((j+1) < m_users->getNumItems()) { m_commandline->setText(line.replace(pos, n, getNick(j+1))); m_commandline->setCursorPos(pos+getNick(j+1).length()); } else { m_commandline->setText(line.replace(pos, n, getNick(0))); m_commandline->setCursorPos(pos+getNick(0).length()); } break; } else if(comparecase(toCompletion, getNick(j).left(toCompletion.length())) == 0) { m_commandline->setText(line.replace(pos, n, getNick(j))); m_commandline->setCursorPos(pos+getNick(j).length()); break; } } return 1; } return 1; case KEY_Up: if(m_currentPosition!=-1 && m_currentPosition<m_commandsHistory.no()) { if(!line.empty() && line!=m_commandsHistory[m_currentPosition]) { m_commandsHistory.append(line); if(m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; } if(m_currentPosition > 0 && !line.empty()) --m_currentPosition; m_commandline->setText(m_commandsHistory[m_currentPosition]); } return 1; case KEY_Down: if(m_currentPosition!=-1 && m_currentPosition<m_commandsHistory.no()) { if(!line.empty() && line!=m_commandsHistory[m_currentPosition]) { m_commandsHistory.append(line); if(m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; } if(m_currentPosition < m_commandsHistory.no()-1) { ++m_currentPosition; m_commandline->setText(m_commandsHistory[m_currentPosition]); } else m_commandline->setText(""); } return 1; case KEY_k: case KEY_K: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^C")); //color m_commandline->setCursorPos(pos+2); return 1; } case KEY_b: case KEY_B: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^B")); //bold m_commandline->setCursorPos(pos+2); return 1; } case KEY_i: case KEY_I: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^_")); //underline m_commandline->setCursorPos(pos+2); return 1; } case KEY_r: case KEY_R: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^V")); //reverse m_commandline->setCursorPos(pos+2); return 1; } case KEY_o: case KEY_O: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(m_commandline->getCursorPos(), "^O")); //reset m_commandline->setCursorPos(pos+2); return 1; } } } return 0; } //Check is this tab right for server message (e.g. not for IRC_SERVERREPLY) FXbool IrcTabItem::isRightForServerMsg() { //Check if current tab is in server targets if(m_engine->findTarget(m_parent->childAtIndex(m_parent->getCurrent()*2))) { return m_parent->indexOfChild(this) == m_parent->getCurrent()*2; } else { FXint indexOfThis = m_parent->indexOfChild(this); for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_engine->findTarget(m_parent->childAtIndex(i))) { if(i == indexOfThis) return TRUE; else return FALSE; } } } return FALSE; } FXbool IrcTabItem::isCommandIgnored(const FXString &command) { if(m_commandsList.contains(command)) return TRUE; return FALSE; } void IrcTabItem::addUser(const FXString& user, UserMode mode) { if(mode == ADMIN && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCADMIN); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == OWNER && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCOWNER); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == OP && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCOP); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == VOICE && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCVOICE); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == HALFOP && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCHALFOP); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == NONE && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCNORMAL); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } } void IrcTabItem::removeUser(const FXString& user) { if(m_users->findItem(user) != -1) { m_users->removeItem(m_users->findItem(user)); } m_numberUsers--; m_users->sortItems(); } void IrcTabItem::changeNickUser(const FXString& nick, const FXString& newnick) { FXint i = m_users->findItem(nick); if(i != -1) { m_users->getItem(i)->setText(newnick); m_users->sortItems(); } } void IrcTabItem::setUserMode(const FXString& nick, UserMode mode) { FXint i = m_users->findItem(nick); if(i != -1) { ((NickListItem*)m_users->getItem(i))->setUserMode(mode); } } UserMode IrcTabItem::getUserMode(const FXchar mode) { if(mode == m_engine->getAdminPrefix()) return ADMIN; if(mode == m_engine->getOwnerPrefix()) return OWNER; if(mode == m_engine->getOpPrefix()) return OP; if(mode == m_engine->getHalfopPrefix()) return HALFOP; if(mode == m_engine->getVoicePrefix()) return VOICE; return NONE; } long IrcTabItem::onIrcEvent(FXObject *, FXSelector, void *data) { IrcEvent *ev = (IrcEvent *) data; if(ev->eventType == IRC_PRIVMSG) { onIrcPrivmsg(ev); return 1; } if(ev->eventType == IRC_ACTION) { onIrcAction(ev); return 1; } if(ev->eventType == IRC_CTCPREPLY) { onIrcCtpcReply(ev); return 1; } if(ev->eventType == IRC_CTCPREQUEST) { onIrcCtcpRequest(ev); return 1; } if(ev->eventType == IRC_JOIN) { onIrcJoin(ev); return 1; } if(ev->eventType == IRC_QUIT) { onIrcQuit(ev); return 1; } if(ev->eventType == IRC_PART) { onIrcPart(ev); return 1; } if(ev->eventType == IRC_CHNOTICE) { onIrcChnotice(ev); return 1; } if(ev->eventType == IRC_NOTICE) { onIrcNotice(ev); return 1; } if(ev->eventType == IRC_NICK) { onIrcNick(ev); return 1; } if(ev->eventType == IRC_TOPIC) { onIrcTopic(ev); return 1; } if(ev->eventType == IRC_INVITE) { onIrcInvite(ev); return 1; } if(ev->eventType == IRC_KICK) { onIrcKick(ev); return 1; } if(ev->eventType == IRC_MODE) { onIrcMode(ev); return 1; } if(ev->eventType == IRC_UMODE) { onIrcUmode(ev); return 1; } if(ev->eventType == IRC_CHMODE) { onIrcChmode(ev); return 1; } if(ev->eventType == IRC_SERVERREPLY) { onIrcServerReply(ev); return 1; } if(ev->eventType == IRC_CONNECT) { onIrcConnect(ev); return 1; } if(ev->eventType == IRC_ERROR) { onIrcError(ev); return 1; } if(ev->eventType == IRC_SERVERERROR) { onIrcServerError(ev); return 1; } if(ev->eventType == IRC_DISCONNECT) { onIrcDisconnect(ev); return 1; } if(ev->eventType == IRC_RECONNECT) { onIrcReconnect(ev); return 1; } if(ev->eventType == IRC_UNKNOWN) { onIrcUnknown(ev); return 1; } if(ev->eventType == IRC_301) { onIrc301(ev); return 1; } if(ev->eventType == IRC_305) { onIrc305(ev); return 1; } if(ev->eventType == IRC_306) { onIrc306(ev); return 1; } if(ev->eventType == IRC_331 || ev->eventType == IRC_332 || ev->eventType == IRC_333) { onIrc331332333(ev); return 1; } if(ev->eventType == IRC_353) { onIrc353(ev); return 1; } if(ev->eventType == IRC_366) { onIrc366(ev); return 1; } if(ev->eventType == IRC_372) { onIrc372(ev); return 1; } if(ev->eventType == IRC_AWAY) { onIrcAway(ev); return 1; } if(ev->eventType == IRC_ENDMOTD) { onIrcEndMotd(); return 1; } return 1; } //handle IrcEvent IRC_PRIVMSG void IrcTabItem::onIrcPrivmsg(IrcEvent* ev) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); if(m_coloredNick) { if(needHighlight) appendIrcStyledText(ev->param1+": "+ev->param3, 8, ev->time); else appendIrcNickText(ev->param1, ev->param3, getNickColor(ev->param1), ev->time); } else { if(needHighlight) appendIrcStyledText(ev->param1+": "+ev->param3, 8, ev->time); else appendIrcNickText(ev->param1, ev->param3, 5, ev->time); } if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } //handle IrcEvent IRC_ACTION void IrcTabItem::onIrcAction(IrcEvent* ev) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { if(!isCommandIgnored("me")) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); appendIrcStyledText(ev->param1+" "+ev->param3, 2, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } } //handle IrcEvent IRC_CTCPREPLY void IrcTabItem::onIrcCtpcReply(IrcEvent* ev) { if(isRightForServerMsg()) { if(!isCommandIgnored("ctcp")) { appendIrcStyledText(FXStringFormat(_("CTCP %s reply from %s: %s"), utils::instance().getParam(ev->param2, 1, FALSE).text(), ev->param1.text(), utils::instance().getParam(ev->param2, 2, TRUE).text()), 2, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_CTCPREQUEST void IrcTabItem::onIrcCtcpRequest(IrcEvent* ev) { if(isRightForServerMsg()) { if(!isCommandIgnored("ctcp")) { appendIrcStyledText(FXStringFormat(_("CTCP %s request from %s"), ev->param2.text(), ev->param1.text()), 2, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_JOIN void IrcTabItem::onIrcJoin(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0 && ev->param1 != getNickName()) { if(!isCommandIgnored("join") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has joined to %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); addUser(ev->param1, NONE); } } //handle IrcEvent IRC_QUIT void IrcTabItem::onIrcQuit(IrcEvent* ev) { if(m_type == CHANNEL && m_users->findItem(ev->param1) != -1) { removeUser(ev->param1); if(ev->param2.empty()) { if(!isCommandIgnored("quit") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has quit"), ev->param1.text()), 1, ev->time); } else { if(!isCommandIgnored("quit") && !m_engine->isUserIgnored(ev->param1, getText()))appendIrcStyledText(FXStringFormat(_("%s has quit (%s)"), ev->param1.text(), +ev->param2.text()), 1, ev->time); } } else if(m_type == QUERY && getText() == ev->param1) { appendIrcStyledText(FXStringFormat(_("%s has quit"), ev->param1.text()), 1, ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_PART void IrcTabItem::onIrcPart(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0) { if(ev->param3.empty() && !isCommandIgnored("part") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has parted %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); else if(!isCommandIgnored("part") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has parted %s (%s)"), ev->param1.text(), ev->param2.text(), ev->param3.text()), 1, ev->time); removeUser(ev->param1); } } //handle IrcEvent IRC_CHNOTICE void IrcTabItem::onIrcChnotice(IrcEvent* ev) { if(!isCommandIgnored("notice")) { FXbool tabExist = FALSE; for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_parent->childAtIndex(i)->getMetaClass()==&IrcTabItem::metaClass && m_engine->findTarget(static_cast<IrcTabItem*>(m_parent->childAtIndex(i)))) { if((comparecase(ev->param2, static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getText()) == 0 && static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getType() == CHANNEL) || (ev->param1 == static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getText() && static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getType() == QUERY && ev->param2 == static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getNickName())) { tabExist = TRUE; break; } } } if(tabExist) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param3.text()), 2, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } else { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param3.text()), 3, ev->time); } } } } //handle IrcEvent IRC_NOTICE void IrcTabItem::onIrcNotice(IrcEvent* ev) { if(isRightForServerMsg()) { if(ev->param1 == getNickName() && !isCommandIgnored("notice")) { appendIrcStyledText(FXStringFormat(_("NOTICE for you: %s"), ev->param2.text()), 3, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } else if(!isCommandIgnored("notice")) { appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param2.text()), 3, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_NICK void IrcTabItem::onIrcNick(IrcEvent* ev) { if(m_users->findItem(ev->param1) != -1) { if(ev->param2 == getNickName() && !isCommandIgnored("nick")) appendIrcStyledText(FXStringFormat(_("You're now known as %s"), ev->param2.text()), 1, ev->time); else if(!isCommandIgnored("nick") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s is now known as %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); changeNickUser(ev->param1, ev->param2); } if(m_type == QUERY && ev->param1 == getText()) { this->setText(ev->param2); stopLogging(); } } //handle IrcEvent IRC_TOPIC void IrcTabItem::onIrcTopic(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0) { appendIrcText(FXStringFormat(_("%s set new topic for %s: %s"), ev->param1.text(), ev->param2.text(), ev->param3.text()), ev->time); m_topic = stripColors(ev->param3, TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } } //handle IrcEvent IRC_INVITE void IrcTabItem::onIrcInvite(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("%s invites you to: %s"), ev->param1.text(), ev->param3.text()), 3, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_KICK void IrcTabItem::onIrcKick(IrcEvent* ev) { if(comparecase(ev->param3, getText()) == 0) { if(ev->param2 != getNickName()) { if(ev->param4.empty()) appendIrcStyledText(FXStringFormat(_("%s was kicked from %s by %s"), ev->param2.text(), ev->param3.text(), ev->param1.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s was kicked from %s by %s (%s)"), ev->param2.text(), ev->param3.text(), ev->param1.text(), ev->param4.text()), 1, ev->time, FALSE, FALSE); removeUser(ev->param2); } } if(ev->param2 == getNickName() && isRightForServerMsg()) { if(ev->param4.empty()) appendIrcStyledText(FXStringFormat(_("You were kicked from %s by %s"), ev->param3.text(), ev->param1.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("You were kicked from %s by %s (%s)"), ev->param3.text(), ev->param1.text(), ev->param4.text()), 1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_MODE void IrcTabItem::onIrcMode(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("Mode change [%s] for %s"), ev->param1.text(), ev->param2.text()), 1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_UMODE void IrcTabItem::onIrcUmode(IrcEvent* ev) { FXString moderator = ev->param1; FXString channel = ev->param2; FXString modes = ev->param3; FXString args = ev->param4; if(comparecase(channel, getText()) == 0) { FXbool sign = FALSE; int argsiter = 1; for(int i =0; i < modes.count(); i++) { switch(modes[i]) { case '+': sign = TRUE; break; case '-': sign = FALSE; break; case 'a': //admin { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?ADMIN:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you admin"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s admin"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you admin"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s admin"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'o': //op { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?OP:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you op"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s op"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you op"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s op"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } if(getNickName() == nick) sign ? m_iamOp = TRUE : m_iamOp = FALSE; argsiter++; }break; case 'v': //voice { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?VOICE:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you voice"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s voice"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you voice"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s voice"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'h': //halfop { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?HALFOP:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you halfop"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s halfop"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you halfop"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s halfop"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'b': //ban { FXString banmask = utils::instance().getParam(args, argsiter, FALSE); onBan(banmask, sign, moderator, ev->time); argsiter++; }break; case 't': //topic settable by channel operator { sign ? m_editableTopic = FALSE : m_editableTopic = TRUE; } default: { appendIrcStyledText(FXStringFormat(_("%s set Mode: %s"), moderator.text(), FXString(modes+" "+args).text()), 1, ev->time, FALSE, FALSE); } } } } } //handle IrcEvent IRC_CHMODE void IrcTabItem::onIrcChmode(IrcEvent* ev) { FXString channel = ev->param1; FXString modes = ev->param2; if(comparecase(channel, getText()) == 0) { if(modes.contains('t')) m_editableTopic = FALSE; appendIrcStyledText(FXStringFormat(_("Mode for %s: %s"), channel.text(), modes.text()), 1, ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_SERVERREPLY void IrcTabItem::onIrcServerReply(IrcEvent* ev) { if(m_ownServerWindow) { if(m_type == SERVER) { //this->setText(server->GetRealServerName()); appendIrcText(ev->param1, ev->time); if(getApp()->getForeColor() == this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } else { if(isRightForServerMsg()) { appendIrcText(ev->param1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_CONNECT void IrcTabItem::onIrcConnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 3, ev->time, FALSE, FALSE); } //handle IrcEvent IRC_ERROR void IrcTabItem::onIrcError(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); } //handle IrcEvent IRC_SERVERERROR void IrcTabItem::onIrcServerError(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_DISCONNECT void IrcTabItem::onIrcDisconnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(isRightForServerMsg()) { if(m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_highlightColor); } if(m_type == CHANNEL) { m_users->clearItems(); m_iamOp = FALSE; } } //handle IrcEvent IRC_RECONNECT void IrcTabItem::onIrcReconnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(isRightForServerMsg()) { if(m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_highlightColor); } if(m_type == CHANNEL) { m_users->clearItems(); m_iamOp = FALSE; } } //handle IrcEvent IRC_UNKNOWN void IrcTabItem::onIrcUnknown(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("Unhandled command '%s' params: %s"), ev->param1.text(), ev->param2.text()), 4, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_301 void IrcTabItem::onIrc301(IrcEvent* ev) { if(m_parent->getCurrent()*2 == m_parent->indexOfChild(this) || getText() == ev->param1) { if(!isCommandIgnored("away") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s is away: %s"),ev->param1.text(), ev->param2.text()), 1, ev->time); } } //handle IrcEvent IRC_305 void IrcTabItem::onIrc305(IrcEvent* ev) { FXint i = m_users->findItem(getNickName()); if(i != -1) { appendIrcStyledText(ev->param1, 1, ev->time, FALSE, FALSE); ((NickListItem*)m_users->getItem(i))->changeAway(FALSE); } } //handle IrcEvent IRC_306 void IrcTabItem::onIrc306(IrcEvent* ev) { FXint i = m_users->findItem(getNickName()); if(i != -1) { appendIrcStyledText(ev->param1, 1, ev->time, FALSE, FALSE); ((NickListItem*)m_users->getItem(i))->changeAway(TRUE); } } //handle IrcEvent IRC_331, IRC_332 and IRC_333 void IrcTabItem::onIrc331332333(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { appendIrcText(ev->param2, ev->time); if(ev->eventType == IRC_331) { m_topic = stripColors(ev->param2, TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } if(ev->eventType == IRC_332) { m_topic = stripColors(utils::instance().getParam(ev->param2, 2, TRUE, ':').after(' '), TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } } } //handle IrcEvent IRC_353 void IrcTabItem::onIrc353(IrcEvent* ev) { FXString channel = ev->param1; FXString usersStr = ev->param2; FXString myNick = getNickName(); if(usersStr.right(1) != " ") usersStr.append(" "); if(comparecase(channel, getText()) == 0) { while (usersStr.contains(' ')) { FXString nick = usersStr.before(' '); UserMode mode = getUserMode(nick[0]); if(mode != NONE) nick = nick.after(nick[0]); addUser(nick, mode); if(mode == OP && nick == myNick) m_iamOp = TRUE; usersStr = usersStr.after(' '); } } else { FXbool channelOn = FALSE; for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_engine->findTarget(static_cast<IrcTabItem*>(m_parent->childAtIndex(i))) && comparecase(static_cast<FXTabItem*>(m_parent->childAtIndex(i))->getText(), channel) == 0) { channelOn = TRUE; break; } } if(!channelOn && !isCommandIgnored("numeric")) appendIrcText(FXStringFormat(_("Users on %s: %s"), channel.text(), usersStr.text()), ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_366 void IrcTabItem::onIrc366(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { m_engine->addIgnoreWho(getText()); } } //handle IrcEvent IRC_372 void IrcTabItem::onIrc372(IrcEvent* ev) { if(m_ownServerWindow) { if(m_type == SERVER) { appendIrcText(ev->param1, ev->time); if(getApp()->getForeColor() == this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } else { if(isRightForServerMsg()) { appendIrcText(ev->param1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_AWAY void IrcTabItem::onIrcAway(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { onAway(); } } //handle IrcEvent IRC_ENDMOTD void IrcTabItem::onIrcEndMotd() { m_text->makeLastRowVisible(TRUE); if(m_type == SERVER && !m_engine->getNetworkName().empty()) setText(m_engine->getNetworkName()); } long IrcTabItem::onPipe(FXObject*, FXSelector, void *ptr) { FXString text = *(FXString*)ptr; if(m_sendPipe && (m_type == CHANNEL || m_type == QUERY)) { if(!getApp()->hasTimeout(this, IrcTabItem_PTIME)) getApp()->addTimeout(this, IrcTabItem_PTIME); m_pipeStrings.append(text); } else appendIrcText(text, FXSystem::now()); return 1; } //checking away in channel void IrcTabItem::checkAway() { if(m_type == CHANNEL && m_engine->getConnected() && m_numberUsers < m_maxAway) { m_engine->addIgnoreWho(getText()); } } long IrcTabItem::onPipeTimeout(FXObject*, FXSelector, void*) { if(m_type == CHANNEL || m_type == QUERY) { if(m_pipeStrings.no() > 3) { if(m_pipeStrings[0].empty()) m_pipeStrings[0] = " "; if(m_pipeStrings[0].length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(m_pipeStrings[0], m_maxLen-10-getText().length()); for(FXint i=0; i<messages.no(); i++) { if(m_coloredNick) appendIrcNickText(getNickName(), messages[i], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), messages[i], 5, FXSystem::now()); m_engine->sendMsg(getText(), messages[i]); } } else { if(m_coloredNick) appendIrcNickText(getNickName(), m_pipeStrings[0], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), m_pipeStrings[0], 5, FXSystem::now()); m_engine->sendMsg(getText(), m_pipeStrings[0]); } m_pipeStrings.erase(0); getApp()->addTimeout(this, IrcTabItem_PTIME, 3000); } else { while(m_pipeStrings.no()) { if(m_pipeStrings[0].empty()) m_pipeStrings[0] = " "; if(m_pipeStrings[0].length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(m_pipeStrings[0], m_maxLen-10-getText().length()); for(FXint i=0; i<messages.no(); i++) { if(m_coloredNick) appendIrcNickText(getNickName(), messages[i], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), messages[i], 5, FXSystem::now()); m_engine->sendMsg(getText(), messages[i]); } } else { if(m_coloredNick) appendIrcNickText(getNickName(), m_pipeStrings[0], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), m_pipeStrings[0], 5, FXSystem::now()); m_engine->sendMsg(getText(), m_pipeStrings[0]); } m_pipeStrings.erase(0); } } } return 1; } long IrcTabItem::onEggTimeout(FXObject*, FXSelector, void*) { if(m_pics<24) { getApp()->addTimeout(this, IrcTabItem_ETIME, 222); FXString replace = "\n"; FXint max = rand()%30; for(FXint i=0; i<max; i++) replace.append(' '); FXString pic = "\n ยฉยฉยฉยฉยฉยฉ\n ยฉ ยฉ\n ยฉ ยฉ\n ยฉ ยฉ\nยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉ\nยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉ\nยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉยฉ\n ยฉ ยฉ\n ยฉ ยฉ\n ยฉ ยฉ\n ยฉยฉยฉยฉยฉยฉ"; pic.substitute("\n", replace); pic.append('\n'); m_text->clearText(); max = rand()%15; for(FXint i=0; i<max; i++) pic.prepend('\n'); max = rand()%7; m_text->appendStyledText(pic, max+10); m_pics++; } return 1; } void IrcTabItem::onAway() { if(m_numberUsers < m_maxAway) { for(FXint i = 0; i < m_users->getNumItems(); i++) { FXbool away = m_engine->getNickInfo(m_users->getItemText(i)).away; ((NickListItem*)m_users->getItem(i))->changeAway(away); } } else { for(FXint i = 0; i < m_users->getNumItems(); i++) { ((NickListItem*)m_users->getItem(i))->changeAway(FALSE); } } } long IrcTabItem::onTextLink(FXObject *, FXSelector, void *data) { utils::instance().launchLink(static_cast<FXchar*>(data)); return 1; } long IrcTabItem::onRightMouse(FXObject *, FXSelector, void *ptr) { //focus(); FXEvent* event = (FXEvent*)ptr; if(event->moved) return 1; FXint index = m_users->getItemAt(event->win_x,event->win_y); if(index >= 0) { NickInfo nick = m_engine->getNickInfo(m_users->getItemText(index)); m_nickOnRight = nick; FXString flagpath = DXIRC_DATADIR PATHSEPSTRING "icons" PATHSEPSTRING "flags"; delete ICO_FLAG; ICO_FLAG = NULL; if(FXStat::exists(flagpath+PATHSEPSTRING+nick.host.rafter('.')+".png")) ICO_FLAG = makeIcon(getApp(), flagpath, nick.host.rafter('.')+".png", TRUE); else ICO_FLAG = makeIcon(getApp(), flagpath, "unknown.png", TRUE); FXMenuPane opmenu(this); new FXMenuCommand(&opmenu, _("Give op"), NULL, this, IrcTabItem_OP); new FXMenuCommand(&opmenu, _("Remove op"), NULL, this, IrcTabItem_DEOP); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Give voice"), NULL, this, IrcTabItem_VOICE); new FXMenuCommand(&opmenu, _("Remove voice"), NULL, this, IrcTabItem_DEVOICE); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Kick"), NULL, this, IrcTabItem_KICK); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Ban"), NULL, this, IrcTabItem_BAN); new FXMenuCommand(&opmenu, _("KickBan"), NULL, this, IrcTabItem_KICKBAN); FXMenuPane popup(this); new FXMenuCommand(&popup, FXStringFormat(_("User: %s@%s"), nick.user.text(), nick.host.text()), ICO_FLAG); new FXMenuCommand(&popup, FXStringFormat(_("Realname: %s"), nick.real.text())); if(nick.nick != getNickName()) { new FXMenuSeparator(&popup); new FXMenuCommand(&popup, _("Query"), NULL, this, IrcTabItem_NEWQUERY); new FXMenuCommand(&popup, _("User information (WHOIS)"), NULL, this, IrcTabItem_WHOIS); new FXMenuCommand(&popup, _("DCC chat"), NULL, this, IrcTabItem_DCCCHAT); new FXMenuCommand(&popup, _("Send file"), NULL, this, IrcTabItem_DCCSEND); new FXMenuCommand(&popup, _("Ignore"), NULL, this, IrcTabItem_IGNORE); if(m_iamOp) new FXMenuCascade(&popup, _("Operator actions"), NULL, &opmenu); } else { new FXMenuSeparator(&popup); if(m_engine->isAway(getNickName())) new FXMenuCommand(&popup, _("Remove Away"), NULL, this, IrcTabItem_DEAWAY); else new FXMenuCommand(&popup, _("Set Away"), NULL, this, IrcTabItem_AWAY); } popup.create(); popup.popup(NULL,event->root_x,event->root_y); getApp()->runModalWhileShown(&popup); } return 1; } long IrcTabItem::onDoubleclick(FXObject*, FXSelector, void*) { FXint index = m_users->getCursorItem(); if(index >= 0) { if(m_users->getItemText(index) == getNickName()) return 1; IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = m_users->getItemText(index); ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } return 1; } long IrcTabItem::onNewQuery(FXObject *, FXSelector, void *) { IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = m_nickOnRight.nick; ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return 1; } long IrcTabItem::onWhois(FXObject *, FXSelector, void *) { m_engine->sendWhois(m_nickOnRight.nick); return 1; } long IrcTabItem::onDccChat(FXObject*, FXSelector, void*) { IrcEvent ev; ev.eventType = IRC_DCCSERVER; ev.param1 = m_nickOnRight.nick; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return 1; } long IrcTabItem::onDccSend(FXObject*, FXSelector, void*) { DccSendDialog dialog((FXMainWindow*)m_parent->getParent()->getParent(), m_nickOnRight.nick); if(dialog.execute()) { IrcEvent ev; ev.eventType = dialog.getPassive() ? IRC_DCCPOUT: IRC_DCCOUT; ev.param1 = m_nickOnRight.nick; ev.param2 = dialog.getFilename(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } return 1; } long IrcTabItem::onOp(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" +o "+m_nickOnRight.nick); return 1; } long IrcTabItem::onDeop(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" -o "+m_nickOnRight.nick); return 1; } long IrcTabItem::onVoice(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" +v "+m_nickOnRight.nick); return 1; } long IrcTabItem::onDevoice(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" -v "+m_nickOnRight.nick); return 1; } long IrcTabItem::onKick(FXObject *, FXSelector, void *) { FXDialogBox kickDialog(this, _("Kick dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&kickDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *kickframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(kickframe, _("Kick reason:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *reasonEdit = new FXTextField(kickframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &kickDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &kickDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(kickDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendKick(getText(), m_nickOnRight.nick, reasonEdit->getText()); } return 1; } long IrcTabItem::onBan(FXObject *, FXSelector, void *) { FXDialogBox banDialog(this, _("Ban dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&banDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *banframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(banframe, _("Banmask:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *banEdit = new FXTextField(banframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); banEdit->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &banDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &banDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(banDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendMode(getText()+" +b "+banEdit->getText()); } return 1; } long IrcTabItem::onKickban(FXObject *, FXSelector, void *) { FXDialogBox banDialog(this, _("Kick/Ban dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&banDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *kickframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(kickframe, _("Kick reason:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *reasonEdit = new FXTextField(kickframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXHorizontalFrame *banframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(banframe, _("Banmask:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *banEdit = new FXTextField(banframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); banEdit->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &banDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &banDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(banDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendKick(getText(), m_nickOnRight.nick, reasonEdit->getText()); m_engine->sendMode(getText()+" +b "+banEdit->getText()); } return 1; } //handle popup Ignore long IrcTabItem::onIgnore(FXObject*, FXSelector, void*) { FXDialogBox dialog(this, _("Add ignore user"), DECOR_TITLE|DECOR_BORDER, 0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame *contents = new FXVerticalFrame(&dialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, 10,10,10,10, 0,0); FXMatrix *matrix = new FXMatrix(contents,2,MATRIX_BY_COLUMNS|LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(matrix, _("Nick:"), NULL, JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *nick = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); nick->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); new FXLabel(matrix, _("Channel(s):\tChannels need to be comma separated"), NULL,JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *channel = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); channel->setText(getText()); channel->setTipText(_("Channels need to be comma separated")); new FXLabel(matrix, _("Server:"), NULL,JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *server = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); server->setText(getServerName()); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents,LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &dialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); new dxEXButton(buttonframe, _("&OK"), NULL, &dialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); if(dialog.execute(PLACEMENT_CURSOR)) { FXString ignoretext = nick->getText()+" "+channel->getText()+" "+server->getText(); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDIUSER), &ignoretext); } return 1; } //handle IrcTabItem_AWAY long IrcTabItem::onSetAway(FXObject*, FXSelector, void*) { FXDialogBox awayDialog(this, _("Away dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&awayDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *msgframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(msgframe, _("Message:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *msgEdit = new FXTextField(msgframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); msgEdit->setText(_("away")); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &awayDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &awayDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(awayDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendAway(msgEdit->getText().empty() ? _("away"): msgEdit->getText()); } return 1; } //handle IrcTabItem_DEAWAY long IrcTabItem::onRemoveAway(FXObject*, FXSelector, void*) { m_engine->sendAway(""); return 1; } //handle change in spellLang combobox long IrcTabItem::onSpellLang(FXObject*, FXSelector, void*) { m_commandline->setLanguage(m_spellLangs->getItemText(m_spellLangs->getCurrentItem())); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),m_spellLangs->getItemText(m_spellLangs->getCurrentItem()).text())); return 1; } long IrcTabItem::onTopic(FXObject*, FXSelector, void*) { if(m_editableTopic || m_iamOp) { if(m_topicline->getText().length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); m_engine->sendTopic(getText(), m_topicline->getText()); return 1; } m_engine->sendTopic(getText(), m_topicline->getText()); } else { m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } return 1; } long IrcTabItem::onTopicLink(FXObject*, FXSelector, void *data) { utils::instance().launchLink(static_cast<FXchar*>(data)); return 1; } void IrcTabItem::onBan(const FXString &banmask, const FXbool &sign, const FXString &sender, const FXTime &time) { if(sign) { FXString nicks = m_engine->getBannedNick(banmask); FXString myNick = getNickName(); while(nicks.contains(';')) { for(FXint i=m_users->getNumItems()-1; i>-1; i--) { if(nicks.before(';') == m_users->getItemText(i)) { if(m_users->getItemText(i) == myNick) appendIrcStyledText(FXStringFormat(_("You was banned by %s"), sender.text()), 1, time, FALSE, FALSE); else { if(!isCommandIgnored("ban") && !m_engine->isUserIgnored(m_users->getItemText(i), getText())) appendIrcStyledText(FXStringFormat(_("%s was banned by %s"), m_users->getItemText(i).text(), sender.text()), 1, time, FALSE, FALSE); //RemoveUser(users->getItemText(i)); } } } nicks = nicks.after(';'); } } } FXString IrcTabItem::stripColors(const FXString &text, const FXbool stripOther) { FXString newstr; FXbool color = FALSE; FXint numbers = 0; FXint i = 0; while(text[i] != '\0') { if(text[i] == '\017') //reset { color = FALSE; } else if(stripOther && text[i] == '\002') { //remove bold mark } else if(stripOther && text[i] == '\037') { //remove underline mark } else if(text[i] == '\035') { //remove italic mark } else if(text[i] == '\021') { //remove fixed mark } else if(text[i] == '\026') { //remove reverse mark } else if(text[i] == '\003') //color { color = TRUE; } else if(color && isdigit(text[i]) && numbers < 2) { numbers++; } else if(color && text[i] == ',' && numbers < 3) { numbers = 0; } else { numbers = 0; color = FALSE; newstr += text[i]; } i++; } return newstr; } FXString IrcTabItem::getNick(FXint i) { return m_users->getItemText(i); } FXint IrcTabItem::getNickColor(const FXString &nick) { //10 is first colored nick style return 10+nick.hash()%8; } FXColor IrcTabItem::getIrcColor(FXint code) { switch(code){ case 0: return fxcolorfromname("white"); case 1: return fxcolorfromname("black"); case 2: return FXRGB(0,0,128); //blue case 3: return FXRGB(0,128,0); //green case 4: return FXRGB(255,0,0); //lightred case 5: return FXRGB(128,0,64); //brown case 6: return FXRGB(128,0,128); //purple case 7: return FXRGB(255,128,64); //orange case 8: return FXRGB(255,255,0); //yellow case 9: return FXRGB(128,255,0); //lightgreen case 10: return FXRGB(0,128,128); //cyan case 11: return FXRGB(0,255,255); //lightcyan case 12: return FXRGB(0,0,255); //lightblue case 13: return FXRGB(255,0,255); //pink case 14: return FXRGB(128,128,128); //grey case 15: return FXRGB(192,192,192); //lightgrey default: return m_colors.text; } } FXint IrcTabItem::hiliteStyleExist(FXColor foreColor, FXColor backColor, FXuint style) { for(FXint i=0; i<m_textStyleList.no(); i++) { if(m_textStyleList[i].normalForeColor == foreColor && m_textStyleList[i].normalBackColor == backColor && m_textStyleList[i].style == style) return i+1; } return -1; } void IrcTabItem::createHiliteStyle(FXColor foreColor, FXColor backColor, FXuint style) { dxHiliteStyle nstyle = {foreColor,backColor,getApp()->getSelforeColor(),getApp()->getSelbackColor(),style,FALSE}; m_textStyleList.append(nstyle); m_text->setHiliteStyles(m_textStyleList.data()); } dxStringArray IrcTabItem::cutText(FXString text, FXint len) { FXint textLen = text.length(); FXint previous = 0; dxStringArray texts; while(textLen>len) { texts.append(text.mid(previous, len)); previous += len; textLen -= len; } texts.append(text.mid(previous, len)); return texts; } void IrcTabItem::setCommandFocus() { m_commandline->setFocus(); } //for "handle" checking, if script contains "all". Send from dxirc. void IrcTabItem::hasAllCommand(FXbool result) { m_scriptHasAll = result; } //for "handle" checking, if script contains "mymsg". Send from dxirc. void IrcTabItem::hasMyMsg(FXbool result) { m_scriptHasMyMsg = result; } //check need of highlight in msg FXbool IrcTabItem::highlightNeeded(const FXString &msg) { FXint pos = msg.find(getNickName()); if(pos==-1) return FALSE; FXbool before = TRUE; FXbool after = FALSE; if(pos) before = isDelimiter(msg[pos-1]); if(pos+getNickName().length() == msg.length()) after = TRUE; if(pos+getNickName().length() < msg.length()) after = isDelimiter(msg[pos+getNickName().length()]); return before && after; }
rofl0r/dxirc
src/irctabitem.cpp
C++
gpl-2.0
183,742
<?php # i think this class should go somewhere in a common PEAR-place, # because a lot of classes use options, at least PEAR::DB does # but since it is not very fancy to crowd the PEAR-namespace too much i dont know where to put it yet :-( // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Wolfram Kriesing <wolfram@kriesing.de> | // +----------------------------------------------------------------------+ // // $Id: Options.php,v 1.4 2003/01/04 11:56:27 mj Exp $ require_once('PEAR.php'); /** * this class only defines commonly used methods, etc. * it is worthless without being extended * * @package Tree * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * */ class Tree_Options extends PEAR { /** * @var array $options you need to overwrite this array and give the keys, that are allowed */ var $options = array(); var $_forceSetOption = false; /** * this constructor sets the options, since i normally need this and * in case the constructor doesnt need to do anymore i already have it done :-) * * @version 02/01/08 * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * @param array the key-value pairs of the options that shall be set * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function Tree_Options( $options=array() , $force=false ) { $this->_forceSetOption = $force; if( is_array($options) && sizeof($options) ) foreach( $options as $key=>$value ) $this->setOption( $key , $value ); } /** * * @access public * @author Stig S. Baaken * @param * @param * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function setOption( $option , $value , $force=false ) { if( is_array($value) ) // if the value is an array extract the keys and apply only each value that is set { // so we dont override existing options inside an array, if an option is an array foreach( $value as $key=>$aValue ) $this->setOption( array($option , $key) , $aValue ); return true; } if( is_array($option) ) { $mainOption = $option[0]; $options = "['".implode("']['",$option)."']"; $evalCode = "\$this->options".$options." = \$value;"; } else { $evalCode = "\$this->options[\$option] = \$value;"; $mainOption = $option; } if( $this->_forceSetOption==true || $force==true || isset($this->options[$mainOption]) ) { eval($evalCode); return true; } return false; } /** * set a number of options which are simply given in an array * * @access public * @author * @param * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function setOptions( $options , $force=false ) { if( is_array($options) && sizeof($options) ) { foreach( $options as $key=>$value ) { $this->setOption( $key , $value , $force ); } } } /** * * @access public * @author copied from PEAR: DB/commmon.php * @param boolean true on success */ function getOption($option) { if( func_num_args() > 1 && is_array($this->options[$option])) { $args = func_get_args(); $evalCode = "\$ret = \$this->options['".implode( "']['" , $args )."'];"; eval( $evalCode ); return $ret; } if (isset($this->options[$option])) { return $this->options[$option]; } # return $this->raiseError("unknown option $option"); return false; } /** * returns all the options * * @version 02/05/20 * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * @return string all options as an array */ function getOptions() { return $this->options; } } // end of class ?>
Esleelkartea/kz-adeada-talleres-electricos-
kzadeadatallereselectricos_v1.0.0_linux32_installer/linux/lampp/lib/php/Tree/Options.php
PHP
gpl-2.0
5,542