code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package com.shumz.think.ex004;
public class ExFour03 {
public ExFour03() {
System.out.println("An instance of ExFour03 was created...");
}
public static void main(String[] args) {
new ExFour03();
}
}
| Izek/think_in_java_4 | MeCodez/src/com/shumz/think/ex004/ExFour03.java | Java | gpl-3.0 | 210 |
package TFC.Handlers.Client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.event.ForgeSubscribe;
import org.lwjgl.opengl.GL11;
import TFC.Core.TFC_Climate;
import TFC.Core.TFC_Settings;
import TFC.Core.Player.PlayerManagerTFC;
import TFC.Core.Player.TFC_PlayerClient;
import TFC.Food.FoodStatsTFC;
import TFC.Items.Tools.ItemChisel;
import TFC.Items.Tools.ItemCustomHoe;
public class RenderOverlayHandler
{
@ForgeSubscribe
public void render(RenderGameOverlayEvent.Pre event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
}
@ForgeSubscribe
public void render(RenderGameOverlayEvent.Post event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
ScaledResolution sr = event.resolution;
int healthRowHeight = sr.getScaledHeight() - 39;
int armorRowHeight = healthRowHeight - 10;
TFC_PlayerClient playerclient = ((TFC.Core.Player.TFC_PlayerClient)Minecraft.getMinecraft().thePlayer.getPlayerBase("TFC Player Client"));
if(playerclient != null)
{
//Draw Health
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
Minecraft.getMinecraft().renderEngine.bindTexture("/bioxx/icons.png");
this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 0, 90, 10);
float maxHealth = playerclient.getMaxHealth();
float percentHealth = Minecraft.getMinecraft().thePlayer.getHealth()/maxHealth;
this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 9, (int) (90*percentHealth), 9);
//Draw Food and Water
FoodStatsTFC foodstats = playerclient.getFoodStatsTFC();
int foodLevel = foodstats.getFoodLevel();
int preFoodLevel = foodstats.getPrevFoodLevel();
float waterLevel = foodstats.waterLevel;
float percentFood = foodLevel/100f;
float percentWater = waterLevel/foodstats.getMaxWater(Minecraft.getMinecraft().thePlayer);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 18, 90, 5);
if(playerclient.guishowFoodRestoreAmount)
{
float percentFood2 = Math.min(percentFood + playerclient.guiFoodRestoreAmount/100f, 1);
GL11.glColor4f(0.0F, 0.6F, 0.0F, 0.3F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*(percentFood2)), 5);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*percentFood), 5);
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 28, 90, 5);
this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 33, (int) (90*percentWater), 5);
//Render Tool Mode
if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemCustomHoe)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().hoeMode;
this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 38, 20, 20);
}
else if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemChisel)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().ChiselMode;
this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 58, 20, 20);
}
}
Minecraft.getMinecraft().renderEngine.resetBoundTexture();
}
@ForgeSubscribe
public void renderText(RenderGameOverlayEvent.Text event)
{
if(Minecraft.getMinecraft().gameSettings.showDebugInfo || TFC_Settings.enableDebugMode)
{
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
int xCoord = (int)player.posX;
int yCoord = (int)player.posY;
int zCoord = (int)player.posZ;
event.left.add(String.format("rain: %.0f, temp: %.2f, evt: %.3f", new Object[] {
TFC_Climate.getRainfall(xCoord, yCoord, zCoord),
TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord),
TFC_Climate.manager.getEVTLayerAt(xCoord, zCoord).floatdata1}));
event.left.add("Health: " + player.getHealth());
}
}
public void drawTexturedModalRect(int par1, int par2, int par3, int par4, int par5, int par6)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(par1 + 0, par2 + par6, 0.0, (par3 + 0) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + par6, 0.0, (par3 + par5) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + 0, 0.0, (par3 + par5) * f, (par4 + 0) * f1);
tessellator.addVertexWithUV(par1 + 0, par2 + 0, 0.0, (par3 + 0) * f, (par4 + 0) * f1);
tessellator.draw();
}
}
| Timeslice42/TFCraft | TFC_Shared/src/TFC/Handlers/Client/RenderOverlayHandler.java | Java | gpl-3.0 | 5,784 |
namespace ContaLibre.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | seranfuen/contalibre | ContaLibre/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | C# | gpl-3.0 | 242 |
var path = require('path')
module.exports = {
// Webpack aliases
aliases: {
quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),
src: path.resolve(__dirname, '../src'),
assets: path.resolve(__dirname, '../src/assets'),
components: path.resolve(__dirname, '../src/components')
},
// Progress Bar Webpack plugin format
// https://github.com/clessg/progress-bar-webpack-plugin#options
progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)',
// Default theme to build with ('ios' or 'mat')
defaultTheme: 'mat',
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
publicPath: '',
productionSourceMap: false,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css']
},
dev: {
env: require('./dev.env'),
cssSourceMap: true,
// auto open browser or not
openBrowser: true,
publicPath: '/',
port: 8081,
// If for example you are using Quasar Play
// to generate a QR code then on each dev (re)compilation
// you need to avoid clearing out the console, so set this
// to "false", otherwise you can set it to "true" to always
// have only the messages regarding your last (re)compilation.
clearConsoleOnRebuild: false,
// Proxy your API if using any.
// Also see /build/script.dev.js and search for "proxy api requests"
// https://github.com/chimurai/http-proxy-middleware
proxyTable: {}
}
}
/*
* proxyTable example:
*
proxyTable: {
// proxy all requests starting with /api
'/api': {
target: 'https://some.address.com/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
*/
| agustincl/AclBoilerplate | config/index.js | JavaScript | gpl-3.0 | 1,969 |
//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
// Copyright (c) 2002-2011 Merkur ( devs@emule-project.net / http://www.emule-project.net )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//
#include <wx/wx.h>
#include <wx/mstream.h>
#include <wx/tokenzr.h>
#include "updownclient.h" // Needed for CUpDownClient
#include "SharedFileList.h" // Needed for CSharedFileList
#include <protocol/Protocols.h>
#include <protocol/ed2k/Client2Client/TCP.h>
#include <protocol/ed2k/ClientSoftware.h>
#include <protocol/kad/Client2Client/UDP.h>
#include <protocol/kad2/Constants.h>
#include <protocol/kad2/Client2Client/TCP.h>
#include <protocol/kad2/Client2Client/UDP.h>
#include <common/ClientVersion.h>
#include <tags/ClientTags.h>
#include <zlib.h> // Needed for inflateEnd
#include <common/Format.h> // Needed for CFormat
#include "SearchList.h" // Needed for CSearchList
#include "DownloadQueue.h" // Needed for CDownloadQueue
#include "UploadQueue.h" // Needed for CUploadQueue
#include "IPFilter.h" // Needed for CIPFilter
#include "ServerConnect.h" // Needed for CServerConnect
#include "ClientCredits.h" // Needed for CClientCredits
#include "ClientCreditsList.h" // Needed for CClientCreditsList
#include "Server.h" // Needed for CServer
#include "Preferences.h" // Needed for CPreferences
#include "MemFile.h" // Needed for CMemFile
#include "Packet.h" // Needed for CPacket
#include "Friend.h" // Needed for CFriend
#include "ClientList.h" // Needed for CClientList
#ifndef AMULE_DAEMON
#include "amuleDlg.h" // Needed for CamuleDlg
#include "CaptchaDialog.h" // Needed for CCaptchaDialog
#include "CaptchaGenerator.h"
#include "ChatWnd.h" // Needed for CChatWnd
#endif
#include "amule.h" // Needed for theApp
#include "PartFile.h" // Needed for CPartFile
#include "ClientTCPSocket.h" // Needed for CClientTCPSocket
#include "ListenSocket.h" // Needed for CListenSocket
#include "FriendList.h" // Needed for CFriendList
#include "Statistics.h" // Needed for theStats
#include "ClientUDPSocket.h"
#include "Logger.h"
#include "DataToText.h" // Needed for GetSoftName()
#include "GuiEvents.h" // Needed for Notify_
#include "ServerList.h" // For CServerList
#include "kademlia/kademlia/Kademlia.h"
#include "kademlia/kademlia/Prefs.h"
#include "kademlia/kademlia/Search.h"
#include "kademlia/kademlia/UDPFirewallTester.h"
#include "kademlia/routing/RoutingZone.h"
//#define __PACKET_DEBUG__
// some client testing variables
static wxString crash_name = wxT("[Invalid User Name]");
static wxString empty_name = wxT("[Empty User Name]");
// members of CUpDownClient
// which are used by down and uploading functions
CUpDownClient::CUpDownClient(CClientTCPSocket* sender)
{
#ifdef __DEBUG__
m_socket = NULL;
SetSocket(sender);
#else
m_socket = sender;
#endif
Init();
}
CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend)
{
m_socket = NULL;
Init();
m_nUserPort = in_port;
if(ed2kID && !IsLowID(in_userid)) {
SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid) );
} else {
SetUserIDHybrid( in_userid);
}
//If highID and ED2K source, incoming ID and IP are equal..
//If highID and Kad source, incoming IP needs swap for the IP
if (!HasLowID()) {
if (ed2kID) {
m_nConnectIP = in_userid;
} else {
m_nConnectIP = wxUINT32_SWAP_ALWAYS(in_userid);
}
// Will be on right endianess now
m_FullUserIP = m_nConnectIP;
}
m_dwServerIP = in_serverip;
m_nServerPort = in_serverport;
SetRequestFile( in_reqfile );
ReGetClientSoft();
if (checkfriend) {
if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
m_bFriendSlot = false;
}
}
}
void CUpDownClient::Init()
{
m_linked = 0;
#ifdef DEBUG_ZOMBIE_CLIENTS
m_linkedDebug = false;
#endif
m_bAddNextConnect = false;
credits = NULL;
m_byChatstate = MS_NONE;
m_nKadState = KS_NONE;
m_nChatCaptchaState = CA_NONE;
m_cShowDR = 0;
m_reqfile = NULL; // No file required yet
m_nTransferredUp = 0;
m_cSendblock = 0;
m_cAsked = 0;
msReceivedPrev = 0;
kBpsDown = 0.0;
bytesReceivedCycle = 0;
m_nServerPort = 0;
m_iFileListRequested = 0;
m_dwLastUpRequest = 0;
m_bEmuleProtocol = false;
m_bCompleteSource = false;
m_bFriendSlot = false;
m_bCommentDirty = false;
m_bReaskPending = false;
m_bUDPPending = false;
m_nUserPort = 0;
m_nPartCount = 0;
m_dwLastAskedTime = 0;
m_nDownloadState = DS_NONE;
m_dwUploadTime = 0;
m_nTransferredDown = 0;
m_nUploadState = US_NONE;
m_dwLastBlockReceived = 0;
m_bUnicodeSupport = false;
m_fSentOutOfPartReqs = 0;
m_nCurQueueSessionPayloadUp = 0;
m_addedPayloadQueueSession = 0;
m_nUpDatarate = 0;
m_nSumForAvgUpDataRate = 0;
m_nRemoteQueueRank = 0;
m_nOldRemoteQueueRank = 0;
m_dwLastSourceRequest = 0;
m_dwLastSourceAnswer = 0;
m_dwLastAskedForSources = 0;
m_SecureIdentState = IS_UNAVAILABLE;
m_dwLastSignatureIP = 0;
m_byInfopacketsReceived = IP_NONE;
m_bIsHybrid = false;
m_bIsML = false;
m_Friend = NULL;
m_iRating = 0;
m_nCurSessionUp = 0;
m_clientSoft=SO_UNKNOWN;
m_bRemoteQueueFull = false;
m_HasValidHash = false;
SetWaitStartTime();
m_fHashsetRequesting = 0;
m_fSharedDirectories = 0;
m_lastPartAsked = 0xffff;
m_nUpCompleteSourcesCount= 0;
m_waitingPosition = 0;
m_score = 0;
m_lastRefreshedDLDisplay = 0;
m_bHelloAnswerPending = false;
m_fSentCancelTransfer = 0;
m_Aggressiveness = 0;
m_LastFileRequest = 0;
m_clientState = CS_NEW;
ClearHelloProperties();
m_pReqFileAICHHash = NULL;
m_fSupportsAICH = 0;
m_fAICHRequested = 0;
m_fSupportsLargeFiles = 0;
m_fExtMultiPacket = 0;
m_fIsSpammer = 0;
m_dwUserIP = 0;
m_nConnectIP = 0;
m_dwServerIP = 0;
m_fNeedOurPublicIP = false;
m_bHashsetRequested = false;
m_lastDownloadingPart = 0;
m_uploadingfile = NULL;
m_OSInfo_sent = false;
/* Kad stuff */
SetBuddyID(NULL);
m_nBuddyIP = 0;
m_nBuddyPort = 0;
m_nUserIDHybrid = 0;
m_nSourceFrom = SF_NONE;
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
SetIP(0);
}
/* Statistics */
m_lastClientSoft = (uint32)(-1);
m_lastClientVersion = 0;
/* Creation time (for buddies timeout) */
m_nCreationTime = ::GetTickCount();
m_MaxBlockRequests = STANDARD_BLOCKS_REQUEST; // Safe starting amount
m_last_block_start = 0;
m_lastaverage = 0;
SetLastBuddyPingPongTime();
m_fRequestsCryptLayer = 0;
m_fSupportsCryptLayer = 0;
m_fRequiresCryptLayer = 0;
m_fSupportsSourceEx2 = 0;
m_fSupportsCaptcha = 0;
m_fDirectUDPCallback = 0;
m_dwDirectCallbackTimeout = 0;
m_hasbeenobfuscatinglately = false;
m_cCaptchasSent = 0;
m_cMessagesReceived = 0;
m_cMessagesSent = 0;
}
CUpDownClient::~CUpDownClient()
{
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddDebugLogLineN(logClient, wxT("Client to check for ") + connection_reason + wxT(" was deleted without connection."));
}
#endif
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
// Indicate that we are not anymore on stats
m_lastClientSoft = (uint32)(-1);
// The socket should have been removed in Safe_Delete, but it
// doesn't hurt to have an extra check.
if (m_socket) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
ClearUploadBlockRequests();
ClearDownloadBlockRequests();
DeleteContents(m_WaitingPackets_list);
// Allow detection of deleted clients that didn't go through Safe_Delete
m_clientState = CS_DYING;
}
void CUpDownClient::ClearHelloProperties()
{
m_nUDPPort = 0;
m_byUDPVer = 0;
m_byDataCompVer = 0;
m_byEmuleVersion = 0;
m_bySourceExchange1Ver = 0;
m_byAcceptCommentVer = 0;
m_byExtendedRequestsVer = 0;
m_byCompatibleClient = 0;
m_nKadPort = 0;
m_bySupportSecIdent = 0;
m_bSupportsPreview = 0;
m_nClientVersion = 0;
m_fSharedDirectories = 0;
m_bMultiPacket = 0;
m_fOsInfoSupport = 0;
m_fValueBasedTypeTags = 0;
SecIdentSupRec = 0;
m_byKadVersion = 0;
m_fRequestsCryptLayer = 0;
m_fSupportsCryptLayer = 0;
m_fRequiresCryptLayer = 0;
m_fSupportsSourceEx2 = 0;
m_fSupportsCaptcha = 0;
m_fDirectUDPCallback = 0;
m_bIsHybrid = false;
m_bIsML = false;
m_fNoViewSharedFiles = true; // that's a sensible default to assume until we get the real value
m_bUnicodeSupport = false;
}
bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
uint8 hashsize = data.ReadUInt8();
if ( 16 != hashsize ) {
/*
* Hint: We can not accept other sizes here because:
* - the magic number is spread all over the source
* - the answer packet lacks the size field
*/
throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
}
// eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
ClearHelloProperties();
return ProcessHelloTypePacket(data);
}
void CUpDownClient::Safe_Delete()
{
// Because we are delaying the deletion, we might end up trying to delete
// it twice, however, this is normal and shouldn't trigger any failures
if ( m_clientState == CS_DYING ) {
return;
}
// If called from background, post an event to process it in main thread
if (!wxThread::IsMain()) {
CoreNotify_Client_Delete(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete CoreNotify_Client_Delete")));
return;
}
m_clientState = CS_DYING;
// Make sure client doesn't get deleted until this method is finished
CClientRef ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker")));
// Close the socket to avoid any more connections and related events
if ( m_socket ) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
// Remove the client from the clientlist if we still have it
if ( theApp->clientlist ) {
theApp->clientlist->RemoveClient( this );
}
// Doing what RemoveClient used to do. Just to be sure...
if (theApp->uploadqueue) {
theApp->uploadqueue->RemoveFromUploadQueue(this);
theApp->uploadqueue->RemoveFromWaitingQueue(this);
}
if (theApp->downloadqueue) {
theApp->downloadqueue->RemoveSource(this);
}
// For security, remove it from the lists unconditionally.
Notify_SharedCtrlRemoveClient(ECID(), (CKnownFile*)NULL);
Notify_SourceCtrlRemoveSource(ECID(), (CPartFile*)NULL);
if (IsAICHReqPending()){
m_fAICHRequested = FALSE;
CAICHHashSet::ClientAICHRequestFailed(this);
}
if (m_Friend) {
m_Friend->UnLinkClient(); // this notifies
m_Friend = NULL;
}
if (m_iRating>0 || !m_strComment.IsEmpty()) {
m_iRating = 0;
m_strComment.Clear();
if (m_reqfile) {
m_reqfile->UpdateFileRatingCommentAvail();
}
}
// Ensure that source-counts gets updated in case
// of a source not on the download-queue
SetRequestFile( NULL );
SetUploadFileID(NULL);
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
#ifdef DEBUG_ZOMBIE_CLIENTS
if (m_linked > 1) {
AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked - 1) % GetLinkedFrom());
m_linkedDebug = true;
}
#endif
}
bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
bool bIsMule = ProcessHelloTypePacket(data);
m_bHelloAnswerPending = false;
return bIsMule;
}
bool CUpDownClient::ProcessHelloTypePacket(const CMemFile& data)
{
uint32 dwEmuleTags = 0;
CMD4Hash hash = data.ReadHash();
SetUserHash( hash );
SetUserIDHybrid( data.ReadUInt32() );
uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why?
uint32 tagcount = data.ReadUInt32();
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case CT_NAME:
m_Username = temptag.GetStr();
break;
case CT_VERSION:
m_nClientVersion = temptag.GetInt();
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
case CT_PORT:
nUserPort = temptag.GetInt();
break;
case CT_EMULE_UDPPORTS:
// 16 KAD Port
// 16 UDP Port
SetKadPort((temptag.GetInt() >> 16) & 0xFFFF);
m_nUDPPort = temptag.GetInt() & 0xFFFF;
dwEmuleTags |= 1;
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort % m_nKadPort);
#endif
break;
case CT_EMULE_BUDDYIP:
// 32 BUDDY IP
m_nBuddyIP = temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP % Uint32toStringIP(m_nBuddyIP));
#endif
break;
case CT_EMULE_BUDDYUDP:
// 16 --Reserved for future use--
// 16 BUDDY Port
m_nBuddyPort = (uint16)temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort);
#endif
break;
case CT_EMULE_MISCOPTIONS1: {
// 3 AICH Version (0 = not supported)
// 1 Unicode
// 4 UDP version
// 4 Data compression version
// 4 Secure Ident
// 4 Source Exchange
// 4 Ext. Requests
// 4 Comments
// 1 PeerCache supported
// 1 No 'View Shared Files' supported
// 1 MultiPacket
// 1 Preview
uint32 flags = temptag.GetInt();
m_fSupportsAICH = (flags >> (4*7+1)) & 0x07;
m_bUnicodeSupport = (flags >> 4*7) & 0x01;
m_byUDPVer = (flags >> 4*6) & 0x0f;
m_byDataCompVer = (flags >> 4*5) & 0x0f;
m_bySupportSecIdent = (flags >> 4*4) & 0x0f;
m_bySourceExchange1Ver = (flags >> 4*3) & 0x0f;
m_byExtendedRequestsVer = (flags >> 4*2) & 0x0f;
m_byAcceptCommentVer = (flags >> 4*1) & 0x0f;
m_fNoViewSharedFiles = (flags >> 1*2) & 0x01;
m_bMultiPacket = (flags >> 1*1) & 0x01;
m_fSupportsPreview = (flags >> 1*0) & 0x01;
dwEmuleTags |= 2;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer);
AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer);
AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent);
AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver);
AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer);
AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer);
AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles);
AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket);
AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories);
AddLogLineNS(wxT("That's all."));
#endif
SecIdentSupRec += 1;
break;
}
case CT_EMULE_MISCOPTIONS2:
// 19 Reserved
// 1 Direct UDP Callback supported and available
// 1 Supports ChatCaptchas
// 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
// 1 Requires CryptLayer
// 1 Requests CryptLayer
// 1 Supports CryptLayer
// 1 Reserved (ModBit)
// 1 Ext Multipacket (Hash+Size instead of Hash)
// 1 Large Files (includes support for 64bit tags)
// 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
m_fDirectUDPCallback = (temptag.GetInt() >> 12) & 0x01;
m_fSupportsCaptcha = (temptag.GetInt() >> 11) & 0x01;
m_fSupportsSourceEx2 = (temptag.GetInt() >> 10) & 0x01;
m_fRequiresCryptLayer = (temptag.GetInt() >> 9) & 0x01;
m_fRequestsCryptLayer = (temptag.GetInt() >> 8) & 0x01;
m_fSupportsCryptLayer = (temptag.GetInt() >> 7) & 0x01;
// reserved 1
m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01;
m_fSupportsLargeFiles = (temptag.GetInt() >> 4) & 0x01;
m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f;
dwEmuleTags |= 8;
m_fRequestsCryptLayer &= m_fSupportsCryptLayer;
m_fRequiresCryptLayer &= m_fRequestsCryptLayer;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback);
AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha);
AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2);
AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer);
AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket);
AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles);
AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion);
AddLogLineNS(wxT("That's all."));
#endif
break;
// Special tag for Compat. Clients Misc options.
case CT_EMULECOMPAT_OPTIONS:
// 1 Operative System Info
// 1 Value-based-type int tags (experimental!)
m_fValueBasedTypeTags = (temptag.GetInt() >> 1*1) & 0x01;
m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01;
break;
case CT_EMULE_VERSION:
// 8 Compatible Client ID
// 7 Mjr Version (Doesn't really matter..)
// 7 Min Version (Only need 0-99)
// 3 Upd Version (Only need 0-5)
// 7 Bld Version (Only need 0-99)
m_byCompatibleClient = (temptag.GetInt() >> 24);
m_nClientVersion = temptag.GetInt() & 0x00ffffff;
m_byEmuleVersion = 0x99;
m_fSharedDirectories = 1;
dwEmuleTags |= 4;
break;
}
}
m_nUserPort = nUserPort;
m_dwServerIP = data.ReadUInt32();
m_nServerPort = data.ReadUInt16();
// Hybrid now has an extra uint32.. What is it for?
// Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) {
uint32 test = data.ReadUInt32();
/*if (test == 'KDLM') below kdlm is converted to ascii values.
This fixes a warning with gcc 3.4.
K=4b D=44 L=4c M=4d
*/
if (test == 0x4b444c4d) { //if it's == "KDLM"
m_bIsML=true;
} else{
m_bIsHybrid = true;
m_fSharedDirectories = 1;
}
}
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
}
if (thePrefs::AddServersFromClient()) {
CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP));
addsrv->SetListName(addsrv->GetAddress());
if (!theApp->AddServer(addsrv)) {
delete addsrv;
}
}
//(a)If this is a highID user, store the ID in the Hybrid format.
//(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
//(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily
//because they will send a ID that is the same as their IP..
if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) {
SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP));
}
// get client credits
CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash);
if (credits == NULL){
credits = pFoundCredits;
if (!theApp->clientlist->ComparePriorUserhash(m_dwUserIP, m_nUserPort, pFoundCredits)){
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
Ban();
}
} else if (credits != pFoundCredits){
// userhash change ok, however two hours "waittime" before it can be used
credits = pFoundCredits;
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
Ban();
}
if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::ProcessHelloTypePacket m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
SetFriendSlot(false);
}
ReGetClientSoft();
m_byInfopacketsReceived |= IP_EDONKEYPROTPACK;
// check if at least CT_EMULEVERSION was received, all other tags are optional
bool bIsMule = (dwEmuleTags & 0x04) == 0x04;
if (bIsMule) {
m_bEmuleProtocol = true;
m_byInfopacketsReceived |= IP_EMULEPROTPACK;
}
if (GetKadPort() && GetKadVersion() > 1) {
Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort());
}
return bIsMule;
}
bool CUpDownClient::SendHelloPacket()
{
if (m_socket == NULL) {
wxFAIL;
return true;
}
// if IP is filtered, don't greet him but disconnect...
if (theApp->ipfilter->IsFiltered(m_socket->GetPeerInt())) {
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
CMemFile data(128);
data.WriteUInt8(16); // size of userhash
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true);
m_bHelloAnswerPending = true;
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
return true;
}
void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) {
if (m_socket == NULL){
wxFAIL;
return;
}
CPacket* packet = NULL;
CMemFile data;
data.WriteUInt8(CURRENT_VERSION_SHORT);
if (OSInfo) {
// Special MuleInfo packet for clients supporting it.
// This means aMule >= 2.0.0 and Hydranode
// Violently mark it as special Mule Info packet
// Sending this makes non-supporting-osinfo clients to refuse to read this
// packet. Anyway, this packet should NEVER get to non-supporting clients.
data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
data.WriteUInt32(1); // One Tag (OS_INFO)
CTagString tag1(ET_OS_INFO,theApp->GetOSType());
tag1.WriteTagToFile(&data);
m_OSInfo_sent = true; // So we don't send it again
} else {
// Normal MuleInfo packet
// Kry - There's no point on upgrading to VBT tags here
// as no client supporting it uses mule info packet.
data.WriteUInt8(EMULE_PROTOCOL);
// Tag number
data.WriteUInt32(9);
CTagInt32 tag1(ET_COMPRESSION,1);
tag1.WriteTagToFile(&data);
CTagInt32 tag2(ET_UDPVER,4);
tag2.WriteTagToFile(&data);
CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort());
tag3.WriteTagToFile(&data);
CTagInt32 tag4(ET_SOURCEEXCHANGE,3);
tag4.WriteTagToFile(&data);
CTagInt32 tag5(ET_COMMENTS,1);
tag5.WriteTagToFile(&data);
CTagInt32 tag6(ET_EXTENDEDREQUEST,2);
tag6.WriteTagToFile(&data);
uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0);
// Kry - Needs the preview code from eMule
/*
// set 'Preview supported' only if 'View Shared Files' allowed
if (thePrefs::CanSeeShares() != vsfaNobody) {
dwTagValue |= 128;
}
*/
CTagInt32 tag7(ET_FEATURES, dwTagValue);
tag7.WriteTagToFile(&data);
CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE);
tag8.WriteTagToFile(&data);
// Support for tag ET_MOD_VERSION
wxString mod_name(MOD_VERSION_LONG);
CTagString tag9(ET_MOD_VERSION, mod_name);
tag9.WriteTagToFile(&data);
// Maella end
}
packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO));
if (m_socket) {
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (!bAnswer) {
if (!OSInfo) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
}
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
}
#endif
}
}
bool CUpDownClient::ProcessMuleInfoPacket(const byte* pachPacket, uint32 nSize)
{
uint8 protocol_version;
const CMemFile data(pachPacket,nSize);
// The version number part of this packet will soon be useless since
// it is only able to go to v.99. Why the version is a uint8 and why
// it was not done as a tag like the eDonkey hello packet is not known.
// Therefore, sooner or later, we are going to have to switch over to
// using the eDonkey hello packet to set the version. No sense making
// a third value sent for versions.
uint8 mule_version = data.ReadUInt8();
protocol_version = data.ReadUInt8();
uint32 tagcount = data.ReadUInt32();
if (protocol_version == 0xFF) {
// OS Info supporting clients sending a recycled Mule info packet
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case ET_OS_INFO:
// Special tag, only supporting clients (aMule/Hydranode)
// It was recycled from a mod's tag, so if the other side
// is not supporting OS Info, we're seriously fucked up :)
m_sClientOSInfo = temptag.GetStr();
// If we didn't send our OSInfo to this client, just send it
if (!m_OSInfo_sent) {
SendMuleInfoPacket(false,true);
}
UpdateStats();
break;
// Your ad... er... I mean TAG, here
default:
break;
}
}
} else {
// Old eMule sending tags
m_byCompatibleClient = 0;
m_byEmuleVersion = mule_version;
if( m_byEmuleVersion == 0x2B ) {
m_byEmuleVersion = 0x22;
}
if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) {
return false;
}
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, false);
switch(temptag.GetNameID()){
case ET_COMPRESSION:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: data compression version
m_byDataCompVer = temptag.GetInt();
break;
case ET_UDPPORT:
// Bits 31-16: 0 - reserved
// Bits 15- 0: UDP port
m_nUDPPort = temptag.GetInt();
break;
case ET_UDPVER:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: UDP protocol version
m_byUDPVer = temptag.GetInt();
break;
case ET_SOURCEEXCHANGE:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: source exchange protocol version
m_bySourceExchange1Ver = temptag.GetInt();
break;
case ET_COMMENTS:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: comments version
m_byAcceptCommentVer = temptag.GetInt();
break;
case ET_EXTENDEDREQUEST:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: extended requests version
m_byExtendedRequestsVer = temptag.GetInt();
break;
case ET_COMPATIBLECLIENT:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: compatible client ID
m_byCompatibleClient = temptag.GetInt();
break;
case ET_FEATURES:
// Bits 31- 8: 0 - reserved
// Bit 7: Preview
// Bit 6- 0: secure identification
m_bySupportSecIdent = temptag.GetInt() & 3;
m_bSupportsPreview = (temptag.GetInt() & 128) > 0;
SecIdentSupRec += 2;
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
default:
AddDebugLogLineN( logPacketErrors,
CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
% temptag.GetFullInfo()
% GetClientFullInfo()
);
break;
}
}
if( m_byDataCompVer == 0 ){
m_bySourceExchange1Ver = 0;
m_byExtendedRequestsVer = 0;
m_byAcceptCommentVer = 0;
m_nUDPPort = 0;
}
//implicitly supported options by older clients
//in the future do not use version to guess about new features
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) {
m_byUDPVer = 1;
}
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) {
m_bySourceExchange1Ver = 1;
}
if(m_byEmuleVersion == 0x24) {
m_byAcceptCommentVer = 1;
}
// Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
// the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a
// directory which has a trailing backslash.
if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories
m_fSharedDirectories = 1;
}
ReGetClientSoft();
m_byInfopacketsReceived |= IP_EMULEPROTPACK;
}
return (protocol_version == 0xFF); // This was a OS_Info?
}
void CUpDownClient::SendHelloAnswer()
{
if (m_socket == NULL){
wxFAIL;
return;
}
CMemFile data(128);
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
SendPacket(packet,true);
}
void CUpDownClient::SendHelloTypePacket(CMemFile* data)
{
data->WriteHash(thePrefs::GetUserHash());
data->WriteUInt32(theApp->GetID());
data->WriteUInt16(thePrefs::GetPort());
uint32 tagcount = 6;
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
tagcount += 2;
}
tagcount ++; // eMule misc flags 2 (kad version)
#ifdef __SVN__
// Kry - This is the tagcount!!! Be sure to update it!!
// Last update: CT_EMULECOMPAT_OPTIONS included
data->WriteUInt32(tagcount + 1);
#else
data->WriteUInt32(tagcount); // NO MOD_VERSION
#endif
CTagString tagname(CT_NAME,thePrefs::GetUserNick());
tagname.WriteTagToFile(data, utf8strRaw);
CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32);
tagversion.WriteTagToFile(data);
// eMule UDP Ports
uint32 kadUDPPort = 0;
if(Kademlia::CKademlia::IsConnected()) {
if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
} else {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
}
}
CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
tagUdpPorts.WriteTagToFile(data);
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
tagBuddyIP.WriteTagToFile(data);
CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP,
// ( RESERVED )
((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() )
, GetVBTTags() ? 0 : 32);
tagBuddyPort.WriteTagToFile(data);
}
// aMule Version
CTagVarInt tagMuleVersion(CT_EMULE_VERSION,
(SO_AMULE << 24) |
make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
// | (RESERVED )
, GetVBTTags() ? 0 : 32);
tagMuleVersion.WriteTagToFile(data);
// eMule Misc. Options #1
const uint32 uUdpVer = 4;
const uint32 uDataCompVer = 1;
const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0;
const uint32 uSourceExchangeVer = 3;
const uint32 uExtendedRequestsVer = 2;
const uint32 uAcceptCommentVer = 1;
const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
const uint32 uMultiPacket = 1;
const uint32 uSupportPreview = 0; // No network preview at all.
const uint32 uPeerCache = 0; // No peercache for aMule, baby
const uint32 uUnicodeSupport = 1;
const uint32 nAICHVer = 1; // AICH is ENABLED right now.
CTagVarInt tagMisOptions(CT_EMULE_MISCOPTIONS1,
(nAICHVer << ((4*7)+1)) |
(uUnicodeSupport << 4*7) |
(uUdpVer << 4*6) |
(uDataCompVer << 4*5) |
(uSupportSecIdent << 4*4) |
(uSourceExchangeVer << 4*3) |
(uExtendedRequestsVer << 4*2) |
(uAcceptCommentVer << 4*1) |
(uPeerCache << 1*3) |
(uNoViewSharedFiles << 1*2) |
(uMultiPacket << 1*1) |
(uSupportPreview << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisOptions.WriteTagToFile(data);
// eMule Misc. Options #2
const uint32 uKadVersion = KADEMLIA_VERSION;
const uint32 uSupportLargeFiles = 1;
const uint32 uExtMultiPacket = 1;
const uint32 uReserved = 0; // mod bit
const uint32 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
const uint32 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
const uint32 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
const uint32 uSupportsSourceEx2 = 1;
#ifdef AMULE_DAEMON
// captcha for daemon/remotegui not supported for now
const uint32 uSupportsCaptcha = 0;
#else
const uint32 uSupportsCaptcha = 1;
#endif
// direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
&& !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
CTagVarInt tagMisOptions2(CT_EMULE_MISCOPTIONS2,
// (RESERVED )
(uDirectUDPCallback << 12) |
(uSupportsCaptcha << 11) |
(uSupportsSourceEx2 << 10) |
(uRequiresCryptLayer << 9) |
(uRequestsCryptLayer << 8) |
(uSupportsCryptLayer << 7) |
(uReserved << 6) |
(uExtMultiPacket << 5) |
(uSupportLargeFiles << 4) |
(uKadVersion << 0)
, GetVBTTags() ? 0 : 32 );
tagMisOptions2.WriteTagToFile(data);
const uint32 nOSInfoSupport = 1; // We support OS_INFO
const uint32 nValueBasedTypeTags = 0; // Experimental, disabled
CTagVarInt tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS,
(nValueBasedTypeTags << 1*1) |
(nOSInfoSupport << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisCompatOptions.WriteTagToFile(data);
#ifdef __SVN__
wxString mod_name(MOD_VERSION_LONG);
CTagString tagModName(ET_MOD_VERSION, mod_name);
tagModName.WriteTagToFile(data);
#endif
uint32 dwIP = 0;
uint16 nPort = 0;
if (theApp->IsConnectedED2K()) {
dwIP = theApp->serverconnect->GetCurrentServer()->GetIP();
nPort = theApp->serverconnect->GetCurrentServer()->GetPort();
}
data->WriteUInt32(dwIP);
data->WriteUInt16(nPort);
}
void CUpDownClient::ProcessMuleCommentPacket(const byte* pachPacket, uint32 nSize)
{
if (!m_reqfile) {
throw CInvalidPacket(wxT("Comment packet for unknown file"));
}
if (!m_reqfile->IsPartFile()) {
throw CInvalidPacket(wxT("Comment packet for completed file"));
}
const CMemFile data(pachPacket, nSize);
uint8 rating = data.ReadUInt8();
if (rating > 5) {
AddDebugLogLineN( logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating);
m_iRating = 0;
} else {
m_iRating = rating;
AddDebugLogLineN( logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating);
}
// The comment is unicoded, with a uin32 len and safe read
// (won't break if string size is < than advertised len)
// Truncated to MAXFILECOMMENTLEN size
m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN);
AddDebugLogLineN( logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment);
// Update file rating
m_reqfile->UpdateFileRatingCommentAvail();
}
void CUpDownClient::ClearDownloadBlockRequests()
{
{
std::list<Requested_Block_Struct*>::iterator it = m_DownloadBlocks_list.begin();
for (; it != m_DownloadBlocks_list.end(); ++it) {
Requested_Block_Struct* cur_block = *it;
if (m_reqfile){
m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset);
}
delete cur_block;
}
m_DownloadBlocks_list.clear();
}
{
std::list<Pending_Block_Struct*>::iterator it = m_PendingBlocks_list.begin();
for (; it != m_PendingBlocks_list.end(); ++it) {
Pending_Block_Struct* pending = *it;
if (m_reqfile) {
m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
}
delete pending->block;
// Not always allocated
if (pending->zStream){
inflateEnd(pending->zStream);
delete pending->zStream;
}
delete pending;
}
m_PendingBlocks_list.clear();
}
}
bool CUpDownClient::Disconnected(const wxString& DEBUG_ONLY(strReason), bool bFromSocket)
{
//wxASSERT(theApp->clientlist->IsValidClient(this));
if (HasBeenDeleted()) {
AddDebugLogLineN(logClient, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP()));
return false;
}
// was this a direct callback?
if (m_dwDirectCallbackTimeout != 0) {
theApp->clientlist->RemoveDirectCallback(this);
m_dwDirectCallbackTimeout = 0;
theApp->clientlist->AddDeadSource(this);
AddDebugLogLineN(logClient, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
}
if (GetKadState() == KS_QUEUED_FWCHECK_UDP || GetKadState() == KS_CONNECTING_FWCHECK_UDP) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled
} else if (GetKadState() == KS_FWCHECK_UDP) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed
} else if (GetKadState() == KS_CONNECTED_BUDDY) {
AddDebugLogLineN(logClient, wxT("Buddy client disconnected - ") + strReason);
}
//If this is a KAD client object, just delete it!
SetKadState(KS_NONE);
if (GetUploadState() == US_UPLOADING) {
// sets US_NONE
theApp->uploadqueue->RemoveFromUploadQueue(this);
}
if (GetDownloadState() == DS_DOWNLOADING) {
SetDownloadState(DS_ONQUEUE);
} else {
// ensure that all possible block requests are removed from the partfile
ClearDownloadBlockRequests();
if (GetDownloadState() == DS_CONNECTED) {
// successfully connected, but probably didn't respond to our filerequest
theApp->clientlist->AddDeadSource(this);
theApp->downloadqueue->RemoveSource(this);
}
}
// we had still an AICH request pending, handle it
if (IsAICHReqPending()) {
m_fAICHRequested = FALSE;
CAICHHashSet::ClientAICHRequestFailed(this);
}
// The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
// after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
// is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
if (((GetDownloadState() == DS_REQHASHSET) || m_fHashsetRequesting) && (m_reqfile)) {
m_reqfile->SetHashSetNeeded(true);
}
SourceItemType source_type = UNAVAILABLE_SOURCE;
SourceItemType peer_type = UNAVAILABLE_SOURCE;
//check if this client is needed in any way, if not delete it
bool bDelete = true;
switch (m_nUploadState) {
case US_ONUPLOADQUEUE:
bDelete = false;
peer_type = AVAILABLE_SOURCE;
break;
};
switch (m_nDownloadState) {
case DS_ONQUEUE:
source_type = A4AF_SOURCE; // Will be checked.
case DS_TOOMANYCONNS:
case DS_NONEEDEDPARTS:
case DS_LOWTOLOWIP:
bDelete = false;
break;
};
switch (m_nUploadState) {
case US_CONNECTING:
case US_WAITCALLBACK:
case US_ERROR:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
switch (m_nDownloadState) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_ERROR:
case DS_BANNED:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
// We keep chat partners in any case
if (GetChatState() != MS_NONE) {
bDelete = false;
m_pendingMessage.Clear();
Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString);
}
// Delete socket
if (!bFromSocket && m_socket) {
wxASSERT (theApp->listensocket->IsValidSocket(m_socket));
m_socket->Safe_Delete();
}
SetSocket(NULL);
if (m_iFileListRequested) {
AddLogLineC(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
m_iFileListRequested = 0;
}
if (bDelete) {
if (m_Friend) {
// Remove the friend linkage
m_Friend->UnLinkClient(); // this notifies
}
} else {
Notify_SharedCtrlRefreshClient(ECID(), peer_type);
Notify_SourceCtrlUpdateSource(ECID(), source_type);
m_fHashsetRequesting = 0;
SetSentCancelTransfer(0);
m_bHelloAnswerPending = false;
m_fSentOutOfPartReqs = 0;
}
AddDebugLogLineN(logClient, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
% (bDelete ? wxT("Deleted") : wxT("Disconnected"))
% m_nDownloadState % m_nUploadState % GetClientFullInfo() % strReason );
return bDelete;
}
//Returned bool is not if the TryToConnect is successful or not..
//false means the client was deleted!
//true means the client was not deleted!
bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon)
{
// Kad reviewed
if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) {
if (!(m_socket && m_socket->IsConnected())) {
if(Disconnected(wxT("Too many connections"))) {
Safe_Delete();
return false;
}
return true;
}
}
// Do not try to connect to source which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){
if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
Safe_Delete();
return false;
} else {
return true;
}
}
// Ipfilter check
uint32 uClientIP = GetIP();
if (uClientIP == 0 && !HasLowID()) {
uClientIP = wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid);
}
if (uClientIP) {
// Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
// we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
if (theApp->ipfilter->IsFiltered(uClientIP)) {
AddDebugLogLineN(logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP));
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
// for safety: check again whether that IP is banned
if (theApp->clientlist->IsBannedClient(uClientIP)) {
AddDebugLogLineN(logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP));
if (Disconnected(wxT("Banned IP"))) {
Safe_Delete();
return false;
}
return true;
}
}
if (GetKadState() == KS_QUEUED_FWCHECK) {
SetKadState(KS_CONNECTING_FWCHECK);
} else if (GetKadState() == KS_QUEUED_FWCHECK_UDP) {
SetKadState(KS_CONNECTING_FWCHECK_UDP);
}
if (HasLowID()) {
if (!theApp->CanDoCallback(GetServerIP(), GetServerPort())) {
//We cannot do a callback!
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_LOWTOLOWIP);
} else if (GetDownloadState() == DS_REQHASHSET) {
SetDownloadState(DS_ONQUEUE);
m_reqfile->SetHashSetNeeded(true);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
}
return true;
}
//We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
//If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
//with the condition that the source is firewalled and we are firewalled, we must
//recheck it before the this check..
if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort())
&& !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) {
//This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
if( Kademlia::CKademlia::IsConnected() ) {
//We are connect to Kad
if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
//There are too many source lookups already or we are already searching this key.
SetDownloadState(DS_TOOMANYCONNSKAD);
return true;
}
}
}
}
if (!m_socket || !m_socket->IsConnected()) {
if (m_socket) {
m_socket->Safe_Delete();
}
m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData());
} else {
ConnectionEstablished();
return true;
}
if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
if (m_dwDirectCallbackTimeout != 0) {
AddDebugLogLineN(logClient, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
return true; // We're already trying a direct connection to this client
}
// a direct callback is possible - since no other parties are involved and only one additional packet overhead
// is used we basically handle it like a normal connection try, no restrictions apply
// we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
m_dwDirectCallbackTimeout = ::GetTickCount() + SEC2MS(45);
theApp->clientlist->AddDirectCallbackClient(this);
AddDebugLogLineN(logClient, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
CMemFile data;
data.WriteUInt16(thePrefs::GetPort()); // needs to know our port
data.WriteHash(thePrefs::GetUserHash()); // and userhash
// our connection settings
data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
AddDebugLogLineN(logClientUDP, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_DIRECTCALLBACKREQ);
theStats::AddUpOverheadOther(packet->GetPacketSize());
theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0);
} else if (HasLowID()) { // LOWID
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_WAITCALLBACK);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
return true;
}
if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) {
CMemFile data;
// AFAICS, this id must be reversed to be sent to clients
// But if I reverse it, we do a serve violation ;)
data.WriteUInt32(m_nUserIDHybrid);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST);
theStats::AddUpOverheadServer(packet->GetPacketSize());
AddDebugLogLineN(logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
theApp->serverconnect->SendPacket(packet);
SetDownloadState(DS_WAITCALLBACK);
} else {
if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) {
if( !HasValidBuddyID() ) {
theApp->downloadqueue->RemoveSource(this);
if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
Safe_Delete();
return false;
}
return true;
}
if( !Kademlia::CKademlia::IsConnected() ) {
//We are not connected to Kad and this is a Kad Firewalled source..
theApp->downloadqueue->RemoveSource(this);
if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
Safe_Delete();
return false;
}
return true;
}
if( GetDownloadState() == DS_WAITCALLBACK ) {
if( GetBuddyIP() && GetBuddyPort()) {
CMemFile bio(34);
bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
bio.WriteUInt16(thePrefs::GetPort());
CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, KADEMLIA_CALLBACK_REQ);
// eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0);
AddDebugLogLineN(logClientKadUDP, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort()));
theStats::AddUpOverheadKad(packet->GetRealPacketSize());
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
AddLogLineN(_("Searching buddy for lowid connection"));
//Create search to find buddy.
Kademlia::CSearch *findSource = new Kademlia::CSearch;
findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE);
findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
if(Kademlia::CSearchManager::StartSearch(findSource)) {
//Started lookup..
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
//This should never happen..
wxFAIL;
}
}
}
} else {
if (GetDownloadState() == DS_WAITCALLBACK) {
m_bReaskPending = true;
SetDownloadState(DS_ONQUEUE);
}
}
}
} else { // HIGHID
if (!Connect()) {
return false;
}
}
return true;
}
bool CUpDownClient::Connect()
{
m_hasbeenobfuscatinglately = false;
if (!m_socket->IsOk()) {
// Enable or disable crypting based on our and the remote clients preference
if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){
m_socket->SetConnectionEncryption(true, GetUserHash().GetHash(), false);
} else {
m_socket->SetConnectionEncryption(false, NULL, false);
}
amuleIPV4Address tmp;
tmp.Hostname(GetConnectIP());
tmp.Service(GetUserPort());
AddDebugLogLineN(logClient, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort()));
m_socket->Connect(tmp, false);
// We should send hello packets AFTER connecting!
// so I moved it to OnConnect
return true;
} else {
return false;
}
}
void CUpDownClient::ConnectionEstablished()
{
/* Kry - First thing, check if this client was just used to retrieve
info. That's some debug thing for myself... check connection_reason
definition */
m_hasbeenobfuscatinglately = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating());
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason % GetClientFullInfo());
connection_reason.Clear(); // So we don't re-print on destructor.
Safe_Delete();
return;
}
#endif
// Check if we should use this client to retrieve our public IP
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) {
SendPublicIPRequest();
}
// was this a direct callback?
if (m_dwDirectCallbackTimeout != 0){
theApp->clientlist->RemoveDirectCallback(this);
m_dwDirectCallbackTimeout = 0;
AddDebugLogLineN(logClient, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
}
switch (GetKadState()) {
case KS_CONNECTING_FWCHECK:
SetKadState(KS_CONNECTED_FWCHECK);
break;
case KS_CONNECTING_BUDDY:
case KS_INCOMING_BUDDY:
SetKadState(KS_CONNECTED_BUDDY);
break;
case KS_CONNECTING_FWCHECK_UDP:
SetKadState(KS_FWCHECK_UDP);
SendFirewallCheckUDPRequest();
break;
default:
break;
}
// ok we have a connection, lets see if we want anything from this client
if (GetChatState() == MS_CONNECTING) {
SetChatState( MS_CHATTING );
}
if (GetChatState() == MS_CHATTING) {
bool result = true;
if (!m_pendingMessage.IsEmpty()) {
result = SendChatMessage(m_pendingMessage);
}
Notify_ChatConnResult(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage);
m_pendingMessage.Clear();
}
switch(GetDownloadState()) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_WAITCALLBACKKAD:
m_bReaskPending = false;
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
if (m_bReaskPending){
m_bReaskPending = false;
if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) {
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
}
switch(GetUploadState()){
case US_CONNECTING:
case US_WAITCALLBACK:
if (theApp->uploadqueue->IsDownloading(this)) {
SetUploadState(US_UPLOADING);
CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT);
theStats::AddUpOverheadFileRequest(packet->GetPacketSize());
SendPacket(packet,true);
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
}
}
if (m_iFileListRequested == 1) {
CPacket* packet = new CPacket(m_fSharedDirectories ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (m_fSharedDirectories) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
}
#endif
}
while (!m_WaitingPackets_list.empty()) {
CPacket* packet = m_WaitingPackets_list.front();
m_WaitingPackets_list.pop_front();
SendPacket(packet);
}
}
int CUpDownClient::GetHashType() const
{
if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) {
return SO_OLDEMULE;
}
if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) {
return SO_EMULE;
}
if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) {
return SO_MLDONKEY;
}
return SO_UNKNOWN;
}
void CUpDownClient::SetSocket(CClientTCPSocket* socket)
{
#ifdef __DEBUG__
if (m_socket == NULL && socket != NULL) {
theStats::SocketAssignedToClient();
} else if (m_socket != NULL && socket == NULL) {
theStats::SocketUnassignedFromClient();
}
#endif
m_socket = socket;
}
void CUpDownClient::ReGetClientSoft()
{
if (m_Username.IsEmpty()) {
m_clientSoft=SO_UNKNOWN;
m_clientVerString = m_clientSoftString = m_clientVersionString = m_fullClientVerString = _("Unknown");
UpdateStats();
return;
}
int iHashType = GetHashType();
wxString clientModString;
if (iHashType == SO_EMULE) {
m_clientSoft = m_byCompatibleClient;
m_clientSoftString = GetSoftName(m_clientSoft);
// Special issues:
if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) {
m_clientSoftString = GetClientModString();
}
// Isn't xMule annoying?
if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
m_clientSoftString += CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
}
if ((m_clientSoft == SO_EMULE) &&
(
wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
|| GetUserName().Find(wxT("xmule.")) != -1
)
) {
// FAKE eMule -a newer xMule faking is ident.
m_clientSoft = SO_LXMULE;
if (GetClientModString().IsEmpty() == false) {
m_clientSoftString = GetClientModString() + _(" (Fake eMule)");
} else {
m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
}
}
// Now, what if we don't know this SO_ID?
if (m_clientSoftString.IsEmpty()) {
if(m_bIsML) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (m_bIsHybrid) {
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (m_byCompatibleClient != 0) {
m_clientSoft = SO_COMPAT_UNK;
#ifdef __DEBUG__
if (
// Exceptions:
(m_byCompatibleClient != 0xf0) // Chinese leech mod
&& (1==1) // Your ad here
) {
AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient);
}
#endif
m_clientSoftString = CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft) % m_byCompatibleClient;
} else {
// If we step here, it might mean 2 things:
// a eMule
// a Compat Client that has sent no MuleInfo packet yet.
m_clientSoft = SO_EMULE;
m_clientSoftString = wxT("eMule");
}
}
if (m_byEmuleVersion == 0) {
m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0);
} else if (m_byEmuleVersion != 0x99) {
uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f);
m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0);
switch (m_clientSoft) {
case SO_AMULE:
m_clientVerString = CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion;
break;
case SO_LPHANT:
m_clientVerString = wxT("< v0.05");
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
break;
}
} else {
uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f;
uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f;
uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07;
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
switch (m_clientSoft) {
case SO_AMULE:
case SO_LXMULE:
case SO_HYDRANODE:
case SO_MLDONKEY:
case SO_NEW_MLDONKEY:
case SO_NEW2_MLDONKEY:
// Kry - xMule started sending correct version tags on 1.9.1b.
// It only took them 4 months, and being told by me and the
// eMule+ developers, so I think they're slowly getting smarter.
// They are based on our implementation, so we use the same format
// for the version string.
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
break;
case SO_LPHANT:
m_clientVerString = CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion-1) % nClientMinVersion % ('a' + nClientUpVersion);
break;
case SO_EMULEPLUS:
m_clientVerString = CFormat(wxT("v%u")) % nClientMajVersion;
if(nClientMinVersion != 0) {
m_clientVerString += CFormat(wxT(".%u")) % nClientMinVersion;
}
if(nClientUpVersion != 0) {
m_clientVerString += CFormat(wxT("%c")) % ('a' + nClientUpVersion - 1);
}
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v%u.%u%c")) % nClientMajVersion % nClientMinVersion % ('a' + nClientUpVersion);
break;
}
}
} else if (m_bIsHybrid) {
// seen:
// 105010 50.10
// 10501 50.1
// 1051 51.0
// 501 50.1
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMajVersion;
uint32 nClientMinVersion;
uint32 nClientUpVersion;
if (m_nClientVersion > 100000) {
uint32 uMaj = m_nClientVersion/100000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100;
nClientUpVersion = m_nClientVersion % 100;
}
else if (m_nClientVersion > 10000) {
uint32 uMaj = m_nClientVersion/10000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10;
nClientUpVersion = m_nClientVersion % 10;
}
else if (m_nClientVersion > 1000) {
uint32 uMaj = m_nClientVersion/1000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = m_nClientVersion - uMaj*1000;
nClientUpVersion = 0;
}
else if (m_nClientVersion > 100) {
uint32 uMin = m_nClientVersion/10;
nClientMajVersion = 0;
nClientMinVersion = uMin;
nClientUpVersion = m_nClientVersion - uMin*10;
}
else{
nClientMajVersion = 0;
nClientMinVersion = m_nClientVersion;
nClientUpVersion = 0;
}
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
if (nClientUpVersion) {
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
} else {
m_clientVerString = CFormat(wxT("v%u.%u")) % nClientMajVersion % nClientMinVersion;
}
} else if (m_bIsML || (iHashType == SO_MLDONKEY)) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else if (iHashType == SO_OLDEMULE) {
m_clientSoft = SO_OLDEMULE;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else {
m_clientSoft = SO_EDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
m_nClientVersion *= 10;
m_clientVerString = CFormat(wxT("v%u.%u")) % (m_nClientVersion / 100000) % ((m_nClientVersion / 1000) % 100);
}
m_clientVersionString = m_clientVerString;
if (!clientModString.IsEmpty()) {
m_clientVerString += wxT(" - ") + clientModString;
}
m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString;
UpdateStats();
}
void CUpDownClient::RequestSharedFileList()
{
if (m_iFileListRequested == 0) {
AddDebugLogLineN( logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
m_iFileListRequested = 1;
TryToConnect(true);
} else {
AddDebugLogLineN( logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
}
}
void CUpDownClient::ProcessSharedFileList(const byte* pachPacket, uint32 nSize, wxString& pszDirectory)
{
if (m_iFileListRequested > 0) {
m_iFileListRequested--;
theApp->searchlist->ProcessSharedFileList(pachPacket, nSize, this, NULL, pszDirectory);
}
}
void CUpDownClient::ResetFileStatusInfo()
{
m_nPartCount = 0;
if ( m_reqfile ) {
m_reqfile->UpdatePartsFrequency( this, false );
}
m_downPartStatus.clear();
m_clientFilename.Clear();
m_bCompleteSource = false;
m_dwLastAskedTime = 0;
m_iRating = 0;
m_strComment.Clear();
if (m_pReqFileAICHHash != NULL) {
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
}
}
wxString CUpDownClient::GetUploadFileInfo()
{
// build info text and display it
wxString sRet;
sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
if (m_reqfile) {
sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName();
sRet += CFormat(
wxPLURAL("Filestats for this session: Accepted %d of %d request, %s transferred\n", "Filestats for this session: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetRequests())
) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred());
sRet += CFormat(
wxPLURAL("Filestats for all sessions: Accepted %d of %d request, %s transferred\n", "Filestats for all sessions: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetAllTimeRequests())
) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.GetAllTimeTransferred());
} else {
sRet += _("Requested unknown file");
}
return sRet;
}
// sends a packet, if needed it will establish a connection before
// options used: ignore max connections, control packet, delete packet
// !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
bool CUpDownClient::SafeSendPacket(CPacket* packet)
{
if (IsConnected()) {
SendPacket(packet, true);
return true;
} else {
m_WaitingPackets_list.push_back(packet);
return TryToConnect(true);
}
}
void CUpDownClient::SendPublicKeyPacket(){
// send our public key to the client who requested it
if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
CMemFile data;
data.WriteUInt8(theApp->clientcredits->GetPubKeyLen());
data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen());
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_SIGNATURENEEDED;
}
void CUpDownClient::SendSignaturePacket(){
// signate the public key of this client and send it
if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable()) {
return;
}
if (credits->GetSecIDKeyLen() == 0) {
return; // We don't have his public key yet, will be back here later
}
// do we have a challenge value received (actually we should if we are in this function)
if (credits->m_dwCryptRndChallengeFrom == 0){
AddDebugLogLineN( logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
return;
}
// v2
// we will use v1 as default, except if only v2 is supported
bool bUseV2;
if ( (m_bySupportSecIdent&1) == 1 )
bUseV2 = false;
else
bUseV2 = true;
uint8 byChaIPKind = 0;
uint32 ChallengeIP = 0;
if (bUseV2){
if (::IsLowID(theApp->GetED2KID())) {
// we cannot do not know for sure our public ip, so use the remote clients one
ChallengeIP = GetIP();
byChaIPKind = CRYPT_CIP_REMOTECLIENT;
} else {
ChallengeIP = theApp->GetED2KID();
byChaIPKind = CRYPT_CIP_LOCALCLIENT;
}
}
//end v2
byte achBuffer[250];
uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind );
if (siglen == 0){
wxFAIL;
return;
}
CMemFile data;
data.WriteUInt8(siglen);
data.Write(achBuffer, siglen);
if (bUseV2) {
data.WriteUInt8(byChaIPKind);
}
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_ALLREQUESTSSEND;
}
void CUpDownClient::ProcessPublicKeyPacket(const byte* pachPacket, uint32 nSize)
{
theApp->clientlist->AddTrackClient(this);
if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1
|| nSize == 0 || nSize > 250){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// the function will handle everything (mulitple key etc)
if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){
// if this client wants a signature, now we can send him one
if (m_SecureIdentState == IS_SIGNATURENEEDED){
SendSignaturePacket();
}
else if (m_SecureIdentState == IS_KEYANDSIGNEEDED) {
// something is wrong
AddDebugLogLineN( logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") );
}
} else {
AddDebugLogLineN( logClient, wxT("Failed to use new received public key") );
}
}
void CUpDownClient::ProcessSignaturePacket(const byte* pachPacket, uint32 nSize)
{
// here we spread the good guys from the bad ones ;)
if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){
wxFAIL;
return;
}
uint8 byChaIPKind;
if (pachPacket[0] == nSize-1)
byChaIPKind = 0;
else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0) //v2
byChaIPKind = pachPacket[nSize-1];
else{
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
if (m_dwLastSignatureIP == GetIP()){
AddDebugLogLineN( logClient, wxT("received multiple signatures from one client") );
return;
}
// also make sure this client has a public key
if (credits->GetSecIDKeyLen() == 0){
AddDebugLogLineN( logClient, wxT("received signature for client without public key") );
return;
}
// and one more check: did we ask for a signature and sent a challange packet?
if (credits->m_dwCryptRndChallengeFor == 0){
AddDebugLogLineN( logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
return;
}
// cppcheck-suppress duplicateBranch
if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ) {
// result is saved in function above
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
} else {
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
}
m_dwLastSignatureIP = GetIP();
}
void CUpDownClient::SendSecIdentStatePacket(){
// check if we need public key and signature
if (credits){
uint8 nValue = 0;
if (theApp->CryptoAvailable()){
if (credits->GetSecIDKeyLen() == 0) {
nValue = IS_KEYANDSIGNEEDED;
} else if (m_dwLastSignatureIP != GetIP()) {
nValue = IS_SIGNATURENEEDED;
}
}
if (nValue == 0){
AddDebugLogLineN( logClient, wxT("Not sending SecIdentState Packet, because State is Zero") );
return;
}
// crypt: send random data to sign
uint32 dwRandom = rand()+1;
credits->m_dwCryptRndChallengeFor = dwRandom;
CMemFile data;
data.WriteUInt8(nValue);
data.WriteUInt32(dwRandom);
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
SendPacket(packet,true,true);
} else {
wxFAIL;
}
}
void CUpDownClient::ProcessSecIdentStatePacket(const byte* pachPacket, uint32 nSize)
{
if ( nSize != 5 ) {
return;
}
if ( !credits ) {
wxASSERT( credits );
return;
}
CMemFile data(pachPacket,nSize);
switch ( data.ReadUInt8() ) {
case 0:
m_SecureIdentState = IS_UNAVAILABLE;
break;
case 1:
m_SecureIdentState = IS_SIGNATURENEEDED;
break;
case 2:
m_SecureIdentState = IS_KEYANDSIGNEEDED;
break;
default:
return;
}
credits->m_dwCryptRndChallengeFrom = data.ReadUInt32();
}
void CUpDownClient::InfoPacketsReceived()
{
// indicates that both Information Packets has been received
// needed for actions, which process data from both packets
wxASSERT ( m_byInfopacketsReceived == IP_BOTH );
m_byInfopacketsReceived = IP_NONE;
if (m_bySupportSecIdent){
SendSecIdentStatePacket();
}
}
bool CUpDownClient::CheckHandshakeFinished() const
{
if (m_bHelloAnswerPending) {
// this triggers way too often.. need more time to look at this -> only create a warning
// The reason for this is that 2 clients are connecting to each other at the same time..
AddDebugLogLineN( logClient, wxT("Handshake not finished while processing packet.") );
return false;
}
return true;
}
#ifdef __DEBUG__
wxString CUpDownClient::GetClientFullInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% GetFullIP()
% GetUserPort()
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
#endif
wxString CUpDownClient::GetClientShortInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("'%s' (%s %s %s)") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
void CUpDownClient::SendPublicIPRequest()
{
if (IsConnected()){
CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP());
SendPacket(packet,true);
m_fNeedOurPublicIP = true;
}
}
void CUpDownClient::ProcessPublicIPAnswer(const byte* pbyData, uint32 uSize)
{
if (uSize != 4) {
throw wxString(wxT("Wrong Packet size on Public IP answer"));
}
uint32 dwIP = PeekUInt32(pbyData);
if (m_fNeedOurPublicIP == true){ // did we?
m_fNeedOurPublicIP = false;
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) {
theApp->SetPublicIP(dwIP);
}
}
}
bool CUpDownClient::IsConnected() const
{
return m_socket && m_socket->IsConnected();
}
bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket)
{
if ( m_socket ) {
m_socket->SendPacket(packet, delpacket, controlpacket );
return true;
} else {
AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
return false;
}
}
float CUpDownClient::SetDownloadLimit(uint32 reducedownload)
{
// lfroen: in daemon it actually can happen
wxASSERT( m_socket );
float kBpsClient = CalculateKBpsDown();
if ( m_socket ) {
if (reducedownload) {
// (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
// which is how often it is called per second.
uint32 limit = (uint32)(reducedownload * kBpsClient * 1024.0 / 100000.0 * CORE_TIMER_PERIOD);
if(limit<1024 && reducedownload >= 200) {
// If we're going up and this download is < 1kB,
// we want it to go up fast. Can be reduced later,
// and it'll probably be in a more fair way with
// other downloads that are faster.
limit +=1024;
} else if(limit == 0) {
// This download is not transferring yet... make it
// 1024 so we don't fill the TCP stack and lose the
// connection.
limit = 1024;
}
m_socket->SetDownloadLimit(limit);
} else {
m_socket->DisableDownloadLimit();
}
} else {
AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient);
}
return kBpsClient;
}
void CUpDownClient::SetUserIDHybrid(uint32 nUserID)
{
theApp->clientlist->UpdateClientID( this, nUserID );
m_nUserIDHybrid = nUserID;
}
void CUpDownClient::SetIP( uint32 val )
{
theApp->clientlist->UpdateClientIP( this, val );
m_dwUserIP = val;
m_nConnectIP = val;
m_FullUserIP = val;
}
void CUpDownClient::SetUserHash(const CMD4Hash& userhash)
{
theApp->clientlist->UpdateClientHash( this, userhash );
m_UserHash = userhash;
ValidateHash();
}
EUtf8Str CUpDownClient::GetUnicodeSupport() const
{
return m_bUnicodeSupport ? utf8strRaw : utf8strNone;
}
void CUpDownClient::SetSpammer(bool bVal)
{
if (bVal) {
Ban();
} else if (IsBanned() && m_fIsSpammer) {
UnBan();
}
m_fIsSpammer = bVal;
}
uint8 CUpDownClient::GetSecureIdentState()
{
if (m_SecureIdentState != IS_UNAVAILABLE) {
if (!SecIdentSupRec) {
// This can be caused by a 0.30x based client which sends the old
// style Hello packet, and the mule info packet, but between them they
// send a secure ident state packet (after a hello but before we have
// the SUI capabilities). This is a misbehaving client, and somehow I
// feel like it should be dropped. But then again, it won't harm to use
// this SUI state if they are reporting no SUI (won't be used) and if
// they report using SUI on the mule info packet, it's ok to use it.
AddDebugLogLineN(logClient, wxT("A client sent secure ident state before telling us the SUI capabilities"));
AddDebugLogLineN(logClient, wxT("Client info: ") + GetClientFullInfo());
AddDebugLogLineN(logClient, wxT("This client won't be disconnected, but it should be. :P"));
}
}
return m_SecureIdentState;
}
bool CUpDownClient::SendChatMessage(const wxString& message)
{
if (GetChatCaptchaState() == CA_CAPTCHARECV) {
m_nChatCaptchaState = CA_SOLUTIONSENT;
} else if (GetChatCaptchaState() == CA_SOLUTIONSENT) {
wxFAIL; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
} else {
m_nChatCaptchaState = CA_ACCEPTING;
}
SetSpammer(false);
IncMessagesSent();
// Already connecting?
if (GetChatState() == MS_CONNECTING) {
// Queue all messages till we're able to send them (or discard them)
if (!m_pendingMessage.IsEmpty()) {
m_pendingMessage += wxT("\n");
} else {
// There must be a message to send
// - except if we got disconnected. No need to assert therefore.
}
m_pendingMessage += message;
return false;
}
if (IsConnected()) {
// If we are already connected when we send the first message,
// we have to update the chat status.
SetChatState(MS_CHATTING);
CMemFile data;
data.WriteString(message, GetUnicodeSupport());
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
SendPacket(packet, true, true);
return true;
} else {
m_pendingMessage = message;
SetChatState(MS_CONNECTING);
// True to ignore "Too Many Connections"
TryToConnect(true);
return false;
}
}
/* Kad stuff */
void CUpDownClient::SetBuddyID(const byte* pucBuddyID)
{
if( pucBuddyID == NULL ){
md4clr(m_achBuddyID);
m_bBuddyIDValid = false;
return;
}
m_bBuddyIDValid = true;
md4cpy(m_achBuddyID, pucBuddyID);
}
// Kad added by me
bool CUpDownClient::SendBuddyPing() {
SetLastBuddyPingPongTime();
CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT);
theStats::AddUpOverheadKad(buddyPing->GetPacketSize());
AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
return SafeSendPacket(buddyPing);
}
/* Statistics */
void CUpDownClient::UpdateStats()
{
if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) {
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
m_lastClientSoft = m_clientSoft;
m_lastClientVersion = m_nClientVersion;
m_lastOSInfo = m_sClientOSInfo;
if (m_clientSoft == SO_UNKNOWN) {
theStats::AddUnknownClient();
} else {
theStats::AddKnownClient(this);
}
}
}
bool CUpDownClient::IsIdentified() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED);
}
bool CUpDownClient::IsBadGuy() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY);
}
bool CUpDownClient::SUIFailed() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED);
}
bool CUpDownClient::SUINeeded() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED);
}
bool CUpDownClient::SUINotSupported() const
{
return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE);
}
uint64 CUpDownClient::GetDownloadedTotal() const
{
return credits ? credits->GetDownloadedTotal() : 0;
}
uint64 CUpDownClient::GetUploadedTotal() const
{
return credits ? credits->GetUploadedTotal() : 0;
}
double CUpDownClient::GetScoreRatio() const
{
return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
}
const wxString CUpDownClient::GetServerName() const
{
wxString ret;
wxString srvaddr = Uint32toStringIP(GetServerIP());
CServer* cserver = theApp->serverlist->GetServerByAddress(
srvaddr, GetServerPort());
if (cserver) {
ret = cserver->GetListName();
} else {
ret = _("Unknown");
}
return ret;
}
bool CUpDownClient::ShouldReceiveCryptUDPPackets() const
{
return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp->GetPublicIP() != 0
&& HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) );
}
#ifdef AMULE_DAEMON
void CUpDownClient::ProcessCaptchaRequest(CMemFile* WXUNUSED(data)) {}
void CUpDownClient::ProcessCaptchaReqRes(uint8 WXUNUSED(nStatus)) {}
void CUpDownClient::ProcessChatMessage(const wxString WXUNUSED(message)) {}
#else
void CUpDownClient::ProcessCaptchaRequest(CMemFile* data)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
// received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
if (GetChatCaptchaState() == CA_ACCEPTING && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
// read tags (for future use)
uint8 nTagCount = data->ReadUInt8();
if (nTagCount) {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount);
// and ignore them for now
for (uint32 i = 0; i < nTagCount; i++) {
CTag tag(*data, true);
}
}
// sanitize checks - we want a small captcha not a wallpaper
uint32 nSize = (uint32)(data->GetLength() - data->GetPosition());
if ( nSize > 128 && nSize < 4096 ) {
uint64 pos = data->GetPosition();
wxMemoryInputStream memstr(data->GetRawBuffer() + pos, nSize);
wxImage imgCaptcha(memstr, wxBITMAP_TYPE_BMP);
if (imgCaptcha.IsOk() && imgCaptcha.GetHeight() > 10 && imgCaptcha.GetHeight() < 50
&& imgCaptcha.GetWidth() > 10 && imgCaptcha.GetWidth() < 150 ) {
m_nChatCaptchaState = CA_CAPTCHARECV;
CCaptchaDialog * dialog = new CCaptchaDialog(theApp->amuledlg, imgCaptcha, id);
dialog->Show();
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
if (GetChatCaptchaState() == CA_SOLUTIONSENT && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
wxASSERT( nStatus < 3 );
m_nChatCaptchaState = CA_NONE;
theApp->amuledlg->m_chatwnd->ShowCaptchaResult(id, nStatus == 0);
} else {
m_nChatCaptchaState = CA_NONE;
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::ProcessChatMessage(wxString message)
{
if (IsMessageFiltered(message)) {
AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
return;
}
// advanced spamfilter check
if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) {
// captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
// first check if we need to send a captcha request to this client
if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED) {
// we have never sent a message to this client, and no message from him has ever passed our filters
if (GetChatCaptchaState() != CA_CHALLENGESENT) {
// we also aren't currently expecting a captcha response
if (m_fSupportsCaptcha) {
// and he supports captcha, so send him one and store the message (without showing for now)
if (m_cCaptchasSent < 3) { // no more than 3 tries
m_strCaptchaPendingMsg = message;
wxMemoryOutputStream memstr;
memstr.PutC(0); // no tags, for future use
CCaptchaGenerator captcha(4);
if (captcha.WriteCaptchaImage(memstr)){
m_strCaptchaChallenge = captcha.GetCaptchaText();
m_nChatCaptchaState = CA_CHALLENGESENT;
m_cCaptchasSent++;
CMemFile fileAnswer((byte*) memstr.GetOutputStreamBuffer()->GetBufferStart(), memstr.GetLength());
CPacket* packet = new CPacket(fileAnswer, OP_EMULEPROT, OP_CHATCAPTCHAREQ);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge % packet->GetPacketSize());
SafeSendPacket(packet);
} else {
wxFAIL;
}
}
} else {
// client doesn't support captchas, but we require them, tell him that it's not going to work out
// with an answer message (will not be shown and doesn't count as sent message)
if (m_cCaptchasSent < 1) { // don't send this notifier more than once
m_cCaptchasSent++;
// always sent in english
SendChatMessage(wxT("In order to avoid spam messages, this user requires you to solve a captcha before you can send a message to him. However your client does not supports captchas, so you will not be able to chat with this user."));
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
}
}
return;
} else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
// this message must be the answer to the captcha request we sent him, let's verify
wxASSERT( !m_strCaptchaChallenge.IsEmpty() );
if (m_strCaptchaChallenge.CmpNoCase(message.Trim().Right(std::min(message.Length(), m_strCaptchaChallenge.Length()))) == 0) {
// allright
AddDebugLogLineN(logClient, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_CAPTCHASOLVED; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
// replace captchaanswer with withheld message and show it
message = m_strCaptchaPendingMsg;
m_cCaptchasSent = 0;
m_strCaptchaChallenge.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = 0; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
} else { // wrong, cleanup and ignore
AddDebugLogLineN(logClient, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_NONE;
m_strCaptchaChallenge.Clear();
m_strCaptchaPendingMsg.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = (m_cCaptchasSent < 3) ? 1 : 2; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
return; // nothing more todo
}
}
}
}
if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
bool bIsSpam = false;
if (m_fIsSpammer) {
bIsSpam = true;
} else {
// first fixed criteria: If a client sends me an URL in his first message before I respond to him
// there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
if (GetMessagesSent() == 0) {
static wxArrayString urlindicators(wxStringTokenize(wxT("http:|www.|.de |.net |.com |.org |.to |.tk |.cc |.fr |ftp:|ed2k:|https:|ftp.|.info|.biz|.uk|.eu|.es|.tv|.cn|.tw|.ws|.nu|.jp"), wxT("|")));
for (size_t pos = urlindicators.GetCount(); pos--;) {
if (message.Find(urlindicators[pos]) != wxNOT_FOUND) {
bIsSpam = true;
break;
}
}
// second fixed criteria: he sent me 4 or more messages and I didn't answer him once
if (GetMessagesReceived() > 3) {
bIsSpam = true;
}
}
}
if (bIsSpam) {
AddDebugLogLineN(logClient, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
SetSpammer(true);
theApp->amuledlg->m_chatwnd->EndSession(GUI_ID(GetIP(),GetUserPort()));
return;
}
}
wxString logMsg = CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
if(thePrefs::ShowMessagesInLog()) {
logMsg += wxT(": ") + message;
}
AddLogLineC(logMsg);
IncMessagesReceived();
Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message);
}
bool CUpDownClient::IsMessageFiltered(const wxString& message)
{
bool filtered = false;
// If we're chatting to the guy, we don't want to filter!
if (GetChatState() != MS_CHATTING) {
if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
filtered = true;
} else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
filtered = true;
} else if (thePrefs::MustFilterMessages()) {
filtered = thePrefs::IsMessageFiltered(message);
}
}
if (filtered) {
SetSpammer(true);
}
return filtered;
}
#endif
void CUpDownClient::SendSharedDirectories()
{
// This list will contain all (unique) folders.
PathList foldersToSend;
// The shared folders
const unsigned folderCount = theApp->glob_prefs->shareddir_list.size();
for (unsigned i = 0; i < folderCount; ++i) {
foldersToSend.push_back(theApp->glob_prefs->shareddir_list[i]);
}
// ... the categories folders ... (category 0 -> incoming)
for (unsigned i = 0; i < theApp->glob_prefs->GetCatCount(); ++i) {
foldersToSend.push_back(theApp->glob_prefs->GetCategory(i)->path);
}
// Strip duplicates
foldersToSend.sort();
foldersToSend.unique();
// Build packet
CMemFile tempfile(80);
tempfile.WriteUInt32(foldersToSend.size() + 1); // + 1 for the incomplete files
PathList::iterator it = foldersToSend.begin();
for (; it != foldersToSend.end(); ++it) {
// Note: the public shared name contains the 'raw' path, so we can recognize it again.
// the 'raw' path is determined using CPath::GetRaw()
tempfile.WriteString( theApp->sharedfiles->GetPublicSharedDirName(*it), GetUnicodeSupport() );
}
// ... and the Magic thing from the eDonkey Hybrids...
tempfile.WriteString(OP_INCOMPLETE_SHARED_FILES, GetUnicodeSupport());
// Send the packet.
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDDIRSANS);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRSANS to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::SendSharedFilesOfDirectory(const wxString& strReqDir)
{
CKnownFilePtrList list;
if (strReqDir == OP_INCOMPLETE_SHARED_FILES) {
// get all shared files from download queue
int iQueuedFiles = theApp->downloadqueue->GetFileCount();
for (int i = 0; i < iQueuedFiles; i++) {
CPartFile* pFile = theApp->downloadqueue->GetFileByIndex(i);
if (pFile == NULL || pFile->GetStatus(true) != PS_READY) {
continue;
}
list.push_back(pFile);
}
} else {
// get all shared files for the requested directory
const CPath *sharedDir = theApp->sharedfiles->GetDirForPublicSharedDirName(strReqDir);
if (sharedDir) {
theApp->sharedfiles->GetSharedFilesByDirectory(sharedDir->GetRaw(), list);
} else {
AddLogLineC(CFormat(_("User %s (%u) requested sharedfiles-list for not existing directory '%s' -> Ignored")) % GetUserName() % GetUserIDHybrid() % strReqDir);
}
}
CMemFile tempfile(80);
tempfile.WriteString(strReqDir, GetUnicodeSupport());
tempfile.WriteUInt32(list.size());
while (!list.empty()) {
if (!list.front()->IsLargeFile() || SupportsLargeFiles()) {
list.front()->CreateOfferedFilePacket(&tempfile, NULL, this);
}
list.pop_front();
}
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDFILESDIRANS);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILESDIRANS to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::SendFirewallCheckUDPRequest()
{
wxASSERT(GetKadState() == KS_FWCHECK_UDP);
if (!Kademlia::CKademlia::IsRunning()) {
SetKadState(KS_NONE);
return;
} else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled
SetKadState(KS_NONE);
return;
}
CMemFile data;
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ);
theStats::AddUpOverheadKad(packet->GetPacketSize());
SafeSendPacket(packet);
}
void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile* data)
{
if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) {
//DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
return;
}
// first search if we know this IP already, if so the result might be biased and we need tell the requester
bool errorAlreadyKnown = false;
if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) {
errorAlreadyKnown = true;
} else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL) {
errorAlreadyKnown = true;
}
uint16_t remoteInternPort = data->ReadUInt16();
uint16_t remoteExternPort = data->ReadUInt16();
uint32_t senderKey = data->ReadUInt32();
if (remoteInternPort == 0) {
//DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
return;
}
// if (senderKey == 0)
// DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
CMemFile testPacket1;
testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket1.WriteUInt16(remoteInternPort);
DebugSend(Kad2FirewallUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
// if the client has a router with PAT (and therefore a different extern port than intern), test this port too
if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) {
CMemFile testPacket2;
testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket2.WriteUInt16(remoteExternPort);
DebugSend(Kad2FirewalledUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
}
//DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
}
void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback)
{
SetCryptLayerSupport((options & 0x01) != 0 && encryption);
SetCryptLayerRequest((options & 0x02) != 0 && encryption);
SetCryptLayerRequires((options & 0x04) != 0 && encryption);
SetDirectUDPCallbackSupport((options & 0x08) != 0 && callback);
}
#ifdef DEBUG_ZOMBIE_CLIENTS
void CUpDownClient::Unlink(const wxString& from)
{
std::multiset<wxString>::iterator it = m_linkedFrom.find(from);
if (it != m_linkedFrom.end()) {
m_linkedFrom.erase(it);
}
m_linked--;
if (!m_linked) {
if (m_linkedDebug) {
AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this);
}
delete this;
}
}
#else
void CUpDownClient::Unlink()
{
m_linked--;
if (!m_linked) {
delete this;
}
}
#endif
// File_checked_for_headers
| hlechner/hl-test | amule/src/BaseClient.cpp | C++ | gpl-3.0 | 96,820 |
/*
* An Abstract communicator interface which implements listeners.
*/
/*
Copywrite 2013 Will Winder
This file is part of Universal Gcode Sender (UGS).
UGS 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.
UGS 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 UGS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.willwinder.universalgcodesender;
import com.willwinder.universalgcodesender.i18n.Localization;
import com.willwinder.universalgcodesender.listeners.SerialCommunicatorListener;
import com.willwinder.universalgcodesender.types.GcodeCommand;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author wwinder
*/
public abstract class AbstractCommunicator {
public static String DEFAULT_TERMINATOR = "\r\n";
private String lineTerminator;
protected Connection conn;
// Callback interfaces
ArrayList<SerialCommunicatorListener> commandSentListeners;
ArrayList<SerialCommunicatorListener> commandCompleteListeners;
ArrayList<SerialCommunicatorListener> commConsoleListeners;
ArrayList<SerialCommunicatorListener> commVerboseConsoleListeners;
ArrayList<SerialCommunicatorListener> commRawResponseListener;
private final ArrayList<Connection> connections;
public AbstractCommunicator() {
this.lineTerminator = DEFAULT_TERMINATOR;
this.commandSentListeners = new ArrayList<SerialCommunicatorListener>();
this.commandCompleteListeners = new ArrayList<SerialCommunicatorListener>();
this.commConsoleListeners = new ArrayList<SerialCommunicatorListener>();
this.commVerboseConsoleListeners = new ArrayList<SerialCommunicatorListener>();
this.commRawResponseListener = new ArrayList<SerialCommunicatorListener>();
//instanciate all known connection drivers
//TODO: Scan the classpath for classes extending Connection,
// and instantiate them dynamically.
this.connections = new ArrayList<Connection>();
this.addConnectionType(new SerialConnection());
}
final public void addConnectionType(Connection conn) {
this.connections.add(conn);
}
/*********************/
/* Serial Layer API. */
/*********************/
abstract public void setSingleStepMode(boolean enable);
abstract public boolean getSingleStepMode();
abstract public void queueStringForComm(final String input);
abstract public void sendByteImmediately(byte b) throws IOException;
abstract public boolean areActiveCommands();
abstract public void streamCommands();
abstract public void pauseSend();
abstract public void resumeSend();
abstract public void cancelSend();
abstract public void softReset();
abstract public void responseMessage(String response);
//do common operations (related to the connection, that is shared by all communicators)
protected boolean openCommPort(String name, int baud) throws Exception {
//choose port
for(Connection candidate: connections) {
if(candidate.supports(name)) {
conn = candidate;
conn.setCommunicator(this);
break;
}
}
if(conn==null) {
throw new Exception(Localization.getString("communicator.exception.port") + ": "+name);
}
//open it
conn.openPort(name, baud);
return true;
}
//do common things (related to the connection, that is shared by all communicators)
protected void closeCommPort() {
conn.closePort();
}
/** Getters & Setters. */
void setLineTerminator(String terminator) {
if (terminator == null || terminator.length() < 1) {
this.lineTerminator = DEFAULT_TERMINATOR;
} else {
this.lineTerminator = terminator;
}
}
String getLineTerminator() {
return this.lineTerminator;
}
/* ****************** */
/** Listener helpers. */
/* ****************** */
void setListenAll(SerialCommunicatorListener scl) {
this.addCommandSentListener(scl);
this.addCommandCompleteListener(scl);
this.addCommConsoleListener(scl);
this.addCommVerboseConsoleListener(scl);
this.addCommRawResponseListener(scl);
}
void addCommandSentListener(SerialCommunicatorListener scl) {
this.commandSentListeners.add(scl);
}
void addCommandCompleteListener(SerialCommunicatorListener scl) {
this.commandCompleteListeners.add(scl);
}
void addCommConsoleListener(SerialCommunicatorListener scl) {
this.commConsoleListeners.add(scl);
}
void addCommVerboseConsoleListener(SerialCommunicatorListener scl) {
this.commVerboseConsoleListeners.add(scl);
}
void addCommRawResponseListener(SerialCommunicatorListener scl) {
this.commRawResponseListener.add(scl);
}
// Helper for the console listener.
protected void sendMessageToConsoleListener(String msg) {
this.sendMessageToConsoleListener(msg, false);
}
protected void sendMessageToConsoleListener(String msg, boolean verbose) {
// Exit early if there are no listeners.
if (this.commConsoleListeners == null) {
return;
}
int verbosity;
if (!verbose) {
verbosity = CONSOLE_MESSAGE;
}
else {
verbosity = VERBOSE_CONSOLE_MESSAGE;
}
dispatchListenerEvents(verbosity, this.commConsoleListeners, msg);
}
// Serial Communicator Listener Events
protected static final int COMMAND_SENT = 1;
protected static final int COMMAND_COMPLETE = 2;
protected static final int RAW_RESPONSE = 3;
protected static final int CONSOLE_MESSAGE = 4;
protected static final int VERBOSE_CONSOLE_MESSAGE = 5;
/**
* A bunch of methods to dispatch listener events with various arguments.
*/
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, String message) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, message, null);
}
}
}
static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, GcodeCommand command) {
if (sclList != null) {
for (SerialCommunicatorListener s : sclList) {
sendEventToListener(event, s, null, command);
}
}
}
static protected void sendEventToListener(int event, SerialCommunicatorListener scl,
String string, GcodeCommand command) {
switch(event) {
case COMMAND_SENT:
scl.commandSent(string);
break;
case CONSOLE_MESSAGE:
scl.messageForConsole(string);
break;
case VERBOSE_CONSOLE_MESSAGE:
scl.verboseMessageForConsole(string);
break;
case RAW_RESPONSE:
scl.rawResponseListener(string);
default:
}
}
}
| shapeoko/Universal-G-Code-Sender | src/com/willwinder/universalgcodesender/AbstractCommunicator.java | Java | gpl-3.0 | 7,779 |
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ManualLink from 'browser-components/ManualLink'
const title = 'FOREACH'
const subtitle = 'Operate on a collection'
const category = 'cypherHelp'
const content = (
<>
<p>
The <code>FOREACH</code> clause is used to update data within a collection
whether components of a path, or result of aggregation.
</p>
<div className="links">
<div className="link">
<p className="title">Reference</p>
<p className="content">
<ManualLink chapter="cypher-manual" page="/clauses/foreach/">
FOREACH
</ManualLink>{' '}
manual page
</p>
</div>
<div className="link">
<p className="title">Related</p>
<p className="content">
<a help-topic="create">:help CREATE</a>
<a help-topic="delete">:help DELETE</a>
<a help-topic="set">:help SET</a>
<a help-topic="cypher">:help Cypher</a>
</p>
</div>
</div>
<section className="example">
<figure className="runnable">
<pre>
{`MATCH p = (ups)<-[DEPENDS_ON]-(device) WHERE ups.id='EPS-7001'
FOREACH (n IN nodes(p) | SET n.available = FALSE )`}
</pre>
<figcaption>
Mark all devices plugged into a failed UPS as unavailable.
</figcaption>
</figure>
</section>
</>
)
export default { title, subtitle, category, content }
| neo4j/neo4j-browser | src/browser/documentation/help/foreach.tsx | TypeScript | gpl-3.0 | 2,176 |
/*
* Unplayer
* Copyright (C) 2015-2019 Alexey Rochev <equeim@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 "queuemodel.h"
#include "queue.h"
namespace unplayer
{
QVariant QueueModel::data(const QModelIndex& index, int role) const
{
if (!mQueue || !index.isValid()) {
return QVariant();
}
const QueueTrack* track = mQueue->tracks()[static_cast<size_t>(index.row())].get();
switch (role) {
case UrlRole:
return track->url;
case IsLocalFileRole:
return track->url.isLocalFile();
case FilePathRole:
return track->url.path();
case TitleRole:
return track->title;
case ArtistRole:
return track->artist;
case DisplayedArtistRole:
return track->artist;
case AlbumRole:
return track->album;
case DisplayedAlbumRole:
return track->album;
case DurationRole:
return track->duration;
default:
return QVariant();
}
}
int QueueModel::rowCount(const QModelIndex&) const
{
return mQueue ? static_cast<int>(mQueue->tracks().size()) : 0;
}
Queue* QueueModel::queue() const
{
return mQueue;
}
void QueueModel::setQueue(Queue* queue)
{
if (queue == mQueue || !queue) {
return;
}
mQueue = queue;
QObject::connect(mQueue, &Queue::tracksAboutToBeAdded, this, [=](int count) {
const int first = rowCount();
beginInsertRows(QModelIndex(), first, first + count - 1);
});
QObject::connect(mQueue, &Queue::tracksAdded, this, [=]() {
endInsertRows();
});
QObject::connect(mQueue, &Queue::trackAboutToBeRemoved, this, [=](int index) {
beginRemoveRows(QModelIndex(), index, index);
});
QObject::connect(mQueue, &Queue::trackRemoved, this, [=]() {
endRemoveRows();
});
QObject::connect(mQueue, &Queue::aboutToBeCleared, this, [=]() {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
});
QObject::connect(mQueue, &Queue::cleared, this, [=]() {
endRemoveRows();
});
}
QHash<int, QByteArray> QueueModel::roleNames() const
{
return {{UrlRole, "url"},
{IsLocalFileRole, "isLocalFile"},
{FilePathRole, "filePath"},
{TitleRole, "title"},
{ArtistRole, "artist"},
{DisplayedArtistRole, "displayedArtist"},
{AlbumRole, "album"},
{DisplayedAlbumRole, "displayedAlbum"},
{DurationRole, "duration"}};
}
}
| equeim/unplayer | src/queuemodel.cpp | C++ | gpl-3.0 | 3,387 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quickstep;
import static com.android.launcher3.FastBitmapDrawable.newIcon;
import static com.android.launcher3.uioverrides.QuickstepLauncher.GO_LOW_RAM_RECENTS_ENABLED;
import static com.android.launcher3.util.Executors.MAIN_EXECUTOR;
import android.app.ActivityManager.TaskDescription;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.util.SparseArray;
import android.view.accessibility.AccessibilityManager;
import androidx.annotation.WorkerThread;
import com.android.launcher3.FastBitmapDrawable;
import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.icons.BitmapInfo;
import com.android.launcher3.icons.IconProvider;
import com.android.launcher3.icons.LauncherIcons;
import com.android.launcher3.icons.cache.HandlerRunnable;
import com.android.launcher3.util.Preconditions;
import com.android.quickstep.util.TaskKeyLruCache;
import com.android.systemui.shared.recents.model.Task;
import com.android.systemui.shared.recents.model.Task.TaskKey;
import com.android.systemui.shared.system.ActivityManagerWrapper;
import com.android.systemui.shared.system.PackageManagerWrapper;
import com.android.systemui.shared.system.TaskDescriptionCompat;
import java.util.function.Consumer;
/**
* Manages the caching of task icons and related data.
*/
public class TaskIconCache {
private final Handler mBackgroundHandler;
private final AccessibilityManager mAccessibilityManager;
private final Context mContext;
private final TaskKeyLruCache<TaskCacheEntry> mIconCache;
private final SparseArray<BitmapInfo> mDefaultIcons = new SparseArray<>();
private final IconProvider mIconProvider;
public TaskIconCache(Context context, Looper backgroundLooper) {
mContext = context;
mBackgroundHandler = new Handler(backgroundLooper);
mAccessibilityManager = context.getSystemService(AccessibilityManager.class);
Resources res = context.getResources();
int cacheSize = res.getInteger(R.integer.recentsIconCacheSize);
mIconCache = new TaskKeyLruCache<>(cacheSize);
mIconProvider = new IconProvider(context);
}
/**
* Asynchronously fetches the icon and other task data.
*
* @param task The task to fetch the data for
* @param callback The callback to receive the task after its data has been populated.
* @return A cancelable handle to the request
*/
public IconLoadRequest updateIconInBackground(Task task, Consumer<Task> callback) {
Preconditions.assertUIThread();
if (task.icon != null) {
// Nothing to load, the icon is already loaded
callback.accept(task);
return null;
}
IconLoadRequest request = new IconLoadRequest(mBackgroundHandler) {
@Override
public void run() {
TaskCacheEntry entry = getCacheEntry(task);
if (isCanceled()) {
// We don't call back to the provided callback in this case
return;
}
MAIN_EXECUTOR.execute(() -> {
task.icon = entry.icon;
task.titleDescription = entry.contentDescription;
callback.accept(task);
onEnd();
});
}
};
Utilities.postAsyncCallback(mBackgroundHandler, request);
return request;
}
public void clear() {
mIconCache.evictAll();
}
void onTaskRemoved(TaskKey taskKey) {
mIconCache.remove(taskKey);
}
void invalidateCacheEntries(String pkg, UserHandle handle) {
Utilities.postAsyncCallback(mBackgroundHandler,
() -> mIconCache.removeAll(key ->
pkg.equals(key.getPackageName()) && handle.getIdentifier() == key.userId));
}
@WorkerThread
private TaskCacheEntry getCacheEntry(Task task) {
TaskCacheEntry entry = mIconCache.getAndInvalidateIfModified(task.key);
if (entry != null) {
return entry;
}
TaskDescription desc = task.taskDescription;
TaskKey key = task.key;
ActivityInfo activityInfo = null;
// Create new cache entry
entry = new TaskCacheEntry();
// Load icon
// TODO: Load icon resource (b/143363444)
Bitmap icon = TaskDescriptionCompat.getIcon(desc, key.userId);
if (icon != null) {
entry.icon = new FastBitmapDrawable(getBitmapInfo(
new BitmapDrawable(mContext.getResources(), icon),
key.userId,
desc.getPrimaryColor(),
false /* isInstantApp */));
} else {
activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
key.getComponent(), key.userId);
if (activityInfo != null) {
BitmapInfo bitmapInfo = getBitmapInfo(
mIconProvider.getIcon(activityInfo, UserHandle.of(key.userId)),
key.userId,
desc.getPrimaryColor(),
activityInfo.applicationInfo.isInstantApp());
entry.icon = newIcon(mContext, bitmapInfo);
} else {
entry.icon = getDefaultIcon(key.userId);
}
}
// Loading content descriptions if accessibility or low RAM recents is enabled.
if (GO_LOW_RAM_RECENTS_ENABLED || mAccessibilityManager.isEnabled()) {
// Skip loading the content description if the activity no longer exists
if (activityInfo == null) {
activityInfo = PackageManagerWrapper.getInstance().getActivityInfo(
key.getComponent(), key.userId);
}
if (activityInfo != null) {
entry.contentDescription = ActivityManagerWrapper.getInstance()
.getBadgedContentDescription(activityInfo, task.key.userId,
task.taskDescription);
}
}
mIconCache.put(task.key, entry);
return entry;
}
@WorkerThread
private Drawable getDefaultIcon(int userId) {
synchronized (mDefaultIcons) {
BitmapInfo info = mDefaultIcons.get(userId);
if (info == null) {
try (LauncherIcons la = LauncherIcons.obtain(mContext)) {
info = la.makeDefaultIcon(UserHandle.of(userId));
}
mDefaultIcons.put(userId, info);
}
return new FastBitmapDrawable(info);
}
}
@WorkerThread
private BitmapInfo getBitmapInfo(Drawable drawable, int userId,
int primaryColor, boolean isInstantApp) {
try (LauncherIcons la = LauncherIcons.obtain(mContext)) {
la.disableColorExtraction();
la.setWrapperBackgroundColor(primaryColor);
// User version code O, so that the icon is always wrapped in an adaptive icon container
return la.createBadgedIconBitmap(drawable, UserHandle.of(userId),
Build.VERSION_CODES.O, isInstantApp);
}
}
public static abstract class IconLoadRequest extends HandlerRunnable {
IconLoadRequest(Handler handler) {
super(handler, null);
}
}
private static class TaskCacheEntry {
public Drawable icon;
public String contentDescription = "";
}
}
| Deletescape-Media/Lawnchair | quickstep/src/com/android/quickstep/TaskIconCache.java | Java | gpl-3.0 | 8,440 |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 6 22:58:00 2016
@author: Diogo
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 26 19:08:00 2016
@author: Diogo
"""
def ImportGames():
games = list()
user_games = dict()
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesCleansed.txt', 'r', encoding = 'utf-8') as lines:
next(lines) # Skiping headers
for ln in lines:
user, board_game, board_type, list_type, score10 = ln.split('##')
if board_game not in games:
games.append(board_game.replace('\t',' ').replace(' ', ' '))
if user not in user_games:
user_games[user] = dict()
if board_game not in user_games[user].keys():
user_games[user][board_game] = 1
return (games, user_games)
games, user_games = ImportGames()
def BuildMatrix(games, user_games):
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write('user\t' + '\t'.join(games) + '\n')
for user in user_games:
user_line = list()
for game in games:
if game in user_games[user].keys():
user_line.append('1')
else:
user_line.append('0')
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write(user + '\t' + '\t'.join(user_line) + '\n')
BuildMatrix(games, user_games) | DiogoGoes/TCC | AssociationRule.py | Python | gpl-3.0 | 1,429 |
<?php
/******************************************************************************
*
* Subrion - open source content management system
* Copyright (C) 2017 Intelliants, LLC <https://intelliants.com>
*
* This file is part of Subrion.
*
* Subrion 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.
*
* Subrion 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 Subrion. If not, see <http://www.gnu.org/licenses/>.
*
*
* @link https://subrion.org/
*
******************************************************************************/
require_once IA_INCLUDES . 'helpers/ia.category.interface.php';
abstract class iaAbstractFrontHelperCategoryFlat extends abstractModuleFront
{
const ROOT_PARENT_ID = 0;
const COL_PARENT_ID = 'parent_id';
const COL_LEVEL = 'level';
protected $_tableFlat;
protected $_recountEnabled = true;
protected $_recountOptions = []; // this to be extended by ancestor
private $_defaultRecountOptions = [
'listingsTable' => null,
'activeStatus' => iaCore::STATUS_ACTIVE,
'columnCounter' => 'num_listings',
'columnTotalCounter' => 'num_all_listings'
];
private $_root;
public function init()
{
parent::init();
$this->_tableFlat = self::getTable() . '_flat';
}
public function getTableFlat($prefix = false)
{
return ($prefix ? $this->iaDb->prefix : '') . $this->_tableFlat;
}
public function getRoot()
{
if (is_null($this->_root)) {
$this->_root = $this->getOne(iaDb::convertIds(self::ROOT_PARENT_ID, self::COL_PARENT_ID));
}
return $this->_root;
}
public function getRootId()
{
return $this->getRoot()['id'];
}
public function getTopLevel($fields = null)
{
return $this->getByLevel(1, $fields);
}
public function getByLevel($level, $fields = null)
{
$where = '`status` = :status and `level` = :level';
$this->iaDb->bind($where, ['status' => iaCOre::STATUS_ACTIVE, 'level' => $level]);
return $this->getAll($where, $fields);
}
public function getParents($entryId)
{
$where = sprintf('`id` IN (SELECT `parent_id` FROM `%s` WHERE `child_id` = %d)',
$this->getTableFlat(true), $entryId);
return $this->getAll($where);
}
public function getChildren($entryId, $recursive = false)
{
$where = $recursive
? sprintf('`id` IN (SELECT `child_id` FROM `%s` WHERE `parent_id` = %d)', $this->getTableFlat(true), $entryId)
: iaDb::convertIds($entryId, self::COL_PARENT_ID);
return $this->getAll($where);
}
public function getTreeVars($id, $title)
{
$nodes = [];
foreach ($this->getParents($id) as $category) {
$nodes[] = $category['id'];
}
$result = [
'url' => $this->getInfo('url') . 'add/tree.json',
'id' => $id,
'nodes' => implode(',', $nodes),
'title' => $title
];
return $result;
}
public function getJsonTree(array $data)
{
$output = [];
$this->iaDb->setTable(self::getTable());
$dynamicLoadMode = ((int)$this->iaDb->one(iaDb::STMT_COUNT_ROWS) > 150);
$rootId = $this->getRootId();
$parentId = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : $rootId;
$where = $dynamicLoadMode
? iaDb::convertIds($parentId, self::COL_PARENT_ID)
: iaDb::convertIds($rootId, 'id', false);
$where .= ' ORDER BY `title`';
$fields = '`id`, `title_' . $this->iaCore->language['iso'] . '` `title`, `parent_id`, '
. '(SELECT COUNT(*) FROM `' . $this->getTableFlat(true) . '` f WHERE f.`parent_id` = `id`) `children_count`';
foreach ($this->iaDb->all($fields, $where) as $row) {
$entry = ['id' => $row['id'], 'text' => $row['title']];
if ($dynamicLoadMode) {
$entry['children'] = $row['children_count'] > 1;
} else {
$entry['state'] = [];
$entry['parent'] = $rootId == $row[self::COL_PARENT_ID] ? '#' : $row[self::COL_PARENT_ID];
}
$output[] = $entry;
}
return $output;
}
public function recountById($id, $factor = 1)
{
if (!$this->_recountEnabled) {
return;
}
$options = array_merge($this->_defaultRecountOptions, $this->_recountOptions);
$sql = <<<SQL
UPDATE `:table_data`
SET `:col_counter` = IF(`id` = :id, `:col_counter` + :factor, `:col_counter`),
`:col_total_counter` = `:col_total_counter` + :factor
WHERE `id` IN (SELECT `parent_id` FROM `:table_flat` WHERE `child_id` = :id)
SQL;
$sql = iaDb::printf($sql, [
'table_data' => self::getTable(true),
'table_flat' => self::getTableFlat(true),
'col_counter' => $options['columnCounter'],
'col_total_counter' => $options['columnTotalCounter'],
'id' => (int)$id,
'factor' => (int)$factor
]);
$this->iaDb->query($sql);
}
}
| Saltw/webusable | includes/helpers/ia.category.front.flat.php | PHP | gpl-3.0 | 5,629 |
<?php
/**
* \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff.
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\LanguageConstructs;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff.
*
* Verify that nothing but variables are passed to empty().
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class NewEmptyNonVariableSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(\T_EMPTY);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
if ($this->supportsBelow('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$open = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
if ($open === false
|| $tokens[$open]['code'] !== \T_OPEN_PARENTHESIS
|| isset($tokens[$open]['parenthesis_closer']) === false
) {
return;
}
$close = $tokens[$open]['parenthesis_closer'];
$nestingLevel = 0;
if ($close !== ($open + 1) && isset($tokens[$open + 1]['nested_parenthesis'])) {
$nestingLevel = count($tokens[$open + 1]['nested_parenthesis']);
}
if ($this->isVariable($phpcsFile, ($open + 1), $close, $nestingLevel) === true) {
return;
}
$phpcsFile->addError(
'Only variables can be passed to empty() prior to PHP 5.5.',
$stackPtr,
'Found'
);
}
}
| universityofglasgow/moodle | local/codechecker/PHPCompatibility/Sniffs/LanguageConstructs/NewEmptyNonVariableSniff.php | PHP | gpl-3.0 | 2,308 |
package com.glory.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Log {
@Id
@GeneratedValue
private Long id;
private Long transactionId;
private String message;
public Log() {
}
public Log(Long id, Long transactionId, String message) {
super();
this.id = id;
this.transactionId = transactionId;
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTransactionId() {
return transactionId;
}
public void setTransactionId(Long transactionId) {
this.transactionId = transactionId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| aliemrahpekesen/4GloryApi | src/main/java/com/glory/model/Log.java | Java | gpl-3.0 | 851 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Class1
{
}
}
| romanf77/Metodos-Estaticos | Clase 8 Array/PROG-LAB-II-master/Clase 08/ejemplosArray/Clases/Class1.cs | C# | gpl-3.0 | 180 |
package l2s.gameserver.network.l2.s2c;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import l2s.commons.lang.ArrayUtils;
import l2s.gameserver.model.Player;
import l2s.gameserver.model.items.ItemInfo;
import l2s.gameserver.model.items.ItemInstance;
import l2s.gameserver.model.items.Warehouse.ItemClassComparator;
import l2s.gameserver.model.items.Warehouse.WarehouseType;
public class WareHouseWithdrawListPacket extends L2GameServerPacket
{
private long _adena;
private List<ItemInfo> _itemList = new ArrayList<ItemInfo>();
private int _type;
private int _inventoryUsedSlots;
public WareHouseWithdrawListPacket(Player player, WarehouseType type)
{
_adena = player.getAdena();
_type = type.ordinal();
ItemInstance[] items;
switch(type)
{
case PRIVATE:
items = player.getWarehouse().getItems();
break;
case FREIGHT:
items = player.getFreight().getItems();
break;
case CLAN:
case CASTLE:
items = player.getClan().getWarehouse().getItems();
break;
default:
_itemList = Collections.emptyList();
return;
}
_itemList = new ArrayList<ItemInfo>(items.length);
ArrayUtils.eqSort(items, ItemClassComparator.getInstance());
for(ItemInstance item : items)
_itemList.add(new ItemInfo(item));
_inventoryUsedSlots = player.getInventory().getSize();
}
@Override
protected final void writeImpl()
{
writeH(_type);
writeQ(_adena);
writeH(_itemList.size());
if(_type == 1 || _type == 2)
{
if(_itemList.size() > 0)
{
writeH(0x01);
writeD(0x1063); // TODO: writeD(_itemList.get(0).getItemId()); первый предмет в списке.
}
else
writeH(0x00);
}
writeD(_inventoryUsedSlots); //Количество занятых ячеек в инвентаре.
for(ItemInfo item : _itemList)
{
writeItemInfo(item);
writeD(item.getObjectId());
writeD(0);
writeD(0);
}
}
} | pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/network/l2/s2c/WareHouseWithdrawListPacket.java | Java | gpl-3.0 | 1,932 |
# -*- coding: utf-8 -*-
from django.contrib import admin
from models import FileMapping
# Register your models here.
admin.site.register(FileMapping)
| tiankangkan/paper_plane | treasure/admin.py | Python | gpl-3.0 | 155 |
<?php
/**
* BwPostman Newsletter Component
*
* BwPostman form field Text templates class.
*
* @version %%version_number%%
* @package BwPostman-Admin
* @author Karl Klostermann
* @copyright (C) %%copyright_year%% Boldt Webservice <forum@boldt-webservice.de>
* @support https://www.boldt-webservice.de/en/forum-en/forum/bwpostman.html
* @license GNU/GPL, see LICENSE.txt
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace BoldtWebservice\Component\BwPostman\Administrator\Field;
defined('JPATH_PLATFORM') or die;
use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHelper;
use Exception;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Field\RadioField;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use RuntimeException;
/**
* Form Field class for the Joomla Platform.
* Supports a nested check box field listing user groups.
* Multi select is available by default.
*
* @package BwPostman.Administrator
*
* @since 1.2.0
*/
class TexttemplatesField extends RadioField
{
/**
* The form field type.
*
* @var string
*
* @since 1.2.0
*/
protected $type = 'Texttemplates';
/**
* Method to get the Text template field input markup.
*
* @return string The field input markup.
*
* @throws Exception
*
* @since 1.2.0
*/
protected function getInput(): string
{
$item = Factory::getApplication()->getUserState('com_bwpostman.edit.newsletter.data');
$html = array();
$selected = '';
// Initialize some field attributes.
$readonly = $this->readonly;
// Get the field options.
$options = $this->getOptions();
// Get selected template.
if (is_object($item))
{
$selected = $item->text_template_id;
}
// note for old templates
if ($selected < 1)
{
$html[] = Text::_('COM_BWPOSTMAN_NOTE_OLD_TEMPLATE');
}
if (count($options) > 0)
{
// Build the radio field output.
foreach ($options as $i => $option)
{
// Initialize some option attributes.
$checked = ((string) $option->value == (string) $selected) ? ' checked="checked"' : '';
$lblclass = ' class="mailinglists form-check-label"';
$inputclass = ' class="mailinglists form-check-input"';
$disabled = !empty($option->disable) || ($readonly && !$checked);
$disabled = $disabled ? ' disabled' : '';
// Initialize some JavaScript option attributes.
$onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : '';
$onchange = !empty($option->onchange) ? ' onchange="' . $option->onchange . '"' : '';
$html[] = '<div class="form-check" aria-describedby="tip-' . $this->id . $i . '">';
$html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="'
. htmlspecialchars($option->value, ENT_COMPAT) . '"' . $checked . $inputclass . $onclick
. $onchange . $disabled . ' />';
$html[] = '<label for="' . $this->id . $i . '"' . $lblclass . ' >';
$html[] = $option->title . '</label>';
$tooltip = '<strong>' . $option->description . '</strong><br /><br />'
. '<div><img src="' . Uri::root() . $option->thumbnail . '" alt="' . $option->title . '"'
.'style="max-width:160px; max-height:100px;" /></div>';
$html[] = '<div role="tooltip" id="tip-' . $this->id . $i . '">'.$tooltip.'</div>';
$html[] = '</div>';
}
}
else
{
$html[] = Text::_('COM_BWPOSTMAN_NO_DATA');
}
// End the radio field output.
// $html[] = '</div>';
return implode($html);
}
/**
* Method to get the field options.
*
* @return array The field option objects.
*
* @throws Exception
*
* @since 1.2.0
*/
public function getOptions(): array
{
$app = Factory::getApplication();
// Initialize variables.
$item = $app->getUserState('com_bwpostman.edit.newsletter.data');
$options = array();
// prepare query
$db = BwPostmanHelper::getDbo();
// Build the select list for the templates
$query = $db->getQuery(true);
$query->select($db->quoteName('id') . ' AS ' . $db->quoteName('value'));
$query->select($db->quoteName('title') . ' AS ' . $db->quoteName('title'));
$query->select($db->quoteName('description') . ' AS ' . $db->quoteName('description'));
$query->select($db->quoteName('thumbnail') . ' AS ' . $db->quoteName('thumbnail'));
$query->from($db->quoteName('#__bwpostman_templates'));
// special for old newsletters with template_id < 1
if (is_object($item))
{
if ($item->text_template_id < 1 && !is_null($item->text_template_id))
{
$query->where($db->quoteName('id') . ' >= ' . $db->quote('-2'));
}
else
{
$query->where($db->quoteName('id') . ' > ' . $db->quote('0'));
}
}
$query->where($db->quoteName('archive_flag') . ' = ' . $db->quote('0'));
$query->where($db->quoteName('published') . ' = ' . $db->quote('1'));
$query->where($db->quoteName('tpl_id') . ' > ' . $db->quote('997'));
$query->order($db->quoteName('title') . ' ASC');
try
{
$db->setQuery($query);
$options = $db->loadObjectList();
}
catch (RuntimeException $e)
{
Factory::getApplication()->enqueueMessage($e->getMessage(), 'error');
}
// Merge any additional options in the XML definition.
return array_merge(parent::getOptions(), $options);
}
}
| RomanaBW/BwPostman | src/administrator/components/com_bwpostman/src/Field/TexttemplatesField.php | PHP | gpl-3.0 | 5,859 |
<?php
namespace App\Model\Table;
use App\Model\Entity\Guest;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Guests Model
*
* @property \Cake\ORM\Association\BelongsTo $Matchteams
* @property \Cake\ORM\Association\BelongsToMany $Hosts
*/
class GuestsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('guests');
$this->displayField('name');
$this->primaryKey('id');
$this->belongsTo('Matchteams', [
'foreignKey' => 'matchteam_id'
]);
$this->belongsToMany('Hosts', [
'foreignKey' => 'guest_id',
'targetForeignKey' => 'host_id',
'joinTable' => 'hosts_guests'
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->add('primary_squad', 'valid', ['rule' => 'boolean'])
->allowEmpty('primary_squad');
$validator
->allowEmpty('name');
$validator
->allowEmpty('yellow');
$validator
->allowEmpty('red');
$validator
->allowEmpty('substitution');
$validator
->allowEmpty('goals');
$validator
->allowEmpty('rating');
$validator
->allowEmpty('assist');
$validator
->allowEmpty('injuries');
return $validator;
}
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['matchteam_id'], 'Matchteams'));
return $rules;
}
}
| pacior/testimonials | src/Model/Table/GuestsTable.php | PHP | gpl-3.0 | 2,307 |
<?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/>.
require_once('../../config.php');
require_once($CFG->dirroot.'/mod/scorm/locallib.php');
$id = optional_param('id', '', PARAM_INT); // Course Module ID, or
$a = optional_param('a', '', PARAM_INT); // scorm ID
$scoid = required_param('scoid', PARAM_INT); // sco ID
$attempt = required_param('attempt', PARAM_INT); // attempt number
if (!empty($id)) {
if (! $cm = get_coursemodule_from_id('scorm', $id)) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record("course", array("id"=>$cm->course))) {
print_error('coursemisconf');
}
if (! $scorm = $DB->get_record("scorm", array("id"=>$cm->instance))) {
print_error('invalidcoursemodule');
}
} else if (!empty($a)) {
if (! $scorm = $DB->get_record("scorm", array("id"=>$a))) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record("course", array("id"=>$scorm->course))) {
print_error('coursemisconf');
}
if (! $cm = get_coursemodule_from_instance("scorm", $scorm->id, $course->id)) {
print_error('invalidcoursemodule');
}
} else {
print_error('missingparameter');
}
$PAGE->set_url('/mod/scorm/datamodel.php', array('scoid'=>$scoid, 'attempt'=>$attempt, 'id'=>$cm->id));
require_login($course, false, $cm);
if (confirm_sesskey() && (!empty($scoid))) {
$result = true;
$request = null;
if (has_capability('mod/scorm:savetrack', context_module::instance($cm->id))) {
foreach (data_submitted() as $element => $value) {
$element = str_replace('__', '.', $element);
if (substr($element, 0, 3) == 'cmi') {
$netelement = preg_replace('/\.N(\d+)\./', "\.\$1\.", $element);
$result = scorm_insert_track($USER->id, $scorm->id, $scoid, $attempt, $element, $value, $scorm->forcecompleted) && $result;
}
if (substr($element, 0, 15) == 'adl.nav.request') {
// SCORM 2004 Sequencing Request
require_once($CFG->dirroot.'/mod/scorm/datamodels/scorm_13lib.php');
$search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@', '@exit@', '@exitAll@', '@abandon@', '@abandonAll@');
$replace = array('continue_', 'previous_', '\1', 'exit_', 'exitall_', 'abandon_', 'abandonall');
$action = preg_replace($search, $replace, $value);
if ($action != $value) {
// Evaluating navigation request
$valid = scorm_seq_overall ($scoid, $USER->id, $action, $attempt);
$valid = 'true';
// Set valid request
$search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@');
$replace = array('true', 'true', 'true');
$matched = preg_replace($search, $replace, $value);
if ($matched == 'true') {
$request = 'adl.nav.request_valid["'.$action.'"] = "'.$valid.'";';
}
}
}
}
}
if ($result) {
echo "true\n0";
} else {
echo "false\n101";
}
if ($request != null) {
echo "\n".$request;
}
}
| ouyangyu/fdmoodle | mod/scorm/datamodel.php | PHP | gpl-3.0 | 4,031 |
"use strict";
/*
Copyright (C) 2013-2017 Bryan Hughes <bryan@nebri.us>
Aquarium Control 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.
Aquarium Control 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 Aquarium Control. If not, see <http://www.gnu.org/licenses/>.
*/
Object.defineProperty(exports, "__esModule", { value: true });
// Force to "any" type, otherwise TypeScript thinks the type is too strict
exports.cleaningValidationSchema = {
type: 'object',
properties: {
time: {
required: true,
type: 'number'
},
bioFilterReplaced: {
required: true,
type: 'boolean'
},
mechanicalFilterReplaced: {
required: true,
type: 'boolean'
},
spongeReplaced: {
required: true,
type: 'boolean'
}
}
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSUNsZWFuaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NvbW1vbi9zcmMvSUNsZWFuaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTs7Ozs7Ozs7Ozs7Ozs7O0VBZUU7O0FBYUYsMEVBQTBFO0FBQzdELFFBQUEsd0JBQXdCLEdBQVE7SUFDM0MsSUFBSSxFQUFFLFFBQVE7SUFDZCxVQUFVLEVBQUU7UUFDVixJQUFJLEVBQUU7WUFDSixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxRQUFRO1NBQ2Y7UUFDRCxpQkFBaUIsRUFBRTtZQUNqQixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxTQUFTO1NBQ2hCO1FBQ0Qsd0JBQXdCLEVBQUU7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxJQUFJLEVBQUUsU0FBUztTQUNoQjtRQUNELGNBQWMsRUFBRTtZQUNkLFFBQVEsRUFBRSxJQUFJO1lBQ2QsSUFBSSxFQUFFLFNBQVM7U0FDaEI7S0FDRjtDQUNGLENBQUMifQ== | nebrius/aquarium-control | server/dist/common/src/ICleaning.js | JavaScript | gpl-3.0 | 1,996 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
namespace Chess
{
public abstract class Screen : UserControl
{
public ScreenControl parentWindow;
public ScreenControl ParentWindow { get { return parentWindow; } }
protected Screen() { }
public Screen(ScreenControl parentWindow)
{
this.parentWindow = parentWindow;
}
}
}
| TomHulme/P4P | Chess/Screen.cs | C# | gpl-3.0 | 468 |
package com.habitrpg.android.habitica.ui.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;
import com.amplitude.api.Amplitude;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.habitrpg.android.habitica.APIHelper;
import com.habitrpg.android.habitica.HostConfig;
import com.habitrpg.android.habitica.R;
import com.habitrpg.android.habitica.callbacks.HabitRPGUserCallback;
import com.habitrpg.android.habitica.prefs.scanner.IntentIntegrator;
import com.habitrpg.android.habitica.prefs.scanner.IntentResult;
import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
import com.magicmicky.habitrpgwrapper.lib.models.UserAuthResponse;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* @author Mickael Goubin
*/
public class LoginActivity extends AppCompatActivity
implements Callback<UserAuthResponse>,HabitRPGUserCallback.OnUserReceived {
private final static String TAG_ADDRESS="address";
private final static String TAG_USERID="user";
private final static String TAG_APIKEY="key";
private APIHelper mApiHelper;
public String mTmpUserToken;
public String mTmpApiToken;
public Boolean isRegistering;
private Menu menu;
@BindString(R.string.SP_address_default)
String apiAddress;
//private String apiAddress;
//private String apiAddress = "http://192.168.2.155:8080/"; // local testing
private CallbackManager callbackManager;
@Bind(R.id.login_btn)
Button mLoginNormalBtn;
@Bind(R.id.PB_AsyncTask)
ProgressBar mProgressBar;
@Bind(R.id.username)
EditText mUsernameET;
@Bind(R.id.password)
EditText mPasswordET;
@Bind(R.id.email)
EditText mEmail;
@Bind(R.id.confirm_password)
EditText mConfirmPassword;
@Bind(R.id.email_row)
TableRow mEmailRow;
@Bind(R.id.confirm_password_row)
TableRow mConfirmPasswordRow;
@Bind(R.id.login_button)
LoginButton mFacebookLoginBtn;
@Bind(R.id.forgot_pw_tv)
TextView mForgotPWTV;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_account_details, false);
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false);
ButterKnife.bind(this);
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
mFacebookLoginBtn.setReadPermissions("user_friends");
mForgotPWTV.setOnClickListener(mForgotPWClick);
SpannableString content = new SpannableString(mForgotPWTV.getText());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
mForgotPWTV.setText(content);
callbackManager = CallbackManager.Factory.create();
mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
mApiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken(), LoginActivity.this);
}
@Override
public void onCancel() {
Log.d("FB Login", "Cancelled");
}
@Override
public void onError(FacebookException exception) {
Log.e("FB Login", "Error", exception);
}
});
HostConfig hc= PrefsActivity.fromContext(this);
if(hc ==null) {
hc = new HostConfig(apiAddress, "80", "", "");
}
mApiHelper = new APIHelper(hc);
this.isRegistering = true;
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "navigate");
eventProperties.put("eventCategory", "navigation");
eventProperties.put("hitType", "pageview");
eventProperties.put("page", this.getClass().getSimpleName());
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("navigate", eventProperties);
}
private void resetLayout() {
if (this.isRegistering) {
if (this.mEmailRow.getVisibility() == View.GONE) {
expand(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.GONE) {
expand(this.mConfirmPasswordRow);
}
} else {
if (this.mEmailRow.getVisibility() == View.VISIBLE) {
collapse(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.VISIBLE) {
collapse(this.mConfirmPasswordRow);
}
}
}
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (isRegistering) {
String username, email,password,cpassword;
username = String.valueOf(mUsernameET.getText()).trim();
email = String.valueOf(mEmail.getText()).trim();
password = String.valueOf(mPasswordET.getText());
cpassword = String.valueOf(mConfirmPassword.getText());
if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.registerUser(username,email,password, cpassword, LoginActivity.this);
} else {
String username,password;
username = String.valueOf(mUsernameET.getText()).trim();
password = String.valueOf(mPasswordET.getText());
if (username.length() == 0 || password.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.connectUser(username,password, LoginActivity.this);
}
}
};
private View.OnClickListener mForgotPWClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = getString(R.string.SP_address_default);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
};
public static void expand(final View v) {
v.setVisibility(View.VISIBLE);
}
public static void collapse(final View v) {
v.setVisibility(View.GONE);
}
private void startMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void startSetupActivity() {
Intent intent = new Intent(LoginActivity.this, SetupActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void toggleRegistering() {
this.isRegistering = !this.isRegistering;
this.setRegistering();
}
private void setRegistering() {
MenuItem menuItem = menu.findItem(R.id.action_toggleRegistering);
if (this.isRegistering) {
this.mLoginNormalBtn.setText(getString(R.string.register_btn));
menuItem.setTitle(getString(R.string.login_btn));
mUsernameET.setHint(R.string.username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_NEXT);
} else {
this.mLoginNormalBtn.setText(getString(R.string.login_btn));
menuItem.setTitle(getString(R.string.register_btn));
mUsernameET.setHint(R.string.email_username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE);
}
this.resetLayout();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
callbackManager.onActivityResult(requestCode, resultCode, intent);
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
try {
Log.d("scanresult", scanResult.getContents());
this.parse(scanResult.getContents());
} catch(Exception e) {
Log.e("scanresult", "Could not parse scanResult", e);
}
}
}
private void parse(String contents) {
String adr,user,key;
try {
JSONObject obj;
obj = new JSONObject(contents);
adr = obj.getString(TAG_ADDRESS);
user = obj.getString(TAG_USERID);
key = obj.getString(TAG_APIKEY);
Log.d("", "adr" + adr + " user:" + user + " key" + key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_address), adr)
.putString(getString(R.string.SP_APIToken), key)
.putString(getString(R.string.SP_userID), user)
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
startMainActivity();
} catch (JSONException e) {
showSnackbar(getString(R.string.ERR_pb_barcode));
e.printStackTrace();
} catch(Exception e) {
if("PB_string_commit".equals(e.getMessage())) {
showSnackbar(getString(R.string.ERR_pb_barcode));
}
}
}
private void showSnackbar(String content)
{
Snackbar snackbar = Snackbar
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
snackbar.show(); // Don’t forget to show!
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_toggleRegistering:
toggleRegistering();
break;
}
return super.onOptionsItemSelected(item);
}
private void afterResults() {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void success(UserAuthResponse userAuthResponse, Response response) {
try {
saveTokens(userAuthResponse.getToken(), userAuthResponse.getId());
} catch (Exception e) {
e.printStackTrace();
}
if (this.isRegistering) {
this.startSetupActivity();
} else {
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "lofin");
eventProperties.put("eventCategory", "behaviour");
eventProperties.put("hitType", "event");
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("login", eventProperties);
this.startMainActivity();
}
}
private void saveTokens(String api, String user) throws Exception {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
.putString(getString(R.string.SP_userID), user)
.putString(getString(R.string.SP_address),getString(R.string.SP_address_default))
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
}
@Override
public void failure(RetrofitError error) {
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onUserReceived(HabitRPGUser user) {
try {
saveTokens(mTmpApiToken, mTmpUserToken);
} catch (Exception e) {
e.printStackTrace();
}
this.startMainActivity();
}
@Override
public void onUserFail() {
mProgressBar.setVisibility(View.GONE);
showSnackbar(getString(R.string.unknown_error));
}
private void showValidationError(int resourceMessageString) {
mProgressBar.setVisibility(View.GONE);
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.login_validation_error_title)
.setMessage(resourceMessageString)
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.ic_warning_black)
.show();
}
}
| yishanhe/habitrpg-android | Habitica/src/com/habitrpg/android/habitica/ui/activities/LoginActivity.java | Java | gpl-3.0 | 13,599 |
<?php
namespace hemio\html;
/**
* The <code>figure</code> element represents a unit of content, optionally with
* a caption, that is self-contained, that is typically referenced as a single
* unit from the main flow of the document, and that can be moved away from the
* main flow of the document without affecting the document’s meaning.
*
* @since version 1.0
* @url http://www.w3.org/TR/html5/grouping-content.html#the-figure-element
*/
class Figure extends Abstract_\ElementContent
{
use Trait_\DefaultElementContent;
public static function tagName()
{
return 'figure';
}
public function blnIsBlock()
{
return true;
}
}
| qua-bla/html | src/Figure.php | PHP | gpl-3.0 | 683 |
/*
* Copyright (C) 2010-2019 The ESPResSo project
* Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
* Max-Planck-Institute for Polymer Research, Theory Group
*
* This file is part of ESPResSo.
*
* ESPResSo 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.
*
* ESPResSo 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/>.
*/
#ifndef SCRIPT_INTERFACE_COM_FIXED_HPP
#define SCRIPT_INTERFACE_COM_FIXED_HPP
#include "script_interface/ScriptInterface.hpp"
#include "core/comfixed_global.hpp"
namespace ScriptInterface {
class ComFixed : public AutoParameters<ComFixed> {
public:
ComFixed() {
add_parameters({{"types",
[](Variant const &v) {
comfixed.set_fixed_types(get_value<std::vector<int>>(v));
},
[]() { return comfixed.get_fixed_types(); }}});
}
};
} // namespace ScriptInterface
#endif
| KaiSzuttor/espresso | src/script_interface/ComFixed.hpp | C++ | gpl-3.0 | 1,418 |
/**
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.function;
import org.structr.common.error.FrameworkException;
import org.structr.common.error.SemanticErrorToken;
import org.structr.core.GraphObject;
import org.structr.core.app.StructrApp;
import org.structr.core.property.PropertyKey;
import org.structr.schema.action.ActionContext;
import org.structr.schema.action.Function;
/**
*
*/
public class ErrorFunction extends Function<Object, Object> {
public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}";
@Override
public String getName() {
return "error()";
}
@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException {
final Class entityType;
final String type;
if (entity != null) {
entityType = entity.getClass();
type = entity.getType();
} else {
entityType = GraphObject.class;
type = "Base";
}
try {
if (sources == null) {
throw new IllegalArgumentException();
}
switch (sources.length) {
case 1:
throw new IllegalArgumentException();
case 2:
{
arrayHasLengthAndAllElementsNotNull(sources, 2);
final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString());
ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString()));
break;
}
case 3:
{
arrayHasLengthAndAllElementsNotNull(sources, 3);
final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString());
ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString(), sources[2]));
break;
}
default:
logParameterError(entity, sources, ctx.isJavaScriptContext());
break;
}
} catch (final IllegalArgumentException e) {
logParameterError(entity, sources, ctx.isJavaScriptContext());
return usage(ctx.isJavaScriptContext());
}
return null;
}
@Override
public String usage(boolean inJavaScriptContext) {
return ERROR_MESSAGE_ERROR;
}
@Override
public String shortDescription() {
return "Signals an error to the caller";
}
}
| derkaiserreich/structr | structr-core/src/main/java/org/structr/core/function/ErrorFunction.java | Java | gpl-3.0 | 2,991 |
package org.maxgamer.rs.model.skill.prayer;
import java.util.LinkedList;
/**
* @author netherfoam, alva
*/
public enum PrayerGroup {
//Standard prayer book
/** All prayers that boost defense */
DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY),
/** All prayers that boost strength */
STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY),
/** All prayers that boost attack */
ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY),
/** All prayers that boost range */
RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR),
/** All prayers that boost magic */
MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY),
/**
* most prayers that put a symbol above player head (Prot
* (melee/magic/range), retribution, smite, redemption)
*/
STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE),
/** Protect from melee/range/magic prayers */
PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC),
//Curses prayer book
/** Sap prayers (warrior, range, spirit) */
SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT),
/**
* leech prayers (attack, range, magic, defence, strength, energy, special
* attack)
*/
LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.LEECH_SPECIAL_ATTACK),
/**
* similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles,
* melee)
*/
CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE),
/** All deflections (magic, missiles, melee) */
DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE);
private PrayerType[] types;
private PrayerGroup(PrayerType... types) {
this.types = types;
}
public PrayerType[] getTypes() {
return types;
}
/**
* Returns true if this prayer group contains the given prayer.
* @param type the prayer
* @return true if it is contained, else false.
*/
public boolean contains(PrayerType type) {
for (PrayerType p : this.types) {
if (type == p) {
return true;
}
}
return false;
}
/**
* Returns an array of groups that the given prayer is in.
* @param type the prayer
* @return an array of groups that the given prayer is in.
*/
public static LinkedList<PrayerGroup> getGroups(PrayerType type) {
LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>();
for (PrayerGroup g : values()) {
if (g.contains(type)) {
groups.add(g);
}
}
return groups;
}
} | tehnewb/Titan | src/org/maxgamer/rs/model/skill/prayer/PrayerGroup.java | Java | gpl-3.0 | 3,118 |
/*
* ASpark
* Copyright (C) 2015 Nikolay Platov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nikoladasm.aspark;
import java.io.IOException;
import java.io.InputStream;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.netty.buffer.ByteBuf;
import static nikoladasm.aspark.HttpMethod.*;
public final class ASparkUtil {
private static final String PARAMETERS_PATTERN = "(?i)(:[A-Z_][A-Z_0-9]*)";
private static final Pattern PATTERN = Pattern.compile(PARAMETERS_PATTERN);
private static final String DEFAULT_ACCEPT_TYPE = "*/*";
private static final String REGEXP_METACHARS = "<([{\\^-=$!|]})?*+.>";
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final String FOLDER_SEPARATOR = "/";
private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
private static final String TOP_PATH = "..";
private static final String CURRENT_PATH = ".";
private static final String QUERY_KEYS_PATTERN = "\\s*\\[?\\s*([^\\]\\[\\s]+)\\s*\\]?\\s*";
private static final Pattern QK_PATTERN = Pattern.compile(QUERY_KEYS_PATTERN);
private ASparkUtil() {}
private static String processRegexPath(String path, String asteriskReplacement, String slashAsteriskReplacement) {
String pathToUse = sanitizePath(path);
int length = pathToUse.length();
StringBuilder sb = new StringBuilder();
boolean startWithWildcard = false;
for (int i = 0; i < length; i++) {
char c = pathToUse.charAt(i);
if (i == 0 && c == '*') {
sb.append(asteriskReplacement);
startWithWildcard = true;
continue;
}
if (i == length-2 && c == '/' && pathToUse.charAt(i+1) == '*') {
if (startWithWildcard)
throw new IllegalArgumentException("Path can't contain first and last star wildcard");
sb.append(slashAsteriskReplacement);
break;
}
if (i == length-1 && c == '*') {
if (startWithWildcard)
throw new IllegalArgumentException("Path can't contain first and last star wildcard");
sb.append(asteriskReplacement);
continue;
}
if (REGEXP_METACHARS.contains(String.valueOf(c))) {
sb.append('\\').append(c);
continue;
}
sb.append(c);
}
return sb.toString();
}
public static Pattern buildParameterizedPathPattern(String path, Map<String, Integer> parameterNamesMap, Boolean startWithWildcard) {
String pathToUse = processRegexPath(path, "(.*)", "(?:/?|/(.+))");
Matcher parameterMatcher = PATTERN.matcher(pathToUse);
int i = 1;
while (parameterMatcher.find()) {
String parameterName = parameterMatcher.group(1);
if (parameterNamesMap.containsKey(parameterName))
throw new ASparkException("Duplicate parameter name.");
parameterNamesMap.put(parameterName, i);
i++;
}
return Pattern.compile("^"+parameterMatcher.replaceAll("([^/]+)")+"$");
}
public static Pattern buildPathPattern(String path) {
String pathToUse = processRegexPath(path, ".*", "(?:/?|/.+)");
return Pattern.compile("^"+pathToUse+"$");
}
public static boolean isAcceptContentType(String requestAcceptTypes,
String routeAcceptType) {
if (requestAcceptTypes == null)
return routeAcceptType.trim().equals(DEFAULT_ACCEPT_TYPE);
String[] requestAcceptTypesArray = requestAcceptTypes.split(",");
String[] rtat = routeAcceptType.trim().split("/");
for (int i=0; i<requestAcceptTypesArray.length; i++) {
String requestAcceptType = requestAcceptTypesArray[i].split(";")[0];
String[] rqat = requestAcceptType.trim().split("/");
if (((rtat[0].equals("*")) ? true : rqat[0].trim().equals(rtat[0])) &&
((rtat[1].equals("*")) ? true : rqat[1].equals(rtat[1]))) return true;
}
return false;
}
public static long copyStreamToByteBuf(InputStream input, ByteBuf buf) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while ((n = input.read(buffer)) != -1) {
buf.writeBytes(buffer, 0, n);
count += n;
}
return count;
}
public static String collapsePath(String path) {
String pathToUse = path.trim();
if (pathToUse.isEmpty()) return pathToUse;
String rpath = pathToUse.replace(WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);
String[] directories = rpath.split(FOLDER_SEPARATOR);
Deque<String> newDirectories = new LinkedList<>();
for (int i=0; i<directories.length; i++) {
String directory = directories[i].trim();
if (directory.equals(TOP_PATH) && !newDirectories.isEmpty())
newDirectories.removeLast();
else if (!directory.equals(CURRENT_PATH) && !directory.isEmpty())
newDirectories.addLast(directory);
}
String result = FOLDER_SEPARATOR;
for (String directory : newDirectories)
result += directory + FOLDER_SEPARATOR;
if (!path.startsWith(FOLDER_SEPARATOR))
result = result.substring(1);
if (!path.endsWith(FOLDER_SEPARATOR) && result.equals(FOLDER_SEPARATOR))
result = result.substring(0, result.length()-1);
return result;
}
public static boolean isEqualHttpMethod(HttpMethod requestHttpMethod,
HttpMethod routeHttpMethod) {
if (requestHttpMethod.equals(HEAD) && routeHttpMethod.equals(GET))
return true;
return requestHttpMethod.equals(routeHttpMethod);
}
public static ParamsMap parseParams(Map<String, List<String>> params) {
ParamsMap result = new ParamsMap();
params.forEach((keys, values) -> {
ParamsMap root = result;
Matcher keyMatcher = QK_PATTERN.matcher(keys);
while (keyMatcher.find()) {
String key = keyMatcher.group(1);
root = root.createIfAbsentAndGet(key);
}
root.values(values.toArray(new String[values.size()]));
});
return result;
}
public static ParamsMap parseUniqueParams(Map<String, String> params) {
ParamsMap result = new ParamsMap();
params.forEach((key, value) -> {
result.createIfAbsentAndGet(key).value(value);
});
return result;
}
public static String sanitizePath(String path) {
String pathToUse = collapsePath(path);
if (pathToUse.isEmpty()) return pathToUse;
if (pathToUse.endsWith("/")) pathToUse = pathToUse.substring(0, pathToUse.length()-1);
return pathToUse;
}
public static String mimeType(String file, Properties mimeTypes) {
int extIndex = file.lastIndexOf('.');
extIndex = (extIndex < 0 ) ? 0 : extIndex;
String ext = file.substring(extIndex);
return mimeTypes.getProperty(ext, "application/octet-stream");
}
}
| NikolaDasm/aspark | src/nikoladasm/aspark/ASparkUtil.java | Java | gpl-3.0 | 7,066 |
package controller;
import java.io.IOException;
import java.sql.Time;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONObject;
import utils.Common;
import utils.Constant;
import utils.MessageProperties;
import dao.HocKyDao;
import dao.OnlDao;
import dao.WeekDao;
import dao.impl.HocKyDaoImpl;
import dao.impl.OnlDaoImpl;
import dao.impl.PositionDaoImpl;
import dao.impl.WeekDaoImpl;
import entity.HocKy;
import entity.Onl;
import entity.Position;
import entity.User;
import entity.Week;
/**
* Servlet implementation class OnlController
*/
@WebServlet("/jsp/onl.htm")
public class OnlController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
// get list học kỳ
HocKyDao hocKyDao = new HocKyDaoImpl();
List<HocKy> listHocKy = hocKyDao.getListHocKy();
request.setAttribute("listHocKy", listHocKy);
// lấy học kỳ hiện tại
String currentHocKy = hocKyDao.getHocKy(Common.getNow());
request.setAttribute("currentHocKy", currentHocKy);
// lấy danh sách tuần theo học kỳ hiện tại
WeekDao weekDao = new WeekDaoImpl();
List<Week> listWeek = weekDao.getListWeek(currentHocKy);
request.setAttribute("listWeek", listWeek);
// lấy tuần hiện tại
Week currentWeek = weekDao.getCurrentWeek(Common.getNow());
request.setAttribute("currentWeek", currentWeek);
// lấy lịch trực trong tuần
List<Onl> listOnl = new OnlDaoImpl().getListOnl(null, currentWeek.getWeekId(), user.getUserId());
request.setAttribute(Constant.ACTION, "viewOnl");
request.setAttribute("listOnl", listOnl);
request.getRequestDispatcher("view_onl_cal.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
@SuppressWarnings({ "unchecked", "deprecation" })
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("position".equals(action)) {
double latitude = Double.parseDouble(request
.getParameter("latitude"));
double longitude = Double.parseDouble(request
.getParameter("longitude"));
long onlId = Long.parseLong(request.getParameter("id"));
// lấy tọa độ phòng B1-502
Position position = new PositionDaoImpl().getPositionById("B1-502");
JSONObject jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
if (position == null) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR12"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// check vị trí
if (!checkPosition(position, latitude, longitude)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR13"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// if (!(latitude >= 20 && latitude <= 22 && longitude >= 105 &&
// longitude <= 106)) {
// String error = MessageProperties.getData("ERR09");
// jsonObject.put(Constant.STATUS, false);
// jsonObject.put(Constant.DATA, error);
// out.write(jsonObject.toJSONString().getBytes());
// out.flush();
// return;
// }
// check thời giạn click nhận giao ban
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh"));
Time now = new Time(cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
// lấy lịch trực bởi id
OnlDao onlDao = new OnlDaoImpl();
Onl onl = onlDao.getOnlById(onlId);
if (now.after(onl.getTimeStart()) && now.before(onl.getTimeEnd())) {
// tính thời gian muộn
int lateMin = (int) Math.round((double) ((now.getTime() - onl
.getTimeStart().getTime()) / 1000) / 60);
// thay đổi trạng thái
onl.setLate(true);
onl.setLateMin(lateMin);
} else if (now.after(onl.getTimeEnd())) {
// nghỉ
String error = MessageProperties.getData("ERR14");
jsonObject.put(Constant.STATUS, false);
jsonObject.put("flagHol", true);
jsonObject.put(Constant.DATA, error);
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
// cập nhật trạng thái nghỉ
onl.setHol(false);
// cập nhật
if (!onlDao.update(onl, true)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR10"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
jsonObject.put(Constant.STATUS, true);
jsonObject.put(Constant.DATA, MessageProperties.getData("MSG04"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
} else if ("addReason".equals(action)) {
JSONObject jsonObject = new JSONObject();
ServletOutputStream out = response.getOutputStream();
String reason = request.getParameter("reason");
long onlId = Long.parseLong(request.getParameter("id"));
// update lý do
if (!new OnlDaoImpl().setReason(reason, onlId)) {
jsonObject.put(Constant.STATUS, false);
jsonObject.put(Constant.DATA,
MessageProperties.getData("ERR10"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
jsonObject.put(Constant.STATUS, true);
jsonObject.put(Constant.DATA, MessageProperties.getData("MSG01"));
out.write(jsonObject.toJSONString().getBytes());
out.flush();
return;
}
}
/**
* check vị trí khi nhận giao ban
*
* @param position
* tọa độ vị trí phòng B1-502
* @param latitude
* vĩ độ lấy được ở vị trí hiện tại
* @param longitude
* kinh độ ở vị trí hiện tại
* @return true nếu vị trí hiện tại trùng với vị trí phòng B1-502. flase nếu
* ngược lại không trùng
*/
public boolean checkPosition(Position position, double latitude,
double longitude) {
double latitudeMin = Math.floor(position.getLatitude() * 1000000) / 1000000;
double latitudeMax = Math.ceil(position.getLatitude() * 1000000) / 1000000;
double longitudeMin = Math.floor(position.getLongitude() * 10000000) / 10000000;
double longitudeMax = Math.ceil((position.getLongitude()) * 10000000) / 10000000;
System.out.println(latitudeMin + " <= " + latitude + " <= "+ latitudeMax);
System.out.println(longitudeMin + " <= " + longitude + " <= "+ longitudeMax);
return latitudeMin <= latitude && latitude <= latitudeMax && longitudeMin <= longitude && longitude <= longitudeMax;
}
}
| phuong95st/project-LA16 | qlhoatdong2/src/controller/OnlController.java | Java | gpl-3.0 | 7,370 |
#ifndef __PLATFORM_H_
#define __PLATFORM_H_
#define STDOUT_IS_PS7_UART
#define UART_DEVICE_ID 0
#include "xil_io.h"
#include "xtmrctr.h"
#include "assert.h"
/* Write to memory location or register */
#define X_mWriteReg(BASE_ADDRESS, RegOffset, data) \
*(unsigned volatile int *)(BASE_ADDRESS + RegOffset) = ((unsigned volatile int) data);
/* Read from memory location or register */
#define X_mReadReg(BASE_ADDRESS, RegOffset) \
*(unsigned volatile int *)(volatile)(BASE_ADDRESS + RegOffset);
#define XUartChanged_IsTransmitFull(BaseAddress) \
((Xil_In32((BaseAddress) + 0x2C) & \
0x10) == 0x10)
void wait_ms(unsigned int time);
void init_platform();
void cleanup_platform();
void ChangedPrint(char *ptr);
void timer_init();
void tic();
void toc();
u64 elapsed_time_us();
#endif
| malkadi/FGPU | benchmark/MicroBlaze/src/platform.hpp | C++ | gpl-3.0 | 818 |
import platform
import glob
from .io import DxlIO, Dxl320IO, DxlError
from .error import BaseErrorHandler
from .controller import BaseDxlController
from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor
from ..robot import Robot
def _get_available_ports():
""" Tries to find the available usb2serial port on your system. """
if platform.system() == 'Darwin':
return glob.glob('/dev/tty.usb*')
elif platform.system() == 'Linux':
return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*')
elif platform.system() == 'Windows':
import _winreg
import itertools
ports = []
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)
for i in itertools.count():
try:
ports.append(str(_winreg.EnumValue(key, i)[1]))
except WindowsError:
return ports
return []
def get_available_ports(only_free=False):
ports = _get_available_ports()
if only_free:
ports = list(set(ports) - set(DxlIO.get_used_ports()))
return ports
def find_port(ids, strict=True):
""" Find the port with the specified attached motor ids.
:param list ids: list of motor ids to find
:param bool strict: specify if all ids should be find (when set to False, only half motor must be found)
.. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
"""
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
try:
with DxlIOCls(port) as dxl:
founds = len(dxl.scan(ids))
if strict and founds == len(ids):
return port
if not strict and founds >= len(ids) / 2:
return port
except DxlError:
continue
raise IndexError('No suitable port found for ids {}!'.format(ids))
def autodetect_robot():
""" Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """
motor_controllers = []
for port in get_available_ports():
for DxlIOCls in (DxlIO, Dxl320IO):
dxl_io = DxlIOCls(port)
ids = dxl_io.scan()
if not ids:
dxl_io.close()
continue
models = dxl_io.get_model(ids)
motorcls = {
'MX': DxlMXMotor,
'RX': DxlAXRXMotor,
'AX': DxlAXRXMotor,
'XL': DxlXL320Motor
}
motors = [motorcls[model[:2]](id, model=model)
for id, model in zip(ids, models)]
c = BaseDxlController(dxl_io, motors)
motor_controllers.append(c)
return Robot(motor_controllers)
| manon-cortial/pypot | pypot/dynamixel/__init__.py | Python | gpl-3.0 | 2,888 |
/* -----------------------------------------------------------------------------
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 ppm_java._dev.concept.example.event;
import ppm_java.backend.TController;
import ppm_java.typelib.IControllable;
import ppm_java.typelib.IEvented;
import ppm_java.typelib.VBrowseable;
/**
*
*/
class TSink extends VBrowseable implements IEvented, IControllable
{
public TSink (String id)
{
super (id);
}
public void OnEvent (int e, String arg0)
{
String msg;
msg = GetID () + ": " + "Received messaging event. Message: " + arg0;
System.out.println (msg);
}
public void Start () {/* Do nothing */}
public void Stop () {/* Do nothing */}
public void OnEvent (int e) {/* Do nothing */}
public void OnEvent (int e, int arg0) {/* Do nothing */}
public void OnEvent (int e, long arg0) {/* Do nothing */}
protected void _Register ()
{
TController.Register (this);
}
}
| ustegrew/ppm-java | src/ppm_java/_dev/concept/example/event/TSink.java | Java | gpl-3.0 | 1,733 |
<?php
// This file is part of VPL for Moodle - http://vpl.dis.ulpgc.es/
//
// VPL for 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.
//
// VPL for 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 VPL for Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Class to show two files diff
*
* @package mod_vpl
* @copyright 2012 Juan Carlos Rodríguez-del-Pino
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Juan Carlos Rodríguez-del-Pino <jcrodriguez@dis.ulpgc.es>
*/
require_once dirname(__FILE__).'/../../../config.php';
require_once dirname(__FILE__).'/../locallib.php';
require_once dirname(__FILE__).'/../vpl.class.php';
require_once dirname(__FILE__).'/../vpl_submission.class.php';
require_once dirname(__FILE__).'/../views/sh_base.class.php';
require_once dirname(__FILE__).'/similarity_factory.class.php';
require_once dirname(__FILE__).'/similarity_base.class.php';
class vpl_diff{
/**
* Remove chars and digits
* @param $line string to process
* @return string without chars and digits
*/
static function removeAlphaNum($line){
$ret='';
$l= strlen($line);
//Parse line to remove alphanum chars
for($i=0; $i<$l; $i++){
$c=$line[$i];
if(!ctype_alnum($c) && $c != ' '){
$ret.=$c;
}
}
return $ret;
}
/**
* Calculate the similarity of two lines
* @param $line1
* @param $line2
* @return int (3 => trimmed equal, 2 =>removeAlphaNum , 1 => start of line , 0 => not equal)
*/
static function diffLine($line1,$line2){
//TODO Refactor.
//This is a bad solution that must be rebuild to consider diferent languages
//Compare trimed text
$line1=trim($line1);
$line2=trim($line2);
if($line1==$line2){
if(strlen($line1)>0){
return 3;
}else{
return 1;
}
}
//Compare filtered text (removing alphanum)
$rAN1=self::removeAlphaNum($line1);
$limit = strlen($rAN1);
if($limit>0){
if($limit>3){
$limite = 3;
}
if(strncmp($rAN1,self::removeAlphaNum($line2),$limit) == 0){
return 2;
}
}
//Compare start of line
$l=4;
if($l>strlen($line1)){
$l=strlen($line1);
}
if($l>strlen($line2)){
$l=strlen($line2);
}
for($i=0; $i<$l; ++$i){
if($line1[$i] !=$line2[$i]){
break;
}
}
return $i>0 ? 1:0;
}
static function newLineInfo($type,$ln1,$ln2=0){
$ret = new StdClass();
$ret->type = $type;
$ret->ln1 = $ln1;
$ret->ln2 = $ln2;
return $ret;
}
/**
* Initialize used matrix
* @param $matrix matrix to initialize
* @param $prev matrix to initialize
* @param $nl1 number of rows
* @param $nl2 number of columns
* @return void
*/
static function initAuxiliarMatrices(&$matrix,&$prev,$nl1,$nl2){
// matrix[0..nl1+1][0..nl2+1]=0
$row = array_pad(array(),$nl2+1,0);
$matrix = array_pad(array(),$nl1+1,$row);
// prev[0..nl1+1][0..nl2+1]=0
$prev = $matrix;
//update first column
for($i=0; $i<=$nl1;$i++){
$matriz[$i][0]=0;
$prev[$i][0]=-1;
}
//update first row
for($j=1; $j<=$nl2;$j++){
$matriz[0][$j]=0;
$prev[0][$j]=1;
}
}
/**
* Calculate diff for two array of lines
* @param $lines1 array of string
* @param $lines2 array of string
* @return array of objects with info to show the two array of lines
*/
static function calculateDiff($lines1,$lines2){
$ret = array();
$nl1=count($lines1);
$nl2=count($lines2);
if($nl1==0 && $nl2==0){
return false;
}
if($nl1==0){ //There is no first file
foreach($lines2 as $pos => $line){
$ret[] = self::newLineInfo('>',0,$pos+1);
}
return $ret;
}
if($nl2==0){ //There is no second file
foreach($lines1 as $pos => $line){
$ret[] = self::newLineInfo('<',$pos+1);
}
return $ret;
}
self::initAuxiliarMatrices($matrix,$prev,$nl1,$nl2);
//Matrix processing
for($i=1; $i <= $nl1;$i++){
$line=$lines1[$i-1];
for($j=1; $j<=$nl2;$j++){
if($matrix[$i][$j-1]>$matrix[$i-1][$j]) {
$max=$matrix[$i][$j-1];
$best = 1;
}else{
$max=$matrix[$i-1][$j];
$best = -1;
}
$prize=self::diffLine($line,$lines2[$j-1]);
if($matrix[$i-1][$j-1]+$prize>=$max){
$max=$matrix[$i-1][$j-1]+$prize;
$best = 0;
}
$matrix[$i][$j]=$max;
$prev[$i][$j]=$best;
}
}
//Calculate show info
$limit=$nl1+$nl2;
$pairs = array();
$pi=$nl1;
$pj=$nl2;
while((!($pi == 0 && $pj == 0)) && $limit>0){
$pair = new stdClass();
$pair->i = $pi;
$pair->j = $pj;
$pairs[]=$pair;
$p = $prev[$pi][$pj];
if($p == 0){
$pi--;
$pj--;
}elseif($p == -1){
$pi--;
}else{
$pj--;
}
$limit--;
}
krsort($pairs);
$prevpair = new stdClass();
$prevpair->i=0;
$prevpair->j=0;
foreach($pairs as $pair){
if($pair->i == $prevpair->i+1 && $pair->j == $prevpair->j+1){ //Regular advance
if($lines1[$pair->i-1] == $lines2[$pair->j-1]){ //Equals
$ret[]=self::newLineInfo('=',$pair->i,$pair->j);
}else{
$ret[]=self::newLineInfo('#',$pair->i,$pair->j);
}
}elseif($pair->i == $prevpair->i+1){ //Removed next line
$ret[]=self::newLineInfo('<',$pair->i);
}elseif($pair->j == $prevpair->j+1){ //Added one line
$ret[]=self::newLineInfo('>',0,$pair->j);
}else{
debugging("Internal error ".print_r($pair,true)." ".print_r($prevpair,true));
}
$prevpair=$pair;
}
return $ret;
}
static function show($filename1, $data1, $HTMLheader1, $filename2, $data2, $HTMLheader2) {
//Get file lines
$nl = vpl_detect_newline($data1);
$lines1 = explode($nl,$data1);
$nl = vpl_detect_newline($data2);
$lines2 = explode($nl,$data2);
//Get dif as an array of info
$diff = self::calculateDiff($lines1,$lines2);
if($diff === false){
return;
}
$separator= array('<'=>' <<< ', '>'=>' >>> ','='=>' === ','#'=>' ### ');
$emptyline=" \n";
$data1='';
$data2='';
$datal1='';
$datal2='';
$diffl='';
$lines1[-1]='';
$lines2[-1]='';
foreach($diff as $line){
$diffl.= $separator[$line->type]."\n";
if($line->ln1){
$datal1.=$line->ln1." \n";
$data1.=$lines1[$line->ln1-1]."\n";
}else{
$data1.=" \n";
$datal1.=$emptyline;
}
if($line->ln2){
$datal2.=$line->ln2." \n";
$data2.=$lines2[$line->ln2-1]."\n";
}else{
$data2.=" \n";
$datal2.=$emptyline;
}
}
echo '<div style="width: 100%;min-width: 950px; overflow: auto">';
//Header
echo '<div style="float:left; width: 445px">';
echo $HTMLheader1;
echo '</div>';
echo '<div style="float:left; width: 445px">';
echo $HTMLheader2;
echo '</div>';
echo '<div style="clear:both;"></div>';
//Files
echo '<div style="float:left; text-align: right">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $datal1;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; width: 390px; overflow:auto">';
$shower= vpl_sh_factory::get_sh($filename1);
$shower->print_file($filename1,$data1,false);
echo '</div>';
echo '<div style="float:left">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $diffl;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; text-align: right;">';
echo '<pre class="'.vpl_sh_base::c_general.'">';
echo $datal2;
echo '</pre>';
echo '</div>';
echo '<div style="float:left; width: 390px; overflow:auto">';
$shower= vpl_sh_factory::get_sh($filename2);
$shower->print_file($filename2,$data2,false);
echo '</div>';
echo '</div>';
echo '<div style="clear:both;"></div>';
}
static function vpl_get_similfile($f,$vpl,&$HTMLheader,&$filename,&$data){
global $DB;
$HTMLheader='';
$filename='';
$data='';
$type = required_param('type'.$f, PARAM_INT);
if($type==1){
$subid = required_param('subid'.$f, PARAM_INT);
$filename = required_param('filename'.$f, PARAM_TEXT);
$subinstance = $DB->get_record('vpl_submissions',array('id' => $subid));
if($subinstance !== false){
$vpl = new mod_vpl(false,$subinstance->vpl);
$vpl->require_capability(VPL_SIMILARITY_CAPABILITY);
$submission = new mod_vpl_submission($vpl,$subinstance);
$user = $DB->get_record('user', array('id' => $subinstance->userid));
if($user){
$HTMLheader .='<a href="'.vpl_mod_href('/forms/submissionview.php',
'id',$vpl->get_course_module()->id,'userid',$subinstance->userid).'">';
}
$HTMLheader .=s($filename).' ';
if($user){
$HTMLheader .= '</a>';
$HTMLheader .= $vpl->user_fullname_picture($user);
}
$fg = $submission->get_submitted_fgm();
$data = $fg->getFileData($filename);
\mod_vpl\event\vpl_diff_viewed::log($submission);
}
}elseif($type == 2){
//FIXME adapt to moodle 2.x
/*
global $CFG;
$dirname = required_param('dirname'.$f,PARAM_RAW);
$filename = required_param('filename'.$f,PARAM_RAW);
$base=$CFG->dataroot.'/'.$vpl->get_course()->id.'/';
$data = file_get_contents($base.$dirname.'/'.$filename);
$HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT);
*/
}elseif($type == 3){
global $CFG;
$data='';
$zipname = required_param('zipfile'.$f,PARAM_RAW);
$filename = required_param('filename'.$f,PARAM_RAW);
$HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT);
$ext = strtoupper(pathinfo($zipfile,PATHINFO_EXTENSION));
if($ext != 'ZIP'){
print_error('nozipfile');
}
$zip = new ZipArchive();
$zipfilename=self::get_zip_filepath($zipname);
if($zip->open($zipfilename)){
$data=$zip->getFromName($filename);
$zip->close();
}
}else{
print_error('type error');
}
}
}
| InstaLearn/phonegaptest3 | mod/vpl/similarity/diff.class.php | PHP | gpl-3.0 | 12,386 |
package org.runnerup.notification;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import org.runnerup.R;
import org.runnerup.common.util.Constants;
import org.runnerup.view.MainLayout;
@TargetApi(Build.VERSION_CODES.FROYO)
public class GpsBoundState implements NotificationState {
private final Notification notification;
public GpsBoundState(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent i = new Intent(context, MainLayout.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.putExtra(Constants.Intents.FROM_NOTIFICATION, true);
PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
builder.setContentIntent(pi);
builder.setContentTitle(context.getString(R.string.activity_ready));
builder.setContentText(context.getString(R.string.ready_to_start_running));
builder.setSmallIcon(R.drawable.icon);
builder.setOnlyAlertOnce(true);
org.runnerup.util.NotificationCompat.setLocalOnly(builder);
notification = builder.build();
}
@Override
public Notification createNotification() {
return notification;
}
}
| netmackan/runnerup | app/src/org/runnerup/notification/GpsBoundState.java | Java | gpl-3.0 | 1,443 |
package pl.idedyk.japanese.dictionary.web.html;
import java.util.List;
public class Ul extends HtmlElementCommon {
public Ul() {
super();
}
public Ul(String clazz) {
super(clazz);
}
public Ul(String clazz, String style) {
super(clazz, style);
}
@Override
protected String getTagName() {
return "ul";
}
@Override
protected boolean isSupportHtmlElementList() {
return true;
}
@Override
protected List<String[]> getAdditionalTagAttributes() {
return null;
}
}
| dedyk/JapaneseDictionaryWeb | src/main/java/pl/idedyk/japanese/dictionary/web/html/Ul.java | Java | gpl-3.0 | 502 |
<?php
/* checklinks.class.php ver.1.1
** Author: Jason Henry www.yourarcadescript.com
** Please keep authorship info intact
** Nov. 26, 2011
**
** Class is used to validate that a link exists on a given web page
** Usage example:
** include("checklinks.class.php");
** $checklink = new checkLink;
** $response = $checklink->validateLink("www.website.com/links.html", "www.mywebsite.com");
** $response will be: LINKDATAERROR(means unable to get data from the website) or LINKFOUND or LINKNOTFOUND or LINKFOUNDNOFOLLOW
** Updates in ver. 1.1
Added the port and path to the link choices to check allowing for a deep link search. Was returning a false negative.
*/
class checkLink {
const LINKFOUND = 1;
const LINKNOTFOUND = 0;
const LINKFOUNDNOFOLLOW = 2;
const LINKDATAERROR = 3;
public function get_data($url) {
$ch = curl_init();
$timeout = 5;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function linkChoices($link) {
$array = parse_url($link);
$link1 = $array['host'];
if (isset($array['port'])) {
$link1 .= ":" . $array['port'];
}
if (isset($array['path'])) {
$link1 .= $array['path'];
}
$links[0] = rtrim($link1,"/");
$links[1] = str_replace("www.", "", $links[0]);
$links[2] = "http://".trim($links[1]);
$links[3] = "http://www.".$links[1];
return $links;
}
public function validateLink($url, $url_tofind) {
$page = $this->get_data($url);
if (!$page) return LINKDATAERROR;
$urlchoices = $this->linkChoices($url_tofind);
$dom = new DOMDocument();
@$dom->loadHTML($page);
$x = new DOMXPath($dom);
foreach($x->query("//a") as $node) {
$link = rtrim($node->getAttribute("href"), "/");
$rel = $node->getAttribute("rel");
if (in_array($link, $urlchoices)) {
if(strtolower($rel) == "nofollow") {
return LINKFOUNDNOFOLLOW;
} else {
return LINKFOUND;
}
}
}
return LINKNOTFOUND;
}
}
?> | Yourarcadescript/Version-2.5.2 | includes/checklinks.class.php | PHP | gpl-3.0 | 2,197 |
"use strict";
function HelpTutorial()
{
let _getText = function()
{
return "HelpTutorial_Base";
};
this.getName = function(){ return "HelpTutorial_Base"; };
this.getImageId = function(){ return "button_help"; };
this.getText = _getText;
}
function HelpTutorialBuilding(name, image)
{
this.getName = function(){ return name; };
this.getImageId = function(){ return image; };
}
function HelpQueueData(colonyState)
{
let queue = [new HelpTutorial()];
let available = [];
let discovery = colonyState.getDiscovery();
for(let i = 0; i < discovery.length; i++)
{
if(discovery[i].startsWith("Resource_"))
{
queue.push(new HelpTutorialBuilding(discovery[i], discovery[i]));
}
}
let technology = colonyState.getTechnology();
for(let i = 0; i < technology.length; i++)
{
let item = PrototypeLib.get(technology[i]);
available.push(new HelpTutorialBuilding(technology[i], item.getBuildingImageId()));
}
QueueData.call(this, queue, available);
this.getInfo = function(item)
{
let text = "";
if(item != null)
{
let imgSize = GetImageSize(ImagesLib.getImage(item.getImageId()));
text += '<div class="queueInfo">';
if(item.getText != undefined)
{
text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">';
text += '<img class="queueInfoTitleImage" style="height: ' + imgSize.height + 'px;" src="' + ImagesLib.getFileName(item.getImageId()) + '">';
text += '<div class="queueInfoTitleData queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>';
text += '</div>';
text += '<div class="queueInfoDetails">' + TextRepository.get(item.getName() + "Description") + '</div>';
}
else
{
let baseImgSize = GetImageSize(ImagesLib.getImage("baseTile"));
text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">';
text += '<div style="float: left; height: ' + imgSize.height + 'px; background: url(\'' + ImagesLib.getFileName("baseTile") + '\') no-repeat; background-position: 0 ' + (imgSize.height - baseImgSize.height) + 'px;">';
text += '<img style="height: ' + imgSize.height + 'px; border-size: 0;" src="' + ImagesLib.getFileName(item.getImageId()) + '">';
text += '</div>';
text += '<div class="queueInfoTitleData">';
text += '<div class="queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>';
text += '<div class="queueInfoTitleDescription">' + TextRepository.get(item.getName() + "Description") + '</div>';
text += '</div>';
text += '</div>';
text += '<div class="queueInfoDetails">';
let proto = PrototypeLib.get(item.getName());
text += '<table>';
text += '<tr><td class="tableMainColumn">' + TextRepository.get("TerrainLayer") + ':</td><td></td><td>' + TextRepository.get(proto.getTerrainLayer()) + '</td></tr>';
let list;
let listItem;
if(proto.getBuildingTime() > 0 || Object.keys(proto.getBuildingCost()).length > 0)
{
//text += '<tr><td>' + TextRepository.get("BuildingTitle") + '</td></tr>';
text += '<tr><td>' + TextRepository.get("BuildingTime") + ':</td><td class="tableDataRight">' + proto.getBuildingTime() + '</td><td>' + TextRepository.get("TimeUnit") + '</td></tr>';
list = proto.getBuildingCost();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingCost") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td>';
if(list[listItem] > colonyState.getProduced(listItem))
{
text += '<td class="colorError">' + TextRepository.get("unavailable") + '</td>';
}
text += '</tr>';
}
}
}
}
if(proto.getRequiredResource() != null)
{
text += '<tr><td>' + TextRepository.get("Requirements") + ':</td><td>' + TextRepository.get(proto.getRequiredResource()) + '</td></tr>';
}
list = proto.getCapacity();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingCapacity") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
if((Object.keys(proto.getConsumption()).length +
Object.keys(proto.getProduction()).length +
Object.keys(proto.getProductionWaste()).length) > 0)
{
//text += '<tr><td>' + TextRepository.get("ProductionTitle") + '</td></tr>';
list = proto.getConsumption();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingConsumption") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
list = proto.getProduction();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingProduction") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
list = proto.getProductionWaste();
if(Object.keys(list).length > 0)
{
text += '<tr><td>' + TextRepository.get("BuildingWaste") + ':</td></tr>';
for (listItem in list)
{
if(list.hasOwnProperty(listItem))
{
text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>';
}
}
}
}
text += '</table>';
text += '</div>';
}
text += '</div>';
}
return text;
};
this.isSortable = function() { return false; };
this.getTitle = function() { return "HelpTitle"; };
this.getQueueTitle = function() { return "HelpBase"; };
this.getAvailableTitle = function() { return "Buildings"; };
}
HelpQueueData.inherits(QueueData); | Hiperblade/OutpostTLH | script/ViewQueueHelp.js | JavaScript | gpl-3.0 | 6,371 |
public class Main {
public static void main(String[] args) {
ProdutoContext manga = new ProdutoContext();
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
manga.reestocar(5);
manga.fazerCompra(5);
manga.reestocar(15);
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
System.out.println("Quantia: " + manga.getQuantia());
}
}
| guilhermepo2/bcc | 2015-2/POO2 - Praticas/Pratica08-1 - State/src/Main.java | Java | gpl-3.0 | 402 |
using CatalokoService.Helpers.DTO;
using CatalokoService.Helpers.FacebookAuth;
using CatalokoService.Models;
using System;
using System.Web.Mvc;
namespace CatalokoService.Controllers
{
public class HomeController : Controller
{
CatalokoEntities bd = new CatalokoEntities();
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
}
| albertoroque/cataloko | service/CatalokoService/CatalokoService/Controllers/ClienteController/HomeController.cs | C# | gpl-3.0 | 439 |
var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function Data ( route ) {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
if( ! session.wiz ) {
session.wiz = {};
}
// Save route on this instance
this.route = route;
// Gather session from session, or just create a new one
this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} );
// Add a control variable for changed state
this.changed = false;
return this;
};
// Export Data
module.exports = Data;
/* instance methods */
Data.prototype.currentStep = function ( step ) {
// If there is no `step` provided, it means that we wan't to get!
// Otherwise, lets set it!
};
/*
Data.prototype.save = function () {
};
Data.prototype.destroy = function () {
};
*/
Data.prototype.getFromStep = function ( step ) {
};
| brunocasanova/emvici-router | lib/type/wizard/control.js | JavaScript | gpl-3.0 | 1,035 |
using System;
namespace RadarrAPI
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | jasonla/RadarrAPI.Update | src/RadarrAPI/Models/ErrorViewModel.cs | C# | gpl-3.0 | 200 |
/**
Copyright (C) 2012 Delcyon, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 com.delcyon.capo.protocol.server;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author jeremiah
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ClientRequestProcessorProvider
{
String name();
} | jahnje/delcyon-capo | java/com/delcyon/capo/protocol/server/ClientRequestProcessorProvider.java | Java | gpl-3.0 | 1,024 |
/*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* ClusterMembership.java
* Copyright (C) 2004 Mark Hall
*
*/
package weka.filters.unsupervised.attribute;
import weka.filters.Filter;
import weka.filters.UnsupervisedFilter;
import weka.filters.unsupervised.attribute.Remove;
import weka.clusterers.Clusterer;
import weka.clusterers.DensityBasedClusterer;
import weka.core.Attribute;
import weka.core.Instances;
import weka.core.Instance;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.FastVector;
import weka.core.Option;
import weka.core.Utils;
import java.util.Enumeration;
import java.util.Vector;
/**
* A filter that uses a clusterer to obtain cluster membership values
* for each input instance and outputs them as new instances. The
* clusterer needs to be a density-based clusterer. If
* a (nominal) class is set, then the clusterer will be run individually
* for each class.<p>
*
* Valid filter-specific options are: <p>
*
* Full class name of clusterer to use. Clusterer options may be
* specified at the end following a -- .(required)<p>
*
* -I range string <br>
* The range of attributes the clusterer should ignore. Note:
* the class attribute (if set) is automatically ignored during clustering.<p>
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author Eibe Frank
* @version $Revision: 1.7 $
*/
public class ClusterMembership extends Filter implements UnsupervisedFilter,
OptionHandler {
/** The clusterer */
protected DensityBasedClusterer m_clusterer = new weka.clusterers.EM();
/** Array for storing the clusterers */
protected DensityBasedClusterer[] m_clusterers;
/** Range of attributes to ignore */
protected Range m_ignoreAttributesRange;
/** Filter for removing attributes */
protected Filter m_removeAttributes;
/** The prior probability for each class */
protected double[] m_priors;
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input instance
* structure (any instances contained in the object are ignored - only the
* structure is required).
* @return true if the outputFormat may be collected immediately
* @exception Exception if the inputFormat can't be set successfully
*/
public boolean setInputFormat(Instances instanceInfo) throws Exception {
super.setInputFormat(instanceInfo);
m_removeAttributes = null;
m_priors = null;
return false;
}
/**
* Signify that this batch of input to the filter is finished.
*
* @return true if there are instances pending output
* @exception IllegalStateException if no input structure has been defined
*/
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (outputFormatPeek() == null) {
Instances toFilter = getInputFormat();
Instances[] toFilterIgnoringAttributes;
// Make subsets if class is nominal
if ((toFilter.classIndex() >= 0) && toFilter.classAttribute().isNominal()) {
toFilterIgnoringAttributes = new Instances[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i] = new Instances(toFilter, toFilter.numInstances());
}
for (int i = 0; i < toFilter.numInstances(); i++) {
toFilterIgnoringAttributes[(int)toFilter.instance(i).classValue()].add(toFilter.instance(i));
}
m_priors = new double[toFilter.numClasses()];
for (int i = 0; i < toFilter.numClasses(); i++) {
toFilterIgnoringAttributes[i].compactify();
m_priors[i] = toFilterIgnoringAttributes[i].sumOfWeights();
}
Utils.normalize(m_priors);
} else {
toFilterIgnoringAttributes = new Instances[1];
toFilterIgnoringAttributes[0] = toFilter;
m_priors = new double[1];
m_priors[0] = 1;
}
// filter out attributes if necessary
if (m_ignoreAttributesRange != null || toFilter.classIndex() >= 0) {
m_removeAttributes = new Remove();
String rangeString = "";
if (m_ignoreAttributesRange != null) {
rangeString += m_ignoreAttributesRange.getRanges();
}
if (toFilter.classIndex() >= 0) {
if (rangeString.length() > 0) {
rangeString += (","+(toFilter.classIndex()+1));
} else {
rangeString = ""+(toFilter.classIndex()+1);
}
}
((Remove)m_removeAttributes).setAttributeIndices(rangeString);
((Remove)m_removeAttributes).setInvertSelection(false);
((Remove)m_removeAttributes).setInputFormat(toFilter);
for (int i = 0; i < toFilterIgnoringAttributes.length; i++) {
toFilterIgnoringAttributes[i] = Filter.useFilter(toFilterIgnoringAttributes[i],
m_removeAttributes);
}
}
// build the clusterers
if ((toFilter.classIndex() <= 0) || !toFilter.classAttribute().isNominal()) {
m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, 1);
m_clusterers[0].buildClusterer(toFilterIgnoringAttributes[0]);
} else {
m_clusterers = DensityBasedClusterer.makeCopies(m_clusterer, toFilter.numClasses());
for (int i = 0; i < m_clusterers.length; i++) {
if (toFilterIgnoringAttributes[i].numInstances() == 0) {
m_clusterers[i] = null;
} else {
m_clusterers[i].buildClusterer(toFilterIgnoringAttributes[i]);
}
}
}
// create output dataset
FastVector attInfo = new FastVector();
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
for (int i = 0; i < m_clusterers[j].numberOfClusters(); i++) {
attInfo.addElement(new Attribute("pCluster_" + j + "_" + i));
}
}
}
if (toFilter.classIndex() >= 0) {
attInfo.addElement(toFilter.classAttribute().copy());
}
attInfo.trimToSize();
Instances filtered = new Instances(toFilter.relationName()+"_clusterMembership",
attInfo, 0);
if (toFilter.classIndex() >= 0) {
filtered.setClassIndex(filtered.numAttributes() - 1);
}
setOutputFormat(filtered);
// build new dataset
for (int i = 0; i < toFilter.numInstances(); i++) {
convertInstance(toFilter.instance(i));
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
/**
* Input an instance for filtering. Ordinarily the instance is processed
* and made available for output immediately. Some filters require all
* instances be read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @exception IllegalStateException if no input format has been defined.
*/
public boolean input(Instance instance) throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_NewBatch) {
resetQueue();
m_NewBatch = false;
}
if (outputFormatPeek() != null) {
convertInstance(instance);
return true;
}
bufferInput(instance);
return false;
}
/**
* Converts logs back to density values.
*/
protected double[] logs2densities(int j, Instance in) throws Exception {
double[] logs = m_clusterers[j].logJointDensitiesForInstance(in);
for (int i = 0; i < logs.length; i++) {
logs[i] += Math.log(m_priors[j]);
}
return logs;
}
/**
* Convert a single instance over. The converted instance is added to
* the end of the output queue.
*
* @param instance the instance to convert
*/
protected void convertInstance(Instance instance) throws Exception {
// set up values
double [] instanceVals = new double[outputFormatPeek().numAttributes()];
double [] tempvals;
if (instance.classIndex() >= 0) {
tempvals = new double[outputFormatPeek().numAttributes() - 1];
} else {
tempvals = new double[outputFormatPeek().numAttributes()];
}
int pos = 0;
for (int j = 0; j < m_clusterers.length; j++) {
if (m_clusterers[j] != null) {
double [] probs;
if (m_removeAttributes != null) {
m_removeAttributes.input(instance);
probs = logs2densities(j, m_removeAttributes.output());
} else {
probs = logs2densities(j, instance);
}
System.arraycopy(probs, 0, tempvals, pos, probs.length);
pos += probs.length;
}
}
tempvals = Utils.logs2probs(tempvals);
System.arraycopy(tempvals, 0, instanceVals, 0, tempvals.length);
if (instance.classIndex() >= 0) {
instanceVals[instanceVals.length - 1] = instance.classValue();
}
push(new Instance(instance.weight(), instanceVals));
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(2);
newVector.
addElement(new Option("\tFull name of clusterer to use (required).\n"
+ "\teg: weka.clusterers.EM",
"W", 1, "-W <clusterer name>"));
newVector.
addElement(new Option("\tThe range of attributes the clusterer should ignore."
+"\n\t(the class attribute is automatically ignored)",
"I", 1,"-I <att1,att2-att4,...>"));
return newVector.elements();
}
/**
* Parses the options for this object. Valid options are: <p>
*
* -W clusterer string <br>
* Full class name of clusterer to use. Clusterer options may be
* specified at the end following a -- .(required)<p>
*
* -I range string <br>
* The range of attributes the clusterer should ignore. Note:
* the class attribute (if set) is automatically ignored during clustering.<p>
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String clustererString = Utils.getOption('W', options);
if (clustererString.length() == 0) {
throw new Exception("A clusterer must be specified"
+ " with the -W option.");
}
setDensityBasedClusterer((DensityBasedClusterer)Utils.
forName(DensityBasedClusterer.class, clustererString,
Utils.partitionOptions(options)));
setIgnoredAttributeIndices(Utils.getOption('I', options));
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] clustererOptions = new String [0];
if ((m_clusterer != null) &&
(m_clusterer instanceof OptionHandler)) {
clustererOptions = ((OptionHandler)m_clusterer).getOptions();
}
String [] options = new String [clustererOptions.length + 5];
int current = 0;
if (!getIgnoredAttributeIndices().equals("")) {
options[current++] = "-I";
options[current++] = getIgnoredAttributeIndices();
}
if (m_clusterer != null) {
options[current++] = "-W";
options[current++] = getDensityBasedClusterer().getClass().getName();
}
options[current++] = "--";
System.arraycopy(clustererOptions, 0, options, current,
clustererOptions.length);
current += clustererOptions.length;
while (current < options.length) {
options[current++] = "";
}
return options;
}
/**
* Returns a string describing this filter
*
* @return a description of the filter suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "A filter that uses a density-based clusterer to generate cluster "
+ "membership values; filtered instances are composed of these values "
+ "plus the class attribute (if set in the input data). If a (nominal) "
+ "class attribute is set, the clusterer is run separately for each "
+ "class. The class attribute (if set) and any user-specified "
+ "attributes are ignored during the clustering operation";
}
/**
* Returns a description of this option suitable for display
* as a tip text in the gui.
*
* @return description of this option
*/
public String clustererTipText() {
return "The clusterer that will generate membership values for the instances.";
}
/**
* Set the clusterer for use in filtering
*
* @param newClusterer the clusterer to use
*/
public void setDensityBasedClusterer(DensityBasedClusterer newClusterer) {
m_clusterer = newClusterer;
}
/**
* Get the clusterer used by this filter
*
* @return the clusterer used
*/
public DensityBasedClusterer getDensityBasedClusterer() {
return m_clusterer;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String ignoredAttributeIndicesTipText() {
return "The range of attributes to be ignored by the clusterer. eg: first-3,5,9-last";
}
/**
* Gets ranges of attributes to be ignored.
*
* @return a string containing a comma-separated list of ranges
*/
public String getIgnoredAttributeIndices() {
if (m_ignoreAttributesRange == null) {
return "";
} else {
return m_ignoreAttributesRange.getRanges();
}
}
/**
* Sets the ranges of attributes to be ignored. If provided string
* is null, no attributes will be ignored.
*
* @param rangeList a string representing the list of attributes.
* eg: first-3,5,6-last
* @exception IllegalArgumentException if an invalid range list is supplied
*/
public void setIgnoredAttributeIndices(String rangeList) {
if ((rangeList == null) || (rangeList.length() == 0)) {
m_ignoreAttributesRange = null;
} else {
m_ignoreAttributesRange = new Range();
m_ignoreAttributesRange.setRanges(rangeList);
}
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter: use -h for help
*/
public static void main(String [] argv) {
try {
if (Utils.getFlag('b', argv)) {
Filter.batchFilterFile(new ClusterMembership(), argv);
} else {
Filter.filterFile(new ClusterMembership(), argv);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
| paolopavan/cfr | src/weka/filters/unsupervised/attribute/ClusterMembership.java | Java | gpl-3.0 | 15,028 |
/*
* This file is part of *** M y C o R e ***
* See http://www.mycore.de/ for details.
*
* MyCoRe 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.
*
* MyCoRe 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 MyCoRe. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mycore.util.concurrent;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
/**
* A supplier with a priority.
*
* <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a>
*
* @author Matthias Eichner
*
* @param <T> the type of results supplied by this supplier
*/
public class MCRPrioritySupplier<T> implements Supplier<T>, MCRPrioritizable {
private static AtomicLong CREATION_COUNTER = new AtomicLong(0);
private Supplier<T> delegate;
private int priority;
private long created;
public MCRPrioritySupplier(Supplier<T> delegate, int priority) {
this.delegate = delegate;
this.priority = priority;
this.created = CREATION_COUNTER.incrementAndGet();
}
@Override
public T get() {
return delegate.get();
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public long getCreated() {
return created;
}
/**
* use this instead of {@link CompletableFuture#supplyAsync(Supplier, Executor)}
*
* This method keep the priority
* @param es
* @return
*/
public CompletableFuture<T> runAsync(ExecutorService es) {
CompletableFuture<T> result = new CompletableFuture<>();
MCRPrioritySupplier<T> supplier = this;
class MCRAsyncPrioritySupplier
implements Runnable, MCRPrioritizable, CompletableFuture.AsynchronousCompletionTask {
@Override
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public void run() {
try {
if (!result.isDone()) {
result.complete(supplier.get());
}
} catch (Throwable t) {
result.completeExceptionally(t);
}
}
@Override
public int getPriority() {
return supplier.getPriority();
}
@Override
public long getCreated() {
return supplier.getCreated();
}
}
es.execute(new MCRAsyncPrioritySupplier());
return result;
}
}
| MyCoRe-Org/mycore | mycore-base/src/main/java/org/mycore/util/concurrent/MCRPrioritySupplier.java | Java | gpl-3.0 | 3,156 |
#include <iostream>
using namespace std;
int main() {
int n, x, y;
cin >> n;
int a[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
x = a[1] - a[0];
y = a[2] - a[0];
for (int i = 2; i < n; ++i) {
x = max(a[i] - a[i - 1], x);
y = min(a[i] - a[i - 2], y);
}
cout << max(x, y);
}
| yamstudio/Codeforces | 400/496A - Minimum Difficulty.cpp | C++ | gpl-3.0 | 309 |
<?php namespace PrivCode;
defined('ROOT_DIR') or die('Forbidden');
/**
* Base Model Class
*
* @package Priv Code
* @subpackage Libraries
* @category Libraries
* @author Supian M
* @link http://www.priv-code.com
*/
use PrivCode\Database\Database;
class BaseModel extends Database
{
public function __construct()
{
parent::__construct();
}
}
/* End of file URI.php */
/* Location: ./System/URI/URI.php */
| SupianID/Framework | System/BaseModel.php | PHP | gpl-3.0 | 438 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.power.text.Run;
import static com.power.text.dialogs.WebSearch.squerry;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JOptionPane;
import static com.power.text.Main.searchbox;
/**
*
* @author thecarisma
*/
public class WikiSearch {
public static void wikisearch(){
String searchqueryw = searchbox.getText();
searchqueryw = searchqueryw.replace(' ', '-');
String squeryw = squerry.getText();
squeryw = squeryw.replace(' ', '-');
if ("".equals(searchqueryw)){
searchqueryw = squeryw ;
} else {}
String url = "https://www.wikipedia.org/wiki/" + searchqueryw ;
try
{
URI uri = new URL(url).toURI();
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE))
desktop.browse(uri);
}
catch (URISyntaxException | IOException e)
{
/*
* I know this is bad practice
* but we don't want to do anything clever for a specific error
*/
JOptionPane.showMessageDialog(null, e.getMessage());
// Copy URL to the clipboard so the user can paste it into their browser
StringSelection stringSelection = new StringSelection(url);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
// Notify the user of the failure
System.out.println("This program just tried to open a webpage." + "\n"
+ "The URL has been copied to your clipboard, simply paste into your browser to accessWebpage: " + url);
}
}
}
| Thecarisma/powertext | Power Text/src/com/power/text/Run/WikiSearch.java | Java | gpl-3.0 | 2,201 |
/**
*
*/
package org.jbpt.pm.bpmn;
import org.jbpt.pm.IDataNode;
/**
* Interface class for BPMN Document.
*
* @author Cindy F�hnrich
*/
public interface IDocument extends IDataNode {
/**
* Marks this Document as list.
*/
public void markAsList();
/**
* Unmarks this Document as list.
*/
public void unmarkAsList();
/**
* Checks whether the current Document is a list.
* @return
*/
public boolean isList();
}
| BPT-NH/jpbt | jbpt-bpm/src/main/java/org/jbpt/pm/bpmn/IDocument.java | Java | gpl-3.0 | 447 |
#include <QtGui/QApplication>
#include "xmlparser.h"
#include "myfiledialog.h"
#include <iostream>
#include <QMessageBox>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);/*
MainWindow w;
w.show();*/
MyFileDialog my;//Create dialog
QString name=my.openFile();//Open dialog, and chose file. We get file path and file name as result
cout<<name.toUtf8().constData()<<"Podaci uspjeno uèitani!";
return 0;
}
| etf-sarajevo/etfimagesearch | XMLParser/main.cpp | C++ | gpl-3.0 | 512 |
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2004-2005 Steve Baker <sjbaker1@airmail.net>
// Copyright (C) 2006 Joerg Henrichs, Steve Baker
//
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_PLAYERKART_HPP
#define HEADER_PLAYERKART_HPP
#include "config/player.hpp"
#include "karts/controller/controller.hpp"
class AbstractKart;
class Player;
class SFXBase;
/** PlayerKart manages control events from the player and moves
* them to the Kart
*
* \ingroup controller
*/
class PlayerController : public Controller
{
private:
int m_steer_val, m_steer_val_l, m_steer_val_r;
int m_prev_accel;
bool m_prev_brake;
bool m_prev_nitro;
float m_penalty_time;
SFXBase *m_bzzt_sound;
SFXBase *m_wee_sound;
SFXBase *m_ugh_sound;
SFXBase *m_grab_sound;
SFXBase *m_full_sound;
void steer(float, int);
public:
PlayerController (AbstractKart *kart,
StateManager::ActivePlayer *_player,
unsigned int player_index);
~PlayerController ();
void update (float);
void action (PlayerAction action, int value);
void handleZipper (bool play_sound);
void collectedItem (const Item &item, int add_info=-1,
float previous_energy=0);
virtual void skidBonusTriggered();
virtual void setPosition (int p);
virtual void finishedRace (float time);
virtual bool isPlayerController() const {return true;}
virtual bool isNetworkController() const { return false; }
virtual void reset ();
void resetInputState ();
virtual void crashed (const AbstractKart *k) {}
virtual void crashed (const Material *m) {}
// ------------------------------------------------------------------------
/** Player will always be able to get a slipstream bonus. */
virtual bool disableSlipstreamBonus() const { return false; }
// ------------------------------------------------------------------------
/** Callback whenever a new lap is triggered. Used by the AI
* to trigger a recomputation of the way to use. */
virtual void newLap(int lap) {}
};
#endif
| langresser/stk | src/karts/controller/player_controller.hpp | C++ | gpl-3.0 | 3,156 |
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2019
// MIT License
#pragma once
#include "../Array/ArrayShortcuts.hpp"
#include "../Object/ObjectShortcuts.hpp"
namespace ARDUINOJSON_NAMESPACE {
template <typename TVariant>
class VariantShortcuts : public ObjectShortcuts<TVariant>,
public ArrayShortcuts<TVariant> {
public:
using ArrayShortcuts<TVariant>::createNestedArray;
using ArrayShortcuts<TVariant>::createNestedObject;
using ArrayShortcuts<TVariant>::operator[];
using ObjectShortcuts<TVariant>::createNestedArray;
using ObjectShortcuts<TVariant>::createNestedObject;
using ObjectShortcuts<TVariant>::operator[];
};
} // namespace ARDUINOJSON_NAMESPACE
| felipehfj/Arduino | libraries/ArduinoJson/src/ArduinoJson/Operators/VariantShortcuts.hpp | C++ | gpl-3.0 | 724 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SimpleDownload
{
public partial class Downloader : Form
{
public Downloader()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Download dn=new Download();
dn.DownloadFile(url.Text, @"c:\NewImages\");
}
}
}
| abdesslem/QuikDownloader | src/Downloader.cs | C# | gpl-3.0 | 618 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyDescription("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Case Design, Inc.")]
[assembly: AssemblyProduct("Case Free Report Groups by View for Revit 2017")]
[assembly: AssemblyCopyright("Copyright © Case Design, Inc. 2014")]
[assembly: AssemblyTrademark("Case Design, Inc.")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("372c7cb9-6d40-4880-91ff-16971c7e4661")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2014.6.2.0")]
[assembly: AssemblyFileVersion("2014.6.2.0")]
| kmorin/case-apps | 2017/Case.ReportGroupsByView/Case.ReportGroupsByView/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,571 |
<?php
/*
* Micrositio-Phoenix v1.0 Software para gestion de la planeación operativa.
* PHP v5
* Autor: Prof. Jesus Antonio Peyrano Luna <antonio.peyrano@live.com.mx>
* Nota aclaratoria: Este programa se distribuye bajo los terminos y disposiciones
* definidos en la GPL v3.0, debidamente incluidos en el repositorio original.
* Cualquier copia y/o redistribucion del presente, debe hacerse con una copia
* adjunta de la licencia en todo momento.
* Licencia: http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
header('Content-Type: text/html; charset=iso-8859-1'); //Forzar la codificación a ISO-8859-1.
$sufijo= "col_";
echo ' <html>
<link rel= "stylesheet" href= "./css/queryStyle.css"></style>
<div id="paginado" style="display:none">
<input id="pagina" type="text" value="1">
<input id="pgcolonia" type="text" value="">
<input id="pgestado" type="text" value="">
<input id="pgciudad" type="text" value="">
<input id="pgcp" type="text" value="">
</div>
<center><div id= "divbusqueda">
<form id="frmbusqueda" method="post" action="">
<table class="queryTable" colspan= "7">
<tr><td class= "queryRowsnormTR" width ="180">Por nombre de la colonia: </td><td class= "queryRowsnormTR" width ="250"><input type= "text" id= "nomcolonia"></td><td rowspan= "4"><img id="'.$sufijo.'buscar" align= "left" src= "./img/grids/view.png" width= "25" height= "25" alt="Buscar"/></td></tr>
<tr><td class= "queryRowsnormTR">Por codigo postal: </td><td class= "queryRowsnormTR"><input type= "text" id= "cpcolonia"></td><td></td></tr>
<tr><td class= "queryRowsnormTR">Por ciudad: </td><td class= "queryRowsnormTR"><input type= "text" id= "ciucolonia"></td><td></td></tr>
<tr><td class= "queryRowsnormTR">Por estado: </td><td class= "queryRowsnormTR"><input type= "text" id= "estcolonia"></td><td></td></tr>
</table>
</form>
</div></center>';
echo '<div id= "busRes">';
include_once("catColonias.php");
echo '</div>
</html>';
?> | antonio-peyrano/micrositio | v1.1.0/php/frontend/colonias/busColonias.php | PHP | gpl-3.0 | 2,393 |
from numpy import sqrt
from pacal.standard_distr import NormalDistr, ChiSquareDistr
from pacal.distr import Distr, SumDistr, DivDistr, InvDistr
from pacal.distr import sqrt as distr_sqrt
class NoncentralTDistr(DivDistr):
def __init__(self, df = 2, mu = 0):
d1 = NormalDistr(mu, 1)
d2 = distr_sqrt(ChiSquareDistr(df) / df)
super(NoncentralTDistr, self).__init__(d1, d2)
self.df = df
self.mu = mu
def __str__(self):
return "NoncentralTDistr(df={0},mu={1})#{2}".format(self.df, self.mu, self.id())
def getName(self):
return "NoncT({0},{1})".format(self.df, self.mu)
class NoncentralChiSquareDistr(SumDistr):
def __new__(cls, df, lmbda = 0):
assert df >= 1
d1 = NormalDistr(sqrt(lmbda))**2
if df == 1:
return d1
d2 = ChiSquareDistr(df - 1)
ncc2 = super(NoncentralChiSquareDistr, cls).__new__(cls, d1, d2)
super(NoncentralChiSquareDistr, ncc2).__init__(d1, d2)
ncc2.df = df
ncc2.lmbda = lmbda
return ncc2
def __init__(self, df, lmbda = 0):
pass
def __str__(self):
return "NoncentralChiSquare(df={0},lambda={1})#{2}".format(self.df, self.lmbda, self.id())
def getName(self):
return "NoncChi2({0},{1})".format(self.df, self.lmbda)
class NoncentralBetaDistr(InvDistr):
def __init__(self, alpha = 1, beta = 1, lmbda = 0):
d = 1 + ChiSquareDistr(2.0 * beta) / NoncentralChiSquareDistr(2 * alpha, lmbda)
super(NoncentralBetaDistr, self).__init__(d)
self.alpha = alpha
self.beta = beta
self.lmbda = lmbda
def __str__(self):
return "NoncentralBetaDistr(alpha={0},beta={1},lambda={2})#{3}".format(self.alpha, self.beta, self.lmbda, self.id())
def getName(self):
return "NoncBeta({0},{1},{2})".format(self.alpha, self.beta, self.lmbda)
class NoncentralFDistr(DivDistr):
def __init__(self, df1 = 1, df2 = 1, lmbda = 0):
d1 = NoncentralChiSquareDistr(df1, lmbda) / df1
d2 = ChiSquareDistr(df2) / df2
super(NoncentralFDistr, self).__init__(d1, d2)
self.df1 = df1
self.df2 = df2
self.lmbda = lmbda
def __str__(self):
return "NoncentralFDistr(df1={0},df2={1},lambda={2})#{3}".format(self.df1, self.df2, self.lmbda, self.id())
def getName(self):
return "NoncF({0},{1},{2})".format(self.df1, self.df2, self.lmbda)
| ianmtaylor1/pacal | pacal/stats/noncentral_distr.py | Python | gpl-3.0 | 2,437 |
IWitness.ErrorsView = Ember.View.extend({
classNames: ["error-bubble"],
classNameBindings: ["isError"],
isError: function() {
return !!this.get("error");
}.property("error")
});
| djacobs/iWitness | app/views/errors_view.js | JavaScript | gpl-3.0 | 198 |
/*
* Copyright 2008-2013, ETH Zürich, Samuel Welten, Michael Kuhn, Tobias Langner,
* Sandro Affentranger, Lukas Bossard, Michael Grob, Rahul Jain,
* Dominic Langenegger, Sonia Mayor Alonso, Roger Odermatt, Tobias Schlueter,
* Yannick Stucki, Sebastian Wendland, Samuel Zehnder, Samuel Zihlmann,
* Samuel Zweifel
*
* This file is part of Jukefox.
*
* Jukefox 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. Jukefox 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
* Jukefox. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.ethz.dcg.jukefox.model.collection;
public class MapTag extends BaseTag {
float[] coordsPca2D;
private float varianceOverPCA;
public MapTag(int id, String name, float[] coordsPca2D, float varianceOverPCA) {
super(id, name);
this.coordsPca2D = coordsPca2D;
this.varianceOverPCA = varianceOverPCA;
}
public float[] getCoordsPca2D() {
return coordsPca2D;
}
public float getVarianceOverPCA() {
return varianceOverPCA;
}
}
| kuhnmi/jukefox | JukefoxModel/src/ch/ethz/dcg/jukefox/model/collection/MapTag.java | Java | gpl-3.0 | 1,428 |
<?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/>.
/**
* Page to handle actions associated with badges management.
*
* @package core
* @subpackage badges
* @copyright 2012 onwards Corplms Learning Solutions Ltd {@link http://www.corplmslms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Yuliya Bozhko <yuliya.bozhko@corplmslms.com>
*/
require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->libdir . '/badgeslib.php');
$badgeid = required_param('id', PARAM_INT);
$copy = optional_param('copy', 0, PARAM_BOOL);
$activate = optional_param('activate', 0, PARAM_BOOL);
$deactivate = optional_param('lock', 0, PARAM_BOOL);
$confirm = optional_param('confirm', 0, PARAM_BOOL);
$return = optional_param('return', 0, PARAM_LOCALURL);
require_login();
$badge = new badge($badgeid);
$context = $badge->get_context();
$navurl = new moodle_url('/badges/index.php', array('type' => $badge->type));
if ($badge->type == BADGE_TYPE_COURSE) {
require_login($badge->courseid);
$navurl = new moodle_url('/badges/index.php', array('type' => $badge->type, 'id' => $badge->courseid));
$PAGE->set_pagelayout('standard');
navigation_node::override_active_url($navurl);
} else {
$PAGE->set_pagelayout('admin');
navigation_node::override_active_url($navurl, true);
}
$PAGE->set_context($context);
$PAGE->set_url('/badges/action.php', array('id' => $badge->id));
if ($return !== 0) {
$returnurl = new moodle_url($return);
} else {
$returnurl = new moodle_url('/badges/overview.php', array('id' => $badge->id));
}
$returnurl->remove_params('awards');
if ($copy) {
require_sesskey();
require_capability('moodle/badges:createbadge', $context);
$cloneid = $badge->make_clone();
// If a user can edit badge details, they will be redirected to the edit page.
if (has_capability('moodle/badges:configuredetails', $context)) {
redirect(new moodle_url('/badges/edit.php', array('id' => $cloneid, 'action' => 'details')));
}
redirect(new moodle_url('/badges/overview.php', array('id' => $cloneid)));
}
if ($activate) {
require_capability('moodle/badges:configurecriteria', $context);
$PAGE->url->param('activate', 1);
$status = ($badge->status == BADGE_STATUS_INACTIVE) ? BADGE_STATUS_ACTIVE : BADGE_STATUS_ACTIVE_LOCKED;
if ($confirm == 1) {
require_sesskey();
list($valid, $message) = $badge->validate_criteria();
if ($valid) {
$badge->set_status($status);
if ($badge->type == BADGE_TYPE_SITE) {
// Review on cron if there are more than 1000 users who can earn a site-level badge.
$sql = 'SELECT COUNT(u.id) as num
FROM {user} u
LEFT JOIN {badge_issued} bi
ON u.id = bi.userid AND bi.badgeid = :badgeid
WHERE bi.badgeid IS NULL AND u.id != :guestid AND u.deleted = 0';
$toearn = $DB->get_record_sql($sql, array('badgeid' => $badge->id, 'guestid' => $CFG->siteguest));
if ($toearn->num < 1000) {
$awards = $badge->review_all_criteria();
$returnurl->param('awards', $awards);
} else {
$returnurl->param('awards', 'cron');
}
} else {
$awards = $badge->review_all_criteria();
$returnurl->param('awards', $awards);
}
redirect($returnurl);
} else {
echo $OUTPUT->header();
echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . $message);
echo $OUTPUT->continue_button($returnurl);
echo $OUTPUT->footer();
die();
}
}
$strheading = get_string('reviewbadge', 'badges');
$PAGE->navbar->add($strheading);
$PAGE->set_title($strheading);
$PAGE->set_heading($badge->name);
echo $OUTPUT->header();
echo $OUTPUT->heading($strheading);
$params = array('id' => $badge->id, 'activate' => 1, 'sesskey' => sesskey(), 'confirm' => 1, 'return' => $return);
$url = new moodle_url('/badges/action.php', $params);
if (!$badge->has_criteria()) {
echo $OUTPUT->notification(get_string('error:cannotact', 'badges', $badge->name) . get_string('nocriteria', 'badges'));
echo $OUTPUT->continue_button($returnurl);
} else {
$message = get_string('reviewconfirm', 'badges', $badge->name);
echo $OUTPUT->confirm($message, $url, $returnurl);
}
echo $OUTPUT->footer();
die;
}
if ($deactivate) {
require_sesskey();
require_capability('moodle/badges:configurecriteria', $context);
$status = ($badge->status == BADGE_STATUS_ACTIVE) ? BADGE_STATUS_INACTIVE : BADGE_STATUS_INACTIVE_LOCKED;
$badge->set_status($status);
redirect($returnurl);
}
| mahalaxmi123/moodleanalytics | badges/action.php | PHP | gpl-3.0 | 5,588 |
/*
* Copyright (C) 2011 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
package de.ailis.microblinks.l.lctrl.shell;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.util.Arrays;
import de.ailis.microblinks.l.lctrl.resources.Resources;
/**
* Base class for all CLI programs.
*
* @author Klaus Reimer (k@ailis.de)
*/
public abstract class CLI
{
/** The command-line program name. */
private final String name;
/** The short options. */
private final String shortOpts;
/** The long options. */
private final LongOpt[] longOpts;
/** Debug mode. */
private boolean debug = false;
/**
* Constructor.
*
* @param name
* The command-line program name.
* @param shortOpts
* The short options.
* @param longOpts
* The long options.
*/
protected CLI(final String name, final String shortOpts, final LongOpt[] longOpts)
{
this.name = name;
this.shortOpts = shortOpts;
this.longOpts = longOpts;
}
/**
* Displays command-line help.
*/
private void showHelp()
{
System.out.println(Resources.getText("help.txt"));
}
/**
* Displays version information.
*/
private void showVersion()
{
System.out.println(Resources.getText("version.txt"));
}
/**
* Displays the help hint.
*/
protected void showHelpHint()
{
System.out.println("Use --help to show usage information.");
}
/**
* Prints error message to stderr and then exits with error code 1.
*
* @param message
* The error message.
* @param args
* The error message arguments.
*/
protected void error(final String message, final Object... args)
{
System.err.print(this.name);
System.err.print(": ");
System.err.format(message, args);
System.err.println();
showHelpHint();
System.exit(1);
}
/**
* Processes all command line options.
*
* @param args
* The command line arguments.
* @throws Exception
* When error occurs.
* @return The index of the first non option argument.
*/
private int processOptions(final String[] args) throws Exception
{
final Getopt opts = new Getopt(this.name, args, this.shortOpts, this.longOpts);
int opt;
while ((opt = opts.getopt()) >= 0)
{
switch (opt)
{
case 'h':
showHelp();
System.exit(0);
break;
case 'V':
showVersion();
System.exit(0);
break;
case 'D':
this.debug = true;
break;
case '?':
showHelpHint();
System.exit(111);
break;
default:
processOption(opt, opts.getOptarg());
}
}
return opts.getOptind();
}
/**
* Processes a single option.
*
* @param option
* The option to process
* @param arg
* The optional option argument
* @throws Exception
* When an error occurred.
*/
protected abstract void processOption(final int option, final String arg) throws Exception;
/**
* Executes the program with the specified arguments. This is called from the run() method after options has been
* processed. The specified arguments array only contains the non-option arguments.
*
* @param args
* The non-option command-line arguments.
* @throws Exception
* When something goes wrong.
*/
protected abstract void execute(String[] args) throws Exception;
/**
* Runs the program.
*
* @param args
* The command line arguments.
*/
public void run(final String[] args)
{
try
{
final int commandStart = processOptions(args);
execute(Arrays.copyOfRange(args, commandStart, args.length));
}
catch (final Exception e)
{
if (this.debug)
{
e.printStackTrace(System.err);
}
error(e.getMessage());
System.exit(1);
}
}
/**
* Checks if program runs in debug mode.
*
* @return True if debug mode, false if not.
*/
public boolean isDebug()
{
return this.debug;
}
}
| microblinks/lctrl | src/main/java/de/ailis/microblinks/l/lctrl/shell/CLI.java | Java | gpl-3.0 | 4,729 |
/************************************************************************
**
** @file vistoolspline.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 18 8, 2014
**
** @brief
** @copyright
** This source code is part of the Valentina project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2013-2015 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina 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.
**
** Valentina 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 Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "vistoolspline.h"
#include <QLineF>
#include <QPainterPath>
#include <QSharedPointer>
#include <Qt>
#include <new>
#include "../ifc/ifcdef.h"
#include "../vgeometry/vabstractcurve.h"
#include "../vgeometry/vgeometrydef.h"
#include "../vgeometry/vpointf.h"
#include "../vgeometry/vspline.h"
#include "../vpatterndb/vcontainer.h"
#include "../vwidgets/vcontrolpointspline.h"
#include "../vwidgets/scalesceneitems.h"
#include "../visualization.h"
#include "vispath.h"
#include "../vmisc/vmodifierkey.h"
const int EMPTY_ANGLE = -1;
//---------------------------------------------------------------------------------------------------------------------
VisToolSpline::VisToolSpline(const VContainer *data, QGraphicsItem *parent)
: VisPath(data, parent),
object4Id(NULL_ID),
point1(nullptr),
point4(nullptr),
angle1(EMPTY_ANGLE),
angle2(EMPTY_ANGLE),
kAsm1(1),
kAsm2(1),
kCurve(1),
isLeftMousePressed(false),
p2Selected(false),
p3Selected(false),
p2(),
p3(),
controlPoints()
{
point1 = InitPoint(supportColor, this);
point4 = InitPoint(supportColor, this); //-V656
auto *controlPoint1 = new VControlPointSpline(1, SplinePointPosition::FirstPoint, this);
controlPoint1->hide();
controlPoints.append(controlPoint1);
auto *controlPoint2 = new VControlPointSpline(1, SplinePointPosition::LastPoint, this);
controlPoint2->hide();
controlPoints.append(controlPoint2);
}
//---------------------------------------------------------------------------------------------------------------------
VisToolSpline::~VisToolSpline()
{
emit ToolTip(QString());
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::RefreshGeometry()
{
//Radius of point circle, but little bigger. Need handle with hover sizes.
const static qreal radius = ScaledRadius(SceneScale(qApp->getCurrentScene()))*1.5;
if (object1Id > NULL_ID)
{
const auto first = Visualization::data->GeometricObject<VPointF>(object1Id);
DrawPoint(point1, static_cast<QPointF>(*first), supportColor);
if (mode == Mode::Creation)
{
if (isLeftMousePressed && not p2Selected)
{
p2 = Visualization::scenePos;
controlPoints[0]->RefreshCtrlPoint(1, SplinePointPosition::FirstPoint, p2,
static_cast<QPointF>(*first));
if (not controlPoints[0]->isVisible())
{
if (QLineF(static_cast<QPointF>(*first), p2).length() > radius)
{
controlPoints[0]->show();
}
else
{
p2 = static_cast<QPointF>(*first);
}
}
}
else
{
p2Selected = true;
}
}
if (object4Id <= NULL_ID)
{
VSpline spline(*first, p2, Visualization::scenePos, VPointF(Visualization::scenePos));
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap);
}
else
{
const auto second = Visualization::data->GeometricObject<VPointF>(object4Id);
DrawPoint(point4, static_cast<QPointF>(*second), supportColor);
if (mode == Mode::Creation)
{
if (isLeftMousePressed && not p3Selected)
{
QLineF ctrlLine (static_cast<QPointF>(*second), Visualization::scenePos);
ctrlLine.setAngle(ctrlLine.angle()+180);
p3 = ctrlLine.p2();
controlPoints[1]->RefreshCtrlPoint(1, SplinePointPosition::LastPoint, p3,
static_cast<QPointF>(*second));
if (not controlPoints[1]->isVisible())
{
if (QLineF(static_cast<QPointF>(*second), p3).length() > radius)
{
controlPoints[1]->show();
}
else
{
p3 = static_cast<QPointF>(*second);
}
}
}
else
{
p3Selected = true;
}
}
if (VFuzzyComparePossibleNulls(angle1, EMPTY_ANGLE) || VFuzzyComparePossibleNulls(angle2, EMPTY_ANGLE))
{
VSpline spline(*first, p2, p3, *second);
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), mainColor, lineStyle, Qt::RoundCap);
}
else
{
VSpline spline(*first, *second, angle1, angle2, kAsm1, kAsm2, kCurve);
spline.SetApproximationScale(m_approximationScale);
DrawPath(this, spline.GetPath(), spline.DirectionArrows(), mainColor, lineStyle, Qt::RoundCap);
Visualization::toolTip = tr("Use <b>%1</b> for sticking angle!")
.arg(VModifierKey::Shift());
emit ToolTip(Visualization::toolTip);
}
}
}
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::setObject4Id(const quint32 &value)
{
object4Id = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetAngle1(const qreal &value)
{
angle1 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetAngle2(const qreal &value)
{
angle2 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKAsm1(const qreal &value)
{
kAsm1 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKAsm2(const qreal &value)
{
kAsm2 = value;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::SetKCurve(const qreal &value)
{
kCurve = value;
}
//---------------------------------------------------------------------------------------------------------------------
QPointF VisToolSpline::GetP2() const
{
return p2;
}
//---------------------------------------------------------------------------------------------------------------------
QPointF VisToolSpline::GetP3() const
{
return p3;
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::MouseLeftPressed()
{
if (mode == Mode::Creation)
{
isLeftMousePressed = true;
}
}
//---------------------------------------------------------------------------------------------------------------------
void VisToolSpline::MouseLeftReleased()
{
if (mode == Mode::Creation)
{
isLeftMousePressed = false;
RefreshGeometry();
}
}
| dismine/Valentina_git | src/libs/vtools/visualization/path/vistoolspline.cpp | C++ | gpl-3.0 | 8,739 |
from ert.cwrap import CWrapper, BaseCClass
from ert.enkf import ENKF_LIB
from ert.util import StringList
class SummaryKeyMatcher(BaseCClass):
def __init__(self):
c_ptr = SummaryKeyMatcher.cNamespace().alloc()
super(SummaryKeyMatcher, self).__init__(c_ptr)
def addSummaryKey(self, key):
assert isinstance(key, str)
return SummaryKeyMatcher.cNamespace().add_key(self, key)
def __len__(self):
return SummaryKeyMatcher.cNamespace().size(self)
def __contains__(self, key):
return SummaryKeyMatcher.cNamespace().match_key(self, key)
def isRequired(self, key):
""" @rtype: bool """
return SummaryKeyMatcher.cNamespace().is_required(self, key)
def keys(self):
""" @rtype: StringList """
return SummaryKeyMatcher.cNamespace().keys(self)
def free(self):
SummaryKeyMatcher.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("summary_key_matcher", SummaryKeyMatcher)
SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype("c_void_p summary_key_matcher_alloc()")
SummaryKeyMatcher.cNamespace().free = cwrapper.prototype("void summary_key_matcher_free(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().size = cwrapper.prototype("int summary_key_matcher_get_size(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype("void summary_key_matcher_add_summary_key(summary_key_matcher, char*)")
SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype("bool summary_key_matcher_match_summary_key(summary_key_matcher, char*)")
SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype("stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)")
SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype("bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)")
| iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/enkf/summary_key_matcher.py | Python | gpl-3.0 | 1,882 |
<?php
/**
* @module wysiwyg Admin
* @version see info.php of this module
* @authors Dietrich Roland Pehlke
* @copyright 2010-2011 Dietrich Roland Pehlke
* @license GNU General Public License
* @license terms see info.php of this module
* @platform see info.php of this module
* @requirements PHP 5.2.x and higher
*/
// include class.secure.php to protect this file and the whole CMS!
if (defined('WB_PATH')) {
include(WB_PATH.'/framework/class.secure.php');
} else {
$oneback = "../";
$root = $oneback;
$level = 1;
while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
$root .= $oneback;
$level += 1;
}
if (file_exists($root.'/framework/class.secure.php')) {
include($root.'/framework/class.secure.php');
} else {
trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
}
}
// end include class.secure.php
// end include class.secure.php
$database->query("DROP TABLE IF EXISTS `".TABLE_PREFIX."mod_editor_admin`");
$table = TABLE_PREFIX ."mod_wysiwyg_admin";
$database->query("DROP TABLE IF EXISTS `".$table."`");
$database->query("DELETE from `".TABLE_PREFIX."sections` where `section_id`='-1' AND `page_id`='-120'");
$database->query("DELETE from `".TABLE_PREFIX."mod_wysiwyg` where `section_id`='-1' AND `page_id`='-120'");
?> | LEPTON-project/LEPTON_1 | upload/modules/wysiwyg_admin/uninstall.php | PHP | gpl-3.0 | 1,358 |
#include <cmath>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include "params.h"
#include "pdg_name.h"
#include "parameters.h"
#include "LeptonMass.h"
//#include "jednostki.h"
#include "grv94_bodek.h"
#include "dis_cr_sec.h"
#include "fragmentation.h"
#include "vect.h"
#include "charge.h"
#include "event1.h"
#include <TMCParticle.h>
#include <TPythia6.h>
TPythia6 *pythia2 = new TPythia6 ();
extern "C" int pycomp_ (const int *);
void
dishadr (event & e, bool current, double hama, double entra)
{
////////////////////////////////////////////////////////////////////////////
// Setting Pythia parameters
// Done by Jaroslaw Nowak
//////////////////////////////////////////////
//stabilne pi0
pythia2->SetMDCY (pycomp_ (&pizero), 1, 0);
//C Thorpe: Adding Hyperons as stable dis particles
pythia2->SetMDCY (pycomp_ (&Lambda), 1, 0);
pythia2->SetMDCY (pycomp_ (&Sigma), 1, 0);
pythia2->SetMDCY (pycomp_ (&SigmaP), 1, 0);
pythia2->SetMDCY (pycomp_ (&SigmaM), 1, 0);
// C Thorpe: Stablize kaons
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kplus) , 1, 0);
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kzero) , 1, 0);
pythia22->SetMDCY ( pycomp_ (&DIS_PDG::Kminus) , 1, 0);
pythia2->SetMSTU (20, 1); //advirsory warning for unphysical flavour switch off
pythia2->SetMSTU (23, 1); //It sets counter of errors at 0
pythia2->SetMSTU (26, 0); //no warnings printed
// PARJ(32)(D=1GeV) is, with quark masses added, used to define the minimum allowable enrgy of a colour singlet parton system
pythia2->SetPARJ (33, 0.1);
// PARJ(33)-PARJ(34)(D=0.8GeV, 1.5GeV) are, with quark masses added, used to define the remaining energy below which
//the fragmentation of a parton system is stopped and two final hadrons formed.
pythia2->SetPARJ (34, 0.5);
pythia2->SetPARJ (35, 1.0);
//PARJ(36) (D=2.0GeV) represents the dependence of the mass of final quark pair for defining the stopping point of the
//fragmentation. Strongly corlated with PARJ(33-35)
pythia2->SetPARJ (37, 1.); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
//MSTJ(17) (D=2) number of attemps made to find two hadrons that have a combined mass below the cluster mass and thus allow
// a cluster to decay rather than collaps
pythia2->SetMSTJ (18, 3); //do not change
/////////////////////////////////////////////////
// End of setting Pythia parameters
////////////////////////////////////////////////
double Mtrue = (PDG::mass_proton+PDG::mass_neutron)/2;
double Mtrue2 = Mtrue * Mtrue;
double W2 = hama * hama;
double nu = entra;
vect nuc0 = e.in[1];
vect nu0 = e.in[0];
nu0.boost (-nuc0.speed ()); //neutrino 4-momentum in the target rest frame
vec nulab = vec (nu0.x, nu0.y, nu0.z); //can be made simpler ???
int lepton = e.in[0].pdg;
int nukleon = e.in[1].pdg;
double m = lepton_mass (abs (lepton), current); //mass of the given lepton (see pgd header file)
double m2 = m * m;
double E = nu0.t;
double E2 = E * E;
int nParticle = 0;
int nCharged = 0;
int NPar = 0;
Pyjets_t *pythiaParticle; //deklaracja event recordu
double W1 = hama / GeV; //W1 w GeV-ach potrzebne do Pythii
while (NPar < 5)
{
hadronization (E, hama, entra, m, lepton, nukleon, current);
pythiaParticle = pythia2->GetPyjets ();
NPar = pythia2->GetN ();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////Kinematics
///////////////////////////////////////////////
//////////// The input data is: neutrinoo 4-momentum, invariant hadronic mass and energy transfer
//////////// With this data the kinematics is resolved
////////////////////////////////////////////////////
/////////// We know that nu^2-q^2= (k-k')^2=m^2-2*k.k'= m^2-2*E*(E-nu)+ 2*E*sqrt((E-nu)^2-m^2)*cos theta
///////////
/////////// (M+nu)^2-q^2=W^2
////////////
//////////// (k-q)^2= m^2 = nu^2-q^2 -2*E*nu + 2*E*q*cos beta
/////////////
///////////// theta is an angle between leptons and beta is an angle between neutrino and momentum transfer
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////// Of course it is not necessary to calculate vectors k' and q separately because of momentum conservation
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double q = sqrt (kwad (Mtrue + nu) - W2);
double kprim = sqrt (kwad (E - nu) - m2);
double cth = (E2 + kprim * kprim - q * q) / 2 / E / kprim;
vec kkprim; //the unit vector in the direction of scattered lepton
kinfinder (nulab, kkprim, cth); //hopefully should produce kkprim
kkprim = kprim * kkprim; //multiplied by its length
vect lepton_out = vect (E - nu, kkprim.x, kkprim.y, kkprim.z);
vec momtran = nulab - kkprim;
vec hadrspeed = momtran / sqrt (W2 + q * q);
nParticle = pythia2->GetN ();
if (nParticle == 0)
{
cout << "nie ma czastek" << endl;
cin.get ();
}
vect par[100];
double ks[100]; //int czy double ???
par[0] = lepton_out;
//powrot do ukladu spoczywajacej tarczy
par[0] = par[0].boost (nuc0.speed ()); //ok
particle lept (par[0]);
if (current == true && lepton > 0)
{
lept.pdg = lepton - 1;
}
if (current == true && lepton < 0)
{
lept.pdg = lepton + 1;
}
if (current == false)
{
lept.pdg = lepton;
}
e.out.push_back (lept); //final lepton; ok
for (int i = 0; i < nParticle; i++)
{
par[i].t = pythiaParticle->P[3][i] * GeV;
par[i].x = pythiaParticle->P[0][i] * GeV;
par[i].y = pythiaParticle->P[1][i] * GeV;
par[i].z = pythiaParticle->P[2][i] * GeV;
rotation (par[i], momtran);
ks[i] = pythiaParticle->K[0][i];
par[i] = par[i].boost (hadrspeed); //correct direction ???
par[i] = par[i].boost (nuc0.speed ());
particle part (par[i]);
part.ks = pythiaParticle->K[0][i];
part.pdg = pythiaParticle->K[1][i];
part.orgin = pythiaParticle->K[2][i];
e.temp.push_back (part);
if (ks[i] == 1) //condition for a real particle in the final state
{
e.out.push_back (part);
}
}
}
| NuWro/nuwro | src/dis/dishadr.cc | C++ | gpl-3.0 | 6,276 |
package example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.piedra.excel.annotation.ExcelExport;
import com.piedra.excel.util.ExcelExportor;
/**
* @Description: Excel导出工具 例子程序
* @Creator:linwb 2014-12-19
*/
public class ExcelExportorExample {
public static void main(String[] args) {
new ExcelExportorExample().testSingleHeader();
new ExcelExportorExample().testMulHeaders();
}
/**
* @Description: 测试单表头
* @History
* 1. 2014-12-19 linwb 创建方法
*/
@Test
public void testSingleHeader(){
OutputStream out = null;
try {
out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST.xls"));
List<ExcelRow> stus = new ArrayList<ExcelRow>();
for(int i=0; i<11120; i++){
stus.add(new ExcelRow());
}
new ExcelExportor<ExcelRow>().exportExcel("测试单表头", stus, out);
System.out.println("excel导出成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
//Ignore..
} finally{
out = null;
}
}
}
}
/**
* @Description: 测试多表头
* @History
* 1. 2014-12-19 linwb 创建方法
*/
@Test
public void testMulHeaders(){
OutputStream out = null;
try {
out = new FileOutputStream(new File("C://EXCEL-EXPORT-TEST-MULTIHEADER.xls"));
List<ExcelRowForMultiHeaders> stus = new ArrayList<ExcelRowForMultiHeaders>();
for(int i=0; i<1120; i++){
stus.add(new ExcelRowForMultiHeaders());
}
new ExcelExportor<ExcelRowForMultiHeaders>().exportExcel("测试多表头", stus, out);
System.out.println("excel导出成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
//Ignore..
} finally{
out = null;
}
}
}
}
}
/**
* @Description: Excel的一行对应的JavaBean类
* @Creator:linwb 2014-12-19
*/
class ExcelRow {
@ExcelExport(header="姓名",colWidth=50)
private String name="AAAAAAAAAAASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS";
@ExcelExport(header="年龄")
private int age=80;
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String clazz="SSSSSSSSS";
@ExcelExport(header="国家")
private String country="RRRRRRR";
@ExcelExport(header="城市")
private String city="EEEEEEEEE";
@ExcelExport(header="城镇")
private String town="WWWWWWW";
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String common="DDDDDDDD";
/** 如果colWidth <= 0 那么取默认的 15 */
@ExcelExport(header="出生日期",colWidth=-1)
private Date birth = new Date();
public ExcelRow(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getCommon() {
return common;
}
public void setCommon(String common) {
this.common = common;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}
/**
* @Description: Excel的一行对应的JavaBean类
* @Creator:linwb 2014-12-19
*/
class ExcelRowForMultiHeaders {
@ExcelExport(header="姓名",colspan="1",rowspan="3")
private String name="无名氏";
@ExcelExport(header="省份,国家",colspan="1,5",rowspan="1,2")
private String province="福建省";
@ExcelExport(header="城市",colspan="1",rowspan="1")
private String city="福建省";
@ExcelExport(header="城镇",colspan="1",rowspan="1")
private String town="不知何处";
@ExcelExport(header="年龄,年龄和备注",colspan="1,2",rowspan="1,1")
private int age=80;
@ExcelExport(header="备注?",colspan="1",rowspan="1")
private String common="我是备注,我是备注";
@ExcelExport(header="我的生日",colspan="1",rowspan="3",datePattern="yyyy-MM-dd HH:mm:ss")
private Date birth = new Date();
/** 这个属性没别注解,那么将不会出现在导出的excel文件中*/
private String clazz="我不会出现的,除非你给我 @ExcelExport 注解标记";
public ExcelRowForMultiHeaders(){
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCommon() {
return common;
}
public void setCommon(String common) {
this.common = common;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}
| webinglin/excelExportor | src/test/java/example/ExcelExportorExample.java | Java | gpl-3.0 | 6,820 |
/***************************************************************************
* Project file: NPlugins - NCore - BasicHttpClient.java *
* Full Class name: fr.ribesg.com.mojang.api.http.BasicHttpClient *
* *
* Copyright (c) 2012-2014 Ribesg - www.ribesg.fr *
* This file is under GPLv3 -> http://www.gnu.org/licenses/gpl-3.0.txt *
* Please contact me at ribesg[at]yahoo.fr if you improve this file! *
***************************************************************************/
package fr.ribesg.com.mojang.api.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
public class BasicHttpClient implements HttpClient {
private static BasicHttpClient instance;
private BasicHttpClient() {
}
public static BasicHttpClient getInstance() {
if (instance == null) {
instance = new BasicHttpClient();
}
return instance;
}
@Override
public String post(final URL url, final HttpBody body, final List<HttpHeader> headers) throws IOException {
return this.post(url, null, body, headers);
}
@Override
public String post(final URL url, Proxy proxy, final HttpBody body, final List<HttpHeader> headers) throws IOException {
if (proxy == null) {
proxy = Proxy.NO_PROXY;
}
final HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy);
connection.setRequestMethod("POST");
for (final HttpHeader header : headers) {
connection.setRequestProperty(header.getName(), header.getValue());
}
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
final DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.write(body.getBytes());
writer.flush();
writer.close();
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
reader.close();
return response.toString();
}
}
| cnaude/NPlugins | NCore/src/main/java/fr/ribesg/com/mojang/api/http/BasicHttpClient.java | Java | gpl-3.0 | 2,563 |
#!/usr/bin/env node
/*jshint -W100*/
'use strict';
/**
* ニコニコ動画ログインサンプル
*
* 以下のusernameとpasswordを書き換えてから実行してください
*/
var username = 'hogehoge';
var password = 'fugafuga';
var client = require('../index');
console.info('ニコニコTOPページにアクセスします');
client.fetch('http://nicovideo.jp/')
.then(function (result) {
console.info('ログインリンクをクリックします');
return result.$('#sideNav .loginBtn').click();
})
.then(function (result) {
console.info('ログインフォームを送信します');
return result.$('#login_form').submit({
mail_tel: username,
password: password
});
})
.then(function (result) {
console.info('ログイン可否をチェックします');
if (! result.response.headers['x-niconico-id']) {
throw new Error('login failed');
}
console.info('クッキー', result.response.cookies);
console.info('マイページに移動します');
return client.fetch('http://www.nicovideo.jp/my/top');
})
.then(function (result) {
console.info('マイページに表示されるアカウント名を取得します');
console.info(result.$('#siteHeaderUserNickNameContainer').text());
})
.catch(function (err) {
console.error('エラーが発生しました', err.message);
})
.finally(function () {
console.info('終了します');
});
| tohshige/test | express/example/niconico.js | JavaScript | gpl-3.0 | 1,404 |
package Eac.event;
import Eac.Eac;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import net.minecraft.item.ItemStack;
public class EacOnItemPickup extends Eac {
@SubscribeEvent
public void EacOnItemPickup(PlayerEvent.ItemPickupEvent e) {
if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreAir))) {
e.player.addStat(airoremined, 1);
}
else if (e.pickedUp.getEntityItem().isItemEqual(new ItemStack(oreShadow))) {
e.player.addStat(shadoworemined, 1);
}
}
}
| EacMods/Eac | src/main/java/Eac/event/EacOnItemPickup.java | Java | gpl-3.0 | 596 |
class PasswordResetsController < ApplicationController
def new
end
def create
@user = User.find_by_email(params[:email])
if @user
@user.deliver_reset_password_instructions!
redirect_to root_path, notice: 'Instructions have been sent to your email.'
else
flash.now[:alert] = "Sorry but we don't recognise the email address \"#{params[:email]}\"."
render :new
end
end
def edit
@user = User.load_from_reset_password_token(params[:id])
@token = params[:id]
if @user.blank?
not_authenticated
return
end
end
def update
@user = User.load_from_reset_password_token(params[:id])
@token = params[:id]
if @user.blank?
not_authenticated
return
end
@user.password_confirmation = params[:user][:password_confirmation]
if @user.change_password!(params[:user][:password])
redirect_to signin_path, notice: 'Password was successfully updated.'
else
render :edit
end
end
end
| armoin/edinburgh_collected | app/controllers/password_resets_controller.rb | Ruby | gpl-3.0 | 1,003 |
/**
* Copyright (c) 2013 Jad
*
* This file is part of Jad.
* Jad 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.
*
* Jad 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 Jad. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fhffm.jad.demo.jad;
import java.util.ArrayList;
import de.fhffm.jad.data.DataWrapper;
import de.fhffm.jad.data.EInputFields;
import de.fhffm.jad.data.IDataFieldEnum;
/**
* This class synchronizes the access to our Data.Frame
* Added Observations are stored in a local ArrayList.
* Use 'write' to send everything to GNU R.
* @author Denis Hock
*/
public class DataFrame {
private static DataWrapper dw = null;
private static ArrayList<String[]> rows = new ArrayList<>();
/**
* @return Singleton Instance of the GNU R Data.Frame
*/
public static DataWrapper getDataFrame(){
if (dw == null){
//Create the data.frame for GNU R:
dw = new DataWrapper("data");
clear();
}
return dw;
}
/**
* Delete the old observations and send all new observations to Gnu R
* @return
*/
public synchronized static boolean write(){
if (rows.size() < 1){
return false;
}
//Clear the R-Data.Frame
clear();
//Send all new Observations to Gnu R
for(String[] row : rows)
dw.addObservation(row);
//Clear the local ArrayList
rows.clear();
return true;
}
/**
* These Observations are locally stored and wait for the write() command
* @param row
*/
public synchronized static void add(String[] row){
//Store everything in an ArrayList
rows.add(row);
}
/**
* Clear local ArrayList and GNU R Data.Frame
*/
private static void clear(){
ArrayList<IDataFieldEnum> fields = new ArrayList<IDataFieldEnum>();
fields.add(EInputFields.ipsrc);
fields.add(EInputFields.tcpdstport);
fields.add(EInputFields.framelen);
dw.createEmptyDataFrame(fields);
}
}
| fg-netzwerksicherheit/jaddemo | src/de/fhffm/jad/demo/jad/DataFrame.java | Java | gpl-3.0 | 2,330 |
/* This file is part of F3TextViewerFX.
*
* F3TextViewerFX 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.
*
* F3TextViewerFX 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 F3TextViewerFX. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2015 by Dominic Scheurer <dscheurer@dominic-scheurer.de>.
*/
package de.dominicscheurer.quicktxtview.view;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFText2HTML;
import de.dominicscheurer.quicktxtview.model.DirectoryTreeItem;
import de.dominicscheurer.quicktxtview.model.FileSize;
import de.dominicscheurer.quicktxtview.model.FileSize.FileSizeUnits;
public class FileViewerController {
public static final Comparator<File> FILE_ACCESS_CMP =
(f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified());
public static final Comparator<File> FILE_ACCESS_CMP_REVERSE =
(f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified());
public static final Comparator<File> FILE_NAME_CMP =
(f1, f2) -> f1.getName().compareTo(f2.getName());
public static final Comparator<File> FILE_NAME_CMP_REVERSE =
(f1, f2) -> f2.getName().compareTo(f1.getName());
private static final String FILE_VIEWER_CSS_FILE = "FileViewer.css";
private static final String ERROR_TEXT_FIELD_CSS_CLASS = "errorTextField";
private FileSize fileSizeThreshold = new FileSize(1, FileSizeUnits.MB);
private Charset charset = Charset.defaultCharset();
private Comparator<File> fileComparator = FILE_ACCESS_CMP;
@FXML
private TreeView<File> fileSystemView;
@FXML
private WebView directoryContentView;
@FXML
private TextField filePatternTextField;
@FXML
private Label fileSizeThresholdLabel;
private boolean isInShowContentsMode = false;
private String fileTreeViewerCSS;
private Pattern filePattern;
@FXML
private void initialize() {
filePattern = Pattern.compile(filePatternTextField.getText());
filePatternTextField.setOnKeyReleased(event -> {
final String input = filePatternTextField.getText();
try {
Pattern p = Pattern.compile(input);
filePattern = p;
filePatternTextField.getStyleClass().remove(ERROR_TEXT_FIELD_CSS_CLASS);
if (!fileSystemView.getSelectionModel().isEmpty()) {
showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem());
}
} catch (PatternSyntaxException e) {
filePatternTextField.getStyleClass().add(ERROR_TEXT_FIELD_CSS_CLASS);
}
filePatternTextField.applyCss();
});
fileSystemView.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showDirectoryContents(newValue));
{
Scanner s = new Scanner(getClass().getResourceAsStream(FILE_VIEWER_CSS_FILE));
s.useDelimiter("\\A");
fileTreeViewerCSS = s.hasNext() ? s.next() : "";
s.close();
}
DirectoryTreeItem[] roots = DirectoryTreeItem.getFileSystemRoots();
if (roots.length > 1) {
TreeItem<File> dummyRoot = new TreeItem<File>();
dummyRoot.getChildren().addAll(roots);
fileSystemView.setShowRoot(false);
fileSystemView.setRoot(dummyRoot);
}
else {
fileSystemView.setRoot(roots[0]);
}
fileSystemView.getRoot().setExpanded(true);
refreshFileSizeLabel();
}
public void toggleInShowContentsMode() {
isInShowContentsMode = !isInShowContentsMode;
refreshFileSystemView();
}
public void setFileSizeThreshold(FileSize fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
refreshFileSystemView();
refreshFileSizeLabel();
}
public FileSize getFileSizeThreshold() {
return fileSizeThreshold;
}
public void setCharset(Charset charset) {
this.charset = charset;
refreshFileContentsView();
}
public Charset getCharset() {
return charset;
}
public Comparator<File> getFileComparator() {
return fileComparator;
}
public void setFileComparator(Comparator<File> fileComparator) {
this.fileComparator = fileComparator;
refreshFileContentsView();
}
private void refreshFileSizeLabel() {
fileSizeThresholdLabel.setText(fileSizeThreshold.getSize() + " " + fileSizeThreshold.getUnit().toString());
}
private void refreshFileContentsView() {
if (!fileSystemView.getSelectionModel().isEmpty()) {
showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem());
}
}
public void expandToDirectory(File file) {
Iterator<Path> it = file.toPath().iterator();
//FIXME: The below root directory selection *might* not work for Windows systems.
// => Do something with `file.toPath().getRoot()`.
TreeItem<File> currentDir = fileSystemView.getRoot();
while (it.hasNext()) {
final String currDirName = it.next().toString();
FilteredList<TreeItem<File>> matchingChildren =
currentDir.getChildren().filtered(elem -> elem.getValue().getName().equals(currDirName));
if (matchingChildren.size() == 1) {
matchingChildren.get(0).setExpanded(true);
currentDir = matchingChildren.get(0);
}
}
fileSystemView.getSelectionModel().clearSelection();
fileSystemView.getSelectionModel().select(currentDir);
fileSystemView.scrollTo(fileSystemView.getSelectionModel().getSelectedIndex());
}
private void showDirectoryContents(TreeItem<File> selectedDirectory) {
if (selectedDirectory == null) {
return;
}
final WebEngine webEngine = directoryContentView.getEngine();
webEngine.loadContent(!isInShowContentsMode ?
getFileNamesInDirectoryHTML(selectedDirectory.getValue()) :
getFileContentsInDirectoryHTML(selectedDirectory.getValue()));
}
private void refreshFileSystemView() {
showDirectoryContents(fileSystemView.getSelectionModel().getSelectedItem());
}
private String getFileNamesInDirectoryHTML(File directory) {
final StringBuilder sb = new StringBuilder();
final DecimalFormat df = new DecimalFormat("0.00");
final File[] files = listFiles(directory);
if (files == null) {
return "";
}
sb.append("<html><head>")
.append("<style type=\"text/css\">")
.append(fileTreeViewerCSS)
.append("</style>")
.append("</head><body><div id=\"fileList\"><ul>");
boolean even = false;
for (File file : files) {
sb.append("<li class=\"")
.append(even ? "even" : "odd")
.append("\"><span class=\"fileName\">")
.append(file.getName())
.append("</span> <span class=\"fileSize\">(")
.append(df.format((float) file.length() / 1024))
.append("K)</span>")
.append("</li>");
even = !even;
}
sb.append("</ul></div></body></html>");
return sb.toString();
}
private String getFileContentsInDirectoryHTML(File directory) {
final StringBuilder sb = new StringBuilder();
final File[] files = listFiles(directory);
if (files == null) {
return "";
}
sb.append("<html>")
.append("<body>")
.append("<style type=\"text/css\">")
.append(fileTreeViewerCSS)
.append("</style>");
for (File file : files) {
try {
String contentsString;
if (file.getName().endsWith(".pdf")) {
final PDDocument doc = PDDocument.load(file);
final StringWriter writer = new StringWriter();
new PDFText2HTML("UTF-8").writeText(doc, writer);
contentsString = writer.toString();
writer.close();
doc.close();
} else {
byte[] encoded = Files.readAllBytes(file.toPath());
contentsString = new String(encoded, charset);
contentsString = contentsString.replace("<", "<");
contentsString = contentsString.replace(">", ">");
contentsString = contentsString.replace("\n", "<br/>");
}
sb.append("<div class=\"entry\"><h3>")
.append(file.getName())
.append("</h3>")
.append("<div class=\"content\">")
.append(contentsString)
.append("</div>")
.append("</div>");
} catch (IOException e) {}
}
sb.append("</body></html>");
return sb.toString();
}
private File[] listFiles(File directory) {
if (directory == null) {
return new File[0];
}
File[] files = directory.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() &&
filePattern.matcher(pathname.getName().toString()).matches() &&
pathname.length() <= fileSizeThreshold.toBytes();
}
});
if (files == null) {
return new File[0];
}
Arrays.sort(files, fileComparator);
return files;
}
}
| rindPHI/F3TextViewerFX | src/de/dominicscheurer/quicktxtview/view/FileViewerController.java | Java | gpl-3.0 | 9,526 |
Ext.define("Voyant.notebook.util.Embed", {
transferable: ['embed'],
embed: function() { // this is for instances
embed.apply(this, arguments);
},
constructor: function(config) {
var me = this;
},
statics: {
i18n: {},
api: {
embeddedParameters: undefined,
embeddedConfig: undefined
},
embed: function(cmp, config) {
if (this.then) {
this.then(function(embedded) {
embed.call(embedded, cmp, config)
})
} else if (Ext.isArray(cmp)) {
Voyant.notebook.util.Show.SINGLE_LINE_MODE=true;
show("<table><tr>");
cmp.forEach(function(embeddable) {
show("<td>");
if (Ext.isArray(embeddable)) {
if (embeddable[0].embeddable) {
embeddable[0].embed.apply(embeddable[0], embeddable.slice(1))
} else {
embed.apply(this, embeddable)
}
} else {
embed.apply(this, embeddable);
}
show("</td>")
})
// for (var i=0; i<arguments.length; i++) {
// var unit = arguments[i];
// show("<td>")
// unit[0].embed.call(unit[0], unit[1], unit[2]);
// show("</td>")
// }
show("</tr></table>")
Voyant.notebook.util.Show.SINGLE_LINE_MODE=false;
return
} else {
// use the default (first) embeddable panel if no panel is specified
if (this.embeddable && (!cmp || Ext.isObject(cmp))) {
// if the first argument is an object, use it as config instead
if (Ext.isObject(cmp)) {config = cmp;}
cmp = this.embeddable[0];
}
if (Ext.isString(cmp)) {
cmp = Ext.ClassManager.getByAlias('widget.'+cmp.toLowerCase()) || Ext.ClassManager.get(cmp);
}
var isEmbedded = false;
if (Ext.isFunction(cmp)) {
var name = cmp.getName();
if (this.embeddable && Ext.Array.each(this.embeddable, function(item) {
if (item==name) {
config = config || {};
var embeddedParams = {};
for (key in Ext.ClassManager.get(Ext.getClassName(cmp)).api) {
if (key in config) {
embeddedParams[key] = config[key]
}
}
if (!embeddedParams.corpus) {
if (Ext.getClassName(this)=='Voyant.data.model.Corpus') {
embeddedParams.corpus = this.getId();
} else if (this.getCorpus) {
var corpus = this.getCorpus();
if (corpus) {
embeddedParams.corpus = this.getCorpus().getId();
}
}
}
Ext.applyIf(config, {
style: 'width: '+(config.width || '90%') + (Ext.isNumber(config.width) ? 'px' : '')+
'; height: '+(config.height || '400px') + (Ext.isNumber(config.height) ? 'px' : '')
});
delete config.width;
delete config.height;
var corpus = embeddedParams.corpus;
delete embeddedParams.corpus;
Ext.applyIf(embeddedParams, Voyant.application.getModifiedApiParams());
var embeddedConfigParamEncodded = Ext.encode(embeddedParams);
var embeddedConfigParam = encodeURIComponent(embeddedConfigParamEncodded);
var iframeId = Ext.id();
var url = Voyant.application.getBaseUrlFull()+"tool/"+name.substring(name.lastIndexOf(".")+1)+'/?';
if (true || embeddedConfigParam.length>1800) {
show('<iframe style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>');
var dfd = Voyant.application.getDeferred(this);
Ext.Ajax.request({
url: Voyant.application.getTromboneUrl(),
params: {
tool: 'resource.StoredResource',
storeResource: embeddedConfigParam
}
}).then(function(response) {
var json = Ext.util.JSON.decode(response.responseText);
var params = {
minimal: true,
embeddedApiId: json.storedResource.id
}
if (corpus) {
params.corpus = corpus;
}
Ext.applyIf(params, Voyant.application.getModifiedApiParams());
document.getElementById(iframeId).setAttribute("src",url+Ext.Object.toQueryString(params));
dfd.resolve();
}).otherwise(function(response) {
showError(response);
dfd.reject();
})
} else {
show('<iframe src="'+url+embeddedConfigParam+'" style="'+config.style+'" id="'+iframeId+'" name="'+iframeId+'"></iframe>');
}
isEmbedded = true;
return false;
}
}, this)===true) {
Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this);
}
if (!isEmbedded) {
var embedded = Ext.create(cmp, config);
embedded.embed(config);
isEmbedded = true;
}
}
if (!isEmbedded) {
Voyant.notebook.util.Embed.showWidgetNotRecognized.call(this);
}
}
},
showWidgetNotRecognized: function() {
var msg = Voyant.notebook.util.Embed.i18n.widgetNotRecognized;
if (this.embeddable) {
msg += Voyant.notebook.util.Embed.i18n.tryWidget+'<ul>'+this.embeddable.map(function(cmp) {
var widget = cmp.substring(cmp.lastIndexOf(".")+1).toLowerCase()
return "\"<a href='../../docs/#!/guide/"+widget+"' target='voyantdocs'>"+widget+"</a>\""
}).join(", ")+"</ul>"
}
showError(msg)
}
}
})
embed = Voyant.notebook.util.Embed.embed | sgsinclair/Voyant | src/main/webapp/app/notebook/util/Embed.js | JavaScript | gpl-3.0 | 5,429 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomWallsAndFloorsRedux
{
public class Settings
{
public List<Animation> AnimatedTiles { get; set; } = new List<Animation>();
}
}
| Platonymous/Stardew-Valley-Mods | CustomWallsAndFloorsRedux/Settings.cs | C# | gpl-3.0 | 282 |
<?php
/**
* Kunena Component
* @package Kunena.Template.Crypsis
* @subpackage Layout.Announcement
*
* @copyright (C) 2008 - 2016 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined('_JEXEC') or die;
$row = $this->row;
$announcement = $this->announcement;
?>
<tr>
<td class="nowrap hidden-xs">
<?php echo $announcement->displayField('created', 'date_today'); ?>
</td>
<td class="nowrap">
<div class="overflow">
<?php echo JHtml::_('kunenaforum.link', $announcement->getUri(), $announcement->displayField('title'),
null, 'follow'); ?>
</div>
</td>
<?php if ($this->checkbox) : ?>
<td class="center">
<?php if ($this->canPublish()) echo JHtml::_('kunenagrid.published', $row, $announcement->published, '', true); ?>
</td>
<td class="center">
<?php if ($this->canEdit()) echo JHtml::_('kunenagrid.task', $row, 'tick.png', JText::_('COM_KUNENA_ANN_EDIT'),
'edit', '', true); ?>
</td>
<td class="center">
<?php if ($this->canDelete()) echo JHtml::_('kunenagrid.task', $row, 'publish_x.png',
JText::_('COM_KUNENA_ANN_DELETE'), 'delete', '', true); ?>
</td>
<td>
<?php echo $announcement->getAuthor()->username; ?>
</td>
<?php endif; ?>
<td class="center hidden-xs">
<?php echo $announcement->displayField('id'); ?>
</td>
<?php if ($this->checkbox) : ?>
<td class="center">
<?php echo JHtml::_('kunenagrid.id', $row, $announcement->id); ?>
</td>
<?php endif; ?>
</tr>
| fxstein/Kunena-Forum | components/com_kunena/site/template/crypsisb3/layouts/announcement/list/row/default.php | PHP | gpl-3.0 | 1,524 |
// opening-tag.hpp
// Started 14 Aug 2018
#pragma once
#include <string>
#include <boost/spirit/include/qi.hpp>
namespace client {
// namespace fusion = boost::fusion;
// namespace phoenix = boost::phoenix;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
template<typename Iterator>
struct opening_tag : qi::grammar<Iterator, mini_xml_tag(), ascii::space_type>
{
qi::rule<Iterator, mini_xml_tag(), ascii::space_type> start;
qi::rule<Iterator, std::string(), ascii::space_type> head;
qi::rule<Iterator, std::string(), ascii::space_type> tail;
opening_tag()
: base_type{ start }
{
head %= qi::lexeme[+ascii::alnum];
tail %= qi::no_skip[*(qi::char_ - '>')];
start %= qi::lit('<') >> head >> tail >> qi::lit('>');
}
};
}
| Lester-Dowling/studies | C++/boost/spirit/Mini-XML-2017/Unit-Tests/opening-tag.hpp | C++ | gpl-3.0 | 778 |
//: pony/PartyFavor.java
package pokepon.pony;
import pokepon.enums.*;
/** Party Favor
* Good def and spa, lacks Hp and Speed
*
* @author silverweed
*/
public class PartyFavor extends Pony {
public PartyFavor(int _level) {
super(_level);
name = "Party Favor";
type[0] = Type.LAUGHTER;
type[1] = Type.HONESTY;
race = Race.UNICORN;
sex = Sex.MALE;
baseHp = 60;
baseAtk = 80;
baseDef = 100;
baseSpatk = 100;
baseSpdef = 80;
baseSpeed = 60;
/* Learnable Moves */
learnableMoves.put("Tackle",1);
learnableMoves.put("Hidden Talent",1);
learnableMoves.put("Mirror Pond",1);
learnableMoves.put("Dodge",1);
}
}
| silverweed/pokepon | pony/PartyFavor.java | Java | gpl-3.0 | 654 |
using System;
namespace GalleryServerPro.Business.Interfaces
{
/// <summary>
/// A collection of <see cref="IUserAccount" /> objects.
/// </summary>
public interface IUserAccountCollection : System.Collections.Generic.ICollection<IUserAccount>
{
/// <summary>
/// Gets a list of user names for accounts in the collection. This is equivalent to iterating through each <see cref="IUserAccount" />
/// and compiling a string array of the <see cref="IUserAccount.UserName" /> properties.
/// </summary>
/// <returns>Returns a string array of user names of accounts in the collection.</returns>
string[] GetUserNames();
/// <summary>
/// Sort the objects in this collection based on the <see cref="IUserAccount.UserName" /> property.
/// </summary>
void Sort();
/// <summary>
/// Adds the user accounts to the current collection.
/// </summary>
/// <param name="userAccounts">The user accounts to add to the current collection.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="userAccounts" /> is null.</exception>
void AddRange(System.Collections.Generic.IEnumerable<IUserAccount> userAccounts);
/// <summary>
/// Gets a reference to the <see cref="IUserAccount" /> object at the specified index position.
/// </summary>
/// <param name="indexPosition">An integer specifying the position of the object within this collection to
/// return. Zero returns the first item.</param>
/// <returns>Returns a reference to the <see cref="IUserAccount" /> object at the specified index position.</returns>
IUserAccount this[Int32 indexPosition]
{
get;
set;
}
/// <summary>
/// Searches for the specified object and returns the zero-based index of the first occurrence within the collection.
/// </summary>
/// <param name="gallery">The user account to locate in the collection. The value can be a null
/// reference (Nothing in Visual Basic).</param>
/// <returns>The zero-based index of the first occurrence of a user account within the collection, if found;
/// otherwise, 1. </returns>
Int32 IndexOf(IUserAccount gallery);
/// <overloads>
/// Determines whether a user is a member of the collection.
/// </overloads>
/// <summary>
/// Determines whether the <paramref name="item"/> is a member of the collection. An object is considered a member
/// of the collection if they both have the same <see cref="IUserAccount.UserName" />.
/// </summary>
/// <param name="item">An <see cref="IUserAccount"/> to determine whether it is a member of the current collection.</param>
/// <returns>Returns <c>true</c> if <paramref name="item"/> is a member of the current collection;
/// otherwise returns <c>false</c>.</returns>
new bool Contains(IUserAccount item);
/// <summary>
/// Determines whether a user account with the specified <paramref name="userName"/> is a member of the collection.
/// </summary>
/// <param name="userName">The user name that uniquely identifies the user.</param>
/// <returns>Returns <c>true</c> if <paramref name="userName"/> is a member of the current collection;
/// otherwise returns <c>false</c>.</returns>
bool Contains(string userName);
/// <summary>
/// Adds the specified user account.
/// </summary>
/// <param name="item">The user account to add.</param>
new void Add(IUserAccount item);
/// <summary>
/// Find the user account in the collection that matches the specified <paramref name="userName" />. If no matching object is found,
/// null is returned.
/// </summary>
/// <param name="userName">The user name that uniquely identifies the user.</param>
/// <returns>Returns an <see cref="IUserAccount" />object from the collection that matches the specified <paramref name="userName" />,
/// or null if no matching object is found.</returns>
IUserAccount FindByUserName(string userName);
/// <summary>
/// Finds the users whose <see cref="IUserAccount.UserName" /> begins with the specified <paramref name="userNameSearchString" />.
/// This method can be used to find a set of users that match the first few characters of a string. Returns an empty collection if
/// no matches are found. The match is case-insensitive. Example: If <paramref name="userNameSearchString" />="Rob", this method
/// returns users with names like "Rob", "Robert", and "robert" but not names such as "Boston Rob".
/// </summary>
/// <param name="userNameSearchString">A string to match against the beginning of a <see cref="IUserAccount.UserName" />. Do not
/// specify a wildcard character. If value is null or an empty string, all users are returned.</param>
/// <returns>Returns an <see cref="IUserAccountCollection" />object from the collection where the <see cref="IUserAccount.UserName" />
/// begins with the specified <paramref name="userNameSearchString" />, or an empty collection if no matching object is found.</returns>
IUserAccountCollection FindAllByUserName(string userNameSearchString);
}
}
| bambit/BGallery | TIS.GSP.Business.Interfaces/IUserAccountCollection.cs | C# | gpl-3.0 | 5,022 |
var Base = require("./../plugin");
module.exports = class extends Base {
isDisableSelfAttackPriority(self, rival) {
return true;
}
isDisableEnemyAttackPriority(self, rival) {
return true;
}
} | ssac/feh-guide | src/models/seal/hardy_bearing_3.js | JavaScript | gpl-3.0 | 208 |
//////////////////////////////////////////////////
// JIST (Java In Simulation Time) Project
// Timestamp: <EntityRef.java Sun 2005/03/13 11:10:16 barr rimbase.rimonbarr.com>
//
// Copyright (C) 2004 by Cornell University
// All rights reserved.
// Refer to LICENSE for terms and conditions of use.
package jist.runtime;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
import java.rmi.RemoteException;
/**
* Stores a reference to a (possibly remote) Entity object. A reference
* consists of a serialized reference to a Controller and an index within that
* Controller.
*
* @author Rimon Barr <barr+jist@cs.cornell.edu>
* @version $Id: EntityRef.java,v 1.1 2007/04/09 18:49:26 drchoffnes Exp $
* @since JIST1.0
*/
public class EntityRef implements InvocationHandler
{
/**
* NULL reference constant.
*/
public static final EntityRef NULL = new EntityRefDist(null, -1);
/**
* Entity index within Controller.
*/
private final int index;
/**
* Initialise a new entity reference with given
* Controller and Entity IDs.
*
* @param index entity ID
*/
public EntityRef(int index)
{
this.index = index;
}
/**
* Return entity reference hashcode.
*
* @return entity reference hashcode
*/
public int hashCode()
{
return index;
}
/**
* Test object equality.
*
* @param o object to test equality
* @return object equality
*/
public boolean equals(Object o)
{
if(o==null) return false;
if(!(o instanceof EntityRef)) return false;
EntityRef er = (EntityRef)o;
if(index!=er.index) return false;
return true;
}
/**
* Return controller of referenced entity.
*
* @return controller of referenced entity
*/
public ControllerRemote getController()
{
if(Main.SINGLE_CONTROLLER)
{
return Controller.activeController;
}
else
{
throw new RuntimeException("multiple controllers");
}
}
/**
* Return index of referenced entity.
*
* @return index of referenced entity
*/
public int getIndex()
{
return index;
}
/**
* Return toString of referenced entity.
*
* @return toString of referenced entity
*/
public String toString()
{
try
{
return "EntityRef:"+getController().toStringEntity(getIndex());
}
catch(java.rmi.RemoteException e)
{
throw new RuntimeException(e);
}
}
/**
* Return class of referenced entity.
*
* @return class of referenced entity
*/
public Class getClassRef()
{
try
{
return getController().getEntityClass(getIndex());
}
catch(java.rmi.RemoteException e)
{
throw new RuntimeException(e);
}
}
//////////////////////////////////////////////////
// proxy entities
//
/** boolean type for null return. */
private static final Boolean RET_BOOLEAN = new Boolean(false);
/** byte type for null return. */
private static final Byte RET_BYTE = new Byte((byte)0);
/** char type for null return. */
private static final Character RET_CHARACTER = new Character((char)0);
/** double type for null return. */
private static final Double RET_DOUBLE = new Double((double)0);
/** float type for null return. */
private static final Float RET_FLOAT = new Float((float)0);
/** int type for null return. */
private static final Integer RET_INTEGER = new Integer(0);
/** long type for null return. */
private static final Long RET_LONG = new Long(0);
/** short type for null return. */
private static final Short RET_SHORT = new Short((short)0);
/**
* Called whenever a proxy entity reference is invoked. Schedules the call
* at the appropriate Controller.
*
* @param proxy proxy entity reference object whose method was invoked
* @param method method invoked on entity reference object
* @param args arguments of the method invocation
* @return result of blocking event; null return for non-blocking events
* @throws Throwable whatever was thrown by blocking events; never for non-blocking events
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
if(Rewriter.isBlockingRuntimeProxy(method))
// todo: make Object methods blocking
//|| method.getDeclaringClass()==Object.class)
{
return blockingInvoke(proxy, method, args);
}
else
{
// schedule a simulation event
if(Main.SINGLE_CONTROLLER)
{
Controller.activeController.addEvent(method, this, args);
}
else
{
getController().addEvent(method, this, args);
}
return null;
}
}
catch(RemoteException e)
{
throw new JistException("distributed simulation failure", e);
}
}
/**
* Helper method: called whenever a BLOCKING method on proxy entity reference
* is invoked. Schedules the call at the appropriate Controller.
*
* @param proxy proxy entity reference object whose method was invoked
* @param method method invoked on entity reference object
* @param args arguments of the method invocation
* @return result of blocking event
* @throws Throwable whatever was thrown by blocking events
*/
private Object blockingInvoke(Object proxy, Method method, Object[] args) throws Throwable
{
Controller c = Controller.getActiveController();
if(c.isModeRestoreInst())
{
// restore complete
if(Controller.log.isDebugEnabled())
{
Controller.log.debug("restored event state!");
}
// return callback result
return c.clearRestoreState();
}
else
{
// calling blocking method
c.registerCallEvent(method, this, args);
// todo: darn Java; this junk slows down proxies
Class ret = method.getReturnType();
if(ret==Void.TYPE)
{
return null;
}
else if(ret.isPrimitive())
{
String retName = ret.getName();
switch(retName.charAt(0))
{
case 'b':
switch(retName.charAt(1))
{
case 'o': return RET_BOOLEAN;
case 'y': return RET_BYTE;
default: throw new RuntimeException("unknown return type");
}
case 'c': return RET_CHARACTER;
case 'd': return RET_DOUBLE;
case 'f': return RET_FLOAT;
case 'i': return RET_INTEGER;
case 'l': return RET_LONG;
case 's': return RET_SHORT;
default: throw new RuntimeException("unknown return type");
}
}
else
{
return null;
}
}
}
} // class: EntityRef
| jbgi/replics | swans/jist/runtime/EntityRef.java | Java | gpl-3.0 | 6,768 |
#!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import codecs
import os
from setuptools import setup, find_packages
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list
packages = find_packages(exclude=['tests*'])
with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
with open(fn) as fh:
code = compile(fh.read(), fn, 'exec')
exec(code)
setup(name='python-telegram-bot',
version=__version__,
author='Leandro Toledo',
author_email='devs@python-telegram-bot.org',
license='LGPLv3',
url='https://python-telegram-bot.org/',
keywords='python telegram bot api wrapper',
description="We have made you a wrapper you can't refuse",
long_description=fd.read(),
packages=packages,
install_requires=requirements(),
extras_require={
'json': 'ujson',
'socks': 'PySocks'
},
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Communications :: Chat',
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],)
| txemagon/1984 | modules/Telegram-bot-python/setup.py | Python | gpl-3.0 | 2,168 |
#include "cmilitwostateselect.h"
#include "ui_cmilitwostateselect.h"
#include "cengine.h"
#include "ctextout.h"
void CMili2McuController::DoUpdateLogicView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateLogicView(engine);
}
void CMili2McuController::DoUpdateMemoryView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateMemoryView(engine);
}
void CMili2McuController::DoUpdateHintsView(const CEngineModel *engine) {
if (engine->CurrentMcuType() == CEngineModel::MILI_MCU)
mView->UpdateHintsView(engine);
}
// -------------------------------------------------------------
CMiliTwoStateSelect::CMiliTwoStateSelect(QWidget *parent) :
QWidget(parent),
ui(new Ui::CMiliTwoStateSelect),
mMcuController(this)
{
ui->setupUi(this);
}
CMiliTwoStateSelect::~CMiliTwoStateSelect()
{
delete ui;
}
void CMiliTwoStateSelect::UpdateMemoryView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
UpdateRG(engine);
}
void CMiliTwoStateSelect::UpdateLogicView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
UpdateMS1(engine);
UpdateMS2(engine);
UpdateY(engine);
}
void CMiliTwoStateSelect::UpdateHintsView(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
ui->mRgMsbNoHint->setText(CTextOut::FormatDec(engine->StateDim() - 1));
ui->mYDimHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim()));
ui->mMs1MsbHint->setText(QString("p%1").arg(CTextOut::FormatDec(engine->McuControlInputDim() - 1)));
ui->mMs2MsbHint->setText(CTextOut::FormatDec(engine->McuControlOutputDim() + engine->StateDim() - 1));
}
void CMiliTwoStateSelect::UpdateRG(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CRegister *rg = engine->CurrentMcu()->Register(CMiliAutomate::STATE_REGISTER_INDEX);
unsigned int stateDim = engine->StateDim();
ui->mRgVal->setText(CTextOut::FormatHex(rg->Output(), stateDim));
ui->mSVal->setText(CTextOut::FormatHex(rg->Output(), stateDim));
}
void CMiliTwoStateSelect::UpdateMS1(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::GROUP_MUX_INDEX);
ui->mMS1P0Val->setText(CTextOut::FormatBin(mux->Input(0), 1));
ui->mMS1P1Val->setText(CTextOut::FormatBin(mux->Input(1), 1));
unsigned int lastIndex = engine->McuControlInputDim() - 1;
ui->mMS1PnVal->setText(CTextOut::FormatBin(mux->Input(lastIndex).AsInt(), 1));
ui->mMs1SelVal->setText(CTextOut::FormatHex(mux->InputIndex(), mux->IndexDim()));
ui->mMs1Val->setText(CTextOut::FormatBin(mux->Output().AsInt(), 1));
}
void CMiliTwoStateSelect::UpdateMS2(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
const CMultiplexor *mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::STATE_MUX_INDEX);
ui->mMS2S0Val->setText(CTextOut::FormatHex(mux->Input(0)));
ui->mMS2S1Val->setText(CTextOut::FormatHex(mux->Input(1)));
ui->mMs2SVal->setText(CTextOut::FormatHex(mux->Output()));
mux = engine->CurrentMcu()->Multiplexor(CMiliAutomate::CONTROL_MUX_INDEX);
ui->mMS2Y0Val->setText(CTextOut::FormatHex(mux->Input(0)));
ui->mMS2Y1Val->setText(CTextOut::FormatHex(mux->Input(1)));
ui->mMs2YVal->setText(CTextOut::FormatHex(mux->Output()));
}
void CMiliTwoStateSelect::UpdateY(const CEngineModel *engine) {
Q_ASSERT(engine != 0);
Q_ASSERT(engine->CurrentMcuType() == CEngineModel::MILI_MCU);
ui->mYVal->setText(CTextOut::FormatHex(engine->CurrentMcu()->ControlOutput()));
}
| mmshihov/microcode | cmilitwostateselect.cpp | C++ | gpl-3.0 | 4,032 |
class Cartridge : property<Cartridge> {
public:
enum class Mode : unsigned {
Normal,
BsxSlotted,
Bsx,
SufamiTurbo,
SuperGameBoy,
};
enum class Region : unsigned {
NTSC,
PAL,
};
//assigned externally to point to file-system datafiles (msu1 and serial)
//example: "/path/to/filename.sfc" would set this to "/path/to/filename"
readwrite<string> basename;
readonly<bool> loaded;
readonly<unsigned> crc32;
readonly<string> sha256;
readonly<Mode> mode;
readonly<Region> region;
readonly<unsigned> ram_size;
readonly<bool> has_bsx_slot;
readonly<bool> has_superfx;
readonly<bool> has_sa1;
readonly<bool> has_necdsp;
readonly<bool> has_srtc;
readonly<bool> has_sdd1;
readonly<bool> has_spc7110;
readonly<bool> has_spc7110rtc;
readonly<bool> has_cx4;
readonly<bool> has_obc1;
readonly<bool> has_st0018;
readonly<bool> has_msu1;
readonly<bool> has_serial;
struct Mapping {
Memory *memory;
MMIO *mmio;
Bus::MapMode mode;
unsigned banklo;
unsigned bankhi;
unsigned addrlo;
unsigned addrhi;
unsigned offset;
unsigned size;
Mapping();
Mapping(Memory&);
Mapping(MMIO&);
};
array<Mapping> mapping;
void load(Mode, const lstring&);
void unload();
void serialize(serializer&);
Cartridge();
~Cartridge();
private:
void parse_xml(const lstring&);
void parse_xml_cartridge(const char*);
void parse_xml_bsx(const char*);
void parse_xml_sufami_turbo(const char*, bool);
void parse_xml_gameboy(const char*);
void xml_parse_rom(xml_element&);
void xml_parse_ram(xml_element&);
void xml_parse_icd2(xml_element&);
void xml_parse_superfx(xml_element&);
void xml_parse_sa1(xml_element&);
void xml_parse_necdsp(xml_element&);
void xml_parse_bsx(xml_element&);
void xml_parse_sufamiturbo(xml_element&);
void xml_parse_supergameboy(xml_element&);
void xml_parse_srtc(xml_element&);
void xml_parse_sdd1(xml_element&);
void xml_parse_spc7110(xml_element&);
void xml_parse_cx4(xml_element&);
void xml_parse_obc1(xml_element&);
void xml_parse_setarisc(xml_element&);
void xml_parse_msu1(xml_element&);
void xml_parse_serial(xml_element&);
void xml_parse_address(Mapping&, const string&);
void xml_parse_mode(Mapping&, const string&);
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bsxflash, bsxram, bsxpram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
};
extern Cartridge cartridge;
| grim210/defimulator | defimulator/snes/cartridge/cartridge.hpp | C++ | gpl-3.0 | 2,519 |
<?php
namespace Schatz\CrmBundle\Controller\Leads;
use Schatz\CrmBundle\Constants\ContactStatusConstants;
use Schatz\CrmBundle\Constants\ContactTypeConstants;
use Schatz\GeneralBundle\Constants\PermissionsConstants;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LeadsController extends Controller
{
const MENU = 'leads';
private $leads = array();
private $user;
private $allCampaigns = array();
private $myCampaigns = array();
private $contactCampaigns = array();
private $allAssignedLeadsOrContacts = array();
public function indexAction($filter)
{
if ($this->get('user.permission')->checkPermission(PermissionsConstants::PERMISSION_7) and !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) return $this->redirect($this->generateUrl('schatz_general_homepage'));
$this->user = $this->getUser();
if (!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
$this->allCampaigns = $this->getDoctrine()->getRepository('SchatzCrmBundle:Campaign')->findAll();
if (!empty($this->allCampaigns)) {
foreach ($this->allCampaigns as $campaign) {
if (in_array($this->user->getId(), $campaign->getAssociates())) {
$this->myCampaigns[] = $campaign;
}
}
}
$this->contactCampaigns = $this->getDoctrine()->getRepository('SchatzCrmBundle:ContactCampaign')->findAll();
if (!empty($this->contactCampaigns)) {
foreach ($this->contactCampaigns as $contactCampaign) {
if ($contactCampaign->getContact()->getFlag() == ContactTypeConstants::CONTACT_TYPE_2 and !in_array($contactCampaign->getContact(), $this->allAssignedLeadsOrContacts)) {
$this->allAssignedLeadsOrContacts[] = $contactCampaign->getContact();
}
}
}
}
$this->_getLeads($filter);
return $this->render('SchatzCrmBundle:Leads:index.html.twig',
array(
'menu' => $this::MENU,
'leads' => $this->leads,
'filter' => $filter
)
);
}
private function _getLeads($filter)
{
if (empty($this->myCampaigns) and empty($this->allAssignedLeadsOrContacts) and !$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
$this->leads = array();
} else {
if ($filter == 'my_leads') {
$this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, null, $this->user);
} else if ($filter == 'new') {
$this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_1);
} else if ($filter == 'contacted') {
$this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_2);
} else if ($filter == 'rejected') {
$this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts, ContactStatusConstants::CONTACT_STATUS_3);
} else {
$this->leads = $this->getDoctrine()->getRepository('SchatzCrmBundle:Contact')->findAllLeadsOrContacts(ContactTypeConstants::CONTACT_TYPE_2, $this->myCampaigns, $this->user, $this->allAssignedLeadsOrContacts);
}
}
}
}
| edoschatz/taskada | src/Schatz/CrmBundle/Controller/Leads/LeadsController.php | PHP | gpl-3.0 | 4,047 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0003_remove_userprofile_is_check'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='is_create',
),
migrations.RemoveField(
model_name='userprofile',
name='is_delete',
),
migrations.RemoveField(
model_name='userprofile',
name='is_modify',
),
]
| yangxianbo/jym | account/migrations/0004_auto_20160525_1032.py | Python | gpl-3.0 | 591 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.hyranasoftware.githubupdater.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.Objects;
import org.joda.time.DateTime;
/**
*
* @author danny_000
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Asset {
String url;
String browser_download_url;
int id;
String name;
String label;
String state;
String content_type;
long size;
long download_count;
DateTime created_at;
DateTime updated_at;
GithubUser uploader;
public Asset() {
}
public Asset(String url, String browser_download_url, int id, String name, String label, String state, String content_type, long size, long download_count, DateTime created_at, DateTime updated_at, GithubUser uploader) {
this.url = url;
this.browser_download_url = browser_download_url;
this.id = id;
this.name = name;
this.label = label;
this.state = state;
this.content_type = content_type;
this.size = size;
this.download_count = download_count;
this.created_at = created_at;
this.updated_at = updated_at;
this.uploader = uploader;
}
public String getState() {
return state;
}
public String getUrl() {
return url;
}
public String getBrowser_download_url() {
return browser_download_url;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getLabel() {
return label;
}
public String getContent_type() {
return content_type;
}
public long getSize() {
return size;
}
public long getDownload_count() {
return download_count;
}
public DateTime getCreated_at() {
return created_at;
}
public DateTime getUpdated_at() {
return updated_at;
}
public GithubUser getUploader() {
return uploader;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + Objects.hashCode(this.content_type);
hash = 79 * hash + (int) (this.download_count ^ (this.download_count >>> 32));
hash = 79 * hash + Objects.hashCode(this.created_at);
hash = 79 * hash + Objects.hashCode(this.updated_at);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Asset other = (Asset) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.content_type, other.content_type)) {
return false;
}
return true;
}
@Override
public String toString(){
return this.name;
}
}
| eternia16/javaGithubUpdater | src/main/java/nl/hyranasoftware/githubupdater/domain/Asset.java | Java | gpl-3.0 | 3,243 |
ModX Revolution 2.5.0 = 88d852255e0a3c20e3abb5ec165b5684
ModX Revolution 2.3.3 = 5137fe8eb650573a752775acc90954b5
ModX Revolution 2.3.2 = 2500d1a81dd43e7e9f4a11e1712aeffb
MODX Revolution 2.2.8 = cc299e05ed6fb94e4d9c4144bf553675
MODX Revolution 2.5.2 = f87541ee3ef82272d4442529fee1028e
| gohdan/DFC | known_files/hashes/manager/controllers/default/resource/update.class.php | PHP | gpl-3.0 | 285 |
#include "RocksIndex.hh"
#include <stdlib.h>
#include <iostream>
// Get command line arguments for array size (100M) and number of trials (1M)
void arrayArgs(int argc, char* argv[], objectId_t& asize, int& reps) {
asize = (argc>1) ? strtoull(argv[1], 0, 0) : 100000000;
reps = (argc>2) ? strtol(argv[2], 0, 0) : 1000000;
}
// Main program goes here
int main(int argc, char* argv[]) {
objectId_t arraySize;
int queryTrials;
arrayArgs(argc, argv, arraySize, queryTrials);
std::cout << "RocksDB Table " << arraySize << " elements, " << queryTrials
<< " trials" << std::endl;
RocksIndex rocks(2); // Verbosity
rocks.CreateTable(arraySize);
rocks.ExerciseTable(queryTrials);
}
| kelseymh/secindex_proto | rocksdb-index.cc | C++ | gpl-3.0 | 706 |
###
# Copyright 2016 - 2022 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md
###
module Reports::SystemPerformance::Fy2015
class MeasureThree < Base
end
end
| greenriver/hmis-warehouse | app/models/reports/system_performance/fy2015/measure_three.rb | Ruby | gpl-3.0 | 237 |
<?php
/* ----------------------------------------------------------------------
* app/controllers/find/AdvancedSearchObjectsController.php : controller for "advanced" object search request handling
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2010-2015 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
require_once(__CA_LIB_DIR__."/ca/BaseAdvancedSearchController.php");
require_once(__CA_LIB_DIR__."/ca/Search/ObjectSearch.php");
require_once(__CA_LIB_DIR__."/ca/Browse/ObjectBrowse.php");
require_once(__CA_LIB_DIR__."/core/GeographicMap.php");
require_once(__CA_MODELS_DIR__."/ca_objects.php");
require_once(__CA_MODELS_DIR__."/ca_sets.php");
class SearchObjectsAdvancedController extends BaseAdvancedSearchController {
# -------------------------------------------------------
/**
* Name of subject table (ex. for an object search this is 'ca_objects')
*/
protected $ops_tablename = 'ca_objects';
/**
* Number of items per search results page
*/
protected $opa_items_per_page = array(8, 16, 24, 32);
/**
* List of search-result views supported for this find
* Is associative array: values are view labels, keys are view specifier to be incorporated into view name
*/
protected $opa_views;
/**
* Name of "find" used to defined result context for ResultContext object
* Must be unique for the table and have a corresponding entry in find_navigation.conf
*/
protected $ops_find_type = 'advanced_search';
# -------------------------------------------------------
public function __construct(&$po_request, &$po_response, $pa_view_paths=null) {
parent::__construct($po_request, $po_response, $pa_view_paths);
$this->opa_views = array(
'thumbnail' => _t('thumbnails'),
'full' => _t('full'),
'list' => _t('list')
);
$this->opo_browse = new ObjectBrowse($this->opo_result_context->getParameter('browse_id'), 'providence');
}
# -------------------------------------------------------
/**
* Advanced search handler (returns search form and results, if any)
* Most logic is contained in the BaseAdvancedSearchController->Index() method; all you usually
* need to do here is instantiate a new subject-appropriate subclass of BaseSearch
* (eg. ObjectSearch for objects, EntitySearch for entities) and pass it to BaseAdvancedSearchController->Index()
*/
public function Index($pa_options=null) {
$pa_options['search'] = $this->opo_browse;
AssetLoadManager::register('imageScroller');
AssetLoadManager::register('tabUI');
AssetLoadManager::register('panel');
return parent::Index($pa_options);
}
# -------------------------------------------------------
/**
*
*/
public function getPartialResult($pa_options=null) {
$pa_options['search'] = $this->opo_browse;
return parent::getPartialResult($pa_options);
}
# -------------------------------------------------------
/**
* Ajax action that returns info on a mapped location based upon the 'id' request parameter.
* 'id' is a list of object_ids to display information before. Each integer id is separated by a semicolon (";")
* The "ca_objects_results_map_balloon_html" view in Results/ is used to render the content.
*/
public function getMapItemInfo() {
$pa_object_ids = explode(';', $this->request->getParameter('id', pString));
$va_access_values = caGetUserAccessValues($this->request);
$this->view->setVar('ids', $pa_object_ids);
$this->view->setVar('access_values', $va_access_values);
$this->render("Results/ca_objects_results_map_balloon_html.php");
}
# -------------------------------------------------------
/**
* Returns string representing the name of the item the search will return
*
* If $ps_mode is 'singular' [default] then the singular version of the name is returned, otherwise the plural is returned
*/
public function searchName($ps_mode='singular') {
return ($ps_mode == 'singular') ? _t("object") : _t("objects");
}
# -------------------------------------------------------
# Sidebar info handler
# -------------------------------------------------------
/**
* Returns "search tools" widget
*/
public function Tools($pa_parameters) {
return parent::Tools($pa_parameters);
}
# -------------------------------------------------------
} | bruceklotz/providence-with-Backup | app/controllers/find/SearchObjectsAdvancedController.php | PHP | gpl-3.0 | 5,413 |
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to 2012 PrismTech
* Limited and its licensees. All rights reserved. See file:
*
* $OSPL_HOME/LICENSE
*
* for full copyright notice and license terms.
*
*/
/**
* @file
*/
#ifndef ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_
#define ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_
#include <dds/core/types.hpp>
#include <dds/core/LengthUnlimited.hpp>
#include <dds/core/Duration.hpp>
//==============================================================================
// DDS Policy Classes
namespace org
{
namespace opensplice
{
namespace core
{
namespace policy
{
//==============================================================================
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Entity objects such that when a remote application
* discovers their existence it can access that information and use it for its
* own purposes. One possible use of this QoS is to attach security credentials
* or some other information that can be used by the remote application to
* authenticate the source. In combination with operations such as
* ignore_participant, ignore_publication, ignore_subscription,
* and ignore_topic these QoS can assist an application to define and enforce
* its own security policies. The use of this QoS is not limited to security,
* rather it offers a simple, yet flexible extensibility mechanism.
*/
class UserData
{
public:
/**
* @internal Create a <code>UserData</code> instance with an empty user data.
*/
UserData() : value_() { }
/**
* @internal Create a <code>UserData</code> instance.
*
* @param seq the sequence of octet representing the user data
*/
explicit UserData(const dds::core::ByteSeq& seq) : value_(seq) { }
/**
* @internal Set the value for the user data.
*
* @param seq a sequence of octet representing the user data.
*/
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
/**
* @internal Get/Set the user data.
*
* @return the sequence of octet representing the user data
*/
dds::core::ByteSeq& value()
{
return value_;
}
/**
* @internal Get the user data.
*
* @return the sequence of octet representing the user data
*/
const dds::core::ByteSeq& value() const
{
return value_;
}
bool operator ==(const UserData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
//==============================================================================
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Publisher or Subscriber.
* The value of the GROUP_DATA is available to the application on the
* DataReader and DataWriter entities and is propagated by means of the
* built-in topics. This QoS can be used by an application combination with
* the DataReaderListener and DataWriterListener to implement matching policies
* similar to those of the PARTITION QoS except the decision can be made based
* on an application-defined policy.
*/
class GroupData
{
public:
/**
* @internal Create a <code>GroupData</code> instance.
*/
GroupData() : value_() { }
/**
* @internal Create a <code>GroupData</code> instance.
*
* @param seq the group data value
*/
explicit GroupData(const dds::core::ByteSeq& seq) : value_(seq) { }
/**
* @internal Set the value for this <code>GroupData</code>
*
* @param seq the group data value
*/
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
/**
* @internal Get/Set the value for this <code>GroupData</code>
*
* @return the group data value
*/
dds::core::ByteSeq& value()
{
return value_;
}
/**
* @internal Get the value for this <code>GroupData</code>
*
* @return the group data value
*/
const dds::core::ByteSeq& value() const
{
return value_;
}
bool operator ==(const GroupData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
//==============================================================================
/**
* @internal The purpose of this QoS is to allow the application to attach additional
* information to the created Topic such that when a remote application
* discovers their existence it can examine the information and use it in
* an application-defined way. In combination with the listeners on the
* DataReader and DataWriter as well as by means of operations such as
* ignore_topic, these QoS can assist an application to extend the provided QoS.
*/
class TopicData
{
public:
TopicData() : value_() { }
explicit TopicData(const dds::core::ByteSeq& seq) : value_(seq) { }
void value(const dds::core::ByteSeq& seq)
{
value_ = seq;
}
const dds::core::ByteSeq& value() const
{
return value_;
}
dds::core::ByteSeq& value()
{
return value_;
}
bool operator ==(const TopicData& other) const
{
return other.value() == value_;
}
private:
dds::core::ByteSeq value_;
};
//==============================================================================
/**
* @internal This policy controls the behavior of the Entity as a factory for other
* entities. This policy concerns only DomainParticipant (as factory for
* Publisher, Subscriber, and Topic), Publisher (as factory for DataWriter),
* and Subscriber (as factory for DataReader). This policy is mutable.
* A change in the policy affects only the entities created after the change;
* not the previously created entities.
* The setting of autoenable_created_entities to TRUE indicates that the
* newly created object will be enabled by default.
* A setting of FALSE indicates that the Entity will not be automatically
* enabled. The application will need to enable it explicitly by means of the
* enable operation (see Section 7.1.2.1.1.7, ÒenableÓ). The default setting
* of autoenable_created_entities = TRUE means that, by default, it is not
* necessary to explicitly call enable on newly created entities.
*/
class EntityFactory
{
public:
EntityFactory() {}
explicit EntityFactory(bool auto_enable)
: auto_enable_(auto_enable) { }
void auto_enable(bool on)
{
auto_enable_ = on;
}
bool auto_enable() const
{
return auto_enable_;
}
bool& auto_enable()
{
return auto_enable_;
}
bool operator ==(const EntityFactory& other) const
{
return other.auto_enable() == auto_enable_;
}
private:
bool auto_enable_;
};
//==============================================================================
/**
* @internal The purpose of this QoS is to allow the application to take advantage of
* transports capable of sending messages with different priorities.
* This policy is considered a hint. The policy depends on the ability of the
* underlying transports to set a priority on the messages they send.
* Any value within the range of a 32-bit signed integer may be chosen;
* higher values indicate higher priority. However, any further interpretation
* of this policy is specific to a particular transport and a particular
* implementation of the Service. For example, a particular transport is
* permitted to treat a range of priority values as equivalent to one another.
* It is expected that during transport configuration the application would
* provide a mapping between the values of the TRANSPORT_PRIORITY set on
* DataWriter and the values meaningful to each transport. This mapping would
* then be used by the infrastructure when propagating the data written by
* the DataWriter.
*/
class TransportPriority
{
public:
TransportPriority() {}
explicit TransportPriority(uint32_t prio) : value_(prio) { }
public:
void value(uint32_t prio)
{
value_ = prio;
}
uint32_t value() const
{
return value_;
}
uint32_t& value()
{
return value_;
}
bool operator ==(const TransportPriority& other) const
{
return other.value() == value_;
}
private:
uint32_t value_;
};
//==============================================================================
/**
* @internal The purpose of this QoS is to avoid delivering ÒstaleÓ data to the
* application. Each data sample written by the DataWriter has an associated
* expiration time beyond which the data should not be delivered to any
* application. Once the sample expires, the data will be removed from the
* DataReader caches as well as from the transient and persistent
* information caches. The expiration time of each sample is computed by
* adding the duration specified by the LIFESPAN QoS to the source timestamp.
* As described in Section 7.1.2.4.2.11, Òwrite and Section 7.1.2.4.2.12,
* write_w_timestamp the source timestamp is either automatically computed by
* the Service each time the DataWriter write operation is called, or else
* supplied by the application by means of the write_w_timestamp operation.
*
* This QoS relies on the sender and receiving applications having their clocks
* sufficiently synchronized. If this is not the case and the Service can
* detect it, the DataReader is allowed to use the reception timestamp instead
* of the source timestamp in its computation of the expiration time.
*/
class Lifespan
{
public:
Lifespan() {}
explicit Lifespan(const dds::core::Duration& d) : duration_(d) { }
public:
void duration(const dds::core::Duration& d)
{
duration_ = d;
}
const dds::core::Duration duration() const
{
return duration_;
}
dds::core::Duration& duration()
{
return duration_;
}
bool operator ==(const Lifespan& other) const
{
return other.duration() == duration_;
}
private:
dds::core::Duration duration_;
};
//==============================================================================
/**
* @internal This policy is useful for cases where a Topic is expected to have each
* instance updated periodically. On the publishing side this setting
* establishes a contract that the application must meet. On the subscribing
* side the setting establishes a minimum requirement for the remote publishers
* that are expected to supply the data values. When the Service ÔmatchesÕ a
* DataWriter and a DataReader it checks whether the settings are compatible
* (i.e., offered deadline period<= requested deadline period) if they are not,
* the two entities are informed (via the listener or condition mechanism)
* of the incompatibility of the QoS settings and communication will not occur.
* Assuming that the reader and writer ends have compatible settings, the
* fulfillment of this contract is monitored by the Service and the application
* is informed of any violations by means of the proper listener or condition.
* The value offered is considered compatible with the value requested if and
* only if the inequality Òoffered deadline period <= requested deadline periodÓ
* evaluates to ÔTRUE.Õ The setting of the DEADLINE policy must be set
* consistently with that of the TIME_BASED_FILTER.
* For these two policies to be consistent the settings must be such that
* Òdeadline period>= minimum_separation.Ó
*/
class Deadline
{
public:
Deadline() {}
explicit Deadline(const dds::core::Duration& d) : period_(d) { }
public:
void period(const dds::core::Duration& d)
{
period_ = d;
}
const dds::core::Duration period() const
{
return period_;
}
bool operator ==(const Deadline& other) const
{
return other.period() == period_;
}
private:
dds::core::Duration period_;
};
//==============================================================================
class LatencyBudget
{
public:
LatencyBudget() {}
explicit LatencyBudget(const dds::core::Duration& d) : duration_(d) { }
public:
void duration(const dds::core::Duration& d)
{
duration_ = d;
}
const dds::core::Duration duration() const
{
return duration_;
}
dds::core::Duration& duration()
{
return duration_;
}
bool operator ==(const LatencyBudget& other) const
{
return other.duration() == duration_;
}
private:
dds::core::Duration duration_;
};
//==============================================================================
class TimeBasedFilter
{
public:
TimeBasedFilter() {}
explicit TimeBasedFilter(const dds::core::Duration& min_separation)
: min_sep_(min_separation) { }
public:
void min_separation(const dds::core::Duration& ms)
{
min_sep_ = ms;
}
const dds::core::Duration min_separation() const
{
return min_sep_;
}
dds::core::Duration& min_separation()
{
return min_sep_;
}
bool operator ==(const TimeBasedFilter& other) const
{
return other.min_separation() == min_sep_;
}
private:
dds::core::Duration min_sep_;
};
//==============================================================================
class Partition
{
public:
Partition() {}
explicit Partition(const std::string& partition) : name_()
{
name_.push_back(partition);
}
explicit Partition(const dds::core::StringSeq& partitions)
: name_(partitions) { }
public:
void name(const std::string& partition)
{
name_.clear();
name_.push_back(partition);
}
void name(const dds::core::StringSeq& partitions)
{
name_ = partitions;
}
const dds::core::StringSeq& name() const
{
return name_;
}
dds::core::StringSeq& name()
{
return name_;
}
bool operator ==(const Partition& other) const
{
return other.name() == name_;
}
private:
dds::core::StringSeq name_;
};
//==============================================================================
class Ownership
{
public:
public:
Ownership() {}
Ownership(dds::core::policy::OwnershipKind::Type kind) : kind_(kind) { }
public:
void kind(dds::core::policy::OwnershipKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::OwnershipKind::Type kind() const
{
return kind_;
}
dds::core::policy::OwnershipKind::Type& kind()
{
return kind_;
}
bool operator ==(const Ownership& other) const
{
return other.kind() == kind_;
}
private:
dds::core::policy::OwnershipKind::Type kind_;
};
//==============================================================================
#ifdef OMG_DDS_OWNERSHIP_SUPPORT
class OwnershipStrength
{
public:
OwnershipStrength() {}
explicit OwnershipStrength(int32_t s) : s_(s) { }
int32_t strength() const
{
return s_;
}
int32_t& strength()
{
return s_;
}
void strength(int32_t s)
{
s_ = s;
}
bool operator ==(const OwnershipStrength& other) const
{
return other.strength() == s_;
}
private:
int32_t s_;
};
#endif // OMG_DDS_OWNERSHIP_SUPPORT
//==============================================================================
class WriterDataLifecycle
{
public:
WriterDataLifecycle() {}
WriterDataLifecycle(bool autodispose)
: autodispose_(autodispose) { }
bool autodispose() const
{
return autodispose_;
}
bool& autodispose()
{
return autodispose_;
}
void autodispose(bool b)
{
autodispose_ = b;
}
bool operator ==(const WriterDataLifecycle& other) const
{
return other.autodispose() == autodispose_;
}
private:
bool autodispose_;
};
//==============================================================================
class ReaderDataLifecycle
{
public:
ReaderDataLifecycle() {}
ReaderDataLifecycle(const dds::core::Duration& nowriter_delay,
const dds::core::Duration& disposed_samples_delay)
: autopurge_nowriter_samples_delay_(nowriter_delay),
autopurge_disposed_samples_delay_(disposed_samples_delay) { }
public:
const dds::core::Duration autopurge_nowriter_samples_delay() const
{
return autopurge_nowriter_samples_delay_;
}
void autopurge_nowriter_samples_delay(const dds::core::Duration& d)
{
autopurge_nowriter_samples_delay_ = d;
}
const dds::core::Duration autopurge_disposed_samples_delay() const
{
return autopurge_disposed_samples_delay_;
}
void autopurge_disposed_samples_delay(const dds::core::Duration& d)
{
autopurge_disposed_samples_delay_ = d;
}
bool operator ==(const ReaderDataLifecycle& other) const
{
return other.autopurge_nowriter_samples_delay() == autopurge_nowriter_samples_delay_ &&
other.autopurge_disposed_samples_delay() == autopurge_disposed_samples_delay();
}
private:
dds::core::Duration autopurge_nowriter_samples_delay_;
dds::core::Duration autopurge_disposed_samples_delay_;
};
//==============================================================================
class Durability
{
public:
public:
Durability() {}
Durability(dds::core::policy::DurabilityKind::Type kind) : kind_(kind) { }
public:
void durability(dds::core::policy::DurabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::DurabilityKind::Type durability() const
{
return kind_;
}
dds::core::policy::DurabilityKind::Type& durability()
{
return kind_;
}
void kind(dds::core::policy::DurabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::DurabilityKind::Type& kind()
{
return kind_;
}
dds::core::policy::DurabilityKind::Type kind() const
{
return kind_;
}
bool operator ==(const Durability& other) const
{
return other.kind() == kind_;
}
public:
dds::core::policy::DurabilityKind::Type kind_;
};
//==============================================================================
class Presentation
{
public:
Presentation() {}
Presentation(dds::core::policy::PresentationAccessScopeKind::Type access_scope,
bool coherent_access,
bool ordered_access)
: access_scope_(access_scope),
coherent_access_(coherent_access),
ordered_access_(ordered_access)
{ }
void access_scope(dds::core::policy::PresentationAccessScopeKind::Type as)
{
access_scope_ = as;
}
dds::core::policy::PresentationAccessScopeKind::Type& access_scope()
{
return access_scope_;
}
dds::core::policy::PresentationAccessScopeKind::Type access_scope() const
{
return access_scope_;
}
void coherent_access(bool on)
{
coherent_access_ = on;
}
bool& coherent_access()
{
return coherent_access_;
}
bool coherent_access() const
{
return coherent_access_;
}
void ordered_access(bool on)
{
ordered_access_ = on;
}
bool& ordered_access()
{
return ordered_access_;
}
bool ordered_access() const
{
return ordered_access_;
}
bool operator ==(const Presentation& other) const
{
return other.access_scope() == access_scope_ &&
other.coherent_access() == coherent_access_ &&
other.ordered_access() == ordered_access_;
}
private:
dds::core::policy::PresentationAccessScopeKind::Type access_scope_;
bool coherent_access_;
bool ordered_access_;
};
//==============================================================================
class Reliability
{
public:
public:
Reliability() {}
Reliability(dds::core::policy::ReliabilityKind::Type kind,
const dds::core::Duration& max_blocking_time)
: kind_(kind),
max_blocking_time_(max_blocking_time) { }
public:
void kind(dds::core::policy::ReliabilityKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::ReliabilityKind::Type kind() const
{
return kind_;
}
void max_blocking_time(const dds::core::Duration& d)
{
max_blocking_time_ = d;
}
const dds::core::Duration max_blocking_time() const
{
return max_blocking_time_;
}
bool operator ==(const Reliability& other) const
{
return other.kind() == kind_ &&
other.max_blocking_time() == max_blocking_time_;
}
private:
dds::core::policy::ReliabilityKind::Type kind_;
dds::core::Duration max_blocking_time_;
};
//==============================================================================
class DestinationOrder
{
public:
DestinationOrder() {};
explicit DestinationOrder(dds::core::policy::DestinationOrderKind::Type kind)
: kind_(kind) { }
public:
void kind(dds::core::policy::DestinationOrderKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::DestinationOrderKind::Type& kind()
{
return kind_;
}
dds::core::policy::DestinationOrderKind::Type kind() const
{
return kind_;
}
bool operator ==(const DestinationOrder& other) const
{
return other.kind() == kind_;
}
private:
dds::core::policy::DestinationOrderKind::Type kind_;
};
//==============================================================================
class History
{
public:
History() {}
History(dds::core::policy::HistoryKind::Type kind, int32_t depth)
: kind_(kind),
depth_(depth)
{ }
dds::core::policy::HistoryKind::Type kind() const
{
return kind_;
}
dds::core::policy::HistoryKind::Type& kind()
{
return kind_;
}
void kind(dds::core::policy::HistoryKind::Type kind)
{
kind_ = kind;
}
int32_t depth() const
{
return depth_;
}
int32_t& depth()
{
return depth_;
}
void depth(int32_t depth)
{
depth_ = depth;
}
bool operator ==(const History& other) const
{
return other.kind() == kind_ &&
other.depth() == depth_;
}
private:
dds::core::policy::HistoryKind::Type kind_;
int32_t depth_;
};
//==============================================================================
class ResourceLimits
{
public:
ResourceLimits() {}
ResourceLimits(int32_t max_samples,
int32_t max_instances,
int32_t max_samples_per_instance)
: max_samples_(max_samples),
max_instances_(max_instances),
max_samples_per_instance_(max_samples_per_instance)
{ }
public:
void max_samples(int32_t samples)
{
max_samples_ = samples;
}
int32_t& max_samples()
{
return max_samples_;
}
int32_t max_samples() const
{
return max_samples_;
}
void max_instances(int32_t max_instances)
{
max_instances_ = max_instances;
}
int32_t& max_instances()
{
return max_instances_;
}
int32_t max_instances() const
{
return max_instances_;
}
void max_samples_per_instance(int32_t max_samples_per_instance)
{
max_samples_per_instance_ = max_samples_per_instance;
}
int32_t& max_samples_per_instance()
{
return max_samples_per_instance_;
}
int32_t max_samples_per_instance() const
{
return max_samples_per_instance_;
}
bool operator ==(const ResourceLimits& other) const
{
return other.max_samples() == max_samples_ &&
other.max_instances() == max_instances_ &&
other.max_samples_per_instance() == max_samples_per_instance_;
}
private:
int32_t max_samples_;
int32_t max_instances_;
int32_t max_samples_per_instance_;
};
//==============================================================================
class Liveliness
{
public:
public:
Liveliness() {}
Liveliness(dds::core::policy::LivelinessKind::Type kind,
dds::core::Duration lease_duration)
: kind_(kind),
lease_duration_(lease_duration)
{ }
void kind(dds::core::policy::LivelinessKind::Type kind)
{
kind_ = kind;
}
dds::core::policy::LivelinessKind::Type& kind()
{
return kind_;
}
dds::core::policy::LivelinessKind::Type kind() const
{
return kind_;
}
void lease_duration(const dds::core::Duration& lease_duration)
{
lease_duration_ = lease_duration;
}
dds::core::Duration& lease_duration()
{
return lease_duration_;
}
const dds::core::Duration lease_duration() const
{
return lease_duration_;
}
bool operator ==(const Liveliness& other) const
{
return other.kind() == kind_ &&
other.lease_duration() == lease_duration_;
}
private:
dds::core::policy::LivelinessKind::Type kind_;
dds::core::Duration lease_duration_;
};
//==============================================================================
#ifdef OMG_DDS_PERSISTENCE_SUPPORT
class DurabilityService
{
public:
DurabilityService() {}
DurabilityService(const dds::core::Duration& service_cleanup_delay,
dds::core::policy::HistoryKind::Type history_kind,
int32_t history_depth,
int32_t max_samples,
int32_t max_instances,
int32_t max_samples_per_instance)
: cleanup_delay_(service_cleanup_delay),
history_kind_(history_kind),
history_depth_(history_depth),
max_samples_(max_samples),
max_instances_(max_instances),
max_samples_per_instance_(max_samples_per_instance)
{ }
public:
void service_cleanup_delay(const dds::core::Duration& d)
{
cleanup_delay_ = d;
}
const dds::core::Duration service_cleanup_delay() const
{
return cleanup_delay_;
}
void history_kind(dds::core::policy::HistoryKind::Type kind)
{
history_kind_ = kind;
}
dds::core::policy::HistoryKind::Type history_kind() const
{
return history_kind_;
}
void history_depth(int32_t depth)
{
history_depth_ = depth;
}
int32_t history_depth() const
{
return history_depth_;
}
void max_samples(int32_t max_samples)
{
max_samples_ = max_samples;
}
int32_t max_samples() const
{
return max_samples_;
}
void max_instances(int32_t max_instances)
{
max_instances_ = max_instances;
}
int32_t max_instances() const
{
return max_instances_;
}
void max_samples_per_instance(int32_t max_samples_per_instance)
{
max_samples_per_instance_ = max_samples_per_instance;
}
int32_t max_samples_per_instance() const
{
return max_samples_per_instance_;
}
bool operator ==(const DurabilityService& other) const
{
return other.service_cleanup_delay() == cleanup_delay_ &&
other.history_kind() == history_kind_ &&
other.history_depth() == history_depth_ &&
other.max_samples() == max_samples_ &&
other.max_instances() == max_instances_ &&
other.max_samples_per_instance() == max_samples_per_instance_;
}
private:
dds::core::Duration cleanup_delay_;
dds::core::policy::HistoryKind::Type history_kind_;
int32_t history_depth_;
int32_t max_samples_;
int32_t max_instances_;
int32_t max_samples_per_instance_;
};
#endif // OMG_DDS_PERSISTENCE_SUPPORT
#ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT
class DataRepresentation { };
#endif // OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT
#ifdef OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT
class TypeConsistencyEnforcement { };
#endif // OMG_DDS_EXTENSIBLE_AND_DYNAMIC_TOPIC_TYPE_SUPPORT
}
}
}
} // namespace org::opensplice::core::policy
#endif /* ORG_OPENSPLICE_CORE_POLICY_CORE_POLICY_IMPL_HPP_ */
| SanderMertens/opensplice | src/api/dcps/isocpp/include/org/opensplice/core/policy/CorePolicy.hpp | C++ | gpl-3.0 | 28,610 |
<?php
/**
* WoWRoster.net WoWRoster
*
* AddOn installer
*
* @copyright 2002-2011 WoWRoster.net
* @license http://www.gnu.org/licenses/gpl.html Licensed under the GNU General Public License v3.
* @package WoWRoster
* @subpackage RosterCP
*/
if( !defined('IN_ROSTER') || !defined('IN_ROSTER_ADMIN') )
{
exit('Detected invalid access to this file!');
}
$roster->output['title'] .= $roster->locale->act['pagebar_addoninst'];
include(ROSTER_ADMIN . 'roster_config_functions.php');
include(ROSTER_LIB . 'install.lib.php');
$installer = new Install;
$op = ( isset($_POST['op']) ? $_POST['op'] : '' );
$id = ( isset($_POST['id']) ? $_POST['id'] : '' );
switch( $op )
{
case 'deactivate':
processActive($id,0);
break;
case 'activate':
processActive($id,1);
break;
case 'process':
$processed = processAddon();
break;
case 'default_page':
processPage();
break;
case 'access':
processAccess();
break;
default:
break;
}
// This is here to refresh the addon list
$roster->get_addon_data();
$l_default_page = explode('|',$roster->locale->act['admin']['default_page']);
$roster->tpl->assign_vars(array(
'S_ADDON_LIST' => false,
'L_DEFAULT_PAGE' => $l_default_page[0],
'L_DEFAULT_PAGE_HELP' => makeOverlib($l_default_page[1],$l_default_page[0],'',0,'',',WRAP'),
'S_DEFAULT_SELECT' => pageNames(array('name'=>'default_page')),
)
);
$addons = getAddonList();
$install = $uninstall = $active = $deactive = $upgrade = $purge = 0;
if( !empty($addons) )
{
$roster->tpl->assign_vars(array(
'S_ADDON_LIST' => true,
'L_TIP_STATUS_ACTIVE' => makeOverlib($roster->locale->act['installer_turn_off'],$roster->locale->act['installer_activated']),
'L_TIP_STATUS_INACTIVE' => makeOverlib($roster->locale->act['installer_turn_on'],$roster->locale->act['installer_deactivated']),
'L_TIP_INSTALL_OLD' => makeOverlib($roster->locale->act['installer_replace_files'],$roster->locale->act['installer_overwrite']),
'L_TIP_INSTALL' => makeOverlib($roster->locale->act['installer_click_uninstall'],$roster->locale->act['installer_installed']),
'L_TIP_UNINSTALL' => makeOverlib($roster->locale->act['installer_click_install'],$roster->locale->act['installer_not_installed']),
)
);
foreach( $addons as $addon )
{
if( !empty($addon['icon']) )
{
if( strpos($addon['icon'],'.') !== false )
{
$addon['icon'] = ROSTER_PATH . 'addons/' . $addon['basename'] . '/images/' . $addon['icon'];
}
else
{
$addon['icon'] = $roster->config['interface_url'] . 'Interface/Icons/' . $addon['icon'] . '.' . $roster->config['img_suffix'];
}
}
else
{
$addon['icon'] = $roster->config['interface_url'] . 'Interface/Icons/inv_misc_questionmark.' . $roster->config['img_suffix'];
}
$roster->tpl->assign_block_vars('addon_list', array(
'ROW_CLASS' => $roster->switch_row_class(),
'ID' => ( isset($addon['id']) ? $addon['id'] : '' ),
'ICON' => $addon['icon'],
'FULLNAME' => $addon['fullname'],
'BASENAME' => $addon['basename'],
'VERSION' => $addon['version'],
'OLD_VERSION' => ( isset($addon['oldversion']) ? $addon['oldversion'] : '' ),
'DESCRIPTION' => $addon['description'],
'DEPENDENCY' => $addon['requires'],
'AUTHOR' => $addon['author'],
'ACTIVE' => ( isset($addon['active']) ? $addon['active'] : '' ),
'INSTALL' => $addon['install'],
'L_TIP_UPGRADE' => ( isset($addon['active']) ? makeOverlib(sprintf($roster->locale->act['installer_click_upgrade'],$addon['oldversion'],$addon['version']),$roster->locale->act['installer_upgrade_avail']) : '' ),
'ACCESS' => false //( isset($addon['access']) ? $roster->auth->rosterAccess(array('name' => 'access', 'value' => $addon['access'])) : false )
)
);
if ($addon['install'] == '3')
{
$install++;
}
if ($addon['install'] == '0')
{
$active++;
}
if ($addon['install'] == '2')
{
$deactive++;
}
if ($addon['install'] == '1')
{
$upgrade++;
}
if ($addon['install'] == '-1')
{
$purge++;
}
}
$roster->tpl->assign_vars(array(
'AL_C_PURGE' => $purge, // -1
'AL_C_UPGRADE' => $upgrade, // 1
'AL_C_DEACTIVE' => $deactive, // 2
'AL_C_ACTIVE' => $active, // 0
'AL_C_INSTALL' => $install, // 3
));
}
else
{
$installer->setmessages('No addons available!');
}
/*
echo '<!-- <pre>';
print_r($addons);
echo '</pre> -->';
*/
$errorstringout = $installer->geterrors();
$messagestringout = $installer->getmessages();
$sqlstringout = $installer->getsql();
// print the error messages
if( !empty($errorstringout) )
{
$roster->set_message($errorstringout, $roster->locale->act['installer_error'], 'error');
}
// Print the update messages
if( !empty($messagestringout) )
{
$roster->set_message($messagestringout, $roster->locale->act['installer_log']);
}
$roster->tpl->set_filenames(array('body' => 'admin/addon_install.html'));
$body = $roster->tpl->fetch('body');
/**
som new js
**/
$js = '
jQuery(document).ready( function($){
// this is the id of the ul to use
var menu;
jQuery(".tab-navigation ul li").click(function(e)
{
e.preventDefault();
menu = jQuery(this).parent().attr("id");
//alert(menu);
//jQuery("."+menu+"").css("display","none");
jQuery(".tab-navigation ul#"+menu+" li").removeClass("selected");
var tab_class = jQuery(this).attr("id");
jQuery(".tab-navigation ul#"+menu+" li").each(function() {
var v = jQuery(this).attr("id");
console.log( "hiding - "+v );
jQuery("div#"+v+"").hide();
});
//jQuery("."+menu+"#" + tab_class).siblings().hide();
jQuery("."+menu+"#" + tab_class).show();
jQuery(".tab-navigation ul#"+menu+" li#" + tab_class).addClass("selected");
});
function first()
{
var tab_class = jQuery(".tab-navigation ul li").first().attr("id");
console.log( "first - "+tab_class );
menu = jQuery(".tab-navigation ul").attr("id");
jQuery(".tab-navigation ul#"+menu+" li").each(function() {
var v = jQuery(this).attr("id");
console.log( "hiding - "+v );
jQuery("div#"+v+"").hide();
});
jQuery("."+menu+"#" + tab_class).show();
jQuery(".tab-navigation ul#"+menu+" li#" + tab_class).addClass("selected");
}
var init = first();
});';
roster_add_js($js, 'inline', 'header', false, false);
/**
* Gets the list of currently installed roster addons
*
* @return array
*/
function getAddonList()
{
global $roster, $installer;
// Initialize output
$addons = '';
$output = '';
if( $handle = @opendir(ROSTER_ADDONS) )
{
while( false !== ($file = readdir($handle)) )
{
if( $file != '.' && $file != '..' && $file != '.svn' && substr($file, strrpos($file, '.')+1) != 'txt')
{
$addons[] = $file;
}
}
}
usort($addons, 'strnatcasecmp');
if( is_array($addons) )
{
foreach( $addons as $addon )
{
$installfile = ROSTER_ADDONS . $addon . DIR_SEP . 'inc' . DIR_SEP . 'install.def.php';
$install_class = $addon . 'Install';
if( file_exists($installfile) )
{
include_once($installfile);
if( !class_exists($install_class) )
{
$installer->seterrors(sprintf($roster->locale->act['installer_no_class'],$addon));
continue;
}
$addonstuff = new $install_class;
if( array_key_exists($addon,$roster->addon_data) )
{
$output[$addon]['id'] = $roster->addon_data[$addon]['addon_id'];
$output[$addon]['active'] = $roster->addon_data[$addon]['active'];
$output[$addon]['access'] = $roster->addon_data[$addon]['access'];
$output[$addon]['oldversion'] = $roster->addon_data[$addon]['version'];
// -1 = overwrote newer version
// 0 = same version
// 1 = upgrade available
$output[$addon]['install'] = version_compare($addonstuff->version,$roster->addon_data[$addon]['version']);
if ($output[$addon]['install'] == 0 && $output[$addon]['active'] == 0)
{
$output[$addon]['install'] = 2;
}
}
/*
else if ($output[$addon]['install'] == 0 && $output[$addon]['active'] == 0)
{
$output[$addon]['install'] = 2;
}*/
else
{
$output[$addon]['install'] = 3;
}
// Save current locale array
// Since we add all locales for localization, we save the current locale array
// This is in case one addon has the same locale strings as another, and keeps them from overwritting one another
$localetemp = $roster->locale->wordings;
foreach( $roster->multilanguages as $lang )
{
$roster->locale->add_locale_file(ROSTER_ADDONS . $addon . DIR_SEP . 'locale' . DIR_SEP . $lang . '.php',$lang);
}
$output[$addon]['basename'] = $addon;
$output[$addon]['fullname'] = ( isset($roster->locale->act[$addonstuff->fullname]) ? $roster->locale->act[$addonstuff->fullname] : $addonstuff->fullname );
$output[$addon]['author'] = $addonstuff->credits[0]['name'];
$output[$addon]['version'] = $addonstuff->version;
$output[$addon]['icon'] = $addonstuff->icon;
$output[$addon]['description'] = ( isset($roster->locale->act[$addonstuff->description]) ? $roster->locale->act[$addonstuff->description] : $addonstuff->description );
$output[$addon]['requires'] = (isset($addonstuff->requires) ? $roster->locale->act['tooltip_reg_requires'].' '.$addonstuff->requires : '');
unset($addonstuff);
// Restore our locale array
$roster->locale->wordings = $localetemp;
unset($localetemp);
}
}
}
return $output;
}
/**
* Sets addon active/inactive
*
* @param int $id
* @param int $mode
*/
function processActive( $id , $mode )
{
global $roster, $installer;
$query = "SELECT `basename` FROM `" . $roster->db->table('addon') . "` WHERE `addon_id` = " . $id . ";";
$basename = $roster->db->query_first($query);
$query = "UPDATE `" . $roster->db->table('addon') . "` SET `active` = '$mode' WHERE `addon_id` = '$id' LIMIT 1;";
$result = $roster->db->query($query);
if( !$result )
{
$installer->seterrors('Database Error: ' . $roster->db->error() . '<br />SQL: ' . $query);
}
else
{
$installer->setmessages(sprintf($roster->locale->act['installer_activate_' . $mode] ,$basename));
}
}
/**
* Addon installer/upgrader/uninstaller
*
*/
function processAddon()
{
global $roster, $installer;
$addon_name = $_POST['addon'];
if( preg_match('/[^a-zA-Z0-9_]/', $addon_name) )
{
$installer->seterrors($roster->locale->act['invalid_char_module'],$roster->locale->act['installer_error']);
return;
}
// Check for temp tables
//$old_error_die = $roster->db->error_die(false);
if( false === $roster->db->query("CREATE TEMPORARY TABLE `test` (id int);") )
{
$installer->temp_tables = false;
$roster->db->query("UPDATE `" . $roster->db->table('config') . "` SET `config_value` = '0' WHERE `id` = 1180;");
}
else
{
$installer->temp_tables = true;
}
//$roster->db->error_die($old_error_die);
// Include addon install definitions
$addonDir = ROSTER_ADDONS . $addon_name . DIR_SEP;
$addon_install_file = $addonDir . 'inc' . DIR_SEP . 'install.def.php';
$install_class = $addon_name . 'Install';
if( !file_exists($addon_install_file) )
{
$installer->seterrors(sprintf($roster->locale->act['installer_no_installdef'],$addon_name),$roster->locale->act['installer_error']);
return;
}
require($addon_install_file);
$addon = new $install_class();
$addata = escape_array((array)$addon);
$addata['basename'] = $addon_name;
if( $addata['basename'] == '' )
{
$installer->seterrors($roster->locale->act['installer_no_empty'],$roster->locale->act['installer_error']);
return;
}
// Get existing addon record if available
$query = 'SELECT * FROM `' . $roster->db->table('addon') . '` WHERE `basename` = "' . $addata['basename'] . '";';
$result = $roster->db->query($query);
if( !$result )
{
$installer->seterrors(sprintf($roster->locale->act['installer_fetch_failed'],$addata['basename']) . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error']);
return;
}
$previous = $roster->db->fetch($result);
$roster->db->free_result($result);
// Give the installer the addon data
$installer->addata = $addata;
$success = false;
// Save current locale array
// Since we add all locales for localization, we save the current locale array
// This is in case one addon has the same locale strings as another, and keeps them from overwritting one another
$localetemp = $roster->locale->wordings;
foreach( $roster->multilanguages as $lang )
{
$roster->locale->add_locale_file(ROSTER_ADDONS . $addata['basename'] . DIR_SEP . 'locale' . DIR_SEP . $lang . '.php',$lang);
}
// Collect data for this install type
switch( $_POST['type'] )
{
case 'install':
if( $previous )
{
$installer->seterrors(sprintf($roster->locale->act['installer_addon_exist'],$installer->addata['basename'],$previous['fullname']));
break;
}
// check to see if any requred addons if so and not enabled disable addon after install and give a message
if (isset($installer->addata['requires']))
{
if (!active_addon($installer->addata['requires']))
{
$installer->addata['active'] = false;
$installer->setmessages('Addon Dependency "'.$installer->addata['requires'].'" not active or installed, "'.$installer->addata['fullname'].'" has been disabled');
break;
}
}
$query = 'INSERT INTO `' . $roster->db->table('addon') . '` VALUES (NULL,"' . $installer->addata['basename'] . '","' . $installer->addata['version'] . '","' . (int)$installer->addata['active'] . '",0,"' . $installer->addata['fullname'] . '","' . $installer->addata['description'] . '","' . $roster->db->escape(serialize($installer->addata['credits'])) . '","' . $installer->addata['icon'] . '","' . $installer->addata['wrnet_id'] . '",NULL);';
$result = $roster->db->query($query);
if( !$result )
{
$installer->seterrors('DB error while creating new addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']);
break;
}
$installer->addata['addon_id'] = $roster->db->insert_id();
// We backup the addon config table to prevent damage
$installer->add_backup($roster->db->table('addon_config'));
$success = $addon->install();
// Delete the addon record if there is an error
if( !$success )
{
$query = 'DELETE FROM `' . $roster->db->table('addon') . "` WHERE `addon_id` = '" . $installer->addata['addon_id'] . "';";
$result = $roster->db->query($query);
}
else
{
$installer->sql[] = 'UPDATE `' . $roster->db->table('addon') . '` SET `active` = ' . (int)$installer->addata['active'] . " WHERE `addon_id` = '" . $installer->addata['addon_id'] . "';";
$installer->sql[] = "INSERT INTO `" . $roster->db->table('permissions') . "` VALUES ('', 'roster', '" . $installer->addata['addon_id'] . "', 'addon', '".$installer->addata['fullname']."', 'addon_access_desc' , '".$installer->addata['basename']."_access');";
}
break;
case 'upgrade':
if( !$previous )
{
$installer->seterrors(sprintf($roster->locale->act['installer_no_upgrade'],$installer->addata['basename']));
break;
}
/* Carry Over from AP branch
if( !in_array($previous['basename'],$addon->upgrades) )
{
$installer->seterrors(sprintf($roster->locale->act['installer_not_upgradable'],$addon->fullname,$previous['fullname'],$previous['basename']));
break;
}
*/
$query = "UPDATE `" . $roster->db->table('addon') . "` SET `basename`='" . $installer->addata['basename'] . "', `version`='" . $installer->addata['version'] . "', `active`=" . (int)$installer->addata['active'] . ", `fullname`='" . $installer->addata['fullname'] . "', `description`='" . $installer->addata['description'] . "', `credits`='" . serialize($installer->addata['credits']) . "', `icon`='" . $installer->addata['icon'] . "', `wrnet_id`='" . $installer->addata['wrnet_id'] . "' WHERE `addon_id`=" . $previous['addon_id'] . ';';
$result = $roster->db->query($query);
if( !$result )
{
$installer->seterrors('DB error while updating the addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']);
break;
}
$installer->addata['addon_id'] = $previous['addon_id'];
// We backup the addon config table to prevent damage
$installer->add_backup($roster->db->table('addon_config'));
$success = $addon->upgrade($previous['version']);
break;
case 'uninstall':
if( !$previous )
{
$installer->seterrors(sprintf($roster->locale->act['installer_no_uninstall'],$installer->addata['basename']));
break;
}
if( $previous['basename'] != $installer->addata['basename'] )
{
$installer->seterrors(sprintf($roster->locale->act['installer_not_uninstallable'],$installer->addata['basename'],$previous['fullname']));
break;
}
$query = 'DELETE FROM `' . $roster->db->table('addon') . '` WHERE `addon_id`=' . $previous['addon_id'] . ';';
$result = $roster->db->query($query);
if( !$result )
{
$installer->seterrors('DB error while deleting the addon record. <br /> MySQL said:' . $roster->db->error(),$roster->locale->act['installer_error']);
break;
}
$installer->addata['addon_id'] = $previous['addon_id'];
// We backup the addon config table to prevent damage
$installer->add_backup($roster->db->table('addon_config'));
$success = $addon->uninstall();
if ($success)
{
$installer->remove_permissions($previous['addon_id']);
}
break;
case 'purge':
$success = purge($installer->addata['basename']);
break;
default:
$installer->seterrors($roster->locale->act['installer_invalid_type']);
$success = false;
break;
}
if( !$success )
{
$installer->seterrors($roster->locale->act['installer_no_success_sql']);
return false;
}
else
{
$success = $installer->install();
$installer->setmessages(sprintf($roster->locale->act['installer_' . $_POST['type'] . '_' . $success],$installer->addata['basename']));
}
// Restore our locale array
$roster->locale->wordings = $localetemp;
unset($localetemp);
return true;
}
/**
* Addon purge
* Removes an addon with a bad install/upgrade/un-install
*
* @param string $dbname
* @return bool
*/
function purge( $dbname )
{
global $roster, $installer;
// Delete addon tables under dbname.
$query = 'SHOW TABLES LIKE "' . $roster->db->prefix . 'addons_' . $dbname . '%"';
$tables = $roster->db->query($query);
if( !$tables )
{
$installer->seterrors('Error while getting table names for ' . $dbname . '. MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query);
return false;
}
if( $roster->db->num_rows($tables) )
{
while ($row = $roster->db->fetch($tables))
{
$query = 'DROP TABLE `' . $row[0] . '`;';
$dropped = $roster->db->query($query);
if( !$dropped )
{
$installer->seterrors('Error while dropping ' . $row[0] . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query);
return false;
}
}
}
// Get the addon id for this basename
$query = "SELECT `addon_id` FROM `" . $roster->db->table('addon') . "` WHERE `basename` = '" . $dbname . "';";
$addon_id = $roster->db->query_first($query);
if( $addon_id !== false )
{
// Delete menu entries
$query = 'DELETE FROM `' . $roster->db->table('menu_button') . '` WHERE `addon_id` = "' . $addon_id . '";';
$roster->db->query($query) or $installer->seterrors('Error while deleting menu entries for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query);
// Delete addon config entries
$query = 'DELETE FROM `' . $roster->db->table('addon_config') . '` WHERE `addon_id` = "' . $addon_id . '";';
$roster->db->query($query) or $installer->seterrors('Error while deleting menu entries for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query);
}
// Delete addon table entry
$query = 'DELETE FROM `' . $roster->db->table('addon') . '` WHERE `basename` = "' . $dbname . '"';
$roster->db->query($query) or $installer->seterrors('Error while deleting addon table entry for ' . $dbname . '.<br />MySQL said: ' . $roster->db->error(),$roster->locale->act['installer_error'],__FILE__,__LINE__,$query);
return true;
}
function processPage()
{
global $roster;
$default = ( $_POST['config_default_page'] );
$query = "UPDATE `" . $roster->db->table('config') . "` SET `config_value` = '$default' WHERE `id` = '1050';";
if( !$roster->db->query($query) )
{
die_quietly($roster->db->error(),'Database Error',__FILE__,__LINE__,$query);
}
else
{
// Set this enforce_rules value to the right one since roster_config isn't refreshed here
$roster->config['default_page'] = $default;
$roster->set_message(sprintf($roster->locale->act['default_page_set'], $default));
}
}
function processAccess()
{
global $roster;
$access = implode(":",$_POST['config_access']);
$id = (int)$_POST['id'];
$query = "UPDATE `" . $roster->db->table('addon') . "` SET `access` = '$access' WHERE `addon_id` = '$id';";
if( !$roster->db->query($query) )
{
die_quietly($roster->db->error(),'Database Error',__FILE__,__LINE__,$query);
}
}
| WoWRoster/wowroster_dev | admin/addon_install.php | PHP | gpl-3.0 | 21,161 |
<?php
namespace Paged;
/**
* Выводит список как маркерованный
*
* @category Basic library
* @package Paged
* @author Peter S. Gribanov <info@peter-gribanov.ru>
* @version 4.0 SVN: $Revision$
* @since $Date$
* @link $HeadURL$
* @link http://peter-gribanov.ru/#open-source/paged/paged_4-x
* @copyright (c) 2008 by Peter S. Gribanov
* @license http://peter-gribanov.ru/license GNU GPL Version 3
*/
class ViewList extends PluginView {
/**
* Возвращает меню в виде списка
*
* @return array
*/
public function getList(){
$list = parent::getList();
$list_new = array();
foreach ($list as $item)
$list_new[] = Template::getTemplate('list.php', array($item));
return $list_new;
}
/**
* Возвращает меню упакованное в строку
*
* @return string
*/
public function getPack(){
return Template::getTemplate('list_pack.php', $this->getList());
}
/**
* Выводит меню упакованное в строку
*
* @return void
*/
public function showPack(){
Template::showTemplate('list_pack.php', $this->getList());
}
} | peter-gribanov/php-paged | classes/views/ViewList.php | PHP | gpl-3.0 | 1,223 |
import io
import openpyxl
from django.test import (
Client, TestCase
)
from django.urls import reverse
from core.models import (
User, Batch, Section, Election, Candidate, CandidateParty,
CandidatePosition, Vote, VoterProfile, Setting, UserType
)
class ResultsExporter(TestCase):
"""
Tests the results xlsx exporter view.
This subview may only process requests from logged in admin users. Other
users will be redirected to '/'. This will also only accept GET requests.
GET requests may have an election`parameter whose value must be the id
of an election. The lack of an election parameter will result in the
results of all elections to be exported, with each election having its
own worksheet. Other URL parameters will be ignored. Invalid election
parameter values, e.g. non-existent election IDs and non-integer parameters,
will return an error message.
View URL: '/results/export'
"""
@classmethod
def setUpTestData(cls):
batch_num = 0
section_num = 0
voter_num = 0
party_num = 0
position_num = 0
candidate_num = 0
num_elections = 2
voters = list()
positions = dict()
for i in range(num_elections):
election = Election.objects.create(name='Election {}'.format(i))
positions[str(election.name)] = list()
num_batches = 2
for j in range(num_batches):
batch = Batch.objects.create(year=batch_num, election=election)
batch_num += 1
num_sections = 2 if j == 0 else 1
for k in range(num_sections):
section = Section.objects.create(
section_name=str(section_num)
)
section_num += 1
num_students = 2
for l in range(num_students):
voter = User.objects.create(
username='user{}'.format(voter_num),
first_name=str(voter_num),
last_name=str(voter_num),
type=UserType.VOTER
)
voter.set_password('voter')
voter.save()
voter_num += 1
VoterProfile.objects.create(
user=voter,
batch=batch,
section=section
)
voters.append(voter)
num_positions = 3
for i in range(num_positions):
position = CandidatePosition.objects.create(
position_name='Position {}'.format(position_num),
election=election
)
positions[str(election.name)].append(position)
position_num += 1
num_parties = 3
for j in range(num_parties):
party = CandidateParty.objects.create(
party_name='Party {}'.format(party_num),
election=election
)
party_num += 1
if j != 2: # Let every third party have no candidates.
num_positions = 3
for k in range(num_positions):
position = positions[str(election.name)][k]
candidate = Candidate.objects.create(
user=voters[candidate_num],
party=party,
position=position,
election=election
)
Vote.objects.create(
user=voters[candidate_num],
candidate=candidate,
election=election
)
candidate_num += 1
# Let's give one candidate an additional vote to really make sure that
# we all got the correct number of votes.
Vote.objects.create(
user=voters[0],
# NOTE: The voter in voter[1] is a Position 1 candidate of
# Party 1, where the voter in voter[0] is a member.
candidate=Candidate.objects.get(user=voters[1]),
election=Election.objects.get(name='Election 0')
)
_admin = User.objects.create(username='admin', type=UserType.ADMIN)
_admin.set_password('root')
_admin.save()
def setUp(self):
self.client.login(username='admin', password='root')
def test_anonymous_get_requests_redirected_to_index(self):
self.client.logout()
response = self.client.get(reverse('results-export'), follow=True)
self.assertRedirects(response, '/?next=%2Fadmin%2Fresults')
def test_voter_get_requests_redirected_to_index(self):
self.client.logout()
self.client.login(username='user0', password='voter')
response = self.client.get(reverse('results-export'), follow=True)
self.assertRedirects(response, reverse('index'))
def test_get_all_elections_xlsx(self):
response = self.client.get(reverse('results-export'))
self.assertEqual(response.status_code, 200)
self.assertEqual(
response['Content-Disposition'],
'attachment; filename="Election Results.xlsx"'
)
wb = openpyxl.load_workbook(io.BytesIO(response.content))
self.assertEqual(len(wb.worksheets), 2)
# Check first worksheet.
ws = wb.worksheets[0]
self.assertEqual(wb.sheetnames[0], 'Election 0')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 0',
'Party 0',
'0, 0',
'Party 1',
'3, 3',
'Party 2',
'None',
'Position 1',
'Party 0',
'1, 1',
'Party 1',
'4, 4',
'Party 2',
'None',
'Position 2',
'Party 0',
'2, 2',
'Party 1',
'5, 5',
'Party 2',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '0')
self.assertEqual(str(ws.cell(4, 2).value), '0') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '2')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '1') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '1')
self.assertEqual(str(ws.cell(4, 4).value), '2') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '2')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
# Check second worksheet.
ws = wb.worksheets[1]
self.assertEqual(wb.sheetnames[1], 'Election 1')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 1 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 3',
'Party 3',
'6, 6',
'Party 4',
'9, 9',
'Party 5',
'None',
'Position 4',
'Party 3',
'7, 7',
'Party 4',
'10, 10',
'Party 5',
'None',
'Position 5',
'Party 3',
'8, 8',
'Party 4',
'11, 11',
'Party 5',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '2')
self.assertEqual(str(ws.cell(4, 2).value), '3') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '1')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '4') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '3')
self.assertEqual(str(ws.cell(4, 4).value), '5') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '1')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
def test_get_election0_xlsx(self):
response = self.client.get(
reverse('results-export'),
{ 'election': str(Election.objects.get(name='Election 0').id) }
)
self.assertEqual(response.status_code, 200)
self.assertEqual(
response['Content-Disposition'],
'attachment; filename="Election 0 Results.xlsx"'
)
wb = openpyxl.load_workbook(io.BytesIO(response.content))
self.assertEqual(len(wb.worksheets), 1)
# Check first worksheet.
ws = wb.worksheets[0]
self.assertEqual(wb.sheetnames[0], 'Election 0')
row_count = ws.max_row
col_count = ws.max_column
self.assertEqual(row_count, 25)
self.assertEqual(col_count, 5)
self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results')
self.assertEqual(str(ws.cell(2, 1).value), 'Candidates')
cellContents = [
'Position 0',
'Party 0',
'0, 0',
'Party 1',
'3, 3',
'Party 2',
'None',
'Position 1',
'Party 0',
'1, 1',
'Party 1',
'4, 4',
'Party 2',
'None',
'Position 2',
'Party 0',
'2, 2',
'Party 1',
'5, 5',
'Party 2',
'None'
]
for cellIndex, content in enumerate(cellContents, 5):
self.assertEqual(str(ws.cell(cellIndex, 1).value), content)
self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes')
self.assertEqual(str(ws.cell(3, 2).value), '0')
self.assertEqual(str(ws.cell(4, 2).value), '0') # Section
self.assertEqual(str(ws.cell(7, 2).value), '1')
self.assertEqual(str(ws.cell(9, 2).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 2).value), '2')
self.assertEqual(str(ws.cell(16, 2).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 2).value), '0')
self.assertEqual(str(ws.cell(23, 2).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(4, 3).value), '1') # Section
self.assertEqual(str(ws.cell(7, 3).value), '0')
self.assertEqual(str(ws.cell(9, 3).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 3).value), '0')
self.assertEqual(str(ws.cell(16, 3).value), '0')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 3).value), '1')
self.assertEqual(str(ws.cell(23, 3).value), '0')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 4).value), '1')
self.assertEqual(str(ws.cell(4, 4).value), '2') # Section
self.assertEqual(str(ws.cell(7, 4).value), '0')
self.assertEqual(str(ws.cell(9, 4).value), '0')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 4).value), '0')
self.assertEqual(str(ws.cell(16, 4).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 4).value), '0')
self.assertEqual(str(ws.cell(23, 4).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes')
self.assertEqual(str(ws.cell(7, 5).value), '1')
self.assertEqual(str(ws.cell(9, 5).value), '1')
self.assertEqual(str(ws.cell(11, 2).value), 'N/A')
self.assertEqual(str(ws.cell(14, 5).value), '2')
self.assertEqual(str(ws.cell(16, 5).value), '1')
self.assertEqual(str(ws.cell(18, 2).value), 'N/A')
self.assertEqual(str(ws.cell(21, 5).value), '1')
self.assertEqual(str(ws.cell(23, 5).value), '1')
self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
def test_get_with_invalid_election_id_non_existent_election_id(self):
response = self.client.get(
reverse('results-export'),
{ 'election': '69' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified an ID for a non-existent election.'
)
self.assertRedirects(response, reverse('results'))
def test_get_with_invalid_election_id_non_integer_election_id(self):
response = self.client.get(
reverse('results-export'),
{ 'election': 'hey' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified a non-integer election ID.'
)
self.assertRedirects(response, reverse('results'))
def test_ref_get_with_invalid_election_id_non_existent_election_id(self):
response = self.client.get(
reverse('results-export'),
{ 'election': '69' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified an ID for a non-existent election.'
)
self.assertRedirects(response, reverse('results'))
def test_ref_get_with_invalid_election_id_non_integer_election_id(self):
response = self.client.get(
reverse('results-export'),
{ 'election': 'hey' },
HTTP_REFERER=reverse('results'),
follow=True
)
messages = list(response.context['messages'])
self.assertEqual(
messages[0].message,
'You specified a non-integer election ID.'
)
self.assertRedirects(response, reverse('results'))
| seanballais/botos | tests/test_results_exporter_view.py | Python | gpl-3.0 | 18,942 |
/*
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/.
*/
#include "unit_vector.h"
namespace geometry
{
template class UnitVector<double>;
template const UnitVector<double> operator-(const UnitVector<double> &rhs);
} | FHust/ISEAFramework | src/geometry/unit_vector.cpp | C++ | gpl-3.0 | 760 |
<?php
/**
@package JobBoard
@copyright Copyright (c)2010-2013 Figomago <http://figomago.wordpress.com> <http://figomago.wordpress.com>
@license : GNU General Public License v3 or later
----------------------------------------------------------------------- */
defined('_JEXEC') or die('Restricted access');
require_once( JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'jobboard_list.php' );
jimport( 'joomla.application.component.view');
jimport('joomla.utilities.date');
class JobboardViewList extends JView
{
function display($tpl = null) {
if(!JobBoardListHelper::rssEnabled()) jexit(JText::_('COM_JOBBOARD_FEEDS_NOACCES') );
$catid = $this->selcat;
$keywd = $this->keysrch;
$document =& JFactory::getDocument();
$document->setLink(JRoute::_('index.php?option=com_jobboard&selcat='.$catid));
// get category name
$db =& JFactory::getDBO();
$query = 'SELECT '.$db->nameQuote('type').' FROM '.$db->nameQuote('#__jobboard_categories').' WHERE '.$db->nameQuote('id').' = '.$catid;
$db->setQuery($query);
$seldesc = $db->loadResult();
// get "show location" settings:
$query = 'SELECT '.$db->nameQuote('use_location').' FROM '.$db->nameQuote('#__jobboard_config').' WHERE '.$db->nameQuote('id').' = 1';
$db->setQuery($query);
$use_location = $db->loadResult();
// get the items to add to the feed
$where = ($catid == 1)? '' : ' WHERE c.'.$db->nameQuote('id').' = '.$catid;
$tag_include = strlen($keywd);
if($tag_include > 0 && $catid == 1) {
$tag_requested = $this->checkTagRequest($keywd);
$where .= ($tag_requested <> '')? " WHERE j.".$db->nameQuote('job_tags')." LIKE '%{$tag_requested}%' " : '';
}
$limit = 10;
$where .= ' AND (DATE_FORMAT(j.expiry_date,"%Y-%m-%d") >= CURDATE() OR DATE_FORMAT(j.expiry_date,"%Y-%m-%d") = 0000-00-00) ';
$query = 'SELECT
j.`id`
, j.`post_date`
, j.`job_title`
, j.`job_type`
, j.`country`
, c.`type` AS category
, cl.`description` AS job_level
, j.`description`
, j.`city`
FROM
`#__jobboard_jobs` AS j
INNER JOIN `#__jobboard_categories` AS c
ON (j.`category` = c.`id`)
INNER JOIN `#__jobboard_career_levels` AS cl
ON (j.`career_level` = cl.`id`)
'.$where.'
ORDER BY j.`post_date` DESC LIMIT '.$limit;
$db->setQuery($query);
$rows = $db->loadObjectList();
$site_name = $_SERVER['SERVER_NAME'];
if($tag_requested <> ''){
$document->setDescription(JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" '.JText::_('KEYWD_TAG'));
$rss_title = $site_name. ': '.JText::_('JOBS_WITH').' "'.ucfirst($tag_requested).'" ';
}else {
$document->setDescription(JText::_('RSS_LATEST_JOBS').': '.$seldesc );
$rss_title = $site_name. ': '.JText::_('RSS_LATEST_JOBS').': '.$seldesc;
}
$document->setTitle($rss_title);
foreach ($rows as $row)
{
// create a new feed item
$job = new JFeedItem();
// assign values to the item
$job_date = new JDate($row->post_date);
$job_pubDate = new JDate();
$job->category = $row->category ;
$job->date = $job_date->toRFC822();
$job->description = $this->trimDescr(html_entity_decode($this->escape($row->description)), '.');
$link = htmlentities('index.php?option=com_jobboard&view=job&id='.$row->id);
$job->link = JRoute::_($link);
$job->pubDate = $job_pubDate->toRFC822();
if($use_location) {
$job_location = ($row->country <> 266)? ', '.$row->city : ', '.JText::_('WORK_FROM_ANYWHERE');
} else $job_location = '';
$job->title = JText::_('JOB_VACANCY').': '.html_entity_decode($this->escape($row->job_title.$job_location.' ('.JText::_($row->job_type).')'));
// add item to the feed
$document->addItem($job);
}
}
function checkTagRequest($keywd) {
$key_array = explode( ',' , $keywd);
return (count($key_array) == 1)? $this->escape(trim(strtolower ( $key_array[0]) ) ) : '';
}
function trimDescr($descr, $delim){
$first_bit = strstr($descr, '.', true);
$remainder = strstr($descr, '.');
return $first_bit.'. '.strstr(substr($remainder, 1), '.', true).' ...';
}
}
?>
| figomago/joomla-jobboard | pkg_jobboard_1.2.7.1_lite/site/views/list/view.feed.php | PHP | gpl-3.0 | 4,860 |
/*
Copyright © 2017 the InMAP authors.
This file is part of InMAP.
InMAP 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.
InMAP 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 InMAP. If not, see <http://www.gnu.org/licenses/>.*/
package eieio
import (
"context"
"fmt"
"github.com/spatialmodel/inmap/emissions/slca"
"github.com/spatialmodel/inmap/emissions/slca/eieio/eieiorpc"
"github.com/spatialmodel/inmap/internal/hash"
"gonum.org/v1/gonum/mat"
)
type emissionsRequest struct {
demand *mat.VecDense
industries *Mask
pol slca.Pollutant
year Year
loc Location
aqm string
}
// Emissions returns spatially-explicit emissions caused by the
// specified economic demand. Emitters
// specifies the emitters emissions should be calculated for.
// If emitters == nil, combined emissions for all emitters are calculated.
func (e *SpatialEIO) Emissions(ctx context.Context, request *eieiorpc.EmissionsInput) (*eieiorpc.Vector, error) {
e.loadEmissionsOnce.Do(func() {
var c string
if e.EIEIOCache != "" {
c = e.EIEIOCache + "/individual"
}
e.emissionsCache = loadCacheOnce(func(ctx context.Context, request interface{}) (interface{}, error) {
r := request.(*emissionsRequest)
return e.emissions(ctx, r.demand, r.industries, r.aqm, r.pol, r.year, r.loc) // Actually calculate the emissions.
}, 1, e.MemCacheSize, c, vectorMarshal, vectorUnmarshal)
})
req := &emissionsRequest{
demand: rpc2vec(request.Demand),
industries: rpc2mask(request.Emitters),
pol: slca.Pollutant(request.Emission),
year: Year(request.Year),
loc: Location(request.Location),
aqm: request.AQM,
}
rr := e.emissionsCache.NewRequest(ctx, req, "emissions_"+hash.Hash(req))
resultI, err := rr.Result()
if err != nil {
return nil, err
}
return vec2rpc(resultI.(*mat.VecDense)), nil
}
// emissions returns spatially-explicit emissions caused by the
// specified economic demand. industries
// specifies the industries emissions should be calculated for.
// If industries == nil, combined emissions for all industries are calculated.
func (e *SpatialEIO) emissions(ctx context.Context, demand *mat.VecDense, industries *Mask, aqm string, pol slca.Pollutant, year Year, loc Location) (*mat.VecDense, error) {
// Calculate emission factors. matrix dimension: [# grid cells, # industries]
ef, err := e.emissionFactors(ctx, aqm, pol, year)
if err != nil {
return nil, err
}
// Calculate economic activity. vector dimension: [# industries, 1]
activity, err := e.economicImpactsSCC(demand, year, loc)
if err != nil {
return nil, err
}
if industries != nil {
// Set activity in industries we're not interested in to zero.
industries.Mask(activity)
}
r, _ := ef.Dims()
emis := mat.NewVecDense(r, nil)
emis.MulVec(ef, activity)
return emis, nil
}
// EmissionsMatrix returns spatially- and industry-explicit emissions caused by the
// specified economic demand. In the result matrix, the rows represent air quality
// model grid cells and the columns represent emitters.
func (e *SpatialEIO) EmissionsMatrix(ctx context.Context, request *eieiorpc.EmissionsMatrixInput) (*eieiorpc.Matrix, error) {
ef, err := e.emissionFactors(ctx, request.AQM, slca.Pollutant(request.Emission), Year(request.Year)) // rows = grid cells, cols = industries
if err != nil {
return nil, err
}
activity, err := e.economicImpactsSCC(array2vec(request.Demand.Data), Year(request.Year), Location(request.Location)) // rows = industries
if err != nil {
return nil, err
}
r, c := ef.Dims()
emis := mat.NewDense(r, c, nil)
emis.Apply(func(_, j int, v float64) float64 {
// Multiply each emissions factor column by the corresponding activity row.
return v * activity.At(j, 0)
}, ef)
return mat2rpc(emis), nil
}
// emissionFactors returns spatially-explicit emissions per unit of economic
// production for each industry. In the result matrix, the rows represent
// air quality model grid cells and the columns represent industries.
func (e *SpatialEIO) emissionFactors(ctx context.Context, aqm string, pol slca.Pollutant, year Year) (*mat.Dense, error) {
e.loadEFOnce.Do(func() {
e.emissionFactorCache = loadCacheOnce(e.emissionFactorsWorker, 1, 1, e.EIEIOCache,
matrixMarshal, matrixUnmarshal)
})
key := fmt.Sprintf("emissionFactors_%s_%v_%d", aqm, pol, year)
rr := e.emissionFactorCache.NewRequest(ctx, aqmPolYear{aqm: aqm, pol: pol, year: year}, key)
resultI, err := rr.Result()
if err != nil {
return nil, fmt.Errorf("eieio.emissionFactors: %s: %v", key, err)
}
return resultI.(*mat.Dense), nil
}
// emissionFactors returns spatially-explicit emissions per unit of economic
// production for each industry. In the result matrix, the rows represent
// air quality model grid cells and the columns represent industries.
func (e *SpatialEIO) emissionFactorsWorker(ctx context.Context, request interface{}) (interface{}, error) {
aqmpolyear := request.(aqmPolYear)
prod, err := e.domesticProductionSCC(aqmpolyear.year)
if err != nil {
return nil, err
}
var emisFac *mat.Dense
for i, refTemp := range e.SpatialRefs {
if len(refTemp.SCCs) == 0 {
return nil, fmt.Errorf("bea: industry %d; no SCCs", i)
}
ref := refTemp
ref.EmisYear = int(aqmpolyear.year)
ref.AQM = aqmpolyear.aqm
industryEmis, err := e.CSTConfig.EmissionsSurrogate(ctx, aqmpolyear.pol, &ref)
if err != nil {
return nil, err
}
if i == 0 {
emisFac = mat.NewDense(industryEmis.Shape[0], len(e.SpatialRefs), nil)
}
for r, v := range industryEmis.Elements {
// The emissions factor is the industry emissions divided by the
// industry economic production.
if p := prod.At(i, 0); p != 0 {
emisFac.Set(r, i, v/prod.At(i, 0))
}
}
}
return emisFac, nil
}
| spatialmodel/inmap | emissions/slca/eieio/spatialemis.go | GO | gpl-3.0 | 6,205 |
<?php
class ControllerTotalShipping extends Controller {
private $error = array();
public function index() {
$this->load->language('total/shipping');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/setting');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->model_setting_setting->editSetting('shipping', $this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->response->redirect($this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL'));
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_enabled'] = $this->language->get('text_enabled');
$data['text_disabled'] = $this->language->get('text_disabled');
$data['entry_estimator'] = $this->language->get('entry_estimator');
$data['entry_status'] = $this->language->get('entry_status');
$data['entry_sort_order'] = $this->language->get('entry_sort_order');
$data['button_save'] = $this->language->get('button_save');
$data['button_cancel'] = $this->language->get('button_cancel');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_total'),
'href' => $this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('total/shipping', 'token=' . $this->session->data['token'], 'SSL')
);
$data['action'] = $this->url->link('total/shipping', 'token=' . $this->session->data['token'], 'SSL');
$data['cancel'] = $this->url->link('extension/total', 'token=' . $this->session->data['token'], 'SSL');
if (isset($this->request->post['shipping_estimator'])) {
$data['shipping_estimator'] = $this->request->post['shipping_estimator'];
} else {
$data['shipping_estimator'] = $this->config->get('shipping_estimator');
}
if (isset($this->request->post['shipping_status'])) {
$data['shipping_status'] = $this->request->post['shipping_status'];
} else {
$data['shipping_status'] = $this->config->get('shipping_status');
}
if (isset($this->request->post['shipping_sort_order'])) {
$data['shipping_sort_order'] = $this->request->post['shipping_sort_order'];
} else {
$data['shipping_sort_order'] = $this->config->get('shipping_sort_order');
}
$data['header'] = $this->load->controller('common/header');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('total/shipping.tpl', $data));
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'total/shipping')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if (!$this->error) {
return true;
} else {
return false;
}
}
} | stan-bg/opencart | upload/admin/controller/total/shipping.php | PHP | gpl-3.0 | 3,431 |
//
// 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: 2014.08.02 at 08:05:16 PM CEST
//
package net.ramso.dita.concept;
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.XmlElements;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for synblk.class complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="synblk.class">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{}synblk.content"/>
* </sequence>
* <attGroup ref="{}synblk.attributes"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "synblk.class", propOrder = {
"title",
"groupseqOrGroupchoiceOrGroupcomp"
})
@XmlSeeAlso({
Synblk.class
})
public class SynblkClass {
protected Title title;
@XmlElements({
@XmlElement(name = "groupseq", type = Groupseq.class),
@XmlElement(name = "groupchoice", type = Groupchoice.class),
@XmlElement(name = "groupcomp", type = Groupcomp.class),
@XmlElement(name = "fragref", type = Fragref.class),
@XmlElement(name = "synnote", type = Synnote.class),
@XmlElement(name = "synnoteref", type = Synnoteref.class),
@XmlElement(name = "fragment", type = Fragment.class)
})
protected List<java.lang.Object> groupseqOrGroupchoiceOrGroupcomp;
@XmlAttribute(name = "outputclass")
protected String outputclass;
@XmlAttribute(name = "xtrc")
protected String xtrc;
@XmlAttribute(name = "xtrf")
protected String xtrf;
@XmlAttribute(name = "base")
protected String base;
@XmlAttribute(name = "rev")
protected String rev;
@XmlAttribute(name = "importance")
protected ImportanceAttsClass importance;
@XmlAttribute(name = "status")
protected StatusAttsClass status;
@XmlAttribute(name = "props")
protected String props;
@XmlAttribute(name = "platform")
protected String platform;
@XmlAttribute(name = "product")
protected String product;
@XmlAttribute(name = "audience")
protected String audienceMod;
@XmlAttribute(name = "otherprops")
protected String otherprops;
@XmlAttribute(name = "translate")
protected YesnoAttClass translate;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "dir")
protected DirAttsClass dir;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "conref")
protected String conref;
@XmlAttribute(name = "conrefend")
protected String conrefend;
@XmlAttribute(name = "conaction")
protected ConactionAttClass conaction;
@XmlAttribute(name = "conkeyref")
protected String conkeyref;
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link Title }
*
*/
public Title getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link Title }
*
*/
public void setTitle(Title value) {
this.title = value;
}
/**
* Gets the value of the groupseqOrGroupchoiceOrGroupcomp 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 groupseqOrGroupchoiceOrGroupcomp property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGroupseqOrGroupchoiceOrGroupcomp().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Groupseq }
* {@link Groupchoice }
* {@link Groupcomp }
* {@link Fragref }
* {@link Synnote }
* {@link Synnoteref }
* {@link Fragment }
*
*
*/
public List<java.lang.Object> getGroupseqOrGroupchoiceOrGroupcomp() {
if (groupseqOrGroupchoiceOrGroupcomp == null) {
groupseqOrGroupchoiceOrGroupcomp = new ArrayList<java.lang.Object>();
}
return this.groupseqOrGroupchoiceOrGroupcomp;
}
/**
* Gets the value of the outputclass property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutputclass() {
return outputclass;
}
/**
* Sets the value of the outputclass property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutputclass(String value) {
this.outputclass = value;
}
/**
* Gets the value of the xtrc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrc() {
return xtrc;
}
/**
* Sets the value of the xtrc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrc(String value) {
this.xtrc = value;
}
/**
* Gets the value of the xtrf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXtrf() {
return xtrf;
}
/**
* Sets the value of the xtrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXtrf(String value) {
this.xtrf = value;
}
/**
* Gets the value of the base property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBase() {
return base;
}
/**
* Sets the value of the base property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBase(String value) {
this.base = value;
}
/**
* Gets the value of the rev property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRev() {
return rev;
}
/**
* Sets the value of the rev property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRev(String value) {
this.rev = value;
}
/**
* Gets the value of the importance property.
*
* @return
* possible object is
* {@link ImportanceAttsClass }
*
*/
public ImportanceAttsClass getImportance() {
return importance;
}
/**
* Sets the value of the importance property.
*
* @param value
* allowed object is
* {@link ImportanceAttsClass }
*
*/
public void setImportance(ImportanceAttsClass value) {
this.importance = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusAttsClass }
*
*/
public StatusAttsClass getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusAttsClass }
*
*/
public void setStatus(StatusAttsClass value) {
this.status = value;
}
/**
* Gets the value of the props property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProps() {
return props;
}
/**
* Sets the value of the props property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProps(String value) {
this.props = value;
}
/**
* Gets the value of the platform property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlatform() {
return platform;
}
/**
* Sets the value of the platform property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlatform(String value) {
this.platform = value;
}
/**
* Gets the value of the product property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProduct() {
return product;
}
/**
* Sets the value of the product property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProduct(String value) {
this.product = value;
}
/**
* Gets the value of the audienceMod property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAudienceMod() {
return audienceMod;
}
/**
* Sets the value of the audienceMod property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAudienceMod(String value) {
this.audienceMod = value;
}
/**
* Gets the value of the otherprops property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOtherprops() {
return otherprops;
}
/**
* Sets the value of the otherprops property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOtherprops(String value) {
this.otherprops = value;
}
/**
* Gets the value of the translate property.
*
* @return
* possible object is
* {@link YesnoAttClass }
*
*/
public YesnoAttClass getTranslate() {
return translate;
}
/**
* Sets the value of the translate property.
*
* @param value
* allowed object is
* {@link YesnoAttClass }
*
*/
public void setTranslate(YesnoAttClass value) {
this.translate = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the dir property.
*
* @return
* possible object is
* {@link DirAttsClass }
*
*/
public DirAttsClass getDir() {
return dir;
}
/**
* Sets the value of the dir property.
*
* @param value
* allowed object is
* {@link DirAttsClass }
*
*/
public void setDir(DirAttsClass value) {
this.dir = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the conref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConref() {
return conref;
}
/**
* Sets the value of the conref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConref(String value) {
this.conref = value;
}
/**
* Gets the value of the conrefend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConrefend() {
return conrefend;
}
/**
* Sets the value of the conrefend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConrefend(String value) {
this.conrefend = value;
}
/**
* Gets the value of the conaction property.
*
* @return
* possible object is
* {@link ConactionAttClass }
*
*/
public ConactionAttClass getConaction() {
return conaction;
}
/**
* Sets the value of the conaction property.
*
* @param value
* allowed object is
* {@link ConactionAttClass }
*
*/
public void setConaction(ConactionAttClass value) {
this.conaction = value;
}
/**
* Gets the value of the conkeyref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getConkeyref() {
return conkeyref;
}
/**
* Sets the value of the conkeyref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConkeyref(String value) {
this.conkeyref = value;
}
}
| ramsodev/DitaManagement | dita/dita.concept/src/net/ramso/dita/concept/SynblkClass.java | Java | gpl-3.0 | 14,623 |
/*
* Copyright (C) 2013-2017 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.series.db.beans.parameter;
import java.util.HashMap;
import java.util.Map;
public abstract class Parameter<T> {
private long parameterId;
private long fkId;
private String name;
private T value;
public Map<String, Object> toValueMap() {
Map<String, Object> valueMap = new HashMap<>();
valueMap.put("name", getName());
valueMap.put("value", getValue());
return valueMap;
}
public long getParameterId() {
return parameterId;
}
public void setParameterId(long parameterId) {
this.parameterId = parameterId;
}
public long getFkId() {
return fkId;
}
public void setFkId(long fkId) {
this.fkId = fkId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSetName() {
return getName() != null;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public boolean isSetValue() {
return getValue() != null;
}
}
| ridoo/dao-series-api | dao/src/main/java/org/n52/series/db/beans/parameter/Parameter.java | Java | gpl-3.0 | 2,458 |
package com.mortensickel.measemulator;
// http://maps.google.com/maps?q=loc:59.948509,10.602627
import com.google.android.gms.common.api.*;
import android.content.Context;
import android.text.*;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.animation.*;
import android.app.*;
import android.os.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.*;
import android.view.View.*;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.*;
import com.google.android.gms.common.*;
import android.preference.*;
import android.view.*;
import android.content.*;
import android.net.Uri;
// import org.apache.http.impl.execchain.*;
// Todo over a certain treshold, change calibration factor
// TODO settable calibration factor
// TODO finish icons
// DONE location
// DONE input background and source. Calculate activity from distance
// TODO Use distribution map
// DONE add settings menu
// TODO generic skin
// TODO handle pause and shutdown
public class MainActivity extends Activity
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,LocationListener
{
/*
AUTOMESS:
0.44 pps = 0.1uSv/h
ca 16. pulser pr nSv
*/
boolean poweron=false;
long shutdowntime=0;
long meastime;
TextView tvTime,tvPulsedata, tvPause,tvAct, tvDoserate;
long starttime = 0;
public long pulses=0;
Integer mode=0;
final Integer MAXMODE=3;
final int MODE_OFF=0;
final int MODE_MOMENTANDOSE=1;
final int MODE_DOSERATE=2;
final int MODE_DOSE=3;
public final String TAG="measem";
double calibration=4.4;
public Integer sourceact=1;
protected long lastpulses=0;
public boolean gpsenabled = true;
public Context context;
public Integer gpsinterval=2000;
private GoogleApiClient gac;
private Location here,there;
protected LocationRequest loreq;
private LinearLayout llDebuginfo;
private Double background=0.0;
private float sourcestrength=1000;
private boolean showDebug=false;
private final String PULSES="pulses";
@Override
public void onConnectionFailed(ConnectionResult p1)
{
// TODO: Implement this method
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putLong(PULSES,pulses);
//savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
pulses = savedInstanceState.getLong(PULSES);
//mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}
protected void createLocationRequest(){
loreq = new LocationRequest();
loreq.setInterval(gpsinterval);
loreq.setFastestInterval(100);
loreq.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates(){
if(loreq==null){
createLocationRequest();
}
LocationServices.FusedLocationApi.requestLocationUpdates(gac,loreq,this);
}
public void ConnectionCallbacks(){
}
@Override
public void onLocationChanged(Location p1)
{
here=p1;
double distance=here.distanceTo(there);
sourceact=(int)Math.round(background+sourcestrength/(distance*distance));
tvAct.setText(String.valueOf(sourceact));
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// TODO: Implement this method
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case R.id.mnuSettings:
Intent intent=new Intent();
intent.setClass(MainActivity.this,SetPreferenceActivity.class);
startActivityForResult(intent,0);
return true;
case R.id.mnuSaveLoc:
saveLocation();
return true;
case R.id.mnuShowLoc:
showLocation();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showLocation(){
String lat=String.valueOf(there.getLatitude());
String lon=String.valueOf(there.getLongitude());
Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show();
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=loc:"+lat+","+lon));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request.",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
protected void saveLocation(){
Location LastLocation = LocationServices.FusedLocationApi.getLastLocation(
gac);
if (LastLocation != null) {
String lat=String.valueOf(LastLocation.getLatitude());
String lon=String.valueOf(LastLocation.getLongitude());
Toast.makeText(getApplicationContext(),getString(R.string.SourceLocation)+lat+','+lon, Toast.LENGTH_LONG).show();
there=LastLocation;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//SharedPreferences sp=this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putString("Latitude",lat);
ed.putString("Longitude",lon);
ed.apply();
ed.commit();
}else{
Toast.makeText(getApplicationContext(),getString(R.string.CouldNotGetLocation), Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnected(Bundle p1)
{
Location loc = LocationServices.FusedLocationApi.getLastLocation(gac);
if(loc != null){
here=loc;
}
}
@Override
public void onConnectionSuspended(int p1)
{
// TODO: Implement this method
}
protected void onStart(){
gac.connect();
super.onStart();
}
protected void onStop(){
gac.disconnect();
super.onStop();
}
//this posts a message to the main thread from our timertask
//and updates the textfield
final Handler h = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
if(seconds>0){
double display=0;
if( mode==MODE_MOMENTANDOSE){
if (lastpulses==0 || (lastpulses>pulses)){
display=0;
}else{
display=((pulses-lastpulses)/calibration);
}
lastpulses=pulses;
}
if (mode==MODE_DOSERATE){
display=(double)pulses/(double)seconds/calibration;
}
if (mode==MODE_DOSE){
display=(double)pulses/calibration/3600;
}
tvDoserate.setText(String.format("%.2f",display));
}
if(showDebug){
int minutes = seconds / 60;
seconds = seconds % 60;
tvTime.setText(String.format("%d:%02d", minutes, seconds));
}
return false;
}
});
//runs without timer - reposting itself after a random interval
Handler h2 = new Handler();
Runnable run = new Runnable() {
@Override
public void run() {
int n=1;
long pause=pause(getInterval());
h2.postDelayed(run,pause);
if(showDebug){
tvPause.setText(String.format("%d",pause));
}
receivepulse(n);
}
};
public Integer getInterval(){
Integer act=sourceact;
if(act==0){
act=1;
}
Integer interval=5000/act;
if (interval==0){
interval=1;
}
return(interval);
}
public long pause(Integer interval){
double pause=interval;
if(interval > 5){
Random rng=new Random();
pause=rng.nextGaussian();
Integer sd=interval/4;
pause=pause*sd+interval;
if(pause<0){pause=0;}
}
return((long)pause);
}
public void receivepulse(int n){
LinearLayout myText = (LinearLayout) findViewById(R.id.llLed );
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(20); //You can manage the time of the blink with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(0);
myText.startAnimation(anim);
pulses=pulses+1;
Double sdev=Math.sqrt(pulses);
if(showDebug){
tvPulsedata.setText(String.format("%d - %.1f - %.0f %%",pulses,sdev,sdev/pulses*100));
}
}
//tells handler to send a message
class firstTask extends TimerTask {
@Override
public void run() {
h.sendEmptyMessage(0);
}
}
@Override
protected void onResume()
{
// TODO: Implement this method
super.onResume();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
// lowprobCutoff = (double)sharedPref.getFloat("pref_key_lowprobcutoff", 1)/100;
readPrefs();
//XlowprobCutoff=
}
private void readPrefs(){
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String ret=sharedPref.getString("Latitude", "10");
Double lat= Double.parseDouble(ret);
ret=sharedPref.getString("Longitude", "60");
Double lon= Double.parseDouble(ret);
there.setLatitude(lat);
there.setLongitude(lon);
ret=sharedPref.getString("backgroundValue", "1");
background= Double.parseDouble(ret)/200;
showDebug=sharedPref.getBoolean("showDebug", false);
debugVisible(showDebug);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
readPrefs();
}
Timer timer = new Timer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context=this;
loadPref(context);
/*SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
double lat = getResources().get;
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
// getString(R.string.preference_file_key), Context.MODE_PRIVATE);
*/
there = new Location("dummyprovider");
there.setLatitude(59.948509);
there.setLongitude(10.602627);
llDebuginfo=(LinearLayout)findViewById(R.id.llDebuginfo);
llDebuginfo.setVisibility(View.GONE);
gac=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
tvTime = (TextView)findViewById(R.id.tvTime);
tvPulsedata = (TextView)findViewById(R.id.tvPulsedata);
tvPause = (TextView)findViewById(R.id.tvPause);
tvDoserate = (TextView)findViewById(R.id.etDoserate);
tvAct=(EditText)findViewById(R.id.activity);
tvAct.addTextChangedListener(activityTW);
switchMode(mode);
Button b = (Button)findViewById(R.id.btPower);
b.setOnClickListener(onOffClick);
b=(Button)findViewById(R.id.btMode);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modechange(v);
}
});
b=(Button)findViewById(R.id.btLight);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDebug=!showDebug;
}
});
}
@Override
public void onPause() {
super.onPause();
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
}
TextWatcher activityTW = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
String act=tvAct.getText().toString();
if(act.equals("")){act="1";}
sourceact=Integer.parseInt(act);
// TODO better errorchecking.
// TODO disable if using geolocation
}};
View.OnClickListener onOffClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(poweron){
long now=System.currentTimeMillis();
if(now> shutdowntime && now < shutdowntime+500){
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
pulses=0;
poweron=false;
mode=MODE_OFF;
switchMode(mode);
}
shutdowntime = System.currentTimeMillis()+500;
}else{
shutdowntime=0;
starttime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
startLocationUpdates();
h2.postDelayed(run, pause(getInterval()));
mode=1;
switchMode(mode);
poweron=true;
}
}
};
private void debugVisible(Boolean show){
View debug=findViewById(R.id.llDebuginfo);
if(show){
debug.setVisibility(View.VISIBLE);
}else{
debug.setVisibility(View.GONE);
}
}
public void loadPref(Context ctx){
//SharedPreferences shpref=PreferenceManager.getDefaultSharedPreferences(ctx);
PreferenceManager.setDefaultValues(ctx, R.xml.preferences, false);
}
public void modechange(View v){
if(mode > 0){
mode++;
if (mode > MAXMODE){
mode=1;
}
switchMode(mode);}
}
public void switchMode(int mode){
int unit=0;
switch(mode){
case MODE_MOMENTANDOSE:
unit= R.string.ugyh;
break;
case MODE_DOSERATE:
unit = R.string.ugyhint;
break;
case MODE_DOSE:
unit = R.string.ugy;
break;
case MODE_OFF:
unit= R.string.blank;
tvDoserate.setText("");
break;
}
TextView tv=(TextView)findViewById(R.id.etUnit);
tv.setText(unit);
}
}
| sickel/measem | app/src/main/java/com/mortensickel/measemulator/MainActivity.java | Java | gpl-3.0 | 13,932 |
<?php
// Esercizio: un numero che si dimezza sempre
header('Content-Type: text/plain');
ini_set('display_errors', true); // MAI in produzione!!!
ini_set('html_errors', 0);
/**
* Questa classe continua a dividere
* il suo stato interno per un valore dato.
*/
class invert
{
/**
* Il valore corrente
* @var integer
*/
public $val = 1;
/**
* Il divisore
* @var integer
*/
protected $_divisor = 3;
/**
* Esegue la divisione e restituisce il risultato
* @return integer
*/
public function div()
{
$this->val = $this->val / $this->_divisor;
return $this->val;
}
/**
* Imposta il valore del divisore
* @param integer $divisor
* @return void
*/
public function setDivisor($divisor)
{
if ($divisor) {
$this->_divisor = $divisor;
} else {
// Prendo dei provvedimenti
}
}
}
$sempreMeno = new invert;
while ($sempreMeno->val > 1e-5) {
echo $sempreMeno->div(), PHP_EOL;
}
// Tento di impostare un nuovo divisore...
$sempreMeno->_divisor = 2;
// ...ma devo usare la funzione
$sempreMeno->setDivisor(2);
echo $sempreMeno->div(), PHP_EOL;
| hujuice/oopphp | public/esercizi/divide.php | PHP | gpl-3.0 | 1,214 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.2.4 or newer
*
* NOTICE OF LICENSE
*
* Licensed under the Open Software License version 3.0
*
* This source file is subject to the Open Software License (OSL 3.0) that is
* bundled with this package in the files license.txt / license.rst. It is
* also available through the world wide web at this URL:
* http://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to obtain it
* through the world wide web, please send an email to
* licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2013, EllisLab, Inc. (http://ellislab.com/)
* @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Database Utility Class
*
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
abstract class CI_DB_utility {
/**
* Database object
*
* @var object
*/
protected $db;
// --------------------------------------------------------------------
/**
* List databases statement
*
* @var string
*/
protected $_list_databases = FALSE;
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $_optimize_table = FALSE;
/**
* REPAIR TABLE statement
*
* @var string
*/
protected $_repair_table = FALSE;
// --------------------------------------------------------------------
/**
* Class constructor
*
* @param object &$db Database object
* @return void
*/
public function __construct(&$db)
{
$this->db =& $db;
log_message('debug', 'Database Utility Class Initialized');
}
// --------------------------------------------------------------------
/**
* List databases
*
* @return array
*/
public function list_databases()
{
// Is there a cached result?
if (isset($this->db->data_cache['db_names']))
{
return $this->db->data_cache['db_names'];
}
elseif ($this->_list_databases === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$this->db->data_cache['db_names'] = array();
$query = $this->db->query($this->_list_databases);
if ($query === FALSE)
{
return $this->db->data_cache['db_names'];
}
for ($i = 0, $query = $query->result_array(), $c = count($query); $i < $c; $i++)
{
$this->db->data_cache['db_names'][] = current($query[$i]);
}
return $this->db->data_cache['db_names'];
}
// --------------------------------------------------------------------
/**
* Determine if a particular database exists
*
* @param string $database_name
* @return bool
*/
public function database_exists($database_name)
{
return in_array($database_name, $this->list_databases());
}
// --------------------------------------------------------------------
/**
* Optimize Table
*
* @param string $table_name
* @return mixed
*/
public function optimize_table($table_name)
{
if ($this->_optimize_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$query = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
if ($query !== FALSE)
{
$query = $query->result_array();
return current($query);
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Optimize Database
*
* @return mixed
*/
public function optimize_database()
{
if ($this->_optimize_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$result = array();
foreach ($this->db->list_tables() as $table_name)
{
$res = $this->db->query(sprintf($this->_optimize_table, $this->db->escape_identifiers($table_name)));
if (is_bool($res))
{
return $res;
}
// Build the result array...
$res = $res->result_array();
$res = current($res);
$key = str_replace($this->db->database.'.', '', current($res));
$keys = array_keys($res);
unset($res[$keys[0]]);
$result[$key] = $res;
}
return $result;
}
// --------------------------------------------------------------------
/**
* Repair Table
*
* @param string $table_name
* @return mixed
*/
public function repair_table($table_name)
{
if ($this->_repair_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$query = $this->db->query(sprintf($this->_repair_table, $this->db->escape_identifiers($table_name)));
if (is_bool($query))
{
return $query;
}
$query = $query->result_array();
return current($query);
}
// --------------------------------------------------------------------
/**
* Generate CSV from a query result object
*
* @param object $query Query result object
* @param string $delim Delimiter (default: ,)
* @param string $newline Newline character (default: \n)
* @param string $enclosure Enclosure (default: ")
* @return string
*/
public function csv_from_result($query, $delim = ',', $newline = "\n", $enclosure = '"')
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}
$out = '';
// First generate the headings from the table column names
foreach ($query->list_fields() as $name)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
}
$out = substr(rtrim($out), 0, -strlen($delim)).$newline;
// Next blast through the result array and build out the rows
while ($row = $query->unbuffered_row('array'))
{
foreach ($row as $item)
{
$out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
}
$out = substr(rtrim($out), 0, -strlen($delim)).$newline;
}
return $out;
}
// --------------------------------------------------------------------
/**
* Generate XML data from a query result object
*
* @param object $query Query result object
* @param array $params Any preferences
* @return string
*/
public function xml_from_result($query, $params = array())
{
if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
{
show_error('You must submit a valid result object');
}
// Set our default values
foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val)
{
if ( ! isset($params[$key]))
{
$params[$key] = $val;
}
}
// Create variables for convenience
extract($params);
// Load the xml helper
get_instance()->load->helper('xml');
// Generate the result
$xml = '<'.$root.'>'.$newline;
while ($row = $query->unbuffered_row())
{
$xml .= $tab.'<'.$element.'>'.$newline;
foreach ($row as $key => $val)
{
$xml .= $tab.$tab.'<'.$key.'>'.xml_convert($val).'</'.$key.'>'.$newline;
}
$xml .= $tab.'</'.$element.'>'.$newline;
}
return $xml.'</'.$root.'>'.$newline;
}
// --------------------------------------------------------------------
/**
* Database Backup
*
* @param array $params
* @return void
*/
public function backup($params = array())
{
// If the parameters have not been submitted as an
// array then we know that it is simply the table
// name, which is a valid short cut.
if (is_string($params))
{
$params = array('tables' => $params);
}
// Set up our default preferences
$prefs = array(
'tables' => array(),
'ignore' => array(),
'filename' => '',
'format' => 'gzip', // gzip, zip, txt
'add_drop' => TRUE,
'add_insert' => TRUE,
'newline' => "\n",
'foreign_key_checks' => TRUE
);
// Did the user submit any preferences? If so set them....
if (count($params) > 0)
{
foreach ($prefs as $key => $val)
{
if (isset($params[$key]))
{
$prefs[$key] = $params[$key];
}
}
}
// Are we backing up a complete database or individual tables?
// If no table names were submitted we'll fetch the entire table list
if (count($prefs['tables']) === 0)
{
$prefs['tables'] = $this->db->list_tables();
}
// Validate the format
if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE))
{
$prefs['format'] = 'txt';
}
// Is the encoder supported? If not, we'll either issue an
// error or use plain text depending on the debug settings
if (($prefs['format'] === 'gzip' && ! @function_exists('gzencode'))
OR ($prefs['format'] === 'zip' && ! @function_exists('gzcompress')))
{
if ($this->db->db_debug)
{
return $this->db->display_error('db_unsupported_compression');
}
$prefs['format'] = 'txt';
}
// Was a Zip file requested?
if ($prefs['format'] === 'zip')
{
// Set the filename if not provided (only needed with Zip files)
if ($prefs['filename'] === '')
{
$prefs['filename'] = (count($prefs['tables']) === 1 ? $prefs['tables'] : $this->db->database)
.date('Y-m-d_H-i', time()).'.sql';
}
else
{
// If they included the .zip file extension we'll remove it
if (preg_match('|.+?\.zip$|', $prefs['filename']))
{
$prefs['filename'] = str_replace('.zip', '', $prefs['filename']);
}
// Tack on the ".sql" file extension if needed
if ( ! preg_match('|.+?\.sql$|', $prefs['filename']))
{
$prefs['filename'] .= '.sql';
}
}
// Load the Zip class and output it
$CI =& get_instance();
$CI->load->library('zip');
$CI->zip->add_data($prefs['filename'], $this->_backup($prefs));
return $CI->zip->get_zip();
}
elseif ($prefs['format'] === 'txt') // Was a text file requested?
{
return $this->_backup($prefs);
}
elseif ($prefs['format'] === 'gzip') // Was a Gzip file requested?
{
return gzencode($this->_backup($prefs));
}
return;
}
}
/* End of file DB_utility.php */
/* Location: ./system/database/DB_utility.php */ | ngoaho91/sharif-judge | system/database/DB_utility.php | PHP | gpl-3.0 | 10,617 |