repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
TOMIGalway/cmoct-sourcecode
src/com/joey/software/volumeTools/SliceLinker.java
6124
/******************************************************************************* * Copyright (c) 2012 joey.enfield. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * joey.enfield - initial API and implementation ******************************************************************************/ package com.joey.software.volumeTools; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import com.joey.software.userinterface.VersionManager; /** * this is a hub to update all the panels when one is changed * * @author Joey.Enfield * */ public class SliceLinker implements Externalizable { private static final long serialVersionUID = VersionManager .getCurrentVersion(); double xMin; double xMax; double yMin; double yMax; double zMin; double zMax; double xSlice; double ySlice; double zSlice; SliceControler xSliceControl; SliceControler ySliceControl; SliceControler zSliceControl; OCTVolumeDivider owner; public SliceLinker() { SliceSelectPanel xPanel = new SliceSelectPanel(); SliceSelectPanel yPanel = new SliceSelectPanel(); SliceSelectPanel zPanel = new SliceSelectPanel(); xSliceControl = xPanel.controler; ySliceControl = yPanel.controler; zSliceControl = zPanel.controler; } public void setData(SliceLinker link) { owner = link.owner; xMax = link.xMax; xMin = link.xMin; yMax = link.yMax; yMin = link.yMin; zMax = link.zMax; zMin = link.zMin; xSlice = link.xSlice; ySlice = link.ySlice; zSlice = link.zSlice; updateSlices(); } public SliceLinker(OCTVolumeDivider owner, SliceControler xcont, SliceControler ycont, SliceControler zcont) { this.owner = owner; xSliceControl = xcont; ySliceControl = ycont; zSliceControl = zcont; xcont.setLinker(this); ycont.setLinker(this); zcont.setLinker(this); readValues(); updateSlices(); } public void readValues() { xMin = zSliceControl.panel.xMinValue; xMax = zSliceControl.panel.xMaxValue; yMin = zSliceControl.panel.yMinValue; yMax = zSliceControl.panel.yMaxValue; zMin = xSliceControl.panel.xMinValue; zMax = xSliceControl.panel.xMaxValue; yMin = xSliceControl.panel.yMinValue; yMax = xSliceControl.panel.yMaxValue; xMin = ySliceControl.panel.xMinValue; xMax = ySliceControl.panel.xMaxValue; zMin = ySliceControl.panel.yMinValue; zMax = ySliceControl.panel.yMaxValue; ySlice = zSliceControl.panel.crossY; xSlice = zSliceControl.panel.crossX; zSlice = ySliceControl.panel.crossY; xSlice = ySliceControl.panel.crossX; ySlice = xSliceControl.panel.crossY; zSlice = xSliceControl.panel.crossX; } public void updateSlices() { zSliceControl.panel.xMinValue = xMin; zSliceControl.panel.xMaxValue = xMax; zSliceControl.panel.yMinValue = yMin; zSliceControl.panel.yMaxValue = yMax; xSliceControl.panel.xMinValue = zMin; xSliceControl.panel.xMaxValue = zMax; xSliceControl.panel.yMinValue = yMin; xSliceControl.panel.yMaxValue = yMax; ySliceControl.panel.xMinValue = xMin; ySliceControl.panel.xMaxValue = xMax; ySliceControl.panel.yMinValue = zMin; ySliceControl.panel.yMaxValue = zMax; xSliceControl.panel.setSliderListen(false); xSliceControl.panel.setPosition(xSlice); xSliceControl.panel.crossX = zSlice; xSliceControl.panel.crossY = ySlice; xSliceControl.panel.setSliderListen(true); ySliceControl.panel.setSliderListen(false); ySliceControl.panel.setPosition(ySlice); ySliceControl.panel.crossX = xSlice; ySliceControl.panel.crossY = zSlice; ySliceControl.panel.setSliderListen(true); zSliceControl.panel.setSliderListen(false); zSliceControl.panel.setPosition(zSlice); zSliceControl.panel.crossX = xSlice; zSliceControl.panel.crossY = ySlice; zSliceControl.panel.setSliderListen(true); xSliceControl.panel.repaint(); ySliceControl.panel.repaint(); zSliceControl.panel.repaint(); try { owner.getVolumeViewer().updateRealSize(owner.renderHighRes .isSelected()); owner.getVolumeViewer().updateSlices(); } catch (Exception e) { } } public void valueChanged(SliceControler src) { if (src == xSliceControl) { yMin = xSliceControl.panel.yMinValue; yMax = xSliceControl.panel.yMaxValue; zMin = xSliceControl.panel.xMinValue; zMax = xSliceControl.panel.xMaxValue; ySlice = xSliceControl.panel.crossY; zSlice = xSliceControl.panel.crossX; } else if (src == ySliceControl) { xMin = ySliceControl.panel.xMinValue; xMax = ySliceControl.panel.xMaxValue; zMin = ySliceControl.panel.yMinValue; zMax = ySliceControl.panel.yMaxValue; zSlice = ySliceControl.panel.crossY; xSlice = ySliceControl.panel.crossX; } else if (src == zSliceControl) { xMin = zSliceControl.panel.xMinValue; xMax = zSliceControl.panel.xMaxValue; yMin = zSliceControl.panel.yMinValue; yMax = zSliceControl.panel.yMaxValue; ySlice = zSliceControl.panel.crossY; xSlice = zSliceControl.panel.crossX; } updateSlices(); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { xMin = in.readDouble(); xMax = in.readDouble(); xSlice = in.readDouble(); yMin = in.readDouble(); yMax = in.readDouble(); ySlice = in.readDouble(); zMin = in.readDouble(); zMax = in.readDouble(); zSlice = in.readDouble(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeDouble(xMin); out.writeDouble(xMax); out.writeDouble(xSlice); out.writeDouble(yMin); out.writeDouble(yMax); out.writeDouble(ySlice); out.writeDouble(zMin); out.writeDouble(zMax); out.writeDouble(zSlice); } }
gpl-2.0
atizo/epicwall
standalone/src/rec.py
2408
#!/usr/bin/env python # -*- coding: utf-8 -*- # # epicwall Project # http://epicwall.ch/ # # Copyright (c) 2017 see AUTHORS file. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USAª # from __future__ import print_function # Only needed for Python 2 import argparse import os import sys try: import cPickle as pickle except: import pickle from ola.ClientWrapper import ClientWrapper from ola.OlaClient import OLADNotRunningException from serial import Serial from core.serial import detect_serial_device from core.wall import send from settings import CLIPS_DIR from datetime import datetime last = 0 def rec(ar): if ar.dev: serial_device = Serial(ar.dev, 115200, timeout=1) else: serial_device = Serial(detect_serial_device(), 115200, timeout=1) clip_name = ar.clip if not clip_name.endswith('.clip'): clip_name += '.clip' clip = open(os.path.join(CLIPS_DIR, clip_name), 'w') def dmxdata(data): global last if last == 0: td = 0 else: td = int((datetime.now() - last).total_seconds() * 1000) last = datetime.now() pickle.dump({'td': td, 'frm': data}, clip) send(data, serial_device) universe = 1 try: wrapper = ClientWrapper() except OLADNotRunningException: print("Start olad first") sys.exit(1) client = wrapper.Client() client.RegisterUniverse(universe, client.REGISTER, dmxdata) wrapper.Run() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("clip", help="clip name") parser.add_argument("--dev", help="serial device (auto-detected if not provided)") args = parser.parse_args() rec(args)
gpl-2.0
Hefester/l2c-devsadmin
L2DevsAdmins/L2.LoginService/InnerNetwork/CacheServiceConnection.cs
5223
using System; using System.Net; using L2.Net.LoginService.OuterNetwork; using L2.LoginService.Properties; using L2.Net.Network; using L2.Net.Structs.Services; namespace L2.Net.LoginService.InnerNetwork { /// <summary> /// Provides connection between cache service and login service. /// </summary> internal static class CacheServiceConnection { /// <summary> /// Indicates, if currently connected service has to reconnect to remote service automatically, when connection was lost. /// </summary> internal static volatile bool AutoReconnectToRemoteService = Settings.Default.CacheServiceAutoReconnect; /// <summary> /// Cache server connection object. /// </summary> internal static InnerNetworkConnection Connection; /// <summary> /// Initializes service in unsafe mode. /// </summary> internal static void UnsafeInitialize() { if ( Connection != null ) { if ( Connection.Connected ) throw new InvalidOperationException(); Initialize(Connection.RemoteEndPoint, Connection.ReconnectInterval); return; } Service.Terminate(new ServiceShutdownEventArgs("Remote connection was not initialized yet")); } /// <summary> /// Initializes 'cache to login' connection. /// </summary> /// <param name="remoteEP">Remote cache service endpoint.</param> /// <param name="reconnectAttemptInterval">Interval between reconnection attempts.</param> internal static void Initialize( IPEndPoint remoteEP, TimeSpan reconnectAttemptInterval ) { if ( Connection != null && Connection.Connected ) { Logger.WriteLine(Source.InnerNetwork, "Already connected to remote cache service."); return; } if ( Connection == null ) { Connection = new InnerNetworkConnection(remoteEP, reconnectAttemptInterval); Connection.HandleDelegate = CacheServiceRequestsHandlers.Handle; Connection.OnConnected += new OnConnectedEventHandler(Connection_OnConnected); Connection.OnDisconnected += new OnDisconnectedEventHandler(Connection_OnDisconnected); } else { Connection.RemoteEndPoint = remoteEP; Connection.ReconnectInterval = reconnectAttemptInterval; } Logger.WriteLine(Source.InnerNetwork, "Initializing cache service connection."); Connection.BeginConnect(); } /// <summary> /// Executes when connection to remote host has been aborted. /// </summary> /// <param name="errorCode">Error code.</param> /// <param name="client"><see cref="NetworkClient"/> object.</param> /// <param name="connectionId">Connection id.</param> private static void Connection_OnDisconnected( int errorCode, NetworkClient client, byte connectionId ) { Logger.WriteLine(Source.InnerNetwork, "Disconnected from cache service."); UserConnectionsListener.Active = false; if ( AutoReconnectToRemoteService ) { Logger.WriteLine(Source.InnerNetwork, "Connection to remote side was lost, attempting to reconnect..."); UnsafeInitialize(); } else Service.Terminate(new ServiceShutdownEventArgs("Service terminated, can't operate without cache server connection.")); } /// <summary> /// Executes when connection to remote host has been established. /// </summary> /// <param name="endPoint">Remote <see cref="IPEndPoint"/>.</param> /// <param name="connectionId">Connection id.</param> private static void Connection_OnConnected( IPEndPoint endPoint, byte connectionId ) { Logger.WriteLine(Source.InnerNetwork, "Authorizing on CacheService on {0}", endPoint.ToString()); Connection.Send ( new InitializeRequest(Settings.Default.ServiceUniqueID, ( byte )ServiceType.LoginService).ToPacket() ); Connection.BeginReceive(); } /// <summary> /// Sends <see cref="Packet"/> to cache service. /// </summary> /// <param name="p"><see cref="Packet"/> to send.</param> internal static void Send( Packet p ) { if ( Connection != null && Connection.Connected ) Connection.Send(p); else { Logger.WriteLine(Source.InnerNetwork, "Failed to send packet to cache service, connection isn't active."); Logger.WriteLine(p.ToString()); } } /// <summary> /// Indicates if logins service is connected to cache service. /// </summary> internal static bool Active { get { return Connection != null && Connection.Connected; } } } }
gpl-2.0
zaakpay/zaakpay-drupal-commerce-kit
response.php
692
<?php include('checksum.php'); ?> <?php // Please insert your own secret key here $secret_key = 'Your Secret key goes here'; $recd_checksum = $_POST['checksum']; $all = Checksum::getAllParams(); $checksum_check = Checksum::verifyChecksum($recd_checksum, $all, $secret_key); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zaakpay</title> </head> <body> <center> <table width="500px;"> <?php Checksum::outputResponse($checksum_check); ?> </table> </center> </body> </html>
gpl-2.0
pitosalas/blogbridge
test/com/salas/bb/domain/TestStandardGuideEvents.java
9149
// BlogBridge -- RSS feed reader, manager, and web based service // Copyright (C) 2002-2006 by R. Pito Salas // // 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 // // Contact: R. Pito Salas // mailto:pitosalas@users.sourceforge.net // More information: about BlogBridge // http://www.blogbridge.com // http://sourceforge.net/projects/blogbridge // // $Id: TestStandardGuideEvents.java,v 1.4 2006/07/07 14:58:29 spyromus Exp $ // package com.salas.bb.domain; import org.jmock.Mock; import org.jmock.MockObjectTestCase; import java.net.MalformedURLException; import java.net.URL; /** * This suite contains tests for <code>StandardGuide</code> unit. */ public class TestStandardGuideEvents extends MockObjectTestCase { private StandardGuide guide; private Mock listener; protected void setUp() throws Exception { super.setUp(); listener = new Mock(IGuideListener.class); guide = new StandardGuide(); guide.addListener((IGuideListener)listener.proxy()); } /** * Adding a feed manually directly to the guide. */ public void testAddFeedManual() { DirectFeed feed = new DirectFeed(); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); guide.add(feed); listener.verify(); } /** * Adding a feed as part of a reading list. */ public void testAddFeedReadingList() { DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); list.add(feed); guide.add(list); listener.verify(); } /** * Adding a feed after the reading list is added. */ public void testAddFeedAfterReadingList() { DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); guide.add(list); list.add(feed); listener.verify(); } /** * Adding the feed to the guide directly when it's already present as part of the reading list. */ public void testAddVisibleFeedDirectly() { DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed)); guide.add(list); list.add(feed); guide.add(feed); listener.verify(); } /** * Removing a feed directly from the reading list. */ public void testRemoveFeed() { DirectFeed feed = new DirectFeed(); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedLinkRemoved").with(same(guide), same(feed)); listener.expects(once()).method("feedRemoved"); //.with(same(guide), same(feed)); guide.add(feed); guide.remove(feed); listener.verify(); } /** * Removing a feed as part of the reading list. */ public void testRemoveFeedReadingList() { DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedRemoved"); //.with(same(guide), same(feed)); listener.expects(once()).method("readingListRemoved").with(same(guide), same(list)); guide.add(list); list.add(feed); guide.remove(list, true); listener.verify(); } /** * Removing the reading list with saving the feeds (adding them directly to the guide). */ public void testRemoveReadingListSaveFeeds() { DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed)); listener.expects(once()).method("readingListRemoved").with(same(guide), same(list)); guide.add(list); list.add(feed); guide.remove(list, false); listener.verify(); } public void testCopyFeed() { StandardGuide guide2 = new StandardGuide(); guide2.addListener((IGuideListener)listener.proxy()); DirectFeed feed = new DirectFeed(); ReadingList list = new ReadingList(getTestURL()); listener.expects(once()).method("readingListAdded").with(same(guide), same(list)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); // Move (copy) listener.expects(once()).method("feedAdded").with(same(guide2), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide2), same(feed)); guide.add(list); list.add(feed); guide.moveFeed(feed, guide2, 0); // copy because of feed being locked by the reading list listener.verify(); } public void testMoveFeed() { StandardGuide guide2 = new StandardGuide(); guide2.addListener((IGuideListener)listener.proxy()); DirectFeed feed = new DirectFeed(); listener.expects(once()).method("feedAdded").with(same(guide), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed)); // Move listener.expects(once()).method("feedAdded").with(same(guide2), same(feed)); listener.expects(once()).method("feedLinkAdded").with(same(guide2), same(feed)); listener.expects(once()).method("feedLinkRemoved").with(same(guide), same(feed)); listener.expects(once()).method("feedRemoved"); //.with(same(guide), same(feed)); guide.add(feed); guide.moveFeed(feed, guide2, 0); listener.verify(); } public void testRepositionFeed() { DirectFeed feed0 = new DirectFeed(); DirectFeed feed1 = new DirectFeed(); DirectFeed feed2 = new DirectFeed(); listener.expects(once()).method("feedAdded").with(same(guide), same(feed0)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed0)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed1)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed1)); listener.expects(once()).method("feedAdded").with(same(guide), same(feed2)); listener.expects(once()).method("feedLinkAdded").with(same(guide), same(feed2)); guide.add(feed0); guide.add(feed1); guide.add(feed2); listener.expects(once()).method("feedRepositioned").with(same(guide), same(feed0), eq(0), eq(2)); listener.expects(once()).method("feedRepositioned").with(same(guide), same(feed0), eq(2), eq(0)); // Move feed 0 after feed 2 guide.moveFeed(feed0, guide, 2); // Move feed 0 back to top guide.moveFeed(feed0, guide, 0); // There should be no events listener.verify(); } /** * Creates test URL. * * @return url. */ private URL getTestURL() { URL url = null; try { url = new URL("file://test"); } catch (MalformedURLException e) { e.printStackTrace(); fail(); } return url; } }
gpl-2.0
ericphamhoang/awesomeblock
includes/class-awesomeblock-loader.php
5053
<?php /** * Register all actions and filters for the plugin * * @link https://github.com/ericphamhoang * @since 1.0.0 * * @package Awesomeblock * @subpackage Awesomeblock/includes */ /** * Register all actions and filters for the plugin. * * Maintain a list of all hooks that are registered throughout * the plugin, and register them with the WordPress API. Call the * run function to execute the list of actions and filters. * * @package Awesomeblock * @subpackage Awesomeblock/includes * @author Eric Pham Hoang <ericphamhoang@gmail.com> */ class Awesomeblock_Loader { /** * The array of actions registered with WordPress. * * @since 1.0.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 1.0.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 1.0.0 */ public function __construct() { $this->actions = array(); $this->filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress action that is being registered. * @param object $component A reference to the instance of the object on which the action is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1 */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 1.0.0 * @access private * @param array $hooks The collection of hooks that is being registered (that is, actions or filters). * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority The priority at which the function should be fired. * @param int $accepted_args The number of arguments that should be passed to the $callback. * @return array The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 1.0.0 */ public function run() { foreach ( $this->filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this->actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } $public = new Awesomeblock_Public('awesomeblock', '1.0'); $public->init_custom_post_type_block(); $public->add_block_shortcode(); $public->allow_span_tags(); } }
gpl-2.0
dmitrysmagin/profadeluxe
src/sprites/TSprVerticalFlip.cpp
3525
#ifndef _TSPRVERTICALFLIP_ #define _TSPRVERTICALFLIP_ #include "sprites.h" #include "../escenas/escenarios.h" REGISTER_CLASS_ID(TSprVerticalFlip); // Babosas // int TSprVerticalFlip::AnimBabosaAmarilla[8]={92,93,94,95,96,95,94,93}; int TSprVerticalFlip::AnimBabosaVerde[8]= {109,110,111,112,113,112,111,110}; int TSprVerticalFlip::AnimBabosaRoja[8]= {126,127,128,129,130,129,128,127}; // Peces // int TSprVerticalFlip::AnimPezAmarilloS[4]={86,87,88,87}; int TSprVerticalFlip::AnimPezAmarilloB[4]={89,90,91,90}; int TSprVerticalFlip::AnimPezAzulS[4] ={103,104,105,104}; int TSprVerticalFlip::AnimPezAzulB[4] ={106,107,108,107}; int TSprVerticalFlip::AnimPezVerdeS[4] ={120,121,122,121}; int TSprVerticalFlip::AnimPezVerdeB[4] ={123,124,125,124}; TSprVerticalFlip::TSprVerticalFlip(PMAImageBank bank,int tipo,int posx,int posy,int pymin,int pymax,int vel,int retardo):TSpriteEnemigo(bank) { anim=NULL; ii_Retardo=retardo; switch (tipo) { case TSPR_VBABOSA_AMARILLA: setAnimSequence(AnimBabosaAmarilla,8); break; case TSPR_VBABOSA_VERDE: setAnimSequence(AnimBabosaVerde,8); break; case TSPR_VBABOSA_ROJA: setAnimSequence(AnimBabosaRoja,8); break; case TSPR_PEZ_AMARILLO: setAnimSequence(AnimPezAmarilloB,4); anim=AnimPezAmarilloS; break; case TSPR_PEZ_AZUL: setAnimSequence(AnimPezAzulB,4); anim=AnimPezAzulS; break; case TSPR_PEZ_VERDE: setAnimSequence(AnimPezVerdeB,4); anim=AnimPezVerdeS; break; } init_y = pymin*_TileAY; end_y = pymax*_TileAY; velocidad=vel; if (velocidad<0) { const int *aux_anim; aux_anim = ia_AnimSequence; ia_AnimSequence = anim; anim = aux_anim; velocidad=-velocidad; bajando=false; } else bajando=true; // Definimos la posición inicial y el tamaño del Sprite // position.x = posx*_TileAX; position.y = posy*_TileAY; position.width = 40/_REDUCE; position.height = 40/_REDUCE; // Establecemos el primer fotograma de la animación. // ii_Frame=0; ii_Estado=0; } void TSprVerticalFlip::animate(void) { const int *aux_anim; if (ii_RetardoPos<ii_Retardo) { ii_RetardoPos ++; } else { ii_Frame = (ii_Frame<ii_AnimSequenceLength-1)?(ii_Frame+1):0; ii_RetardoPos=0; } if (bajando) { position.y += velocidad; if (position.y > end_y) { position.y = end_y; bajando = false; if (anim!=NULL) { aux_anim = ia_AnimSequence; ia_AnimSequence = anim; anim = aux_anim; } else ib_flip_y=!ib_flip_y; } } else { position.y -= velocidad; if (position.y < init_y) { position.y = init_y; bajando = true; if (anim!=NULL) { aux_anim = ia_AnimSequence; ia_AnimSequence = anim; anim = aux_anim; } else ib_flip_y=!ib_flip_y; } } TMASprite::animate(); } bool TSprVerticalFlip::draw(TMABitmap& g) { g.drawSprite(io_images->getBitmap(ii_CurrentFotograma),position.x,position.y,ib_flip_x,ib_flip_y); return true; } #endif
gpl-2.0
nobrother/omc-wp-draft
wp-content/plugins/wp-media-javascript-guide-master/sections/wp.media.view.MediaFrame.Post/index.php
3077
<h3>wp.media.view.MediaFrame.Post</h3> <p>A workflow for choosing content in various forms (media, galleries, playlists) to insert into the content editor.</p> <h3>Properties</h3> <dl> <dt><code>content</code><?php WPMJG::inherited_from_text( 'wp.media.view.Frame' ) ?></dt> <dd>The <code>content</code> region controller object. See <code><?php WPMJG::the_section_link( 'wp.media.controller.Region' ) ?></code>.</dd> <dt><code>menu</code><?php WPMJG::inherited_from_text( 'wp.media.view.Frame' ) ?></dt> <dd>The <code>menu</code> region controller object. See <code><?php WPMJG::the_section_link( 'wp.media.controller.Region' ) ?></code>.</dd> <dt><code>title</code><?php WPMJG::inherited_from_text( 'wp.media.view.Frame' ) ?></dt> <dd>The <code>title</code> region controller object. See <code><?php WPMJG::the_section_link( 'wp.media.controller.Region' ) ?></code>.</dd> <dt><code>toolbar</code><?php WPMJG::inherited_from_text( 'wp.media.view.Frame' ) ?></dt> <dd>The <code>toolbar</code> region controller object. See <code><?php WPMJG::the_section_link( 'wp.media.controller.Region' ) ?></code>.</dd> <dt><code>router</code><?php WPMJG::inherited_from_text( 'wp.media.view.Frame' ) ?></dt> <dd>The <code>router</code> region controller object. See <code><?php WPMJG::the_section_link( 'wp.media.controller.Region' ) ?></code>.</dd> <dt><code>views</code><?php WPMJG::inherited_from_text( 'wp.Backbone.View' ) ?></dt> <dd>A subview manager. Instance of <code>wp.Backbone.Subviews</code>.</dd> </dl> <h3>Methods</h3> <dl> <dt><code>open()</code><?php WPMJG::inherited_from_text( 'wp.media.view.MediaFrame' ) ?></dt> <dd>Open the frame in a modal.</dd> <dt><code>close()</code><?php WPMJG::inherited_from_text( 'wp.media.view.MediaFrame' ) ?></dt> <dd>Close the modal.</dd> <dt><code>state( state )</code><?php WPMJG::inherited_from_text( 'wp.media.controller.StateMachine' ) ?></dt> <dd>Get a state object. <br>Defaults to the current state; if a state ID is supplied, returns that state.</dd> <dt><code>setState( state )</code><?php WPMJG::inherited_from_text( 'wp.media.controller.StateMachine' ) ?></dt> <dd>Set the state.<br> Triggers an `activate` event on the state, and a `deactivate` event on the previous state.</dd> <dt><code>lastState()</code><?php WPMJG::inherited_from_text( 'wp.media.controller.StateMachine' ) ?></dt> <dd>Get the previously active state object.</dd> </dl> <div class="example"> <h3>Example: Open a post frame</h3> <h4>LIVE EXAMPLE <a class="add-new-h2" target="_blank" href="<?php echo WPMJG::get_example_url( WPMJG::get_current_section(), 1 ) ?>">open in a new window</a></h4> <iframe class="iframe-interactive-demo" src="<?php echo WPMJG::get_example_url( WPMJG::get_current_section(), 1 ) ?>"></iframe> <h4>MARKUP</h4> <pre><code class="language-html"><?php WPMJG()->the_section_example_markup( WPMJG::get_current_section(), 1 ) ?></code></pre> <h4>JAVASCRIPT</h4> <pre><code class="language-javascript"><?php WPMJG()->the_section_example_javascript( WPMJG::get_current_section(), 1 ) ?></code></pre> </div>
gpl-2.0
fafeitsch/Lateness
src/main/java/de/fafeitsch/lateness/domain/Route.java
2185
/* * 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 de.fafeitsch.lateness.domain; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * * @author Fabian Feitsch <info@fafeitsch.de> */ public class Route { private final String name; private final Map<String, RouteVariant> routeVariants; public Route(String name) { Objects.requireNonNull(name, "name must not be null"); this.name = name; routeVariants = new HashMap<>(); } public RouteVariant createNewRouteVariant(String name) { if (routeVariants.containsKey(name)) { throw new IllegalStateException("A route variant with the name '" + name + "' already exists."); } routeVariants.put(name, new RouteVariant(name, this)); return routeVariants.get(name); } public String getName() { return name; } public Collection<RouteVariant> getRouteVariants() { return Collections.unmodifiableCollection(routeVariants.values()); } public RouteVariant getVariantWithName(String name) { if (!routeVariants.containsKey(name)) { throw new IllegalArgumentException("There is no variant with the name '" + name + "' in the route '" + this); } return routeVariants.get(name); } @Override public int hashCode() { int hash = 7; hash = 97 * hash + Objects.hashCode(this.name); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Route other = (Route) obj; if (!Objects.equals(this.name, other.name)) { return false; } return true; } @Override public String toString() { return "Route{" + "name=" + name + '}'; } }
gpl-2.0
alip/paludis-alip
paludis/resolver/strongly_connected_component.hh
2274
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ /* * Copyright (c) 2010 Ciaran McCreesh * * This file is part of the Paludis package manager. Paludis 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. * * Paludis 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 PALUDIS_GUARD_PALUDIS_RESOLVER_STRONGLY_CONNECTED_COMPONENT_HH #define PALUDIS_GUARD_PALUDIS_RESOLVER_STRONGLY_CONNECTED_COMPONENT_HH 1 #include <paludis/resolver/strongly_connected_component-fwd.hh> #include <paludis/resolver/resolvent-fwd.hh> #include <paludis/util/named_value.hh> #include <paludis/util/set.hh> #include <paludis/util/sequence.hh> #include <paludis/util/wrapped_forward_iterator.hh> #include <paludis/util/wrapped_output_iterator.hh> #include <tr1/memory> namespace paludis { namespace n { typedef Name<struct nodes_name> nodes; typedef Name<struct requirements_name> requirements; } namespace resolver { struct StronglyConnectedComponent { NamedValue<n::nodes, std::tr1::shared_ptr<Set<Resolvent> > > nodes; NamedValue<n::requirements, std::tr1::shared_ptr<Set<Resolvent> > > requirements; }; } #ifdef PALUDIS_HAVE_EXTERN_TEMPLATE extern template class Set<resolver::Resolvent>; extern template class WrappedForwardIterator<Set<resolver::Resolvent>::ConstIteratorTag, const resolver::Resolvent>; extern template class WrappedOutputIterator<Set<resolver::Resolvent>::InserterTag, resolver::Resolvent>; extern template class Sequence<resolver::StronglyConnectedComponent>; extern template class WrappedForwardIterator<Sequence<resolver::StronglyConnectedComponent>::ConstIteratorTag, const resolver::StronglyConnectedComponent>; #endif } #endif
gpl-2.0
Smattacus/data-analysis
python/5-28-2014/analyze_xcorrs_5_28_2014.py
982
#/usr/bin/python2 #Import some packages. Mainly the scipy stuff. #Consider being more selective with imports in the future, for speed of course. import numpy as np import matplotlib as mp import os import glob import scipy as sp from scipy import io from matplotlib import pyplot as plt print("Hello world!") N = 800000 os.chdir('/home/sean/data/5-28-2014/XCMeans/') #Create a 2D array for the normalized cross correlations to try and recreate #Fred's broadening peaks. l = np.sort(glob.glob("*.mat")) #Read all the mat files, grab the xcsmean_lifscaled array, take the middle 5000 #points. Isn't Python neat? xc = [io.loadmat(x)["xcsmean_lifscaled"][0, ((N-1) - 2048):((N-1)+2049)] for x in l] xc = np.array(xc) #Note that the indices go from 0 - N+1 on slicing; they do #not include the final element. This is due to indexing from zero. #Initialize the time array. t =np.linspace(-(N-1), N-1, 2 * N - 1) / 1e5 t = t[(N-1) - 2048: (N-1) + 2049] p = np.amax(xc, 1)
gpl-2.0
archlinux/archweb
packages/views/signoff.py
8366
import json from operator import attrgetter from django import forms from django.contrib.auth.decorators import permission_required from django.contrib.auth.models import User from django.core.mail import EmailMessage from django.core.serializers.json import DjangoJSONEncoder from django.db import transaction from django.http import HttpResponse, Http404 from django.shortcuts import get_list_or_404, redirect, render from django.template import loader from django.utils.timezone import now from django.views.decorators.cache import never_cache from main.models import Package, Arch, Repo from ..models import SignoffSpecification, Signoff from ..utils import (get_signoff_groups, approved_by_signoffs, PackageSignoffGroup) @permission_required('packages.change_signoff') def signoffs(request): signoff_groups = sorted(get_signoff_groups(), key=attrgetter('pkgbase')) for group in signoff_groups: group.user = request.user context = { 'signoff_groups': signoff_groups, 'arches': Arch.objects.all(), 'repo_names': sorted({g.target_repo for g in signoff_groups}), } return render(request, 'packages/signoffs.html', context) @permission_required('packages.change_signoff') @never_cache def signoff_package(request, name, repo, arch, revoke=False): packages = get_list_or_404(Package, pkgbase=name, arch__name=arch, repo__name__iexact=repo, repo__testing=True) package = packages[0] spec = SignoffSpecification.objects.get_or_default_from_package(package) if revoke: try: signoff = Signoff.objects.get_from_package(package, request.user, False) except Signoff.DoesNotExist: raise Http404 signoff.revoked = now() signoff.save(update_fields=('revoked',)) created = False else: # ensure we should even be accepting signoffs if spec.known_bad or not spec.enabled: return render(request, '403.html', status=403) signoff, created = Signoff.objects.get_or_create_from_package(package, request.user) signoffs = Signoff.objects.for_package(package).filter(revoked__isnull=True) if signoffs.count() == spec.required: packager = package.packager # TODO: Handle notification when packager does not exist if packager: toemail = [packager.email] subject = f'{package.repo.name} package [{package.pkgname} {package.full_version}] approved' # send notification email to the maintainers tmpl = loader.get_template('packages/approved.txt') ctx = { 'signoffs': signoffs, 'pkg': package, } msg = EmailMessage(subject, tmpl.render(ctx), 'Arch Website Notification <nobody@archlinux.org>', toemail) msg.send(fail_silently=True) all_signoffs = Signoff.objects.for_package(package) if request.headers.get('x-requested-with') == 'XMLHttpRequest': data = { 'created': created, 'revoked': bool(signoff.revoked), 'approved': approved_by_signoffs(all_signoffs, spec), 'required': spec.required, 'enabled': spec.enabled, 'known_bad': spec.known_bad, 'user': str(request.user), } return HttpResponse(json.dumps(data, ensure_ascii=False), content_type='application/json') return redirect('package-signoffs') class SignoffOptionsForm(forms.ModelForm): apply_all = forms.BooleanField(required=False, help_text="Apply these options to all architectures?") class Meta: model = SignoffSpecification fields = ('required', 'enabled', 'known_bad', 'comments') def _signoff_options_all(request, name, repo): seen_ids = set() with transaction.atomic(): # find or create a specification for all architectures, then # graft the form data onto them packages = Package.objects.filter(pkgbase=name, repo__name__iexact=repo, repo__testing=True) for package in packages: try: spec = SignoffSpecification.objects.get_from_package(package) if spec.pk in seen_ids: continue except SignoffSpecification.DoesNotExist: spec = SignoffSpecification(pkgbase=package.pkgbase, pkgver=package.pkgver, pkgrel=package.pkgrel, epoch=package.epoch, arch=package.arch, repo=package.repo) if spec.user is None: spec.user = request.user form = SignoffOptionsForm(request.POST, instance=spec) if form.is_valid(): form.save() seen_ids.add(form.instance.pk) @permission_required('main.change_package') @never_cache def signoff_options(request, name, repo, arch): packages = get_list_or_404(Package, pkgbase=name, arch__name=arch, repo__name__iexact=repo, repo__testing=True) package = packages[0] if request.user != package.packager and \ request.user not in package.maintainers: return render(request, '403.html', status=403) try: spec = SignoffSpecification.objects.get_from_package(package) except SignoffSpecification.DoesNotExist: # create a fake one, but don't save it just yet spec = SignoffSpecification(pkgbase=package.pkgbase, pkgver=package.pkgver, pkgrel=package.pkgrel, epoch=package.epoch, arch=package.arch, repo=package.repo) if spec.user is None: spec.user = request.user if request.POST: form = SignoffOptionsForm(request.POST, instance=spec) if form.is_valid(): if form.cleaned_data['apply_all']: _signoff_options_all(request, name, repo) else: form.save() return redirect('package-signoffs') else: form = SignoffOptionsForm(instance=spec) context = { 'packages': packages, 'package': package, 'form': form, } return render(request, 'packages/signoff_options.html', context) class SignoffJSONEncoder(DjangoJSONEncoder): '''Base JSONEncoder extended to handle all serialization of all classes related to signoffs.''' signoff_group_attrs = ['arch', 'last_update', 'maintainers', 'packager', 'pkgbase', 'repo', 'signoffs', 'target_repo', 'version'] signoff_spec_attrs = ['required', 'enabled', 'known_bad', 'comments'] signoff_attrs = ['user', 'created', 'revoked'] def default(self, obj): if isinstance(obj, PackageSignoffGroup): data = {attr: getattr(obj, attr) for attr in self.signoff_group_attrs} data['pkgnames'] = [p.pkgname for p in obj.packages] data['package_count'] = len(obj.packages) data['approved'] = obj.approved() data.update((attr, getattr(obj.specification, attr)) for attr in self.signoff_spec_attrs) return data elif isinstance(obj, Signoff): return {attr: getattr(obj, attr) for attr in self.signoff_attrs} elif isinstance(obj, Arch) or isinstance(obj, Repo): return str(obj) elif isinstance(obj, User): return obj.username elif isinstance(obj, set): return list(obj) return super(SignoffJSONEncoder, self).default(obj) @permission_required('packages.change_signoff') def signoffs_json(request): signoff_groups = sorted(get_signoff_groups(), key=attrgetter('pkgbase')) data = { 'version': 2, 'signoff_groups': signoff_groups, } to_json = json.dumps(data, ensure_ascii=False, cls=SignoffJSONEncoder) response = HttpResponse(to_json, content_type='application/json') return response # vim: set ts=4 sw=4 et:
gpl-2.0
adster101/French-Connections-
administrator/templates/fcadmin/html/modules.php
3275
<?php /** * @package Joomla.Administrator * @subpackage Templates.isis * * @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; /** * This is a file to add template specific chrome to module rendering. To use it you would * set the style attribute for the given module(s) include in your template to use the style * for each given modChrome function. * * eg. To render a module mod_test in the submenu style, you would use the following include: * <jdoc:include type="module" name="test" style="submenu" /> * * This gives template designers ultimate control over how modules are rendered. * * NOTICE: All chrome wrapping methods should be named: modChrome_{STYLE} and take the same * two arguments. */ /* * Module chrome for rendering the module in a submenu */ function modChrome_title($module, &$params, &$attribs) { if ($module->content) { echo "<div class=\"module-title\"><h6>" . $module->title . "</h6></div>"; echo $module->content; } } function modChrome_no($module, &$params, &$attribs) { if ($module->content) { echo $module->content; } } function modChrome_well($module, &$params, &$attribs) { if ($module->content) { $bootstrapSize = $params->get('bootstrap_size'); $moduleClass = !empty($bootstrapSize) ? ' span' . (int) $bootstrapSize . '' : ''; // Temporarily store header class in variable $headerClass = $params->get('header_class'); $headerClass = !empty($headerClass) ? ' class="' . htmlspecialchars($headerClass) . '"' : ''; if ($moduleClass) { echo '<div class="' . $moduleClass . '">'; } echo '<div class="well well-small">'; echo '<h2 class="' . $headerClass . '">' . $module->title . '</h2>'; echo $module->content; echo '</div>'; if ($moduleClass) { echo '</div>'; } } } /* * html5 (chosen html5 tag and font headder tags) */ function modChrome_panel($module, &$params, &$attribs) { $moduleTag = $params->get('module_tag', 'div'); $headerTag = htmlspecialchars($params->get('header_tag', 'h3')); $bootstrapSize = (int) $params->get('bootstrap_size', 0); $moduleClass = $bootstrapSize != 0 ? ' span' . $bootstrapSize : ''; // Temporarily store header class in variable $headerClass = $params->get('header_class'); $headerClass = !empty($headerClass) ? ' class="' . htmlspecialchars($headerClass) . '"' : ''; if (!empty($module->content)) : ?> <<?php echo $moduleTag; ?> class="moduletable<?php echo $moduleClass; ?>"> <!-- This outputs another div but nests the module class suffix into the chrome --> <<?php echo $moduleTag; ?> class="<?php echo htmlspecialchars($params->get('moduleclass_sfx')); ?>"> <?php if ((bool) $module->showtitle) : ?> <?php echo '<div class="panel-heading">' ?> <<?php echo $headerTag . $headerClass . '>' . $module->title; ?></<?php echo $headerTag; ?>> <?php echo '</div>'; ?> <?php endif; ?> <?php echo '<div class="panel-body">' ?> <?php echo $module->content; ?> </<?php echo $moduleTag; ?>> </<?php echo $moduleTag; ?>> </<?php echo $moduleTag; ?>> <?php endif; }
gpl-2.0
drazenzadravec/nequeo
Source/Clients/Common/Nequeo.Client.Common/Nequeo.Client.Common/Chat/IChat.cs
2446
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2010 http://www.nequeo.com.au/ * * File : * Purpose : * */ #region Nequeo Pty Ltd License /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Nequeo.Net.Sockets; using Nequeo.Security; using Nequeo.Threading; using Nequeo.Data.Enum; using Nequeo.Data.Provider; namespace Nequeo.Client.Chat { /// <summary> /// Chat client interface. /// </summary> public interface IChat : Nequeo.Net.Sockets.IClient { /// <summary> /// Send the message to contacts online. /// </summary> /// <param name="message">The message to send.</param> /// <param name="all">If true then message is sent to all online contacts.</param> /// <param name="contactsOnline">The list of contacts online to send the message to.</param> /// <returns>True if sent; else false.</returns> bool SendMessage(byte[] message, bool all = false, string[] contactsOnline = null); } }
gpl-2.0
ElvisLouis/code
work/QT/Expriment/EVA/EVA_0.1/EVA/main.cpp
278
#include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QPushButton * button = new QPushButton("EVA"); connect(button , &QPushButton::clicked,&QApplication::quit); button.show(); /* MainWindow w; w.show(); */ return a.exec(); }
gpl-2.0
MinhTrung352/webbanhang
wp-content/themes/golmart/inc/core/widgets/twitter.php
13617
<?php /** * $Desc * * @version $Id$ * @package wpbase * @author Opal Team <opalwordpressl@gmail.com > * @copyright Copyright (C) 2014 wpopal.com. All Rights Reserved. * @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html * * @website http://www.wpopal.com * @support http://www.wpopal.com/support/forum.html */ class WPO_Tweets_Widget extends WPO_Widget{ public function __construct() { parent::__construct( // Base ID of your widget 'wpo_twitter_widget', // Widget name will appear in UI __('WPO Latest Twitter', TEXTDOMAIN), // Widget description array( 'description' => __( 'Latest Twitter widget.', TEXTDOMAIN ), ) ); $this->widgetName = 'twitter'; add_action( 'admin_enqueue_scripts', array( &$this, 'admin_enqueue_scripts' ) ); } public function admin_enqueue_scripts ( $hook_suffix ) { if ( $hook_suffix != 'widgets.php' ) return; wp_enqueue_style( 'wp-color-picker' ); wp_enqueue_script( 'wp-color-picker' ); } public function widget( $args, $instance ) { extract( $args ); //Our variables from the widget settings. $title = apply_filters('widget_title', esc_attr($instance['title'])); $user = $instance['user']; $twitter_id = $instance['twitter_id']; $limit = $instance['limit']; $width = $instance['width']; $height = $instance['height']; $border_color = $instance['border_color']; $link_color = $instance['link_color']; $text_color = $instance['text_color']; $name_color = $instance['name_color']; $mail_color = $instance['mail_color']; $show_scrollbar = $instance['show_scrollbar']; $show_replies = $instance['show_replies']; $chrome = ''; if ($instance['show_header'] == 0) { $chrome .= 'noheader '; } if ($instance['show_footer'] == 0) { $chrome .= 'nofooter '; } if ($instance['show_border'] == 0) { $chrome .= 'noborders '; } if ($instance['transparent'] == 0) { $chrome .= 'transparent'; } $js = '<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?\'http\':\'https\';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>'; //Test require($this->renderLayout('default')); echo ($after_widget); } //Update the widget public function update( $new_instance, $old_instance ) { $instance = $old_instance; //Strip tags from title and name to remove HTML $instance['title'] = strip_tags( $new_instance['title'] ); $instance['user'] = strip_tags( $new_instance['user'] ); $instance['twitter_id'] = strip_tags( $new_instance['twitter_id'] ); $instance['limit'] = $new_instance['limit']; $instance['width'] = $new_instance['width']; $instance['height'] = $new_instance['height']; $instance['border_color'] = strip_tags( $new_instance['border_color'] ); $instance['link_color'] = strip_tags( $new_instance['link_color'] ); $instance['text_color'] = strip_tags( $new_instance['text_color'] ); $instance['name_color'] = strip_tags( $new_instance['name_color'] ); $instance['mail_color'] = strip_tags( $new_instance['mail_color'] ); $instance['show_header'] = $new_instance['show_header']; $instance['show_footer'] = $new_instance['show_footer']; $instance['show_border'] = $new_instance['show_border']; $instance['show_scrollbar'] = $new_instance['show_scrollbar']; $instance['transparent'] = $new_instance['transparent']; $instance['show_replies'] = $new_instance['show_replies']; return $instance; } public function form( $instance ) { //Set up some default widget settings. $defaults = array( 'title' => __('Latest tweets.', TEXTDOMAIN), 'user' => __('Leotheme', TEXTDOMAIN), 'twitter_id' => '477627952327188480', 'limit' => 2, 'width' => 180, 'height' => 200, 'border_color' => ('#000'), 'link_color' => ('#000'), 'text_color' => ('#000'), 'name_color' => ('#000'), 'mail_color' => ('#000'), 'show_header' => 0, 'show_footer' => 0, 'show_border' => 0, 'show_scrollbar' => 0, 'transparent' => 0, 'show_replies' => 0, ); $values = array( 1 => __('Yes', TEXTDOMAIN), 0 => __('No', TEXTDOMAIN), ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <p> <label for="<?php echo esc_attr($this->get_field_id( 'title' )); ?>"><?php _e('Title:', TEXTDOMAIN); ?></label> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'title' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'title' )); ?>" value="<?php echo esc_attr($instance['title']); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'user' )); ?>"><?php _e('Twitter Username:', TEXTDOMAIN); ?></label> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'user' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'user' )); ?>" value="<?php echo esc_attr( $instance['user'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'limit' )); ?>"><?php _e('Limit:', TEXTDOMAIN); ?></label> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'limit' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'limit' )); ?>" value="<?php echo esc_attr( $instance['limit'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'twitter_id' )); ?>"><?php _e('Twitter Id:', TEXTDOMAIN); ?></label> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'twitter_id' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'twitter_id' )); ?>" value="<?php echo esc_attr( $instance['twitter_id'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'border_color' )); ?>"><?php _e('Border Color:', TEXTDOMAIN); ?></label> <br> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'border_color' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'border_color' )); ?>" value="<?php echo esc_attr( $instance['border_color'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'link_color' )); ?>"><?php _e('Link Color:', TEXTDOMAIN); ?></label> <br> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'link_color' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'link_color' )); ?>" value="<?php echo esc_attr( $instance['link_color'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'text_color' )); ?>"><?php _e('Text Color:', TEXTDOMAIN); ?></label> <br> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'text_color' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'text_color' )); ?>" value="<?php echo esc_attr( $instance['text_color'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'name_color' )); ?>"><?php _e('Name Color:', TEXTDOMAIN); ?></label> <br> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'name_color' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'name_color' )); ?>" value="<?php echo esc_attr( $instance['name_color'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'mail_color' )); ?>"><?php _e('Mail Color:', TEXTDOMAIN); ?></label> <br> <input type="text" id="<?php echo esc_attr($this->get_field_id( 'mail_color' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'mail_color' )); ?>" value="<?php echo esc_attr( $instance['mail_color'] ); ?>" style="width:100%;" /> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'transparent' )); ?>"><?php _e('Show background', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'transparent' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'transparent' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['transparent'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'show_replies' )); ?>"><?php _e('Show Replies', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'show_replies' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'show_replies' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['show_replies'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'show_header' )); ?>"><?php _e('Show Header', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'show_header' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'show_header' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['show_header'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'show_footer' )); ?>"><?php _e('Show Footer', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'show_footer' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'show_footer' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['show_footer'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'show_border' )); ?>"><?php _e('Show Border', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'show_border' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'show_border' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['show_border'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <p> <label for="<?php echo esc_attr($this->get_field_id( 'show_scrollbar' )); ?>"><?php _e('Show Scrollbar', TEXTDOMAIN); ?></label> <br> <select name="<?php echo esc_attr($this->get_field_name( 'show_scrollbar' )); ?>" id="<?php echo esc_attr($this->get_field_id( 'show_scrollbar' )); ?>"> <?php foreach ($values as $key => $value): ?> <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $instance['show_scrollbar'], $key ); ?>><?php echo esc_html( $value ); ?></option> <?php endforeach; ?> </select> </p> <script type="text/javascript"> jQuery(document).ready(function($){ $('#<?php echo esc_js( $this->get_field_id( 'border_color' ) ); ?>').wpColorPicker(); $('#<?php echo esc_js( $this->get_field_id( 'link_color' ) ); ?>').wpColorPicker(); $('#<?php echo esc_js( $this->get_field_id( 'text_color' ) ); ?>').wpColorPicker(); $('#<?php echo esc_js( $this->get_field_id( 'name_color' ) ); ?>').wpColorPicker(); $('#<?php echo esc_js( $this->get_field_id( 'mail_color' ) ); ?>').wpColorPicker(); }); </script> <?php } } register_widget( 'WPO_Tweets_Widget' ); ?>
gpl-2.0
ajaniv/softwarebook
c++/Calendar/CalendarTest/Rules/RulesTest.cpp
13628
/** * \file RulesTest.hpp * \brief RulesTest header file * */ /* * This file is part of OndALear collection of open source components. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Copyright (C) 2008 Amnon Janiv <amnon.janiv@ondalear.com> * * Initial version: 2011-11-11 * Author: Amnon Janiv <amnon.janiv@ondalear.com> */ /* * $Id: $ */ #include "RulesTest.hpp" #include "CalendarRuleTest.hpp" #include "MonthDayRuleTest.hpp" #include "SpecificDateRuleTest.hpp" #include "MonthWeekDayRuleTest.hpp" #include "FirstDayMonthRuleTest.hpp" #include "LastDayMonthRuleTest.hpp" #include "FirstDayAfterRuleTest.hpp" #include "FirstDayBeforeRuleTest.hpp" #include "WeekendRuleTest.hpp" #include "SpecificDatesRuleTest.hpp" #include "DaysOffsetRuleTest.hpp" #include "CompositeCalendarRuleTest.hpp" namespace ondalear { namespace test { namespace calendar { CppUnit::TestSuite* getCalendarRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "CalendarRuleTest" ); suite->addTest( new CppUnit::TestCaller<CalendarRuleTest>( "CalendarRuleTest::test_lifecycle_valid", &CalendarRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<CalendarRuleTest>( "CalendarRuleTest::test_operators_general", &CalendarRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<CalendarRuleTest>( "CalendarRuleTest::test_accessors", &CalendarRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<CalendarRuleTest>( "CalendarRuleTest::test_utilities", &CalendarRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getMonthDayRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "MonthDayRuleTest" ); suite->addTest( new CppUnit::TestCaller<MonthDayRuleTest>( "MonthDayRuleTest::test_lifecycle_valid", &MonthDayRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<MonthDayRuleTest>( "MonthDayRuleTest::test_lifecycle_invalid", &MonthDayRuleTest::test_lifecycle_invalid ) ); suite->addTest( new CppUnit::TestCaller<MonthDayRuleTest>( "MonthDayRuleTest::test_operators_general", &MonthDayRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<MonthDayRuleTest>( "MonthDayRuleTest::test_accessors", &MonthDayRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<MonthDayRuleTest>( "MonthDayRuleTest::test_utilities", &MonthDayRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getSpecificDateRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "SpecificDateRuleTest" ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_lifecycle_valid", &SpecificDateRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_operators_general", &SpecificDateRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_accessors", &SpecificDateRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_basic_calculation_valid", &SpecificDateRuleTest::test_basic_calculation_valid) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_basic_calculation_invalid", &SpecificDateRuleTest::test_basic_calculation_invalid) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_validation", &SpecificDateRuleTest::test_validation) ); suite->addTest( new CppUnit::TestCaller<SpecificDateRuleTest>( "SpecificDateRuleTest::test_utilities", &SpecificDateRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getMonthWeekDayRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "MonthWeekDayRuleTest" ); suite->addTest( new CppUnit::TestCaller<MonthWeekDayRuleTest>( "MonthWeekDayRuleTest::test_lifecycle_valid", &MonthWeekDayRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<MonthWeekDayRuleTest>( "MonthWeekDayRuleTest::test_lifecycle_invalid", &MonthWeekDayRuleTest::test_lifecycle_invalid ) ); suite->addTest( new CppUnit::TestCaller<MonthWeekDayRuleTest>( "MonthWeekDayRuleTest::test_operators_general", &MonthWeekDayRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<MonthWeekDayRuleTest>( "MonthWeekDayRuleTest::test_accessors", &MonthWeekDayRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<MonthWeekDayRuleTest>( "MonthWeekDayRuleTest::test_utilities", &MonthWeekDayRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getFirstDayMonthRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "FirstDayMonthRuleTest" ); suite->addTest( new CppUnit::TestCaller<FirstDayMonthRuleTest>( "FirstDayMonthRuleTest::test_lifecycle_valid", &FirstDayMonthRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<FirstDayMonthRuleTest>( "FirstDayMonthRuleTest::test_operators_general", &FirstDayMonthRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<FirstDayMonthRuleTest>( "FirstDayMonthRuleTest::test_accessors", &FirstDayMonthRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<FirstDayMonthRuleTest>( "FirstDayMonthRuleTest::test_utilities", &FirstDayMonthRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getLastDayMonthRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "LastDayMonthRuleTest" ); suite->addTest( new CppUnit::TestCaller<LastDayMonthRuleTest>( "LastDayMonthRuleTest::test_lifecycle_valid", &LastDayMonthRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<LastDayMonthRuleTest>( "LastDayMonthRuleTest::test_operators_general", &LastDayMonthRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<LastDayMonthRuleTest>( "LastDayMonthRuleTest::test_accessors", &LastDayMonthRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<LastDayMonthRuleTest>( "LastDayMonthRuleTest::test_utilities", &LastDayMonthRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getFirstDayAfterRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "FirstDayAfterRuleTest" ); suite->addTest( new CppUnit::TestCaller<FirstDayAfterRuleTest>( "FirstDayAfterRuleTest::test_lifecycle_valid", &FirstDayAfterRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<FirstDayAfterRuleTest>( "FirstDayAfterRuleTest::test_operators_general", &FirstDayAfterRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<FirstDayAfterRuleTest>( "FirstDayAfterRuleTest::test_accessors", &FirstDayAfterRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<FirstDayAfterRuleTest>( "FirstDayAfterRuleTest::test_utilities", &FirstDayAfterRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getFirstDayBeforeRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "FirstDayBeforeRuleTest" ); suite->addTest( new CppUnit::TestCaller<FirstDayBeforeRuleTest>( "FirstDayBeforeRuleTest::test_lifecycle_valid", &FirstDayBeforeRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<FirstDayBeforeRuleTest>( "FirstDayBeforeRuleTest::test_operators_general", &FirstDayBeforeRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<FirstDayBeforeRuleTest>( "FirstDayBeforeRuleTest::test_accessors", &FirstDayBeforeRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<FirstDayBeforeRuleTest>( "FirstDayBeforeRuleTest::test_utilities", &FirstDayBeforeRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getWeekendRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "WeekendRuleTest" ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_lifecycle_valid", &WeekendRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_operators_general", &WeekendRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_accessors", &WeekendRuleTest::test_accessors ) ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_structure", &WeekendRuleTest::test_structure ) ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_calculation", &WeekendRuleTest::test_calculation ) ); suite->addTest( new CppUnit::TestCaller<WeekendRuleTest>( "WeekendRuleTest::test_utilities", &WeekendRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getSpecificDatesRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "SpecificDatesRuleTest" ); suite->addTest( new CppUnit::TestCaller<SpecificDatesRuleTest>( "SpecificDatesRuleTest::test_lifecycle_valid", &SpecificDatesRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<SpecificDatesRuleTest>( "SpecificDatesRuleTest::test_operators_general", &SpecificDatesRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<SpecificDatesRuleTest>( "SpecificDatesRuleTest::test_accessors", &SpecificDatesRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<SpecificDatesRuleTest>( "SpecificDatesRuleTest::test_structure", &SpecificDatesRuleTest::test_structure) ); suite->addTest( new CppUnit::TestCaller<SpecificDatesRuleTest>( "SpecificDatesRuleTest::test_utilities", &SpecificDatesRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getDaysOffsetRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "DaysOffsetRuleTest" ); suite->addTest( new CppUnit::TestCaller<DaysOffsetRuleTest>( "DaysOffsetRuleTest::test_lifecycle_valid", &DaysOffsetRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<DaysOffsetRuleTest>( "DaysOffsetRuleTest::test_operators_general", &DaysOffsetRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<DaysOffsetRuleTest>( "DaysOffsetRuleTest::test_accessors", &DaysOffsetRuleTest::test_accessors) ); suite->addTest( new CppUnit::TestCaller<DaysOffsetRuleTest>( "DaysOffsetRuleTest::test_utilities", &DaysOffsetRuleTest::test_utilities) ); return suite; } CppUnit::TestSuite* getCompositeCalendarRuleTestSuite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite( "CompositeCalendarRuleTest" ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_lifecycle_valid", &CompositeCalendarRuleTest::test_lifecycle_valid ) ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_operators_general", &CompositeCalendarRuleTest::test_operators_general ) ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_structure", &CompositeCalendarRuleTest::test_structure) ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_utilities", &CompositeCalendarRuleTest::test_utilities) ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_calculation", &CompositeCalendarRuleTest::test_calculation) ); suite->addTest( new CppUnit::TestCaller<CompositeCalendarRuleTest>( "CompositeCalendarRuleTest::test_validation", &CompositeCalendarRuleTest::test_validation) ); return suite; } } //namespace calendar } //namespace test } //namespace ondalear
gpl-2.0
espertechinc/nesper
src/NEsper.Avro/Writer/AvroEventBeanWriterPerProp.cs
1895
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2015 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using com.espertech.esper.common.client; using com.espertech.esper.common.@internal.@event.core; using NEsper.Avro.Core; namespace NEsper.Avro.Writer { /// <summary> /// Writer method for writing to Object-array-type events. /// </summary> public class AvroEventBeanWriterPerProp : EventBeanWriter { private readonly AvroEventBeanPropertyWriter[] _writers; /// <summary> /// Ctor. /// </summary> /// <param name="writers">names of properties to write</param> public AvroEventBeanWriterPerProp(AvroEventBeanPropertyWriter[] writers) { _writers = writers; } /// <summary> /// Write values to an event. /// </summary> /// <param name="values">to write</param> /// <param name="theEvent">to write to</param> public void Write( object[] values, EventBean theEvent) { var arrayEvent = (AvroGenericDataBackedEventBean) theEvent; var arr = arrayEvent.Properties; for (var i = 0; i < _writers.Length; i++) { _writers[i].Write(values[i], arr); } } } } // end of namespace
gpl-2.0
joelbrock/PFC_CORE
pos/is4c-nf/plugins/QuickMenus/quickmenus/1.php
207
<?php $my_menu = array( "Charge Available Card" => "CCFROMCACHE", "Reset Terminal (Quick)" => "TERMRESET", "Tender External CC" => "MANUALCC", "Reboot Terminal (Slow)" => "TERMREBOOT", ); ?>
gpl-2.0
umlsynco/umlsync
diagrammer/dm/dm/LocalFilesView.js
1546
/* Class: LocalFilesView Author: Evgeny Alexeyev (evgeny.alexeyev@googlemail.com) Copyright: Copyright (c) 2012 Evgeny Alexeyev (evgeny.alexeyev@googlemail.com). All rights reserved. URL: umlsync.org/about Version: 2.0.0 (2012-07-22) */ //@aspect (function($, dm, undefined) { dm.base.LocalFilesView = function(urlArg) { var self = { euid: 'LocalFiles', init: function() { // Check localhost availability and select port }, info: function(callback) { if (callback) callback(null); }, remove: function(path, callback) { // All remove method could success if (callback) callback.call(); }, save: function(data, path, callback) { }, loadDiagram: function(node, callback) { $.log("LOADING: " + urlArg + node.getAbsolutePath() + ".json"); $.ajax({ url: urlArg + node.getAbsolutePath() + ".json", dataType: 'json', success: callback.success, error:callback.error }); }, newfolder:function(path,name,callback) { if (callback) callback({isFolder:true,isLazy:true,title:name}); }, tree: { persist: true, initAjax: { url: urlArg + "base.json"}, onLazyRead: function(node){ if (node.data.isFolder) { node.appendAjax({url: urlArg + node.getAbsolutePath() + ".json"}); } }, onActivate: function(node) { if (!node.data.isFolder) dm.dm.fw.loadDiagram(self.euid, node); }, } //tree }; return self; }; // @aspect })(jQuery, dm);
gpl-2.0
Caduceus/DecapitatedSoul
src/protocolgame.cpp
69065
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2020 Mark Samman <mark.samman@gmail.com> * Modifications made by Caduceus <decapitatedsoulot@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. */ #include "otpch.h" #include <boost/range/adaptor/reversed.hpp> #include "protocolgame.h" #include "outputmessage.h" #include "player.h" #include "configmanager.h" #include "actions.h" #include "game.h" #include "iologindata.h" #include "iomarket.h" #include "waitlist.h" #include "ban.h" #include "scheduler.h" #include "databasetasks.h" #include "modules.h" extern Game g_game; extern ConfigManager g_config; extern Actions actions; extern CreatureEvents* g_creatureEvents; extern Chat* g_chat; extern Modules* g_modules; ProtocolGame::LiveCastsMap ProtocolGame::liveCasts; void ProtocolGame::release() { //dispatcher thread stopLiveCast(); if (player && player->client == shared_from_this()) { player->client.reset(); player->decrementReferenceCounter(); player = nullptr; } OutputMessagePool::getInstance().removeProtocolFromAutosend(shared_from_this()); Protocol::release(); } void ProtocolGame::login(const std::string& name, uint32_t accountId, OperatingSystem_t operatingSystem) { //dispatcher thread Player* foundPlayer = g_game.getPlayerByName(name); if (!foundPlayer || g_config.getBoolean(ConfigManager::ALLOW_CLONES)) { player = new Player(getThis()); player->setName(name); player->incrementReferenceCounter(); player->setID(); if (!IOLoginData::preloadPlayer(player, name)) { disconnectClient("Your character could not be loaded."); return; } if (IOBan::isPlayerNamelocked(player->getGUID())) { disconnectClient("Your character has been namelocked."); return; } if (g_game.getGameState() == GAME_STATE_CLOSING && !player->hasFlag(PlayerFlag_CanAlwaysLogin)) { disconnectClient("The game is just going down.\nPlease try again later."); return; } if (g_game.getGameState() == GAME_STATE_CLOSED && !player->hasFlag(PlayerFlag_CanAlwaysLogin)) { disconnectClient("Server is currently closed.\nPlease try again later."); return; } if (g_config.getBoolean(ConfigManager::ONE_PLAYER_ON_ACCOUNT) && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && g_game.getPlayerByAccount(player->getAccount())) { disconnectClient("You may only login with one character\nof your account at the same time."); return; } if (!player->hasFlag(PlayerFlag_CannotBeBanned)) { BanInfo banInfo; if (IOBan::isAccountBanned(accountId, banInfo)) { if (banInfo.reason.empty()) { banInfo.reason = "(none)"; } std::ostringstream ss; if (banInfo.expiresAt > 0) { ss << "Your account has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason; } else { ss << "Your account has been permanently banned by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason; } disconnectClient(ss.str()); return; } } if (!WaitingList::getInstance()->clientLogin(player)) { uint32_t currentSlot = WaitingList::getInstance()->getClientSlot(player); uint32_t retryTime = WaitingList::getTime(currentSlot); std::ostringstream ss; ss << "Too many players online.\nYou are at place " << currentSlot << " on the waiting list."; auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x16); output->addString(ss.str()); output->addByte(retryTime); send(output); disconnect(); return; } if (!IOLoginData::loadPlayerByName(player, name)) { disconnectClient("Your character could not be loaded."); return; } player->setOperatingSystem(operatingSystem); if (!g_game.placeCreature(player, player->getLoginPosition())) { if (!g_game.placeCreature(player, player->getTemplePosition(), false, true)) { disconnectClient("Temple position is wrong. Contact the administrator."); return; } } if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) { player->registerCreatureEvent("ExtendedOpcode"); } player->lastIP = player->getIP(); player->lastLoginSaved = std::max<time_t>(time(nullptr), player->lastLoginSaved + 1); acceptPackets = true; } else { if (eventConnect != 0 || !g_config.getBoolean(ConfigManager::REPLACE_KICK_ON_LOGIN)) { //Already trying to connect disconnectClient("You are already logged in."); return; } if (foundPlayer->client) { foundPlayer->disconnect(); foundPlayer->isConnecting = true; eventConnect = g_scheduler.addEvent(createSchedulerTask(1000, std::bind(&ProtocolGame::connect, getThis(), foundPlayer->getID(), operatingSystem))); } else { connect(foundPlayer->getID(), operatingSystem); } } OutputMessagePool::getInstance().addProtocolToAutosend(shared_from_this()); } void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) { eventConnect = 0; Player* foundPlayer = g_game.getPlayerByID(playerId); if (!foundPlayer || foundPlayer->client) { disconnectClient("You are already logged in."); return; } if (isConnectionExpired()) { //ProtocolGame::release() has been called at this point and the Connection object //no longer exists, so we return to prevent leakage of the Player. return; } player = foundPlayer; player->incrementReferenceCounter(); g_chat->removeUserFromAllChannels(*player); player->clearModalWindows(); player->setOperatingSystem(operatingSystem); player->isConnecting = false; player->client = getThis(); sendAddCreature(player, player->getPosition(), 0, false); player->lastIP = player->getIP(); player->lastLoginSaved = std::max<time_t>(time(nullptr), player->lastLoginSaved + 1); acceptPackets = true; } void ProtocolGame::logout(bool displayEffect, bool forced) { //dispatcher thread if (!player) { return; } if (!player->isRemoved()) { if (!forced) { if (!player->isAccessPlayer()) { if (player->getTile()->hasFlag(TILESTATE_NOLOGOUT)) { player->sendCancelMessage(RETURNVALUE_YOUCANNOTLOGOUTHERE); return; } if (!player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) && player->hasCondition(CONDITION_INFIGHT)) { player->sendCancelMessage(RETURNVALUE_YOUMAYNOTLOGOUTDURINGAFIGHT); return; } } //scripting event - onLogout if (!g_creatureEvents->playerLogout(player)) { //Let the script handle the error message return; } } if (displayEffect && player->getHealth() > 0) { g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); } } stopLiveCast(); disconnect(); g_game.removeCreature(player); } bool ProtocolGame::startLiveCast(const std::string& password /*= ""*/) { auto connection = getConnection(); if (!g_config.getBoolean(ConfigManager::ENABLE_LIVE_CASTING) || isLiveCaster() || !player || player->isRemoved() || !connection || liveCasts.size() >= getMaxLiveCastCount()) { return false; } { std::lock_guard<decltype(liveCastLock)> lock{ liveCastLock }; //DO NOT do any send operations here liveCastName = player->getName(); liveCastPassword = password; isCaster.store(true, std::memory_order_relaxed); } liveCasts.insert(std::make_pair(player, getThis())); registerLiveCast(); //Send a "dummy" channel sendChannel(CHANNEL_CAST, LIVE_CAST_CHAT_NAME, nullptr, nullptr); return true; } bool ProtocolGame::stopLiveCast() { //dispatcher if (!isLiveCaster()) { return false; } CastSpectatorVec spectators; { std::lock_guard<decltype(liveCastLock)> lock{ liveCastLock }; //DO NOT do any send operations here std::swap(this->spectators, spectators); isCaster.store(false, std::memory_order_relaxed); } liveCasts.erase(player); for (auto& spectator : spectators) { spectator->onLiveCastStop(); } unregisterLiveCast(); return true; } void ProtocolGame::clearLiveCastInfo() { static std::once_flag flag; std::call_once(flag, []() { assert(g_game.getGameState() == GAME_STATE_INIT); std::ostringstream query; query << "TRUNCATE TABLE `live_casts`;"; g_databaseTasks.addTask(query.str()); }); } void ProtocolGame::registerLiveCast() { std::ostringstream query; query << "INSERT into `live_casts` (`player_id`, `cast_name`, `password`) VALUES (" << player->getGUID() << ", '" << getLiveCastName() << "', " << isPasswordProtected() << ");"; g_databaseTasks.addTask(query.str()); } void ProtocolGame::unregisterLiveCast() { std::ostringstream query; query << "DELETE FROM `live_casts` WHERE `player_id`=" << player->getGUID() << ";"; g_databaseTasks.addTask(query.str()); } void ProtocolGame::updateLiveCastInfo() { std::ostringstream query; query << "UPDATE `live_casts` SET `cast_name`='" << getLiveCastName() << "', `password`=" << isPasswordProtected() << ", `spectators`=" << getSpectatorCount() << " WHERE `player_id`=" << player->getGUID() << ";"; g_databaseTasks.addTask(query.str()); } void ProtocolGame::addSpectator(ProtocolSpectator_ptr spectatorClient) { std::lock_guard<decltype(liveCastLock)> lock(liveCastLock); //DO NOT do any send operations here spectators.emplace_back(spectatorClient); updateLiveCastInfo(); } void ProtocolGame::removeSpectator(ProtocolSpectator_ptr spectatorClient) { std::lock_guard<decltype(liveCastLock)> lock(liveCastLock); //DO NOT do any send operations here auto it = std::find(spectators.begin(), spectators.end(), spectatorClient); if (it != spectators.end()) { spectators.erase(it); updateLiveCastInfo(); } } void ProtocolGame::onRecvFirstMessage(NetworkMessage& msg) { if (g_game.getGameState() == GAME_STATE_SHUTDOWN) { disconnect(); return; } OperatingSystem_t operatingSystem = static_cast<OperatingSystem_t>(msg.get<uint16_t>()); version = msg.get<uint16_t>(); msg.skipBytes(7); // U32 client version, U8 client type, U16 dat revision if (!Protocol::RSA_decrypt(msg)) { disconnect(); return; } uint32_t key[4]; key[0] = msg.get<uint32_t>(); key[1] = msg.get<uint32_t>(); key[2] = msg.get<uint32_t>(); key[3] = msg.get<uint32_t>(); enableXTEAEncryption(); setXTEAKey(key); if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) { NetworkMessage opcodeMessage; opcodeMessage.addByte(0x32); opcodeMessage.addByte(0x00); opcodeMessage.add<uint16_t>(0x00); writeToOutputBuffer(opcodeMessage); } msg.skipBytes(1); // gamemaster flag std::string sessionKey = msg.getString(); size_t pos = sessionKey.find('\n'); if (pos == std::string::npos) { disconnectClient("You must enter your account name."); return; } std::string accountName = sessionKey.substr(0, pos); if (accountName.empty()) { disconnectClient("You must enter your account name."); return; } std::string password = sessionKey.substr(pos + 1); std::string characterName = msg.getString(); uint32_t timeStamp = msg.get<uint32_t>(); uint8_t randNumber = msg.getByte(); if (challengeTimestamp != timeStamp || challengeRandom != randNumber) { disconnect(); return; } if (version < CLIENT_VERSION_MIN || version > CLIENT_VERSION_MAX) { disconnectClient("Only clients with protocol " CLIENT_VERSION_STR " allowed!"); return; } if (g_game.getGameState() == GAME_STATE_STARTUP) { disconnectClient("Gameworld is starting up. Please wait."); return; } if (g_game.getGameState() == GAME_STATE_MAINTAIN) { disconnectClient("Gameworld is under maintenance. Please re-connect in a while."); return; } BanInfo banInfo; if (IOBan::isIpBanned(getIP(), banInfo)) { if (banInfo.reason.empty()) { banInfo.reason = "(none)"; } std::ostringstream ss; ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason; disconnectClient(ss.str()); return; } uint32_t accountId = IOLoginData::gameworldAuthentication(accountName, password, characterName); if (accountId == 0) { disconnectClient("Account name or password is not correct."); return; } g_dispatcher.addTask(createTask(std::bind(&ProtocolGame::login, getThis(), characterName, accountId, operatingSystem))); } void ProtocolGame::disconnectClient(const std::string& message) const { auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x14); output->addString(message); send(output); disconnect(); } void ProtocolGame::writeToOutputBuffer(const NetworkMessage& msg, bool broadcast /*= true*/) { if (!broadcast && isLiveCaster()) { //We're casting and we need to send a packet that's not supposed to be broadcast so we need a new messasge. //This shouldn't impact performance by a huge amount as most packets can be broadcast. auto out = OutputMessagePool::getOutputMessage(); out->append(msg); send(std::move(out)); } else { auto out = getOutputBuffer(msg.getLength()); if (isLiveCaster()) { out->setBroadcastMsg(true); } out->append(msg); } } void ProtocolGame::parsePacket(NetworkMessage& msg) { if (!acceptPackets || g_game.getGameState() == GAME_STATE_SHUTDOWN || msg.getLength() <= 0) { return; } uint8_t recvbyte = msg.getByte(); //a dead player can not perform actions if (!player || player->isRemoved() || player->getHealth() <= 0) { auto this_ptr = getThis(); g_dispatcher.addTask(createTask([this_ptr]() { this_ptr->stopLiveCast(); })); if (recvbyte == 0x0F) { disconnect(); return; } if (recvbyte != 0x14) { return; } } g_dispatcher.addTask(createTask(std::bind(&Modules::executeOnRecvbyte, g_modules, player, msg, recvbyte))); switch (recvbyte) { case 0x14: g_dispatcher.addTask(createTask(std::bind(&ProtocolGame::logout, getThis(), true, false))); break; case 0x1D: addGameTask(&Game::playerReceivePingBack, player->getID()); break; case 0x1E: addGameTask(&Game::playerReceivePing, player->getID()); break; case 0x32: parseExtendedOpcode(msg); break; //otclient extended opcode case 0x64: parseAutoWalk(msg); break; case 0x65: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTH); break; case 0x66: addGameTask(&Game::playerMove, player->getID(), DIRECTION_EAST); break; case 0x67: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTH); break; case 0x68: addGameTask(&Game::playerMove, player->getID(), DIRECTION_WEST); break; case 0x69: addGameTask(&Game::playerStopAutoWalk, player->getID()); break; case 0x6A: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHEAST); break; case 0x6B: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHEAST); break; case 0x6C: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHWEST); break; case 0x6D: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHWEST); break; case 0x6F: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_NORTH); break; case 0x70: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_EAST); break; case 0x71: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_SOUTH); break; case 0x72: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_WEST); break; case 0x78: parseThrow(msg); break; case 0x79: parseLookInShop(msg); break; case 0x7A: parsePlayerPurchase(msg); break; case 0x7B: parsePlayerSale(msg); break; case 0x7C: addGameTask(&Game::playerCloseShop, player->getID()); break; case 0x7D: parseRequestTrade(msg); break; case 0x7E: parseLookInTrade(msg); break; case 0x7F: addGameTask(&Game::playerAcceptTrade, player->getID()); break; case 0x80: addGameTask(&Game::playerCloseTrade, player->getID()); break; case 0x82: parseUseItem(msg); break; case 0x83: parseUseItemEx(msg); break; case 0x84: parseUseWithCreature(msg); break; case 0x85: parseRotateItem(msg); break; case 0x87: parseCloseContainer(msg); break; case 0x88: parseUpArrowContainer(msg); break; case 0x89: parseTextWindow(msg); break; case 0x8A: parseHouseWindow(msg); break; case 0x8B: parseWrapItem(msg); break; case 0x8C: parseLookAt(msg); break; case 0x8D: parseLookInBattleList(msg); break; case 0x8E: /* join aggression */ break; case 0x96: parseSay(msg); break; case 0x97: addGameTask(&Game::playerRequestChannels, player->getID()); break; case 0x98: parseOpenChannel(msg); break; case 0x99: parseCloseChannel(msg); break; case 0x9A: parseOpenPrivateChannel(msg); break; case 0x9E: addGameTask(&Game::playerCloseNpcChannel, player->getID()); break; case 0xA0: parseFightModes(msg); break; case 0xA1: parseAttack(msg); break; case 0xA2: parseFollow(msg); break; case 0xA3: parseInviteToParty(msg); break; case 0xA4: parseJoinParty(msg); break; case 0xA5: parseRevokePartyInvite(msg); break; case 0xA6: parsePassPartyLeadership(msg); break; case 0xA7: addGameTask(&Game::playerLeaveParty, player->getID()); break; case 0xA8: parseEnableSharedPartyExperience(msg); break; case 0xAA: addGameTask(&Game::playerCreatePrivateChannel, player->getID()); break; case 0xAB: parseChannelInvite(msg); break; case 0xAC: parseChannelExclude(msg); break; case 0xBE: addGameTask(&Game::playerCancelAttackAndFollow, player->getID()); break; case 0xC9: /* update tile */ break; case 0xCA: parseUpdateContainer(msg); break; case 0xCB: parseBrowseField(msg); break; case 0xCC: parseSeekInContainer(msg); break; case 0xD2: addGameTask(&Game::playerRequestOutfit, player->getID()); break; case 0xD3: parseSetOutfit(msg); break; case 0xD4: parseToggleMount(msg); break; case 0xDC: parseAddVip(msg); break; case 0xDD: parseRemoveVip(msg); break; case 0xDE: parseEditVip(msg); break; case 0xE6: parseBugReport(msg); break; case 0xE7: /* thank you */ break; case 0xE8: parseDebugAssert(msg); break; case 0xF0: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerShowQuestLog, player->getID()); break; case 0xF1: parseQuestLine(msg); break; case 0xF2: /* rule violation report */ break; case 0xF3: /* get object info */ break; case 0xF4: parseMarketLeave(); break; case 0xF5: parseMarketBrowse(msg); break; case 0xF6: parseMarketCreateOffer(msg); break; case 0xF7: parseMarketCancelOffer(msg); break; case 0xF8: parseMarketAcceptOffer(msg); break; case 0xF9: parseModalWindowAnswer(msg); break; default: // std::cout << "Player: " << player->getName() << " sent an unknown packet header: 0x" << std::hex << static_cast<uint16_t>(recvbyte) << std::dec << "!" << std::endl; break; } if (msg.isOverrun()) { disconnect(); } } // Parse methods void ProtocolGame::parseChannelInvite(NetworkMessage& msg) { const std::string name = msg.getString(); addGameTask(&Game::playerChannelInvite, player->getID(), name); } void ProtocolGame::parseChannelExclude(NetworkMessage& msg) { const std::string name = msg.getString(); addGameTask(&Game::playerChannelExclude, player->getID(), name); } void ProtocolGame::parseOpenChannel(NetworkMessage& msg) { uint16_t channelId = msg.get<uint16_t>(); addGameTask(&Game::playerOpenChannel, player->getID(), channelId); } void ProtocolGame::parseCloseChannel(NetworkMessage& msg) { uint16_t channelId = msg.get<uint16_t>(); addGameTask(&Game::playerCloseChannel, player->getID(), channelId); } void ProtocolGame::parseOpenPrivateChannel(NetworkMessage& msg) { const std::string receiver = msg.getString(); addGameTask(&Game::playerOpenPrivateChannel, player->getID(), receiver); } void ProtocolGame::parseAutoWalk(NetworkMessage& msg) { uint8_t numdirs = msg.getByte(); if (numdirs == 0 || (msg.getBufferPosition() + numdirs) != (msg.getLength() + 8)) { return; } msg.skipBytes(numdirs); std::forward_list<Direction> path; for (uint8_t i = 0; i < numdirs; ++i) { uint8_t rawdir = msg.getPreviousByte(); switch (rawdir) { case 1: path.push_front(DIRECTION_EAST); break; case 2: path.push_front(DIRECTION_NORTHEAST); break; case 3: path.push_front(DIRECTION_NORTH); break; case 4: path.push_front(DIRECTION_NORTHWEST); break; case 5: path.push_front(DIRECTION_WEST); break; case 6: path.push_front(DIRECTION_SOUTHWEST); break; case 7: path.push_front(DIRECTION_SOUTH); break; case 8: path.push_front(DIRECTION_SOUTHEAST); break; default: break; } } if (path.empty()) { return; } addGameTask(&Game::playerAutoWalk, player->getID(), path); } void ProtocolGame::parseSetOutfit(NetworkMessage& msg) { Outfit_t newOutfit; newOutfit.lookType = msg.get<uint16_t>(); newOutfit.lookHead = msg.getByte(); newOutfit.lookBody = msg.getByte(); newOutfit.lookLegs = msg.getByte(); newOutfit.lookFeet = msg.getByte(); newOutfit.lookAddons = msg.getByte(); newOutfit.lookMount = msg.get<uint16_t>(); addGameTask(&Game::playerChangeOutfit, player->getID(), newOutfit); } void ProtocolGame::parseToggleMount(NetworkMessage& msg) { bool mount = msg.getByte() != 0; addGameTask(&Game::playerToggleMount, player->getID(), mount); } void ProtocolGame::parseUseItem(NetworkMessage& msg) { Position pos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t stackpos = msg.getByte(); uint8_t index = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItem, player->getID(), pos, stackpos, index, spriteId); } void ProtocolGame::parseUseItemEx(NetworkMessage& msg) { Position fromPos = msg.getPosition(); uint16_t fromSpriteId = msg.get<uint16_t>(); uint8_t fromStackPos = msg.getByte(); Position toPos = msg.getPosition(); uint16_t toSpriteId = msg.get<uint16_t>(); uint8_t toStackPos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItemEx, player->getID(), fromPos, fromStackPos, fromSpriteId, toPos, toStackPos, toSpriteId); } void ProtocolGame::parseUseWithCreature(NetworkMessage& msg) { Position fromPos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t fromStackPos = msg.getByte(); uint32_t creatureId = msg.get<uint32_t>(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseWithCreature, player->getID(), fromPos, fromStackPos, creatureId, spriteId); } void ProtocolGame::parseCloseContainer(NetworkMessage& msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerCloseContainer, player->getID(), cid); } void ProtocolGame::parseUpArrowContainer(NetworkMessage& msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerMoveUpContainer, player->getID(), cid); } void ProtocolGame::parseUpdateContainer(NetworkMessage& msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerUpdateContainer, player->getID(), cid); } void ProtocolGame::parseThrow(NetworkMessage& msg) { Position fromPos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t fromStackpos = msg.getByte(); Position toPos = msg.getPosition(); uint8_t count = msg.getByte(); if (toPos != fromPos) { addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerMoveThing, player->getID(), fromPos, spriteId, fromStackpos, toPos, count); } } void ProtocolGame::parseLookAt(NetworkMessage& msg) { Position pos = msg.getPosition(); msg.skipBytes(2); // spriteId uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookAt, player->getID(), pos, stackpos); } void ProtocolGame::parseLookInBattleList(NetworkMessage& msg) { uint32_t creatureId = msg.get<uint32_t>(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInBattleList, player->getID(), creatureId); } void ProtocolGame::parseSay(NetworkMessage& msg) { std::string receiver; uint16_t channelId; SpeakClasses type = static_cast<SpeakClasses>(msg.getByte()); switch (type) { case TALKTYPE_PRIVATE_TO: case TALKTYPE_PRIVATE_RED_TO: receiver = msg.getString(); channelId = 0; break; case TALKTYPE_CHANNEL_Y: case TALKTYPE_CHANNEL_R1: channelId = msg.get<uint16_t>(); break; default: channelId = 0; break; } const std::string text = msg.getString(); if (text.length() > 255) { return; } addGameTask(&Game::playerSay, player->getID(), channelId, type, receiver, text); } void ProtocolGame::parseFightModes(NetworkMessage& msg) { uint8_t rawFightMode = msg.getByte(); // 1 - offensive, 2 - balanced, 3 - defensive uint8_t rawChaseMode = msg.getByte(); // 0 - stand while fightning, 1 - chase opponent uint8_t rawSecureMode = msg.getByte(); // 0 - can't attack unmarked, 1 - can attack unmarked // uint8_t rawPvpMode = msg.getByte(); // pvp mode introduced in 10.0 chaseMode_t chaseMode; if (rawChaseMode == 1) { chaseMode = CHASEMODE_FOLLOW; } else { chaseMode = CHASEMODE_STANDSTILL; } fightMode_t fightMode; if (rawFightMode == 1) { fightMode = FIGHTMODE_ATTACK; } else if (rawFightMode == 2) { fightMode = FIGHTMODE_BALANCED; } else { fightMode = FIGHTMODE_DEFENSE; } addGameTask(&Game::playerSetFightModes, player->getID(), fightMode, chaseMode, rawSecureMode != 0); } void ProtocolGame::parseAttack(NetworkMessage& msg) { uint32_t creatureId = msg.get<uint32_t>(); // msg.get<uint32_t>(); creatureId (same as above) addGameTask(&Game::playerSetAttackedCreature, player->getID(), creatureId); } void ProtocolGame::parseFollow(NetworkMessage& msg) { uint32_t creatureId = msg.get<uint32_t>(); // msg.get<uint32_t>(); creatureId (same as above) addGameTask(&Game::playerFollowCreature, player->getID(), creatureId); } void ProtocolGame::parseTextWindow(NetworkMessage& msg) { uint32_t windowTextId = msg.get<uint32_t>(); const std::string newText = msg.getString(); addGameTask(&Game::playerWriteItem, player->getID(), windowTextId, newText); } void ProtocolGame::parseHouseWindow(NetworkMessage& msg) { uint8_t doorId = msg.getByte(); uint32_t id = msg.get<uint32_t>(); const std::string text = msg.getString(); addGameTask(&Game::playerUpdateHouseWindow, player->getID(), doorId, id, text); } void ProtocolGame::parseWrapItem(NetworkMessage& msg) { Position pos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerWrapItem, player->getID(), pos, stackpos, spriteId); } void ProtocolGame::parseLookInShop(NetworkMessage& msg) { uint16_t id = msg.get<uint16_t>(); uint8_t count = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInShop, player->getID(), id, count); } void ProtocolGame::parsePlayerPurchase(NetworkMessage& msg) { uint16_t id = msg.get<uint16_t>(); uint8_t count = msg.getByte(); uint8_t amount = msg.getByte(); bool ignoreCap = msg.getByte() != 0; bool inBackpacks = msg.getByte() != 0; addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerPurchaseItem, player->getID(), id, count, amount, ignoreCap, inBackpacks); } void ProtocolGame::parsePlayerSale(NetworkMessage& msg) { uint16_t id = msg.get<uint16_t>(); uint8_t count = msg.getByte(); uint8_t amount = msg.getByte(); bool ignoreEquipped = msg.getByte() != 0; addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerSellItem, player->getID(), id, count, amount, ignoreEquipped); } void ProtocolGame::parseRequestTrade(NetworkMessage& msg) { Position pos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t stackpos = msg.getByte(); uint32_t playerId = msg.get<uint32_t>(); addGameTask(&Game::playerRequestTrade, player->getID(), pos, stackpos, playerId, spriteId); } void ProtocolGame::parseLookInTrade(NetworkMessage& msg) { bool counterOffer = (msg.getByte() == 0x01); uint8_t index = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInTrade, player->getID(), counterOffer, index); } void ProtocolGame::parseAddVip(NetworkMessage& msg) { const std::string name = msg.getString(); addGameTask(&Game::playerRequestAddVip, player->getID(), name); } void ProtocolGame::parseRemoveVip(NetworkMessage& msg) { uint32_t guid = msg.get<uint32_t>(); addGameTask(&Game::playerRequestRemoveVip, player->getID(), guid); } void ProtocolGame::parseEditVip(NetworkMessage& msg) { uint32_t guid = msg.get<uint32_t>(); const std::string description = msg.getString(); uint32_t icon = std::min<uint32_t>(10, msg.get<uint32_t>()); // 10 is max icon in 9.63 bool notify = msg.getByte() != 0; addGameTask(&Game::playerRequestEditVip, player->getID(), guid, description, icon, notify); } void ProtocolGame::parseRotateItem(NetworkMessage& msg) { Position pos = msg.getPosition(); uint16_t spriteId = msg.get<uint16_t>(); uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerRotateItem, player->getID(), pos, stackpos, spriteId); } void ProtocolGame::parseBugReport(NetworkMessage& msg) { uint8_t category = msg.getByte(); std::string message = msg.getString(); Position position; if (category == BUG_CATEGORY_MAP) { position = msg.getPosition(); } addGameTask(&Game::playerReportBug, player->getID(), message, position, category); } void ProtocolGame::parseDebugAssert(NetworkMessage& msg) { if (debugAssertSent) { return; } debugAssertSent = true; std::string assertLine = msg.getString(); std::string date = msg.getString(); std::string description = msg.getString(); std::string comment = msg.getString(); addGameTask(&Game::playerDebugAssert, player->getID(), assertLine, date, description, comment); } void ProtocolGame::parseInviteToParty(NetworkMessage& msg) { uint32_t targetId = msg.get<uint32_t>(); addGameTask(&Game::playerInviteToParty, player->getID(), targetId); } void ProtocolGame::parseJoinParty(NetworkMessage& msg) { uint32_t targetId = msg.get<uint32_t>(); addGameTask(&Game::playerJoinParty, player->getID(), targetId); } void ProtocolGame::parseRevokePartyInvite(NetworkMessage& msg) { uint32_t targetId = msg.get<uint32_t>(); addGameTask(&Game::playerRevokePartyInvitation, player->getID(), targetId); } void ProtocolGame::parsePassPartyLeadership(NetworkMessage& msg) { uint32_t targetId = msg.get<uint32_t>(); addGameTask(&Game::playerPassPartyLeadership, player->getID(), targetId); } void ProtocolGame::parseEnableSharedPartyExperience(NetworkMessage& msg) { bool sharedExpActive = msg.getByte() == 1; addGameTask(&Game::playerEnableSharedPartyExperience, player->getID(), sharedExpActive); } void ProtocolGame::parseQuestLine(NetworkMessage& msg) { uint16_t questId = msg.get<uint16_t>(); addGameTask(&Game::playerShowQuestLine, player->getID(), questId); } void ProtocolGame::parseMarketLeave() { addGameTask(&Game::playerLeaveMarket, player->getID()); } void ProtocolGame::parseMarketBrowse(NetworkMessage& msg) { uint16_t browseId = msg.get<uint16_t>(); if (browseId == MARKETREQUEST_OWN_OFFERS) { addGameTask(&Game::playerBrowseMarketOwnOffers, player->getID()); } else if (browseId == MARKETREQUEST_OWN_HISTORY) { addGameTask(&Game::playerBrowseMarketOwnHistory, player->getID()); } else { addGameTask(&Game::playerBrowseMarket, player->getID(), browseId); } } void ProtocolGame::parseMarketCreateOffer(NetworkMessage& msg) { uint8_t type = msg.getByte(); uint16_t spriteId = msg.get<uint16_t>(); uint16_t amount = msg.get<uint16_t>(); uint32_t price = msg.get<uint32_t>(); bool anonymous = (msg.getByte() != 0); addGameTask(&Game::playerCreateMarketOffer, player->getID(), type, spriteId, amount, price, anonymous); } void ProtocolGame::parseMarketCancelOffer(NetworkMessage& msg) { uint32_t timestamp = msg.get<uint32_t>(); uint16_t counter = msg.get<uint16_t>(); addGameTask(&Game::playerCancelMarketOffer, player->getID(), timestamp, counter); } void ProtocolGame::parseMarketAcceptOffer(NetworkMessage& msg) { uint32_t timestamp = msg.get<uint32_t>(); uint16_t counter = msg.get<uint16_t>(); uint16_t amount = msg.get<uint16_t>(); addGameTask(&Game::playerAcceptMarketOffer, player->getID(), timestamp, counter, amount); } void ProtocolGame::parseModalWindowAnswer(NetworkMessage& msg) { uint32_t id = msg.get<uint32_t>(); uint8_t button = msg.getByte(); uint8_t choice = msg.getByte(); addGameTask(&Game::playerAnswerModalWindow, player->getID(), id, button, choice); } void ProtocolGame::parseBrowseField(NetworkMessage& msg) { const Position& pos = msg.getPosition(); addGameTask(&Game::playerBrowseField, player->getID(), pos); } void ProtocolGame::parseSeekInContainer(NetworkMessage& msg) { uint8_t containerId = msg.getByte(); uint16_t index = msg.get<uint16_t>(); addGameTask(&Game::playerSeekInContainer, player->getID(), containerId, index); } // Send methods void ProtocolGame::sendOpenPrivateChannel(const std::string& receiver) { NetworkMessage msg; msg.addByte(0xAD); msg.addString(receiver); writeToOutputBuffer(msg); } void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string& playerName, ChannelEvent_t channelEvent) { NetworkMessage msg; msg.addByte(0xF3); msg.add<uint16_t>(channelId); msg.addString(playerName); msg.addByte(channelEvent); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureOutfit(const Creature* creature, const Outfit_t& outfit) { if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x8E); msg.add<uint32_t>(creature->getID()); AddOutfit(msg, outfit); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureWalkthrough(const Creature* creature, bool walkthrough) { if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x92); msg.add<uint32_t>(creature->getID()); msg.addByte(walkthrough ? 0x00 : 0x01); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureShield(const Creature* creature) { if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x91); msg.add<uint32_t>(creature->getID()); msg.addByte(player->getPartyShield(creature->getPlayer())); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureSkull(const Creature* creature) { if (g_game.getWorldType() != WORLD_TYPE_PVP) { return; } if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x90); msg.add<uint32_t>(creature->getID()); msg.addByte(player->getSkullClient(creature)); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureType(uint32_t creatureId, uint8_t creatureType) { NetworkMessage msg; msg.addByte(0x95); msg.add<uint32_t>(creatureId); msg.addByte(creatureType); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) { NetworkMessage msg; msg.addByte(0x94); msg.add<uint32_t>(creatureId); msg.add<uint16_t>(helpers); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureSquare(const Creature* creature, SquareColor_t color) { if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x93); msg.add<uint32_t>(creature->getID()); msg.addByte(0x01); msg.addByte(color); writeToOutputBuffer(msg); } void ProtocolGame::sendTutorial(uint8_t tutorialId) { NetworkMessage msg; msg.addByte(0xDC); msg.addByte(tutorialId); writeToOutputBuffer(msg); } void ProtocolGame::sendAddMarker(const Position& pos, uint8_t markType, const std::string& desc) { NetworkMessage msg; msg.addByte(0xDD); msg.addPosition(pos); msg.addByte(markType); msg.addString(desc); writeToOutputBuffer(msg); } void ProtocolGame::sendReLoginWindow(uint8_t unfairFightReduction) { NetworkMessage msg; msg.addByte(0x28); msg.addByte(0x00); msg.addByte(unfairFightReduction); writeToOutputBuffer(msg); } void ProtocolGame::sendTextMessage(const TextMessage& message) { NetworkMessage msg; msg.addByte(0xB4); msg.addByte(message.type); switch (message.type) { case MESSAGE_DAMAGE_DEALT: case MESSAGE_DAMAGE_RECEIVED: case MESSAGE_DAMAGE_OTHERS: { msg.addPosition(message.position); msg.add<uint32_t>(message.primary.value); msg.addByte(message.primary.color); msg.add<uint32_t>(message.secondary.value); msg.addByte(message.secondary.color); break; } case MESSAGE_HEALED: case MESSAGE_HEALED_OTHERS: case MESSAGE_EXPERIENCE: case MESSAGE_EXPERIENCE_OTHERS: { msg.addPosition(message.position); msg.add<uint32_t>(message.primary.value); msg.addByte(message.primary.color); break; } default: { break; } } msg.addString(message.text); writeToOutputBuffer(msg); } void ProtocolGame::sendClosePrivate(uint16_t channelId) { NetworkMessage msg; msg.addByte(0xB3); msg.add<uint16_t>(channelId); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatePrivateChannel(uint16_t channelId, const std::string& channelName) { NetworkMessage msg; msg.addByte(0xB2); msg.add<uint16_t>(channelId); msg.addString(channelName); msg.add<uint16_t>(0x01); msg.addString(player->getName()); msg.add<uint16_t>(0x00); writeToOutputBuffer(msg); } void ProtocolGame::sendChannelsDialog() { NetworkMessage msg; msg.addByte(0xAB); const ChannelList& list = g_chat->getChannelList(*player); msg.addByte(list.size()); for (ChatChannel* channel : list) { msg.add<uint16_t>(channel->getId()); msg.addString(channel->getName()); } writeToOutputBuffer(msg); } void ProtocolGame::sendChannelMessage(const std::string& author, const std::string& text, SpeakClasses type, uint16_t channel) { NetworkMessage msg; msg.addByte(0xAA); msg.add<uint32_t>(0x00); msg.addString(author); msg.add<uint16_t>(0x00); msg.addByte(type); msg.add<uint16_t>(channel); msg.addString(text); writeToOutputBuffer(msg); } void ProtocolGame::sendIcons(uint16_t icons) { NetworkMessage msg; msg.addByte(0xA2); msg.add<uint16_t>(icons); writeToOutputBuffer(msg); } void ProtocolGame::sendShop(Npc* npc, const ShopInfoList& itemList) { NetworkMessage msg; msg.addByte(0x7A); msg.addString(npc->getName()); uint16_t itemsToSend = std::min<size_t>(itemList.size(), std::numeric_limits<uint16_t>::max()); msg.add<uint16_t>(itemsToSend); uint16_t i = 0; for (ShopInfoList::const_iterator it = itemList.begin(); i < itemsToSend; ++it, ++i) { AddShopItem(msg, *it); } writeToOutputBuffer(msg); } void ProtocolGame::sendCloseShop() { NetworkMessage msg; msg.addByte(0x7C); writeToOutputBuffer(msg); } void ProtocolGame::sendSaleItemList(const std::list<ShopInfo>& shop) { NetworkMessage msg; msg.addByte(0x7B); //msg.add<uint64_t>(player->getMoney()); default msg.add<uint64_t>(player->getMoney() + player->getBankBalance()); std::map<uint16_t, uint32_t> saleMap; if (shop.size() <= 5) { // For very small shops it's not worth it to create the complete map for (const ShopInfo& shopInfo : shop) { if (shopInfo.sellPrice == 0) { continue; } int8_t subtype = -1; const ItemType& itemType = Item::items[shopInfo.itemId]; if (itemType.hasSubType() && !itemType.stackable) { subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType); } uint32_t count = player->getItemTypeCount(shopInfo.itemId, subtype); if (count > 0) { saleMap[shopInfo.itemId] = count; } } } else { // Large shop, it's better to get a cached map of all item counts and use it // We need a temporary map since the finished map should only contain items // available in the shop std::map<uint32_t, uint32_t> tempSaleMap; player->getAllItemTypeCount(tempSaleMap); // We must still check manually for the special items that require subtype matches // (That is, fluids such as potions etc., actually these items are very few since // health potions now use their own ID) for (const ShopInfo& shopInfo : shop) { if (shopInfo.sellPrice == 0) { continue; } int8_t subtype = -1; const ItemType& itemType = Item::items[shopInfo.itemId]; if (itemType.hasSubType() && !itemType.stackable) { subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType); } if (subtype != -1) { uint32_t count; if (!itemType.isFluidContainer() && !itemType.isSplash()) { count = player->getItemTypeCount(shopInfo.itemId, subtype); // This shop item requires extra checks } else { count = subtype; } if (count > 0) { saleMap[shopInfo.itemId] = count; } } else { std::map<uint32_t, uint32_t>::const_iterator findIt = tempSaleMap.find(shopInfo.itemId); if (findIt != tempSaleMap.end() && findIt->second > 0) { saleMap[shopInfo.itemId] = findIt->second; } } } } uint8_t itemsToSend = std::min<size_t>(saleMap.size(), std::numeric_limits<uint8_t>::max()); msg.addByte(itemsToSend); uint8_t i = 0; for (std::map<uint16_t, uint32_t>::const_iterator it = saleMap.begin(); i < itemsToSend; ++it, ++i) { msg.addItemId(it->first); msg.addByte(std::min<uint32_t>(it->second, std::numeric_limits<uint8_t>::max())); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketEnter(uint32_t depotId) { NetworkMessage msg; msg.addByte(0xF6); msg.add<uint64_t>(player->getBankBalance()); msg.addByte(std::min<uint32_t>(IOMarket::getPlayerOfferCount(player->getGUID()), std::numeric_limits<uint8_t>::max())); DepotLocker* depotLocker = player->getDepotLocker(depotId); if (!depotLocker) { msg.add<uint16_t>(0x00); writeToOutputBuffer(msg); return; } player->setInMarket(true); std::map<uint16_t, uint32_t> depotItems; std::forward_list<Container*> containerList{depotLocker}; do { Container* container = containerList.front(); containerList.pop_front(); for (Item* item : container->getItemList()) { Container* c = item->getContainer(); if (c && !c->empty()) { containerList.push_front(c); continue; } const ItemType& itemType = Item::items[item->getID()]; if (itemType.wareId == 0) { continue; } if (c && (!itemType.isContainer() || c->capacity() != itemType.maxItems)) { continue; } if (!item->hasMarketAttributes()) { continue; } depotItems[itemType.wareId] += Item::countByType(item, -1); } } while (!containerList.empty()); uint16_t itemsToSend = std::min<size_t>(depotItems.size(), std::numeric_limits<uint16_t>::max()); msg.add<uint16_t>(itemsToSend); uint16_t i = 0; for (std::map<uint16_t, uint32_t>::const_iterator it = depotItems.begin(); i < itemsToSend; ++it, ++i) { msg.add<uint16_t>(it->first); msg.add<uint16_t>(std::min<uint32_t>(0xFFFF, it->second)); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketLeave() { NetworkMessage msg; msg.addByte(0xF7); writeToOutputBuffer(msg); } void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList& buyOffers, const MarketOfferList& sellOffers) { NetworkMessage msg; msg.addByte(0xF9); msg.addItemId(itemId); msg.add<uint32_t>(buyOffers.size()); for (const MarketOffer& offer : buyOffers) { msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); msg.addString(offer.playerName); } msg.add<uint32_t>(sellOffers.size()); for (const MarketOffer& offer : sellOffers) { msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); msg.addString(offer.playerName); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx& offer) { NetworkMessage msg; msg.addByte(0xF9); msg.addItemId(offer.itemId); if (offer.type == MARKETACTION_BUY) { msg.add<uint32_t>(0x01); msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); msg.addString(offer.playerName); msg.add<uint32_t>(0x00); } else { msg.add<uint32_t>(0x00); msg.add<uint32_t>(0x01); msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); msg.addString(offer.playerName); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList& buyOffers, const MarketOfferList& sellOffers) { NetworkMessage msg; msg.addByte(0xF9); msg.add<uint16_t>(MARKETREQUEST_OWN_OFFERS); msg.add<uint32_t>(buyOffers.size()); for (const MarketOffer& offer : buyOffers) { msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.addItemId(offer.itemId); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); } msg.add<uint32_t>(sellOffers.size()); for (const MarketOffer& offer : sellOffers) { msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.addItemId(offer.itemId); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx& offer) { NetworkMessage msg; msg.addByte(0xF9); msg.add<uint16_t>(MARKETREQUEST_OWN_OFFERS); if (offer.type == MARKETACTION_BUY) { msg.add<uint32_t>(0x01); msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.addItemId(offer.itemId); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); msg.add<uint32_t>(0x00); } else { msg.add<uint32_t>(0x00); msg.add<uint32_t>(0x01); msg.add<uint32_t>(offer.timestamp); msg.add<uint16_t>(offer.counter); msg.addItemId(offer.itemId); msg.add<uint16_t>(offer.amount); msg.add<uint32_t>(offer.price); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList& buyOffers, const HistoryMarketOfferList& sellOffers) { uint32_t i = 0; std::map<uint32_t, uint16_t> counterMap; uint32_t buyOffersToSend = std::min<uint32_t>(buyOffers.size(), 810 + std::max<int32_t>(0, 810 - sellOffers.size())); uint32_t sellOffersToSend = std::min<uint32_t>(sellOffers.size(), 810 + std::max<int32_t>(0, 810 - buyOffers.size())); NetworkMessage msg; msg.addByte(0xF9); msg.add<uint16_t>(MARKETREQUEST_OWN_HISTORY); msg.add<uint32_t>(buyOffersToSend); for (HistoryMarketOfferList::const_iterator it = buyOffers.begin(); i < buyOffersToSend; ++it, ++i) { msg.add<uint32_t>(it->timestamp); msg.add<uint16_t>(counterMap[it->timestamp]++); msg.addItemId(it->itemId); msg.add<uint16_t>(it->amount); msg.add<uint32_t>(it->price); msg.addByte(it->state); } counterMap.clear(); i = 0; msg.add<uint32_t>(sellOffersToSend); for (HistoryMarketOfferList::const_iterator it = sellOffers.begin(); i < sellOffersToSend; ++it, ++i) { msg.add<uint32_t>(it->timestamp); msg.add<uint16_t>(counterMap[it->timestamp]++); msg.addItemId(it->itemId); msg.add<uint16_t>(it->amount); msg.add<uint32_t>(it->price); msg.addByte(it->state); } writeToOutputBuffer(msg); } void ProtocolGame::sendMarketDetail(uint16_t itemId) { NetworkMessage msg; msg.addByte(0xF8); msg.addItemId(itemId); const ItemType& it = Item::items[itemId]; if (it.armor != 0) { msg.addString(std::to_string(it.armor)); } else { msg.add<uint16_t>(0x00); } if (it.attack != 0) { // TODO: chance to hit, range // example: // "attack +x, chance to hit +y%, z fields" if (it.abilities && it.abilities->elementType != COMBAT_NONE && it.abilities->elementDamage != 0) { std::ostringstream ss; ss << it.attack << " physical +" << it.abilities->elementDamage << ' ' << getCombatName(it.abilities->elementType); msg.addString(ss.str()); } else { msg.addString(std::to_string(it.attack)); } } else { msg.add<uint16_t>(0x00); } if (it.isContainer()) { msg.addString(std::to_string(it.maxItems)); } else { msg.add<uint16_t>(0x00); } if (it.defense != 0) { if (it.extraDefense != 0) { std::ostringstream ss; ss << it.defense << ' ' << std::showpos << it.extraDefense << std::noshowpos; msg.addString(ss.str()); } else { msg.addString(std::to_string(it.defense)); } } else { msg.add<uint16_t>(0x00); } if (!it.description.empty()) { const std::string& descr = it.description; if (descr.back() == '.') { msg.addString(std::string(descr, 0, descr.length() - 1)); } else { msg.addString(descr); } } else { msg.add<uint16_t>(0x00); } if (it.decayTime != 0) { std::ostringstream ss; ss << it.decayTime << " seconds"; msg.addString(ss.str()); } else { msg.add<uint16_t>(0x00); } if (it.abilities) { std::ostringstream ss; bool separator = false; for (size_t i = 0; i < COMBAT_COUNT; ++i) { if (it.abilities->absorbPercent[i] == 0) { continue; } if (separator) { ss << ", "; } else { separator = true; } ss << getCombatName(indexToCombatType(i)) << ' ' << std::showpos << it.abilities->absorbPercent[i] << std::noshowpos << '%'; } msg.addString(ss.str()); } else { msg.add<uint16_t>(0x00); } if (it.minReqLevel != 0) { msg.addString(std::to_string(it.minReqLevel)); } else { msg.add<uint16_t>(0x00); } if (it.minReqMagicLevel != 0) { msg.addString(std::to_string(it.minReqMagicLevel)); } else { msg.add<uint16_t>(0x00); } msg.addString(it.vocationString); msg.addString(it.runeSpellName); if (it.abilities) { std::ostringstream ss; bool separator = false; for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; i++) { if (!it.abilities->skills[i]) { continue; } if (separator) { ss << ", "; } else { separator = true; } ss << getSkillName(i) << ' ' << std::showpos << it.abilities->skills[i] << std::noshowpos; } for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; i++) { if (!it.abilities->skills[i]) { continue; } if (separator) { ss << ", "; } else { separator = true; } ss << getSkillName(i) << ' ' << std::showpos << it.abilities->skills[i] << std::noshowpos << '%'; } if (it.abilities->stats[STAT_MAGICPOINTS] != 0) { if (separator) { ss << ", "; } else { separator = true; } ss << "magic level " << std::showpos << it.abilities->stats[STAT_MAGICPOINTS] << std::noshowpos; } if (it.abilities->speed != 0) { if (separator) { ss << ", "; } ss << "speed " << std::showpos << (it.abilities->speed >> 1) << std::noshowpos; } msg.addString(ss.str()); } else { msg.add<uint16_t>(0x00); } if (it.charges != 0) { msg.addString(std::to_string(it.charges)); } else { msg.add<uint16_t>(0x00); } std::string weaponName = getWeaponName(it.weaponType); if (it.slotPosition & SLOTP_TWO_HAND) { if (!weaponName.empty()) { weaponName += ", two-handed"; } else { weaponName = "two-handed"; } } msg.addString(weaponName); if (it.weight != 0) { std::ostringstream ss; if (it.weight < 10) { ss << "0.0" << it.weight; } else if (it.weight < 100) { ss << "0." << it.weight; } else { std::string weightString = std::to_string(it.weight); weightString.insert(weightString.end() - 2, '.'); ss << weightString; } ss << " oz"; msg.addString(ss.str()); } else { msg.add<uint16_t>(0x00); } MarketStatistics* statistics = IOMarket::getInstance()->getPurchaseStatistics(itemId); if (statistics) { msg.addByte(0x01); msg.add<uint32_t>(statistics->numTransactions); msg.add<uint32_t>(std::min<uint64_t>(std::numeric_limits<uint32_t>::max(), statistics->totalPrice)); msg.add<uint32_t>(statistics->highestPrice); msg.add<uint32_t>(statistics->lowestPrice); } else { msg.addByte(0x00); } statistics = IOMarket::getInstance()->getSaleStatistics(itemId); if (statistics) { msg.addByte(0x01); msg.add<uint32_t>(statistics->numTransactions); msg.add<uint32_t>(std::min<uint64_t>(std::numeric_limits<uint32_t>::max(), statistics->totalPrice)); msg.add<uint32_t>(statistics->highestPrice); msg.add<uint32_t>(statistics->lowestPrice); } else { msg.addByte(0x00); } writeToOutputBuffer(msg); } void ProtocolGame::sendQuestLog() { NetworkMessage msg; msg.addByte(0xF0); msg.add<uint16_t>(g_game.quests.getQuestsCount(player)); for (const Quest& quest : g_game.quests.getQuests()) { if (quest.isStarted(player)) { msg.add<uint16_t>(quest.getID()); msg.addString(quest.getName()); msg.addByte(quest.isCompleted(player)); } } writeToOutputBuffer(msg); } void ProtocolGame::sendQuestLine(const Quest* quest) { NetworkMessage msg; msg.addByte(0xF1); msg.add<uint16_t>(quest->getID()); msg.addByte(quest->getMissionsCount(player)); for (const Mission& mission : quest->getMissions()) { if (mission.isStarted(player)) { msg.addString(mission.getName(player)); msg.addString(mission.getDescription(player)); } } writeToOutputBuffer(msg); } void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const Item* item, bool ack) { NetworkMessage msg; if (ack) { msg.addByte(0x7D); } else { msg.addByte(0x7E); } msg.addString(traderName); if (const Container* tradeContainer = item->getContainer()) { std::list<const Container*> listContainer {tradeContainer}; std::list<const Item*> itemList {tradeContainer}; while (!listContainer.empty()) { const Container* container = listContainer.front(); listContainer.pop_front(); for (Item* containerItem : container->getItemList()) { Container* tmpContainer = containerItem->getContainer(); if (tmpContainer) { listContainer.push_back(tmpContainer); } itemList.push_back(containerItem); } } msg.addByte(itemList.size()); for (const Item* listItem : itemList) { msg.addItem(listItem); } } else { msg.addByte(0x01); msg.addItem(item); } writeToOutputBuffer(msg); } void ProtocolGame::sendCloseTrade() { NetworkMessage msg; msg.addByte(0x7F); writeToOutputBuffer(msg); } void ProtocolGame::sendCloseContainer(uint8_t cid) { NetworkMessage msg; msg.addByte(0x6F); msg.addByte(cid); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureTurn(const Creature* creature, uint32_t stackPos) { if (!canSee(creature)) { return; } NetworkMessage msg; msg.addByte(0x6B); msg.addPosition(creature->getPosition()); msg.addByte(stackPos); msg.add<uint16_t>(0x63); msg.add<uint32_t>(creature->getID()); msg.addByte(creature->getDirection()); msg.addByte(player->canWalkthroughEx(creature) ? 0x00 : 0x01); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string& text, const Position* pos/* = nullptr*/) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; msg.add<uint32_t>(++statementId); msg.addString(creature->getName()); //Add level only for players if (const Player* speaker = creature->getPlayer()) { msg.add<uint16_t>(speaker->getLevel()); } else { msg.add<uint16_t>(0x00); } msg.addByte(type); if (pos) { msg.addPosition(*pos); } else { msg.addPosition(creature->getPosition()); } msg.addString(text); writeToOutputBuffer(msg); } void ProtocolGame::sendToChannel(const Creature* creature, SpeakClasses type, const std::string& text, uint16_t channelId) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; msg.add<uint32_t>(++statementId); if (!creature) { msg.add<uint32_t>(0x00); } else if (type == TALKTYPE_CHANNEL_R2) { msg.add<uint32_t>(0x00); type = TALKTYPE_CHANNEL_R1; } else { msg.addString(creature->getName()); //Add level only for players if (const Player* speaker = creature->getPlayer()) { msg.add<uint16_t>(speaker->getLevel()); } else { msg.add<uint16_t>(0x00); } } msg.addByte(type); msg.add<uint16_t>(channelId); msg.addString(text); writeToOutputBuffer(msg); } void ProtocolGame::sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string& text) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; msg.add<uint32_t>(++statementId); if (speaker) { msg.addString(speaker->getName()); msg.add<uint16_t>(speaker->getLevel()); } else { msg.add<uint32_t>(0x00); } msg.addByte(type); msg.addString(text); writeToOutputBuffer(msg); } void ProtocolGame::sendCancelTarget() { NetworkMessage msg; msg.addByte(0xA3); msg.add<uint32_t>(0x00); writeToOutputBuffer(msg); } void ProtocolGame::sendChangeSpeed(const Creature* creature, uint32_t speed) { NetworkMessage msg; msg.addByte(0x8F); msg.add<uint32_t>(creature->getID()); msg.add<uint16_t>(creature->getBaseSpeed() / 2); msg.add<uint16_t>(speed / 2); writeToOutputBuffer(msg); } void ProtocolGame::sendDistanceShoot(const Position& from, const Position& to, uint8_t type) { NetworkMessage msg; msg.addByte(0x85); msg.addPosition(from); msg.addPosition(to); msg.addByte(type); writeToOutputBuffer(msg); } void ProtocolGame::sendCreatureHealth(const Creature* creature) { NetworkMessage msg; msg.addByte(0x8C); msg.add<uint32_t>(creature->getID()); if (creature->isHealthHidden()) { msg.addByte(0x00); } else { msg.addByte(std::ceil((static_cast<double>(creature->getHealth()) / std::max<int32_t>(creature->getMaxHealth(), 1)) * 100)); } writeToOutputBuffer(msg); } void ProtocolGame::sendFYIBox(const std::string& message) { NetworkMessage msg; msg.addByte(0x15); msg.addString(message); writeToOutputBuffer(msg); } //tile void ProtocolGame::sendAddTileItem(const Position& pos, uint32_t stackpos, const Item* item) { if (!canSee(pos)) { return; } NetworkMessage msg; msg.addByte(0x6A); msg.addPosition(pos); msg.addByte(stackpos); msg.addItem(item); writeToOutputBuffer(msg); } void ProtocolGame::sendUpdateTileItem(const Position& pos, uint32_t stackpos, const Item* item) { if (!canSee(pos)) { return; } NetworkMessage msg; msg.addByte(0x6B); msg.addPosition(pos); msg.addByte(stackpos); msg.addItem(item); writeToOutputBuffer(msg); } void ProtocolGame::sendRemoveTileThing(const Position& pos, uint32_t stackpos) { if (!canSee(pos)) { return; } NetworkMessage msg; RemoveTileThing(msg, pos, stackpos); writeToOutputBuffer(msg); } void ProtocolGame::sendFightModes() { NetworkMessage msg; msg.addByte(0xA7); msg.addByte(player->fightMode); msg.addByte(player->chaseMode); msg.addByte(player->secureMode); msg.addByte(PVP_MODE_DOVE); writeToOutputBuffer(msg); } void ProtocolGame::sendMoveCreature(const Creature* creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport) { if (creature == player) { if (oldStackPos >= 10) { sendMapDescription(newPos); } else if (teleport) { NetworkMessage msg; RemoveTileThing(msg, oldPos, oldStackPos); writeToOutputBuffer(msg); sendMapDescription(newPos); } else { NetworkMessage msg; if (oldPos.z == 7 && newPos.z >= 8) { RemoveTileThing(msg, oldPos, oldStackPos); } else { msg.addByte(0x6D); msg.addPosition(oldPos); msg.addByte(oldStackPos); msg.addPosition(newPos); } if (newPos.z > oldPos.z) { MoveDownCreature(msg, creature, newPos, oldPos); } else if (newPos.z < oldPos.z) { MoveUpCreature(msg, creature, newPos, oldPos); } if (oldPos.y > newPos.y) { // north, for old x msg.addByte(0x65); GetMapDescription(oldPos.x - 8, newPos.y - 6, newPos.z, 18, 1, msg); } else if (oldPos.y < newPos.y) { // south, for old x msg.addByte(0x67); GetMapDescription(oldPos.x - 8, newPos.y + 7, newPos.z, 18, 1, msg); } if (oldPos.x < newPos.x) { // east, [with new y] msg.addByte(0x66); GetMapDescription(newPos.x + 9, newPos.y - 6, newPos.z, 1, 14, msg); } else if (oldPos.x > newPos.x) { // west, [with new y] msg.addByte(0x68); GetMapDescription(newPos.x - 8, newPos.y - 6, newPos.z, 1, 14, msg); } writeToOutputBuffer(msg); } } else if (canSee(oldPos) && canSee(creature->getPosition())) { if (teleport || (oldPos.z == 7 && newPos.z >= 8) || oldStackPos >= 10) { sendRemoveTileThing(oldPos, oldStackPos); sendAddCreature(creature, newPos, newStackPos, false); } else { NetworkMessage msg; msg.addByte(0x6D); msg.addPosition(oldPos); msg.addByte(oldStackPos); msg.addPosition(creature->getPosition()); writeToOutputBuffer(msg); } } else if (canSee(oldPos)) { sendRemoveTileThing(oldPos, oldStackPos); } else if (canSee(creature->getPosition())) { sendAddCreature(creature, newPos, newStackPos, false); } } void ProtocolGame::sendInventoryClientIds() { std::map<uint16_t, uint16_t> items = player->getInventoryClientIds(); NetworkMessage msg; msg.addByte(0xF5); msg.add<uint16_t>(items.size() + 11); for (uint16_t i = 1; i <= 11; i++) { msg.add<uint16_t>(i); msg.addByte(0x00); msg.add<uint16_t>(0x01); } for (const auto& it : items) { msg.add<uint16_t>(it.first); msg.addByte(0x00); msg.add<uint16_t>(it.second); } writeToOutputBuffer(msg); } void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item* item) { NetworkMessage msg; msg.addByte(0x70); msg.addByte(cid); msg.add<uint16_t>(slot); msg.addItem(item); writeToOutputBuffer(msg); } void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item* item) { NetworkMessage msg; msg.addByte(0x71); msg.addByte(cid); msg.add<uint16_t>(slot); msg.addItem(item); writeToOutputBuffer(msg); } void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item* lastItem) { NetworkMessage msg; msg.addByte(0x72); msg.addByte(cid); msg.add<uint16_t>(slot); if (lastItem) { msg.addItem(lastItem); } else { msg.add<uint16_t>(0x00); } writeToOutputBuffer(msg); } void ProtocolGame::sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite) { NetworkMessage msg; msg.addByte(0x96); msg.add<uint32_t>(windowTextId); msg.addItem(item); if (canWrite) { msg.add<uint16_t>(maxlen); msg.addString(item->getText()); } else { const std::string& text = item->getText(); msg.add<uint16_t>(text.size()); msg.addString(text); } const std::string& writer = item->getWriter(); if (!writer.empty()) { msg.addString(writer); } else { msg.add<uint16_t>(0x00); } time_t writtenDate = item->getDate(); if (writtenDate != 0) { msg.addString(formatDateShort(writtenDate)); } else { msg.add<uint16_t>(0x00); } writeToOutputBuffer(msg); } void ProtocolGame::sendTextWindow(uint32_t windowTextId, uint32_t itemId, const std::string& text) { NetworkMessage msg; msg.addByte(0x96); msg.add<uint32_t>(windowTextId); msg.addItem(itemId, 1); msg.add<uint16_t>(text.size()); msg.addString(text); msg.add<uint16_t>(0x00); msg.add<uint16_t>(0x00); writeToOutputBuffer(msg); } void ProtocolGame::sendHouseWindow(uint32_t windowTextId, const std::string& text) { NetworkMessage msg; msg.addByte(0x97); msg.addByte(0x00); msg.add<uint32_t>(windowTextId); msg.addString(text); writeToOutputBuffer(msg); } void ProtocolGame::sendOutfitWindow() { NetworkMessage msg; msg.addByte(0xC8); Outfit_t currentOutfit = player->getDefaultOutfit(); Mount* currentMount = g_game.mounts.getMountByID(player->getCurrentMount()); if (currentMount) { currentOutfit.lookMount = currentMount->clientId; } AddOutfit(msg, currentOutfit); std::vector<ProtocolOutfit> protocolOutfits; if (player->isAccessPlayer()) { static const std::string gamemasterOutfitName = "Gamemaster"; protocolOutfits.emplace_back( &gamemasterOutfitName, 75, 0 ); } const auto& outfits = Outfits::getInstance()->getOutfits(player->getSex()); protocolOutfits.reserve(outfits.size()); for (const Outfit& outfit : outfits) { uint8_t addons; if (!player->getOutfitAddons(outfit, addons)) { continue; } protocolOutfits.emplace_back( &outfit.name, outfit.lookType, addons ); if (protocolOutfits.size() == 150) { // Game client doesn't allow more than 50 outfits break; } } msg.addByte(protocolOutfits.size()); for (const ProtocolOutfit& outfit : protocolOutfits) { msg.add<uint16_t>(outfit.lookType); msg.addString(*outfit.name); msg.addByte(outfit.addons); } std::vector<const Mount*> mounts; for (const Mount& mount : g_game.mounts.getMounts()) { if (player->hasMount(&mount)) { mounts.push_back(&mount); } } msg.addByte(mounts.size()); for (const Mount* mount : mounts) { msg.add<uint16_t>(mount->clientId); msg.addString(mount->name); } writeToOutputBuffer(msg); } void ProtocolGame::sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus) { NetworkMessage msg; msg.addByte(0xD3); msg.add<uint32_t>(guid); msg.addByte(newStatus); writeToOutputBuffer(msg); } void ProtocolGame::sendSpellCooldown(uint8_t spellId, uint32_t time) { NetworkMessage msg; msg.addByte(0xA4); msg.addByte(spellId); msg.add<uint32_t>(time); writeToOutputBuffer(msg); } void ProtocolGame::sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) { NetworkMessage msg; msg.addByte(0xA5); msg.addByte(groupId); msg.add<uint32_t>(time); writeToOutputBuffer(msg); } void ProtocolGame::sendModalWindow(const ModalWindow& modalWindow) { NetworkMessage msg; msg.addByte(0xFA); msg.add<uint32_t>(modalWindow.id); msg.addString(modalWindow.title); msg.addString(modalWindow.message); msg.addByte(modalWindow.buttons.size()); for (const auto& it : modalWindow.buttons) { msg.addString(it.first); msg.addByte(it.second); } msg.addByte(modalWindow.choices.size()); for (const auto& it : modalWindow.choices) { msg.addString(it.first); msg.addByte(it.second); } msg.addByte(modalWindow.defaultEscapeButton); msg.addByte(modalWindow.defaultEnterButton); msg.addByte(modalWindow.priority ? 0x01 : 0x00); writeToOutputBuffer(msg); } ////////////// Add common messages void ProtocolGame::MoveUpCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos) { if (creature != player) { return; } //floor change up msg.addByte(0xBE); //going to surface if (newPos.z == 7) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 5, 18, 14, 3, skip); //(floor 7 and 6 already set) GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 4, 18, 14, 4, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 3, 18, 14, 5, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 2, 18, 14, 6, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 1, 18, 14, 7, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 0, 18, 14, 8, skip); if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } //underground, going one floor up (still underground) else if (newPos.z > 7) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, oldPos.getZ() - 3, 18, 14, 3, skip); if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } //moving up a floor up makes us out of sync //west msg.addByte(0x68); GetMapDescription(oldPos.x - 8, oldPos.y - 5, newPos.z, 1, 14, msg); //north msg.addByte(0x65); GetMapDescription(oldPos.x - 8, oldPos.y - 6, newPos.z, 18, 1, msg); } void ProtocolGame::MoveDownCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos) { if (creature != player) { return; } //floor change down msg.addByte(0xBF); //going from surface to underground if (newPos.z == 8) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z, 18, 14, -1, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 1, 18, 14, -2, skip); GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 2, 18, 14, -3, skip); if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } //going further down else if (newPos.z > oldPos.z && newPos.z > 8 && newPos.z < 14) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 2, 18, 14, -3, skip); if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } //moving down a floor makes us out of sync //east msg.addByte(0x66); GetMapDescription(oldPos.x + 9, oldPos.y - 7, newPos.z, 1, 14, msg); //south msg.addByte(0x67); GetMapDescription(oldPos.x - 8, oldPos.y + 7, newPos.z, 18, 1, msg); } void ProtocolGame::AddShopItem(NetworkMessage& msg, const ShopInfo& item) { const ItemType& it = Item::items[item.itemId]; msg.add<uint16_t>(it.clientId); if (it.isSplash() || it.isFluidContainer()) { msg.addByte(serverFluidToClient(item.subType)); } else { msg.addByte(0x00); } msg.addString(item.realName); msg.add<uint32_t>(it.weight); msg.add<uint32_t>(item.buyPrice); msg.add<uint32_t>(item.sellPrice); } void ProtocolGame::parseExtendedOpcode(NetworkMessage& msg) { uint8_t opcode = msg.getByte(); const std::string& buffer = msg.getString(); // process additional opcodes via lua script event addGameTask(&Game::parsePlayerExtendedOpcode, player->getID(), opcode, buffer); }
gpl-2.0
ianling/nespy
setup.py
530
from distutils.core import setup from Cython.Build import cythonize # python3 setup.py build_ext --inplace # cythonize -3 -a -i .\nespy\util.py .\nespy\cpu.py .\nespy\ppu.py .\nespy\clock.py .\nespy\nes.py .\nespy\apu.py .\nespy\enum.py setup(ext_modules=cythonize(['nespy/nes.py', 'nespy/apu.py', 'nespy/clock.py', 'nespy/cpu.py', 'nespy/ppu.py', 'nespy/enum.py', 'nespy/util.py', 'nespy/exceptions.py'], language_level='3', annotate=True))
gpl-2.0
ctag/cpe453
JMRI/jython/TurnoutReset.py
1105
# Reset a turnout to Closed every time it's clicked Thrown # # This might be used so that a turnout icon on a panel sits # in one position, ready to be clicked and fire a route # # The top of the file defines the needed code. There are some # lines near the bottom you should edit to adapt it to your # particular layout. # # Author: Bob Jacobsen, copyright 2005 # Part of the JMRI distribution # # The next line is maintained by CVS, please don't change it # $Revision: 27263 $ # First, define the listener. class MyListener(java.beans.PropertyChangeListener): def propertyChange(self, event): if ( event.propertyName == "KnownState" ) : if ( event.newValue == THROWN ) : turnouts.provideTurnout(event.source.systemName).setState(CLOSED) # Define a routine to make it easy to attach listeners def SetTurnoutToReset(name) : t = turnouts.provideTurnout(name) t.setState(CLOSED) t.addPropertyChangeListener(MyListener()) # Attach listeners to the desired turnouts # (Edit the following to apply to your layout) SetTurnoutToReset("14") SetTurnoutToReset("15")
gpl-2.0
jsampedro77/AccessTokenSecurityBundle
Util/TokenGenerator.php
1100
<?php namespace Nazka\AccessTokenSecurityBundle\Util; /** * Adapted from FOSUserBundle */ class TokenGenerator { private $useOpenSsl; public function __construct() { // determine whether to use OpenSSL if (defined('PHP_WINDOWS_VERSION_BUILD') && version_compare(PHP_VERSION, '5.3.4', '<')) { $this->useOpenSsl = false; } elseif (!function_exists('openssl_random_pseudo_bytes')) { $this->useOpenSsl = false; } else { $this->useOpenSsl = true; } } public function generateToken() { return rtrim(strtr(base64_encode($this->getRandomNumber()), '+/', '-_'), '='); } private function getRandomNumber() { $nbBytes = 32; // try OpenSSL if ($this->useOpenSsl) { $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); if (false !== $bytes && true === $strong) { return $bytes; } } return hash('sha256', uniqid(mt_rand(), true), true); } }
gpl-2.0
bsteph/FFLLogbook
tests/TestCase/Controller/GunmaintControllerTest.php
1210
<?php namespace App\Test\TestCase\Controller; use App\Controller\GunmaintController; use Cake\TestSuite\IntegrationTestCase; /** * App\Controller\GunmaintController Test Case */ class GunmaintControllerTest extends IntegrationTestCase { /** * Fixtures * * @var array */ public $fixtures = [ 'app.gunmaint' ]; /** * Test index method * * @return void */ public function testIndex() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test view method * * @return void */ public function testView() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test add method * * @return void */ public function testAdd() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test edit method * * @return void */ public function testEdit() { $this->markTestIncomplete('Not implemented yet.'); } /** * Test delete method * * @return void */ public function testDelete() { $this->markTestIncomplete('Not implemented yet.'); } }
gpl-2.0
grlf/eyedock
components/com_gpmaterial/js/search_box.js
2409
var SearchBox = new Class({ Implements: [Options, Events], options: { transition: 'quad:out', fps: 50, open_width: 315, open_color: '#e7c348', duration: 300, defaults: { width: 150, color: '#a5a5a5', border_color: '#2687ae', value: 'Search everything...' } }, initialize: function(container, options) { this.setOptions(options); this.container = document.id(container); this.input = this.container.getElement('input'); this.state = 'closed'; // open or closed this.morph = new Fx.Morph(this.input, { duration: this.options.duration, transition: this.options.transition, fps: this.options.fps, link: 'cancel' }); this.build_events(); this.quick_search = function(q){ this.input.fireEvent('focus'); this.input.value = q; this.input.fireEvent('keyup'); } }, build_events: function() { this.input.addEvents({ 'focus': function() { if(this.state == 'closed') { this.morph.start({ 'border-top-color': this.options.open_color, 'border-left-color': this.options.open_color, 'border-right-color': this.options.open_color, 'border-bottom-color': this.options.open_color, 'width': this.options.open_width, 'color': '#000000' }); this.input.set('value', ''); this.state = 'open'; } }.bind(this), 'blur': function() { if(this.input.get('value') == '' && this.state == 'open') { this.morph.start({ 'border-color': this.options.defaults.border_color, 'width': this.options.defaults.width, 'color': '#ffffff' }).chain(function() { this.input.set('value', this.options.defaults.value); this.morph.start({ 'color': this.options.defaults.color }); }.bind(this)); this.state = 'closed'; } }.bind(this), 'keyup': function() { this.fireEvent('keyup', this.input.get('value').trim()); }.bind(this) }); }, start_loader: function() { var input_position = this.input.getCoordinates(); this.loader = new Element('img', { src: '/components/com_eyedocksearch/img/loader_small.gif', styles: { 'position': 'absolute', 'top': input_position.top + 6, 'left': input_position.right - 22 } }).inject(document.body); }, end_loader: function() { this.loader.destroy(); } });
gpl-2.0
xtingray/tupi
src/shell/tupapplication.cpp
3925
/*************************************************************************** * Project TUPI: Magia 2D * * Project Contact: info@maefloresta.com * * Project Website: http://www.maefloresta.com * * Project Leader: Gustav Gonzalez <info@maefloresta.com> * * * * Developers: * * 2010: * * Gustavo Gonzalez / xtingray * * * * KTooN's versions: * * * * 2006: * * David Cuadrado * * Jorge Cuadrado * * 2003: * * Fernado Roldan * * Simena Dinas * * * * Copyright (C) 2010 Gustav Gonzalez - http://www.maefloresta.com * * License: * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "tupapplication.h" #include "tapplicationproperties.h" /** * Support Class for main.cpp * This class contains some of the basic methods required when Tupi is launched * @author David Cuadrado */ TupApplication::TupApplication(int &argc, char **argv) : TApplication(argc, argv) { setApplicationName("tupi"); } TupApplication::~TupApplication() { #ifdef K_DEBUG QString msg = "[Destroying ~TupApplication]"; #ifdef Q_OS_WIN qDebug() << msg; #else tDebug() << msg; #endif #endif } void TupApplication::createCache(const QString &cacheDir) { QDir cache(cacheDir); if (!cache.exists()) { #ifdef K_DEBUG QString msg = "Initializing repository: " + cacheDir; #ifdef Q_OS_WIN qWarning() << msg; #else tWarning() << msg; #endif #endif if (!cache.mkdir(cacheDir)) { #ifdef K_DEBUG QString msg = "TupApplication::createCache() - Fatal Error: Can't create project repository"; #ifdef Q_OS_WIN qDebug() << msg; #else tError() << msg; #endif #endif } } kAppProp->setCacheDir(cacheDir); }
gpl-2.0
rebase-helper/rebase-helper
rebasehelper/argument_parser.py
4142
# -*- coding: utf-8 -*- # # This tool helps you rebase your package to the latest version # Copyright (C) 2013-2019 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Authors: Petr Hráček <phracek@redhat.com> # Tomáš Hozza <thozza@redhat.com> # Nikola Forró <nforro@redhat.com> # František Nečas <fifinecas@seznam.cz> import argparse import sys from rebasehelper.exceptions import RebaseHelperError, ParseError class SilentArgumentParser(argparse.ArgumentParser): def __init__(self): super().__init__(add_help=False) def error(self, message): raise ParseError(message) class CustomHelpFormatter(argparse.HelpFormatter): def _expand_help(self, action): action.default = getattr(action, 'actual_default', None) if isinstance(action.default, list): default_str = ','.join(str(c) for c in action.default) action.default = default_str return super()._expand_help(action) class CustomAction(argparse.Action): def __init__(self, option_strings, switch=False, counter=False, append=False, actual_default=None, dest=None, default=None, nargs=None, const=None, required=False, type=None, # pylint: disable=redefined-builtin metavar=None, help=None, # pylint: disable=redefined-builtin choices=None): super().__init__( option_strings=option_strings, dest=dest, const=const, default=default, required=required, metavar=metavar, type=type, help=help, choices=choices) self.switch = switch self.counter = counter self.append = append self.nargs = 0 if self.switch or self.counter else 1 if self.append else nargs self.actual_default = actual_default def __call__(self, parser, namespace, values, option_string=None): if self.counter: value = getattr(namespace, self.dest, 0) + 1 elif self.append: value = getattr(namespace, self.dest, []) value.extend(values) elif self.switch: value = True else: value = values setattr(namespace, self.dest, value) class CustomArgumentParser(argparse.ArgumentParser): def _check_value(self, action, value): if isinstance(value, list): # converted value must be subset of the choices (if specified) empty = value == action.const if action.choices is not None and not empty and not set(value).issubset(action.choices): invalid = set(value).difference(action.choices) if len(invalid) == 1: tup = repr(invalid.pop()), ', '.join(map(repr, action.choices)) msg = 'invalid choice: %s (choose from %s)' % tup else: tup = ', '.join(map(repr, invalid)), ', '.join(map(repr, action.choices)) msg = 'invalid choices: %s (choose from %s)' % tup raise argparse.ArgumentError(action, msg) else: super()._check_value(action, value) def error(self, message): self.print_usage(sys.stderr) raise RebaseHelperError(message)
gpl-2.0
brianedsauer/wordpress-fieldmanager
tests/php/test-fieldmanager-term-meta.php
5593
<?php /** * Tests the Fieldmanager Term Meta * * @group util * @group term */ class Test_Fieldmanager_Term_Meta extends WP_UnitTestCase { public $current_user; public function setUp() { parent::setUp(); Fieldmanager_Field::$debug = true; $this->current_user = get_current_user_id(); wp_set_current_user( $this->factory->user->create( array( 'role' => 'administrator' ) ) ); $this->term = $this->factory->category->create_and_get( array( 'name' => rand_str() ) ); } public function tearDown() { if ( get_current_user_id() != $this->current_user ) { wp_delete_user( get_current_user_id() ); } wp_set_current_user( $this->current_user ); } /** * Set up the request environment values and save the data. * * @param Fieldmanager_Field $field * @param WP_Post $post * @param mixed $values */ public function save_values( $field, $term, $values ) { $field->add_term_form( $field->name, $term->taxonomy )->save_to_term_meta( $term->term_id, $term->taxonomy, $values ); } /** * Test behavior when using the term meta fields. */ public function test_save_term_meta() { $term_option = new Fieldmanager_Textfield( array( 'name' => 'term_option', ) ); // check normal save and fetch behavior $text = rand_str(); $this->save_values( $term_option, $this->term, $text ); $data = fm_get_term_meta( $this->term->term_id, $this->term->taxonomy, 'term_option', true ); $this->assertEquals( $text, $data ); $data = fm_get_term_meta( $this->term->term_id, $this->term->taxonomy, 'term_option', false ); $this->assertEquals( array( $text ), $data ); // check update and fetch $text_updated = rand_str(); $this->save_values( $term_option, $this->term, $text_updated ); $data = fm_get_term_meta( $this->term->term_id, $this->term->taxonomy, 'term_option', true ); $this->assertEquals( $text_updated, $data ); $this->assertInternalType( 'int', Fieldmanager_Util_Term_Meta()->get_term_meta_post_id( $this->term->term_id, $this->term->taxonomy ) ); $cache_key = Fieldmanager_Util_Term_Meta()->get_term_meta_post_id_cache_key( $this->term->term_id, $this->term->taxonomy ); $this->assertNotEquals( false, wp_cache_get( $cache_key ) ); fm_delete_term_meta( $this->term->term_id, $this->term->taxonomy, 'term_option' ); // post id not cached right after removal of only meta value, which results in deletion of the post $this->assertEquals( false, wp_cache_get( $cache_key ) ); // checking that the post id is reported as false when it doesn't exist now $this->assertEquals( false, Fieldmanager_Util_Term_Meta()->get_term_meta_post_id( $this->term->term_id, $this->term->taxonomy ) ); // checking that the post id is cached now to return false since it doesn't exist $this->assertNotEquals( false, wp_cache_get( $cache_key ) ); } public function test_garbage_collection() { $term_option = new Fieldmanager_Textfield( array( 'name' => 'term_option', ) ); // check normal save and fetch behavior $text = rand_str(); $this->save_values( $term_option, $this->term, $text ); $data = fm_get_term_meta( $this->term->term_id, $this->term->taxonomy, 'term_option', true ); $this->assertEquals( $text, $data ); // Verify the FM term post exists $post = get_page_by_path( "fm-term-meta-{$this->term->term_id}-category", OBJECT, 'fm-term-meta' ); $this->assertTrue( ! empty( $post->ID ) ); $this->assertEquals( 'fm-term-meta', $post->post_type ); $post_id = $post->ID; $this->assertEquals( $text, get_post_meta( $post_id, 'term_option', true ) ); // Delete the term wp_delete_term( $this->term->term_id, 'category' ); // The post and meta should be deleted $post = get_page_by_path( "fm-term-meta-{$this->term->term_id}-category", OBJECT, 'fm-term-meta' ); $this->assertEmpty( $post ); $this->assertEquals( '', get_post_meta( $post_id, 'term_option', true ) ); } /** * @group term_splitting */ public function test_term_splitting() { // Ensure that term splitting exists if ( ! function_exists( 'wp_get_split_terms' ) ) { return; } global $wpdb; // Add our first term. This is the one that will split off. $t1 = wp_insert_term( 'Joined Term', 'category' ); // Add term meta to the term $value = rand_str(); $term_id_1 = $t1['term_id']; fm_add_term_meta( $term_id_1, 'category', 'split_test', $value ); // Add a second term to a custom taxonomy register_taxonomy( 'fm_test_tax', 'post' ); $t2 = wp_insert_term( 'Second Joined Term', 'fm_test_tax' ); // Manually modify the second term to setup the term splitting // condition. Shared terms don't naturally occur any longer. $wpdb->update( $wpdb->term_taxonomy, array( 'term_id' => $term_id_1 ), array( 'term_taxonomy_id' => $t2['term_taxonomy_id'] ), array( '%d' ), array( '%d' ) ); // Verify that we can retrieve the term meta $this->assertEquals( $value, fm_get_term_meta( $term_id_1, 'category', 'split_test', true ) ); // Update the term to cause it to split $new_t1 = wp_update_term( $term_id_1, 'category', array( 'name' => 'Split Term', ) ); // Verify that the term updated and split $this->assertTrue( isset( $new_t1['term_id'] ) ); $this->assertNotEquals( $new_t1['term_id'], $term_id_1 ); // Verify that the term meta works at the new term id $this->assertEquals( $value, fm_get_term_meta( $new_t1['term_id'], 'category', 'split_test', true ) ); // Verify that we CANNOT access the term meta at the old term id $this->assertEquals( '', fm_get_term_meta( $term_id_1, 'category', 'split_test', true ) ); } }
gpl-2.0
GiuseppeGorgoglione/mame
src/devices/bus/cbmiec/c1541.cpp
37306
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Commodore 1540/1541/1541C/1541-II Single Disk Drive emulation **********************************************************************/ /* TODO: - c1540 fails to load the directory intermittently - hardware extensions - Dolphin-DOS 2.0 - Dolphin-DOS 3.0 - Professional-DOS - Prologic-DOS */ /* 1540/1541/1541A/SX-64 Parts Location Part Number Description 2016 2K x 8 bit Static RAM (short board) UA2-UB3 2114 (4) 1K x 4 bit Static RAM (long board) 325572-01 64H105 40 pin Gate Array (short board) 325302-01 2364-130 ROM DOS 2.6 C000-DFFF 325303-01 2364-131 ROM DOS 2.6 (1540) E000-FFFF 901229-01 2364-173 ROM DOS 2.6 rev. 0 E000-FFFF 901229-03 2364-197 ROM DOS 2.6 rev. 1 E000-FFFF 901229-05 8K ROM DOS 2.6 rev. 2 E000-FFFF 6502 CPU 6522 (2) VIA drive Alps DFB111M25A drive Alps FDM2111-B2 drive Newtronics D500 1541B/1541C Parts Location Part Number Description UA3 2016 2K x 8 bit Static RAM UC2 6502 CPU UC1, UC3 6522 (2) CIA UC4 251828-02 64H156 42 pin Gate Array UC5 251829-01 64H157 20 pin Gate Array UD1 * 251853-01 R/W Hybrid UD1 * 251853-02 R/W Hybrid UA2 251968-01 27128 EPROM DOS 2.6 rev. 3 C000-FFFF drive Newtronics D500 * Not interchangeable. 1541-II Parts Location Part Number Description U5 2016-15 2K x 8 bit Static RAM U12 SONY CX20185 R/W Amp. U3 6502A CPU U6, U8 6522 (2) CIA U10 251828-01 64H156 40 pin Gate Array U4 251968-03 16K ROM DOS 2.6 rev. 4 C000-FFFF drive Chinon FZ-501M REV A drive Digital System DS-50F drive Newtronics D500 drive Safronic DS-50F ... PCB Assy # 1540008-01 Schematic # 1540001 Original "Long" Board Has 4 discreet 2114 RAMs ALPS Drive only PCB Assy # 1540048 Schematic # 1540049 Referred to as the CR board Changed to 2048 x 8 bit RAM pkg. A 40 pin Gate Array is used Alps Drive (-01) Newtronics Drive (-03) PCB Assy # 250442-01 Schematic # 251748 Termed the 1541 A Just one jumper change to accommodate both types of drive PCB Assy # 250446-01 Schematic # 251748 (See Notes) Termed the 1541 A-2 Just one jumper change to accommodate both types of drive ... VIC1541 1540001-01 Very early version, long board. 1540001-03 As above, only the ROMs are different. 1540008-01 1541 1540048-01 Shorter board with a 40 pin gate array, Alps mech. 1540048-03 As above, but Newtronics mech. 1540049 Similar to above 1540050 Similar to above, Alps mechanism. SX64 250410-01 Design most similar to 1540048-01, Alps mechanism. 1541 251777 Function of bridge rects. reversed, Newtronics mech. 251830 Same as above 1541A 250442-01 Alps or Newtronics drive selected by a jumper. 1541A2 250446-01 A 74LS123 replaces the 9602 at UD4. 1541B 250448-01 Same as the 1541C, but in a case like the 1541. 1541C 250448-01 Short board, new 40/42 pin gate array, 20 pin gate array and a R/W hybrid chip replace many components. Uses a Newtronics drive with optical trk 0 sensor. 1541C 251854 As above, single DOS ROM IC, trk 0 sensor, 30 pin IC for R/W ampl & stepper motor control (like 1541). 1541-II A complete redesign using the 40 pin gate array from the 1451C and a Sony R/W hybrid, but not the 20 pin gate array, single DOS ROM IC. NOTE: These system boards are the 60 Hz versions. The -02 and -04 boards are probably the 50 Hz versions. The ROMs appear to be completely interchangeable. For instance, the first version of ROM for the 1541-II contained the same code as the last version of the 1541. I copy the last version of the 1541-II ROM into two 68764 EPROMs and use them in my original 1541 (long board). Not only do they work, but they work better than the originals. http://www.amiga-stuff.com/hardware/cbmboards.html */ #include "c1541.h" #include "bus/centronics/ctronics.h" //************************************************************************** // MACROS / CONSTANTS //************************************************************************** #define M6502_TAG "ucd5" #define M6522_0_TAG "uab1" #define M6522_1_TAG "ucd4" #define C64H156_TAG "uc4" #define C64H157_TAG "uc5" #define MC6821_TAG "pia" #define CENTRONICS_TAG "centronics" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** const device_type C1540 = &device_creator<c1540_t>; const device_type C1541 = &device_creator<c1541_t>; const device_type C1541C = &device_creator<c1541c_t>; const device_type C1541II = &device_creator<c1541ii_t>; const device_type SX1541 = &device_creator<sx1541_t>; const device_type FSD1 = &device_creator<fsd1_t>; const device_type FSD2 = &device_creator<fsd2_t>; const device_type CSD1 = &device_creator<csd1_t>; const device_type C1541_DOLPHIN_DOS = &device_creator<c1541_dolphin_dos_t>; const device_type C1541_PROFESSIONAL_DOS_V1 = &device_creator<c1541_professional_dos_v1_t>; const device_type C1541_PROLOGIC_DOS_CLASSIC = &device_creator<c1541_prologic_dos_classic_t>; const device_type INDUS_GT = &device_creator<indus_gt_t>; //------------------------------------------------- // ROM( c1540 ) //------------------------------------------------- ROM_START( c1540 ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_LOAD( "325302-01.uab4", 0x0000, 0x2000, CRC(29ae9752) SHA1(8e0547430135ba462525c224e76356bd3d430f11) ) ROM_LOAD( "325303-01.uab5", 0x2000, 0x2000, CRC(10b39158) SHA1(56dfe79b26f50af4e83fd9604857756d196516b9) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1540_t::device_rom_region() const { return ROM_NAME( c1540 ); } //------------------------------------------------- // ROM( c1541 ) //------------------------------------------------- ROM_START( c1541 ) ROM_REGION( 0x8000, M6502_TAG, 0 ) ROM_LOAD( "325302-01.uab4", 0x0000, 0x2000, CRC(29ae9752) SHA1(8e0547430135ba462525c224e76356bd3d430f11) ) ROM_DEFAULT_BIOS("r6") ROM_SYSTEM_BIOS( 0, "r1", "Revision 1" ) ROMX_LOAD( "901229-01.uab5", 0x2000, 0x2000, CRC(9a48d3f0) SHA1(7a1054c6156b51c25410caec0f609efb079d3a77), ROM_BIOS(1) ) ROM_SYSTEM_BIOS( 1, "r2", "Revision 2" ) ROMX_LOAD( "901229-02.uab5", 0x2000, 0x2000, CRC(b29bab75) SHA1(91321142e226168b1139c30c83896933f317d000), ROM_BIOS(2) ) ROM_SYSTEM_BIOS( 2, "r3", "Revision 3" ) ROMX_LOAD( "901229-03.uab5", 0x2000, 0x2000, CRC(9126e74a) SHA1(03d17bd745066f1ead801c5183ac1d3af7809744), ROM_BIOS(3) ) ROM_SYSTEM_BIOS( 3, "r4", "Revision 4" ) ROMX_LOAD( "901229-04.uab5", 0x2000, 0x2000, NO_DUMP, ROM_BIOS(4) ) ROM_SYSTEM_BIOS( 4, "r5", "Revision 5" ) ROMX_LOAD( "901229-05 ae.uab5", 0x2000, 0x2000, CRC(361c9f37) SHA1(f5d60777440829e46dc91285e662ba072acd2d8b), ROM_BIOS(5) ) ROM_SYSTEM_BIOS( 5, "r6", "Revision 6" ) ROMX_LOAD( "901229-06 aa.uab5", 0x2000, 0x2000, CRC(3a235039) SHA1(c7f94f4f51d6de4cdc21ecbb7e57bb209f0530c0), ROM_BIOS(6) ) ROM_SYSTEM_BIOS( 6, "jiffydos", "JiffyDOS v6.01" ) ROMX_LOAD( "jiffydos 1541.uab5", 0x2000, 0x2000, CRC(bc7e4aeb) SHA1(db6cfaa6d9b78d58746c811de29f3b1f44d99ddf), ROM_BIOS(7) ) ROM_SYSTEM_BIOS( 7, "speeddos", "SpeedDOS-Plus+" ) ROMX_LOAD( "speed-dosplus.uab5", 0x0000, 0x4000, CRC(f9db1eac) SHA1(95407e59a9c1d26a0e4bcf2c244cfe8942576e2c), ROM_BIOS(8) ) ROM_SYSTEM_BIOS( 8, "rolo27", "Rolo DOS v2.7" ) ROMX_LOAD( "rolo27.uab5", 0x0000, 0x2000, CRC(171c7962) SHA1(04c892c4b3d7c74750576521fa081f07d8ca8557), ROM_BIOS(9) ) ROM_SYSTEM_BIOS( 9, "tt34", "TurboTrans v3.4" ) ROMX_LOAD( "ttd34.uab5", 0x0000, 0x8000, CRC(518d34a1) SHA1(4d6ffdce6ab122e9627b0a839861687bcd4e03ec), ROM_BIOS(10) ) ROM_SYSTEM_BIOS( 10, "digidos", "DigiDOS" ) ROMX_LOAD( "digidos.uab5", 0x0000, 0x2000, CRC(b3f05ea3) SHA1(99d3d848344c68410b686cda812f3788b41fead3), ROM_BIOS(11) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541_t::device_rom_region() const { return ROM_NAME( c1541 ); } //------------------------------------------------- // ROM( c1541c ) //------------------------------------------------- ROM_START( c1541c ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_DEFAULT_BIOS("r2") ROM_SYSTEM_BIOS( 0, "r1", "Revision 1" ) ROMX_LOAD( "251968-01.ua2", 0x0000, 0x4000, CRC(1b3ca08d) SHA1(8e893932de8cce244117fcea4c46b7c39c6a7765), ROM_BIOS(1) ) ROM_SYSTEM_BIOS( 1, "r2", "Revision 2" ) ROMX_LOAD( "251968-02.ua2", 0x0000, 0x4000, CRC(2d862d20) SHA1(38a7a489c7bbc8661cf63476bf1eb07b38b1c704), ROM_BIOS(2) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541c_t::device_rom_region() const { return ROM_NAME( c1541c ); } //------------------------------------------------- // ROM( c1541ii ) //------------------------------------------------- ROM_START( c1541ii ) ROM_REGION( 0x8000, M6502_TAG, 0 ) ROM_LOAD( "251968-03.u4", 0x0000, 0x4000, CRC(899fa3c5) SHA1(d3b78c3dbac55f5199f33f3fe0036439811f7fb3) ) ROM_DEFAULT_BIOS("r1") ROM_SYSTEM_BIOS( 0, "r1", "Revision 1" ) ROMX_LOAD( "355640-01.u4", 0x0000, 0x4000, CRC(57224cde) SHA1(ab16f56989b27d89babe5f89c5a8cb3da71a82f0), ROM_BIOS(1) ) ROM_SYSTEM_BIOS( 1, "jiffydos", "JiffyDOS v6.01" ) ROMX_LOAD( "jiffydos 1541-ii.u4", 0x0000, 0x4000, CRC(dd409902) SHA1(b1a5b826304d3df2a27d7163c6a81a532e040d32), ROM_BIOS(2) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541ii_t::device_rom_region() const { return ROM_NAME( c1541ii ); } //------------------------------------------------- // ROM( sx1541 ) //------------------------------------------------- ROM_START( sx1541 ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_LOAD( "325302-01.uab4", 0x0000, 0x2000, CRC(29ae9752) SHA1(8e0547430135ba462525c224e76356bd3d430f11) ) ROM_DEFAULT_BIOS("r5") ROM_SYSTEM_BIOS( 0, "r5", "Revision 5" ) ROMX_LOAD( "901229-05 ae.uab5", 0x2000, 0x2000, CRC(361c9f37) SHA1(f5d60777440829e46dc91285e662ba072acd2d8b), ROM_BIOS(1) ) ROM_SYSTEM_BIOS( 1, "jiffydos", "JiffyDOS v6.01" ) ROMX_LOAD( "jiffydos sx1541", 0x0000, 0x4000, CRC(783575f6) SHA1(36ccb9ff60328c4460b68522443ecdb7f002a234), ROM_BIOS(2) ) ROM_SYSTEM_BIOS( 2, "flash", "1541 FLASH!" ) ROMX_LOAD( "1541 flash.uab5", 0x2000, 0x2000, CRC(22f7757e) SHA1(86a1e43d3d22b35677064cca400a6bd06767a3dc), ROM_BIOS(3) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *sx1541_t::device_rom_region() const { return ROM_NAME( sx1541 ); } //------------------------------------------------- // ROM( fsd1 ) //------------------------------------------------- ROM_START( fsd1 ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_LOAD( "fsd1.bin", 0x0000, 0x4000, CRC(57224cde) SHA1(ab16f56989b27d89babe5f89c5a8cb3da71a82f0) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *fsd1_t::device_rom_region() const { return ROM_NAME( fsd1 ); } //------------------------------------------------- // ROM( fsd2 ) //------------------------------------------------- ROM_START( fsd2 ) ROM_REGION( 0x4000, M6502_TAG, 0 ) // data lines D3 and D4 are swapped ROM_DEFAULT_BIOS("fsd2") ROM_SYSTEM_BIOS( 0, "ra", "Revision A" ) ROMX_LOAD( "fsd2a.u3", 0x0000, 0x4000, CRC(edf18265) SHA1(47a7c4bdcc20ecc5e59d694b151f493229becaea), ROM_BIOS(1) ) ROM_SYSTEM_BIOS( 1, "rb", "Revision B" ) ROMX_LOAD( "fsd2b.u3", 0x0000, 0x4000, CRC(b39e4600) SHA1(991132fcc6e70e9a428062ae76055a150f2f7ac6), ROM_BIOS(2) ) ROM_SYSTEM_BIOS( 2, "jiffydos", "JiffyDOS v5.0" ) ROMX_LOAD( "jiffydos v5.0.u3", 0x0000, 0x4000, CRC(46c3302c) SHA1(e3623658cb7af30c9d3bce2ba3b6ad5ee89ac1b8), ROM_BIOS(3) ) ROM_SYSTEM_BIOS( 3, "rexdos", "REX-DOS" ) ROMX_LOAD( "rdos.bin", 0x0000, 0x4000, CRC(8ad6dba1) SHA1(f279d327d5e16ea1b62fb18514fb679d0b442941), ROM_BIOS(4) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *fsd2_t::device_rom_region() const { return ROM_NAME( fsd2 ); } //------------------------------------------------- // ROM( csd1 ) //------------------------------------------------- ROM_START( csd1 ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_LOAD( "ic14", 0x0000, 0x2000, CRC(adb6980e) SHA1(13051587dfe43b04ce1bf354b89438ddf6d8d76b) ) ROM_LOAD( "ic15", 0x2000, 0x2000, CRC(b0cecfa1) SHA1(c67e79a7ffefc9e9eafc238cb6ff6bb718f19afb) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *csd1_t::device_rom_region() const { return ROM_NAME( csd1 ); } //------------------------------------------------- // ROM( c1541dd ) //------------------------------------------------- ROM_START( c1541dd ) ROM_REGION( 0x8000, M6502_TAG, 0 ) ROM_LOAD( "dd20.bin", 0x0000, 0x8000, CRC(94c7fe19) SHA1(e4d5b9ad6b719dd988276214aa4536d3525d313c) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541_dolphin_dos_t::device_rom_region() const { return ROM_NAME( c1541dd ); } //------------------------------------------------- // ROM( c1541pd ) //------------------------------------------------- ROM_START( c1541pd ) ROM_REGION( 0x6000, M6502_TAG, 0 ) ROM_LOAD( "325302-01.uab4", 0x0000, 0x2000, CRC(29ae9752) SHA1(8e0547430135ba462525c224e76356bd3d430f11) ) ROM_LOAD( "professionaldos-v1-floppy-expansion-eprom-27128.bin", 0x2000, 0x4000, CRC(c9abf072) SHA1(2b26adc1f4192b6ca1514754f73c929087b24426) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541_professional_dos_v1_t::device_rom_region() const { return ROM_NAME( c1541pd ); } //------------------------------------------------- // ROM( c1541pdc ) //------------------------------------------------- ROM_START( c1541pdc ) ROM_REGION( 0x8000, M6502_TAG, 0 ) ROM_LOAD( "325302-01.uab4", 0x0000, 0x2000, CRC(29ae9752) SHA1(8e0547430135ba462525c224e76356bd3d430f11) ) ROM_LOAD( "901229-06 aa.uab5", 0x2000, 0x2000, CRC(3a235039) SHA1(c7f94f4f51d6de4cdc21ecbb7e57bb209f0530c0) ) ROM_LOAD( "kernal.bin", 0x4000, 0x4000, CRC(79032ed5) SHA1(0ca4d5ef41c7e3d18d8945476d1481573af3e27c) ) ROM_REGION( 0x2000, "mmu", 0 ) ROM_LOAD( "mmu.bin", 0x0000, 0x2000, CRC(4c41392c) SHA1(78846af2ee6a56fceee44f9246659685ab2cbb7e) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *c1541_prologic_dos_classic_t::device_rom_region() const { return ROM_NAME( c1541pdc ); } //------------------------------------------------- // ROM( indusgt ) //------------------------------------------------- ROM_START( indusgt ) ROM_REGION( 0x4000, M6502_TAG, 0 ) ROM_LOAD( "u18 v1.1.u18", 0x0000, 0x2000, CRC(e401ce56) SHA1(9878053bdff7a036f57285c2c4974459df2602d8) ) ROM_LOAD( "u17 v1.1.u17", 0x2000, 0x2000, CRC(575ad906) SHA1(f48837b024add84f888acd83a9cf9eb7d2379172) ) ROM_REGION( 0x2000, "romdisk", 0 ) ROM_LOAD( "u19 v1.1.u19", 0x0000, 0x2000, CRC(8f83e7a5) SHA1(5bceaad520dac9d0527723b3b454e8ec99748e5b) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *indus_gt_t::device_rom_region() const { return ROM_NAME( indusgt ); } //------------------------------------------------- // read - //------------------------------------------------- READ8_MEMBER( c1541_prologic_dos_classic_t::read ) { return 0; } //------------------------------------------------- // write - //------------------------------------------------- WRITE8_MEMBER( c1541_prologic_dos_classic_t::write ) { } //------------------------------------------------- // ADDRESS_MAP( c1541_mem ) //------------------------------------------------- static ADDRESS_MAP_START( c1541_mem, AS_PROGRAM, 8, c1541_base_t ) AM_RANGE(0x0000, 0x07ff) AM_MIRROR(0x6000) AM_RAM AM_RANGE(0x1800, 0x180f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_0_TAG, via6522_device, read, write) AM_RANGE(0x1c00, 0x1c0f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_1_TAG, via6522_device, read, write) AM_RANGE(0x8000, 0xbfff) AM_MIRROR(0x4000) AM_ROM AM_REGION(M6502_TAG, 0) ADDRESS_MAP_END //------------------------------------------------- // ADDRESS_MAP( c1541dd_mem ) //------------------------------------------------- static ADDRESS_MAP_START( c1541dd_mem, AS_PROGRAM, 8, c1541_base_t ) AM_RANGE(0x0000, 0x07ff) AM_MIRROR(0x6000) AM_RAM AM_RANGE(0x1800, 0x180f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_0_TAG, via6522_device, read, write) AM_RANGE(0x1c00, 0x1c0f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_1_TAG, via6522_device, read, write) AM_RANGE(0x8000, 0x9fff) AM_RAM AM_RANGE(0xa000, 0xffff) AM_ROM AM_REGION(M6502_TAG, 0x2000) ADDRESS_MAP_END //------------------------------------------------- // ADDRESS_MAP( c1541pd_mem ) //------------------------------------------------- static ADDRESS_MAP_START( c1541pd_mem, AS_PROGRAM, 8, c1541_base_t ) AM_RANGE(0x0000, 0x07ff) AM_MIRROR(0x6000) AM_RAM AM_RANGE(0x1800, 0x180f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_0_TAG, via6522_device, read, write) AM_RANGE(0x1c00, 0x1c0f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_1_TAG, via6522_device, read, write) AM_RANGE(0x8000, 0x9fff) AM_ROM AM_REGION(M6502_TAG, 0x4000) AM_RANGE(0xa000, 0xbfff) AM_RAM AM_RANGE(0xc000, 0xffff) AM_ROM AM_REGION(M6502_TAG, 0x0000) AM_RANGE(0xe000, 0xffff) AM_ROM AM_REGION(M6502_TAG, 0x2000) ADDRESS_MAP_END //------------------------------------------------- // ADDRESS_MAP( c1541pdc_mem ) //------------------------------------------------- static ADDRESS_MAP_START( c1541pdc_mem, AS_PROGRAM, 8, c1541_prologic_dos_classic_t ) AM_RANGE(0x0000, 0xffff) AM_READWRITE(read, write) /* AM_RANGE(0x0000, 0x07ff) AM_MIRROR(0x6000) AM_RAM AM_SHARE("share1") AM_RANGE(0x1800, 0x180f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_0_TAG, via6522_device, read, write) AM_RANGE(0x1c00, 0x1c0f) AM_MIRROR(0x63f0) AM_DEVREADWRITE(M6522_1_TAG, via6522_device, read, write) AM_RANGE(0x8000, 0x87ff) AM_RAM AM_SHARE("share1") AM_RANGE(0x8800, 0x9fff) AM_RAM AM_RANGE(0xa000, 0xb7ff) AM_ROM AM_REGION(M6502_TAG, 0x0000) AM_RANGE(0xb800, 0xb80f) AM_READWRITE(pia_r, pia_w) AM_RANGE(0xf000, 0xffff) AM_ROM AM_REGION(M6502_TAG, 0x2000)*/ ADDRESS_MAP_END WRITE_LINE_MEMBER( c1541_base_t::via0_irq_w ) { m_via0_irq = state; m_maincpu->set_input_line(INPUT_LINE_IRQ0, (m_via0_irq || m_via1_irq) ? ASSERT_LINE : CLEAR_LINE); } READ8_MEMBER( c1541_base_t::via0_pa_r ) { // dummy read to acknowledge ATN IN interrupt return m_parallel_data; } WRITE8_MEMBER( c1541_base_t::via0_pa_w ) { if (m_other != nullptr) { m_other->parallel_data_w(data); } } READ8_MEMBER( c1541_base_t::via0_pb_r ) { /* bit description PB0 DATA IN PB1 PB2 CLK IN PB3 PB4 PB5 J1 PB6 J2 PB7 ATN IN */ UINT8 data; // data in data = !m_bus->data_r() && !m_ga->atn_r(); // clock in data |= !m_bus->clk_r() << 2; // serial bus address data |= ((m_slot->get_address() - 8) & 0x03) << 5; // attention in data |= !m_bus->atn_r() << 7; return data; } WRITE8_MEMBER( c1541_base_t::via0_pb_w ) { /* bit description PB0 PB1 DATA OUT PB2 PB3 CLK OUT PB4 ATNA PB5 PB6 PB7 */ // data out m_data_out = BIT(data, 1); // attention acknowledge m_ga->atna_w(BIT(data, 4)); // clock out m_bus->clk_w(this, !BIT(data, 3)); } WRITE_LINE_MEMBER( c1541_base_t::via0_ca2_w ) { if (m_other != nullptr) { m_other->parallel_strobe_w(state); } } READ8_MEMBER( c1541c_t::via0_pa_r ) { /* bit description PA0 TR00 SENCE PA1 PA2 PA3 PA4 PA5 PA6 PA7 */ return !m_floppy->trk00_r(); } WRITE_LINE_MEMBER( c1541_base_t::via1_irq_w ) { m_via1_irq = state; m_maincpu->set_input_line(INPUT_LINE_IRQ0, (m_via0_irq || m_via1_irq) ? ASSERT_LINE : CLEAR_LINE); } READ8_MEMBER( c1541_base_t::via1_pb_r ) { /* bit signal description PB0 PB1 PB2 PB3 PB4 WPS write protect sense PB5 PB6 PB7 SYNC SYNC detect line */ UINT8 data = 0; // write protect sense data |= !m_floppy->wpt_r() << 4; // SYNC detect line data |= m_ga->sync_r() << 7; return data; } WRITE8_MEMBER( c1541_base_t::via1_pb_w ) { /* bit signal description PB0 STP0 stepping motor bit 0 PB1 STP1 stepping motor bit 1 PB2 MTR motor ON/OFF PB3 ACT drive 0 LED PB4 PB5 DS0 density select 0 PB6 DS1 density select 1 PB7 SYNC SYNC detect line */ // spindle motor m_ga->mtr_w(BIT(data, 2)); // stepper motor m_ga->stp_w(data & 0x03); // activity LED machine().output().set_led_value(LED_ACT, BIT(data, 3)); // density select m_ga->ds_w((data >> 5) & 0x03); } //------------------------------------------------- // C64H156_INTERFACE( ga_intf ) //------------------------------------------------- WRITE_LINE_MEMBER( c1541_base_t::atn_w ) { set_iec_data(); } WRITE_LINE_MEMBER( c1541_base_t::byte_w ) { m_maincpu->set_input_line(M6502_SET_OVERFLOW, state); m_via1->write_ca1(state); } //------------------------------------------------- // SLOT_INTERFACE( c1540_floppies ) //------------------------------------------------- static SLOT_INTERFACE_START( c1540_floppies ) SLOT_INTERFACE( "525ssqd", ALPS_3255190x ) SLOT_INTERFACE_END //------------------------------------------------- // FLOPPY_FORMATS( floppy_formats ) //------------------------------------------------- FLOPPY_FORMATS_MEMBER( c1541_base_t::floppy_formats ) FLOPPY_D64_FORMAT, FLOPPY_G64_FORMAT FLOPPY_FORMATS_END READ8_MEMBER( c1541_prologic_dos_classic_t::pia_r ) { return m_pia->read(space, (offset >> 2) & 0x03); } WRITE8_MEMBER( c1541_prologic_dos_classic_t::pia_w ) { m_pia->write(space, (offset >> 2) & 0x03, data); } WRITE8_MEMBER( c1541_prologic_dos_classic_t::pia_pa_w ) { /* bit description 0 1/2 MHz 1 2 3 35/40 tracks 4 5 6 7 Hi */ } READ8_MEMBER( c1541_prologic_dos_classic_t::pia_pb_r ) { return m_parallel_data; } WRITE8_MEMBER( c1541_prologic_dos_classic_t::pia_pb_w ) { m_parallel_data = data; m_cent_data_out->write(space, 0, data); } //------------------------------------------------- // MACHINE_DRIVER( c1541 ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( c1541 ) MCFG_CPU_ADD(M6502_TAG, M6502, XTAL_16MHz/16) MCFG_CPU_PROGRAM_MAP(c1541_mem) MCFG_QUANTUM_PERFECT_CPU(M6502_TAG) MCFG_DEVICE_ADD(M6522_0_TAG, VIA6522, XTAL_16MHz/16) MCFG_VIA6522_READPA_HANDLER(READ8(c1541_base_t, via0_pa_r)) MCFG_VIA6522_READPB_HANDLER(READ8(c1541_base_t, via0_pb_r)) MCFG_VIA6522_WRITEPA_HANDLER(WRITE8(c1541_base_t, via0_pa_w)) MCFG_VIA6522_WRITEPB_HANDLER(WRITE8(c1541_base_t, via0_pb_w)) MCFG_VIA6522_CB2_HANDLER(WRITELINE(c1541_base_t, via0_ca2_w)) MCFG_VIA6522_IRQ_HANDLER(WRITELINE(c1541_base_t, via0_irq_w)) MCFG_DEVICE_ADD(M6522_1_TAG, VIA6522, XTAL_16MHz/16) MCFG_VIA6522_READPA_HANDLER(DEVREAD8(C64H156_TAG, c64h156_device, yb_r)) MCFG_VIA6522_READPB_HANDLER(READ8(c1541_base_t, via1_pb_r)) MCFG_VIA6522_WRITEPA_HANDLER(DEVWRITE8(C64H156_TAG, c64h156_device, yb_w)) MCFG_VIA6522_WRITEPB_HANDLER(WRITE8(c1541_base_t, via1_pb_w)) MCFG_VIA6522_CA2_HANDLER(DEVWRITELINE(C64H156_TAG, c64h156_device, soe_w)) MCFG_VIA6522_CB2_HANDLER(DEVWRITELINE(C64H156_TAG, c64h156_device, oe_w)) MCFG_VIA6522_IRQ_HANDLER(WRITELINE(c1541_base_t, via1_irq_w)) MCFG_DEVICE_ADD(C64H156_TAG, C64H156, XTAL_16MHz) MCFG_64H156_ATN_CALLBACK(WRITELINE(c1541_base_t, atn_w)) MCFG_64H156_BYTE_CALLBACK(WRITELINE(c1541_base_t, byte_w)) MCFG_FLOPPY_DRIVE_ADD(C64H156_TAG":0", c1540_floppies, "525ssqd", c1541_base_t::floppy_formats) MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor c1541_base_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( c1541 ); } //------------------------------------------------- // MACHINE_DRIVER( c1541c ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( c1541c ) MCFG_FRAGMENT_ADD(c1541) MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor c1541c_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( c1541c ); } //------------------------------------------------- // MACHINE_DRIVER( c1541dd ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( c1541dd ) MCFG_FRAGMENT_ADD(c1541) MCFG_CPU_MODIFY(M6502_TAG) MCFG_CPU_PROGRAM_MAP(c1541dd_mem) MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor c1541_dolphin_dos_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( c1541dd ); } //------------------------------------------------- // MACHINE_DRIVER( c1541pd ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( c1541pd ) MCFG_FRAGMENT_ADD(c1541) MCFG_CPU_MODIFY(M6502_TAG) MCFG_CPU_PROGRAM_MAP(c1541pd_mem) MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor c1541_professional_dos_v1_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( c1541pd ); } //------------------------------------------------- // MACHINE_DRIVER( c1541pdc ) //------------------------------------------------- static MACHINE_CONFIG_FRAGMENT( c1541pdc ) MCFG_FRAGMENT_ADD(c1541) MCFG_CPU_MODIFY(M6502_TAG) MCFG_CPU_PROGRAM_MAP(c1541pdc_mem) MCFG_DEVICE_ADD(MC6821_TAG, PIA6821, 0) MCFG_PIA_READPB_HANDLER(READ8(c1541_prologic_dos_classic_t, pia_pb_r)) MCFG_PIA_WRITEPA_HANDLER(WRITE8(c1541_prologic_dos_classic_t, pia_pa_w)) MCFG_PIA_WRITEPB_HANDLER(WRITE8(c1541_prologic_dos_classic_t, pia_pb_w)) MCFG_PIA_CA2_HANDLER(DEVWRITELINE(CENTRONICS_TAG, centronics_device, write_strobe)) MCFG_CENTRONICS_ADD(CENTRONICS_TAG, centronics_devices, "printer") MCFG_CENTRONICS_ACK_HANDLER(DEVWRITELINE(MC6821_TAG, pia6821_device, ca1_w)) MCFG_CENTRONICS_OUTPUT_LATCH_ADD("cent_data_out", "centronics") MACHINE_CONFIG_END //------------------------------------------------- // machine_config_additions - device-specific // machine configurations //------------------------------------------------- machine_config_constructor c1541_prologic_dos_classic_t::device_mconfig_additions() const { return MACHINE_CONFIG_NAME( c1541pdc ); } //------------------------------------------------- // INPUT_PORTS( c1541 ) //------------------------------------------------- static INPUT_PORTS_START( c1541 ) PORT_START("ADDRESS") PORT_DIPNAME( 0x03, 0x00, "Device Address" ) PORT_DIPSETTING( 0x00, "8" ) PORT_DIPSETTING( 0x01, "9" ) PORT_DIPSETTING( 0x02, "10" ) PORT_DIPSETTING( 0x03, "11" ) INPUT_PORTS_END //------------------------------------------------- // input_ports - device-specific input ports //------------------------------------------------- ioport_constructor c1541_base_t::device_input_ports() const { return INPUT_PORTS_NAME( c1541 ); } //************************************************************************** // INLINE HELPERS //************************************************************************** //------------------------------------------------- // set_iec_data - //------------------------------------------------- inline void c1541_base_t::set_iec_data() { int data = !m_data_out && !m_ga->atn_r(); m_bus->data_w(this, data); } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // c1541_base_t - constructor //------------------------------------------------- c1541_base_t:: c1541_base_t(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source) : device_t(mconfig, type, name, tag, owner, clock, shortname, source), device_cbm_iec_interface(mconfig, *this), device_c64_floppy_parallel_interface(mconfig, *this), m_maincpu(*this, M6502_TAG), m_via0(*this, M6522_0_TAG), m_via1(*this, M6522_1_TAG), m_ga(*this, C64H156_TAG), m_floppy(*this, C64H156_TAG":0:525ssqd"), m_address(*this, "ADDRESS"), m_data_out(1), m_via0_irq(CLEAR_LINE), m_via1_irq(CLEAR_LINE) { } //------------------------------------------------- // c1540_t - constructor //------------------------------------------------- c1540_t::c1540_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1540, "C1540", tag, owner, clock, "c1540", __FILE__) { } //------------------------------------------------- // c1541_t - constructor //------------------------------------------------- c1541_t::c1541_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541, "C1541", tag, owner, clock, "c1541", __FILE__) { } //------------------------------------------------- // c1541c_t - constructor //------------------------------------------------- c1541c_t::c1541c_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541C, "C1541C", tag, owner, clock, "c1541c", __FILE__) { } //------------------------------------------------- // c1541ii_t - constructor //------------------------------------------------- c1541ii_t::c1541ii_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541II, "C1541-II", tag, owner, clock, "c1541ii", __FILE__) { } //------------------------------------------------- // sx1541_t - constructor //------------------------------------------------- sx1541_t::sx1541_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, SX1541, "SX1541", tag, owner, clock, "sx1541", __FILE__) { } //------------------------------------------------- // fsd1_t - constructor //------------------------------------------------- fsd1_t::fsd1_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, FSD1, "FSD-1", tag, owner, clock, "fsd1", __FILE__) { } //------------------------------------------------- // fsd2_t - constructor //------------------------------------------------- fsd2_t::fsd2_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, FSD2, "FSD-2", tag, owner, clock, "fsd2", __FILE__) { } //------------------------------------------------- // csd1_t - constructor //------------------------------------------------- csd1_t::csd1_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, CSD1, "CSD-1", tag, owner, clock, "csd1", __FILE__) { } //------------------------------------------------- // c1541_dolphin_dos_t - constructor //------------------------------------------------- c1541_dolphin_dos_t::c1541_dolphin_dos_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541_DOLPHIN_DOS, "C1541 Dolphin-DOS 2.0", tag, owner, clock, "c1541dd", __FILE__) { } //------------------------------------------------- // c1541_professional_dos_v1_t - constructor //------------------------------------------------- c1541_professional_dos_v1_t::c1541_professional_dos_v1_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541_PROFESSIONAL_DOS_V1, "C1541 Professional-DOS v1", tag, owner, clock, "c1541pd", __FILE__) { } //------------------------------------------------- // c1541_prologic_dos_classic_t - constructor //------------------------------------------------- c1541_prologic_dos_classic_t::c1541_prologic_dos_classic_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, C1541_PROLOGIC_DOS_CLASSIC, "C1541 ProLogic-DOS Classic", tag, owner, clock, "c1541pdc", __FILE__), m_pia(*this, MC6821_TAG), m_cent_data_out(*this, "cent_data_out"), m_mmu_rom(*this, "mmu") { } //------------------------------------------------- // indus_gt_t - constructor //------------------------------------------------- indus_gt_t::indus_gt_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : c1541_base_t(mconfig, INDUS_GT, "Indus GT", tag, owner, clock, "indusgt", __FILE__) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void c1541_base_t::device_start() { // install image callbacks m_ga->set_floppy(m_floppy); // register for state saving save_item(NAME(m_data_out)); save_item(NAME(m_via0_irq)); save_item(NAME(m_via1_irq)); } void fsd2_t::device_start() { c1541_base_t::device_start(); // decrypt ROM UINT8 *rom = memregion(M6502_TAG)->base(); for (offs_t offset = 0; offset < 0x4000; offset++) { UINT8 data = BITSWAP8(rom[offset], 7, 6, 5, 3, 4, 2, 1, 0); rom[offset] = data; } } //------------------------------------------------- // device_reset - device-specific reset //------------------------------------------------- void c1541_base_t::device_reset() { m_maincpu->reset(); m_via0->reset(); m_via1->reset(); // initialize gate array m_ga->accl_w(0); m_ga->ted_w(1); } //------------------------------------------------- // iec_atn_w - //------------------------------------------------- void c1541_base_t::cbm_iec_atn(int state) { m_via0->write_ca1(!state); m_ga->atni_w(!state); set_iec_data(); } //------------------------------------------------- // iec_reset_w - //------------------------------------------------- void c1541_base_t::cbm_iec_reset(int state) { if (!state) { device_reset(); } } //------------------------------------------------- // parallel_data_w - //------------------------------------------------- void c1541_base_t::parallel_data_w(UINT8 data) { m_parallel_data = data; } //------------------------------------------------- // parallel_strobe_w - //------------------------------------------------- void c1541_base_t::parallel_strobe_w(int state) { m_via0->write_cb1(state); }
gpl-2.0
no-reply/cbpl-vufind
module/VuFind/src/VuFind/Theme/Root/Helper/Record.php
12557
<?php /** * Record driver view helper * * PHP version 5 * * Copyright (C) Villanova University 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @category VuFind2 * @package View_Helpers * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/building_a_recommendations_module Wiki */ namespace VuFind\Theme\Root\Helper; use VuFind\Config\Reader as ConfigReader, Zend\View\Exception\RuntimeException, Zend\View\Helper\AbstractHelper; /** * Record driver view helper * * @category VuFind2 * @package View_Helpers * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org/wiki/building_a_recommendations_module Wiki */ class Record extends AbstractHelper { protected $contextHelper; protected $driver; /** * Render a template within a record driver folder. * * @param string $name Template name to render * @param array $context Variables needed for rendering template; these will * be temporarily added to the global view context, then reverted after the * template is rendered (default = record driver only). * * @return string */ protected function renderTemplate($name, $context = null) { // Set default context if none provided: if (is_null($context)) { $context = array('driver' => $this->driver); } // Set up the needed context in the view: $oldContext = $this->contextHelper->apply($context); // Get the current record driver's class name, then start a loop // in case we need to use a parent class' name to find the appropriate // template. $className = get_class($this->driver); while (true) { // Guess the template name for the current class: $classParts = explode('\\', $className); $template = 'RecordDriver/' . array_pop($classParts) . '/' . $name; try { // Try to render the template.... $html = $this->view->render($template); $this->contextHelper->restore($oldContext); return $html; } catch (RuntimeException $e) { // If the template doesn't exist, let's see if we can inherit a // template from a parent class: $className = get_parent_class($className); if (empty($className)) { // No more parent classes left to try? Throw an exception! throw new RuntimeException( 'Cannot find ' . $name . ' template for record driver: ' . get_class($this->driver) ); } } } } /** * Store a record driver object and return this object so that the appropriate * template can be rendered. * * @param \VuFind\RecordDriver\AbstractBase $driver Record driver object. * * @return \VuFind\Theme\Root\Helper\Record */ public function __invoke($driver) { // Set up context helper: $contextHelper = $this->getView()->plugin('context'); $this->contextHelper = $contextHelper($this->getView()); // Set up driver context: $this->driver = $driver; return $this; } /** * Render the core metadata area of the record view. * * @return string */ public function getCoreMetadata() { return $this->renderTemplate('core.phtml'); } /** * Export the record in the requested format. For legal values, see * getExportFormats(). * * @param string $format Export format to display * * @return string Exported data */ public function getExport($format) { $format = strtolower($format); return $this->renderTemplate('export-' . $format . '.phtml'); } /** * Get an array of strings representing formats in which this record's * data may be exported (empty if none). Legal values: "RefWorks", * "EndNote", "MARC", "RDF". * * @return array Strings representing export formats. * @access public */ public function getExportFormats() { $config = ConfigReader::getConfig(); $exportConfig = ConfigReader::getConfig('export'); // Get an array of enabled export formats (from config, or use defaults // if nothing in config array). $active = isset($config->Export) ? $config->Export->toArray() : array('RefWorks' => true, 'EndNote' => true); // Loop through all possible formats: $formats = array(); foreach ($exportConfig as $format => $details) { if (isset($active[$format]) && $active[$format] && $this->driver->supportsExport($format) ) { $formats[] = $format; } } // Send back the results: return $formats; } /** * Get the CSS class used to properly render a format. (Note that this may * not be used by every theme). * * @param string $format Format text to convert into CSS class * * @return string */ public function getFormatClass($format) { return $this->renderTemplate( 'format-class.phtml', array('format' => $format) ); } /** * Render a list of record formats. * * @return string */ public function getFormatList() { return $this->renderTemplate('format-list.phtml'); } /** * Render an entry in a favorite list. * * @param \VuFind\Db\Row\UserList $list Currently selected list (null for * combined favorites) * @param \VuFind\Db\Row\User $user Current logged in user (false if none) * * @return string */ public function getListEntry($list = null, $user = false) { // Get list of lists containing this entry $lists = null; if ($user) { $lists = $this->driver->getContainingLists($user->id); } return $this->renderTemplate( 'list-entry.phtml', array( 'driver' => $this->driver, 'list' => $list, 'user' => $user, 'lists' => $lists ) ); } /** * Render previews of the item if configured. * * @return string */ public function getPreviews() { $config = ConfigReader::getConfig(); return $this->renderTemplate( 'preview.phtml', array('driver' => $this->driver, 'config' => $config) ); } /** * Get the name of the controller used by the record route. * * @return string */ public function getController() { // Figure out controller using naming convention based on resource // source: $source = $this->driver->getResourceSource(); if ($source == 'VuFind') { // "VuFind" is special case -- it refers to Solr, which uses // the basic record controller. return 'Record'; } // All non-Solr controllers will correspond with the record source: return ucwords(strtolower($source)) . 'record'; } /** * Render the link of the specified type. * * @param string $type Link type * @param string $lookfor String to search for at link * * @return string */ public function getLink($type, $lookfor) { return $this->renderTemplate( 'link-' . $type . '.phtml', array('lookfor' => $lookfor) ); } /** * Render the contents of the specified record tab. * * @param string $tab Tab to display * * @return string */ public function getTab($tab) { // Maintain full view context rather than default driver/data-only context: return $this->renderTemplate('tab-' . $tab . '.phtml', array()); } /** * Render a search result for the specified view mode. * * @param string $view View mode to use. * * @return string */ public function getSearchResult($view) { return $this->renderTemplate('result-' . $view . '.phtml'); } /** * Render an HTML checkbox control for the current record. * * @param string $idPrefix Prefix for checkbox HTML ids * * @return string */ public function getCheckbox($idPrefix = '') { static $checkboxCount = 0; $id = $this->driver->getResourceSource() . '|' . $this->driver->getUniqueId(); $context = array('id' => $id, 'count' => $checkboxCount++, 'prefix' => $idPrefix); return $this->contextHelper->renderInContext( 'record/checkbox.phtml', $context ); } /** * Generate a thumbnail URL (return false if unsupported). * * @param string $size Size of thumbnail (small, medium or large -- small is * default). * * @return string|bool */ public function getThumbnail($size = 'small') { // Try to build thumbnail: $thumb = $this->driver->tryMethod('getThumbnail', array($size)); // No thumbnail? Return false: if (empty($thumb)) { return false; } // Array? It's parameters to send to the cover generator: if (is_array($thumb)) { $urlHelper = $this->getView()->plugin('url'); return $urlHelper('cover-show') . '?' . http_build_query($thumb); } // Default case -- return fixed string: return $thumb; } /** * Get all URLs associated with the record. Returns an array of strings. * * @return array */ public function getUrlList() { // Use a filter to pick URLs from the output of getLinkDetails(): $filter = function ($i) { return $i['url']; }; return array_map($filter, $this->getLinkDetails()); } /** * Get all the links associated with this record. Returns an array of * associative arrays each containing 'desc' and 'url' keys. * * @return array */ public function getLinkDetails() { // See if there are any links available: $urls = $this->driver->tryMethod('getURLs'); if (empty($urls)) { return array(); } // If we found links, we may need to convert from the "route" format // to the "full URL" format. $urlHelper = $this->getView()->plugin('url'); $serverUrlHelper = $this->getView()->plugin('serverurl'); $formatLink = function ($link) use ($urlHelper, $serverUrlHelper) { // Error if route AND URL are missing at this point! if (!isset($link['route']) && !isset($link['url'])) { throw new \Exception('Invalid URL array.'); } // Build URL from route/query details if missing: if (!isset($link['url'])) { $routeParams = isset($link['routeParams']) ? $link['routeParams'] : array(); $link['url'] = $serverUrlHelper( $urlHelper($link['route'], $routeParams) ); if (isset($link['queryString'])) { $link['url'] .= $link['queryString']; } } // Use URL as description if missing: if (!isset($link['desc'])) { $link['desc'] = $link['url']; } return $link; }; return array_map($formatLink, $urls); } }
gpl-2.0
gitbooster/kuhnijam.ru
page-about.php
10537
<?php /* * Template name: About * */ get_header(); ?> <div class="conteiner"><div class="head_about pad"> <img src="images/modules.png" alt=""> <div class="cont"> <h1 class="title">О студии</h1> <div class="text"> В нашей студии вы можете заказать: <a href="/works/web-design">сайт</a>, <a href="/works/interface">дизайн приложения (интерфейса)</a>, <a href="/works/graphics">иллюстрацию</a>, <a href="/works/logotypes">логотип, фирменный стиль</a>, <a href="/works/web-design">дизайн для сайта</a> (<a href="/works?tag=шаблон+для+DLE">шаблон для DLE</a>, <a href="/works?tag=Шаблон+HTML">HTML шаблон</a>). За время существования студии было реализовано множество проектов разного уровня сложности. В каждом нашем проекте мы стремимся создать привлекательный образ, который обеспечит удобство использования. </div> <p class="text_copy"> <b>Дизайн студия CODBOX</b><br> Мы работаем с 2009 года. </p> </div> </div> <div id="row_cat_thm" class="row_cat"> <div class="row_cat_info"> <div class="cont"> <h3 class="title">Вебдизайн</h3> <p class="text">Возможны различные варианты сотрудничества: 1. Разработка шаблона: DLE, Eleanor, Simpla, HTML, PSD. 2. Разработка сайта под ключ: корпоративный, новостной (информационный), промо-сайт, интернет-магазин.</p> </div> </div> <div class="row_cat_works"> <div class="row_cat_works_in"> <div class="row_cat_works_in_box"> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-234.jpg" alt="FStud"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-231.jpg" alt="Billgator"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-243.jpg" alt="Pawn"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-48.jpg" alt="Mobigama"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-248.jpg" alt="Ussurka"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-235.jpg" alt="Кинофокс"> </div> </div> </div> </div> <a class="overlay" href="/works/web-design"><b class="icon" title="Перейти в портфолио">Перейти в портфолио</b></a> </div> </div> <div id="row_cat_ui" class="row_cat"> <div class="row_cat_works"> <div class="row_cat_works_in"> <div class="row_cat_works_in_box"> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-43.jpg" alt="HistoryLost"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-48.jpg" alt="XXIbek"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-51.jpg" alt="Free-get"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-52.jpg" alt="Zeos"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-55.jpg" alt="Media CMS"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-56.jpg" alt="RadioAdrenalin"> </div> </div> </div> </div> <a class="overlay" href="/works/interface"><b class="icon" title="Перейти в портфолио">Перейти в портфолио</b></a> </div> <div class="row_cat_info"> <div class="cont"> <h3 class="title">Интерфейсы</h3> <p class="text">Возможна разработка интерфейса различной тематики, уровня сложности, детализации и платформы: интерфейсы для программного обеспечения, CMS, панели управления, приложения для мобильных платформ и многое другое.</p> </div> </div> </div> <div id="row_cat_bb" class="row_cat"> <div class="row_cat_info"> <div class="cont"> <h3 class="title">Логотипы</h3> <p class="text">Предлагаем разработку логотипа, фирменного стиля, товарного знака. Логотип и фирменный стиль используется при оформлении всех рекламных материалов компании. Это важный элемент бизнеса, для его продвижения и успеха.</p> </div> </div> <div class="row_cat_works"> <div class="row_cat_works_in"> <div class="row_cat_works_in_box"> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-254.jpg" alt="AppVisor"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-261.jpg" alt="Evil Geniuses"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-271.jpg" alt="Backspace"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-288.jpg" alt="Tetatet"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-299.jpg" alt="Mfilm"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-275.jpg" alt="Транссервис"> </div> </div> </div> </div> <a class="overlay" href="/works/logotypes"><b class="icon" title="Перейти в портфолио">Перейти в портфолио</b></a> </div> </div> <div id="row_cat_gui" class="row_cat"> <div class="row_cat_works"> <div class="row_cat_works_in"> <div class="row_cat_works_in_box"> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-249.jpg" alt="Zobra"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-246.jpg" alt="Xpay"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-247.jpg" alt="DleBoard"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-263.jpg" alt="Slaed"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-264.jpg" alt="Slaed"> </div> </div> <div class="teaser"> <div class="teaser_in"> <img src="images/work/centroarts-262.jpg" alt="TheEnd"> </div> </div> </div> </div> <a class="overlay" href="/works/graphics"><b class="icon" title="Перейти в портфолио">Перейти в портфолио</b></a> </div> <div class="row_cat_info"> <div class="cont"> <h3 class="title">Графдизайн</h3> <p class="text">В этом направлении мы предлагаем разработку иллюстраций, пиктограмм, обложек, этикеток, дизайн упаковок, создание плакатов, рекламных материалов типа обои для рабочего стола, дизайн сувенирной продукции.</p> </div> </div> </div> <!-- <div id="foot-about" class="pad greybg"> <div class="text"> За время существования студии было реализовано множество проектов разного уровня сложности: <a href="/works/web-design">веб-сайты</a>, <a href="/works/interface">интерфейсы</a>, <a href="/works/graphics">иллюстрации</a>, <a href="/works/logotypes">логотипы</a>, <a href="/works/web-design">дизайн для сайтов</a> (<a href="/works?tag=шаблон+для+DLE">шаблоны для DLE</a>, <a href="/works?tag=Шаблон+HTML">HTML шаблоны</a>). В каждом нашем проекте мы стремимся создать привлекательный образ, который обеспечит удобство использования. </div> </div> --> <?php get_footer();
gpl-2.0
marceloomiqueles/vallewp_miqueles
wp-content/themes/storefront/template-rental.php
21217
<?php /** * The template for displaying full width pages. * * Template Name: Rental * * @package storefront */ $nombre; $apellido; $edad; $estatura; $fecha; $fecha_rental; $peso; $sexo; $sexo_text = array( 0 => "", 1 => "MASCULINO", 2 => "FEMENINO" ); $aparato; $aparato_text = array( 0 => "", 1 => "Ski", 2 => "Snowboard" ); $tipo; $tipo_text = array( 0 => "", 1 => "Tipo 1: Esquia sin tomar riesgos, prefiere velocidades bajas y elige pendientes suaves.", 2 => "Tipo 2: Esquiador medio, prefiere velocidades variadas y terrenos de todo tipo.", 3 => "Tipo 3: Esqui de forma agresiva y a alta velocidad. SE desenvuelve a la perfección en pendientes medias y fuertes y tiene tendencias a llevar regulaciones mas altas de lo normal." ); $zapato; $producto; // print_r($array);die(); if (isset($_POST["nombre"])) $nombre = $_POST["nombre"]; if (isset($_POST["apellido"])) $apellido = $_POST["apellido"]; if (isset($_POST["edad"])) $edad = $_POST["edad"]; if (isset($_POST["estatura"])) $estatura = $_POST["estatura"]; if (isset($_POST["fecha"])) $fecha = $_POST["fecha"]; if (isset($_POST["peso"])) $peso = $_POST["peso"]; if (isset($_POST["sexo"])) $sexo = $_POST["sexo"]; if (isset($_POST["producto"])) $producto = $_POST["producto"]; if (isset($_POST["ski"])) $aparato = $_POST["ski"]; if (isset($_POST["tipo"])) $tipo = $_POST["tipo"]; if (isset($_POST["talla"])) $zapato = $_POST["talla"]; if (isset($_POST["fecha_rental"])) $fecha_rental = $_POST["fecha_rental"]; if ( count($nombre) > 0 && count($apellido) > 0 && count($edad) > 0 && count($estatura) > 0 && count($fecha) > 0 && count($peso) > 0 && count($sexo) > 0 && count($producto) > 0 && count($aparato) > 0 && count($tipo) > 0 && count($zapato) > 0) { // if ( count($producto) > 0 ) { // echo count($producto);die(); for ($i = 0; $i < count($producto); $i++) { $product = get_product( $producto[$i] ); $array_carro = Array ( "addons" => Array ( Array ( "name" => "Rental - Nombre", "value" => $nombre[$i], "price" => "", ), Array ( "name" => "Rental - Apellido", "value" => $apellido[$i], "price" => "", ), Array ( "name" => "Rental - Edad", "value" => $edad[$i], "price" => "", ), Array ( "name" => "Rental - Estatura", "value" => $estatura[$i], "price" => "", ), Array ( "name" => "Rental - Fecha Nacimiento", "value" => $fecha[$i], "price" => "", ), Array ( "name" => "Rental - Peso", "value" => $peso[$i], "price" => "", ), Array ( "name" => "Rental - Sexo", "value" => $sexo_text[$sexo[$i]], "price" => "", ), Array ( "name" => "Rental - Set", "value" => $product->post->post_title, "price" => "", ), Array ( "name" => "Rental - Aparato", "value" => $aparato_text[$aparato[$i]], "price" => "", ), Array ( "name" => "Rental - Tipo", "value" => $tipo_text[$tipo[$i]], "price" => "", ), Array ( "name" => "Rental - Zapato", "value" => $zapato[$i], "price" => "", ), Array ( "name" => "Rental - Fecha Rental", "value" => $fecha_rental[$i], "price" => "", ), ), "product_id" => $producto[$i], "variation_id" => "", "variation" => Array ( ), "quantity" => "1", "data" => new WC_Product_Simple( $producto[$i] ) ); $array_carro["data"]->sold_individually = "no"; $array_carro["data"]->price = $product->get_price(); $array_carro["data"]->stock_status = "instock"; // print_r($array_carro);die(); $woocommerce->cart->add_to_cart( $producto[$i], 1, null, null, $array_carro ); // $woocommerce->cart->add_to_cart( $value ); } } // die("salimos"); get_header(); ?> <script type="text/javascript"> $(document).ready(function(){ cargaCalendario(); }); function valida_form () { var pasa = true; var mensaje = ""; var nombre = document.getElementsByName("nombre[]"); var apellido = document.getElementsByName("apellido[]"); var edad = document.getElementsByName("edad[]"); var estatura = document.getElementsByName("estatura[]"); var fecha = document.getElementsByName("fecha[]"); var peso = document.getElementsByName("peso[]"); var sexo = document.getElementsByName("sexo[]"); var producto = document.getElementsByName("producto[]"); var aparato = document.getElementsByName("ski[]"); var tipo = document.getElementsByName("tipo[]"); var zapato = document.getElementsByName("talla[]"); var fecha_rental = document.getElementsByName("fecha_rental[]"); // console.log(document.getElementsByName("nombre[]")); for (var i = 0; i < nombre.length; i++) { mensaje += "Pase " + (i + 1) + "\n"; if (nombre[i].value.trim().length < 1) { mensaje += "Debes ingresar un nombre!\n"; pasa = false; } if (apellido[i].value.trim().length < 1) { mensaje += "Debes ingresar un apellido!\n"; pasa = false; } if (edad[i].value.trim().length < 1) { mensaje += "Debes ingresar una edad!\n"; pasa = false; } if (estatura[i].value.trim().length < 1) { mensaje += "Debes ingresar una estatura!\n"; pasa = false; } if (fecha[i].value.trim().length < 1) { mensaje += "Debes seleccionar una fecha!\n"; pasa = false; } if (peso[i].value.trim().length < 1) { mensaje += "Debes ingresar un peso!\n"; pasa = false; } if (sexo[i].value.trim().length < 1) { mensaje += "Debes seleccionar un sexo!\n"; pasa = false; } if (producto[i].value.trim().length < 1) { mensaje += "Debes seleccionar un producto!\n"; pasa = false; } if (aparato[i].value.trim().length < 1) { mensaje += "Debes seleccionar un aparato!\n"; pasa = false; } if (tipo[i].value.trim().length < 1) { mensaje += "Debes seleccionar un tipo!\n"; pasa = false; } if (zapato[i].value.trim().length < 1) { mensaje += "Debes seleccionar una talla!\n"; pasa = false; } if (fecha_rental[i].value.trim().length < 1) { mensaje += "Debes seleccionar una fecha de arriendo!\n"; pasa = false; } } if (!pasa) { alert(mensaje); return false; } } function comprueba_extension(archivo) { var extensiones_permitidas = new Array(".gif", ".jpg", ".jpeg", ".png"); var mierror = ""; var resul = true; if (!archivo) { resul = false; } else { extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase(); permitida = false; for (var i = 0; i < extensiones_permitidas.length; i++) { if (extensiones_permitidas[i] == extension) { permitida = true; break; } } if (!permitida) { mierror = "Comprueba la extensión de los archivos a subir. \nSólo se pueden subir archivos con extensiones: " + extensiones_permitidas.join(); resul = false; } } // alert (mierror); return resul; } function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } </script> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header> <h1 class="page-title"> Rental </h1> <?php the_archive_description(); ?> </header><!-- .page-header --> <div class="row"> <div class="col-md-12"> <hr style="width:100%; float:left; border:1px solid #033d5a !important; position:relative; "> </div> </div> <form method="post" name='form_data' action="<?php the_permalink() ?>" enctype="multipart/form-data" onsubmit='return valida_form();'> <div id="form-rental"> <div id="caja-nro-1"> <div class="row"> <div class='col-md-12'> <p align=='center'></p> </div> </div> <div class="row"> <div class="col-md-2"> <img data-src="holder.js/140x140" class="img-rounded" alt="140x140" src="<?php echo get_template_directory_uri(); ?>/images/ski.png" data-holder-rendered="true" style="width: 121px; height: 114px;"> </div> <div class="col-md-10"> <div class="row"> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" name='nombre[]' placeholder="NOMBRE"> </div> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" name='apellido[]' placeholder="APELLIDO"> </div> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" name="edad[]" placeholder="EDAD"> </div> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" name="estatura[]" placeholder="ESTATURA"> </div> </div> <div class="row"> <div class="form-group col-md-3 form-group-sm date"> <input type="text" class="form-control input-sm" name="fecha[]" readonly placeholder="FECHA NACIMIENTO"> </div> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" name="peso[]" placeholder="PESO"> </div> <div class="form-group col-md-3 form-group-sm"> <select class="form-control input-sm" name="sexo[]" id="sexo1" onchange="cambiaTalla(1);"> <option value="2">FEMENINO</option> <option value="1">MASCULINO</option> </select> </div> <div class="form-group col-md-3 form-group-sm"> <select id="descr1" class="form-control input-sm" name="producto[]" onchange="cambiaInfoTextRental(1)"> <?php $args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'product_cat' => 'rental'); $loop = new WP_Query( $args ); // print_r($loop);die(); while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?> <option value="<?php the_ID(); ?>"><?php echo $product->get_price_html(); ?> - <?php the_title(); ?></option> <?php endwhile; ?> <?php wp_reset_query(); ?> </select> </div> </div> <div class="row"> <div class="form-group col-md-3 form-group-sm"> <select id="skisnow1" class="form-control input-sm" name="ski[]" onchange="cambiaDetalle(1);"> <option value="1">Ski</option> <option value="2">Snowboard</option> </select> </div> <div class="form-group col-md-3 form-group-sm"> <select id="skisnowval1" class="form-control input-sm" name="tipo[]"> <option value="1">Tipo 1: Esquia sin tomar riesgos, prefiere velocidades bajas y elige pendientes suaves.</option> <option value="2">Tipo 2: Esquiador medio, prefiere velocidades variadas y terrenos de todo tipo.</option> <option value="3">Tipo 3: Esqui de forma agresiva y a alta velocidad. SE desenvuelve a la perfección en pendientes medias y fuertes y tiene tendencias a llevar regulaciones mas altas de lo normal.</option> </select> </div> <div class="form-group col-md-3 form-group-sm"> <select id="zapatoval1" class="form-control input-sm" onchange="cambiaTalla(1);"> <option value="0">Talla Zapato: 27</option> <option value="1">Talla Zapato: 28</option> <option value="2">Talla Zapato: 29</option> <option value="3">Talla Zapato: 30,5</option> <option value="4">Talla Zapato: 31,5</option> <option value="5">Talla Zapato: 33</option> <option value="6">Talla Zapato: 34</option> <option value="7">Talla Zapato: 35</option> <option value="8">Talla Zapato: 36</option> <option value="9">Talla Zapato: 36,5</option> <option value="10">Talla Zapato: 37</option> <option value="11">Talla Zapato: 38</option> <option value="12">Talla Zapato: 39</option> <option value="13">Talla Zapato: 40</option> <option value="14">Talla Zapato: 40,5</option> <option value="15">Talla Zapato: 41</option> <option value="16">Talla Zapato: 41,5</option> <option value="17">Talla Zapato: 42</option> <option value="18">Talla Zapato: 42,5</option> <option value="19">Talla Zapato: 43</option> <option value="20">Talla Zapato: 43,5</option> <option value="21">Talla Zapato: 44</option> <option value="22">Talla Zapato: 45</option> <option value="23">Talla Zapato: 46</option> <option value="24">Talla Zapato: 46,5</option> <option value="25">Talla Zapato: 48</option> <option value="26">Talla Zapato: 49</option> <option value="27">Talla Zapato: 50</option> </select> </div> <div class="form-group col-md-3 form-group-sm"> <input type="text" class="form-control input-sm" id="converttalla1" name="talla[]" readonly placeholder="Talla Equipo" value="Talla Ski: 16,5"> </div> </div> <div class="row"> <div class="form-group col-md-3 form-group-sm date"> <input type="text" class="form-control input-sm" name="fecha_rental[]" readonly placeholder="FECHA RENTAL"> </div> </div> <div class="row"> <div class="form-group col-md-12 form-group-sm has-error"> <p id="textoinf1" class="help-block">Voucher válido por 1 arriendo Set Ski/Snowboard Prestige Adulto (Entre 12 y 65 años) para cualquier día de la temporada de ski 2015. Set Ski: Ski + Bastones + Botas. Set Snowboard: Snowboard + Botas. Acércate a cualquier rental de Valle Nevado y canjea tu voucher</p> </div> </div> </div> </div> <div class="row"> <div class="col-md-10"> <hr style="width:100%; float:left; border:1px solid #033d5a !important; position:relative; "> </div> <div class="col-md-2 text-right"> <button type="button" class="single_add_to_cart_button button alt" onclick="elimina_caja('nro-1');"> <span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span> Eliminar </button> </div> </div> </div> </div> <div class="contenedor_btn_amigo"> <div id="btn-add-amigos" class="btn_amigos"></div> </div> <div class="row"> <div class="col-md-12"> <div class="row"> <div class="form-group col-md-12 text-right"> <button type="submit" class="single_add_to_cart_button button alt">Añadir al carro</button> </div> </div> </div> </div> </form> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </main><!-- #main --> </section><!-- #primary --> <?php do_action( 'storefront_sidebar' ); ?> <?php get_footer(); ?>
gpl-2.0
gurjitdhillon/phpmyadmin
test/libraries/common/PMA_formatNumberByteDown_test.php
2654
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Test for format number and byte * * @package PhpMyAdmin-test * @group common.lib-tests */ /* * Include to test. */ require_once 'libraries/CommonFunctions.class.php'; require_once 'libraries/php-gettext/gettext.inc'; class PMA_formatNumberByteDown_test extends PHPUnit_Framework_TestCase { /** * temporary variable for globals array */ protected $tmpGlobals; /** * temporary variable for session array */ protected $tmpSession; /** * storing globals and session */ public function setUp() { $this->tmpGlobals = $GLOBALS; $this->tmpSession = $_SESSION; } /** * recovering globals and session */ public function tearDown() { $GLOBALS = $this->tmpGlobals; $_SESSION = $this->tmpSession; } /** * format number data provider * * @return array */ public function formatNumberDataProvider() { return array( array(10, 2, 2, '10 '), array(100, 2, 0, '100 '), array(100, 2, 2, '100 '), array(-1000.454, 4, 2, '-1,000.45 '), array(0.00003, 3, 2, '30 &micro;'), array(0.003, 3, 3, '3 m'), array(-0.003, 6, 0, '-3,000 &micro;'), array(100.98, 0, 2, '100.98') ); } /** * format number test, globals are defined * @dataProvider formatNumberDataProvider */ public function testFormatNumber($a, $b, $c, $d) { $this->assertEquals( $d, (string) PMA_CommonFunctions::getInstance()->formatNumber( $a, $b, $c, false ) ); } /** * format byte down data provider * * @return array */ public function formatByteDownDataProvider() { return array( array(10, 2, 2, array('10', __('B'))), array(100, 2, 0, array('0', __('KiB'))), array(100, 3, 0, array('100', __('B'))), array(100, 2, 2, array('0.10', __('KiB'))), array(1034, 3, 2, array('1.01', __('KiB'))), array(100233, 3, 3, array('97.884', __('KiB'))), array(2206451, 1, 2, array('2.10', __('MiB'))) ); } /** * format byte test, globals are defined * @dataProvider formatByteDownDataProvider */ public function testFormatByteDown($a, $b, $c, $e) { $result = PMA_CommonFunctions::getInstance()->formatByteDown($a, $b, $c); $result[0] = trim($result[0]); $this->assertEquals($e, $result); } } ?>
gpl-2.0
Zaturrby/deploykanvas
wp-config.php
3388
<?php /** * The base configurations of the WordPress. * * This file has the following configurations: MySQL settings, Table Prefix, * Secret Keys, WordPress Language, and ABSPATH. You can find more information * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing * wp-config.php} Codex page. You can get the MySQL settings from your web host. * * This file is used by the wp-config.php creation script during the * installation. You don't have to use the web site, you can just copy this file * to "wp-config.php" and fill in the values. * * @package WordPress */ // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', '31014wordpress'); /** MySQL database username */ define('DB_USER', '31014wordpress'); /** MySQL database password */ define('DB_PASSWORD', 'k4nv4s'); /** MySQL hostname */ define('DB_HOST', 'sql10.pcextreme.nl'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', 'N2M>A DY-j4GSECI&qFK<AHxC,)1f}`:B-O[[;f:Zt0I5Ywew;obRK<$`3@r-nIV'); define('SECURE_AUTH_KEY', '-bH:A}y,M>}} #H;YozqP UCy$H_`4k(UIk3({Ze[iZ@0kS~igqbZ2IS3:X9-%o*'); define('LOGGED_IN_KEY', '*&S+awEi,]e16%GBzZX4<=GrMQ@~3Pi+9w[S2^SG2|_*m|+PgQL.6!zFyGvIKg|U'); define('NONCE_KEY', 'wc~W.1i$:7C,_5uRh>QY^wMrGoXQwrvh7|EKIT/|7+o_P-qkF6n_i<!^ueZjVK$U'); define('AUTH_SALT', '<LEx5~| yjZ/HOH=f81iZ|Wg?.)`MV7WPc2U@LEA4QXBP7AD8pAm J7vHL}$*^wq'); define('SECURE_AUTH_SALT', 'C3-S[GtLD5Lfa`<2/.]jQ(?|hx$0+a]/9Z;.K9%aG4Dfae<f7>KnKpaHrLB^(.,o'); define('LOGGED_IN_SALT', '3b.z@=96Q21-ZoE78F<|ynBh@(6WK||5Ezv2AKE9D5?N+[dq-wF9vTc=@LJ6~:vC'); define('NONCE_SALT', '=G~Op;x8305VF:.=kuFwPcn-[<!Q3U^}B|j5u?xfI&?BZ|GyjL.X3#T>&BPremkv'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'wp_'; /** * WordPress Localized Language, defaults to English. * * Change this to localize WordPress. A corresponding MO file for the chosen * language must be installed to wp-content/languages. For example, install * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German * language support. */ define ('WPLANG', 'nl_NL'); /** * For developers: WordPress debugging mode. * * Change this to true to enable the display of notices during development. * It is strongly recommended that plugin and theme developers use WP_DEBUG * in their development environments. */ define('WP_DEBUG', false); /* That's all, stop editing! Happy blogging. */ /** Absolute path to the WordPress directory. */ if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); /** Sets up WordPress vars and included files. */ require_once(ABSPATH . 'wp-settings.php');
gpl-2.0
DynamicDevices/dta
Renci.SshNet/ScpClient.cs
16166
using System; using System.Linq; using System.Text; using Renci.SshNet.Channels; using System.IO; using Renci.SshNet.Common; using System.Text.RegularExpressions; using System.Threading; using System.Diagnostics.CodeAnalysis; namespace Renci.SshNet { /// <summary> /// Provides SCP client functionality. /// </summary> public partial class ScpClient : BaseClient { private static readonly Regex _fileInfoRe = new Regex(@"C(?<mode>\d{4}) (?<length>\d+) (?<filename>.+)"); private static char[] _byteToChar; /// <summary> /// Gets or sets the operation timeout. /// </summary> /// <value> /// The timeout to wait until an operation completes. The default value is negative /// one (-1) milliseconds, which indicates an infinite time-out period. /// </value> public TimeSpan OperationTimeout { get; set; } /// <summary> /// Gets or sets the size of the buffer. /// </summary> /// <value> /// The size of the buffer. The default buffer size is 16384 bytes. /// </value> public uint BufferSize { get; set; } /// <summary> /// Occurs when downloading file. /// </summary> public event EventHandler<ScpDownloadEventArgs> Downloading; /// <summary> /// Occurs when uploading file. /// </summary> public event EventHandler<ScpUploadEventArgs> Uploading; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SftpClient"/> class. /// </summary> /// <param name="connectionInfo">The connection info.</param> /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception> public ScpClient(ConnectionInfo connectionInfo) : this(connectionInfo, false) { } /// <summary> /// Initializes a new instance of the <see cref="SftpClient"/> class. /// </summary> /// <param name="host">Connection host.</param> /// <param name="port">Connection port.</param> /// <param name="username">Authentication username.</param> /// <param name="password">Authentication password.</param> /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception> [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")] public ScpClient(string host, int port, string username, string password) : this(new PasswordConnectionInfo(host, port, username, password), true) { } /// <summary> /// Initializes a new instance of the <see cref="SftpClient"/> class. /// </summary> /// <param name="host">Connection host.</param> /// <param name="username">Authentication username.</param> /// <param name="password">Authentication password.</param> /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception> public ScpClient(string host, string username, string password) : this(host, ConnectionInfo.DEFAULT_PORT, username, password) { } /// <summary> /// Initializes a new instance of the <see cref="SftpClient"/> class. /// </summary> /// <param name="host">Connection host.</param> /// <param name="port">Connection port.</param> /// <param name="username">Authentication username.</param> /// <param name="keyFiles">Authentication private key file(s) .</param> /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception> [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")] public ScpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles) : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true) { } /// <summary> /// Initializes a new instance of the <see cref="SftpClient"/> class. /// </summary> /// <param name="host">Connection host.</param> /// <param name="username">Authentication username.</param> /// <param name="keyFiles">Authentication private key file(s) .</param> /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception> public ScpClient(string host, string username, params PrivateKeyFile[] keyFiles) : this(host, ConnectionInfo.DEFAULT_PORT, username, keyFiles) { } /// <summary> /// Initializes a new instance of the <see cref="ScpClient"/> class. /// </summary> /// <param name="connectionInfo">The connection info.</param> /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param> /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception> /// <remarks> /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the /// connection info will be disposed when this instance is disposed. /// </remarks> private ScpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo) : base(connectionInfo, ownsConnectionInfo) { this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1); this.BufferSize = 1024 * 16; if (_byteToChar == null) { _byteToChar = new char[128]; var ch = '\0'; for (int i = 0; i < 128; i++) { _byteToChar[i] = ch++; } } } #endregion /// <summary> /// Uploads the specified stream to the remote host. /// </summary> /// <param name="source">Stream to upload.</param> /// <param name="path">Remote host file name.</param> public void Upload(Stream source, string path) { using (var input = new PipeStream()) using (var channel = this.Session.CreateClientChannel<ChannelSession>()) { channel.DataReceived += delegate(object sender, ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); int pathEnd = path.LastIndexOfAny(new[] { '\\', '/' }); if (pathEnd != -1) { // split the path from the file string pathOnly = path.Substring(0, pathEnd); string fileOnly = path.Substring(pathEnd + 1); // Send channel command request channel.SendExecRequest(string.Format("scp -t \"{0}\"", pathOnly)); this.CheckReturnCode(input); path = fileOnly; } this.InternalUpload(channel, input, source, path); channel.Close(); } } /// <summary> /// Downloads the specified file from the remote host to the stream. /// </summary> /// <param name="filename">Remote host file name.</param> /// <param name="destination">The stream where to download remote file.</param> /// <exception cref="ArgumentException"><paramref name="filename"/> is null or contains whitespace characters.</exception> /// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception> /// <remarks>Method calls made by this method to <paramref name="destination"/>, may under certain conditions result in exceptions thrown by the stream.</remarks> public void Download(string filename, Stream destination) { if (filename.IsNullOrWhiteSpace()) throw new ArgumentException("filename"); if (destination == null) throw new ArgumentNullException("destination"); using (var input = new PipeStream()) using (var channel = this.Session.CreateClientChannel<ChannelSession>()) { channel.DataReceived += delegate(object sender, ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); // Send channel command request channel.SendExecRequest(string.Format("scp -f \"{0}\"", filename)); this.SendConfirmation(channel); // Send reply var message = ReadString(input); var match = _fileInfoRe.Match(message); if (match.Success) { // Read file this.SendConfirmation(channel); // Send reply var mode = match.Result("${mode}"); var length = long.Parse(match.Result("${length}")); var fileName = match.Result("${filename}"); this.InternalDownload(channel, input, destination, fileName, length); } else { this.SendConfirmation(channel, 1, string.Format("\"{0}\" is not valid protocol message.", message)); } channel.Close(); } } private void InternalSetTimestamp(ChannelSession channel, Stream input, DateTime lastWriteTime, DateTime lastAccessime) { var zeroTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var modificationSeconds = (long)(lastWriteTime - zeroTime).TotalSeconds; var accessSeconds = (long)(lastAccessime - zeroTime).TotalSeconds; this.SendData(channel, string.Format("T{0} 0 {1} 0\n", modificationSeconds, accessSeconds)); this.CheckReturnCode(input); } private void InternalUpload(ChannelSession channel, Stream input, Stream source, string filename) { var length = source.Length; this.SendData(channel, string.Format("C0644 {0} {1}\n", length, Path.GetFileName(filename))); var buffer = new byte[this.BufferSize]; var read = source.Read(buffer, 0, buffer.Length); long totalRead = 0; while (read > 0) { this.SendData(channel, buffer, read); totalRead += read; this.RaiseUploadingEvent(filename, length, totalRead); read = source.Read(buffer, 0, buffer.Length); } this.SendConfirmation(channel); this.CheckReturnCode(input); } private void InternalDownload(ChannelSession channel, Stream input, Stream output, string filename, long length) { var buffer = new byte[Math.Min(length, this.BufferSize)]; var needToRead = length; do { var read = input.Read(buffer, 0, (int)Math.Min(needToRead, this.BufferSize)); output.Write(buffer, 0, read); this.RaiseDownloadingEvent(filename, length, length - needToRead); needToRead -= read; } while (needToRead > 0); output.Flush(); // Raise one more time when file downloaded this.RaiseDownloadingEvent(filename, length, length - needToRead); // Send confirmation byte after last data byte was read this.SendConfirmation(channel); this.CheckReturnCode(input); } private void RaiseDownloadingEvent(string filename, long size, long downloaded) { if (this.Downloading != null) { this.Downloading(this, new ScpDownloadEventArgs(filename, size, downloaded)); } } private void RaiseUploadingEvent(string filename, long size, long uploaded) { if (this.Uploading != null) { this.Uploading(this, new ScpUploadEventArgs(filename, size, uploaded)); } } private void SendConfirmation(ChannelSession channel) { this.SendData(channel, new byte[] { 0 }); } private void SendConfirmation(ChannelSession channel, byte errorCode, string message) { this.SendData(channel, new[] { errorCode }); this.SendData(channel, string.Format("{0}\n", message)); } /// <summary> /// Checks the return code. /// </summary> /// <param name="input">The output stream.</param> private void CheckReturnCode(Stream input) { var b = ReadByte(input); if (b > 0) { var errorText = ReadString(input); throw new ScpException(errorText); } } partial void SendData(ChannelSession channel, string command); private void SendData(ChannelSession channel, byte[] buffer, int length) { if (length == buffer.Length) { channel.SendData(buffer); } else { channel.SendData(buffer.Take(length).ToArray()); } } private void SendData(ChannelSession channel, byte[] buffer) { channel.SendData(buffer); } private static int ReadByte(Stream stream) { var b = stream.ReadByte(); while (b < 0) { Thread.Sleep(100); b = stream.ReadByte(); } return b; } private static string ReadString(Stream stream) { var hasError = false; var sb = new StringBuilder(); var b = ReadByte(stream); if (b == 1 || b == 2) { hasError = true; b = ReadByte(stream); } var ch = _byteToChar[b]; while (ch != '\n') { sb.Append(ch); b = ReadByte(stream); ch = _byteToChar[b]; } if (hasError) throw new ScpException(sb.ToString()); return sb.ToString(); } } }
gpl-2.0
alxnns1/Essemancy
src/main/java/com/alxnns1/essemancy/init/EEntities.java
1891
package com.alxnns1.essemancy.init; import com.alxnns1.essemancy.Essemancy; import com.alxnns1.essemancy.entity.EntitySpawn; import com.alxnns1.essemancy.entity.EntityWisp; import com.alxnns1.essemancy.entity.EntityWraith; import com.alxnns1.essemancy.entity.render.RenderSpawn; import com.alxnns1.essemancy.entity.render.RenderWisp; import com.alxnns1.essemancy.entity.render.RenderWraith; import net.minecraft.entity.Entity; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry; /** * Created by Alex on 22/11/2016. */ public class EEntities { private static int modEntityID = 0; private static void registerMobWithEgg(Class<? extends Entity> entityClass, String name, int eggColour, int eggSpotColour) { EntityRegistry.registerModEntity(entityClass, name, ++modEntityID, Essemancy.instance, 64, 1, false, eggColour, eggSpotColour); } public static void init(boolean isClientSide) { registerMobWithEgg(EntityWisp.class, "Wisp", 0xffffff, 0x00ffff); registerMobWithEgg(EntitySpawn.class, "Spawn", 0xffffff, 0x00ffff); registerMobWithEgg(EntityWraith.class, "Wraith", 0xffffff, 0x00ffff); /* registerMobWithEgg(EntityPyre.class, "Pyre", 0xffffff, 0xff0000); registerMobWithEgg(EntityKnoll.class, "Knoll", 0xffffff, 0x00ff00); registerMobWithEgg(EntityNymph.class, "Nymph", 0xffffff, 0x0000ff); registerMobWithEgg(EntityDryad.class, "Dryad", 0xffffff, 0x337700); */ if(isClientSide) { RenderingRegistry.registerEntityRenderingHandler(EntityWisp.class, RenderWisp.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntitySpawn.class, RenderSpawn.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityWraith.class, RenderWraith.FACTORY); } } }
gpl-2.0
Bryukh-Checkio-Tasks/checkio-task-simplification
editor/animation/init.js
4856
//Dont change it requirejs(['ext_editor_1', 'jquery_190', 'raphael_210', 'snap.svg_030'], function (ext, $, Raphael, Snap) { var cur_slide = {}; ext.set_start_game(function (this_e) { }); ext.set_process_in(function (this_e, data) { cur_slide = {}; cur_slide["in"] = data[0]; this_e.addAnimationSlide(cur_slide); }); ext.set_process_out(function (this_e, data) { cur_slide["out"] = data[0]; }); ext.set_process_ext(function (this_e, data) { cur_slide.ext = data; }); ext.set_process_err(function (this_e, data) { cur_slide['error'] = data[0]; this_e.addAnimationSlide(cur_slide); cur_slide = {}; }); ext.set_animate_success_slide(function (this_e, options) { var $h = $(this_e.setHtmlSlide('<div class="animation-success"><div></div></div>')); this_e.setAnimationHeight(115); }); ext.set_animate_slide(function (this_e, data, options) { var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content'); if (!data) { console.log("data is undefined"); return false; } //YOUR FUNCTION NAME var fname = 'simplify'; var checkioInput = data.in || "x"; var checkioInputStr = fname + '(u' + JSON.stringify(checkioInput) + ')'; var failError = function (dError) { $content.find('.call').html(checkioInputStr); $content.find('.output').html(dError.replace(/\n/g, ",")); $content.find('.output').addClass('error'); $content.find('.call').addClass('error'); $content.find('.answer').remove(); $content.find('.explanation').remove(); this_e.setAnimationHeight($content.height() + 60); }; if (data.error) { failError(data.error); return false; } if (data.ext && data.ext.inspector_fail) { failError(data.ext.inspector_result_addon); return false; } $content.find('.call').html(checkioInputStr); $content.find('.output').html('Working...'); if (data.ext) { var rightResult = data.ext["answer"]; var userResult = data.out; var result = data.ext["result"]; var result_addon = data.ext["result_addon"]; //if you need additional info from tests (if exists) var explanation = data.ext["explanation"]; $content.find('.output').html('&nbsp;Your result:&nbsp;' + JSON.stringify(userResult)); if (!result) { $content.find('.answer').html('Right result:&nbsp;' + JSON.stringify(rightResult)); $content.find('.answer').addClass('error'); $content.find('.output').addClass('error'); $content.find('.call').addClass('error'); } else { $content.find('.answer').remove(); } } else { $content.find('.answer').remove(); } //Your code here about test explanation animation //$content.find(".explanation").html("Something text for example"); // // // // // this_e.setAnimationHeight($content.height() + 60); }); //This is for Tryit (but not necessary) // var $tryit; // ext.set_console_process_ret(function (this_e, ret) { // $tryit.find(".checkio-result").html("Result<br>" + ret); // }); // // ext.set_generate_animation_panel(function (this_e) { // $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))).find('.tryit-content'); // $tryit.find('.bn-check').click(function (e) { // e.preventDefault(); // this_e.sendToConsoleCheckiO("something"); // }); // }); var colorOrange4 = "#F0801A"; var colorOrange3 = "#FA8F00"; var colorOrange2 = "#FAA600"; var colorOrange1 = "#FABA00"; var colorBlue4 = "#294270"; var colorBlue3 = "#006CA9"; var colorBlue2 = "#65A1CF"; var colorBlue1 = "#8FC7ED"; var colorGrey4 = "#737370"; var colorGrey3 = "#9D9E9E"; var colorGrey2 = "#C5C6C6"; var colorGrey1 = "#EBEDED"; var colorWhite = "#FFFFFF"; //Your Additional functions or objects inside scope // // // } );
gpl-2.0
EaseTech/schema-generator
src/main/java/org/easetech/schema/SimpleType.java
5794
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.04.28 at 02:40:28 PM CEST // package org.easetech.schema; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for simpleType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="simpleType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="annotation" type="{urn:org:easetech:easytest:schema}annotation" minOccurs="0"/> * &lt;element name="list" type="{urn:org:easetech:easytest:schema}list" minOccurs="0"/> * &lt;element name="restriction" type="{urn:org:easetech:easytest:schema}restrictionSimpleType" minOccurs="0"/> * &lt;element name="union" type="{urn:org:easetech:easytest:schema}union" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}NCName" /> * &lt;attribute name="final" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "simpleType", propOrder = { "annotation", "list", "restriction", "union" }) public class SimpleType { protected Annotation annotation; protected List list; protected RestrictionSimpleType restriction; protected Union union; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "name") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NCName") protected String name; @XmlAttribute(name = "final") protected String _final; /** * Gets the value of the annotation property. * * @return * possible object is * {@link Annotation } * */ public Annotation getAnnotation() { return annotation; } /** * Sets the value of the annotation property. * * @param value * allowed object is * {@link Annotation } * */ public void setAnnotation(Annotation value) { this.annotation = value; } /** * Gets the value of the list property. * * @return * possible object is * {@link List } * */ public List getList() { return list; } /** * Sets the value of the list property. * * @param value * allowed object is * {@link List } * */ public void setList(List value) { this.list = value; } /** * Gets the value of the restriction property. * * @return * possible object is * {@link RestrictionSimpleType } * */ public RestrictionSimpleType getRestriction() { return restriction; } /** * Sets the value of the restriction property. * * @param value * allowed object is * {@link RestrictionSimpleType } * */ public void setRestriction(RestrictionSimpleType value) { this.restriction = value; } /** * Gets the value of the union property. * * @return * possible object is * {@link Union } * */ public Union getUnion() { return union; } /** * Sets the value of the union property. * * @param value * allowed object is * {@link Union } * */ public void setUnion(Union value) { this.union = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the final property. * * @return * possible object is * {@link String } * */ public String getFinal() { return _final; } /** * Sets the value of the final property. * * @param value * allowed object is * {@link String } * */ public void setFinal(String value) { this._final = value; } }
gpl-2.0
langcog/wordbank
instruments/migrations/0015_english_british_teds_twos.py
13063
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('instruments', '0014_auto_20160517_1301'), ] operations = [ migrations.CreateModel( name='English_British_TEDS_Twos', fields=[ ('basetable_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='instruments.BaseTable', on_delete=models.CASCADE)), ('item_1', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_2', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_3', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_4', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_5', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_6', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_7', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_8', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_9', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_10', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_11', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_12', models.CharField(max_length=7, null=True, choices=[('simple', 'simple'), ('complex', 'complex')])), ('item_13', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_14', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_15', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_16', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_17', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_18', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_19', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_20', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_21', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_22', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_23', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_24', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_25', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_26', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_27', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_28', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_29', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_30', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_31', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_32', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_33', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_34', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_35', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_36', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_37', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_38', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_39', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_40', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_41', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_42', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_43', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_44', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_45', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_46', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_47', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_48', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_49', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_50', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_51', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_52', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_53', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_54', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_55', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_56', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_57', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_58', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_59', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_60', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_61', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_62', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_63', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_64', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_65', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_66', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_67', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_68', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_69', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_70', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_71', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_72', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_73', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_74', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_75', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_76', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_77', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_78', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_79', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_80', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_81', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_82', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_83', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_84', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_85', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_86', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_87', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_88', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_89', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_90', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_91', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_92', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_93', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_94', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_95', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_96', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_97', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_98', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_99', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_100', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_101', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_102', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_103', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_104', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_105', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_106', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_107', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_108', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_109', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_110', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_111', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_112', models.CharField(max_length=8, null=True, choices=[('produces', 'produces')])), ('item_113', models.CharField(max_length=9, null=True, choices=[('often', 'often'), ('sometimes', 'sometimes'), ('not yet', 'not yet')])), ], bases=('instruments.basetable',), ), ]
gpl-2.0
diogodanielsoaresferreira/ProgrammingExercises-Java-
P2/Aula 3/p34.java
1024
package p2; import static java.lang.System.*; public class p34 { public static void main(String[] args) { Agenda agenda = new Agenda(); agenda.novaNota(new Data2(14,6,2012), new Data2(27,6,2012), "Prog2: APF"); agenda.novaNota(new Data2(2,7,2012), new Data2(13,7,2012), "Prog2: Recurso"); agenda.novaNota(new Data2(6,6,2012), new Data2(6,6,2012), "Prog2: ACITP2"); agenda.novaNota(new Data2(9,5,2012), new Data2(9,5,2012), "Prog2: AIP"); agenda.novaNota(new Data2(22,3,2012), new Data2(27,3,2012), "Prog2: ACITP1"); agenda.escreve(); out.println(); Data2 d1 = new Data2(27,3,2012); Data2 d2 = new Data2(15,6,2012); Nota[] todo = agenda.compromissos(d1, d2); out.print("Compromissos de "); out.print(d1.escreve()); out.print(" a "); out.print(d2.escreve()); out.println(":"); for(int i = 0; i < todo.length; i++) out.println(todo[i].escreve()); } }
gpl-2.0
lycoben/veneflights
plugins/system/jfdatabase.php
8635
<?php /** * Joom!Fish - Multi Lingual extention and translation manager for Joomla! * Copyright (C) 2003-2008 Think Network GmbH, Munich * * All rights reserved. The Joom!Fish project is a set of extentions for * the content management system Joomla!. It enables Joomla! * to manage multi lingual sites especially in all dynamic information * which are stored in the database. * * This program 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 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * The "GNU Lesser General Public License" (LGPL) is available at * http: *www.gnu.org/copyleft/lgpl.html * ----------------------------------------------------------------------------- * $Id: ReadMe,v 1.2 2005/03/15 11:07:01 akede Exp $ * @package joomfish * @subpackage system.jfdatabase_bot * @version 2.0 * */ /** ensure this file is being included by a parent file */ defined( '_JEXEC' ) or die( 'Restricted access' ); // In PHP5 this should be a instance_of check // Currently Joom!Fish does not need to be active in Administrator // This might be an extended version if($mainframe->isAdmin()) { return; } // Joom!Fish bot get's only activated if essential files are missing //if ( !file_exists( JPATH_PLUGINS .DS. 'system' .DS. 'jfdatabase' .DS. 'jfdatabase.class.php' )) { if ( !file_exists( dirname(__FILE__) .DS. 'jfdatabase' .DS. 'jfdatabase_inherit.php' )) { JError::raiseNotice('no_jf_plugin', JText::_('Joom!Fish plugin not installed correctly. Plugin not executed')); return; } jimport('joomla.filesystem.file'); if(JFile::exists(JPATH_SITE .DS. 'components' .DS. 'com_joomfish' .DS. 'helpers' .DS. 'defines.php')) { require_once( JPATH_SITE .DS. 'components' .DS. 'com_joomfish' .DS. 'helpers' .DS. 'defines.php' ); JLoader::register('JoomfishManager', JOOMFISH_ADMINPATH .DS. 'classes' .DS. 'JoomfishManager.class.php' ); JLoader::register('JoomFishVersion', JOOMFISH_ADMINPATH .DS. 'version.php' ); JLoader::register('JoomFish', JOOMFISH_PATH .DS. 'helpers' .DS. 'joomfish.class.php' ); } else { JError::raiseNotice('no_jf_extension', JText::_('Joom!Fish extension not installed correctly. Plugin not executed')); return; } /** * Exchange of the database abstraction layer for multi lingual translations. */ class plgSystemJFDatabase extends JPlugin{ /** * stored configuration from plugin * * @var object configuration information */ var $_config = null; function plgSystemJFDatabase(& $subject, $config) { global $mainframe; if ($mainframe->isAdmin()) { // This plugin is only relevant for use within the frontend! return; } parent::__construct($subject, $config); // put params in registry so I have easy access to them later $conf =& JFactory::getConfig(); $conf->setValue("jfdatabase.params",$this->params); $this->_config = array( 'adapter' => $this->params->get('dbadapter', "inheritor") ); if(defined('JOOMFISH_PATH')) { $this->_jfInitialize(); } else { JError::raiseNotice('no_jf_component', JText::_('Joom!Fish component not installed correctly. Plugin not executed')); } } /** * During this event we setup the database and link it to the Joomla! ressources for future use * @return void */ function onAfterInitialise() { global $mainframe; if ($mainframe->isAdmin()) { // This plugin is only relevant for use within the frontend! return; } $this->_setupJFDatabase(); } function onAfterRender() { // There is a bug in Garbage collectino in Joomla 1.5.5 see http://joomlacode.org/gf/project/joomla/tracker/?action=TrackerItemEdit&tracker_item_id=12101 // garbage collect the cache /* $jfm =& JoomFishManager::getInstance(); if ($jfm->getCfg("transcaching",1)){ $jlang =& JFactory::getLanguage(); $language = $jlang->getTag(); $cache = $jfm->getCache($language); $cache->gc(); } */ // Therefore do it ourselves (the old fashioned way to maximise performance) $jfm =& JoomFishManager::getInstance(); if ($jfm->getCfg("transcaching",1)){ $jlang =& JFactory::getLanguage(); $language = $jlang->getTag(); $cache = $jfm->getCache($language); $handler =& $cache->_getStorage(); $lifetime = intval($jfm->getCfg("cachelife",1440)) * 60; // minutes to seconds if (!JError::isError($handler) && strtolower(get_class($handler)) == "jcachestoragefile") { $files = JFolder::files($handler->_root.DS.$cache->_options["defaultgroup"], '_expire', true, true); clearstatcache(); foreach($files As $file) { $time = @filemtime($file); if ($time){ $time += $lifetime; if ( $handler->_now > $time) { JFile::delete($file); JFile::delete(str_replace('_expire', '', $file)); } } } } } $buffer = JResponse::getBody(); $info = ""; $db =& JFactory::getDBO(); $info .= "<div style='font-size:11px'>"; foreach ($db->profileData as $func=>$data) { $info .= "$func = ".round($data["total"],4)." (".$data["count"].")<br />"; } $info .= "</div>"; $buffer = str_replace("JFTimings",$info,$buffer); JResponse::setBody($buffer); } /** * Setup for the Joom!Fish database connectors, overwriting the original instances of Joomla! * Which connector is used and which technique is based on the extension configuration * @return void */ function _setupJFDatabase(){ if ($this->_config["adapter"] == "decorator") { if (file_exists( JPATH_ADMINISTRATOR .DS. 'components' .DS. 'com_joomfish' .DS. 'jfdatabase_decorator.class.php' )) { require_once( JPATH_ADMINISTRATOR .DS. 'components' .DS. 'com_joomfish' .DS. 'jfdatabase_decorator.class.php' ); $db = & JFactory::getDBO(); $db = new JFDatabase(); $conf =& JFactory::getConfig(); $conf->setValue('config.mbf_content', 1 ); $conf->setValue('config.multilingual_support', 1 ); // TODO: check on legacy mode on or off $GLOBALS['database'] = $db; } } else { if (file_exists( dirname(__FILE__).DS.'jfdatabase'.DS.'jfdatabase_inherit.php' )) { require_once( dirname(__FILE__).DS.'jfdatabase'.DS.'jfdatabase_inherit.php' ); $conf =& JFactory::getConfig(); $host = $conf->getValue('config.host'); $user = $conf->getValue('config.user'); $password = $conf->getValue('config.password'); $db = $conf->getValue('config.db'); $dbprefix = $conf->getValue('config.dbprefix'); $dbtype = $conf->getValue('config.dbtype'); $debug = $conf->getValue('config.debug'); $driver = $conf->getValue('config.dbtype'); $options = array("driver"=>$driver, "host"=>$host, "user"=>$user, "password"=>$password, "database"=>$db, "prefix"=>$dbprefix,"select"=>true); $db = & JFactory::getDBO(); $db = new JFDatabase($options); $debug = $conf->getValue('config.debug'); $db->debug($debug); if ($db->getErrorNum() > 2) { JError::raiseError('joomla.library:'.$db->getErrorNum(), 'JDatabase::getInstance: Could not connect to database <br/>' . $db->getErrorMsg() ); } $conf->setValue('config.mbf_content', 1 ); $conf->setValue('config.multilingual_support', 1 ); // legacy mode only // check on legacy mode on/off by testing existence of $database global if (defined('_JLEGACY') && array_key_exists('database',$GLOBALS)){ $GLOBALS['database'] = new mldatabase($options); $GLOBALS['database']->debug($conf->getValue('config.debug')); } //echo phpinfo(); } } } /** This function initialize the Joom!Fish manager in order to have * easy access and prepare certain information. * @access private */ function _jfInitialize ( ) { /* ToDo: check if we really need this any longer. Should be removed latest with 2.1 * @deprecated */ $GLOBALS[ '_JOOMFISH_MANAGER'] =& JoomFishManager::getInstance(); } }
gpl-2.0
tiberiusteng/financisto1-holo
app/src/main/java/ru/orangesoftware/financisto/activity/PayeeListActivity.java
1222
/******************************************************************************* * Copyright (c) 2010 Denis Solonenko. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * <p/> * Contributors: * Denis Solonenko - initial API and implementation ******************************************************************************/ package ru.orangesoftware.financisto.activity; import ru.orangesoftware.financisto.R; import ru.orangesoftware.financisto.blotter.BlotterFilter; import ru.orangesoftware.financisto.filter.Criteria; import ru.orangesoftware.financisto.model.Payee; public class PayeeListActivity extends MyEntityListActivity<Payee> { public PayeeListActivity() { super(Payee.class, R.string.no_payees); } @Override protected Class<? extends MyEntityActivity> getEditActivityClass() { return PayeeActivity.class; } @Override protected Criteria createBlotterCriteria(Payee p) { return Criteria.eq(BlotterFilter.PAYEE_ID, String.valueOf(p.id)); } }
gpl-2.0
automenta/corenlp
src/edu/stanford/nlp/util/CoreMaps.java
5205
package edu.stanford.nlp.util; import edu.stanford.nlp.ling.CoreAnnotation; import edu.stanford.nlp.ling.CoreLabel; import java.util.*; /** * Utility functions for working with {@link CoreMap}'s. * * @author dramage * @author Gabor Angeli (merge() method) */ public class CoreMaps { private CoreMaps() {} // static stuff /** * Merge one CoreMap into another -- that is, overwrite and add any keys in * the base CoreMap with those in the one to be merged. * This method is functional -- neither of the argument CoreMaps are changed. * @param base The CoreMap to serve as the base (keys in this are lower priority) * @param toBeMerged The CoreMap to merge in (keys in this are higher priority) * @return A new CoreMap representing the merge of the two inputs */ public static CoreMap merge(CoreMap base, CoreMap toBeMerged){ //(variables) CoreMap rtn = new DefaultCoreMap(base.size()); //(copy base) for(Class key : base.keySet()){ rtn.set(key, base.get(key)); } //(merge) for(Class key : toBeMerged.keySet()){ rtn.set(key,toBeMerged.get(key)); } //(return) return rtn; } // /** // * see merge(CoreMap base, CoreMap toBeMerged) // */ // public static CoreLabel merge(CoreLabel base, CoreLabel toBeMerged){ // //(variables) // CoreLabel rtn = new CoreLabel(base.size()); // //(copy base) // for(Map.Entry<Class<?>, Object> classObjectEntry : base.entrySet()){ // rtn.set(classObjectEntry.getKey(), classObjectEntry.getValue()); // } // //(merge) // for(Map.Entry<Class<?>, Object> classObjectEntry : toBeMerged.entrySet()){ // rtn.set(classObjectEntry.getKey(), classObjectEntry.getValue()); // } // //(return) // return rtn; // } /** * Returns a view of a collection of CoreMaps as a Map from each CoreMap to * the value it stores under valueKey. Changes to the map are propagated * directly to the coremaps in the collection and to the collection itself in * the case of removal operations. Keys added or removed from the given * collection by anything other than the returned map will leave the map * in an undefined state. */ public static <V, CM extends CoreMap, COLL extends Collection<CM>> Map<CM,V> asMap(final COLL coremaps, final Class<? extends TypesafeMap.Key<V>> valueKey) { final IdentityHashMap<CM,Boolean> references = new IdentityHashMap<>(); for(CM map : coremaps){ references.put(map, true); } // an EntrySet view of the elements of coremaps final Set<Map.Entry<CM, V>> entrySet = new AbstractSet<Map.Entry<CM,V>>() { @Override public Iterator<Map.Entry<CM, V>> iterator() { return new Iterator<Map.Entry<CM,V>>() { Iterator<CM> it = coremaps.iterator(); CM last = null; public boolean hasNext() { return it.hasNext(); } public Map.Entry<CM, V> next() { final CM next = it.next(); last = next; return new Map.Entry<CM,V>() { public CM getKey() { return next; } public V getValue() { return next.get(valueKey); } public V setValue(V value) { return next.set(valueKey, value); } }; } public void remove() { references.remove(last); it.remove(); } }; } @Override public int size() { return coremaps.size(); } }; return new AbstractMap<CM,V>() { @Override public int size() { return coremaps.size(); } @Override public boolean containsKey(Object key) { return coremaps.contains(key); } @Override public V get(Object key) { if (!references.containsKey(key)) { return null; } return ((CoreMap)key).get(valueKey); } @Override public V put(CM key, V value) { if (!references.containsKey(key)) { coremaps.add(key); references.put(key,true); } return key.set(valueKey, value); } @Override public V remove(Object key) { if (!references.containsKey(key)) { return null; } return coremaps.remove(key) ? ((CoreMap)key).get(valueKey) : null; } @Override public Set<Map.Entry<CM, V>> entrySet() { return entrySet; } }; } /** * Utility function for dumping all the keys and values of a CoreMap to a String. */ public static String dumpCoreMap(CoreMap cm) { StringBuilder sb = new StringBuilder(); dumpCoreMapToStringBuilder(cm, sb); return sb.toString(); } @SuppressWarnings("unchecked") public static void dumpCoreMapToStringBuilder(CoreMap cm, StringBuilder sb) { for (Class<?> rawKey : cm.keySet()) { Class<CoreAnnotation<Object>> key = (Class<CoreAnnotation<Object>>) rawKey; String className = key.getSimpleName(); Object value = cm.get(key); sb.append(className).append(": ").append(value).append('\n'); } } }
gpl-2.0
ACP3/cms
ACP3/Modules/ACP3/System/Resources/Assets/js/partials/polyfill.js
193
/* * Copyright (c) by the ACP3 Developers. * See the LICENSE file at the top-level module directory for licensing details. */ import "core-js/stable"; import "regenerator-runtime/runtime";
gpl-2.0
moulderr/pm
wp-content/themes/lucy/helpers/classes/output_ug.class.php
37216
<?php defined('_JEXEC') or die('Restricted access'); class UGMainOutput extends UniteOutputBaseUF{ protected static $serial = 0; private $page; protected $urlPlugin; private $pageHtmlID; private $pageID; protected $theme; private $putNoConflictMode = false; protected $putJsToBody = false; protected $isTilesType = false; protected $arrJsParamsAssoc = array(); const THEME_DEFAULT = "default"; const THEME_COMPACT = "compact"; const THEME_SLIDER = "slider"; const THEME_GRID = "grid"; const THEME_VIDEO = "video"; const THEME_TILES = "tiles"; const THEME_TILESGRID = "tilesgrid"; const THEME_CAROUSEL = "carousel"; const THEME_PAGE = "page"; /** * * construct the output object */ public function __construct(){ $this->init(); } /** * * init the page */ private function init(){ $urlBase = GlobalsUGPage::$urlBase; if(empty($urlBase)) UniteFunctionsUF::throwError("The page globals object not inited!"); $this->urlPlugin = GlobalsUG::$url_media_ug; } /** * get must fields that will be thrown from the settings anyway */ protected function getArrMustFields(){ $arrMustKeys = array( "category", "page_theme", "full_width", "page_width", "page_height", "position", "margin_top", "margin_bottom", "margin_left", "margin_right" ); return($arrMustKeys); } /** * * init page related variables */ protected function initPage($pageID){ self::$serial++; $this->page = new UniteFrameworkPage(); $this->page->initByID($pageID); //get real page id: $pageID = $this->page->getID(); $serial = self::$serial; $this->pageID = $pageID; $this->pageHtmlID = "ugdefault_{$pageID}_{$serial}"; $origParams = $this->page->getParams(); //set params for default settings get function $this->arrOriginalParams = $origParams; $defaultValues = $this->getDefautSettingsValues(); $origParams = UniteFunctionsUF::filterArrFields($origParams, $defaultValues, true); $this->arrOriginalParams = array_merge($defaultValues, $origParams); $arrMustKeys = $this->getArrMustFields(); $this->arrParams = UniteFunctionsUF::getDiffArrItems($this->arrOriginalParams, $defaultValues, $arrMustKeys); $this->modifyOptions(); } /** * modify options */ protected function modifyOptions(){ if($this->isTilesType == true){ //handle compact lightbox type options $lightboxType = $this->getParam("lightbox_type"); if($lightboxType == "compact"){ $this->renameOption("lightbox_compact_overlay_opacity", "lightbox_overlay_opacity", true); $this->renameOption("lightbox_compact_overlay_color", "lightbox_overlay_color", true); $this->renameOption("lightbox_compact_show_numbers", "lightbox_show_numbers", true); $this->renameOption("lightbox_compact_numbers_size", "lightbox_numbers_size", true); $this->renameOption("lightbox_compact_numbers_color", "lightbox_numbers_color", true); $this->renameOption("lightbox_compact_numbers_padding_top", "lightbox_numbers_padding_top", true); $this->renameOption("lightbox_compact_numbers_padding_right", "lightbox_numbers_padding_right", true); $this->renameOption("lightbox_compact_show_textpanel", "lightbox_show_textpanel", true); $this->renameOption("lightbox_compact_textpanel_source", "lightbox_textpanel_source", true); $this->renameOption("lightbox_compact_textpanel_title_color", "lightbox_textpanel_title_color", true); $this->renameOption("lightbox_compact_textpanel_title_font_size", "lightbox_textpanel_title_font_size", true); $this->renameOption("lightbox_compact_textpanel_title_bold", "lightbox_textpanel_title_bold", true); $this->renameOption("lightbox_compact_textpanel_padding_left", "lightbox_textpanel_padding_left", true); $this->renameOption("lightbox_compact_textpanel_padding_right", "lightbox_textpanel_padding_right", true); $this->renameOption("lightbox_compact_textpanel_padding_top", "lightbox_textpanel_padding_top", true); $this->renameOption("lightbox_compact_slider_image_border", "lightbox_slider_image_border", true); $this->renameOption("lightbox_compact_slider_image_border_width", "lightbox_slider_image_border_width", true); $this->renameOption("lightbox_compact_slider_image_border_color", "lightbox_slider_image_border_color", true); $this->renameOption("lightbox_compact_slider_image_border_radius", "lightbox_slider_image_border_radius", true); $this->renameOption("lightbox_compact_slider_image_shadow", "lightbox_slider_image_shadow", true); $this->deleteOption("lightbox_textpanel_title_text_align"); }else{ //delete all compact related options if exists $arrOptionsToDelete = array( "lightbox_compact_overlay_opacity", "lightbox_compact_overlay_color", "lightbox_compact_show_numbers", "lightbox_compact_numbers_size", "lightbox_compact_numbers_color", "lightbox_compact_numbers_padding_top", "lightbox_compact_numbers_padding_right", "lightbox_compact_show_textpanel", "lightbox_compact_textpanel_source", "lightbox_compact_textpanel_title_color", "lightbox_compact_textpanel_title_font_size", "lightbox_compact_textpanel_title_bold", "lightbox_compact_textpanel_padding_top", "lightbox_compact_textpanel_padding_left", "lightbox_compact_textpanel_padding_right", "lightbox_compact_slider_image_border", "lightbox_compact_slider_image_border_width", "lightbox_compact_slider_image_border_color", "lightbox_compact_slider_image_border_radius", "lightbox_compact_slider_image_shadow" ); $this->deleteOptions($arrOptionsToDelete); } //handle text panel source $lightboxSource = $this->getParam("lightbox_textpanel_source"); if($lightboxSource == "desc"){ $this->arrParams["lightbox_textpanel_enable_title"] = "false"; $this->arrParams["lightbox_textpanel_enable_description"] = "true"; $this->renameOption("lightbox_textpanel_title_color", "lightbox_textpanel_desc_color"); $this->renameOption("lightbox_textpanel_title_text_align", "lightbox_textpanel_desc_text_align"); $this->renameOption("lightbox_textpanel_title_font_size", "lightbox_textpanel_desc_font_size"); $this->renameOption("lightbox_textpanel_title_bold", "lightbox_textpanel_desc_bold"); } }else{ if($this->isParamExists("strippanel_background_transparent")){ $isTrans = $this->getParam("strippanel_background_transparent", self::FORCE_BOOLEAN); if($isTrans == true) $this->arrParams["strippanel_background_color"] = "transparent"; } } } /** * get array of skins that exists in the page */ protected function getArrActiveSkins($arrAddOptions = array()){ $pageSkin = $this->getParam("page_skin"); if(empty($pageSkin)) $pageSkin = "default"; $arrSkins = array($pageSkin=>true); $arrOptions = array( "strippanel_buttons_skin", "strippanel_handle_skin", "slider_bullets_skin", "slider_arrows_skin", "slider_play_button_skin", "slider_fullscreen_button_skin", "slider_zoompanel_skin" ); $arrOptions = array_merge($arrOptions, $arrAddOptions); foreach($arrOptions as $option){ $skin = $this->getParam($option); if(empty($skin)) continue; $arrSkins[$skin] = true; } return($arrSkins); } /** * * put page scripts */ protected function putScripts($putSkins = true){ //put jquery $includeJQuery = $this->getParam("include_jquery", self::FORCE_BOOLEAN); if($includeJQuery == true){ $urljQuery = GlobalsUG::$url_media_ug."js/jquery-11.0.min.js"; UniteProviderFunctionsUF::addjQueryInclude("unitepage", $urljQuery); } if($this->putJsToBody == false) HelperPageUF::addScriptAbsoluteUrl($this->urlPlugin."js/unitepage.min.js", "unitepage_main"); HelperPageUF::addStyleAbsoluteUrl($this->urlPlugin."css/unite-page.css","unite-page-css"); //include skins if($putSkins == true){ $arrSkins = $this->getArrActiveSkins(); foreach($arrSkins as $skin => $nothing){ if(empty($skin) || $skin == "default") continue; HelperPageUF::addStyleAbsoluteUrl($this->urlPlugin."skins/{$skin}/{$skin}.css","ug-skin-{$skin}"); } } } /** * get default settings values * get them only once */ protected function getDefautSettingsValues(){ require HelperPageUF::getFilepathSettings("page_settings"); return($valuesMerged); } /** * get params array defenitions that shouls be put as is from the settings */ protected function getArrJsOptions(){ $arr = array(); $arr[] = $this->buildJsParam("page_theme"); $arr[] = $this->buildJsParam("page_width", self::VALIDATE_SIZE, self::TYPE_SIZE); $arr[] = $this->buildJsParam("page_height", self::VALIDATE_SIZE, self::TYPE_SIZE); $arr[] = $this->buildJsParam("page_min_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("page_min_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("page_skin"); $arr[] = $this->buildJsParam("page_images_preload_type"); $arr[] = $this->buildJsParam("page_autoplay", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("page_play_interval", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("page_pause_on_mouseover", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("page_mousewheel_role"); $arr[] = $this->buildJsParam("page_control_keyboard", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("page_preserve_ratio", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("page_shuffle", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("page_debug_errors", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_background_color"); $arr[] = $this->buildJsParam("slider_background_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_scale_mode"); $arr[] = $this->buildJsParam("slider_scale_mode_media"); $arr[] = $this->buildJsParam("slider_scale_mode_fullscreen"); $arr[] = $this->buildJsParam("slider_transition"); $arr[] = $this->buildJsParam("slider_transition_speed", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_transition_easing"); $arr[] = $this->buildJsParam("slider_control_swipe", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_control_zoom", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_zoom_max_ratio", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_links", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_links_newpage", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_video_enable_closebutton", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_controls_always_on", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_controls_appear_ontap", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_controls_appear_duration", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_loader_type", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_loader_color"); $arr[] = $this->buildJsParam("slider_enable_bullets", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_bullets_skin"); $arr[] = $this->buildJsParam("slider_bullets_space_between", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_bullets_align_hor"); $arr[] = $this->buildJsParam("slider_bullets_align_vert"); $arr[] = $this->buildJsParam("slider_bullets_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_bullets_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_arrows", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_arrows_skin"); $arr[] = $this->buildJsParam("slider_arrow_left_align_hor"); $arr[] = $this->buildJsParam("slider_arrow_left_align_vert"); $arr[] = $this->buildJsParam("slider_arrow_left_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_arrow_left_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_arrow_right_align_hor"); $arr[] = $this->buildJsParam("slider_arrow_right_align_vert"); $arr[] = $this->buildJsParam("slider_arrow_right_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_arrow_right_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_progress_indicator", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_progress_indicator_type"); $arr[] = $this->buildJsParam("slider_progress_indicator_align_hor"); $arr[] = $this->buildJsParam("slider_progress_indicator_align_vert"); $arr[] = $this->buildJsParam("slider_progress_indicator_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progress_indicator_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progressbar_color"); $arr[] = $this->buildJsParam("slider_progressbar_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progressbar_line_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progresspie_color1"); $arr[] = $this->buildJsParam("slider_progresspie_color2"); $arr[] = $this->buildJsParam("slider_progresspie_stroke_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progresspie_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_progresspie_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_play_button", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_play_button_skin"); $arr[] = $this->buildJsParam("slider_play_button_align_hor"); $arr[] = $this->buildJsParam("slider_play_button_align_vert"); $arr[] = $this->buildJsParam("slider_play_button_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_play_button_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_fullscreen_button", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_fullscreen_button_skin"); $arr[] = $this->buildJsParam("slider_fullscreen_button_align_hor"); $arr[] = $this->buildJsParam("slider_fullscreen_button_align_vert"); $arr[] = $this->buildJsParam("slider_fullscreen_button_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_fullscreen_button_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_zoom_panel", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_zoompanel_skin"); $arr[] = $this->buildJsParam("slider_zoompanel_align_hor"); $arr[] = $this->buildJsParam("slider_zoompanel_align_vert"); $arr[] = $this->buildJsParam("slider_zoompanel_offset_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_zoompanel_offset_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_enable_text_panel", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_textpanel_always_on", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_textpanel_align"); $arr[] = $this->buildJsParam("slider_textpanel_margin", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_text_valign"); $arr[] = $this->buildJsParam("slider_textpanel_padding_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_padding_bottom", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_padding_title_description", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_padding_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_padding_left", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_fade_duration", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_enable_title", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_textpanel_enable_description", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_textpanel_enable_bg", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("slider_textpanel_bg_color"); $arr[] = $this->buildJsParam("slider_textpanel_bg_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("slider_textpanel_bg_css", null, self::TYPE_OBJECT); $arr[] = $this->buildJsParam("slider_textpanel_css_title", null, self::TYPE_OBJECT); $arr[] = $this->buildJsParam("slider_textpanel_css_description", null, self::TYPE_OBJECT); $arr[] = $this->buildJsParam("thumb_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_border_effect", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("thumb_border_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_border_color"); $arr[] = $this->buildJsParam("thumb_over_border_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_over_border_color"); $arr[] = $this->buildJsParam("thumb_selected_border_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_selected_border_color"); $arr[] = $this->buildJsParam("thumb_round_corners_radius", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_color_overlay_effect", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("thumb_overlay_color"); $arr[] = $this->buildJsParam("thumb_overlay_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_overlay_reverse", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("thumb_image_overlay_effect", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("thumb_image_overlay_type"); $arr[] = $this->buildJsParam("thumb_transition_duration", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("thumb_transition_easing"); $arr[] = $this->buildJsParam("thumb_show_loader", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("thumb_loader_type"); $arr[] = $this->buildJsParam("strippanel_padding_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_padding_bottom", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_padding_left", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_padding_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_enable_buttons", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("strippanel_buttons_skin"); $arr[] = $this->buildJsParam("strippanel_padding_buttons", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_buttons_role"); $arr[] = $this->buildJsParam("strippanel_enable_handle", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("strippanel_handle_align"); $arr[] = $this->buildJsParam("strippanel_handle_offset", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strippanel_handle_skin"); $arr[] = $this->buildJsParam("strippanel_background_color"); $arr[] = $this->buildJsParam("strip_thumbs_align"); $arr[] = $this->buildJsParam("strip_space_between_thumbs", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strip_thumb_touch_sensetivity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strip_scroll_to_thumb_duration", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("strip_scroll_to_thumb_easing"); $arr[] = $this->buildJsParam("strip_control_avia", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("strip_control_touch", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("gridpanel_vertical_scroll", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("gridpanel_grid_align"); $arr[] = $this->buildJsParam("gridpanel_padding_border_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_padding_border_bottom", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_padding_border_left", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_padding_border_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_arrows_skin"); $arr[] = $this->buildJsParam("gridpanel_arrows_align_vert"); $arr[] = $this->buildJsParam("gridpanel_arrows_padding_vert", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_arrows_align_hor"); $arr[] = $this->buildJsParam("gridpanel_arrows_padding_hor", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_space_between_arrows", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_arrows_always_on", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("gridpanel_enable_handle", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("gridpanel_handle_align"); $arr[] = $this->buildJsParam("gridpanel_handle_offset", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("gridpanel_handle_skin"); $arr[] = $this->buildJsParam("gridpanel_background_color"); $arr[] = $this->buildJsParam("grid_panes_direction"); $arr[] = $this->buildJsParam("grid_num_cols", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("grid_space_between_cols", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("grid_space_between_rows", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("grid_transition_duration", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("grid_transition_easing"); $arr[] = $this->buildJsParam("grid_carousel", null, self::TYPE_BOOLEAN); if($this->isTilesType == true){ $arr[] = $this->buildJsParam("tile_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_height", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_enable_border", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_border_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_border_color"); $arr[] = $this->buildJsParam("tile_border_radius", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_enable_outline", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_outline_color"); $arr[] = $this->buildJsParam("tile_enable_shadow", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_shadow_h", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_shadow_v", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_shadow_blur", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_shadow_spread", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_shadow_color"); $arr[] = $this->buildJsParam("tile_enable_action"); $arr[] = $this->buildJsParam("tile_as_link", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_link_newpage", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_enable_overlay", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_overlay_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_overlay_color"); $arr[] = $this->buildJsParam("tile_enable_icons", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_show_link_icon", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_space_between_icons", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_enable_image_effect", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_image_effect_type"); $arr[] = $this->buildJsParam("tile_image_effect_reverse", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_enable_textpanel", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_textpanel_source"); $arr[] = $this->buildJsParam("tile_textpanel_always_on", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("tile_textpanel_appear_type"); $arr[] = $this->buildJsParam("tile_textpanel_padding_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_padding_bottom", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_padding_left", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_padding_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_bg_color"); $arr[] = $this->buildJsParam("tile_textpanel_bg_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_title_color"); $arr[] = $this->buildJsParam("tile_textpanel_title_text_align"); $arr[] = $this->buildJsParam("tile_textpanel_title_font_size", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("tile_textpanel_title_bold", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_hide_arrows_onvideoplay", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_slider_control_zoom", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_overlay_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_overlay_color"); $arr[] = $this->buildJsParam("lightbox_top_panel_opacity", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_show_numbers", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_numbers_size", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_numbers_color"); $arr[] = $this->buildJsParam("lightbox_show_textpanel", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_textpanel_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_enable_title", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_textpanel_enable_description", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_textpanel_title_color"); $arr[] = $this->buildJsParam("lightbox_textpanel_title_text_align"); $arr[] = $this->buildJsParam("lightbox_textpanel_title_font_size", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_title_bold", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_textpanel_desc_color"); $arr[] = $this->buildJsParam("lightbox_textpanel_desc_text_align"); $arr[] = $this->buildJsParam("lightbox_textpanel_desc_font_size", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_desc_bold", null, self::TYPE_BOOLEAN); //lightbox compact related styles $arr[] = $this->buildJsParam("lightbox_type"); $arr[] = $this->buildJsParam("lightbox_arrows_position"); $arr[] = $this->buildJsParam("lightbox_arrows_inside_alwayson", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_numbers_padding_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_numbers_padding_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_padding_left", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_padding_right", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_textpanel_padding_top", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_slider_image_border", null, self::TYPE_BOOLEAN); $arr[] = $this->buildJsParam("lightbox_slider_image_border_width", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_slider_image_border_color"); $arr[] = $this->buildJsParam("lightbox_slider_image_border_radius", self::VALIDATE_NUMERIC, self::TYPE_NUMBER); $arr[] = $this->buildJsParam("lightbox_slider_image_shadow", null, self::TYPE_BOOLEAN); } //tiles type end return($arr); } /** * put error message instead of the page */ private function putErrorMessage(Exception $e, $prefix){ $message = $e->getMessage(); $trace = ""; if(GlobalsUG::SHOW_TRACE == true) $trace = $e->getTraceAsString(); $message = $prefix . ": ".$message; HelperUF::$operations->putModuleErrorMessage($message, $trace); ?> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery("<?php echo $this->pageHtmlID?>").show(); }); </script> <?php } /** * put javascript includes to the body before the page div */ protected function putJsIncludesToBody(){ $src = $this->urlPlugin."js/unitepage.min.js"; $html = "\n <script type='text/javascript' src='{$src}'></script>"; return($html); } /** * get video add html */ protected function getVideoAddHtml($type, $objItem){ $addHtml = ""; switch($type){ case UniteFrameworkItem::TYPE_YOUTUBE: case UniteFrameworkItem::TYPE_VIMEO: case UniteFrameworkItem::TYPE_WISTIA: $videoID = $objItem->getParam("videoid"); $addHtml .= "data-videoid=\"{$videoID}\" "; break; case UniteFrameworkItem::TYPE_HTML5VIDEO: $urlMp4 = $objItem->getParam("video_mp4"); $urlWebm = $objItem->getParam("video_webm"); $urlOgv = $objItem->getParam("video_ogv"); $addHtml .= "data-videomp4=\"{$urlMp4}\" "; $addHtml .= "data-videowebm=\"{$urlWebm}\" "; $addHtml .= "data-videoogv=\"{$urlOgv}\" "; break; } return($addHtml); } /** * put page items */ protected function putItems($arrItems){ $tab = " "; $nl = "\n".$tab; $thumbSize = ""; if($this->isTilesType){ $thumbSize = $this->getParam("tile_image_resolution"); } $totalHTML = ""; foreach($arrItems as $objItem): $urlImage = $objItem->getUrlImage(); $urlThumb = $objItem->getUrlThumb($thumbSize); $title = $objItem->getTitle(); $type = $objItem->getType(); $alt = $objItem->getAlt(); $description = $objItem->getParam("ug_item_description"); $enableLink = $objItem->getParam("ug_item_enable_link"); $enableLink = UniteFunctionsUF::strToBool($enableLink); //combine description if($enableLink == true){ $link = $objItem->getParam("ug_item_link"); /* if(!empty($link) && $this->isTilesType == false){ $isBlank = ($objItem->getParam("ug_item_link_open_in") == "new"); $htmlLink = UniteFunctionsUF::getHtmlLink($link, $link, "", "", $isBlank); $description .= " ".$htmlLink; } */ } $title = htmlspecialchars($title); $description = htmlspecialchars($description); $alt = htmlspecialchars($alt); $strType = ""; if($type != UniteFrameworkItem::TYPE_IMAGE){ $strType = "data-type=\"{$type}\" "; } $addHtml = $this->getVideoAddHtml($type, $objItem); //set link (on tiles mode) $linkStart = ""; $linkEnd = ""; if($enableLink == true){ $linkStart = "<a href=\"{$link}\">"; $linkEnd = "</a>"; } $html = "\n"; if($linkStart) $html .= $nl.$linkStart; $html .= $nl."<img alt=\"{$alt}\""; $html .= $nl." {$strType} src=\"{$urlThumb}\""; $html .= $nl." data-image=\"{$urlImage}\""; $html .= $nl." data-description=\"{$description}\""; $html .= $nl." {$addHtml}style=\"display:none\">"; if($linkEnd) $html .= $nl.$linkEnd; $totalHTML .= $html; endforeach; return($totalHTML); } /** * set page output options like put js to body etc. */ protected function setOutputOptions(){ $jsToBody = $this->getParam("js_to_body", self::FORCE_BOOLEAN); $this->putJsToBody = $jsToBody; } /** * * put the page */ public function putPage($pageID, $arrOptions = array(), $initType = "id"){ try{ $objCategories = new UniteFrameworkCategories(); $this->initPage($pageID); $this->setOutputOptions(); $this->putScripts(); if(isset($arrOptions["scriptsonly"])) return(false); //custom items pass if(is_array($arrOptions) && array_key_exists("items", $arrOptions)){ $arrItems = $arrOptions["items"]; }else{ //set page category $optCatID = UniteFunctionsUF::getVal($arrOptions, "categoryid"); if(!empty($optCatID) && $objCategories->isCatExists($optCatID)) $categoryID = $optCatID; else $categoryID = $this->getParam("category"); if(empty($categoryID)) UniteFunctionsUF::throwError(__("No items category selected", UNITEFRAMEWORK_TEXTDOMAIN)); $items = new UniteFrameworkItems(); $arrItems = $items->getCatItems($categoryID); } if(empty($arrItems)) UniteFunctionsUF::throwError("No page items found", UNITEFRAMEWORK_TEXTDOMAIN); //set wrapper style //size validation $this->getParam("page_width", self::FORCE_SIZE); if($this->isTilesType == false) $this->getParam("page_height", self::VALIDATE_NUMERIC); $fullWidth = $this->getParam("full_width", self::FORCE_BOOLEAN); if($fullWidth == true){ $this->arrParams["page_width"] = "100%"; } $wrapperStyle = $this->getPositionString(); //set position $jsOptions = $this->buildJsParams(); global $unitePageVersion; $output = " \n <!-- START UNITE PAGE {$unitePageVersion} --> "; if($this->putJsToBody == true) $output .= $this->putJsIncludesToBody(); $linePrefix = "\n "; $linePrefix2 = "\n "; $linePrefix3 = "\n "; $linePrefix4 = "\n "; $br = "\n"; $serial = self::$serial; $pageHtmlID = $this->pageHtmlID; $output .= $linePrefix."<div id='{$this->pageHtmlID}' style='{$wrapperStyle}'>"; $output .= $linePrefix2.$this->putItems($arrItems); $output .= $linePrefix."</div>"; $output .= $br; $output .= $linePrefix."<script type='text/javascript'>"; if($this->putNoConflictMode == true) $output .= $linePrefix2."jQuery.noConflict();"; $output .= $linePrefix2."var ugapi{$serial};"; $output .= $linePrefix2."jQuery(document).ready(function(){"; $output .= $linePrefix3."var objUGParams = {"; $output .= $linePrefix4.$jsOptions; $output .= $linePrefix3."};"; $output .= $linePrefix3."if(ugCheckForErrors('#{$pageHtmlID}', 'cms'))"; $output .= $linePrefix4."ugapi{$serial} = jQuery('#{$pageHtmlID}').unitepage(objUGParams);"; $output .= $linePrefix2."});"; $output .= $linePrefix."</script>"; $output .= $br; $output .= $linePrefix."<!-- END UNITEPAGE -->"; $compressOutput = $this->getParam("compress_output", self::FORCE_BOOLEAN); if($compressOutput == true){ $output = str_replace("\r", "", $output); $output = str_replace("\n", "", $output); $output = trim($output); } return $output; ?> <?php }catch(Exception $e){ $prefix = __("Unite Page Error",UNITEFRAMEWORK_TEXTDOMAIN); $this->putErrorMessage($e, $prefix); } } } ?>
gpl-2.0
alex-winter/totton-timber
administrator/components/com_hikashop/views/discount/tmpl/listing.php
7444
<?php /** * @package HikaShop for Joomla! * @version 2.3.4 * @author hikashop.com * @copyright (C) 2010-2014 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><div class="iframedoc" id="iframedoc"></div> <form action="index.php?option=<?php echo HIKASHOP_COMPONENT ?>&amp;ctrl=discount" method="post" name="adminForm" id="adminForm"> <table> <tr> <td width="100%"> <?php echo JText::_( 'FILTER' ); ?>: <input type="text" name="search" id="search" value="<?php echo $this->escape($this->pageInfo->search);?>" class="text_area" /> <button class="btn" onclick="document.adminForm.limitstart.value=0;this.form.submit();"><?php echo JText::_( 'GO' ); ?></button> <button class="btn" onclick="document.adminForm.limitstart.value=0;document.getElementById('search').value='';this.form.submit();"><?php echo JText::_( 'RESET' ); ?></button> </td> <td nowrap="nowrap"> <?php echo $this->filter_type->display('filter_type',$this->pageInfo->filter->filter_type); ?> </td> </tr> </table> <table id="hikashop_discount_listing" class="adminlist table table-striped table-hover" cellpadding="1"> <thead> <tr> <th class="title titlenum"> <?php echo JText::_( 'HIKA_NUM' );?> </th> <th class="title titlebox"> <input type="checkbox" name="toggle" value="" onclick="hikashop.checkAll(this);" /> </th> <th class="title"> <?php echo JHTML::_('grid.sort', JText::_('DISCOUNT_CODE'), 'a.discount_code', $this->pageInfo->filter->order->dir,$this->pageInfo->filter->order->value ); ?> </th> <th class="title"> <?php echo JHTML::_('grid.sort', JText::_('DISCOUNT_TYPE'), 'a.discount_type', $this->pageInfo->filter->order->dir,$this->pageInfo->filter->order->value ); ?> </th> <th class="title"> <?php echo JHTML::_('grid.sort', JText::_('DISCOUNT_START_DATE'), 'a.discount_start', $this->pageInfo->filter->order->dir,$this->pageInfo->filter->order->value ); ?> </th> <th class="title"> <?php echo JHTML::_('grid.sort', JText::_('DISCOUNT_END_DATE'), 'a.discount_end', $this->pageInfo->filter->order->dir,$this->pageInfo->filter->order->value ); ?> </th> <th class="title"> <?php echo JText::_('DISCOUNT_VALUE'); ?> </th> <?php if(hikashop_level(1)){ ?> <th class="title"> <?php echo JText::_('DISCOUNT_QUOTA'); ?> </th> <th class="title"> <?php echo JText::_('RESTRICTIONS'); ?> </th> <?php } ?> <th class="title titletoggle"> <?php echo JHTML::_('grid.sort', JText::_('HIKA_PUBLISHED'), 'a.discount_published', $this->pageInfo->filter->order->dir, $this->pageInfo->filter->order->value ); ?> </th> <th class="title"> <?php echo JHTML::_('grid.sort', JText::_( 'ID' ), 'a.discount_id', $this->pageInfo->filter->order->dir, $this->pageInfo->filter->order->value ); ?> </th> </tr> </thead> <tfoot> <tr> <td colspan="11"> <?php echo $this->pagination->getListFooter(); ?> <?php echo $this->pagination->getResultsCounter(); ?> </td> </tr> </tfoot> <tbody> <?php $k = 0; for($i = 0,$a = count($this->rows);$i<$a;$i++){ $row =& $this->rows[$i]; $publishedid = 'discount_published-'.$row->discount_id; ?> <tr class="<?php echo "row$k"; ?>"> <td align="center"> <?php echo $this->pagination->getRowOffset($i); ?> </td> <td align="center"> <?php echo JHTML::_('grid.id', $i, $row->discount_id ); ?> </td> <td> <?php if($this->manage){ ?> <a href="<?php echo hikashop_completeLink('discount&task=edit&cid[]='.$row->discount_id); ?>"> <?php } ?> <?php echo $row->discount_code; ?> <?php if($this->manage){ ?> </a> <?php } ?> </td> <td> <?php echo $row->discount_type; ?> </td> <td align="center"> <?php echo hikashop_getDate($row->discount_start); ?> </td> <td align="center"> <?php echo hikashop_getDate($row->discount_end); ?> </td> <td align="center"> <?php if(isset($row->discount_flat_amount) && $row->discount_flat_amount > 0){ echo $this->currencyHelper->displayPrices(array($row),'discount_flat_amount','discount_currency_id'); } elseif(isset($row->discount_percent_amount) && $row->discount_percent_amount > 0){ echo $row->discount_percent_amount. '%'; } ?> </td> <?php if(hikashop_level(1)){ ?> <td align="center"> <?php if(empty($row->discount_quota)){ echo JText::_('UNLIMITED'); }else{ echo $row->discount_quota. ' ('.JText::sprintf('X_LEFT',$row->discount_quota-$row->discount_used_times).')'; } ?> </td> <td> <?php $restrictions=array(); if(!empty($row->discount_minimum_order) && (float)$row->discount_minimum_order != 0){ $restrictions[]=JText::_('MINIMUM_ORDER_VALUE').':'.$this->currencyHelper->displayPrices(array($row),'discount_minimum_order','discount_currency_id'); } if(!empty($row->product_name)){ $restrictions[]=JText::_('PRODUCT').':'.$row->product_name; } if(!empty($row->category_name)){ $restriction=JText::_('CATEGORY').':'.$row->category_name; if($row->discount_category_childs){ $restriction.=' '.JText::_('INCLUDING_SUB_CATEGORIES'); } $restrictions[]=$restriction; } if(!empty($row->zone_name_english)){ $restrictions[]=JText::_('ZONE').':'.$row->zone_name_english; } if(!empty($row->username)){ $restrictions[]=JText::_('HIKA_USER').':'.$row->username; } if ($row->discount_type == 'coupon') { if (!empty($row->discount_coupon_product_only)) { $restrictions[]='Percentage for product only'; } if(!empty($row->discount_coupon_nodoubling)){ switch($row->discount_coupon_nodoubling) { case 1: $restrictions[]='Ignore discounted products'; break; case 2: $restrictions[]='Override discounted products'; break; default: break; } } } echo implode('<br/>',$restrictions); ?> </td> <?php } ?> <td align="center"> <?php if($this->manage){ ?> <span id="<?php echo $publishedid ?>" class="spanloading"><?php echo $this->toggleClass->toggle($publishedid,(int) $row->discount_published,'discount') ?></span> <?php }else{ echo $this->toggleClass->display('activate',$row->discount_published); } ?> </td> <td width="1%" align="center"> <?php echo $row->discount_id; ?> </td> </tr> <?php $k = 1-$k; } ?> </tbody> </table> <input type="hidden" name="option" value="<?php echo HIKASHOP_COMPONENT; ?>" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="ctrl" value="<?php echo JRequest::getCmd('ctrl'); ?>" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="filter_order" value="<?php echo $this->pageInfo->filter->order->value; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->pageInfo->filter->order->dir; ?>" /> <?php echo JHTML::_( 'form.token' ); ?> </form>
gpl-2.0
tgrimault/manorhouseporto.wp
wp-content/plugins/checkfront-wp-booking/checkfront.php
8458
<?php /* Plugin Name: Checkfront Online Booking System Plugin URI: http://www.checkfront.com/wordpress Description: Connects Wordpress to the Checkfront Online Booking, Reservation and Availability System. Checkfront integrates into popular payment systems including Paypal, Authorize.net, SagePay and integrates into Salesforce, Xero and Google Apps. Transactions, Reporting and Bookings are securly stored in the Checkfront backoffice app, while providing a self service booking portal on your own website. Version: 2.7.1 Author: Checkfront Inc. Author URI: http://www.checkfront.com/ Copyright: 2008 - 2013 Checkfront Inc */ if ( ! defined( 'WP_PLUGIN_URL' ) ) define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' ); /* ------------------------------------------------------ * Wordpress Required Functions /* ------------------------------------------------------*/ //Shortcode [clean-conract parameter="value"] function checkfront_func($cnf, $content=null) { $cnf=shortcode_atts(array( 'category_id' => '', 'item_id' => '', 'date' => '', 'tid' => '', 'discount' => '', 'options' => '', 'style' => '', 'host' => '', 'width' => '', 'theme' => '', ), $cnf); return checkfront($cnf); } // Global shortcode call function checkfront($cnf) { global $Checkfront; if(is_page() or is_single()) { // Wordpress will try and auto format paragraphs -- remove new lines return str_replace("\n",'',$Checkfront->render($cnf)); } } // Wordpress Admin Hook function checkfront_conf() { if ( function_exists('add_submenu_page') ) { add_submenu_page('plugins.php', __('Checkfront'), __('Checkfront'), 'manage_options', 'checkfront', 'checkfront_setup'); } add_filter('plugin_row_meta', 'checkfront_plugin_meta', 10, 2 ); } // Wordpress Setup Page function checkfront_setup() { global $Checkfront; wp_enqueue_script('jquery'); wp_enqueue_script(WP_PLUGIN_URL . '/setup.js'); include(dirname(__FILE__).'/setup.php'); } // Init Checkfront, include any required js / css only when required function checkfront_head() { $embedded = 0; $Checkfront->arg['widget'] = 0; global $post, $Checkfront; if(!isset($Checkfront->host)) return; // does this page have any shortcode. If not, back out. if($pos = stripos($post->post_content,'[checkfront') or $pos === 0) $embedded = 1; // calendar widget if($Checkfront->arg['widget']) { $checkfront_widget_post = get_option("checkfront_widget_post"); $checkfront_widget_page = get_option("checkfront_widget_page"); $checkfront_widget_booking = get_option("checkfront_widget_booking"); if($embedded and !$checkfront_widget_booking) { $Checkfront->arg['widget'] = 0; } else { if(is_page() and !$checkfront_widget_page) $Checkfront->arg['widget'] = 0; if(is_single() and !$checkfront_widget_post) $Checkfront->arg['widget'] = 0; } } if ($Checkfront->arg['widget'] or $embedded) { echo ' <script src="//' . $Checkfront->host . '/lib/interface--' . $Checkfront->interface_build . '.js" type="text/javascript"></script>' ."\n"; if($embedded) { // Disable Comments add_filter('comments_open', 'checkfront_comments_open_filter', 10, 2); add_filter('comments_template', 'checkfront_comments_template_filter', 10, 1); //disable auto p //remove_filter ('the_content', 'wpautop'); ////disable wptexturize remove_filter('the_content', 'wptexturize'); } } } // disable comments on booking pagfe function checkfront_comments_open_filter($open, $post_id=null) { return $open; } // disable comment include (required to clear) function checkfront_comments_template_filter($file) { return dirname(__FILE__).'/xcomments.html'; } // pligin init function checkfront_init() { global $Checkfront; wp_register_sidebar_widget('checkfront_widget', 'Checkfront', 'checkfront_widget',array('description' => __('Availability calendar and search'))); wp_register_widget_control('checkfront_widget', 'Checkfront', 'checkfront_widget_ctrl'); add_action('wp_head', 'checkfront_head'); # required includes wp_enqueue_script('jquery'); $Checkfront->arg['widget'] = (is_active_widget('checkfront_widget')) ? 1 : 0; } // Set admin meta function checkfront_plugin_meta($links, $file) { // create link if (basename($file,'.php') == 'checkfront') { return array_merge( $links, array( '<a href="plugins.php?page=checkfront">' . __('Setup') . '</a>', '<a href="http://www.checkfront.com/support/">' . __('Support') . '</a>', '<a href="https://www.checkfront.com/login/">' . __('Login') . '</a>', ) ); } return $links; } // Show widget function checkfront_widget() { global $Checkfront; if(!$Checkfront->arg['widget']) return; $checkfront_widget_title = get_option("checkfront_widget_title"); if($checkfront_book_url = get_option("checkfront_book_url")) { if(!(strpos('http',$checkfront_book_url) === 0)) { $checkfront_book_url = 'http://' . $_SERVER['HTTP_HOST'] . $checkfront_book_url; } } if(!empty($checkfront_widget_title)) echo '<h2 class="widgettitle">' . $checkfront_widget_title . '</h2>'; echo '<div id="checkfront-cal"><iframe allowTransparency=true border=0 style="border:0; height: 260px;" src="//' . $Checkfront->host . '/reserve/widget/calendar/?return=' . urlencode($checkfront_book_url) . '"></iframe></div>'; } // Widget control function checkfront_widget_ctrl() { if($_POST['checkfront_update']) { update_option("checkfront_book_url", $_POST['checkfront_book_url']); update_option("checkfront_widget_title", $_POST['checkfront_widget_title']); update_option("checkfront_widget_post ", $_POST['checkfront_widget_post']); update_option("checkfront_widget_page ", $_POST['checkfront_widget_page']); update_option("checkfront_widget_booking", $_POST['checkfront_widget_booking']); } $checkfront_book_url = get_option("checkfront_book_url"); // try and find booking page in content if(!$checkfront_book_url) { global $wpdb; $checkfront_book_url = $wpdb->get_var("select guid FROM `{$wpdb->prefix}posts` where post_content like '%[checkfront%' and post_type = 'page' limit 1"); update_option("checkfront_widget_url", $checkfront_book_url); } $checkfront_widget_title = get_option("checkfront_widget_title"); $checkfront_widget_post = (get_option("checkfront_widget_post")) ? ' checked="checked"' : ''; $checkfront_widget_page = (get_option("checkfront_widget_page")) ? ' checked="checked"' : ''; $checkfront_widget_booking = (get_option("checkfront_widget_booking")) ? ' checked="checked"' : ''; echo '<input type="hidden" name="checkfront_update" value="1" />'; echo '<ul>'; echo '<li><label for="checkfront_book_url">' . __('Internal Booking Page (URL)') . ': </label><input type="text" id="checkfront_book_url" name="checkfront_book_url" value="' . $checkfront_book_url . '" /> </li>'; echo '<li><label for="checkfront_widget_title">' . __('Title') . ': </label><input type="text" id="checkfront_widget_title" name="checkfront_widget_title" value="' . $checkfront_widget_title . '" /> </li>'; echo '<li style="color: firebrick">It is not recommended to use this with the v2 interface.</li>'; echo '<li><input type="checkbox" id="checkfront_widget_post" name="checkfront_widget_post" value="1"' . $checkfront_widget_post . '/><label for="checkfront_widget_post" />' . __('Show on posts') . '</li>'; echo '<li><input type="checkbox" id="checkfront_widget_page" name="checkfront_widget_page" value="1"' . $checkfront_widget_page . '/><label for="checkfront_widget_post" />' . __('Show on pages') . '</li>'; echo '<li><input type="checkbox" id="checkfront_widget_booking" name="checkfront_widget_booking" value="1"' . $checkfront_widget_booking . '/><label for="checkfront_widget_booking" />' . __('Show on booking page') . '</li>'; echo '</ul>'; } /* Create Checkront class. If you wish to include this in a custom theme (not shortcode) see the custom-theme-sample.php */ // Include Checkfront Widget Class include_once(dirname(__FILE__).'/CheckfrontWidget.php'); $Checkfront = new CheckfrontWidget( array( 'host'=>get_option('checkfront_host'), 'pipe_url'=>'/' . basename(WP_CONTENT_URL) . '/plugins/' .basename(dirname(__FILE__)) . '/pipe.html', 'provider' =>'wordpress', 'load_msg'=>__('Searching Availability'), 'continue_msg'=>__('Continue to Secure Booking System'), ) ); add_shortcode('checkfront', 'checkfront_func'); add_action('admin_menu', 'checkfront_conf'); add_action('init', 'checkfront_init'); ?>
gpl-2.0
Creativetech-Solutions/joomla-easysocial-network
plugins/system/crowdfundingmodules/postinstall.script.php
1951
<?php /** * @package Crowdfunding * @subpackage Plugins * @author Todor Iliev * @copyright Copyright (C) 2016 Todor Iliev <todor@itprism.com>. All rights reserved. * @license GNU General Public License version 3 or later; see LICENSE.txt */ // no direct access defined('_JEXEC') or die; /** * Post install script of the plugin. */ class plgSystemCrowdfundingModulesInstallerScript { /** * Method to install the component. * * @param string $parent * * @return void */ public function install($parent) { } /** * Method to uninstall the component. * * @param string $parent * * @return void */ public function uninstall($parent) { } /** * Method to update the component. * * @param string $parent * * @return void */ public function update($parent) { } /** * Method to run before an install/update/uninstall method. * * @param string $type * @param string $parent * * @return void */ public function preflight($type, $parent) { } /** * Method to run after an install/update/uninstall method. * * @param string $type * @param string $parent * * @return void */ public function postflight($type, $parent) { $db = JFactory::getDbo(); $query = $db->getQuery(true); $query ->update($db->quoteName('#__extensions')) ->set($db->quoteName('enabled') .' = 1') ->where($db->quoteName('element') .'='. $db->quote('crowdfundingmodules')) ->where($db->quoteName('type') .'='. $db->quote('plugin')) ->where($db->quoteName('folder') .'='. $db->quote('system')); $db->setQuery($query); $db->execute(); } }
gpl-2.0
cst316/spring16project-Team-Detroit
src/net/sf/memoranda/EmailContact.java
2631
/* File: EmailContact.java Author: Ryan Schultz Date: 2/4/2016 Description: Creates contacts */ package net.sf.memoranda; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Class: EmailContact Description: Creates contact with following attributes: name, email, phone, notes */ public class EmailContact implements Serializable { private static final long serialVersionUID = 7110740542273981533L; private String name; private String email; private String phone; private String notes; private String credentials; private String password; // Default Constructor public EmailContact() { } // User constructor public EmailContact(String name, String email, String password) { this.name = name; this.email = email; this.password = password; credentials = "User"; phone = ""; notes = ""; } // Normal contact constructor public EmailContact(String name, String email, String phone, String notes) { this.name = name; this.email = email; password = ""; credentials = ""; this.phone = phone; this.notes = notes; } // Supervisor contact constructor public EmailContact(String name, String email, String phone, String notes, String credentials) { this.name = name; this.email = email; password = ""; this.credentials = credentials; this.phone = phone; this.notes = notes; } // Getters/Setters public void setName(String name) { this.name = name; } public String getName() { return name; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setPhone(String phone) { this.phone = phone; } public String getPhone() { return phone; } public void setNotes(String notes) { this.notes = notes; } public String getNotes() { return notes; } public void setCredentials(String credentials) { this.credentials = credentials; } public String getCredentials() { return credentials; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } /** Method: validateEmail @param: email - contacts email address @return: true if valid email, false otherwise Description: Validates email entered for contact creation is valid */ public boolean validateEmail(String email) { String regex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(email); return matcher.matches(); } }
gpl-2.0
laoneo/joomla-pythagoras
tests/unit/ORM/Storage/Csv/CsvRelationTest.php
1465
<?php /** * Part of the Joomla Framework ORM Package Test Suite * * @copyright Copyright (C) 2015 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ namespace Joomla\Tests\Unit\ORM\Storage\Csv; use Joomla\ORM\Repository\Repository; use Joomla\ORM\Storage\Csv\CsvDataGateway; use Joomla\ORM\Storage\Csv\CsvDataMapper; use Joomla\ORM\Storage\Csv\CsvTransactor; use Joomla\Tests\Unit\ORM\Mocks\Detail; use Joomla\Tests\Unit\ORM\Mocks\Extra; use Joomla\Tests\Unit\ORM\Mocks\Master; use Joomla\Tests\Unit\ORM\Mocks\Tag; use Joomla\Tests\Unit\ORM\Storage\RelationTestCases; class CsvRelationTest extends RelationTestCases { protected function onBeforeSetup() { $dataPath = realpath(__DIR__ . '/../..'); $this->config = parse_ini_file($dataPath . '/data/entities.csv.ini', true); $this->connection = new CsvDataGateway($this->config['dataPath']); $this->transactor = new CsvTransactor($this->connection); } protected function onAfterSetUp() { $entities = [Master::class, Detail::class, Extra::class, Tag::class]; foreach ($entities as $className) { $meta = $this->builder->getMeta($className); $dataMapper = new CsvDataMapper( $this->connection, $className, $meta->storage['table'], $this->entityRegistry ); $this->repo[$className] = new Repository($className, $dataMapper, $this->unitOfWork); } } }
gpl-2.0
ismaelmelo/git-zapmetrics
02 - Prototipação/01 - Fontes/gc_resolucaoedit.php
44886
<?php if (session_id() == "") session_start(); // Initialize Session data ob_start(); // Turn on output buffering ?> <?php include_once "ewcfg10.php" ?> <?php include_once "adodb5/adodb.inc.php" ?> <?php include_once "phpfn10.php" ?> <?php include_once "gc_resolucaoinfo.php" ?> <?php include_once "usuarioinfo.php" ?> <?php include_once "userfn10.php" ?> <?php // // Page class // $gc_resolucao_edit = NULL; // Initialize page object first class cgc_resolucao_edit extends cgc_resolucao { // Page ID var $PageID = 'edit'; // Project ID var $ProjectID = "{F59C7BF3-F287-4BE0-9F86-FCB94F808AF8}"; // Table name var $TableName = 'gc_resolucao'; // Page object name var $PageObjName = 'gc_resolucao_edit'; // Page name function PageName() { return ew_CurrentPage(); } // Page URL function PageUrl() { $PageUrl = ew_CurrentPage() . "?"; if ($this->UseTokenInUrl) $PageUrl .= "t=" . $this->TableVar . "&"; // Add page token return $PageUrl; } // Message function getMessage() { return @$_SESSION[EW_SESSION_MESSAGE]; } function setMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_MESSAGE], $v); } function getFailureMessage() { return @$_SESSION[EW_SESSION_FAILURE_MESSAGE]; } function setFailureMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_FAILURE_MESSAGE], $v); } function getSuccessMessage() { return @$_SESSION[EW_SESSION_SUCCESS_MESSAGE]; } function setSuccessMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_SUCCESS_MESSAGE], $v); } function getWarningMessage() { return @$_SESSION[EW_SESSION_WARNING_MESSAGE]; } function setWarningMessage($v) { ew_AddMessage($_SESSION[EW_SESSION_WARNING_MESSAGE], $v); } // Show message function ShowMessage() { $hidden = FALSE; $html = ""; // Message $sMessage = $this->getMessage(); $this->Message_Showing($sMessage, ""); if ($sMessage <> "") { // Message in Session, display if (!$hidden) $sMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sMessage; $html .= "<div class=\"alert alert-success ewSuccess\">" . $sMessage . "</div>"; $_SESSION[EW_SESSION_MESSAGE] = ""; // Clear message in Session } // Warning message $sWarningMessage = $this->getWarningMessage(); $this->Message_Showing($sWarningMessage, "warning"); if ($sWarningMessage <> "") { // Message in Session, display if (!$hidden) $sWarningMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sWarningMessage; $html .= "<div class=\"alert alert-warning ewWarning\">" . $sWarningMessage . "</div>"; $_SESSION[EW_SESSION_WARNING_MESSAGE] = ""; // Clear message in Session } // Success message $sSuccessMessage = $this->getSuccessMessage(); $this->Message_Showing($sSuccessMessage, "success"); if ($sSuccessMessage <> "") { // Message in Session, display if (!$hidden) $sSuccessMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sSuccessMessage; $html .= "<div class=\"alert alert-success ewSuccess\">" . $sSuccessMessage . "</div>"; $_SESSION[EW_SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session } // Failure message $sErrorMessage = $this->getFailureMessage(); $this->Message_Showing($sErrorMessage, "failure"); if ($sErrorMessage <> "") { // Message in Session, display if (!$hidden) $sErrorMessage = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>" . $sErrorMessage; $html .= "<div class=\"alert alert-error ewError\">" . $sErrorMessage . "</div>"; $_SESSION[EW_SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session } echo "<table class=\"ewStdTable\"><tr><td><div class=\"ewMessageDialog\"" . (($hidden) ? " style=\"display: none;\"" : "") . ">" . $html . "</div></td></tr></table>"; } var $PageHeader; var $PageFooter; // Show Page Header function ShowPageHeader() { $sHeader = $this->PageHeader; $this->Page_DataRendering($sHeader); if ($sHeader <> "") { // Header exists, display echo "<p>" . $sHeader . "</p>"; } } // Show Page Footer function ShowPageFooter() { $sFooter = $this->PageFooter; $this->Page_DataRendered($sFooter); if ($sFooter <> "") { // Footer exists, display echo "<p>" . $sFooter . "</p>"; } } // Validate page request function IsPageRequest() { global $objForm; if ($this->UseTokenInUrl) { if ($objForm) return ($this->TableVar == $objForm->GetValue("t")); if (@$_GET["t"] <> "") return ($this->TableVar == $_GET["t"]); } else { return TRUE; } } // // Page class constructor // function __construct() { global $conn, $Language, $UserAgent; // User agent $UserAgent = ew_UserAgent(); $GLOBALS["Page"] = &$this; // Language object if (!isset($Language)) $Language = new cLanguage(); // Parent constuctor parent::__construct(); // Table object (gc_resolucao) if (!isset($GLOBALS["gc_resolucao"])) { $GLOBALS["gc_resolucao"] = &$this; $GLOBALS["Table"] = &$GLOBALS["gc_resolucao"]; } // Table object (usuario) if (!isset($GLOBALS['usuario'])) $GLOBALS['usuario'] = new cusuario(); // Page ID if (!defined("EW_PAGE_ID")) define("EW_PAGE_ID", 'edit', TRUE); // Table name (for backward compatibility) if (!defined("EW_TABLE_NAME")) define("EW_TABLE_NAME", 'gc_resolucao', TRUE); // Start timer if (!isset($GLOBALS["gTimer"])) $GLOBALS["gTimer"] = new cTimer(); // Open connection if (!isset($conn)) $conn = ew_Connect(); } // // Page_Init // function Page_Init() { global $gsExport, $gsExportFile, $UserProfile, $Language, $Security, $objForm; // User profile $UserProfile = new cUserProfile(); $UserProfile->LoadProfile(@$_SESSION[EW_SESSION_USER_PROFILE]); // Security $Security = new cAdvancedSecurity(); if (IsPasswordExpired()) $this->Page_Terminate("changepwd.php"); if (!$Security->IsLoggedIn()) $Security->AutoLogin(); if (!$Security->IsLoggedIn()) { $Security->SaveLastUrl(); $this->Page_Terminate("login.php"); } $Security->TablePermission_Loading(); $Security->LoadCurrentUserLevel($this->ProjectID . $this->TableName); $Security->TablePermission_Loaded(); if (!$Security->IsLoggedIn()) { $Security->SaveLastUrl(); $this->Page_Terminate("login.php"); } if (!$Security->CanEdit()) { $Security->SaveLastUrl(); $this->setFailureMessage($Language->Phrase("NoPermission")); // Set no permission $this->Page_Terminate("gc_resolucaolist.php"); } $Security->UserID_Loading(); if ($Security->IsLoggedIn()) $Security->LoadUserID(); $Security->UserID_Loaded(); // Create form object $objForm = new cFormObj(); $this->CurrentAction = (@$_GET["a"] <> "") ? $_GET["a"] : @$_POST["a_list"]; // Set up curent action // Global Page Loading event (in userfn*.php) Page_Loading(); // Page Load event $this->Page_Load(); } // // Page_Terminate // function Page_Terminate($url = "") { global $conn; // Page Unload event $this->Page_Unload(); // Global Page Unloaded event (in userfn*.php) Page_Unloaded(); $this->Page_Redirecting($url); // Close connection $conn->Close(); // Go to URL if specified if ($url <> "") { if (!EW_DEBUG_ENABLED && ob_get_length()) ob_end_clean(); header("Location: " . $url); } exit(); } var $DbMasterFilter; var $DbDetailFilter; // // Page main // function Page_Main() { global $objForm, $Language, $gsFormError; // Load key from QueryString if (@$_GET["nu_resolucao"] <> "") { $this->nu_resolucao->setQueryStringValue($_GET["nu_resolucao"]); } // Set up Breadcrumb $this->SetupBreadcrumb(); // Process form if post back if (@$_POST["a_edit"] <> "") { $this->CurrentAction = $_POST["a_edit"]; // Get action code $this->LoadFormValues(); // Get form values } else { $this->CurrentAction = "I"; // Default action is display } // Check if valid key if ($this->nu_resolucao->CurrentValue == "") $this->Page_Terminate("gc_resolucaolist.php"); // Invalid key, return to list // Validate form if post back if (@$_POST["a_edit"] <> "") { if (!$this->ValidateForm()) { $this->CurrentAction = ""; // Form error, reset action $this->setFailureMessage($gsFormError); $this->EventCancelled = TRUE; // Event cancelled $this->RestoreFormValues(); } } switch ($this->CurrentAction) { case "I": // Get a record to display if (!$this->LoadRow()) { // Load record based on key if ($this->getFailureMessage() == "") $this->setFailureMessage($Language->Phrase("NoRecord")); // No record found $this->Page_Terminate("gc_resolucaolist.php"); // No matching record, return to list } break; Case "U": // Update $this->SendEmail = TRUE; // Send email on update success if ($this->EditRow()) { // Update record based on key if ($this->getSuccessMessage() == "") $this->setSuccessMessage($Language->Phrase("UpdateSuccess")); // Update success $sReturnUrl = $this->getReturnUrl(); if (ew_GetPageName($sReturnUrl) == "gc_resolucaoview.php") $sReturnUrl = $this->GetViewUrl(); // View paging, return to View page directly $this->Page_Terminate($sReturnUrl); // Return to caller } else { $this->EventCancelled = TRUE; // Event cancelled $this->RestoreFormValues(); // Restore form values if update failed } } // Render the record $this->RowType = EW_ROWTYPE_EDIT; // Render as Edit $this->ResetAttrs(); $this->RenderRow(); } // Set up starting record parameters function SetUpStartRec() { if ($this->DisplayRecs == 0) return; if ($this->IsPageRequest()) { // Validate request if (@$_GET[EW_TABLE_START_REC] <> "") { // Check for "start" parameter $this->StartRec = $_GET[EW_TABLE_START_REC]; $this->setStartRecordNumber($this->StartRec); } elseif (@$_GET[EW_TABLE_PAGE_NO] <> "") { $PageNo = $_GET[EW_TABLE_PAGE_NO]; if (is_numeric($PageNo)) { $this->StartRec = ($PageNo-1)*$this->DisplayRecs+1; if ($this->StartRec <= 0) { $this->StartRec = 1; } elseif ($this->StartRec >= intval(($this->TotalRecs-1)/$this->DisplayRecs)*$this->DisplayRecs+1) { $this->StartRec = intval(($this->TotalRecs-1)/$this->DisplayRecs)*$this->DisplayRecs+1; } $this->setStartRecordNumber($this->StartRec); } } } $this->StartRec = $this->getStartRecordNumber(); // Check if correct start record counter if (!is_numeric($this->StartRec) || $this->StartRec == "") { // Avoid invalid start record counter $this->StartRec = 1; // Reset start record counter $this->setStartRecordNumber($this->StartRec); } elseif (intval($this->StartRec) > intval($this->TotalRecs)) { // Avoid starting record > total records $this->StartRec = intval(($this->TotalRecs-1)/$this->DisplayRecs)*$this->DisplayRecs+1; // Point to last page first record $this->setStartRecordNumber($this->StartRec); } elseif (($this->StartRec-1) % $this->DisplayRecs <> 0) { $this->StartRec = intval(($this->StartRec-1)/$this->DisplayRecs)*$this->DisplayRecs+1; // Point to page boundary $this->setStartRecordNumber($this->StartRec); } } // Get upload files function GetUploadFiles() { global $objForm; // Get upload data $this->im_anexo->Upload->Index = $objForm->Index; if ($this->im_anexo->Upload->UploadFile()) { // No action required } else { echo $this->im_anexo->Upload->Message; $this->Page_Terminate(); exit(); } $this->im_anexo->CurrentValue = $this->im_anexo->Upload->FileName; } // Load form values function LoadFormValues() { // Load from form global $objForm; $this->GetUploadFiles(); // Get upload files if (!$this->nu_grupoOuComite->FldIsDetailKey) { $this->nu_grupoOuComite->setFormValue($objForm->GetValue("x_nu_grupoOuComite")); } if (!$this->ds_resolucao->FldIsDetailKey) { $this->ds_resolucao->setFormValue($objForm->GetValue("x_ds_resolucao")); } if (!$this->no_local->FldIsDetailKey) { $this->no_local->setFormValue($objForm->GetValue("x_no_local")); } if (!$this->dt_publicacao->FldIsDetailKey) { $this->dt_publicacao->setFormValue($objForm->GetValue("x_dt_publicacao")); $this->dt_publicacao->CurrentValue = ew_UnFormatDateTime($this->dt_publicacao->CurrentValue, 7); } if (!$this->ic_situacao->FldIsDetailKey) { $this->ic_situacao->setFormValue($objForm->GetValue("x_ic_situacao")); } if (!$this->nu_resolucao->FldIsDetailKey) $this->nu_resolucao->setFormValue($objForm->GetValue("x_nu_resolucao")); } // Restore form values function RestoreFormValues() { global $objForm; $this->LoadRow(); $this->nu_resolucao->CurrentValue = $this->nu_resolucao->FormValue; $this->nu_grupoOuComite->CurrentValue = $this->nu_grupoOuComite->FormValue; $this->ds_resolucao->CurrentValue = $this->ds_resolucao->FormValue; $this->no_local->CurrentValue = $this->no_local->FormValue; $this->dt_publicacao->CurrentValue = $this->dt_publicacao->FormValue; $this->dt_publicacao->CurrentValue = ew_UnFormatDateTime($this->dt_publicacao->CurrentValue, 7); $this->ic_situacao->CurrentValue = $this->ic_situacao->FormValue; } // Load row based on key values function LoadRow() { global $conn, $Security, $Language; $sFilter = $this->KeyFilter(); // Call Row Selecting event $this->Row_Selecting($sFilter); // Load SQL based on filter $this->CurrentFilter = $sFilter; $sSql = $this->SQL(); $res = FALSE; $rs = ew_LoadRecordset($sSql); if ($rs && !$rs->EOF) { $res = TRUE; $this->LoadRowValues($rs); // Load row values $rs->Close(); } return $res; } // Load row values from recordset function LoadRowValues(&$rs) { global $conn; if (!$rs || $rs->EOF) return; // Call Row Selected event $row = &$rs->fields; $this->Row_Selected($row); $this->nu_resolucao->setDbValue($rs->fields('nu_resolucao')); $this->nu_grupoOuComite->setDbValue($rs->fields('nu_grupoOuComite')); $this->ds_resolucao->setDbValue($rs->fields('ds_resolucao')); $this->no_local->setDbValue($rs->fields('no_local')); $this->im_anexo->Upload->DbValue = $rs->fields('im_anexo'); $this->dt_publicacao->setDbValue($rs->fields('dt_publicacao')); $this->ic_situacao->setDbValue($rs->fields('ic_situacao')); $this->nu_usuario->setDbValue($rs->fields('nu_usuario')); $this->ts_datahora->setDbValue($rs->fields('ts_datahora')); } // Load DbValue from recordset function LoadDbValues(&$rs) { if (!$rs || !is_array($rs) && $rs->EOF) return; $row = is_array($rs) ? $rs : $rs->fields; $this->nu_resolucao->DbValue = $row['nu_resolucao']; $this->nu_grupoOuComite->DbValue = $row['nu_grupoOuComite']; $this->ds_resolucao->DbValue = $row['ds_resolucao']; $this->no_local->DbValue = $row['no_local']; $this->im_anexo->Upload->DbValue = $row['im_anexo']; $this->dt_publicacao->DbValue = $row['dt_publicacao']; $this->ic_situacao->DbValue = $row['ic_situacao']; $this->nu_usuario->DbValue = $row['nu_usuario']; $this->ts_datahora->DbValue = $row['ts_datahora']; } // Render row values based on field settings function RenderRow() { global $conn, $Security, $Language; global $gsLanguage; // Initialize URLs // Call Row_Rendering event $this->Row_Rendering(); // Common render codes for all row types // nu_resolucao // nu_grupoOuComite // ds_resolucao // no_local // im_anexo // dt_publicacao // ic_situacao // nu_usuario // ts_datahora if ($this->RowType == EW_ROWTYPE_VIEW) { // View row // nu_resolucao $this->nu_resolucao->ViewValue = $this->nu_resolucao->CurrentValue; $this->nu_resolucao->ViewCustomAttributes = ""; // nu_grupoOuComite if (strval($this->nu_grupoOuComite->CurrentValue) <> "") { $sFilterWrk = "[nu_gpComite]" . ew_SearchString("=", $this->nu_grupoOuComite->CurrentValue, EW_DATATYPE_NUMBER); $sSqlWrk = "SELECT [nu_gpComite], [no_gpComite] AS [DispFld], '' AS [Disp2Fld], '' AS [Disp3Fld], '' AS [Disp4Fld] FROM [dbo].[gpcomite]"; $sWhereWrk = ""; if ($sFilterWrk <> "") { ew_AddFilter($sWhereWrk, $sFilterWrk); } // Call Lookup selecting $this->Lookup_Selecting($this->nu_grupoOuComite, $sWhereWrk); if ($sWhereWrk <> "") $sSqlWrk .= " WHERE " . $sWhereWrk; $rswrk = $conn->Execute($sSqlWrk); if ($rswrk && !$rswrk->EOF) { // Lookup values found $this->nu_grupoOuComite->ViewValue = $rswrk->fields('DispFld'); $rswrk->Close(); } else { $this->nu_grupoOuComite->ViewValue = $this->nu_grupoOuComite->CurrentValue; } } else { $this->nu_grupoOuComite->ViewValue = NULL; } $this->nu_grupoOuComite->ViewCustomAttributes = ""; // ds_resolucao $this->ds_resolucao->ViewValue = $this->ds_resolucao->CurrentValue; $this->ds_resolucao->ViewCustomAttributes = ""; // no_local $this->no_local->ViewValue = $this->no_local->CurrentValue; $this->no_local->ViewCustomAttributes = ""; // im_anexo $this->im_anexo->UploadPath = "arquivos/resolucoes"; if (!ew_Empty($this->im_anexo->Upload->DbValue)) { $this->im_anexo->ViewValue = $this->im_anexo->Upload->DbValue; } else { $this->im_anexo->ViewValue = ""; } $this->im_anexo->ViewCustomAttributes = ""; // dt_publicacao $this->dt_publicacao->ViewValue = $this->dt_publicacao->CurrentValue; $this->dt_publicacao->ViewValue = ew_FormatDateTime($this->dt_publicacao->ViewValue, 7); $this->dt_publicacao->ViewCustomAttributes = ""; // ic_situacao if (strval($this->ic_situacao->CurrentValue) <> "") { switch ($this->ic_situacao->CurrentValue) { case $this->ic_situacao->FldTagValue(1): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(1) <> "" ? $this->ic_situacao->FldTagCaption(1) : $this->ic_situacao->CurrentValue; break; case $this->ic_situacao->FldTagValue(2): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(2) <> "" ? $this->ic_situacao->FldTagCaption(2) : $this->ic_situacao->CurrentValue; break; case $this->ic_situacao->FldTagValue(3): $this->ic_situacao->ViewValue = $this->ic_situacao->FldTagCaption(3) <> "" ? $this->ic_situacao->FldTagCaption(3) : $this->ic_situacao->CurrentValue; break; default: $this->ic_situacao->ViewValue = $this->ic_situacao->CurrentValue; } } else { $this->ic_situacao->ViewValue = NULL; } $this->ic_situacao->ViewCustomAttributes = ""; // nu_usuario $this->nu_usuario->ViewValue = $this->nu_usuario->CurrentValue; $this->nu_usuario->ViewCustomAttributes = ""; // ts_datahora $this->ts_datahora->ViewValue = $this->ts_datahora->CurrentValue; $this->ts_datahora->ViewValue = ew_FormatDateTime($this->ts_datahora->ViewValue, 7); $this->ts_datahora->ViewCustomAttributes = ""; // nu_grupoOuComite $this->nu_grupoOuComite->LinkCustomAttributes = ""; $this->nu_grupoOuComite->HrefValue = ""; $this->nu_grupoOuComite->TooltipValue = ""; // ds_resolucao $this->ds_resolucao->LinkCustomAttributes = ""; $this->ds_resolucao->HrefValue = ""; $this->ds_resolucao->TooltipValue = ""; // no_local $this->no_local->LinkCustomAttributes = ""; $this->no_local->HrefValue = ""; $this->no_local->TooltipValue = ""; // im_anexo $this->im_anexo->LinkCustomAttributes = ""; $this->im_anexo->HrefValue = ""; $this->im_anexo->HrefValue2 = $this->im_anexo->UploadPath . $this->im_anexo->Upload->DbValue; $this->im_anexo->TooltipValue = ""; // dt_publicacao $this->dt_publicacao->LinkCustomAttributes = ""; $this->dt_publicacao->HrefValue = ""; $this->dt_publicacao->TooltipValue = ""; // ic_situacao $this->ic_situacao->LinkCustomAttributes = ""; $this->ic_situacao->HrefValue = ""; $this->ic_situacao->TooltipValue = ""; } elseif ($this->RowType == EW_ROWTYPE_EDIT) { // Edit row // nu_grupoOuComite $this->nu_grupoOuComite->EditCustomAttributes = ""; $sFilterWrk = ""; $sSqlWrk = "SELECT [nu_gpComite], [no_gpComite] AS [DispFld], '' AS [Disp2Fld], '' AS [Disp3Fld], '' AS [Disp4Fld], '' AS [SelectFilterFld], '' AS [SelectFilterFld2], '' AS [SelectFilterFld3], '' AS [SelectFilterFld4] FROM [dbo].[gpcomite]"; $sWhereWrk = ""; if ($sFilterWrk <> "") { ew_AddFilter($sWhereWrk, $sFilterWrk); } // Call Lookup selecting $this->Lookup_Selecting($this->nu_grupoOuComite, $sWhereWrk); if ($sWhereWrk <> "") $sSqlWrk .= " WHERE " . $sWhereWrk; $rswrk = $conn->Execute($sSqlWrk); $arwrk = ($rswrk) ? $rswrk->GetRows() : array(); if ($rswrk) $rswrk->Close(); array_unshift($arwrk, array("", $Language->Phrase("PleaseSelect"), "", "", "", "", "", "", "")); $this->nu_grupoOuComite->EditValue = $arwrk; // ds_resolucao $this->ds_resolucao->EditCustomAttributes = ""; $this->ds_resolucao->EditValue = $this->ds_resolucao->CurrentValue; $this->ds_resolucao->PlaceHolder = ew_HtmlEncode(ew_RemoveHtml($this->ds_resolucao->FldCaption())); // no_local $this->no_local->EditCustomAttributes = ""; $this->no_local->EditValue = ew_HtmlEncode($this->no_local->CurrentValue); $this->no_local->PlaceHolder = ew_HtmlEncode(ew_RemoveHtml($this->no_local->FldCaption())); // im_anexo $this->im_anexo->EditCustomAttributes = ""; $this->im_anexo->UploadPath = "arquivos/resolucoes"; if (!ew_Empty($this->im_anexo->Upload->DbValue)) { $this->im_anexo->EditValue = $this->im_anexo->Upload->DbValue; } else { $this->im_anexo->EditValue = ""; } if ($this->CurrentAction == "I" && !$this->EventCancelled) ew_RenderUploadField($this->im_anexo); // dt_publicacao $this->dt_publicacao->EditCustomAttributes = ""; $this->dt_publicacao->EditValue = ew_HtmlEncode(ew_FormatDateTime($this->dt_publicacao->CurrentValue, 7)); $this->dt_publicacao->PlaceHolder = ew_HtmlEncode(ew_RemoveHtml($this->dt_publicacao->FldCaption())); // ic_situacao $this->ic_situacao->EditCustomAttributes = ""; $arwrk = array(); $arwrk[] = array($this->ic_situacao->FldTagValue(1), $this->ic_situacao->FldTagCaption(1) <> "" ? $this->ic_situacao->FldTagCaption(1) : $this->ic_situacao->FldTagValue(1)); $arwrk[] = array($this->ic_situacao->FldTagValue(2), $this->ic_situacao->FldTagCaption(2) <> "" ? $this->ic_situacao->FldTagCaption(2) : $this->ic_situacao->FldTagValue(2)); $arwrk[] = array($this->ic_situacao->FldTagValue(3), $this->ic_situacao->FldTagCaption(3) <> "" ? $this->ic_situacao->FldTagCaption(3) : $this->ic_situacao->FldTagValue(3)); array_unshift($arwrk, array("", $Language->Phrase("PleaseSelect"))); $this->ic_situacao->EditValue = $arwrk; // Edit refer script // nu_grupoOuComite $this->nu_grupoOuComite->HrefValue = ""; // ds_resolucao $this->ds_resolucao->HrefValue = ""; // no_local $this->no_local->HrefValue = ""; // im_anexo $this->im_anexo->HrefValue = ""; $this->im_anexo->HrefValue2 = $this->im_anexo->UploadPath . $this->im_anexo->Upload->DbValue; // dt_publicacao $this->dt_publicacao->HrefValue = ""; // ic_situacao $this->ic_situacao->HrefValue = ""; } if ($this->RowType == EW_ROWTYPE_ADD || $this->RowType == EW_ROWTYPE_EDIT || $this->RowType == EW_ROWTYPE_SEARCH) { // Add / Edit / Search row $this->SetupFieldTitles(); } // Call Row Rendered event if ($this->RowType <> EW_ROWTYPE_AGGREGATEINIT) $this->Row_Rendered(); } // Validate form function ValidateForm() { global $Language, $gsFormError; // Initialize form error message $gsFormError = ""; // Check if validation required if (!EW_SERVER_VALIDATE) return ($gsFormError == ""); if (!$this->nu_grupoOuComite->FldIsDetailKey && !is_null($this->nu_grupoOuComite->FormValue) && $this->nu_grupoOuComite->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->nu_grupoOuComite->FldCaption()); } if (!$this->ds_resolucao->FldIsDetailKey && !is_null($this->ds_resolucao->FormValue) && $this->ds_resolucao->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->ds_resolucao->FldCaption()); } if (!$this->no_local->FldIsDetailKey && !is_null($this->no_local->FormValue) && $this->no_local->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->no_local->FldCaption()); } if (!$this->dt_publicacao->FldIsDetailKey && !is_null($this->dt_publicacao->FormValue) && $this->dt_publicacao->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->dt_publicacao->FldCaption()); } if (!ew_CheckEuroDate($this->dt_publicacao->FormValue)) { ew_AddMessage($gsFormError, $this->dt_publicacao->FldErrMsg()); } if (!$this->ic_situacao->FldIsDetailKey && !is_null($this->ic_situacao->FormValue) && $this->ic_situacao->FormValue == "") { ew_AddMessage($gsFormError, $Language->Phrase("EnterRequiredField") . " - " . $this->ic_situacao->FldCaption()); } // Return validate result $ValidateForm = ($gsFormError == ""); // Call Form_CustomValidate event $sFormCustomError = ""; $ValidateForm = $ValidateForm && $this->Form_CustomValidate($sFormCustomError); if ($sFormCustomError <> "") { ew_AddMessage($gsFormError, $sFormCustomError); } return $ValidateForm; } // Update record based on key values function EditRow() { global $conn, $Security, $Language; $sFilter = $this->KeyFilter(); $this->CurrentFilter = $sFilter; $sSql = $this->SQL(); $conn->raiseErrorFn = 'ew_ErrorFn'; $rs = $conn->Execute($sSql); $conn->raiseErrorFn = ''; if ($rs === FALSE) return FALSE; if ($rs->EOF) { $EditRow = FALSE; // Update Failed } else { // Save old values $rsold = &$rs->fields; $this->LoadDbValues($rsold); $this->im_anexo->OldUploadPath = "arquivos/resolucoes"; $this->im_anexo->UploadPath = $this->im_anexo->OldUploadPath; $rsnew = array(); // nu_grupoOuComite $this->nu_grupoOuComite->SetDbValueDef($rsnew, $this->nu_grupoOuComite->CurrentValue, NULL, $this->nu_grupoOuComite->ReadOnly); // ds_resolucao $this->ds_resolucao->SetDbValueDef($rsnew, $this->ds_resolucao->CurrentValue, "", $this->ds_resolucao->ReadOnly); // no_local $this->no_local->SetDbValueDef($rsnew, $this->no_local->CurrentValue, "", $this->no_local->ReadOnly); // im_anexo if (!($this->im_anexo->ReadOnly) && !$this->im_anexo->Upload->KeepFile) { $this->im_anexo->Upload->DbValue = $rs->fields('im_anexo'); // Get original value if ($this->im_anexo->Upload->FileName == "") { $rsnew['im_anexo'] = NULL; } else { $rsnew['im_anexo'] = $this->im_anexo->Upload->FileName; } } // dt_publicacao $this->dt_publicacao->SetDbValueDef($rsnew, ew_UnFormatDateTime($this->dt_publicacao->CurrentValue, 7), NULL, $this->dt_publicacao->ReadOnly); // ic_situacao $this->ic_situacao->SetDbValueDef($rsnew, $this->ic_situacao->CurrentValue, NULL, $this->ic_situacao->ReadOnly); if (!$this->im_anexo->Upload->KeepFile) { $this->im_anexo->UploadPath = "arquivos/resolucoes"; $OldFiles = explode(",", $this->im_anexo->Upload->DbValue); if (!ew_Empty($this->im_anexo->Upload->FileName)) { $NewFiles = explode(",", $this->im_anexo->Upload->FileName); $FileCount = count($NewFiles); for ($i = 0; $i < $FileCount; $i++) { $fldvar = ($this->im_anexo->Upload->Index < 0) ? $this->im_anexo->FldVar : substr($this->im_anexo->FldVar, 0, 1) . $this->im_anexo->Upload->Index . substr($this->im_anexo->FldVar, 1); if ($NewFiles[$i] <> "") { $file = ew_UploadTempPath($fldvar) . EW_PATH_DELIMITER . $NewFiles[$i]; if (file_exists($file)) { if (!in_array($NewFiles[$i], $OldFiles)) { $NewFiles[$i] = ew_UploadFileNameEx($this->im_anexo->UploadPath, $NewFiles[$i]); // Get new file name $file1 = ew_UploadTempPath($fldvar) . EW_PATH_DELIMITER . $NewFiles[$i]; if ($file1 <> $file) // Rename temp file rename($file, $file1); } } } } $this->im_anexo->Upload->FileName = implode(",", $NewFiles); $rsnew['im_anexo'] = $this->im_anexo->Upload->FileName; } else { $NewFiles = array(); } } // Call Row Updating event $bUpdateRow = $this->Row_Updating($rsold, $rsnew); if ($bUpdateRow) { $conn->raiseErrorFn = 'ew_ErrorFn'; if (count($rsnew) > 0) $EditRow = $this->Update($rsnew, "", $rsold); else $EditRow = TRUE; // No field to update $conn->raiseErrorFn = ''; if ($EditRow) { if (!$this->im_anexo->Upload->KeepFile) { $OldFiles = explode(",", $this->im_anexo->Upload->DbValue); if (!ew_Empty($this->im_anexo->Upload->FileName)) { $NewFiles = explode(",", $this->im_anexo->Upload->FileName); $NewFiles2 = explode(",", $rsnew['im_anexo']); $FileCount = count($NewFiles); for ($i = 0; $i < $FileCount; $i++) { $fldvar = ($this->im_anexo->Upload->Index < 0) ? $this->im_anexo->FldVar : substr($this->im_anexo->FldVar, 0, 1) . $this->im_anexo->Upload->Index . substr($this->im_anexo->FldVar, 1); if ($NewFiles[$i] <> "") { $file = ew_UploadTempPath($fldvar) . EW_PATH_DELIMITER . $NewFiles[$i]; if (file_exists($file)) { $this->im_anexo->Upload->Value = file_get_contents($file); $this->im_anexo->Upload->SaveToFile($this->im_anexo->UploadPath, (@$NewFiles2[$i] <> "") ? $NewFiles2[$i] : $NewFiles[$i], TRUE); // Just replace } } } } else { $NewFiles = array(); } $FileCount = count($OldFiles); for ($i = 0; $i < $FileCount; $i++) { if ($OldFiles[$i] <> "" && !in_array($OldFiles[$i], $NewFiles)) @unlink(ew_UploadPathEx(TRUE, $this->im_anexo->OldUploadPath) . $OldFiles[$i]); } } } } else { if ($this->getSuccessMessage() <> "" || $this->getFailureMessage() <> "") { // Use the message, do nothing } elseif ($this->CancelMessage <> "") { $this->setFailureMessage($this->CancelMessage); $this->CancelMessage = ""; } else { $this->setFailureMessage($Language->Phrase("UpdateCancelled")); } $EditRow = FALSE; } } // Call Row_Updated event if ($EditRow) $this->Row_Updated($rsold, $rsnew); $rs->Close(); // im_anexo ew_CleanUploadTempPath($this->im_anexo, $this->im_anexo->Upload->Index); return $EditRow; } // Set up Breadcrumb function SetupBreadcrumb() { global $Breadcrumb, $Language; $Breadcrumb = new cBreadcrumb(); $PageCaption = $this->TableCaption(); $Breadcrumb->Add("list", "<span id=\"ewPageCaption\">" . $PageCaption . "</span>", "gc_resolucaolist.php", $this->TableVar); $PageCaption = $Language->Phrase("edit"); $Breadcrumb->Add("edit", "<span id=\"ewPageCaption\">" . $PageCaption . "</span>", ew_CurrentUrl(), $this->TableVar); } // Page Load event function Page_Load() { //echo "Page Load"; } // Page Unload event function Page_Unload() { //echo "Page Unload"; } // Page Redirecting event function Page_Redirecting(&$url) { // Example: //$url = "your URL"; } // Message Showing event // $type = ''|'success'|'failure'|'warning' function Message_Showing(&$msg, $type) { if ($type == 'success') { //$msg = "your success message"; } elseif ($type == 'failure') { //$msg = "your failure message"; } elseif ($type == 'warning') { //$msg = "your warning message"; } else { //$msg = "your message"; } } // Page Render event function Page_Render() { //echo "Page Render"; } // Page Data Rendering event function Page_DataRendering(&$header) { // Example: //$header = "your header"; } // Page Data Rendered event function Page_DataRendered(&$footer) { // Example: //$footer = "your footer"; } // Form Custom Validate event function Form_CustomValidate(&$CustomError) { // Return error message in CustomError return TRUE; } } ?> <?php ew_Header(FALSE) ?> <?php // Create page object if (!isset($gc_resolucao_edit)) $gc_resolucao_edit = new cgc_resolucao_edit(); // Page init $gc_resolucao_edit->Page_Init(); // Page main $gc_resolucao_edit->Page_Main(); // Global Page Rendering event (in userfn*.php) Page_Rendering(); // Page Rendering event $gc_resolucao_edit->Page_Render(); ?> <?php include_once "header.php" ?> <script type="text/javascript"> // Page object var gc_resolucao_edit = new ew_Page("gc_resolucao_edit"); gc_resolucao_edit.PageID = "edit"; // Page ID var EW_PAGE_ID = gc_resolucao_edit.PageID; // For backward compatibility // Form object var fgc_resolucaoedit = new ew_Form("fgc_resolucaoedit"); // Validate form fgc_resolucaoedit.Validate = function() { if (!this.ValidateRequired) return true; // Ignore validation var $ = jQuery, fobj = this.GetForm(), $fobj = $(fobj); this.PostAutoSuggest(); if ($fobj.find("#a_confirm").val() == "F") return true; var elm, felm, uelm, addcnt = 0; var $k = $fobj.find("#" + this.FormKeyCountName); // Get key_count var rowcnt = ($k[0]) ? parseInt($k.val(), 10) : 1; var startcnt = (rowcnt == 0) ? 0 : 1; // Check rowcnt == 0 => Inline-Add var gridinsert = $fobj.find("#a_list").val() == "gridinsert"; for (var i = startcnt; i <= rowcnt; i++) { var infix = ($k[0]) ? String(i) : ""; $fobj.data("rowindex", infix); elm = this.GetElements("x" + infix + "_nu_grupoOuComite"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($gc_resolucao->nu_grupoOuComite->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_ds_resolucao"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($gc_resolucao->ds_resolucao->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_no_local"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($gc_resolucao->no_local->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_dt_publicacao"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($gc_resolucao->dt_publicacao->FldCaption()) ?>"); elm = this.GetElements("x" + infix + "_dt_publicacao"); if (elm && !ew_CheckEuroDate(elm.value)) return this.OnError(elm, "<?php echo ew_JsEncode2($gc_resolucao->dt_publicacao->FldErrMsg()) ?>"); elm = this.GetElements("x" + infix + "_ic_situacao"); if (elm && !ew_HasValue(elm)) return this.OnError(elm, ewLanguage.Phrase("EnterRequiredField") + " - <?php echo ew_JsEncode2($gc_resolucao->ic_situacao->FldCaption()) ?>"); // Set up row object ew_ElementsToRow(fobj); // Fire Form_CustomValidate event if (!this.Form_CustomValidate(fobj)) return false; } // Process detail forms var dfs = $fobj.find("input[name='detailpage']").get(); for (var i = 0; i < dfs.length; i++) { var df = dfs[i], val = df.value; if (val && ewForms[val]) if (!ewForms[val].Validate()) return false; } return true; } // Form_CustomValidate event fgc_resolucaoedit.Form_CustomValidate = function(fobj) { // DO NOT CHANGE THIS LINE! // Your custom validation code here, return false if invalid. return true; } // Use JavaScript validation or not <?php if (EW_CLIENT_VALIDATE) { ?> fgc_resolucaoedit.ValidateRequired = true; <?php } else { ?> fgc_resolucaoedit.ValidateRequired = false; <?php } ?> // Multi-Page properties fgc_resolucaoedit.MultiPage = new ew_MultiPage("fgc_resolucaoedit", [["x_nu_grupoOuComite",1],["x_ds_resolucao",1],["x_no_local",2],["x_im_anexo",2],["x_dt_publicacao",1],["x_ic_situacao",1]] ); // Dynamic selection lists fgc_resolucaoedit.Lists["x_nu_grupoOuComite"] = {"LinkField":"x_nu_gpComite","Ajax":null,"AutoFill":false,"DisplayFields":["x_no_gpComite","","",""],"ParentFields":[],"FilterFields":[],"Options":[]}; // Form object for search </script> <script type="text/javascript"> // Write your client script here, no need to add script tags. </script> <?php $Breadcrumb->Render(); ?> <?php $gc_resolucao_edit->ShowPageHeader(); ?> <?php $gc_resolucao_edit->ShowMessage(); ?> <form name="fgc_resolucaoedit" id="fgc_resolucaoedit" class="ewForm form-horizontal" action="<?php echo ew_CurrentPage() ?>" method="post"> <input type="hidden" name="t" value="gc_resolucao"> <input type="hidden" name="a_edit" id="a_edit" value="U"> <table class="ewStdTable"><tbody><tr><td> <div class="tabbable" id="gc_resolucao_edit"> <ul class="nav nav-tabs"> <li class="active"><a href="#tab_gc_resolucao1" data-toggle="tab"><?php echo $gc_resolucao->PageCaption(1) ?></a></li> <li><a href="#tab_gc_resolucao2" data-toggle="tab"><?php echo $gc_resolucao->PageCaption(2) ?></a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="tab_gc_resolucao1"> <table cellspacing="0" class="ewGrid" style="width: 100%"><tr><td> <table id="tbl_gc_resolucaoedit1" class="table table-bordered table-striped"> <?php if ($gc_resolucao->nu_grupoOuComite->Visible) { // nu_grupoOuComite ?> <tr id="r_nu_grupoOuComite"> <td><span id="elh_gc_resolucao_nu_grupoOuComite"><?php echo $gc_resolucao->nu_grupoOuComite->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $gc_resolucao->nu_grupoOuComite->CellAttributes() ?>> <span id="el_gc_resolucao_nu_grupoOuComite" class="control-group"> <select data-field="x_nu_grupoOuComite" id="x_nu_grupoOuComite" name="x_nu_grupoOuComite"<?php echo $gc_resolucao->nu_grupoOuComite->EditAttributes() ?>> <?php if (is_array($gc_resolucao->nu_grupoOuComite->EditValue)) { $arwrk = $gc_resolucao->nu_grupoOuComite->EditValue; $rowswrk = count($arwrk); $emptywrk = TRUE; for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) { $selwrk = (strval($gc_resolucao->nu_grupoOuComite->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected=\"selected\"" : ""; if ($selwrk <> "") $emptywrk = FALSE; ?> <option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>> <?php echo $arwrk[$rowcntwrk][1] ?> </option> <?php } } ?> </select> <script type="text/javascript"> fgc_resolucaoedit.Lists["x_nu_grupoOuComite"].Options = <?php echo (is_array($gc_resolucao->nu_grupoOuComite->EditValue)) ? ew_ArrayToJson($gc_resolucao->nu_grupoOuComite->EditValue, 1) : "[]" ?>; </script> </span> <?php echo $gc_resolucao->nu_grupoOuComite->CustomMsg ?></td> </tr> <?php } ?> <?php if ($gc_resolucao->ds_resolucao->Visible) { // ds_resolucao ?> <tr id="r_ds_resolucao"> <td><span id="elh_gc_resolucao_ds_resolucao"><?php echo $gc_resolucao->ds_resolucao->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $gc_resolucao->ds_resolucao->CellAttributes() ?>> <span id="el_gc_resolucao_ds_resolucao" class="control-group"> <textarea data-field="x_ds_resolucao" name="x_ds_resolucao" id="x_ds_resolucao" cols="35" rows="4" placeholder="<?php echo $gc_resolucao->ds_resolucao->PlaceHolder ?>"<?php echo $gc_resolucao->ds_resolucao->EditAttributes() ?>><?php echo $gc_resolucao->ds_resolucao->EditValue ?></textarea> </span> <?php echo $gc_resolucao->ds_resolucao->CustomMsg ?></td> </tr> <?php } ?> <?php if ($gc_resolucao->dt_publicacao->Visible) { // dt_publicacao ?> <tr id="r_dt_publicacao"> <td><span id="elh_gc_resolucao_dt_publicacao"><?php echo $gc_resolucao->dt_publicacao->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $gc_resolucao->dt_publicacao->CellAttributes() ?>> <span id="el_gc_resolucao_dt_publicacao" class="control-group"> <input type="text" data-field="x_dt_publicacao" name="x_dt_publicacao" id="x_dt_publicacao" placeholder="<?php echo $gc_resolucao->dt_publicacao->PlaceHolder ?>" value="<?php echo $gc_resolucao->dt_publicacao->EditValue ?>"<?php echo $gc_resolucao->dt_publicacao->EditAttributes() ?>> <?php if (!$gc_resolucao->dt_publicacao->ReadOnly && !$gc_resolucao->dt_publicacao->Disabled && @$gc_resolucao->dt_publicacao->EditAttrs["readonly"] == "" && @$gc_resolucao->dt_publicacao->EditAttrs["disabled"] == "") { ?> <button id="cal_x_dt_publicacao" name="cal_x_dt_publicacao" class="btn" type="button"><img src="phpimages/calendar.png" id="cal_x_dt_publicacao" alt="<?php echo $Language->Phrase("PickDate") ?>" title="<?php echo $Language->Phrase("PickDate") ?>" style="border: 0;"></button><script type="text/javascript"> ew_CreateCalendar("fgc_resolucaoedit", "x_dt_publicacao", "%d/%m/%Y"); </script> <?php } ?> </span> <?php echo $gc_resolucao->dt_publicacao->CustomMsg ?></td> </tr> <?php } ?> <?php if ($gc_resolucao->ic_situacao->Visible) { // ic_situacao ?> <tr id="r_ic_situacao"> <td><span id="elh_gc_resolucao_ic_situacao"><?php echo $gc_resolucao->ic_situacao->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $gc_resolucao->ic_situacao->CellAttributes() ?>> <span id="el_gc_resolucao_ic_situacao" class="control-group"> <select data-field="x_ic_situacao" id="x_ic_situacao" name="x_ic_situacao"<?php echo $gc_resolucao->ic_situacao->EditAttributes() ?>> <?php if (is_array($gc_resolucao->ic_situacao->EditValue)) { $arwrk = $gc_resolucao->ic_situacao->EditValue; $rowswrk = count($arwrk); $emptywrk = TRUE; for ($rowcntwrk = 0; $rowcntwrk < $rowswrk; $rowcntwrk++) { $selwrk = (strval($gc_resolucao->ic_situacao->CurrentValue) == strval($arwrk[$rowcntwrk][0])) ? " selected=\"selected\"" : ""; if ($selwrk <> "") $emptywrk = FALSE; ?> <option value="<?php echo ew_HtmlEncode($arwrk[$rowcntwrk][0]) ?>"<?php echo $selwrk ?>> <?php echo $arwrk[$rowcntwrk][1] ?> </option> <?php } } ?> </select> </span> <?php echo $gc_resolucao->ic_situacao->CustomMsg ?></td> </tr> <?php } ?> </table> </td></tr></table> </div> <div class="tab-pane" id="tab_gc_resolucao2"> <table cellspacing="0" class="ewGrid" style="width: 100%"><tr><td> <table id="tbl_gc_resolucaoedit2" class="table table-bordered table-striped"> <?php if ($gc_resolucao->no_local->Visible) { // no_local ?> <tr id="r_no_local"> <td><span id="elh_gc_resolucao_no_local"><?php echo $gc_resolucao->no_local->FldCaption() ?><?php echo $Language->Phrase("FieldRequiredIndicator") ?></span></td> <td<?php echo $gc_resolucao->no_local->CellAttributes() ?>> <span id="el_gc_resolucao_no_local" class="control-group"> <input type="text" data-field="x_no_local" name="x_no_local" id="x_no_local" size="30" maxlength="255" placeholder="<?php echo $gc_resolucao->no_local->PlaceHolder ?>" value="<?php echo $gc_resolucao->no_local->EditValue ?>"<?php echo $gc_resolucao->no_local->EditAttributes() ?>> </span> <?php echo $gc_resolucao->no_local->CustomMsg ?></td> </tr> <?php } ?> <?php if ($gc_resolucao->im_anexo->Visible) { // im_anexo ?> <tr id="r_im_anexo"> <td><span id="elh_gc_resolucao_im_anexo"><?php echo $gc_resolucao->im_anexo->FldCaption() ?></span></td> <td<?php echo $gc_resolucao->im_anexo->CellAttributes() ?>> <span id="el_gc_resolucao_im_anexo" class="control-group"> <span id="fd_x_im_anexo"> <span class="btn btn-small fileinput-button"> <span><?php echo $Language->Phrase("ChooseFile") ?></span> <input type="file" data-field="x_im_anexo" name="x_im_anexo" id="x_im_anexo" multiple="multiple"> </span> <input type="hidden" name="fn_x_im_anexo" id= "fn_x_im_anexo" value="<?php echo $gc_resolucao->im_anexo->Upload->FileName ?>"> <?php if (@$_POST["fa_x_im_anexo"] == "0") { ?> <input type="hidden" name="fa_x_im_anexo" id= "fa_x_im_anexo" value="0"> <?php } else { ?> <input type="hidden" name="fa_x_im_anexo" id= "fa_x_im_anexo" value="1"> <?php } ?> <input type="hidden" name="fs_x_im_anexo" id= "fs_x_im_anexo" value="255"> </span> <table id="ft_x_im_anexo" class="table table-condensed pull-left ewUploadTable"><tbody class="files"></tbody></table> </span> <?php echo $gc_resolucao->im_anexo->CustomMsg ?></td> </tr> <?php } ?> </table> </td></tr></table> </div> </div> </div> </td></tr></tbody></table> <input type="hidden" data-field="x_nu_resolucao" name="x_nu_resolucao" id="x_nu_resolucao" value="<?php echo ew_HtmlEncode($gc_resolucao->nu_resolucao->CurrentValue) ?>"> <button class="btn btn-primary ewButton" name="btnAction" id="btnAction" type="submit"><?php echo $Language->Phrase("EditBtn") ?></button> </form> <script type="text/javascript"> fgc_resolucaoedit.Init(); <?php if (EW_MOBILE_REFLOW && ew_IsMobile()) { ?> ew_Reflow(); <?php } ?> </script> <?php $gc_resolucao_edit->ShowPageFooter(); if (EW_DEBUG_ENABLED) echo ew_DebugMsg(); ?> <script type="text/javascript"> // Write your table-specific startup script here // document.write("page loaded"); </script> <?php include_once "footer.php" ?> <?php $gc_resolucao_edit->Page_Terminate(); ?>
gpl-2.0
Hill2/JONGman
source/pkg_jongman/libraries/jongman/quota/duration/week.php
2246
<?php defined('_JEXEC') or die; class RFQuotaDurationWeek extends RFQuotaDuration implements IQuotaDuration { /** * @param RFReservationSeries $reservationSeries * @param string $timezone * @return QuotaSearchDates */ public function getSearchDates(RFReservationSeries $reservationSeries, $timezone) { $dates = $this->getFirstAndLastReservationDates($reservationSeries); $startDate = $dates[0]->ToTimezone($timezone); $daysFromWeekStart = $startDate->weekday(); $startDate = $startDate->addDays(-$daysFromWeekStart)->getDate(); $endDate = $dates[1]->toTimezone($timezone); $daysFromWeekEnd = 7 - $endDate->weekday(); $endDate = $endDate->addDays($daysFromWeekEnd)->getDate(); return new RFQuotaSearchDates($startDate, $endDate); } /** * @param Date $date * @return void */ public function getDurationKey(Date $date) { $daysFromWeekStart = $date->weekday(); $firstDayOfWeek = $date->addDays(-$daysFromWeekStart)->getDate(); return sprintf("%s%s%s", $firstDayOfWeek->Year(), $firstDayOfWeek->month(), $firstDayOfWeek->day()); } /** * @param DateRange $dateRange * @return array|DateRange[] */ public function split(RFDateRange $dateRange) { $start = $dateRange->getBegin(); $end = $dateRange->getEnd(); $ranges = array(); if (!$start->dateEquals($end)) { $nextWeek = $this->getStartOfNextWeek($start); if ($nextWeek->lessThan($end)) { $ranges[] = new DateRange($start, $nextWeek); while ($nextWeek->LessThan($end)) { $thisEnd = $this->getStartOfNextWeek($nextWeek); if ($thisEnd->lessThan($end)) { $ranges[] = new RFDateRange($nextWeek, $thisEnd); } else { $ranges[] = new RFDateRange($nextWeek, $end); } $nextWeek = $thisEnd; } } else { $ranges[] = new RFDateRange($start, $end); } } else { $ranges[] = new RFDateRange($start, $end); } return $ranges; } /** * @param Date $date * @return Date */ private function getStartOfNextWeek(Date $date) { $daysFromWeekEnd = 7 - $date->weekday(); return $date->addDays($daysFromWeekEnd)->getDate(); } /** * @return string QuotaDuration */ public function name() { return RFQuotaDuration::Week; } }
gpl-2.0
pods-framework/pods
src/Pods/REST/V1/Post_Repository.php
3379
<?php namespace Pods\REST\V1; use Tribe__REST__Messages_Interface as REST_Messages_Interface; use Tribe__REST__Post_Repository as REST_Post_Repository; use WP_Post; /** * Class Post_Repository * * @since 2.8.0 */ class Post_Repository extends REST_Post_Repository { /** * A post type to get data request handler map. * * @var array */ protected $types_get_map = []; /** * @var REST_Messages_Interface */ protected $messages; /** * Post_Repository constructor. * * @since 2.8.0 * * @param REST_Messages_Interface|null $messages The messages object. */ public function __construct( REST_Messages_Interface $messages = null ) { $this->types_get_map = [ '_pods_pod' => [ $this, 'get_pod_data' ], '_pods_group' => [ $this, 'get_group_data' ], '_pods_field' => [ $this, 'get_field_data' ], ]; $this->messages = $messages ? $messages : tribe( 'pods.rest-v1.messages' ); } /** * Retrieves an array representation of the object. * * @since 2.8.0 * * @param int $id The ID. * @param string $type The type of content. * @param string $context Context of data. * * @return array|WP_Error An array representation of the object or an WP_Error with the error message. */ public function get_data( $id, $type = '', $context = 'default' ) { $object = null; if ( empty( $type ) ) { $object = get_post( $id ); if ( ! $object instanceof WP_Post ) { return []; } $type = $object->post_type; } if ( ! isset( $this->types_get_map[ $type ] ) ) { return (array) $object; } return call_user_func( $this->types_get_map[ $type ], $id, $object, $context ); } /** * Get pod data. * * @since 2.8.0 * * @param int $id The ID. * @param WP_Post|object $object The object. * @param string $context The context. * * @return array|WP_Error */ public function get_pod_data( $id, $object = null, $context = 'default' ) { if ( null === $object ) { $object = get_post( $id ); if ( ! $object instanceof WP_Post ) { return new WP_Error( 'pod-not-found', $this->messages->get_message( 'pod-not-found' ), [ 'status' => 404 ] ); } } // @todo Fill this out. return []; } /** * Get group data. * * @since 2.8.0 * * @param int $id The ID. * @param WP_Post|object $object The object. * @param string $context The context. * * @return array|WP_Error */ public function get_group_data( $id, $object = null, $context = 'default' ) { if ( null === $object ) { $object = get_post( $id ); if ( ! $object instanceof WP_Post ) { return new WP_Error( 'group-not-found', $this->messages->get_message( 'group-not-found' ), [ 'status' => 404 ] ); } } // @todo Fill this out. return []; } /** * Get field data. * * @since 2.8.0 * * @param int $id The ID. * @param WP_Post|object $object The object. * @param string $context The context. * * @return array|WP_Error */ public function get_field_data( $id, $object = null, $context = 'default' ) { if ( null === $object ) { $object = get_post( $id ); if ( ! $object instanceof WP_Post ) { return new WP_Error( 'group-not-found', $this->messages->get_message( 'group-not-found' ), [ 'status' => 404 ] ); } } // @todo Fill this out. return []; } }
gpl-2.0
OpenMORDM/rgl
src/Texture.cpp
6700
#include "Texture.hpp" #include "pixmap.h" #include "config.hpp" #include "platform.h" using namespace std; using namespace rgl; ////////////////////////////////////////////////////////////////////////////// // // CLASS // Texture // Texture::Texture( const char* in_filename , Type in_type , bool in_mipmap , unsigned int in_minfilter , unsigned int in_magfilter , bool in_envmap) { texName = 0; pixmap = new Pixmap(); type = in_type; mipmap = in_mipmap; envmap = in_envmap; magfilter = (in_magfilter) ? GL_LINEAR : GL_NEAREST; if (mipmap) { switch(in_minfilter) { case 0: minfilter = GL_NEAREST; break; case 1: minfilter = GL_LINEAR; break; case 2: minfilter = GL_NEAREST_MIPMAP_NEAREST; break; case 3: minfilter = GL_NEAREST_MIPMAP_LINEAR; break; case 4: minfilter = GL_LINEAR_MIPMAP_NEAREST; break; default: minfilter = GL_LINEAR_MIPMAP_LINEAR; break; } } else { switch(in_minfilter) { case 0: minfilter = GL_NEAREST; break; default: minfilter = GL_LINEAR; break; } } filename = new char [1 + strlen(in_filename)]; memcpy(filename, in_filename, 1 + strlen(in_filename)); if ( !pixmap->load(filename) ) { delete pixmap; pixmap = NULL; } } Texture::~Texture() { if (texName) { glDeleteTextures(1, &texName); } if (pixmap) delete pixmap; } bool Texture::isValid() const { return (pixmap) ? true : false; } void Texture::getParameters(Type *out_type, bool *out_mipmap, unsigned int *out_minfilter, unsigned int *out_magfilter, bool *out_envmap, int buflen, char *out_filename) { *out_type = type; *out_mipmap = mipmap; switch(minfilter) { case GL_NEAREST: *out_minfilter = 0; break; case GL_LINEAR: *out_minfilter = 1; break; case GL_NEAREST_MIPMAP_NEAREST: *out_minfilter = 2; break; case GL_NEAREST_MIPMAP_LINEAR: *out_minfilter = 3; break; case GL_LINEAR_MIPMAP_NEAREST: *out_minfilter = 4; break; case GL_LINEAR_MIPMAP_LINEAR: *out_minfilter = 5; break; default: *out_minfilter = 6; break; } *out_magfilter = (magfilter == GL_LINEAR) ? 1 : 0; *out_envmap = envmap; strncpy(out_filename, filename, buflen); } #ifndef MODERN_OPENGL static unsigned int texsize(unsigned int s) { return 1U << msb(s-1); } #include "lib.hpp" static void printGluErrorMessage(GLint error) { const GLubyte* gluError; char buf[256]; gluError = gluErrorString (error); sprintf(buf, "GLU Library Error : %s", (const char*) gluError); printMessage(buf); } #endif void Texture::init(RenderContext* renderContext) { glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magfilter); GLint internalFormat = 0; GLenum format = 0; GLint ualign; unsigned int bytesperpixel = 0; switch(type) { case ALPHA: internalFormat = GL_ALPHA; break; case LUMINANCE: internalFormat = GL_LUMINANCE; break; case LUMINANCE_ALPHA: internalFormat = GL_LUMINANCE_ALPHA; break; case RGB: internalFormat = GL_RGB; break; case RGBA: internalFormat = GL_RGBA; break; } switch(pixmap->typeID) { case GRAY8: ualign = 1; bytesperpixel = 1; switch(internalFormat) { case GL_LUMINANCE: format = GL_LUMINANCE; break; case GL_ALPHA: format = GL_ALPHA; break; case GL_LUMINANCE_ALPHA: format = GL_LUMINANCE; break; } break; case RGB24: ualign = 1; format = GL_RGB; bytesperpixel = 3; break; case RGB32: ualign = 2; format = GL_RGB; bytesperpixel = 4; break; case RGBA32: ualign = 2; format = GL_RGBA; bytesperpixel = 4; break; default: // INVALID return; } glPixelStorei(GL_UNPACK_ALIGNMENT, ualign); GLenum gl_type = GL_UNSIGNED_BYTE; GLint glTexSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &glTexSize ); #ifdef MODERN_OPENGL glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pixmap->width, pixmap->height, 0, format, gl_type , pixmap->data); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); #else unsigned int maxSize = static_cast<unsigned int>(glTexSize); if (mipmap) { int gluError = gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, pixmap->width, pixmap->height, format, gl_type, pixmap->data); if (gluError) printGluErrorMessage(gluError); } else { unsigned int width = texsize(pixmap->width); unsigned int height = texsize(pixmap->height); if ( (width > maxSize) || (height > maxSize) ) { char buf[256]; sprintf(buf, "GL Library : Maximum texture size of %dx%d exceeded.\n(Perhaps enabling mipmapping could help.)", maxSize,maxSize); printMessage(buf); } else if ( (pixmap->width != width) || ( pixmap->height != height) ) { char* data = new char[width * height * bytesperpixel]; int gluError = gluScaleImage(format, pixmap->width, pixmap->height, gl_type, pixmap->data, width, height, gl_type, data); if (gluError) printGluErrorMessage(gluError); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, gl_type , data); delete[] data; } else { glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pixmap->width, pixmap->height, 0, format, gl_type , pixmap->data); } } #endif /* not MODERN_OPENGL */ if (envmap) { glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glEnable(GL_TEXTURE_GEN_S); glEnable(GL_TEXTURE_GEN_T); } delete pixmap; pixmap = NULL; } void Texture::beginUse(RenderContext* renderContext) { if (!texName) { init(renderContext); } glPushAttrib(GL_TEXTURE_BIT|GL_ENABLE_BIT|GL_CURRENT_BIT); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glBindTexture(GL_TEXTURE_2D, texName); if (type == ALPHA) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); } } void Texture::endUse(RenderContext* renderContext) { glPopAttrib(); }
gpl-2.0
eddywebs/apimaker
app/views/search.blade.php
724
@extends('master') @section('title') Show APIs @stop @section('content') <div class="starter-template" style="text-align: left;"> <!-- <div class="jumbotron" style="text-align: left;"> --> @if($datasets==null) <h2>boo no apis for you</h2> @else @if($query==null) <h2>All available APIs</h2> @else <h2>Here are Apis for term: {{ $query }}</h2> @endif <hr> @foreach($datasets as $dataset) <section> <h3> - <a href='/dataset/{{ $dataset['id'] }}'>{{ $dataset['description'] }} </a> : <a href='/dataset/{{ $dataset['id'] }}/edit'>Edit / Delete</a><h3> </section> @endforeach @endif <br> <!-- </div> --> </div> <p> <!-- some more content in case?--> </p> @stop
gpl-2.0
LeeRisk/JavaTorrent
torrent/download/files/Piece.java
8557
package torrent.download.files; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import org.johnnei.utils.JMath; import torrent.TorrentException; import torrent.download.AFiles; import torrent.download.FileInfo; import torrent.encoding.SHA1; public class Piece implements Comparable<Piece> { /** * The files associated with this piece */ protected AFiles files; /** * The index of this piece in the torrent */ private int index; /** * All the blocks in this piece */ private List<Block> blocks; /** * The next piece which will be dropped on hash fail */ private int hashFailCheck; private byte[] expectedHash; public Piece(AFiles files, byte[] hash, int index, int pieceSize, int blockSize) { this.index = index; this.files = files; this.expectedHash = hash; blocks = new ArrayList<>(JMath.ceilDivision(pieceSize, blockSize)); int blockIndex = 0; while (pieceSize > 0) { Block block = new Block(blockIndex, Math.min(blockSize, pieceSize)); pieceSize -= block.getSize(); blocks.add(block); ++blockIndex; } } /** * Drops ceil(10%) of the blocks in order to maintain speed and still try to *not* redownload the entire piece */ public void hashFail() { int tenPercent = JMath.ceilDivision(blocks.size(), 10); for (int i = 0; i < tenPercent; i++) { reset(hashFailCheck++); if (hashFailCheck >= blocks.size()) { hashFailCheck = 0; } } } /** * Resets a single block as unstarted * * @param blockIndex */ public void reset(int blockIndex) { blocks.get(blockIndex).setDone(false); blocks.get(blockIndex).setRequested(false); } /** * Loads a bit of data from the file but it is not strictly a block as I use it * * @param offset The offset in the piece * @param length The amount of bytes to read * @return The read bytes or an excpetion * @throws TorrentException */ public byte[] loadPiece(int offset, int length) throws TorrentException, IOException { byte[] pieceData = new byte[length]; int readBytes = 0; while (readBytes < length) { // Offset within the piece int alreadyReadOffset = offset + readBytes; // Find file for the given offset FileInfo outputFile = files.getFileForBytes(index, 0, alreadyReadOffset); // Calculate offset as if the torrent was one file long pieceIndexOffset = (index * files.getPieceSize()); long totalOffset = pieceIndexOffset + alreadyReadOffset; // Calculate the offset within the file long offsetInFile = totalOffset - outputFile.getFirstByteOffset(); // Calculate how many bytes we want/can read from the file int bytesToRead = Math.min(length - readBytes, (int) (outputFile.getSize() - offsetInFile)); // Check if we don't read outside the file if (offsetInFile < 0) { throw new IOException("Cannot seek to position: " + offsetInFile); } // Read the actual files synchronized (outputFile.FILE_LOCK) { RandomAccessFile file = outputFile.getFileAcces(); file.seek(offsetInFile); file.readFully(pieceData, readBytes, bytesToRead); readBytes += bytesToRead; } } return pieceData; } /** * Checks if the received bytes hash matches with the hash which was given in the metadata * * @return hashMatched ? true : false * @throws TorrentException If the piece is not within any of the files in this torrent (Shouldn't occur) */ public boolean checkHash() throws TorrentException, IOException { byte[] pieceData = loadPiece(0, getSize()); return SHA1.match(expectedHash, SHA1.hash(pieceData)); } /** * Writes the block into the correct file(s) * * @param blockIndex The index of the block to write * @param blockData The data of the block * @throws Exception */ public void storeBlock(int blockIndex, byte[] blockData) throws TorrentException, IOException { Block block = blocks.get(blockIndex); if (block.getSize() != blockData.length) { blocks.get(blockIndex).setDone(false); blocks.get(blockIndex).setRequested(false); throw new TorrentException("Block size did not match. Expected: " + blocks.get(blockIndex).getSize() + ", Got: " + blockData.length); } int remainingBytesToWrite = block.getSize(); // Write Block while (remainingBytesToWrite > 0) { // The offset within the block itself int dataOffset = (block.getSize() - remainingBytesToWrite); // Retrieve the file to which we need to write FileInfo outputFile = files.getFileForBytes(index, blockIndex, dataOffset); // Calculate the offset in bytes as if the torrent was one file final long pieceOffset = (index * files.getPieceSize()); final long blockOffset = (blockIndex * files.getBlockSize()); final long totalOffset = pieceOffset + blockOffset + dataOffset; // Calculate the offset within the file long offsetInFile = totalOffset - outputFile.getFirstByteOffset(); // Determine how many bytes still belong in this file int bytesToWrite = Math.min(remainingBytesToWrite, (int) (outputFile.getSize() - offsetInFile)); // Check if the calculated offset is within the file if (offsetInFile < 0) { throw new IOException("Cannot seek to position: " + offsetInFile); } // Write the actual bytes synchronized (outputFile.FILE_LOCK) { RandomAccessFile file = outputFile.getFileAcces(); file.seek(offsetInFile); file.write(blockData, dataOffset, bytesToWrite); remainingBytesToWrite -= bytesToWrite; } // Mark the block as done block.setDone(true); } } /** * Counts all block sizes which are not done yet * * @return The remaining amount of bytes to finish this piece */ public long getRemainingBytes() { return blocks.stream().filter(b -> !b.isDone()).mapToLong(Block::getSize).sum(); } /** * Sets the block to done * * @param blockIndex */ public void setDone(int blockIndex) { blocks.get(blockIndex).setDone(true); } public boolean isRequested(int blockIndex) { return blocks.get(blockIndex).isRequested(); } public boolean isDone(int blockIndex) { return blocks.get(blockIndex).isDone(); } /** * Checks if all blocks are done * * @return If this piece is completed */ public boolean isDone() { return blocks.stream().allMatch(b -> b.isDone()); } /** * Checks all blockStates if they have been started * * @return true if any progress is found */ public boolean isStarted() { return blocks.stream().anyMatch(b -> b.isStarted()); } @Override public int compareTo(Piece p) { int myValue = getCompareValue(); int theirValue = p.getCompareValue(); return myValue - theirValue; } private int getCompareValue() { int value = 0; for (Block block : blocks) { if (block.isDone()) value += 2; else if (block.isRequested()) value += 1; } return value; } /** * Gets the amount of blocks in this piece * * @return block count */ public int getBlockCount() { return blocks.size(); } /** * Gets the index of this Piece<br/> * The index is equal to the offset in the file divided by the default piece size * * @return */ public int getIndex() { return index; } /** * Gets the total size of all blocks * * @return The size of this piece */ public int getSize() { return blocks.stream().mapToInt(Block::getSize).sum(); } /** * Gets the amount of blocks done * * @return block done count */ public int getDoneCount() { return (int) blocks.stream().filter(p -> p.isDone()).count(); } /** * Gets the amount of block requested * * @return block requested count */ public int getRequestedCount() { return (int) blocks.stream().filter(p -> p.isRequested() && !p.isDone()).count(); } /** * Gets the amount of block requested including those who are done * * @return */ public int getTotalRequestedCount() { return (int) blocks.stream().filter(p -> p.isRequested()).count(); } /** * Gets a new block to be requested * * @return an unrequested block */ public Block getRequestBlock() { Block block = blocks.stream().filter(p -> !p.isStarted()).findAny().orElse(null); if (block == null) { return null; } else { block.setRequested(true); return block; } } /** * Gets the size of the specified block * * @param blockIndex The index of the block to get the size of * @return Size of the block in bytes */ public int getBlockSize(int blockIndex) { return blocks.get(blockIndex).getSize(); } }
gpl-2.0
vanbumi/pencerahan
plugins/jsnpagebuilder/defaultelements/socialicon/socialicon.php
8246
<?php /** * @version $Id$ * @package JSN_PageBuilder * @author JoomlaShine Team <support@joomlashine.com> * @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved. * @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html * * Websites: http://www.joomlashine.com * Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html */ defined('_JEXEC') or die('Restricted access'); /** * SocialIcon shortcode element * * @package JSN_Pagebuilder * @since 1.0.7 */ class JSNPBShortcodeSocialicon extends IG_Pb_Element { /** * Constructor * * @return type */ public function __construct() { parent::__construct(); } /** * Include admin scripts * * @return type */ public function backend_element_assets() { JSNPagebuilderHelpersFunctions::print_asset_tag( JSNPB_ADMIN_URL . '/assets/joomlashine/js/jsn-iconsocialselector.js', 'js' ); JSNPagebuilderHelpersFunctions::print_asset_tag( JSNPB_FRAMEWORK_ASSETS . '/joomlashine/css/jsn-general.css', 'css' ); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_PLG_SYSTEM_ASSETS_URL . '3rd-party/font-awesome/css/font-awesome.min.css', 'css'); JSNPagebuilderHelpersFunctions::print_asset_tag( JSNPB_ADMIN_URL . '/assets/css/jsn-fontawesome.css', 'css' ); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_FRAMEWORK_ASSETS . '/3rd-party/jquery-colorpicker/js/colorpicker.js', 'js'); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_FRAMEWORK_ASSETS . '/3rd-party/jquery-colorpicker/css/colorpicker.css', 'css'); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_ADMIN_URL . '/assets/joomlashine/js/jsn-colorpicker.js', 'js'); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_ELEMENT_URL . '/socialicon/assets/js/socialicon-settings.js', 'js'); JSNPagebuilderHelpersFunctions::print_asset_tag(JSNPB_ELEMENT_URL . '/socialicon/assets/css/socialicon-settings.css', 'css'); } /** * DEFINE configuration information of shortcode * * @return type */ public function element_config() { $this->config['shortcode'] = 'pb_socialicon'; $this->config['name'] = JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON' ); $this->config['cat'] = JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_TYPOGRAPHY' ); $this->config['icon'] = 'icon-socials'; $this->config['description'] = JText::_('JSN_PAGEBUILDER_ELEMENT_SOCIALICON_DES'); $this->config['has_subshortcode'] = __CLASS__ . 'Item'; $this->config['exception'] = array( 'default_content' => JText::_('JSN_PAGEBUILDER_ELEMENT_SOCIALICON'), 'data-modal-title' => JText::_('JSN_PAGEBUILDER_ELEMENT_SOCIALICON'), ); } /** * DEFINE setting options of shortcode in backend */ public function backend_element_items() { $this->frontend_element_items(); } /** * DEFINE setting options of shortcode in frontend */ public function frontend_element_items() { $this->items = array( 'content' => array( array( 'name' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_ELEMENT_TITLE' ), 'id' => 'el_title', 'type' => 'text_field', 'class' => 'jsn-input-xxlarge-fluid', 'std' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_ELEMENT_TITLE_STD' ), 'role' => 'title', 'tooltip' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_ELEMENT_TITLE_DES' ) ), array( 'id' => 'socialicon_items', 'name' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_ITEMS' ), 'type' => 'group', 'shortcode' => $this->config['shortcode'], 'sub_item_type' => $this->config['has_subshortcode'], 'sub_items' => array( array( 'std' => '[pb_socialicon_item heading="Facebook" link_url="https://www.facebook.com" icon="fa fa-facebook" ][/pb_socialicon_item]' ), array( 'std' => '[pb_socialicon_item heading="Twitter" link_url="https://twitter.com" icon="fa fa-twitter" ][/pb_socialicon_item]' ), array( 'std' => '[pb_socialicon_item heading="Google +" link_url="https://plus.google.com" icon="fa fa-google-plus" ][/pb_socialicon_item]' ), ), 'label_item' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_ITEMS_LABEL' ) ), ), 'styling' => array( array( 'type' => 'preview', ), array( 'name' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_SHAPE' ), 'id' => 'shape', 'type' => 'radio', 'std' => 'square', 'has_depend' => '1', 'options' => array( 'square' => JText::_('JSN_PAGEBUILDER_DEFAULT_ELEMENT_SQUARE'), 'circle' => JText::_('JSN_PAGEBUILDER_DEFAULT_ELEMENT_CIRCLE')), 'tooltip' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_SHAPE_DES' ) ), array( 'name' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_ROUNDED_CORNER_VALUE' ), 'id' => 'rounded_corner', 'type' => 'text_field', 'std' => '5', 'dependency' => array('shape', '=', 'square'), 'tooltip' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_ROUNDED_CORNER_VALUE_DES' ) ), array( 'name' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_SIZE' ), 'id' => 'icon_size', 'type' => 'select', 'std' => 'small', 'options' => array('small' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_SMALL' ), 'medium' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_MEDIUM' ), 'large' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_LARGE' )), 'tooltip' => JText::_( 'JSN_PAGEBUILDER_DEFAULT_ELEMENT_SIZE_DES' ) ), array( 'name' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_BACKGROUND_COLOR' ), 'id' => 'icon_bg_color', 'type' => 'radio', 'std' => 'brand', 'options' => array( 'brand' => JText::_('JSN_PAGEBUILDER_ELEMENT_SOCIALICON_BRAND_COLOR'), 'custom' => JText::_('JSN_PAGEBUILDER_DEFAULT_ELEMENT_CUSTOM')), 'has_depend' => '1', 'tooltip' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_BACKGROUND_COLOR_DES' ) ), array( 'name' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_CHOOSE_COLOR' ), 'id' => 'custom_bg_color', 'type' => 'color_picker', 'std' => '#333333', 'dependency' => array('icon_bg_color', '=', 'custom'), 'tooltip' => JText::_( 'JSN_PAGEBUILDER_ELEMENT_SOCIALICON_CHOOSE_COLOR_DES' ) ), ) ); } /** * DEFINE shortcode content * * @param type $atts * @param type $content * * @return string */ public function element_shortcode( $atts = null, $content = null ) { $document = JFactory::getDocument(); $app = JFactory::getApplication(); if ($app->isAdmin()) { $this->load_assets_frontend(); } $arr_params = JSNPagebuilderHelpersShortcode::shortcodeAtts( $this->config['params'], $atts ); extract( $arr_params ); $style = ''; if ($icon_bg_color == 'custom'){ $style .= 'background:'.$custom_bg_color .';'; } if ($shape == 'square') { if (!empty($rounded_corner)) { $style .= 'border-radius:'. $rounded_corner . 'px;'; } } elseif ($shape == 'circle') { $style .= 'border-radius:50px;'; } $html_elements = ''; $sub_shortcode = empty($content) ? JSNPagebuilderHelpersShortcode::removeAutop($content) : JSNPagebuilderHelpersBuilder::generateShortCode($content, false, 'frontend', true); if ( ! empty( $sub_shortcode ) ) { $html_elements = "<ul class='pb-social-icons {$shape} {$icon_bg_color}'>"; $sub_htmls = $sub_shortcode; $sub_htmls = str_replace('{icon_size}', $icon_size, $sub_htmls); $sub_htmls = str_replace('STYLE', "style='{$style}'", $sub_htmls); $html_elements .= $sub_htmls; $html_elements .= '</ul>'; $html_elements .= '<div style="clear: both"></div>'; } return $this->element_wrapper( $html_elements, $arr_params ); } public function load_assets_frontend() { $document = JFactory::getDocument(); $document->addScript( JSNPB_ELEMENT_URL.'/socialicon/assets/js/socialicon.js', 'text/javascript' ); $document->addStyleSheet(JSNPB_PLG_SYSTEM_ASSETS_URL . '3rd-party/font-awesome/css/font-awesome.min.css', 'css'); $document->addStyleSheet(JSNPB_ELEMENT_URL . '/socialicon/assets/css/socialicon.css', 'text/css'); } }
gpl-2.0
Remo/concrete5-syntax-highlighter
blocks/syntax_highlighter/view.php
144
<?php defined('C5_EXECUTE') or die('Access Denied.'); ?> <div class="ccm-syntax-highlighter"> <?php echo $highlightedCode; ?> </div>
gpl-2.0
Murzic/Quiz-ToolKit
app/models/group.rb
93
class Group < ActiveRecord::Base has_and_belongs_to_many :questions belongs_to :quiz end
gpl-2.0
arifirh/juliet-scott-sculpture
wp-content/themes/dandelion/template-contact.php
1379
<?php /* Template Name: Contact form page */ get_header(); if ( have_posts() ) { while ( have_posts() ) { the_post(); //get the default page settings $subtitle=get_post_meta( $post->ID, 'subtitle_value', true ); $slider=get_post_meta( $post->ID, 'slider_value', $single = true ); $slider_prefix=get_post_meta( $post->ID, 'slider_name_value', true ); if ( $slider_prefix=='default' ) { $slider_prefix=''; } $layout=get_post_meta( $post->ID, 'layout_value', true ); if ( $layout=='' ) { $layout='right'; } $show_title=get_opt( '_show_page_title' ); $sidebar=get_post_meta( $post->ID, 'sidebar_value', $single = true ); if ( $sidebar=='' ) { $sidebar='default'; } //include the page header template locate_template( array( 'includes/page-header.php' ), true, true ); ?> <div id="content-container" class="content-gradient <?php echo $layoutclass; ?> "> <div id="<?php echo $content_id; ?>"> <!--content--> <?php if ( $show_title!='off' ) {?> <h1 class="page-heading"><?php the_title(); ?></h1><hr/> <?php } the_content(); //include the contact form locate_template( array( 'includes/form.php' ), true, true ); } } ?> </div> <?php if ( $layout!='full' ) { print_sidebar( $sidebar ); } ?> <div class="clear"></div> </div> <?php get_footer(); ?>
gpl-2.0
XCSoar/XCSoar
src/ui/event/poll/WaylandQueue.hpp
2447
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 XCSOAR_EVENT_X11_EVENT_QUEUE_HPP #define XCSOAR_EVENT_X11_EVENT_QUEUE_HPP #include "event/SocketEvent.hxx" #include "Math/Point2D.hpp" #include <cstdint> struct wl_display; struct wl_compositor; struct wl_seat; struct wl_pointer; struct wl_shell; struct wl_registry; namespace UI { class Display; class EventQueue; struct Event; /** * This class opens a connection to the X11 server using Xlib and * listens for events. */ class WaylandEventQueue final { EventQueue &queue; struct wl_display *const display; struct wl_compositor *compositor = nullptr; struct wl_seat *seat = nullptr; struct wl_pointer *pointer = nullptr; struct wl_shell *shell = nullptr; IntPoint2D pointer_position = {0, 0}; SocketEvent socket_event; public: /** * @param queue the #EventQueue that shall receive Wayland input * events */ WaylandEventQueue(UI::Display &display, EventQueue &queue); struct wl_compositor *GetCompositor() { return compositor; } struct wl_shell *GetShell() { return shell; } bool IsVisible() const { // TODO: implement return true; } bool Generate(Event &event); void RegistryHandler(struct wl_registry *registry, uint32_t id, const char *interface); void SeatHandleCapabilities(bool pointer, bool keyboard, bool touch); void Push(const Event &event); void PointerMotion(IntPoint2D new_pointer_position); void PointerButton(bool pressed); private: void OnSocketReady(unsigned events) noexcept; }; } // namespace UI #endif
gpl-2.0
ncss-tech/geo-pit
SSURGO_DownloadTools_2015/SSURGO_MergeSoilShapefilesbyAreasymbol.py
5277
# SSURGO_MergeSoilShapefilesbyAreasymbol.py # # This script is almost identical to SSURGO_MergeSoilShapefiles.py except for parameter order. # Keep both scripts in synch!!! # # Purpose: allow batch appending of SSURGO soil polygon shapefiles into a single shapefile # Requires input dataset structures to follow the NRCS standard for Geospatial data... # # There currently is no method for handling inputs with more than one coordinate system, # especially if there is more than one horizontal datum involved. Should work OK if # an output coordinate system and datum transformation is set in the GP environment. # # Merge order is based upon sorted extent coordinates # # Test version 09-30-2013 # Beta version 10-31-2013 # 11-22-2013 # 01-08-2014 # 2014-09-27 ## =================================================================================== class MyError(Exception): pass ## =================================================================================== def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n" PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) pass ## =================================================================================== def PrintMsg(msg, severity=0): # Adds tool message to the geoprocessor # #Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line try: for string in msg.split('\n'): #Add a geoprocessing message (in case this is run as a tool) if severity == 0: arcpy.AddMessage(string) elif severity == 1: arcpy.AddWarning(string) elif severity == 2: arcpy.AddError(" \n" + string) except: pass ## =================================================================================== def Number_Format(num, places=0, bCommas=True): try: # Format a number according to locality and given places #locale.setlocale(locale.LC_ALL, "") if bCommas: theNumber = locale.format("%.*f", (places, num), True) else: theNumber = locale.format("%.*f", (places, num), False) return theNumber except: errorMsg() #PrintMsg("Unhandled exception in Number_Format function (" + str(num) + ")", 2) return "???" ## =================================================================================== # Import system modules import arcpy, sys, string, os, traceback, locale # Create the Geoprocessor object from arcpy import env try: inputFolder = arcpy.GetParameterAsText(0) # location of SSURGO datasets containing spatial folders # skip parameter 1. That is the Access database used to create the list of surveys in parameter 2. # The following line references parameter 1 in the other script and is the only change surveyList = arcpy.GetParameter(2) # list of folder names to be proccessed outputShape = arcpy.GetParameterAsText(3) # Name of final output shapefile if len(surveyList) < 2: raise MyError, "At least 2 input surveys are required" # check outputShape filename fName, fExt = os.path.splitext(outputShape) if fExt == "": outputShape += ".shp" elif fExt != ".shp": outputShape = fName + ".shp" # if the output shapefile already exists, delete it if arcpy.Exists(os.path.join(inputFolder, outputShape)): arcpy.Delete_management(os.path.join(inputFolder, outputShape)) dList = dict() extentList = list() shpList = list() # process each selected soil survey PrintMsg(" \nValidating " + str(len(surveyList)) + " selected surveys...", 0) for subFolder in surveyList: # confirm shapefile existence for each survey and append to input list shpName = "soilmu_a_" + subFolder[-5:] + ".shp" shpPath = os.path.join( os.path.join( inputFolder, os.path.join( subFolder, "spatial")), shpName) if arcpy.Exists(shpPath): desc = arcpy.Describe(shpPath) shpExtent = desc.extent XCntr = ( shpExtent.XMin + shpExtent.XMax) / 2.0 YCntr = ( shpExtent.YMin + shpExtent.YMax) / 2.0 sortKey = XCntr * YCntr PrintMsg("\tAppending " + shpName + " to list", 0) dList[sortKey] = shpPath extentList.append(sortKey) else: raise MyError, "Error. Missing soil polygon shapefile: " + shpName # Sort shapefiles by extent so that the drawing order is a little more effecient extentList.sort() for sortKey in extentList: shpList.append(dList[sortKey]) PrintMsg(" \nMerging listed shapefiles to create new shapefile: " + outputShape + " \n ", 0) arcpy.Merge_management(shpList, os.path.join(inputFolder, outputShape)) PrintMsg("Output folder: " + inputFolder + " \n ", 0) except MyError, e: PrintMsg(str(e), 2) except: errorMsg()
gpl-2.0
dlitz/resin
modules/resin/src/com/caucho/amber/cfg/TableGeneratorConfig.java
2734
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Rodrigo Westrupp */ package com.caucho.amber.cfg; import java.util.ArrayList; /** * <table-generator> tag in orm.xml */ public class TableGeneratorConfig extends AbstractGeneratorConfig { // attributes private String _table; private String _catalog; private String _schema; private String _pkColumnName; private String _valueColumnName; private String _pkColumnValue; // elements private ArrayList<UniqueConstraintConfig> _uniqueConstraintList = new ArrayList<UniqueConstraintConfig>(); public String getTable() { return _table; } public void setTable(String table) { _table = table; } public String getCatalog() { return _catalog; } public void setCatalog(String catalog) { _catalog = catalog; } public String getSchema() { return _schema; } public void setSchema(String schema) { _schema = schema; } public String getPkColumnName(String pkColumnName) { return _pkColumnName; } public void setPkColumnName(String pkColumnName) { _pkColumnName = pkColumnName; } public String getValueColumnName(String valueColumnName) { return _valueColumnName; } public void setValueColumnName(String valueColumnName) { _valueColumnName = valueColumnName; } public String getPkColumnValue(String pkColumnValue) { return _pkColumnValue; } public void setPkColumnValue(String pkColumnValue) { _pkColumnValue = pkColumnValue; } public void addUniqueConstraint(UniqueConstraintConfig uniqueConstraint) { _uniqueConstraintList.add(uniqueConstraint); } public ArrayList<UniqueConstraintConfig> getUniqueConstraintList() { return _uniqueConstraintList; } }
gpl-2.0
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/LNK/FullScreen.php
692
<?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\LNK; use PHPExiftool\Driver\AbstractTag; class FullScreen extends AbstractTag { protected $Id = 112; protected $Name = 'FullScreen'; protected $FullName = 'LNK::ConsoleData'; protected $GroupName = 'LNK'; protected $g0 = 'LNK'; protected $g1 = 'LNK'; protected $g2 = 'Other'; protected $Type = 'int32u'; protected $Writable = false; protected $Description = 'Full Screen'; }
gpl-2.0
germanmoyano09/goStreety
components/com_iproperty/controllers/ipuser.php
4241
<?php /** * @version 3.2.1 2014-02-04 * @package Joomla * @subpackage Intellectual Property * @copyright (C) 2009 - 2014 the Thinkery LLC. All rights reserved. * @license GNU/GPL see LICENSE.php */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access'); jimport('joomla.application.component.controller'); class IpropertyControllerIPuser extends JControllerLegacy { protected $text_prefix = 'COM_IPROPERTY'; public function saveProperty() { $post = JRequest::get('post'); $id = $post['id']; $notes = $post['notes']; $email_update = $post['email_update'] ? 1 : 0; JSession::checkToken() or die( 'Invalid Token!'); #TODO: replace with base64encode $link = @$_SERVER['HTTP_REFERER']; if (empty($link) || !JURI::isInternal($link)) { $link = JURI::base(); } $model = $this->getModel('ipuser'); //save property from favorites if($model->saveProperty($id, $notes, $email_update)){ $msg = JText::_('COM_IPROPERTY_PROPERTY_HAS_BEEN_SAVED'); $type = 'message'; }else{ $msg = JText::_('COM_IPROPERTY_PROPERTY_HAS_NOT_BEEN_SAVED'); $type = 'notice'; } $this->setRedirect($link, $msg, $type); } public function saveSearch() { $post = JRequest::get('post'); $string = $post['ipsearchstring']; $notes = $post['notes']; $email_update = $post['email_update'] ? 1 : 0; JSession::checkToken() or die( 'Invalid Token!'); #TODO: replace with base64encode $link = @$_SERVER['HTTP_REFERER']; if (empty($link) || !JURI::isInternal($link)) { $link = JURI::base(); } $model = $this->getModel('ipuser'); if($model->saveSearch($string, $notes, $email_update)){ $msg = JText::_('COM_IPROPERTY_SEARCH_HAS_BEEN_SAVED'); $type = 'message'; }else{ $msg = JText::_('COM_IPROPERTY_SEARCH_HAS_NOT_BEEN_SAVED'); $type = 'notice'; } $this->setRedirect($link, $msg, $type); } /*// remote actions - from email link //*/ // Unsubscribe email link to unsubscribe from email updates public function unsubscribeSaved() { $vars = JRequest::get( 'GET'); $id = $vars['id']; // id of object to change $all = isset ($vars['all']) ? 1 : 0; // boolean, 1 for unsubscribe from all $token = $vars['token']; // type of object to change if (!$id || !$token) { $this->setRedirect(JRoute::_(ipropertyHelperRoute::getHomeRoute(), false), JText::_('COM_IPROPERTY_INVALID_ID_OR_TOKEN_PASSED')); return false; } $model = $this->getModel('ipuser'); if($model->emailUnsubscribe($id, $token, $all)){ $this->setRedirect(JRoute::_(ipropertyHelperRoute::getHomeRoute(), false), JText::_('COM_IPROPERTY_UNSUBSCRIBE_SUCCESS')); }else{ $this->setRedirect(JRoute::_(ipropertyHelperRoute::getHomeRoute(), false), JText::_('COM_IPROPERTY_UNSUBSCRIBE_FAILED').': '.$model->getError(), 'notice'); } } // Approval link for automatic approval from email public function approveListing() { $vars = JRequest::get( 'GET'); $id = $vars['id']; // id of object to change $token = $vars['token']; // type of object to change if (!$id || !$token) { $this->setRedirect(JRoute::_(ipropertyHelperRoute::getHomeRoute(), false), JText::_('COM_IPROPERTY_INVALID_ID_OR_TOKEN_PASSED')); return false; } $model = $this->getModel('ipuser'); if($model->approveListing($id, $token)){ $this->setRedirect(JRoute::_(ipropertyHelperRoute::getPropertyRoute($id), false), JText::_('COM_IPROPERTY_APPROVAL_SUCCESSFUL')); }else{ $this->setRedirect(JRoute::_(ipropertyHelperRoute::getHomeRoute(), false), JText::_('COM_IPROPERTY_APPROVAL_FAILED').': '.$model->getError(), 'notice'); } } }
gpl-2.0
mooflu/critter
utilssdl/PNG.cpp
2698
// Description: // Helper to save a SDL surface as a PNG. // // Copyright (C) 2001 Frank Becker // // 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 // #include "PNG.hpp" //Save SDL surface as png bool PNG::Save( SDL_Surface *img, const std::string &filename, bool flip) { FILE *fp = fopen( filename.c_str(), "wb"); if( fp == NULL) { return false; } if( ! init( fp, img->w, img->h)) { return false; } unsigned char *data = (unsigned char *)img->pixels; if( flip) { for( int y=0; y<img->h; y++) { png_bytep rowPointers = &data[ img->pitch*y]; png_write_rows(_png, &rowPointers, 1); } } else { for( int y=img->h-1; y>=0; y--) { png_bytep rowPointers = &data[ img->pitch*y]; png_write_rows(_png, &rowPointers, 1); } } close( fp); return true; } //write a chunk of png data void PNG::writeData( png_structp png, png_bytep data, png_size_t length) { png_size_t check; check = fwrite( data, 1, length, (FILE *)(png->io_ptr)); if( check != length) { png_error( png, "Write Error"); } } //init with file pointer and size of bitmap bool PNG::init( FILE *fp, int width, int height) { _png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL); if( _png == NULL) { fclose( fp); return false; } _info = png_create_info_struct(_png); if( _info == NULL) { fclose(fp); png_destroy_write_struct(&_png, (png_infopp)NULL); return false; } if( setjmp(_png->jmpbuf)) { fclose( fp); png_destroy_write_struct(&_png, (png_infopp)NULL); return false; } png_set_write_fn(_png, (void *)fp, PNG::writeData, NULL); int colorType = PNG_COLOR_TYPE_RGB; if( _alpha) colorType = PNG_COLOR_TYPE_RGB_ALPHA; png_set_IHDR( _png, _info, width, height, 8 /*depth*/, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info( _png, _info); return true; } //close png file void PNG::close( FILE *fp) { png_write_end( _png, _info); png_destroy_write_struct( &_png, (png_infopp)NULL); fclose(fp); }
gpl-2.0
hieuit7/freewifi
web/module/Login/autoload_classmap.php
213
<?php /* * 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. */ return array(); ?>
gpl-2.0
mikepea/pkg-puppet-debian
spec/unit/indirector/catalog/compiler.rb
9991
#!/usr/bin/env ruby # # Created by Luke Kanies on 2007-9-23. # Copyright (c) 2007. All rights reserved. require File.dirname(__FILE__) + '/../../../spec_helper' require 'puppet/indirector/catalog/compiler' describe Puppet::Resource::Catalog::Compiler do describe "when initializing" do before do Puppet.expects(:version).returns(1) Facter.expects(:value).with('fqdn').returns("my.server.com") Facter.expects(:value).with('ipaddress').returns("my.ip.address") end it "should gather data about itself" do Puppet::Resource::Catalog::Compiler.new end it "should cache the server metadata and reuse it" do compiler = Puppet::Resource::Catalog::Compiler.new node1 = stub 'node1', :merge => nil node2 = stub 'node2', :merge => nil compiler.stubs(:compile) Puppet::Node.stubs(:find).with('node1').returns(node1) Puppet::Node.stubs(:find).with('node2').returns(node2) compiler.find(stub('request', :node => 'node1', :options => {})) compiler.find(stub('node2request', :node => 'node2', :options => {})) end it "should provide a method for determining if the catalog is networked" do compiler = Puppet::Resource::Catalog::Compiler.new compiler.should respond_to(:networked?) end end describe "when creating the interpreter" do before do # This gets pretty annoying on a plane where we have no IP address Facter.stubs(:value).returns("whatever") @compiler = Puppet::Resource::Catalog::Compiler.new end it "should not create the interpreter until it is asked for the first time" do interp = mock 'interp' Puppet::Parser::Interpreter.expects(:new).with().returns(interp) @compiler.interpreter.should equal(interp) end it "should use the same interpreter for all compiles" do interp = mock 'interp' Puppet::Parser::Interpreter.expects(:new).with().returns(interp) @compiler.interpreter.should equal(interp) @compiler.interpreter.should equal(interp) end end describe "when finding catalogs" do before do Facter.stubs(:value).returns("whatever") env = stub 'environment', :name => "yay", :modulepath => [] Puppet::Node::Environment.stubs(:new).returns(env) @compiler = Puppet::Resource::Catalog::Compiler.new @name = "me" @node = Puppet::Node.new @name @node.stubs(:merge) @request = stub 'request', :key => "does not matter", :node => @name, :options => {} end it "should directly use provided nodes" do Puppet::Node.expects(:find).never @compiler.expects(:compile).with(@node) @request.stubs(:options).returns(:use_node => @node) @compiler.find(@request) end it "should use the request's node name if no explicit node is provided" do Puppet::Node.expects(:find).with(@name).returns(@node) @compiler.expects(:compile).with(@node) @compiler.find(@request) end it "should use the provided node name if no explicit node is provided and no authenticated node information is available" do @request.expects(:node).returns nil @request.expects(:key).returns "my_node" Puppet::Node.expects(:find).with("my_node").returns @node @compiler.expects(:compile).with(@node) @compiler.find(@request) end it "should fail if no node is passed and none can be found" do Puppet::Node.stubs(:find).with(@name).returns(nil) proc { @compiler.find(@request) }.should raise_error(ArgumentError) end it "should fail intelligently when searching for a node raises an exception" do Puppet::Node.stubs(:find).with(@name).raises "eh" proc { @compiler.find(@request) }.should raise_error(Puppet::Error) end it "should pass the found node to the interpreter for compiling" do Puppet::Node.expects(:find).with(@name).returns(@node) config = mock 'config' @compiler.interpreter.expects(:compile).with(@node) @compiler.find(@request) end it "should extract and save any facts from the request" do Puppet::Node.expects(:find).with(@name).returns @node @compiler.expects(:extract_facts_from_request).with(@request) @compiler.interpreter.stubs(:compile) @compiler.find(@request) end it "should return the results of compiling as the catalog" do Puppet::Node.stubs(:find).returns(@node) config = mock 'config' result = mock 'result' @compiler.interpreter.expects(:compile).with(@node).returns(result) @compiler.find(@request).should equal(result) end it "should benchmark the compile process" do Puppet::Node.stubs(:find).returns(@node) @compiler.stubs(:networked?).returns(true) @compiler.expects(:benchmark).with do |level, message| level == :notice and message =~ /^Compiled catalog/ end @compiler.interpreter.stubs(:compile).with(@node) @compiler.find(@request) end end describe "when extracting facts from the request" do before do @compiler = Puppet::Resource::Catalog::Compiler.new @request = stub 'request', :options => {} @facts = stub 'facts', :save => nil end it "should do nothing if no facts are provided" do Puppet::Node::Facts.expects(:convert_from).never @request.options[:facts] = nil @compiler.extract_facts_from_request(@request) end it "should use the Facts class to deserialize the provided facts" do @request.options[:facts_format] = "foo" @request.options[:facts] = "bar" Puppet::Node::Facts.expects(:convert_from).returns @facts @compiler.extract_facts_from_request(@request) end it "should use the provided fact format" do @request.options[:facts_format] = "foo" @request.options[:facts] = "bar" Puppet::Node::Facts.expects(:convert_from).with { |format, text| format == "foo" }.returns @facts @compiler.extract_facts_from_request(@request) end it "should convert the facts into a fact instance and save it" do @request.options[:facts_format] = "foo" @request.options[:facts] = "bar" Puppet::Node::Facts.expects(:convert_from).returns @facts @facts.expects(:save) @compiler.extract_facts_from_request(@request) end end describe "when finding nodes" do before do Facter.stubs(:value).returns("whatever") @compiler = Puppet::Resource::Catalog::Compiler.new @name = "me" @node = mock 'node' @request = stub 'request', :node => @name, :options => {} @compiler.stubs(:compile) end it "should look node information up via the Node class with the provided key" do @node.stubs :merge Puppet::Node.expects(:find).with(@name).returns(@node) @compiler.find(@request) end end describe "after finding nodes" do before do Puppet.expects(:version).returns(1) Facter.expects(:value).with('fqdn').returns("my.server.com") Facter.expects(:value).with('ipaddress').returns("my.ip.address") @compiler = Puppet::Resource::Catalog::Compiler.new @name = "me" @node = mock 'node' @request = stub 'request', :node => @name, :options => {} @compiler.stubs(:compile) Puppet::Node.stubs(:find).with(@name).returns(@node) end it "should add the server's Puppet version to the node's parameters as 'serverversion'" do @node.expects(:merge).with { |args| args["serverversion"] == "1" } @compiler.find(@request) end it "should add the server's fqdn to the node's parameters as 'servername'" do @node.expects(:merge).with { |args| args["servername"] == "my.server.com" } @compiler.find(@request) end it "should add the server's IP address to the node's parameters as 'serverip'" do @node.expects(:merge).with { |args| args["serverip"] == "my.ip.address" } @compiler.find(@request) end end describe "when filtering resources" do before :each do @compiler = Puppet::Resource::Catalog::Compiler.new @catalog = stub_everything 'catalog' @catalog.stubs(:respond_to?).with(:filter).returns(true) end it "should delegate to the catalog instance filtering" do @catalog.expects(:filter) @compiler.filter(@catalog) end it "should filter out virtual resources" do resource = mock 'resource', :virtual? => true @catalog.stubs(:filter).yields(resource) @compiler.filter(@catalog) end it "should return the same catalog if it doesn't support filtering" do @catalog.stubs(:respond_to?).with(:filter).returns(false) @compiler.filter(@catalog).should == @catalog end it "should return the filtered catalog" do catalog = stub 'filtered catalog' @catalog.stubs(:filter).returns(catalog) @compiler.filter(@catalog).should == catalog end end end
gpl-2.0
tronsha/homepage
wp-content/themes/basic/index.php
278
<?php get_header(); ?> <h1><?php the_title(); ?></h1> <?php if(has_post_thumbnail()) { the_post_thumbnail(); } ?> <?php if (have_posts()) { while (have_posts()) { the_post(); the_content(); } } ?> <br style="clear: both"> <?php get_footer(); ?>
gpl-2.0
Saarlonz/Ilch-2.0
application/modules/guestbook/models/Entry.php
3274
<?php /** * @copyright Ilch 2.0 * @package ilch */ namespace Modules\Guestbook\Models; class Entry extends \Ilch\Model { /** * The id of the entry. * * @var integer */ protected $id; /** * The email of the entry. * * @var string */ protected $email; /** * The text of the entry. * * @var string */ protected $text; /** * The name of the entry. * * @var string */ protected $name; /** * The homepage of the entry. * * @var string */ protected $homepage; /** * The datetime of the entry. * * @var string */ protected $datetime; /** * The setfee of the entry. * * @var integer */ protected $setFree; /** * Gets the id of the entry. * * @return integer */ public function getId() { return $this->id; } /** * Gets the email of the entry. * * @return string */ public function getEmail() { return $this->email; } /** * Gets the text of the entry. * * @return string */ public function getText() { return $this->text; } /** * Gets the name of the entry. * * @return string */ public function getName() { return $this->name; } /** * Gets the homepage of the entry. * * @return string */ public function getHomepage() { return $this->homepage; } /** * Gets the datetime of the entry. * * @return string */ public function getDatetime() { return $this->datetime; } /** * Gets the setfree of the entry. * * @return string */ public function getFree() { return $this->setFree; } /** * Sets the id of the entry. * * @param integer $id */ public function setId($id) { $this->id = (int)$id; return $this; } /** * Sets the email. * * @param string $email */ public function setEmail($email) { $this->email = (string)$email; return $this; } /** * Sets the text of the entry. * * @param string $text */ public function setText($text) { $this->text = (string)$text; return $this; } /** * Sets the name of the entry. * * @param string $name */ public function setName($name) { $this->name = (string)$name; return $this; } /** * Sets the homepage of the entry. * * @param string $homepage */ public function setHomepage($homepage) { $this->homepage = (string)$homepage; return $this; } /** * Sets the datetime of the entry. * * @param string $datetime */ public function setDatetime($datetime) { $this->datetime = (string)$datetime; return $this; } /** * Sets the free of the entry. * * @param integer $free */ public function setFree($free) { $this->setFree = (integer)$free; return $this; } }
gpl-2.0
rylynchen/ekff
sites/all/includes/jquery-impromptu.3.2.js
11178
/* * jQuery Impromptu * By: Trent Richardson [http://trentrichardson.com] * Version 3.2 * Last Modified: 10/12/2011 * * Copyright 2011 Trent Richardson * Dual licensed under the MIT and GPL licenses. * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt * */ (function($) { $.prompt = function(message, options) { options = $.extend({},$.prompt.defaults,options); $.prompt.currentPrefix = options.prefix; var ie6 = ($.browser.msie && $.browser.version < 7); var $body = $(document.body); var $window = $(window); options.classes = $.trim(options.classes); if(options.classes != '') options.classes = ' '+ options.classes; //build the box and fade var msgbox = '<div class="'+ options.prefix +'box'+ options.classes +'" id="'+ options.prefix +'box">'; if(options.useiframe && (($('object, applet').length > 0) || ie6)) { msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></iframe>'; } else { if(ie6) { $('select').css('visibility','hidden'); } msgbox +='<div class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></div>'; } msgbox += '<div class="'+ options.prefix +'" id="'+ options.prefix +'"><div class="'+ options.prefix +'container"><div class="'; msgbox += options.prefix +'close">X</div><div id="'+ options.prefix +'states"></div>'; msgbox += '</div></div></div>'; var $jqib = $(msgbox).appendTo($body); var $jqi = $jqib.children('#'+ options.prefix); var $jqif = $jqib.children('#'+ options.prefix +'fade'); //if a string was passed, convert to a single state if(message.constructor == String){ message = { state0: { html: message, buttons: options.buttons, focus: options.focus, submit: options.submit } }; } //build the states var states = ""; $.each(message,function(statename,stateobj){ stateobj = $.extend({},$.prompt.defaults.state,stateobj); message[statename] = stateobj; states += '<div id="'+ options.prefix +'_state_'+ statename +'" class="'+ options.prefix + '_state" style="display:none;"><div class="'+ options.prefix +'message">' + stateobj.html +'</div><div class="'+ options.prefix +'buttons">'; $.each(stateobj.buttons, function(k, v){ if(typeof v == 'object') states += '<button name="' + options.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" id="' + options.prefix + '_' + statename + '_button' + v.title.replace(/[^a-z0-9]+/gi,'') + '" value="' + v.value + '">' + v.title + '</button>'; else states += '<button name="' + options.prefix + '_' + statename + '_button' + k + '" id="' + options.prefix + '_' + statename + '_button' + k + '" value="' + v + '">' + k + '</button>'; }); states += '</div></div>'; }); //insert the states... $jqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block'); $jqi.find('.'+ options.prefix +'buttons:empty').css('display','none'); //Events $.each(message,function(statename,stateobj){ var $state = $jqi.find('#'+ options.prefix +'_state_'+ statename); $state.children('.'+ options.prefix +'buttons').children('button').click(function(){ var msg = $state.children('.'+ options.prefix +'message'); var clicked = stateobj.buttons[$(this).text()]; if(clicked == undefined){ for(var i in stateobj.buttons) if(stateobj.buttons[i].title == $(this).text()) clicked = stateobj.buttons[i].value; } if(typeof clicked == 'object') clicked = clicked.value; var forminputs = {}; //collect all form element values from all states $.each($jqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){ if (forminputs[obj.name] === undefined) { forminputs[obj.name] = obj.value; } else if (typeof forminputs[obj.name] == Array || typeof forminputs[obj.name] == 'object') { forminputs[obj.name].push(obj.value); } else { forminputs[obj.name] = [forminputs[obj.name],obj.value]; } }); var close = stateobj.submit(clicked,msg,forminputs); if(close === undefined || close) { removePrompt(true,clicked,msg,forminputs); } }); $state.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton'); }); var fadeClicked = function(){ if(options.persistent){ var offset = (options.top.toString().indexOf('%') >= 0? ($window.height()*(parseInt(options.top,10)/100)) : parseInt(options.top,10)), top = parseInt($jqi.css('top').replace('px',''),10) - offset; //$window.scrollTop(top); $('html,body').animate({ scrollTop: top }, 'fast', function(){ var i = 0; $jqib.addClass(options.prefix +'warning'); var intervalid = setInterval(function(){ $jqib.toggleClass(options.prefix +'warning'); if(i++ > 1){ clearInterval(intervalid); $jqib.removeClass(options.prefix +'warning'); } }, 100); }); } else { removePrompt(); } }; var keyPressEventHandler = function(e){ var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox? //escape key closes if(key==27) { fadeClicked(); } //constrain tabs if (key == 9){ var $inputels = $(':input:enabled:visible',$jqib); var fwd = !e.shiftKey && e.target == $inputels[$inputels.length-1]; var back = e.shiftKey && e.target == $inputels[0]; if (fwd || back) { setTimeout(function(){ if (!$inputels) return; var el = $inputels[back===true ? $inputels.length-1 : 0]; if (el) el.focus(); },10); return false; } } }; var positionPrompt = function(){ var bodyHeight = $body.outerHeight(true), windowHeight = $window.height(), height = bodyHeight > windowHeight ? bodyHeight : windowHeight, top = parseInt($window.scrollTop(),10) + (options.top.toString().indexOf('%') >= 0? (windowHeight*(parseInt(options.top,10)/100)) : parseInt(options.top,10)); $jqib.css({ position: "absolute", height: height, width: "100%", top: 0, left: 0, right: 0, bottom: 0 }); $jqif.css({ position: "absolute", height: height, width: "100%", top: 0, left: 0, right: 0, bottom: 0 }); $jqi.css({ position: "absolute", top: top, left: "50%", marginLeft: (($jqi.outerWidth()/2)*-1) }); }; var stylePrompt = function(){ $jqif.css({ zIndex: options.zIndex, display: "none", opacity: options.opacity }); $jqi.css({ zIndex: options.zIndex+1, display: "none" }); $jqib.css({ zIndex: options.zIndex }); }; var removePrompt = function(callCallback, clicked, msg, formvals){ $jqi.remove(); $window.unbind('resize',positionPrompt); $jqif.fadeOut(options.overlayspeed,function(){ $jqif.unbind('click',fadeClicked); $jqif.remove(); if(callCallback) { options.callback(clicked,msg,formvals); } $jqib.unbind('keypress',keyPressEventHandler); $jqib.remove(); if(ie6 && !options.useiframe) { $('select').css('visibility','visible'); } }); }; positionPrompt(); stylePrompt(); $jqif.click(fadeClicked); $window.resize(positionPrompt); $jqib.bind("keydown keypress",keyPressEventHandler); $jqi.find('.'+ options.prefix +'close').click(removePrompt); //Show it $jqif.fadeIn(options.overlayspeed); $jqi[options.show](options.promptspeed,options.loaded); $jqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus(); if(options.timeout > 0) setTimeout($.prompt.close,options.timeout); return $jqib; }; $.prompt.defaults = { prefix:'jqi', classes: '', buttons: { Ok: true }, loaded: function(){ }, submit: function(){ return true; }, callback: function(){ }, opacity: 0.6, zIndex: 999, overlayspeed: 'slow', promptspeed: 'fast', show: 'promptDropIn', focus: 0, useiframe: false, top: '15%', persistent: true, timeout: 0, state: { html: '', buttons: { Ok: true }, focus: 0, submit: function(){ return true; } } }; $.prompt.currentPrefix = $.prompt.defaults.prefix; $.prompt.setDefaults = function(o) { $.prompt.defaults = $.extend({}, $.prompt.defaults, o); }; $.prompt.setStateDefaults = function(o) { $.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o); }; $.prompt.getStateContent = function(state) { return $('#'+ $.prompt.currentPrefix +'_state_'+ state); }; $.prompt.getCurrentState = function() { return $('.'+ $.prompt.currentPrefix +'_state:visible'); }; $.prompt.getCurrentStateName = function() { var stateid = $.prompt.getCurrentState().attr('id'); return stateid.replace($.prompt.currentPrefix +'_state_',''); }; $.prompt.goToState = function(state, callback) { $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); $('#'+ $.prompt.currentPrefix +'_state_'+ state).slideDown('slow',function(){ $(this).find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); if (typeof callback == 'function') callback(); }); }; $.prompt.nextState = function(callback) { var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').next(); $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); $next.slideDown('slow',function(){ $next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); if (typeof callback == 'function') callback(); }); }; $.prompt.prevState = function(callback) { var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').prev(); $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); $next.slideDown('slow',function(){ $next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); if (typeof callback == 'function') callback(); }); }; $.prompt.close = function() { $('#'+ $.prompt.currentPrefix +'box').fadeOut('fast',function(){ $(this).remove(); }); }; $.fn.extend({ prompt: function(options){ if(options == undefined) options = {}; if(options.withDataAndEvents == undefined) options.withDataAndEvents = false; $.prompt($(this).clone(options.withDataAndEvents).html(),options); }, promptDropIn: function(speed, callback){ var $t = $(this); if($t.css("display") == "none"){ var eltop = $t.css('top'); $t.css({ top: $(window).scrollTop(), display: 'block' }).animate({ top: eltop },speed,'swing',callback); } } }); })(jQuery);
gpl-2.0
wp-plugins/quickstart
php/aliases.php
9158
<?php /** * QuickStart External Alias Functions * * @package QuickStart * @subpackage Aliases * @since 1.0.0 */ /** * Setup function, process the theme configurations and defaults. * * @since 1.0.0 * * @param array $configs An associative array of theme configuration options. * @param array $default Optional an associative array of default values to use. * @param bool $global Optional Wether or not to assign this new instance to the $QuickStart global variable. * * @return QuickStart $QS The class instance. */ function QuickStart( $configs, $defaults = array(), $global = false ) { $obj = new QuickStart\Setup( $configs, $defaults ); if ( $global ) { global $QuickStart; $QuickStart = $obj; } return $obj; } // ========================= // !Template aliases // ========================= /** * @see QuickStart\Template::the_head() */ function qs_the_head() { call_user_func_array( array( 'QuickStart\Template', 'the_head' ), func_get_args() ); } /** * @see QuickStart\Template::doc_start() */ function qs_doc_start() { call_user_func_array( array( 'QuickStart\Template', 'doc_start' ), func_get_args() ); } /** * @see QuickStart\Template::viewport() */ function qs_viewport() { call_user_func_array( array( 'QuickStart\Template', 'viewport' ), func_get_args() ); } /** * @see QuickStart\Template::title() */ function qs_title() { call_user_func_array( array( 'QuickStart\Template', 'title' ), func_get_args() ); } /** * @see QuickStart\Template::title_filter() */ function qs_title_filter() { call_user_func_array( array( 'QuickStart\Template', 'title_filter' ), func_get_args() ); } /** * @see QuickStart\Template::favicon() */ function qs_favicon() { call_user_func_array( array( 'QuickStart\Template', 'favicon' ), func_get_args() ); } /** * @see QuickStart\Template::ie_css() */ function qs_ie_css() { call_user_func_array( array( 'QuickStart\Template', 'ie_css' ), func_get_args() ); } /** * @see QuickStart\Template::html5shiv() */ function qs_html5shiv() { call_user_func_array( array( 'QuickStart\Template', 'html5shiv' ), func_get_args() ); } /** * @see QuickStart\Template::ajaxurl() */ function qs_ajaxurl() { call_user_func_array( array( 'QuickStart\Template', 'ajaxurl' ), func_get_args() ); } /** * @see QuickStart\Template::template_url() */ function qs_template_url() { call_user_func_array( array( 'QuickStart\Template', 'template_url' ), func_get_args() ); } /** * @see QuickStart\Template::theme_url() */ function qs_theme_url() { call_user_func_array( array( 'QuickStart\Template', 'theme_url' ), func_get_args() ); } /** * @see QuickStart\Template::ga_code() */ function qs_ga_code() { call_user_func_array( array( 'QuickStart\Template', 'ga_code' ), func_get_args() ); } // ========================= // !Tools aliases // ========================= /** * @see QuickStart\Tools::build_tag() */ function qs_build_tag() { call_user_func_array( array( 'QuickStart\Tools', 'build_tag' ), func_get_args() ); } /** * @see QuickStart\Tools::load_helpers() */ function qs_load_helpers() { call_user_func_array( array( 'QuickStart\Tools', 'load_helpers' ), func_get_args() ); } /** * @see QuickStart\Tools::upload() */ function qs_upload() { call_user_func_array( array( 'QuickStart\Tools', 'upload' ), func_get_args() ); } /** * @see QuickStart\Tools::maybe_prefix_post_field() */ function qs_maybe_prefix_post_field() { call_user_func_array( array( 'QuickStart\Tools', 'maybe_prefix_post_field' ), func_get_args() ); } /** * @see QuickStart\Tools::save_post_check() */ function qs_save_post_check() { call_user_func_array( array( 'QuickStart\Tools', 'save_post_check' ), func_get_args() ); } /** * @see QuickStart\Tools::build_meta_box() */ function qs_build_meta_box() { call_user_func_array( array( 'QuickStart\Tools', 'build_meta_box' ), func_get_args() ); } /** * @see QuickStart\Tools::build_settings_field() */ function qs_build_settings_field() { call_user_func_array( array( 'QuickStart\Tools', 'build_settings_field' ), func_get_args() ); } /** * @see QuickStart\Tools::build_field_row() */ function qs_build_field_row() { call_user_func_array( array( 'QuickStart\Tools', 'build_field_row' ), func_get_args() ); } /** * @see QuickStart\Tools::extra_editor() */ function qs_extra_editor() { call_user_func_array( array( 'QuickStart\Tools', 'extra_editor' ), func_get_args() ); } /** * @see QuickStart\Tools::geocode_address() */ function qs_geocode_address() { call_user_func_array( array( 'QuickStart\Tools', 'geocode_address' ), func_get_args() ); } /** * @see QuickStart\Tools::enqueue() */ function qs_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::quick_enqueue() */ function qs_quick_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'quick_enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::add_hooks() */ function qs_add_hooks() { call_user_func_array( array( 'QuickStart\Tools', 'add_hooks' ), func_get_args() ); } /** * @see QuickStart\Tools::add_callbacks() */ function qs_add_callbacks() { call_user_func_array( array( 'QuickStart\Tools', 'add_callbacks' ), func_get_args() ); } /** * @see QuickStart\Tools::simple_shortcode() */ function qs_simple_shortcode() { call_user_func_array( array( 'QuickStart\Tools', 'simple_shortcode' ), func_get_args() ); } /** * @see QuickStart\Tools::register_shortcodes() */ function qs_register_shortcodes() { call_user_func_array( array( 'QuickStart\Tools', 'register_shortcodes' ), func_get_args() ); } /** * @see QuickStart\Tools::hide() */ function qs_hide() { call_user_func_array( array( 'QuickStart\Tools', 'hide' ), func_get_args() ); } /** * @see QuickStart\Tools::hide_posts() */ function qs_hide_posts() { call_user_func_array( array( 'QuickStart\Tools', 'hide_posts' ), func_get_args() ); } /** * @see QuickStart\Tools::hide_pages() */ function qs_hide_pages() { call_user_func_array( array( 'QuickStart\Tools', 'hide_pages' ), func_get_args() ); } /** * @see QuickStart\Tools::hide_comments() */ function qs_hide_comments() { call_user_func_array( array( 'QuickStart\Tools', 'hide_comments' ), func_get_args() ); } /** * @see QuickStart\Tools::hide_links() */ function qs_hide_links() { call_user_func_array( array( 'QuickStart\Tools', 'hide_links' ), func_get_args() ); } /** * @see QuickStart\Tools::hide_wp_head() */ function qs_hide_wp_head() { call_user_func_array( array( 'QuickStart\Tools', 'hide_wp_head' ), func_get_args() ); } /** * @see QuickStart\Tools::relabel_posts() */ function qs_relabel_posts() { call_user_func_array( array( 'QuickStart\Tools', 'relabel_posts' ), func_get_args() ); } /** * @see QuickStart\Tools::_fix_shortcodes() */ function qs_fix_shortcodes() { call_user_func_array( array( 'QuickStart\Tools', 'fix_shortcodes' ), func_get_args() ); } /** * @see QuickStart\Tools::_do_quicktags() */ function qs_do_quicktags() { call_user_func_array( array( 'QuickStart\Tools', 'do_quicktags' ), func_get_args() ); } /** * @see QuickStart\Tools::_disable_quickedit() */ function qs_disable_quickedit() { call_user_func_array( array( 'QuickStart\Tools', 'disable_quickedit' ), func_get_args() ); } /** * @see QuickStart\Tools::_frontend_enqueue() */ function qs_frontend_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'frontend_enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::_backend_enqueue() */ function qs_backend_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'backend_enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::_quick_frontend_enqueue() */ function qs_quick_frontend_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'quick_frontend_enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::_quick_backend_enqueue() */ function qs_quick_backend_enqueue() { call_user_func_array( array( 'QuickStart\Tools', 'quick_backend_enqueue' ), func_get_args() ); } /** * @see QuickStart\Tools::_edit_meta_box() */ function qs_edit_meta_box() { call_user_func_array( array( 'QuickStart\Tools', 'edit_meta_box' ), func_get_args() ); } /** * @see QuickStart\Tools::_taxonomy_filter() */ function qs_taxonomy_filter() { call_user_func_array( array( 'QuickStart\Tools', 'taxonomy_filter' ), func_get_args() ); } /** * @see QuickStart\Tools::_print_extra_editor() */ function qs_print_extra_editor() { call_user_func_array( array( 'QuickStart\Tools', 'print_extra_editor' ), func_get_args() ); } /** * @see QuickStart\Tools::_print_extra_editor_above() */ function qs_print_extra_editor_above() { call_user_func_array( array( 'QuickStart\Tools', 'print_extra_editor_above' ), func_get_args() ); } /** * @see QuickStart\Tools::_print_extra_editor_below() */ function qs_print_extra_editor_below() { call_user_func_array( array( 'QuickStart\Tools', 'print_extra_editor_below' ), func_get_args() ); } /** * @see QuickStart\Tools::_add_query_var() */ function qs_add_query_var() { call_user_func_array( array( 'QuickStart\Tools', 'add_query_var' ), func_get_args() ); }
gpl-2.0
AazzIT/MyHomeWork
src/lesson6/fileSystem/AudioFile.java
500
package lesson6.fileSystem; public class AudioFile extends File { public AudioFile(String name, File parentFolder) { if (name.substring(name.length() - 4 ,name.length()).equals(MP3_EXTENSION)) { //Хардкод super.setName(name); super.setType(AUDIO_FILE_TYPE); //Хардкод super.setParentFolder(parentFolder); } else throw new IllegalStateException("[Error]: Illegal File Extension of Audio File! Must be .mp3"); } }
gpl-2.0
lewlewstar/test
hw.py
44
# Hello world program print "Hello world!"
gpl-2.0
shalomRachapudi/AlgoBench
Frontend/src/inf2b/algobench/util/ITaskSubPanel.java
1686
/* * The MIT License * * Copyright 2015 Eziama Ubachukwu (eziama.ubachukwu@gmail.com). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package inf2b.algobench.util; /** * * @author eziama ubachukwu */ public interface ITaskSubPanel { public void setInputSize(String size); public void setCurrentSize(String currentSize); public void setInitialSize(String startSize); public void setFinalSize(String startSize); public void setStepSize(String stepSize); public void setMemUsage(String memUsage); public void setNumCompletedTasks(String numCompletedTasks); public void setNumTasks(String numTasks); }
gpl-2.0
videolabs/vlc-android
vlc-android/tv/src/org/videolan/vlc/gui/tv/audioplayer/AudioPlayerActivity.java
13004
/***************************************************************************** * AudioPlayerActivity.java ***************************************************************************** * Copyright © 2014-2015 VLC authors, VideoLAN and VideoLabs * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.gui.tv.audioplayer; import java.util.ArrayList; import java.util.Collections; import org.videolan.vlc.MediaLibrary; import org.videolan.libvlc.MediaWrapper; import org.videolan.vlc.R; import org.videolan.vlc.audio.AudioServiceController; import org.videolan.vlc.audio.RepeatType; import org.videolan.vlc.gui.DividerItemDecoration; import org.videolan.vlc.gui.audio.AudioUtil; import org.videolan.vlc.gui.audio.MediaComparators; import org.videolan.vlc.interfaces.IAudioPlayer; import org.videolan.vlc.util.AndroidDevices; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class AudioPlayerActivity extends Activity implements AudioServiceController.AudioServiceConnectionListener, IAudioPlayer, View.OnFocusChangeListener { public static final String TAG = "VLC/AudioPlayerActivity"; public static final String MEDIA_LIST = "media_list"; private AudioServiceController mAudioController; private RecyclerView mRecyclerView; private PlaylistAdapter mAdapter; private LinearLayoutManager mLayoutManager; private ArrayList<MediaWrapper> mMediaList; //PAD navigation private static final int JOYSTICK_INPUT_DELAY = 300; private long mLastMove; private int mCurrentlyPlaying, mPositionSaved = 0; private boolean mShuffling = false; private TextView mTitleTv, mArtistTv; private ImageView mPlayPauseButton, mCover, mNext, mShuffle, mRepeat; private ProgressBar mProgressBar; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tv_audio_player); mMediaList = getIntent().getParcelableArrayListExtra(MEDIA_LIST); mRecyclerView = (RecyclerView) findViewById(R.id.playlist); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); if (mMediaList == null) mMediaList = new ArrayList<MediaWrapper>(); // if (getIntent().getData() != null) // mMediaList.add(getIntent().getDataString()); mAdapter = new PlaylistAdapter(this, mMediaList); mRecyclerView.setAdapter(mAdapter); mAudioController = AudioServiceController.getInstance(); mAudioController.getRepeatType(); mTitleTv = (TextView)findViewById(R.id.media_title); mArtistTv = (TextView)findViewById(R.id.media_artist); mNext = (ImageView)findViewById(R.id.button_next); mPlayPauseButton = (ImageView)findViewById(R.id.button_play); mShuffle = (ImageView)findViewById(R.id.button_shuffle); mRepeat = (ImageView)findViewById(R.id.button_repeat); mProgressBar = (ProgressBar)findViewById(R.id.media_progress); mCover = (ImageView)findViewById(R.id.album_cover); findViewById(R.id.button_shuffle).setOnFocusChangeListener(this); } public void onStart(){ super.onStart(); mAudioController.bindAudioService(this, this); mAudioController.addAudioPlayer(this); } public void onStop(){ super.onStop(); mAudioController.removeAudioPlayer(this); mAudioController.unbindAudioService(this); mMediaList.clear(); } protected void onResume() { super.onResume(); mRecyclerView.post(new Runnable() { @Override public void run() { update(); } }); }; @Override public void onConnectionSuccess() { ArrayList<MediaWrapper> medias = (ArrayList<MediaWrapper>) mAudioController.getMedias(); if (!mMediaList.isEmpty() && !mMediaList.equals(medias)) { mAudioController.load(mMediaList, 0); } else { mMediaList = medias; update(); mAdapter = new PlaylistAdapter(this, mMediaList); mRecyclerView.setAdapter(mAdapter); } } @Override public void onConnectionFailed() {} @Override public void update() { mPlayPauseButton.setImageResource(mAudioController.isPlaying() ? R.drawable.ic_pause : R.drawable.ic_play); if (mAudioController.hasMedia()) { mTitleTv.setText(mAudioController.getTitle()); mArtistTv.setText(mAudioController.getArtist()); mProgressBar.setMax(mAudioController.getLength()); MediaWrapper MediaWrapper = MediaLibrary.getInstance().getMediaItem(mAudioController.getCurrentMediaLocation()); Bitmap cover = AudioUtil.getCover(this, MediaWrapper, mCover.getWidth()); if (cover == null) cover = mAudioController.getCover(); if (cover == null) mCover.setImageResource(R.drawable.background_cone); else mCover.setImageBitmap(cover); } } @Override public void updateProgress() { mProgressBar.setProgress(mAudioController.getTime()); } public boolean onKeyDown(int keyCode, KeyEvent event){ switch (keyCode){ /* * Playback control */ case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: case KeyEvent.KEYCODE_MEDIA_PLAY: case KeyEvent.KEYCODE_MEDIA_PAUSE: case KeyEvent.KEYCODE_SPACE: togglePlayPause(); return true; case KeyEvent.KEYCODE_F: case KeyEvent.KEYCODE_BUTTON_R1: goNext(); return true; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: seek(10000); return true; case KeyEvent.KEYCODE_MEDIA_REWIND: seek(-10000); return true; case KeyEvent.KEYCODE_R: case KeyEvent.KEYCODE_BUTTON_L1: goPrevious(); return true; /* * Playlist navigation */ case KeyEvent.KEYCODE_DPAD_UP: selectPrevious(); mRecyclerView.requestFocus(); return true; case KeyEvent.KEYCODE_DPAD_DOWN: selectNext(); mRecyclerView.requestFocus(); return true; case KeyEvent.KEYCODE_DPAD_CENTER: if (mRecyclerView.hasFocus()) { playSelection(); return true; } else return false; default: return super.onKeyDown(keyCode, event); } } public void playSelection() { mAudioController.playIndex(mAdapter.getmSelectedItem()); mCurrentlyPlaying = mAdapter.getmSelectedItem(); } public boolean dispatchGenericMotionEvent(MotionEvent event){ //Check for a joystick event if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK || event.getAction() != MotionEvent.ACTION_MOVE) return false; InputDevice inputDevice = event.getDevice(); float dpadx = event.getAxisValue(MotionEvent.AXIS_HAT_X); float dpady = event.getAxisValue(MotionEvent.AXIS_HAT_Y); if (inputDevice == null || Math.abs(dpadx) == 1.0f || Math.abs(dpady) == 1.0f) return false; float x = AndroidDevices.getCenteredAxis(event, inputDevice, MotionEvent.AXIS_X); if (System.currentTimeMillis() - mLastMove > JOYSTICK_INPUT_DELAY){ if (Math.abs(x) > 0.3){ seek(x > 0.0f ? 10000 : -10000); mLastMove = System.currentTimeMillis(); return true; } } return true; } private void seek(int delta) { int time = mAudioController.getTime()+delta; if (time < 0 || time > mAudioController.getLength()) return; mAudioController.setTime(time); } public void onClick(View v){ switch (v.getId()){ case R.id.button_play: togglePlayPause(); break; case R.id.button_next: goNext(); break; case R.id.button_previous: goPrevious(); break; case R.id.button_repeat: updateRepeatMode(); break; case R.id.button_shuffle: setShuffleMode(!mShuffling); break; } } private void setShuffleMode(boolean shuffle) { mShuffling = shuffle; mShuffle.setImageResource(shuffle ? R.drawable.ic_shuffle_on : R.drawable.ic_shuffle); ArrayList<MediaWrapper> medias = (ArrayList<MediaWrapper>) mAudioController.getMedias(); if (shuffle){ Collections.shuffle(medias); } else { Collections.sort(medias, MediaComparators.byTrackNumber); } mAudioController.load(medias, 0); mAdapter.updateList(medias); update(); } private void updateRepeatMode() { RepeatType type = mAudioController.getRepeatType(); if (type == RepeatType.None){ mAudioController.setRepeatType(RepeatType.All); mRepeat.setImageResource(R.drawable.ic_repeat_on); } else if (type == RepeatType.All) { mAudioController.setRepeatType(RepeatType.Once); mRepeat.setImageResource(R.drawable.ic_repeat_one); } else if (type == RepeatType.Once) { mAudioController.setRepeatType(RepeatType.None); mRepeat.setImageResource(R.drawable.ic_repeat); } } private void goPrevious() { if (mAudioController.hasPrevious()) { mAudioController.previous(); selectItem(--mCurrentlyPlaying); } } private void goNext() { if (mAudioController.hasNext()){ mAudioController.next(); selectItem(++mCurrentlyPlaying); } } private void togglePlayPause() { if (mAudioController.isPlaying()) mAudioController.pause(); else if (mAudioController.hasMedia()) mAudioController.play(); } private void selectNext() { if (mAdapter.getmSelectedItem() >= mAdapter.getItemCount()-1) return; selectItem(mAdapter.getmSelectedItem()+1); } private void selectPrevious() { if (mAdapter.getmSelectedItem() < 1) return; selectItem(mAdapter.getmSelectedItem()-1); } private void selectItem(final int position){ if (position >= mMediaList.size()) return; mRecyclerView.post(new Runnable() { @Override public void run() { if (position != -1 && (position > mLayoutManager.findLastCompletelyVisibleItemPosition() || position < mLayoutManager.findFirstCompletelyVisibleItemPosition())) { mRecyclerView.stopScroll(); mRecyclerView.smoothScrollToPosition(position); } mAdapter.setSelection(position); } }); } @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (mAdapter.getmSelectedItem() != -1) mPositionSaved = mAdapter.getmSelectedItem(); selectItem(-1); } else if (!mNext.hasFocus()) selectItem(mPositionSaved); } }
gpl-2.0
kylemclaren/buddypress
wp-content/themes/chum/_inc/widgets/widget-shortcode.php
2965
<?php /* * Shortcode Widget Displat * Name: Centauri Testimonials * Class: widget-testimonial * Function: widget_testimonial * * Author: Patrick James Garcia * Company: Beenest Technology Solutions, Inc. * Author URI: http://www.beenest-tech.com * */ add_action( 'widgets_init', 'bn_shortcode_widget' ); function bn_shortcode_widget() { register_widget( 'shortcode_widget' ); } class shortcode_widget extends WP_Widget { function shortcode_widget() { $widget_ops = array( 'classname' => 'widget-shortcode', 'description' => __('A widget that displays any shortcode as widget', 'bn_shortcode_widget') ); $control_ops = array( 'id_base' => 'bn_shortcode_widget' ); $this->WP_Widget( 'bn_shortcode_widget', __('<span style="color: #ff5400;">[Chum]</span> Shortcode Display', 'bn_shortcode_widget'), $widget_ops, $control_ops ); } function widget( $args, $instance ) { extract( $args ); //Our variables from the widget settings. $title = apply_filters('widget_title', $instance['title'] ); $shortcode = $instance['shortcode']; $html = '<aside class="widget widget-shortcode-post"><h3 class="widget-title">' . $title . '</h3>'; $html .= do_shortcode( $shortcode ); $html .= '</aside>'; echo $html; } function update( $new_instance, $old_instance ) { $instance = $old_instance; //Strip tags from title and name to remove HTML $instance['title'] = strip_tags( $new_instance['title'] ); $instance['shortcode'] = strip_tags( $new_instance['shortcode'] ); return $instance; } function form( $instance ) { //Set up some default widget settings. $defaults = array( 'title' => __('Contact Form', 'bn_shortcode_widget'), 'shortcode' => __('[contact_form]', 'bn_shortcode_widget') ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <!-- Widget Title: Text Input --> <style> small {display: block; padding: 0 2px;} .widefat {margin-bottom: 3px;} #extended-text-widget-delete { color: red; margin-left: 5px; } #extended-text-widget-delete:hover { color: maroon; } select[id*="link_url"] { width: 100%; } </style> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'bn_shortcode_widget'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" type="text" /> </p> <p> <label for="<?php echo $this->get_field_id( 'shortcode' ); ?>"><?php _e('Shortcode:', 'bn_shortcode_widget'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'shortcode' ); ?>" name="<?php echo $this->get_field_name( 'shortcode' ); ?>" value="<?php echo $instance['shortcode']; ?>" type="text" /> </p> <?php } //form } //Testimonial_Widget
gpl-2.0
jamal-fuma/epic-food-frequency
include/boost/bind/mem_fn_vw.hpp
7951
// // bind/mem_fn_vw.hpp - void return helper wrappers // // Do not include this header directly // // Copyright (c) 2001 Peter Dimov and Multi Media Ltd. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/bind/mem_fn.html for documentation. // template<class R, class T> struct BOOST_MEM_FN_NAME(mf0): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf0)<R, T, R (BOOST_MEM_FN_CC T::*) ()> { typedef R (BOOST_MEM_FN_CC T::*F) (); explicit BOOST_MEM_FN_NAME(mf0)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf0)<R, T, F>(f) {} }; template<class R, class T> struct BOOST_MEM_FN_NAME(cmf0): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf0)<R, T, R (BOOST_MEM_FN_CC T::*) () const> { typedef R (BOOST_MEM_FN_CC T::*F) () const; explicit BOOST_MEM_FN_NAME(cmf0)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf0)<R, T, F>(f) {} }; template<class R, class T, class A1> struct BOOST_MEM_FN_NAME(mf1): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf1)<R, T, A1, R (BOOST_MEM_FN_CC T::*) (A1)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1); explicit BOOST_MEM_FN_NAME(mf1)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf1)<R, T, A1, F>(f) {} }; template<class R, class T, class A1> struct BOOST_MEM_FN_NAME(cmf1): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf1)<R, T, A1, R (BOOST_MEM_FN_CC T::*) (A1) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1) const; explicit BOOST_MEM_FN_NAME(cmf1)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf1)<R, T, A1, F>(f) {} }; template<class R, class T, class A1, class A2> struct BOOST_MEM_FN_NAME(mf2): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf2)<R, T, A1, A2, R (BOOST_MEM_FN_CC T::*) (A1, A2)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2); explicit BOOST_MEM_FN_NAME(mf2)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf2)<R, T, A1, A2, F>(f) {} }; template<class R, class T, class A1, class A2> struct BOOST_MEM_FN_NAME(cmf2): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf2)<R, T, A1, A2, R (BOOST_MEM_FN_CC T::*) (A1, A2) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2) const; explicit BOOST_MEM_FN_NAME(cmf2)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf2)<R, T, A1, A2, F>(f) {} }; template<class R, class T, class A1, class A2, class A3> struct BOOST_MEM_FN_NAME(mf3): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf3)<R, T, A1, A2, A3, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3); explicit BOOST_MEM_FN_NAME(mf3)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf3)<R, T, A1, A2, A3, F>(f) {} }; template<class R, class T, class A1, class A2, class A3> struct BOOST_MEM_FN_NAME(cmf3): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf3)<R, T, A1, A2, A3, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3) const; explicit BOOST_MEM_FN_NAME(cmf3)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf3)<R, T, A1, A2, A3, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4> struct BOOST_MEM_FN_NAME(mf4): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf4)<R, T, A1, A2, A3, A4, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4); explicit BOOST_MEM_FN_NAME(mf4)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf4)<R, T, A1, A2, A3, A4, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4> struct BOOST_MEM_FN_NAME(cmf4): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf4)<R, T, A1, A2, A3, A4, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4) const; explicit BOOST_MEM_FN_NAME(cmf4)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf4)<R, T, A1, A2, A3, A4, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5> struct BOOST_MEM_FN_NAME(mf5): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf5)<R, T, A1, A2, A3, A4, A5, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5); explicit BOOST_MEM_FN_NAME(mf5)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf5)<R, T, A1, A2, A3, A4, A5, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5> struct BOOST_MEM_FN_NAME(cmf5): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf5)<R, T, A1, A2, A3, A4, A5, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5) const; explicit BOOST_MEM_FN_NAME(cmf5)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf5)<R, T, A1, A2, A3, A4, A5, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6> struct BOOST_MEM_FN_NAME(mf6): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf6)<R, T, A1, A2, A3, A4, A5, A6, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6); explicit BOOST_MEM_FN_NAME(mf6)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf6)<R, T, A1, A2, A3, A4, A5, A6, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6> struct BOOST_MEM_FN_NAME(cmf6): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf6)<R, T, A1, A2, A3, A4, A5, A6, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6) const; explicit BOOST_MEM_FN_NAME(cmf6)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf6)<R, T, A1, A2, A3, A4, A5, A6, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7> struct BOOST_MEM_FN_NAME(mf7): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf7)<R, T, A1, A2, A3, A4, A5, A6, A7, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6, A7)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6, A7); explicit BOOST_MEM_FN_NAME(mf7)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf7)<R, T, A1, A2, A3, A4, A5, A6, A7, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7> struct BOOST_MEM_FN_NAME(cmf7): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf7)<R, T, A1, A2, A3, A4, A5, A6, A7, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6, A7) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6, A7) const; explicit BOOST_MEM_FN_NAME(cmf7)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf7)<R, T, A1, A2, A3, A4, A5, A6, A7, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> struct BOOST_MEM_FN_NAME(mf8): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf8)<R, T, A1, A2, A3, A4, A5, A6, A7, A8, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6, A7, A8)> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6, A7, A8); explicit BOOST_MEM_FN_NAME(mf8)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(mf8)<R, T, A1, A2, A3, A4, A5, A6, A7, A8, F>(f) {} }; template<class R, class T, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> struct BOOST_MEM_FN_NAME(cmf8): public mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf8)<R, T, A1, A2, A3, A4, A5, A6, A7, A8, R (BOOST_MEM_FN_CC T::*) (A1, A2, A3, A4, A5, A6, A7, A8) const> { typedef R (BOOST_MEM_FN_CC T::*F) (A1, A2, A3, A4, A5, A6, A7, A8) const; explicit BOOST_MEM_FN_NAME(cmf8)(F f): mf<R>::BOOST_NESTED_TEMPLATE BOOST_MEM_FN_NAME2(cmf8)<R, T, A1, A2, A3, A4, A5, A6, A7, A8, F>(f) {} };
gpl-2.0
crotwell/sod
src/main/java/edu/sc/seis/sod/status/MicroSecondTimeRangeFormatter.java
2237
package edu.sc.seis.sod.status; import java.util.Iterator; import org.w3c.dom.Element; import edu.sc.seis.fissuresUtil.time.MicroSecondTimeRange; import edu.sc.seis.sod.ConfigurationException; public class MicroSecondTimeRangeFormatter extends Template implements MicroSecondTimeRangeTemplate { public MicroSecondTimeRangeFormatter(Element el) throws ConfigurationException { this(el, false); } public MicroSecondTimeRangeFormatter(Element el, boolean fileize) throws ConfigurationException { this.filizeResults = fileize; parse(el, filizeResults); } protected Object textTemplate(final String text) { return new MicroSecondTimeRangeTemplate() { public String getResult(MicroSecondTimeRange timeRange) { return text; } }; } protected Object getTemplate(String tag, final Element el) { if(tag.equals("beginTime")) { return new MicroSecondTimeRangeTemplate() { public String getResult(MicroSecondTimeRange timeRange) { return tt.getResult(timeRange.getBeginTime() .getFissuresTime()); } TimeTemplate tt = new TimeTemplate(el, true); }; } else if(tag.equals("endTime")) { return new MicroSecondTimeRangeTemplate() { public String getResult(MicroSecondTimeRange timeRange) { return tt.getResult(timeRange.getEndTime() .getFissuresTime()); } TimeTemplate tt = new TimeTemplate(el, true); }; } return super.getCommonTemplate(tag, el); } public String getResult(MicroSecondTimeRange timeRange) { StringBuffer buf = new StringBuffer(); Iterator it = templates.iterator(); while(it.hasNext()) { buf.append(((MicroSecondTimeRangeTemplate)it.next()).getResult(timeRange)); } if(filizeResults) { return FissuresFormatter.filize(buf.toString()); } else { return buf.toString(); } } boolean filizeResults = false; }
gpl-2.0
speendo/raspi-mpd-lcd
locale_class.py
149
# -*- coding: utf-8 -*- class LocaleClass(object): def __init__(self): self.locale_chars = {} self.custom_chars = {} # up to 8 5x8 custom chars
gpl-2.0
dougwm/psi-probe
core/src/main/java/psiprobe/controllers/apps/GetApplicationProcDetailsController.java
1430
/** * Licensed under the GPL License. You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE. */ package psiprobe.controllers.apps; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * The Class GetApplicationProcDetailsController. */ @Controller public class GetApplicationProcDetailsController extends BaseGetApplicationController { @RequestMapping(path = "/appprocdetails.ajax") @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { return super.handleRequest(request, response); } @Value("ajax/appProcTimeDetails") @Override public void setViewName(String viewName) { super.setViewName(viewName); } @Value("true") @Override public void setExtendedInfo(boolean extendedInfo) { super.setExtendedInfo(extendedInfo); } }
gpl-2.0
rossfoley/mqp_neat
src/mqp/mario/MQPMarioTask.java
2381
package mqp.mario; import ch.idsia.agents.Agent; import ch.idsia.benchmark.tasks.BasicTask; import ch.idsia.benchmark.tasks.Task; import ch.idsia.tools.MarioAIOptions; import org.apache.log4j.Logger; /** * Contains the levels that will be used to evolve Mario AI agents * @author Ross Foley and Karl Kuhn */ public class MQPMarioTask extends BasicTask implements Task, Cloneable { private int uniqueSeed; private int difficulties[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1}; public static transient Logger LOGGER = Logger.getLogger(MQPMarioTask.class); /** * MQPMarioTask Constructor * @param evaluationOptions the Mario options */ public MQPMarioTask(MarioAIOptions evaluationOptions) { super(evaluationOptions); setOptionsAndReset(evaluationOptions); uniqueSeed = 1337; LOGGER.info("New generation on MQPMarioTask"); } /** * MQPMarioTask Constructor * @param evaluationOptions the Mario options * @param seed the seed to start the runs on */ public MQPMarioTask(MarioAIOptions evaluationOptions, int seed) { super(evaluationOptions); setOptionsAndReset(evaluationOptions); uniqueSeed = seed; } /** * Run the agent through a single specific level * @param controller the AI agent * @param difficulty the difficulty level * @param seed the level seed * @return the distance travelled by the agent */ public float evaluateSingleLevel(Agent controller, int difficulty, int seed) { options.setAgent(controller); options.setLevelDifficulty(difficulty); options.setLevelRandSeed(seed); setOptionsAndReset(options); runSingleEpisode(1); return getEnvironment().getEvaluationInfo().computeDistancePassed(); } /** * Evaluate an AI agent across multiple levels and difficulties * @param controller the AI agent * @return the total distance travelled by the agent across all levels */ public int evaluate(Agent controller) { float totalFitness = 0; int seed = uniqueSeed; for (int difficulty : difficulties) { totalFitness += evaluateSingleLevel(controller, difficulty, seed); seed++; } return (int) Math.max(0, totalFitness); } }
gpl-2.0
avlhitech256/TimeTable
TimeTable/ViewModel/TopMenu/Command/SpecialtyCommand.cs
480
namespace TimeTable.ViewModel.TopMenu.Command { internal class SpecialtyCommand : TopMenuCommonCommand { #region Constructors public SpecialtyCommand(ITopMenuViewModel viewModel) : base(viewModel) { CanExecuteProperty = true; } #endregion #region Methods public override void Execute(object parameter) { ViewModel?.SelectSpecialtyMenu(); } #endregion } }
gpl-2.0
wfqzhgl/mapyou
manage.py
249
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mapyou.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
gpl-2.0
inverse-inc/packetfence
html/pfappserver/root/src/views/Configuration/syslogParsers/config.js
4295
import { pfFieldType } from '@/globals/pfField' import i18n from '@/utils/locale' export const types = { dhcp: i18n.t('DHCP'), fortianalyser: i18n.t('FortiAnalyzer'), nexpose: i18n.t('Nexpose'), regex: i18n.t('Regex'), security_onion: i18n.t('Security Onion'), snort: i18n.t('Snort'), suricata: i18n.t('Suricata'), suricata_md5: i18n.t('Suricata MD5') } export const typeOptions = Object.keys(types) .sort((a, b) => types[a].localeCompare(types[b])) .map(key => ({ value: key, text: types[key] })) export const regexRuleActions = { add_person: { value: 'add_person', text: i18n.t('Create new user account'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'pid, $pid' } } }, close_security_event: { value: 'close_security_event', text: i18n.t('Close security event'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, vid, VID' } } }, deregister_node_ip: { value: 'deregister_node_ip', text: i18n.t('Deregister node by IP'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'ip, $ip' } } }, dynamic_register_node: { value: 'dynamic_register_node', text: i18n.t('Register node by MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, username, $username' } } }, modify_node: { value: 'modify_node', text: i18n.t('Modify node by MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac' } } }, modify_person: { value: 'modify_person', text: i18n.t('Modify existing user'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'pid, $pid' } } }, reevaluate_access: { value: 'reevaluate_access', text: i18n.t('Reevaluate access by MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, reason, $reason' } } }, register_node: { value: 'register_node', text: i18n.t('Register a new node by PID'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, pid, $pid' } } }, register_node_ip: { value: 'register_node_ip', text: i18n.t('Register node by IP'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'ip, $ip, pid, $pid' } } }, release_all_security_events: { value: 'release_all_security_events', text: i18n.t('Release all security events for node by MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: '$mac' } } }, role_detail: { value: 'role_detail', text: i18n.t('Get role details'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'role, $role' } } }, trigger_scan: { value: 'trigger_scan', text: i18n.t('Launch a scan for the device'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: '$ip, mac, $mac, net_type, TYPE' } } }, trigger_security_event: { value: 'trigger_security_event', text: i18n.t('Trigger a security event'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, tid, TYPEID, type, TYPE' } } }, unreg_node_for_pid: { value: 'unreg_node_for_pid', text: i18n.t('Deregister node by PID'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'pid, $pid' } } }, update_ip4log: { value: 'update_ip4log', text: i18n.t('Update ip4log by IP and MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, ip, $ip' } } }, update_ip6log: { value: 'update_ip6log', text: i18n.t('Update ip6log by IP and MAC'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'mac, $mac, ip, $ip' } } }, update_role_configuration: { value: 'update_role_configuration', text: i18n.t('Update role configuration'), types: [pfFieldType.SUBSTRING], siblings: { api_parameters: { default: 'role, $role' } } } }
gpl-2.0
svante2001/AndroidTest
app/src/androidTest/java/dk/supersejemig/to/ApplicationTest.java
349
package dk.supersejemig.to; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
gpl-2.0
moehuster/dms
client/exception_test.cpp
229
#include "dms_exception.h" #include <cstdio> int main(int argc, char *argv[]) { dmsException *e = new dmsClientException("dms client backup exception"); puts(e->what()); } /* ---------- end of function main ---------- */
gpl-2.0
vansatchen/sundries
zerow/fancontrol/fancontrol.py
1555
#!/usr/bin/env python3 import os import os.path import subprocess import time import requests domomq135 = 'http://domoticz:8080/json.htm?type=command&param=udevice&idx=35&nvalue=0&svalue=' domowcfan = 'http://domoticz:8080/json.htm?type=command&param=switchlight&idx=40&switchcmd=Set%20Level&level=' checktimes=12 controltxt='/opt/fancontrol/control.txt' if os.path.isfile(controltxt): controlread=open(controltxt, 'r') forcerun=int(controlread.read().strip()) controlread.close() if(forcerun >= 1): exit(10) else: forcerun=0 if not os.path.islink('/sys/class/gpio/gpio9'): subprocess.call(["/bin/echo 9 > /sys/class/gpio/export"], shell=True) time.sleep(1) subprocess.call(["/bin/echo out > /sys/class/gpio/gpio9/direction"], shell=True) datchikstart=subprocess.getoutput(["/opt/fancontrol/mq135.py"]) datchikstart=int(datchikstart) time.sleep(1) for x in range(1, checktimes): datchikstat=subprocess.getoutput(["/opt/fancontrol/mq135.py"]) datchikstat=int(datchikstat) # Update mq135 stat requests.get(domomq135 + str(datchikstat)) # Update Fan status lvlup = datchikstart + 5 lvldn = datchikstart - 2 if(datchikstat >= lvlup): subprocess.call(["/bin/echo 1 > /sys/class/gpio/gpio9/value"], shell=True) requests.get(domowcfan + str('70')) if(datchikstat <= lvldn): time.sleep(1) subprocess.call(["/bin/echo 0 > /sys/class/gpio/gpio9/value"], shell=True) if(x == 9): requests.get(domowcfan + str('0')) time.sleep(9)
gpl-2.0
jijianwen/Learn
Linux/container/geektime/24_API_Objects/k8s-controller-custom-resource/pkg/client/clientset/versioned/typed/samplecrd/v1/generated_expansion.go
659
/* Copyright The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by client-gen. DO NOT EDIT. package v1 type NetworkExpansion interface{}
gpl-2.0
UniversalLP/Minimalistica
src/main/java/de/universallp/minimalistica/gui/client/widget/GuiTab.java
8460
package de.universallp.minimalistica.gui.client.widget; import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import de.universallp.minimalistica.config.ConfigRegistry; import de.universallp.minimalistica.gui.client.BaseGui; import de.universallp.minimalistica.helper.LangHelper; import de.universallp.minimalistica.helper.NumberHelper; import de.universallp.minimalistica.misc.Boundary; import de.universallp.minimalistica.ref.References; public class GuiTab { private List<GuiSpecialButton> tabButtons = new ArrayList<GuiSpecialButton>(); private int unextendedX = 21, unextendedY = 20; private int topStart = 8; private int leftBound, rightBound, topBound, bottomBound; private int wordWrapMax = 90; private boolean isExtended; private int alternateHeight = -1; //Used in the output tab, whose width isn't defined by text but by the buttons private int alternateWidth = -1; private String unlocalizedText; private EnumTabType type; private EnumMachineType machineType; private TileEntity te; // For info about the owner etc. public GuiTab(EnumTabType tabType, EnumMachineType machineType) { this.type = tabType; this.machineType = machineType; if (tabType.equals(EnumTabType.INFORMATION)) this.unlocalizedText = machineType.getUnlocalizedInfoText(); else this.unlocalizedText = tabType.getUnlocalizedText(); if (tabType.equals(EnumTabType.OUTPUT)) { this.alternateHeight = References.Textures.output_height; this.alternateWidth = References.Textures.output_width; } } /** * Returns true if the state has changed */ public boolean toggleTab(int mouseX, int mouseY) { if (NumberHelper.isMouseInBound(mouseX, mouseY, leftBound, rightBound, topBound, bottomBound)) { this.isExtended = !isExtended; return true; } return false; } public void setState(boolean isExtended) { this.isExtended = isExtended; } /** * Returns the distance between the top and the bottom of the tab * So other tabs display blow that tab * @return distance */ public int getBottom() { return bottomBound - topStart + 3; } /** * Adds a button with a custom texture and a tooltip */ public void addButton(int leftBound, int rightBound, int topBound, int bottomBound, int width, int height, ResourceLocation texture, EnumButtonType type, int id) { Boundary bounds = new Boundary(leftBound, rightBound, topBound, bottomBound, width, height); tabButtons.add(new GuiSpecialButton(bounds, texture, type, id)); } /** * Displays the background rectangle */ public void displayBackground(BaseGui gui, int topOffset) { GlStateManager.disableRescaleNormal(); RenderHelper.disableStandardItemLighting(); GlStateManager.disableLighting(); GlStateManager.disableDepth(); //Draw main rect gui.drawRect(leftBound, topBound, rightBound, bottomBound, type.getColor(), type.getColor()); //draw black border gui.drawRect(leftBound + 1, topBound - 1, rightBound, topBound, References.Textures.black, References.Textures.black); gui.drawRect(leftBound, topBound, leftBound + 1, bottomBound, References.Textures.black, References.Textures.black); gui.drawRect(leftBound + 1, bottomBound, rightBound, bottomBound + 1, References.Textures.black, References.Textures.black); //draw snazzy borderino (Shadows) gui.drawRect(leftBound, bottomBound - 1, rightBound, bottomBound, References.Textures.lightShadow, References.Textures.lightShadow); gui.drawRect(leftBound + 1, topBound + 1, leftBound + 2, bottomBound, References.Textures.white, References.Textures.white); gui.drawRect(rightBound - 1, topBound, rightBound, bottomBound, References.Textures.shadow, References.Textures.shadow); gui.drawRect(leftBound + 1, topBound, rightBound, topBound + 1, References.Textures.white, References.Textures.white); gui.drawItem(type.getIcon(), -gui.getLeft() - 18, topBound - gui.getTop() + 2); //Draw contained text/Buttons if extended if (isExtended) { gui.drawString(Minecraft.getMinecraft().fontRendererObj, getLocalizedTitle(), leftBound + 4, topBound + 5, NumberHelper.rgbToInt(255, 216, 0)); Minecraft.getMinecraft().fontRendererObj.drawSplitString(getLocalizedText(), leftBound + 4, topBound + 18, wordWrapMax, References.Textures.textColor); } GlStateManager.enableLighting(); GlStateManager.enableDepth(); RenderHelper.enableStandardItemLighting(); GlStateManager.enableRescaleNormal(); } /** * returns true if state changed/mouse was in boundary * topOffset is the distance from top to the tab above this tab */ public boolean render(BaseGui gui, int mouseX, int mouseY, boolean mouseDown, int topOffset) { setUpDimensions(topOffset); if (!mouseDown && !isExtended && !NumberHelper.isMouseInBound(mouseX, mouseY, leftBound, rightBound, topBound, bottomBound)) { displayBackground(gui, topOffset); } else if (!mouseDown && !isExtended && NumberHelper.isMouseInBound(mouseX, mouseY, leftBound, rightBound, topBound, bottomBound)) { displayBackground(gui, topOffset); gui.drawSingleToolTipLine(mouseX, mouseY, getLocalizedTooltip()); } else if (mouseDown && !isExtended && NumberHelper.isMouseInBound(mouseX, mouseY, leftBound, rightBound, topBound, bottomBound)) { setUpDimensions(topOffset); // Update size toggleTab(mouseX, mouseY); return true; } else if (mouseDown && isExtended && NumberHelper.isMouseInBound(mouseX, mouseY, leftBound, rightBound, topBound, bottomBound)) { setUpDimensions(topOffset); // Update size toggleTab(mouseX, mouseY); return true; } else { displayBackground(gui, topOffset); if (isExtended) { for (GuiSpecialButton guiSpecialButton : tabButtons) { guiSpecialButton.render(gui, mouseX, mouseY, mouseDown); } } } return false; } /** * Updates the Tabs size */ private void setUpDimensions(int topOffset) { if (!isExtended) { leftBound = -unextendedX; rightBound = 0; topBound = topStart + topOffset; bottomBound = topBound + unextendedY; } else { if (alternateHeight != -1 && alternateWidth != -1) { //If the tab is using fixed width/height topBound = topStart + topOffset; leftBound = -alternateWidth - 4; // 4 for space between the text and the border rightBound = 0; bottomBound = topBound + alternateHeight + 19; // 19 for space in bottom/top for text } else { int titleWidth; int height; titleWidth = Minecraft.getMinecraft().fontRendererObj.getStringWidth(getLocalizedTitle()); if (titleWidth + 23 > wordWrapMax) // 23 for the icon wordWrapMax = titleWidth + 23; // Same height = Minecraft.getMinecraft().fontRendererObj.splitStringWidth(getLocalizedText(), wordWrapMax); topBound = topStart + topOffset; leftBound = -wordWrapMax - 4; // 4 for space between the text and the border rightBound = 0; bottomBound = topBound + height + 19; // 19 for space in bottom/top for text } } } public String getLocalizedTooltip() { return LangHelper.f(type.getUnlocalizedTooltip()); } public String getLocalizedText() { if (this.type.equals(EnumTabType.ENERGY)) { switch (machineType) { case FLUXFURNACE: return LangHelper.f(this.unlocalizedText, ConfigRegistry.FLUXFURNACE_USE); case TREEFARM: return LangHelper.f(this.unlocalizedText, ConfigRegistry.TREEFARM_USE); } } return LangHelper.f(unlocalizedText); } public String getLocalizedTitle() { return LangHelper.f(type.getUnlocalizedTitle()); } public boolean getIsExtended() { return isExtended; } public EnumTabType getType() { return type; } /** * Sets the max width of one text line * Will be overwritten if the tab title is wider than the wordWrap max * @param max */ public void setWordWrapMax(int max) { wordWrapMax = max; } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest07280.java
2432
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest07280") public class BenchmarkTest07280 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { javax.servlet.http.Cookie[] cookies = request.getCookies(); String param = null; boolean foundit = false; if (cookies != null) { for (javax.servlet.http.Cookie cookie : cookies) { if (cookie.getName().equals("foo")) { param = cookie.getValue(); foundit = true; } } if (!foundit) { // no cookie found in collection param = ""; } } else { // no cookies param = ""; } String bar = new Test().doSomething(param); new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir, bar); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(param); return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
sihai/openshop
server/webapp/src/main/java/com/openteach/openshop/server/webapp/controller/admin/CouponController.java
7740
/* * Copyright 2005-2013 AIGECHIBAOLE. All rights reserved. * Support: http://www.aigechibaole.com * License: http://www.aigechibaole.com/license */ package com.openteach.openshop.server.webapp.controller.admin; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.openteach.openshop.server.service.ExcelView; import com.openteach.openshop.server.service.Message; import com.openteach.openshop.server.service.Pageable; import com.openteach.openshop.server.service.entity.Coupon; import com.openteach.openshop.server.service.entity.CouponCode; import com.openteach.openshop.server.service.service.AdminService; import com.openteach.openshop.server.service.service.CouponCodeService; import com.openteach.openshop.server.service.service.CouponService; import com.openteach.openshop.server.service.util.FreemarkerUtils; /** * Controller - 优惠券 * * @author AIGECHIBAOLE Team * @version 0.0.1 */ @Controller("adminCouponController") @RequestMapping("/admin/coupon") public class CouponController extends BaseController { @Resource(name = "couponServiceImpl") private CouponService couponService; @Resource(name = "couponCodeServiceImpl") private CouponCodeService couponCodeService; @Resource(name = "adminServiceImpl") private AdminService adminService; /** * 检查价格运算表达式是否正确 */ @RequestMapping(value = "/check_price_expression", method = RequestMethod.GET) public @ResponseBody boolean checkPriceExpression(String priceExpression) { if (StringUtils.isEmpty(priceExpression)) { return false; } try { Map<String, Object> model = new HashMap<String, Object>(); model.put("quantity", 111); model.put("price", new BigDecimal("9.99")); new BigDecimal(FreemarkerUtils.process("#{(" + priceExpression + ");M50}", model)); return true; } catch (Exception e) { return false; } } /** * 添加 */ @RequestMapping(value = "/add", method = RequestMethod.GET) public String add(ModelMap model) { return "/admin/coupon/add"; } /** * 保存 */ @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(Coupon coupon, RedirectAttributes redirectAttributes) { if (!isValid(coupon)) { return ERROR_VIEW; } if (coupon.getBeginDate() != null && coupon.getEndDate() != null && coupon.getBeginDate().after(coupon.getEndDate())) { return ERROR_VIEW; } if (coupon.getMinimumQuantity() != null && coupon.getMaximumQuantity() != null && coupon.getMinimumQuantity() > coupon.getMaximumQuantity()) { return ERROR_VIEW; } if (coupon.getMinimumPrice() != null && coupon.getMaximumPrice() != null && coupon.getMinimumPrice().compareTo(coupon.getMaximumPrice()) > 0) { return ERROR_VIEW; } if (StringUtils.isNotEmpty(coupon.getPriceExpression())) { try { Map<String, Object> model = new HashMap<String, Object>(); model.put("quantity", 111); model.put("price", new BigDecimal("9.99")); new BigDecimal(FreemarkerUtils.process("#{(" + coupon.getPriceExpression() + ");M50}", model)); } catch (Exception e) { return ERROR_VIEW; } } if (coupon.getIsExchange() && coupon.getPoint() == null) { return ERROR_VIEW; } if (!coupon.getIsExchange()) { coupon.setPoint(null); } coupon.setCouponCodes(null); coupon.setPromotions(null); coupon.setOrders(null); couponService.save(coupon); addFlashMessage(redirectAttributes, SUCCESS_MESSAGE); return "redirect:list.jhtml"; } /** * 编辑 */ @RequestMapping(value = "/edit", method = RequestMethod.GET) public String edit(Long id, ModelMap model) { model.addAttribute("coupon", couponService.find(id)); return "/admin/coupon/edit"; } /** * 更新 */ @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(Coupon coupon, RedirectAttributes redirectAttributes) { if (!isValid(coupon)) { return ERROR_VIEW; } if (coupon.getBeginDate() != null && coupon.getEndDate() != null && coupon.getBeginDate().after(coupon.getEndDate())) { return ERROR_VIEW; } if (coupon.getMinimumQuantity() != null && coupon.getMaximumQuantity() != null && coupon.getMinimumQuantity() > coupon.getMaximumQuantity()) { return ERROR_VIEW; } if (coupon.getMinimumPrice() != null && coupon.getMaximumPrice() != null && coupon.getMinimumPrice().compareTo(coupon.getMaximumPrice()) > 0) { return ERROR_VIEW; } if (StringUtils.isNotEmpty(coupon.getPriceExpression())) { try { Map<String, Object> model = new HashMap<String, Object>(); model.put("quantity", 111); model.put("price", new BigDecimal("9.99")); new BigDecimal(FreemarkerUtils.process("#{(" + coupon.getPriceExpression() + ");M50}", model)); } catch (Exception e) { return ERROR_VIEW; } } if (coupon.getIsExchange() && coupon.getPoint() == null) { return ERROR_VIEW; } if (!coupon.getIsExchange()) { coupon.setPoint(null); } couponService.update(coupon, "couponCodes", "promotions", "orders"); addFlashMessage(redirectAttributes, SUCCESS_MESSAGE); return "redirect:list.jhtml"; } /** * 列表 */ @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(Pageable pageable, ModelMap model) { model.addAttribute("page", couponService.findPage(pageable)); return "/admin/coupon/list"; } /** * 删除 */ @RequestMapping(value = "/delete", method = RequestMethod.POST) public @ResponseBody Message delete(Long[] ids) { couponService.delete(ids); return SUCCESS_MESSAGE; } /** * 生成优惠码 */ @RequestMapping(value = "/build", method = RequestMethod.GET) public String build(Long id, ModelMap model) { Coupon coupon = couponService.find(id); model.addAttribute("coupon", coupon); model.addAttribute("totalCount", couponCodeService.count(coupon, null, null, null, null)); model.addAttribute("usedCount", couponCodeService.count(coupon, null, null, null, true)); return "/admin/coupon/build"; } /** * 下载优惠码 */ @RequestMapping(value = "/download", method = RequestMethod.POST) public ModelAndView download(Long id, Integer count, ModelMap model) { if (count == null || count <= 0) { count = 50; } Coupon coupon = couponService.find(id); List<CouponCode> data = couponCodeService.build(coupon, null, count); String filename = "coupon_code_" + new SimpleDateFormat("yyyyMM").format(new Date()) + ".xls"; String[] contents = new String[4]; contents[0] = message("admin.coupon.type") + ": " + coupon.getName(); contents[1] = message("admin.coupon.count") + ": " + count; contents[2] = message("admin.coupon.operator") + ": " + adminService.getCurrentUsername(); contents[3] = message("admin.coupon.date") + ": " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); return new ModelAndView(new ExcelView(filename, null, new String[] { "code" }, new String[] { message("admin.coupon.title") }, null, null, data, contents), model); } }
gpl-2.0
repotvsupertuga/tvsupertuga.repository
script.module.streamtvsupertuga/lib/resources/lib/sources/en/cmovieshd.py
1805
# -*- coding: UTF-8 -*- # -Cleaned and Checked on 10-16-2019 by JewBMX in Scrubs. # -Cleaned and Checked on 04-14-2020 by Tempest. # -Created by Tempest import re from resources.lib.modules import cleantitle, client, log_utils from resources.lib.modules import source_utils from resources.lib.sources import cfscrape class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['cmovies.video', 'cmovieshd.bz'] self.base_link = 'https://cmovies.tv' self.search_link = '/film/%s/watching.html?ep=0' self.headers = {'User-Agent': client.agent()} def movie(self, imdb, title, localtitle, aliases, year): try: title = cleantitle.geturl(title).replace('--', '-') url = self.base_link + self.search_link % title return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] hostDict = hostprDict + hostDict r = cfscrape.get(url, headers=self.headers) qual = re.compile('class="quality">(.+?)</span>').findall(r) quality = source_utils.check_url(qual) u = re.compile('data-video="(.+?)"').findall(r) for url in u: if 'load.php' not in url: if not url.startswith('http'): url = "https:" + url valid, host = source_utils.is_host_valid(url, hostDict) if valid: sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False, 'debridonly': False}) return sources except: return sources def resolve(self, url): return url
gpl-2.0
nathanscottdaniels/pnant
tests/NAnt.VisualCpp/VisualCppTestBase.cs
9428
// pNAnt - A parallel .NET build tool // Copyright (C) 2004 Thomas Strauss (strausst@arcor.de) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; 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 // // Thomas Strauss (strausst@arcor.de) // Gert Driesen (drieseng@users.sourceforge.net) using System.Collections.Specialized; using System.Diagnostics; using NAnt.Core; using NAnt.Core.Functions; using Tests.NAnt.Core; namespace Tests.NAnt.VisualCpp { public abstract class VisualCppTestBase : BuildTestBase { /// <summary> /// Gets a value indicating whether the VC++ compiler is present in the PATH. /// </summary> /// <value> /// <see langword="true" /> if the VC++ compiler is present in the PATH; /// otherwise, <see langword="false" />. /// </value> protected static bool CompilerPresent { get { return _compilerPresent; } } /// <summary> /// Gets a value indicating whether the VC++ libs are present in the /// LIB environment variable. /// </summary> /// <value> /// <see langword="true" /> if the VC++ libs are present in the LIB /// environment variable. /// </value> protected static bool LibsPresent { get { return _libsPresent; } } /// <summary> /// Gets a value indicating whether the VC++ header files are present /// in the INCLUDE environment variable. /// </summary> /// <value> /// <see langword="true" /> if the VC++ header files are present in the /// INCLUDE environment variable. /// </value> protected static bool HeaderFilesPresent { get { return _headerFilesPresent; } } /// <summary> /// Combined property which allows to check if you can compile and link. /// </summary> protected static bool CanCompileAndLink { get { return (LibsPresent && CompilerPresent && HeaderFilesPresent && SupportedCompiler); } } /// <summary> /// Gets a value indicating whether the compiler supports Managed /// Extensions. /// </summary> /// <value> /// <see langword="true" /> if the VC++ compiler supports Managed /// Extensions; otherwise, <see langword="false" />. /// </value> protected static bool SupportedCompiler { get { return _supportedCompiler; } } /// <summary> /// Gets a value indicating whether the VC++ Resource Compiler (rc.exe) /// is present in the PATH. /// </summary> /// <value> /// <see langword="true" /> if the VC++ Resource Compiler is present in /// the PATH; otherwise, <see langword="false" />. /// </value> protected static bool ResourceCompilerPresent { get { return _resourceCompilerPresent; } } private static string[] ExpectedLibs { get { return _expectedLibs; } } private static string[] ExpectedHeaderFiles { get { return _expectedHeaderFiles; } } /// <summary> /// Routine which checks if the libs are present. /// </summary> /// <returns> /// <see langword="true" /> if the libs are present; otherwise, /// <see langword="false" />. /// </returns> private static bool CheckLibsPresent() { foreach (string lib in ExpectedLibs) { PathScanner scanner = new PathScanner(); scanner.Add(lib); if (scanner.Scan("LIB").Count == 0) { return false; } } return true; } /// <summary> /// Routine which checks if the header files are present. /// </summary> /// <returns> /// <see langword="true" /> if the header files are present; otherwise, /// <see langword="false" />. /// </returns> private static bool CheckHeaderFilesPresent() { foreach (string headerFile in ExpectedHeaderFiles) { PathScanner scanner = new PathScanner(); scanner.Add(headerFile); if (scanner.Scan("INCLUDE").Count == 0) { return false; } } return true; } /// <summary> /// Routine which checks if the compiler is present. /// </summary> /// <returns> /// <see langword="true" /> if the compiler is present; otherwise, /// <see langword="false" />. /// </returns> private static bool CheckCompilerPresent() { // return true if there is a compiler on the PATH return (GetCompilersOnPath().Count > 0); } /// <summary> /// Routine which checks if the compiler is supported by NAnt. /// </summary> /// <returns> /// <see langword="true" /> if the version of the compiler is at /// least <c>13.xx.xxxx</c>; otherwise, <see langword="false" />. /// </returns> private static bool CheckSupportedCompiler() { StringCollection compilers = GetCompilersOnPath(); foreach (string compiler in compilers) { // get major version of compiler int majorVersion = VersionFunctions.GetMajor( FileVersionInfoFunctions.GetProductVersion( FileVersionInfo.GetVersionInfo(compiler))); // the MS compiler supports Managed Extensions starting from // product version 7 (VS.NET 2002) if (majorVersion < 7) { // stop at first compiler that does not meet the required // version, as we're not sure which entry in the PATH the // <cl> task will use return false; } } // if we made it here, and at least one compiler was on the PATH // then we know its a supported compiler return (compilers.Count > 0); } private static StringCollection GetCompilersOnPath() { PathScanner scanner = new PathScanner(); scanner.Add("cl.exe"); return scanner.Scan("PATH"); } /// <summary> /// Routine which checks if the resource compiler is present. /// </summary> /// <returns> /// <see langword="true" /> if the resource compiler is present; /// otherwise, <see langword="false" />. /// </returns> private static bool CheckResourceCompilerPresent() { PathScanner scanner = new PathScanner(); scanner.Add("rc.exe"); return scanner.Scan("PATH").Count > 0; } private static string[] _expectedLibs = new string[] { "kernel32.lib", "user32.lib", "gdi32.lib", "winspool.lib", "comdlg32.lib", "advapi32.lib", "shell32.lib", "ole32.lib", "oleaut32.lib", "uuid.lib", "odbc32.lib", "odbccp32.lib" }; private static readonly string[] _expectedHeaderFiles = new string[] { "stdio.h", "windows.h" }; private static readonly bool _compilerPresent = CheckCompilerPresent(); private static readonly bool _libsPresent = CheckLibsPresent(); private static readonly bool _headerFilesPresent = CheckHeaderFilesPresent(); private static readonly bool _supportedCompiler = CheckSupportedCompiler(); private static readonly bool _resourceCompilerPresent = CheckResourceCompilerPresent(); } }
gpl-2.0
nathanscottdaniels/pnant
pNAntContrib/src/Tasks/NUnit2Report/NUnit2ReportTask.cs
21796
// NUnit2ReportTask.cs // // Loosely based on Tomas Restrepo NUnitReport for NAnt. // Loosely based on Erik Hatcher JUnitReport for Ant. // // Author: // Gilles Bayon (gilles.bayon@laposte.net) // // Copyright (C) 2003 Gilles Bayon // // // 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 // // Gilles Bayon (gilles.bayon@laposte.net) // Ian Maclean (imaclean@gmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Contrib.Types.NUnit2Report; namespace NAnt.Contrib.Tasks.NUnit2Report { /// <summary> /// A task that generates a summary HTML /// from a set of NUnit xml report files. /// </summary> /// <remarks> /// <para> /// This task can generate a combined HTML report out of a set of NUnit /// result files generated using the XML Result Formatter. /// </para> /// <para> /// All the properties defined in the current project will be passed /// down to the XSLT file as template parameters, so you can access /// properties such as nant.project.name, nant.version, etc. /// </para> /// </remarks> /// <example> /// <code> /// <![CDATA[ /// <nunit2report todir="${outputdir}"> /// <fileset> /// <includes name="${outputdir}\results.xml" /> /// </fileset> /// </nunit2report> /// ]]> /// </code> /// </example> [TaskName("nunit2report")] public class NUnit2ReportTask : Task { #region Private Static Fields private static readonly ArrayList _resFiles = new ArrayList(new string[3]{"toolkit.xsl", "Traductions.xml", "NUnit-Frame.xsl"}); #endregion Private Static Fields #region Private Instance Fields private DirectoryInfo _toDir; private FileSet _fileset = new FileSet(); private XmlDocument _fileSetSummary; private FileSet _summaries = new FileSet(); private string _tempXmlFileSummarie = ""; private FileInfo _xslFile; private string _openDescription ="no"; private string _language = ""; private ReportFormat _format = ReportFormat.NoFrames; private XsltArgumentList _xsltArgs; #endregion Private Instance Fields #region Public Instance Properties /// <summary> /// The format of the generated report. The default is /// <see cref="ReportFormat.NoFrames" />. /// </summary> [TaskAttribute("format")] public ReportFormat Format { get { return _format; } set { _format = value; } } /// <summary> /// The output language. /// </summary> [TaskAttribute("lang")] public string Language { get { return _language; } set { _language = value; } } /// <summary> /// Open all description method. Default to "false". /// </summary> [TaskAttribute("opendesc")] public string OpenDescription { get { return _openDescription; } set { _openDescription = StringUtils.ConvertEmptyToNull(value); } } /// <summary> /// The directory where the files resulting from the transformation /// should be written to. The default is the project's base directory. /// </summary> [TaskAttribute("todir")] public DirectoryInfo ToDir { get { if (_toDir == null) { return new DirectoryInfo(Project.BaseDirectory); } return _toDir; } set { _toDir = value; } } /// <summary> /// Set of XML files to use as input /// </summary> [BuildElement("fileset")] public FileSet XmlFileSet { get { return _fileset; } } /// <summary> /// Set of summary XML files to use as input. /// </summary> //[BuildElement("summaries")] public FileSet XmlSummaries { get { return _summaries; } } /// <summary> /// XSLT file used to generate the report if <see cref="Format" /> is /// <see cref="ReportFormat.NoFrames" />. /// </summary> [TaskAttribute("xslfile")] public FileInfo XslFile { get { return _xslFile; } set { _xslFile = value; } } #endregion Public Instance Properties #region Override implementation of Task /// <summary> /// Initializes task and ensures the supplied attributes are valid. /// </summary> protected override void Initialize() { if (Format == ReportFormat.NoFrames) { if (XslFile != null && !XslFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The XSLT file \"{0}\" could not be found.", XslFile.FullName), Location); } } if (XmlFileSet.FileNames.Count == 0) { throw new BuildException("NUnitReport fileset cannot be empty!", Location); } foreach (string file in XmlSummaries.FileNames) { _tempXmlFileSummarie = file; } // Get the NAnt, OS parameters _xsltArgs = GetPropertyList(); } /// <summary> /// This is where the work is done /// </summary> protected override void ExecuteTask() { _fileSetSummary = CreateSummaryXmlDoc(); foreach (string file in XmlFileSet.FileNames) { XmlDocument source = new XmlDocument(); source.Load(file); XmlNode node = _fileSetSummary.ImportNode(source.DocumentElement, true); _fileSetSummary.DocumentElement.AppendChild(node); } Log(Level.Info, "Generating report..."); try { // ensure destination directory exists if (!ToDir.Exists) { ToDir.Create(); ToDir.Refresh(); } if (Format == ReportFormat.NoFrames) { XslTransform xslTransform = new XslTransform(); XmlResolver resolver = new LocalResXmlResolver(); if (XslFile != null) { xslTransform.Load(LoadStyleSheet(XslFile), resolver); } else { xslTransform.Load(LoadStyleSheet("NUnit-NoFrame.xsl"), resolver); } // xmlReader hold the first transformation XmlReader xmlReader = xslTransform.Transform(_fileSetSummary, _xsltArgs); // i18n XsltArgumentList xsltI18nArgs = new XsltArgumentList(); xsltI18nArgs.AddParam("lang", "",Language); // Load the i18n stylesheet XslTransform xslt = new XslTransform(); xslt.Load(LoadStyleSheet("i18n.xsl"), resolver); XPathDocument xmlDoc; xmlDoc = new XPathDocument(xmlReader); XmlTextWriter writerFinal = new XmlTextWriter( Path.Combine(ToDir.FullName, "index.html"), Encoding.GetEncoding("ISO-8859-1")); // Apply the second transform to xmlReader to final ouput xslt.Transform(xmlDoc, xsltI18nArgs, writerFinal); xmlReader.Close(); writerFinal.Close(); } else { XmlTextReader reader = null; try { // create the index.html StringReader stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"index.html\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write (stream, Path.Combine(ToDir.FullName, "index.html")); // create the stylesheet.css stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"stylesheet.css\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write (stream, Path.Combine(ToDir.FullName, "stylesheet.css")); // create the overview-summary.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"overview.packages\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write (stream, Path.Combine(ToDir.FullName, "overview-summary.html")); // create the allclasses-frame.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"all.classes\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write (stream, Path.Combine(ToDir.FullName, "allclasses-frame.html")); // create the overview-frame.html at the root stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"test-results\">" + " <xsl:call-template name=\"all.packages\"/>" + " </xsl:template>" + " </xsl:stylesheet>"); Write (stream, Path.Combine(ToDir.FullName, "overview-frame.html")); XPathNavigator xpathNavigator = _fileSetSummary.CreateNavigator(); // Get All the test suite containing test-case. XPathExpression expr = xpathNavigator.Compile("//test-suite[(child::results/test-case)]"); XPathNodeIterator iterator = xpathNavigator.Select(expr); while (iterator.MoveNext()) { // output directory string path = ""; XPathNavigator xpathNavigator2 = iterator.Current; string testSuiteName = iterator.Current.GetAttribute("name", ""); // Get get the path for the current test-suite. XPathNodeIterator iterator2 = xpathNavigator2.SelectAncestors("", "", true); string parent = ""; int parentIndex = -1; while (iterator2.MoveNext()) { string directory = iterator2.Current.GetAttribute("name",""); if (directory != "" && directory.IndexOf(".dll") < 0) { path = directory + "/" + path; } if (parentIndex == 1) { parent = directory; } parentIndex++; } // resolve to absolute path path = Path.Combine(ToDir.FullName, path); // ensure directory exists if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Build the "testSuiteName".html file // Correct MockError duplicate testName ! // test-suite[@name='MockTestFixture' and ancestor::test-suite[@name='Assemblies'][position()=last()]] stream = new StringReader("<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0' >" + "<xsl:output method='html' indent='yes' encoding='ISO-8859-1'/>" + "<xsl:include href=\"NUnit-Frame.xsl\"/>" + "<xsl:template match=\"/\">" + " <xsl:for-each select=\"//test-suite[@name='"+testSuiteName+"' and ancestor::test-suite[@name='"+parent+"'][position()=last()]]\">" + " <xsl:call-template name=\"test-case\">" + " <xsl:with-param name=\"dir.test\">"+String.Join(".", path.Split('/'))+"</xsl:with-param>" + " </xsl:call-template>" + " </xsl:for-each>" + " </xsl:template>" + " </xsl:stylesheet>"); Write(stream, Path.Combine(path, testSuiteName + ".html")); Log(Level.Debug,"dir={0} Generating {1}.html", path, testSuiteName); } } finally { Log(Level.Debug, "Processing of stream complete."); // Finished with XmlTextReader if (reader != null) { reader.Close(); } } } } catch (Exception ex) { throw new BuildException("Failure generating report.", Location, ex); } } #endregion Override implementation of Task #region Private Instance Methods /// <summary> /// Load a stylesheet from the assemblies resource stream. /// </summary> ///<param name="xslFileName">File name of the file to extract.</param> protected XPathDocument LoadStyleSheet(string xslFileName) { Stream xsltStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( string.Format("xslt.{0}", xslFileName) ); if (xsltStream == null) { throw new BuildException(string.Format("Missing '{0}' resource stream", xslFileName), Location); } XmlTextReader xtr = new XmlTextReader(xsltStream, XmlNodeType.Document, null); return new XPathDocument(xtr); } /// <summary> /// Load a stylesheet from the file system. /// </summary> ///<param name="xslFile">The XSLT file to load.</param> protected XPathDocument LoadStyleSheet(FileInfo xslFile) { Stream stream = new FileStream(xslFile.FullName, FileMode.Open, FileAccess.Read); XmlTextReader xtr = new XmlTextReader(stream); return new XPathDocument(xtr); } /// <summary> /// Initializes the XmlDocument instance /// used to summarize the test results /// </summary> /// <returns></returns> private XmlDocument CreateSummaryXmlDoc() { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("testsummary"); root.SetAttribute("created", DateTime.Now.ToString()); doc.AppendChild(root); return doc; } /// <summary> /// Builds an XsltArgumentList with all /// the properties defined in the /// current project as XSLT parameters. /// </summary> /// <returns></returns> private XsltArgumentList GetPropertyList() { XsltArgumentList args = new XsltArgumentList(); Log(Level.Verbose, "Processing XsltArgumentList"); foreach (DictionaryEntry entry in this.PropertyAccessor) { string value = entry.Value as string; if (value != null) { args.AddParam((string) entry.Key, "", value); } } // Add argument to the C# XML comment file args.AddParam("summary.xml", "", _tempXmlFileSummarie); // Add open.description argument args.AddParam("open.description", "", OpenDescription); return args; } /// <summary> /// Run the transform and output to filename /// </summary> /// <param name="stream"></param> /// <param name="fileName"></param> private void Write(StringReader stream, string fileName) { XmlTextReader reader = null; // Load the XmlTextReader from the stream reader = new XmlTextReader(stream); XslTransform xslTransform = new XslTransform(); XmlResolver resolver = new LocalResXmlResolver(); //Load the stylesheet from the stream. xslTransform.Load(reader, resolver); XPathDocument xmlDoc; // xmlReader hold the first transformation XmlReader xmlReader = xslTransform.Transform(_fileSetSummary, _xsltArgs); // i18n XsltArgumentList xsltI18nArgs = new XsltArgumentList(); xsltI18nArgs.AddParam("lang", "", Language); XslTransform xslt = new XslTransform(); // Load the stylesheet. xslt.Load(LoadStyleSheet("i18n.xsl"), resolver); xmlDoc = new XPathDocument(xmlReader); XmlTextWriter writerFinal = new XmlTextWriter(fileName, Encoding.GetEncoding("ISO-8859-1")); // Apply the second transform to xmlReader to final ouput xslt.Transform(xmlDoc, xsltI18nArgs, writerFinal); xmlReader.Close(); writerFinal.Close(); } #endregion Private Instance Methods /// <summary> /// Custom XmlResolver used to load the /// XSLT files out of this assembly resources. /// </summary> internal class LocalResXmlResolver : XmlUrlResolver { const string SCHEME_MRES = "mres"; /// <summary> /// Loads the specified file from our internal resources if its there /// </summary> /// <param name="absoluteUri"></param> /// <param name="role"></param> /// <param name="objToReturn"></param> /// <returns></returns> public override object GetEntity(Uri absoluteUri, string role, Type objToReturn) { string filename = absoluteUri.Segments[absoluteUri.Segments.Length-1]; if (absoluteUri.Scheme == SCHEME_MRES || (absoluteUri.Scheme == "file" && ! File.Exists(absoluteUri.AbsolutePath) && _resFiles.Contains(filename))) { Assembly thisAssm = Assembly.GetExecutingAssembly(); //string filename = absoluteUri.Segments[absoluteUri.Segments.Length-1]; return thisAssm.GetManifestResourceStream("xslt." + filename); } else { // we don't know how to handle this URI scheme.... return base.GetEntity(absoluteUri, role, objToReturn); } } } } }
gpl-2.0
amertahir/QuadTRON
GroundControlStation/src/com/digi/xbee/api/models/XBeePacketsQueue.java
12033
/** * Copyright (c) 2014 Digi International Inc., * All rights not expressly granted are reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343 * ======================================================================= */ package com.digi.xbee.api.models; import java.util.LinkedList; import com.digi.xbee.api.RemoteXBeeDevice; import com.digi.xbee.api.packet.APIFrameType; import com.digi.xbee.api.packet.XBeeAPIPacket; import com.digi.xbee.api.packet.XBeePacket; import com.digi.xbee.api.packet.common.ReceivePacket; import com.digi.xbee.api.packet.common.RemoteATCommandResponsePacket; import com.digi.xbee.api.packet.raw.RX16IOPacket; import com.digi.xbee.api.packet.raw.RX16Packet; import com.digi.xbee.api.packet.raw.RX64IOPacket; import com.digi.xbee.api.packet.raw.RX64Packet; /** * This class represents a queue of XBee packets used for sequential packets * reading within the XBee Java API. * * <p>The class provides some methods to get specific packet types from * different source nodes.</p> * * @see com.digi.xbee.api.packet.XBeePacket */ public class XBeePacketsQueue { // Constants. /** * Default maximum number of packets to store in the queue * (value: {@value}). */ public static final int DEFAULT_MAX_LENGTH = 50; // Variables. private int maxLength = DEFAULT_MAX_LENGTH; private LinkedList<XBeePacket> packetsList; /** * Class constructor. Instantiates a new object of type * {@code XBeePacketsQueue}. */ public XBeePacketsQueue() { this(DEFAULT_MAX_LENGTH); } /** * Class constructor. Instantiates a new object of type * {@code XBeePacketsQueue} with the given maximum length. * * @param maxLength Maximum length of the queue. * * @throws IllegalArgumentException if {@code maxLength < 1}. */ public XBeePacketsQueue(int maxLength) { if (maxLength < 1) throw new IllegalArgumentException("Queue length must be greater than 0."); this.maxLength = maxLength; packetsList = new LinkedList<XBeePacket>(); } /** * Adds the provided packet to the list of packets. If the queue is full * the first packet will be discarded to add the given one. * * @param xbeePacket The XBee packet to be added to the list. * * @see com.digi.xbee.api.packet.XBeePacket */ public void addPacket(XBeePacket xbeePacket) { if (packetsList.size() == maxLength) packetsList.removeFirst(); packetsList.add(xbeePacket); } /** * Clears the list of packets. */ public void clearQueue() { packetsList.clear(); } /** * Returns the first packet from the queue waiting up to the specified * timeout if necessary for an XBee packet to become available. * {@code null }if the queue is empty. * * @param timeout The time in milliseconds to wait for an XBee packet to * become available. 0 to return immediately. * @return The first packet from the queue, {@code null} if it is empty. * * @see com.digi.xbee.api.packet.XBeePacket */ public XBeePacket getFirstPacket(int timeout) { if (timeout > 0) { XBeePacket xbeePacket = getFirstPacket(0); // Wait for a timeout or until an XBee packet is read. Long deadLine = System.currentTimeMillis() + timeout; while (xbeePacket == null && deadLine > System.currentTimeMillis()) { sleep(100); xbeePacket = getFirstPacket(0); } return xbeePacket; } else if (!packetsList.isEmpty()) return packetsList.pop(); return null; } /** * Returns the first packet from the queue whose 64-bit source address * matches the address of the provided remote XBee device. * * <p>The methods waits up to the specified timeout if necessary for an * XBee packet to become available. Null if the queue is empty or there is * not any XBee packet sent by the provided remote XBee device.</p> * * @param remoteXBeeDevice The remote XBee device containing the 64-bit * address to look for in the list of packets. * @param timeout The time in milliseconds to wait for an XBee packet from * the specified remote XBee device to become available. * 0 to return immediately. * * @return The first XBee packet whose 64-bit address matches the address * of the provided remote XBee device. {@code null} if no packets * from the specified XBee device are found in the queue. * * @see com.digi.xbee.api.RemoteXBeeDevice * @see com.digi.xbee.api.packet.XBeePacket */ public XBeePacket getFirstPacketFrom(RemoteXBeeDevice remoteXBeeDevice, int timeout) { if (timeout > 0) { XBeePacket xbeePacket = getFirstPacketFrom(remoteXBeeDevice, 0); // Wait for a timeout or until an XBee packet from remoteXBeeDevice is read. Long deadLine = System.currentTimeMillis() + timeout; while (xbeePacket == null && deadLine > System.currentTimeMillis()) { sleep(100); xbeePacket = getFirstPacketFrom(remoteXBeeDevice, 0); } return xbeePacket; } else { for (int i = 0; i < packetsList.size(); i++) { XBeePacket xbeePacket = packetsList.get(i); if (addressesMatch(xbeePacket, remoteXBeeDevice)) return packetsList.remove(i); } } return null; } /** * Returns the first data packet from the queue waiting up to the * specified timeout if necessary for an XBee data packet to become * available. {@code null} if the queue is empty or there is not any data * packet inside. * * @param timeout The time in milliseconds to wait for an XBee data packet * to become available. 0 to return immediately. * * @return The first data packet from the queue, {@code null} if it is * empty or no data packets are contained in the queue. * * @see com.digi.xbee.api.packet.XBeePacket */ public XBeePacket getFirstDataPacket(int timeout) { if (timeout > 0) { XBeePacket xbeePacket = getFirstDataPacket(0); // Wait for a timeout or until a data XBee packet is read. Long deadLine = System.currentTimeMillis() + timeout; while (xbeePacket == null && deadLine > System.currentTimeMillis()) { sleep(100); xbeePacket = getFirstDataPacket(0); } return xbeePacket; } else { for (int i = 0; i < packetsList.size(); i++) { XBeePacket xbeePacket = packetsList.get(i); if (isDataPacket(xbeePacket)) return packetsList.remove(i); } } return null; } /** * Returns the first data packet from the queue whose 64-bit source * address matches the address of the provided remote XBee device. * * <p>The methods waits up to the specified timeout if necessary for an * XBee data packet to become available. {@code null} if the queue is * empty or there is not any XBee data packet sent by the provided remote * XBee device.</p> * * @param remoteXBeeDevice The XBee device containing the 64-bit address * to look for in the list of packets. * @param timeout The time in milliseconds to wait for an XBee data packet * from the specified remote XBee device to become * available. 0 to return immediately. * * @return The first XBee data packet whose its 64-bit address matches the * address of the provided remote XBee device. {@code null} if no * data packets from the specified XBee device are found in the * queue. * * @see com.digi.xbee.api.RemoteXBeeDevice * @see com.digi.xbee.api.packet.XBeePacket */ public XBeePacket getFirstDataPacketFrom(RemoteXBeeDevice remoteXBeeDevice, int timeout) { if (timeout > 0) { XBeePacket xbeePacket = getFirstDataPacketFrom(remoteXBeeDevice, 0); // Wait for a timeout or until an XBee packet from remoteXBeeDevice is read. Long deadLine = System.currentTimeMillis() + timeout; while (xbeePacket == null && deadLine > System.currentTimeMillis()) { sleep(100); xbeePacket = getFirstDataPacketFrom(remoteXBeeDevice, 0); } return xbeePacket; } else { for (int i = 0; i < packetsList.size(); i++) { XBeePacket xbeePacket = packetsList.get(i); if (isDataPacket(xbeePacket) && addressesMatch(xbeePacket, remoteXBeeDevice)) return packetsList.remove(i); } } return null; } /** * Returns whether or not the source address of the provided XBee packet * matches the address of the given remote XBee device. * * @param xbeePacket The XBee packet to compare its address with the * remote XBee device. * @param remoteXBeeDevice The remote XBee device to compare its address * with the XBee packet. * * @return {@code true} if the source address of the provided packet (if * it has) matches the address of the remote XBee device. * * @see com.digi.xbee.api.RemoteXBeeDevice * @see com.digi.xbee.api.packet.XBeePacket */ private boolean addressesMatch(XBeePacket xbeePacket, RemoteXBeeDevice remoteXBeeDevice) { if (!(xbeePacket instanceof XBeeAPIPacket)) return false; APIFrameType packetType = ((XBeeAPIPacket)xbeePacket).getFrameType(); switch (packetType) { case RECEIVE_PACKET: if (remoteXBeeDevice.get64BitAddress() != null && ((ReceivePacket)xbeePacket).get64bitSourceAddress().equals(remoteXBeeDevice.get64BitAddress())) return true; if (remoteXBeeDevice.get16BitAddress() != null && ((ReceivePacket)xbeePacket).get16bitSourceAddress().equals(remoteXBeeDevice.get16BitAddress())) return true; break; case REMOTE_AT_COMMAND_RESPONSE: if (remoteXBeeDevice.get64BitAddress() != null && ((RemoteATCommandResponsePacket)xbeePacket).get64bitSourceAddress().equals(remoteXBeeDevice.get64BitAddress())) return true; if (remoteXBeeDevice.get16BitAddress() != null && ((RemoteATCommandResponsePacket)xbeePacket).get16bitSourceAddress().equals(remoteXBeeDevice.get16BitAddress())) return true; break; case RX_16: if (((RX16Packet)xbeePacket).get16bitSourceAddress().equals(remoteXBeeDevice.get16BitAddress())) return true; break; case RX_64: if (((RX64Packet)xbeePacket).get64bitSourceAddress().equals(remoteXBeeDevice.get64BitAddress())) return true; break; case RX_IO_16: if (((RX16IOPacket)xbeePacket).get16bitSourceAddress().equals(remoteXBeeDevice.get16BitAddress())) return true; break; case RX_IO_64: if (((RX64IOPacket)xbeePacket).get64bitSourceAddress().equals(remoteXBeeDevice.get64BitAddress())) return true; break; default: return false; } return false; } /** * Returns whether or not the given XBee packet is a data packet. * * @param xbeePacket The XBee packet to check if is data packet. * * @return {@code true} if the XBee packet is a data packet, {@code false} * otherwise. * * @see com.digi.xbee.api.packet.XBeePacket */ private boolean isDataPacket(XBeePacket xbeePacket) { if (!(xbeePacket instanceof XBeeAPIPacket)) return false; APIFrameType packetType = ((XBeeAPIPacket)xbeePacket).getFrameType(); switch (packetType) { case RECEIVE_PACKET: case RX_16: case RX_64: return true; default: return false; } } /** * Sleeps the thread for the given number of milliseconds. * * @param milliseconds The number of milliseconds that the thread should * be sleeping. */ private void sleep(int milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { } } /** * Returns the maximum size of the XBee packets queue. * * @return The maximum size of the XBee packets queue. */ public int getMaxSize() { return maxLength; } /** * Returns the current size of the XBee packets queue. * * @return The current size of the XBee packets queue. */ public int getCurrentSize() { return packetsList.size(); } }
gpl-2.0
script-solution/FrameWorkSolution
html/textarea.php
2346
<?php /** * Contains the textarea-class * * @package FrameWorkSolution * @subpackage html * * Copyright (C) 2003 - 2012 Nils Asmussen * * 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. */ /** * Represents a text-area: * <code> * <textarea name="...">...</textarea> * </code> * * @package FrameWorkSolution * @subpackage html * @author Nils Asmussen <nils@script-solution.de> */ class FWS_HTML_TextArea extends FWS_HTML_TextElement { /** * The number of rows of the textarea * * @var int */ private $_rows; /** * Constructor * * @param string $name the name of the control * @param mixed $id the id of the element (null = none) * @param mixed $value the value of the element (null = default) * @param mixed $default the default value * @param mixed $cols the cols of the element * @param mixed $rows the number of rows */ public function __construct($name,$id = null,$value = null,$default = '',$cols = 60, $rows = 15) { parent::__construct($name,$id,$value,$default,$cols); $this->set_rows($rows); } /** * @return int the number of rows */ public final function get_rows() { return $this->_rows; } /** * Sets the number of rows of the textarea * * @param int $rows the new value */ public final function set_rows($rows) { $this->_rows = $rows; } public function to_html() { $html = '<textarea'.$this->get_default_attr_html().' cols="'.$this->get_cols().'"'; $html .= ' rows="'.$this->_rows.'">'.$this->get_used_value().'</textarea>'; return $html; } protected function get_dump_vars() { return array_merge(parent::get_dump_vars(),get_object_vars($this)); } } ?>
gpl-2.0
rjbaniel/upoor
wp-content/themes/Feather/footer.php
1202
</div> <!-- end .container --> </div> <!-- end #content --> <div id="footer"> <div class="container"> <div id="footer-widgets" class="clearfix"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer') ) : ?> <?php endif; ?> </div> <!-- end #footer-widgets --> <div id="footer-bottom" class="clearfix"> <?php $menuID = 'bottom-nav'; $footerNav = ''; if (function_exists('wp_nav_menu')) $footerNav = wp_nav_menu( array( 'theme_location' => 'footer-menu', 'container' => '', 'fallback_cb' => '', 'menu_id' => $menuID, 'menu_class' => 'bottom-nav', 'echo' => false, 'depth' => '1' ) ); if ($footerNav == '') show_page_menu($menuID); else echo($footerNav); ?> <p id="copyright"><?php printf( __('Designed by %s | Powered by %s', 'Feather'), '<a href="http://www.elegantthemes.com" title="Premium WordPress Themes">Elegant WordPress Themes</a>', '<a href="http://www.wordpress.org">WordPress</a>' ); ?></p> </div> <!-- end #footer-bottom --> </div> <!-- end .container --> </div> <!-- end #footer --> <?php get_template_part('includes/scripts'); ?> <?php wp_footer(); ?> </body> </html>
gpl-2.0
MatthieuMichon/flight_data_miner
src/extract/geojson_reader.py
2260
#!/usr/bin/python3 """ extract.geojson_reader ~~~~~~~~~~~~~~~~~~~~~~ This module handles flight data represented as a list of positions in a format compliant with the Geo JSON specification. - longitude - latitude - altitude as well as a time in seconds. """ import json import logging class GeoJsonReader: def __init__(self, verbose=False): if verbose: logging.basicConfig( filename='GeoJsonReader.log', level=logging.DEBUG) self.trails = [] def map_coordinates(self, points): return [{ 'lon': point[0], 'lat': point[1], 'alt': point[2], 'time': point[3], 'gs': point[4] } for point in points] def load_feature(self, feature): retval = {} retval['metadata'] = feature['properties'] retval['points'] = self.map_coordinates( feature['geometry']['coordinates']) logging.debug('Loaded {} points'.format(len(retval['points']))) return retval def load_json(self, json_): logging.debug('Decoding Geo JSON data, ' 'size: {} bytes'.format(len(json_))) jdata = json.loads(json_) # Depending on the value of the 'type' element, the GeoJSON data may # either be a single LineString or a collection of LineString. if jdata['type'] == 'Feature': trail = self.load_feature(jdata) self.trails.append(trail) elif jdata['type'] == 'FeatureCollection': for feature in jdata['features']: if feature['type'] == 'Feature': trail = self.load_feature(feature) self.trails.append(trail) def test(verbose): jdata = '''{"type": "Feature", "properties": \ {"title": "NH216", "stroke": "#012"}, \ "geometry": {"type": "LineString", "coordinates": \ [[139.7726, 35.54811, 0, 1448349714, 9], \ [139.77328, 35.54843, 0, 1448349699, 8], \ [139.77411, 35.5489, 0, 1448349678, 25] \ ]}}''' reader = GeoJsonReader(verbose=verbose) reader.load_json(json_=jdata) if not len(reader.trails): print('FAIL') print(reader.trails) if __name__ == '__main__': test(verbose=True)
gpl-2.0